text stringlengths 1 927k |
|---|
"""
Contains custom callbacks.
"""
from constants import minimum_scores, maximum_scores
import constants
import datetime
import json
from keras.callbacks import Callback, ModelCheckpoint
import numpy as np
import os
from sklearn.metrics import cohen_kappa_score
from util import process_data, create_folder
class QWKSc... |
VERSION = "1.21.3"
NAME = "fandogh_cli"
if __name__ == "__main__":
print(VERSION) |
import sys
import os
import torch
import random
import numpy as np
from tqdm import tqdm
import torch.nn as nn
import torch.optim as optim
import math
from network import GUNet
from mlp_dropout import MLPClassifier
from sklearn import metrics
from util import cmd_args, load_data
sys.path.append(
'%s/pytorch_struc... |
import torch
import torch.nn as nn
import torchvision
class ResNeXtBlock(nn.Module):
def __init__(self,in_places,places, stride=1,downsampling=False, expansion = 2, cardinality=32):
super(ResNeXtBlock,self).__init__()
self.expansion = expansion
self.downsampling = downsampling
sel... |
# Copyright 2018-2019 QuantumBlack Visual Analytics Limited
#
# 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
#
# THE SOFTWARE IS PROVIDED "AS IS"... |
"""SCons.Tool.rpmutils.py
RPM specific helper routines for general usage in the test framework
and SCons core modules.
Since we check for the RPM package target name in several places,
we have to know which machine/system name RPM will use for the current
hardware setup. The following dictionaries and functions try t... |
#!/usr/bin/python
import json
import urllib2
### For monitoring the performance metrics of your Mesos Agents using Site24x7 Server Monitoring Plugins.
### 1. Have the site24x7 server monitoring agent up and running.
### 2. Download the plugin from github
### 3. Create a folder in name of the plugin under agent plugi... |
"""
Upgrade custom's game dir to the latest version.
"""
from utils import compare_version
class BaseUpgrader(object):
"""
Upgrade a game dir from the version in [<from_version>, <to_version>) to version
<target_version>.
"""
# Can upgrade the game of version between from_version and to_version.
... |
from itertools import chain
from pathlib import Path
from typing import Tuple
import torch
from accelerate import Accelerator
from torch.utils.data import DataLoader
from saticl.config import Configuration, SSLConfiguration
from saticl.datasets.icl import ICLDataset
from saticl.datasets.transforms import invariance_t... |
from bs4 import BeautifulSoup
class LeadersScrapper:
def scrap(self, html):
soup = BeautifulSoup(html, features="html.parser")
title = soup.find("h1").text
date = soup.find("div",{"class":"infos"}).text
data = [ arti.text for arti in soup.find("div", {"class":"article_body"}).f... |
# Generated by Django 3.1.1 on 2020-09-14 18:08
from django.db import migrations
import wagtail.core.fields
class Migration(migrations.Migration):
dependencies = [
('contact', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='contactpage',
nam... |
import rclpy
from rclpy.node import Node
from geometry_msgs.msg import Vector3
from std_msgs.msg import Int16
from rclpy.qos import QoSPresetProfiles
from ament_index_python import get_package_share_directory
import numpy as np
import sys, os
from .parameters import force
from .flags import flags
def create_pwm(val... |
################################################################################
# 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... |
import os
commits_file = os.environ['_git_recover_index_tmpfile']
commits_recover_path = os.environ['_git_recover_index_recover_path']
commits = [line.rstrip('\n') for line in open(commits_file)]
from subprocess import call
filename = commits_recover_path + "/file-"
i = 1
for c in commits:
f = open(filename + str(i... |
### 多个函数间的配合
## 变量的作用域
rent = 3000
variable_cost = 0
def cost():
global variable_cost # 使用全局的变量
utilities = int(input('请输入本月的水电费用'))
food_cost = int(input('请输入本月的食材费用'))
variable_cost = utilities + food_cost
print('本月的变动成本费用是' + str(variable_cost))
def sum_cost():
sum = rent + variable_cos... |
def corner_fill(square):
removeStarting = lambda x: [y[:-1] for y in x[1:]]
corner = lambda x: x[0]+[y[-1] for y in x[1:]]
result =[]
n = len(square)
if n == 0: return []
for i in range(n):
if i % 2 ==0:
result = result + corner(square)
else:
result = res... |
import networkx
from algorithms.dfs import dfs
def tree_diameter(t: networkx.Graph):
if __debug__:
assert networkx.is_tree(t)
v, _ = dfs(t)
_, longest_path_length = dfs(t, v)
return longest_path_length |
import dash
from dash import dcc
from dash import html
from dash.dependencies import Input, Output
import plotly.express as px
import pandas as pd
from dash import callback_context
df = px.data.election()
geojson = px.data.election_geojson()
candidates = df.winner.unique()
external_stylesheets = ['https://codepen.io/... |
"""this is a migration
Revision ID: 3aa95a42561c
Revises: 98fef64846fe
Create Date: 2021-10-04 10:49:46.832296
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "3aa95a42561c"
down_revision = "98fef64846fe"
branch_labels = None
depends_on = None
def upgrade():
... |
__version__ = "0.4.4"
from typing import Dict
_OPT_DEFAULTS: Dict[str, bool] = dict(
specialized_code=True,
optimize_einsums=True,
jit_script_fx=True,
)
def set_optimization_defaults(**kwargs) -> None:
r"""Globally set the default optimization settings.
Parameters
----------
**kwargs
... |
# -.- coding: latin-1 -.-
from __future__ import print_function
"""
Champernowne's constant
Problem 40
An irrational decimal fraction is created by concatenating the positive integers:
0.123456789101112131415161718192021...
It can be seen that the 12th digit of the fractional part is 1.
If dn represents the nth dig... |
import requests
class Books(object):
BASE_URL = \
'https://www.googleapis.com/books/v1/volumes?' \
'q="{}"&projection={}&printType={}&langRestrict={}&maxResults={}'
MAX_RESULTS = 1
PRINT_TYPE = 'books'
PROJECTION = 'full'
LANGUAGE = 'en'
# SEARCH_FIELDS = {
# "title":... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... |
# 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... |
# Copyright 2020 Toyota Research Institute. All rights reserved.
import torch
from packnet_sfm.models.SelfSupModel_fisheye import SfmModel, SelfSupModel_fisheye
from packnet_sfm.losses.supervised_loss_valeo import SupervisedLoss
from packnet_sfm.models.model_utils import merge_outputs
from packnet_sfm.utils.depth im... |
import time
from numba import jit
import numpy as np
@jit()
def jit_sum_conbination(N):
xs = [i for i in range(N)]
ys = [i for i in range(N)]
total = 0
for x in xs:
for y in ys:
total += x+y
return total
def py_sum_conbination(N):
xs = np.arange(N)
ys = np.arange(N)
... |
#!/usr/bin/env python3
# Copyright (c) 2019 The redspace Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Performs the same check as in Test_02 verifying that zPoS forked blocks that stake a zerocoin which is sp... |
# -*- coding: utf-8 -*-
#
# statsmodels documentation build configuration file, created by
# sphinx-quickstart on Sat Jan 22 11:17:58 2011.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
#... |
"""Tests for the KernelManager"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import asyncio
import concurrent.futures
import json
import os
import signal
import sys
import time
from subprocess import PIPE
import pytest
from jupyter_core import paths
from traitl... |
#!/bin/python
# -*- coding: utf-8 -*-
import comparators.pixel_comparator
import comparators.chained_image_comparator
import comparators.avg_pixel_comparator
import image_iterator
import sys
# Not really sets, since they may contain "duplicate" images(ie ones that when compared return True)
'''
Input:
image_sets:... |
"""
Utilities for managing moderator notes about users.
"""
import re
import discord
from redbot.core import checks
from redbot.core import commands
from redbot.core.bot import Red
from redbot.core.utils.chat_formatting import inline, box, pagify
from tsutils import CogSettings
class ModNotes(commands.Cog):
def... |
class Solution:
def removeDuplicates(self, S: str) -> str:
stack = []
for c in S:
if stack and stack[-1] == c:
stack.pop()
else:
stack.append(c)
return ''.join(stack) |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------
from . import _utils
from onnxruntime.capi.onnxruntime_inference_collec... |
#!/usr/bin/python
# Copyright (c) 2012-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Extract _("...") strings for translation and convert to Qt stringdefs so that
they can be picked up by Qt l... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: Quentin Kaiser <kaiserquentin@gmail.com>
#
# let's disable 'too many public methods'
# pylint: disable=R0904
"""
rabbitmq-management HTTP API client.
Example:
rbmq = RabbitMQManagementClient('localhost')
rbmq.whoami()
.. _Google Python Style Guide:
... |
"""
Example for posting data to Device Cloud for data graphing, storage and analysis.
(digi.com/products/cloud/digi-device-cloud)
by Rob Faludi, faludi.com
"""
import time
import httpclient
import ubinascii
version = '1.0.0'
username = 'your username here' #enter your username!
password = 'your password here'... |
from itools import lmbdWr,lm
import itertools
from bisect import bisect_right
import brailleG as gr
def abs2(n):
return (n*n.conjugate()).real
def fsample(buf,m=1,b=0):
index = 0
y = 0
while 1:
index = (index+b+m*y)%len(buf)
y = yield buf[(int(index)+1)%len(buf)]*(index%1)+buf[... |
"""NginxParser is a member object of the NginxConfigurator class."""
import copy
import functools
import glob
import logging
import re
import pyparsing
import six
from acme.magic_typing import Dict
from acme.magic_typing import List
from acme.magic_typing import Set
from acme.magic_typing import Tuple
from acme.magic... |
import os
import numpy as np
#os.environ["KERAS_BACKEND"] = "plaidml.keras.backend"
from keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array
from keras.models import Sequential, load_model
img_width, img_height = 48, 48
model_path = '../src/models/model.h5'
weights_path = '../src/models/weigh... |
# Copyright 2019 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
# Copyright (C) GRyCAP - I3M - UPV
#
# 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... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
#!/usr/bin/env python
"""Test Chipsec client actions."""
import collections
import sys
import mock
from chipsec.helper import oshelper
from grr.client import vfs
from grr.client.components.chipsec_support.actions import chipsec_types
from grr.lib import flags
from grr.test_lib import client_test_lib
from grr.test_l... |
#!/usr/bin/env python3
import xml.etree.ElementTree
from datetime import datetime, timedelta, timezone
from dateutil import parser
from statsSend.session import Session
from statsSend.utils import print_exception
from statsSend.urlBuilder import UrlBuilder
from statsSend.jenkins.jenkinsJob import JenkinsJob
class J... |
import os
import markdown2
from bs4 import BeautifulSoup
def get_obs_chapter_data(repo_dir, chapter_num):
obs_chapter_data = {
'title': None,
'frames': [],
'bible_reference': None
}
obs_chapter_file = os.path.join(repo_dir, 'content', f'{chapter_num}.md')
if not os.path.isfile(... |
# -*- coding: utf-8 -*-
from awx.main.models import Credential, CredentialType
def test_unique_hash_with_unicode():
ct = CredentialType(name=u'Väult', kind='vault')
cred = Credential(
id=4,
name=u'Iñtërnâtiônàlizætiøn',
credential_type=ct,
inputs={
u'vault_id': u'�... |
from django.db import models
from rest_framework import mixins, serializers, views, viewsets
from rest_framework.authentication import BaseAuthentication
from rest_framework.decorators import action
from rest_framework.views import APIView
from drf_spectacular.utils import extend_schema
from tests import generate_sche... |
import numpy as np
import warnings
import baselines.common.tf_util as U
import tensorflow as tf
import time
from baselines.common import zipsame, colorize
from contextlib import contextmanager
from collections import deque
from baselines import logger
from baselines.common.cg import cg
from baselines.pomis2.memory impo... |
import asyncio
import uuid
from fastapi import FastAPI, WebSocket
from fastapi.logger import logger
from pymobiledevice3.services.web_protocol.cdp_target import CdpTarget
from pymobiledevice3.services.web_protocol.session_protocol import SessionProtocol
from pymobiledevice3.services.webinspector import WirTypes
app ... |
"""ROUGE metric implementation.
Copy from tf_seq2seq/seq2seq/metrics/rouge.py.
This is a modified and slightly extended verison of
https://github.com/miso-belica/sumy/blob/valid/sumy/evaluation/rouge.py.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
f... |
import datetime
import urllib
from django.conf import settings
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from rest_flex_fields import FlexFieldsModelSerializer
from rest_flex_fields.serializers import FlexFieldsSerializerMixin
from rest_framework import serializers
from ... |
AUTHOR="Jared Haight (@jaredhaight)"
DESCRIPTION="This module will install/update Koadic C3 (COM Command and Control Framework)"
INSTALL_TYPE="GIT"
REPOSITORY_LOCATION="https://github.com/zerosum0x0/koadic"
INSTALL_LOCATION="koadic"
DEBIAN="python,python-pip"
ARCHLINUX = "python,python-pip"
BYPASS_UPDATE="NO"
A... |
import sys
import argparse
from .yamato_utils import get_base_path, run_standalone_build
def main(scene_path):
base_path = get_base_path()
print(f"Running in base path {base_path}")
executable_name = None
if scene_path is not None:
executable_name = scene_path.strip(".unity")
executa... |
import uuid
import pytest
import stix2
from stix2.exceptions import (
AtLeastOnePropertyError, CustomContentError, DictionaryKeyError,
)
from stix2.properties import (
BinaryProperty, BooleanProperty, DictionaryProperty,
EmbeddedObjectProperty, EnumProperty, ExtensionsProperty, FloatProperty,
HashesPr... |
from os import mkdir
from bottle import route, get, request, static_file, run
from settings import PORT, DIR_CACHE, DIR_GRAPH
from crypkograph import render_graph
@route('/')
@route('/index.html')
def serve_html():
return static_file('index.html', '.')
@route('/static/<filename:path>')
def serve_static(filena... |
from libweasyl import ratings
from libweasyl.cache import region
from weasyl import define as d
from weasyl import profile
from weasyl import searchtag
# For blocked tags, `rating` refers to the lowest rating for which that tag is
# blocked; for example, (X, Y, 10) would block tag Y for all ratings, whereas
# (X, Y, ... |
def main():
from sys import stdin, stdout
rl = stdin.readline
pl = stdout.write
int1 = int
str1 = str
xr = range
sum1 = sum
arr = [5]
for k in xr(1, 13):
arr[k] = arr[k - 1] * 5
for _ in xr(int1(rl())):
n = int1(rl())
c = sum1(n / i for i in arr)
pl(str1(c) + "\n")
main() |
from abc import ABCMeta
import logging
import json
class BaseObject(object):
__metaclass__ = ABCMeta
def __init__(self, **kwargs):
self.log = logging.getLogger("irchooky")
for prop in self.properties:
setattr(self, prop, kwargs.get(prop, ""))
def load(self, object_dict):
... |
"""Code for Bag-of-SFA Symbols."""
# Author: Johann Faouzi <johann.faouzi@gmail.com>
# License: BSD-3-Clause
import numpy as np
from math import ceil
from scipy.sparse import csr_matrix
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.ut... |
# Copyright 2016 Cisco Systems, 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 agreed to in writin... |
#
# PySNMP MIB module ROOMALERT3E-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ROOMALERT3E-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:50:01 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2018-04-04 05:44
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations
import django.db.models.deletion
import filer.fields.image
class Migration(migrations.Migration):
dependencies = [
migrations... |
from typing import Optional
from pydantic import BaseModel
class Seq2SeqFormat(BaseModel):
vocab_size: int
context_length: int
has_eos: Optional[bool] = False
keys = ["content", "target"] |
#!/usr/bin/python3
import time
def isTime(str):
try:
time.strptime(str, '%M:%S')
return True
except ValueError:
return False
def timeToSec(input):
return int(input.split(":")[0]) * 60 + int(input.split(":")[1])
def secToTime(input):
return str(input // 60) + ":" + '{:02d}'.fo... |
def how_many_paths_to_end(start_node,paths,no_go,exception_used,path_string):
'''
recursive walk
Parameters:
start_node (string) - the node from which we walk
paths (dict) - a dictionary where every node has a set of connected nodes
no_go (set) - a set of nodes that can not be visited as they a... |
maze = [[0,0,0,0,0,0,0,0,0,0],
[0,1,1,1,1,1,1,1,1,0],
[0,1,1,1,1,1,1,1,1,0],
[0,1,1,1,1,1,1,1,1,0],
[0,1,1,1,1,1,1,1,1,0],
[0,1,1,1,1,1,1,1,1,0],
[0,1,1,1,1,1,1,1,1,0],
[0,1,1,1,1,1,1,1,1,0],
[0,1,1,1,1,1,1,1,1,0],
[0,0,0,0,0,0,0,0,0,0]]
# we start... |
from pydmfet import proj_ao
from pydmfet.qcwrap.pyscf_rks_ao import rks_ao
from pyscf import gto,scf
import numpy as np
from pyscf.tools import molden
from pyscf import lo
from pyscf.lo import iao,orth
from functools import reduce
import math
bas ='ccpvdz'
temp = 0.01
mol = gto.Mole()
mol.atom = open('C3H6.xyz').read... |
# coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import os
from builtins import object
from pants.backend.python.python_requirement impor... |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
HEADRequest,
sanitized_Request,
urlencode_postdata,
)
class GDCVaultIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?gdcvault\.com/play/(?P<id>\d+)/(?P<name>(\w|-)+)?'
_NETRC_MACHINE = '... |
import unittest
import cirq
from cirq.ops import H, X, I
import random
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import randint
import hypothesis.strategies as st
from hypothesis import given, settings
def generate_binary(len):
return randint(2, size=len)
def encode_message(bits, base... |
# coding=utf-8
from jotdx.parser.base import BaseParser
from jotdx.helper import get_datetime, get_volume, get_price
from collections import OrderedDict
import struct
import six
class GetMinuteTimeData(BaseParser):
def setParams(self, market, code):
if type(code) is six.text_type:
code = code... |
""" ThisString Data type(str)
""" |
# Currently this script is configured to use the note-generator model.
from config import sequence_length, output_dir, note_generator_dir
from helper import loadChorales, loadModelAndWeights, createPitchSpecificVocabularies, createDurationVocabularySpecific
from music21 import note, instrument, stream, duration
import... |
import mahotas as mt
from skimage.feature import hog
def extract_features(img_gray, img_mask):
zernike = mt.features.zernike_moments(img_gray, 3)
fd = hog(img_mask, orientations=9, pixels_per_cell=(8, 8),
cells_per_block=(2, 2))
return list(zernike)+list(fd) |
from setuptools import setup, find_packages
setup(
name="tetrisRL",
version="0.5",
author="Jay Butera",
author_email="buterajay@gmail.com",
license="MIT",
url="https://github.com/jaybutera/tetrisRL",
packages=find_packages(),
install_requires=[
'numpy>=1.13',
'torch'
... |
from netmiko import ConnectHandler
from getpass import getpass
device1 = {
"host": 'cisco3.lasthop.io',
"username": 'pyclass',
"password": getpass(),
"device_type": 'cisco_ios',
# "session_log": 'my_session.txt'
}
device2 = {
"host": 'cisco4.lasthop.io',
"username": 'pyclass',
"passwor... |
#!/usr/bin/env python
"""@package GetUSGSNLCDForBoundingbox
@brief Download NLCD 2006 or 2011 data hosted by U.S. Geological Survey Web
Coverage Service (WCS) interface.
This software is provided free of charge under the New BSD License. Please see
the following license information:
Copyright (c) 2015, University o... |
"""
tests.pytests.integration.cli.test_salt_cloud
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
import pytest
pytest.importorskip("libcloud", reason="salt-cloud requires >= libcloud 0.11.4")
def test_function_arguments(salt_cloud_cli):
ret = salt_cloud_cli.run("--function", "show_image", "-h")
assert ret... |
# -*- coding: utf-8 -*-
"""This script generates Slicer Interfaces based on the CLI modules XML. CLI
modules are selected from the hardcoded list below and generated code is placed
in the cli_modules.py file (and imported in __init__.py). For this to work
correctly you must have your CLI executabes in $PATH"""
import x... |
import argparse
import time
import sys
import os
from src.static_trains import TrainParser
from src.const import HEADER
if __name__ == "__main__":
args_parser = argparse.ArgumentParser()
args_parser.add_argument("-a", "--apikey", metavar="YOUR_APIKEY",
help="apikey from developer... |
import builtins
from functools import lru_cache
from types import ModuleType, FunctionType, BuiltinFunctionType
from typing import Iterable
import torch
from .funcs import *
from .funcs import __all__ as _funcs_all
from .funcs.base import get_func_from_torch
from .size import *
from .size import __all__ as _size_all
... |
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
"""
[1,3,1]
[1,5,1]
[4,2,1]
time O (nm)
space O(nm)
state -> sums[r][c] = min path sum till r, c position
initial state -> sums[0][0…cols] = inf
-> sums... |
# Copyright 2019 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 required by applicable law or a... |
from typing import Optional
from flask import render_template, abort, flash, redirect, url_for
from flask_login.utils import login_user, logout_user
from .forms import LoginForm
from .decorators import admin_required
from ..auth.models import User
from ..blueprints import Blueprint
from ..globals import current_app, ... |
from __future__ import absolute_import
from collections import defaultdict
import copy
import logging
import socket
from . import ConfigResourceType
from kafka.vendor import six
from kafka.client_async import KafkaClient, selectors
import kafka.errors as Errors
from kafka.errors import (
IncompatibleBrokerVersio... |
"""
Add a keyword and a description field which are helpful for SEO optimization.
"""
from __future__ import absolute_import, unicode_literals
from django.db import models
from django.utils.translation import ugettext_lazy as _
from feincms import extensions
class Extension(extensions.Extension):
def handle_mo... |
def __bootstrap__():
global __bootstrap__, __loader__, __file__
import sys, pkg_resources, imp
__file__ = pkg_resources.resource_filename(__name__,'_position_weight_matrix.so')
__loader__ = None; del __bootstrap__, __loader__
imp.load_dynamic(__name__,__file__)
__bootstrap__() |
import requests, json
from sys import argv
from modify import write
country = "czech_republic"
url = f"https://top-ghusers.vercel.app/api?c={country}"
responce = requests.get(url)
resJson = json.loads(responce.text)
for user in resJson['users']:
if user['user']['username'] == argv[1]:
write(user['rank'])... |
from msc import bitarray_to_hex, int_to_bitarray, calculate_crc, InvalidCrcError, generate_transport_id
from mot import DirectoryEncoder, SortedHeaderInformation
from bitarray import bitarray
import logging
import types
import itertools
logger = logging.getLogger('msc.datagroups')
MAX_SEGMENT_SIZE=8189 # maximum data... |
import timeit
import os.path
import numpy as np
from math import exp, fabs
from sys import float_info
from globals import *
from utils import loadMatrix, resizeMatrix
from models.SingleOrigin import SingleOrigin
"""
Benchmarks for the Single Origin Constrained model (models/SingleOrigin.py)
All code here is lifted f... |
# -*- coding: utf-8 -*- #
# Copyright 2020 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... |
"""Nif User Interface, custom nif properties store for collisions settings"""
# ***** BEGIN LICENSE BLOCK *****
#
# Copyright © 2014, NIF File Format Library and Tools contributors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided th... |
# -*- coding: utf-8 -*-
import scrapy
import requests
from ..items import TencentItem
import json
class TencentSpider(scrapy.Spider):
name = 'tencent'
allowed_domains = ['careers.tencent.com']
one_url = 'https://careers.tencent.com/tencentcareer/api/post/Query?timestamp=1608216394591&countryId=&cityId=&bgI... |
"""
This module contains pdsolve() and different helper functions that it
uses. It is heavily inspired by the ode module and hence the basic
infrastructure remains the same.
**Functions in this module**
These are the user functions in this module:
- pdsolve() - Solves PDE's
- classify_pde() - Classif... |
from uuid import UUID
import pytest
from flexlate.transactions.transaction import FlexlateTransaction, TransactionType
ADD_SOURCE_ID = UUID("93f984ca-6e8f-45e9-b9b0-aebebfe798c1")
ADD_OUTPUT_ID = UUID("86465f4d-9752-4ae5-aaa7-791b4c814e8d")
ADD_SOURCE_AND_OUTPUT_ID = UUID("bf4cd42c-10b1-4bf9-a15f-294f5be738b0")
REMO... |
from .default_boilerplate import * # noqa: F401, F403 |
import re
import sys
from selenium import webdriver
def get_page_title(page_id):
"""
Get the title of a Facebook page. Reports an error and exits if no page was found.
:param page_id: Facebook ID of the page
:return:
string of the title of the page, if found
"""
options = webdriver.C... |
import json
from time import sleep, strftime, localtime
from qbittorrent import Client
def load_configs():
with open('config.json', 'r', encoding="UTF-8") as file:
js = json.load(file)
global HOST, PORT, LOGIN, PASSWORD, MIN_SIZE, MAX_SIZE
HOST = js["HOST"]
PORT = js["PORT"]
... |
#!/usr/bin/env python3
from setuptools import setup, find_packages
from fancytables import __version__
with open("README.md", "r") as f:
long_description = f.read()
setup(
name="fancytables",
version=__version__,
author="kleinesfilmröllchen",
description="Fancy table formatting that builds on pret... |
def square_pattern(n):
for i in range(n):
for j in range(n):
print("*",end=" ")
print()
square_pattern(5)
'''
python3 squarepattern.py
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
''' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.