content stringlengths 5 1.05M |
|---|
import json
import os
_data = {"files": []}
_directory = os.path.expanduser('~')
_bpl_file = '/.bpl'
def set_working_dir(dir):
os.chdir(dir)
def add_file(name):
_data["files"].append({"name": name})
def add_breakpoint(file_name, bp):
contained = False
for file in _data["files"]:
if file["... |
# Copyright 2017 Mycroft AI 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... |
URL = "url"
IOTA = "iota"
DOC = "document"
URL_TYPES = [URL, IOTA, DOC]
|
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
somap = somavaloter = maior = 0
for l in range(0, 3):
for c in range(0, 3):
n = ' '
while n.isnumeric() == False:
n = input(f'digite um valor para [{l}, {c}]: ')
if n.isnumeric() == False:
print('o valor digitado não ... |
import logging
import math
import cv2
import numpy as np
import tensorflow as tf
from neuralgym.ops.gan_ops import *
from neuralgym.ops.layers import *
from neuralgym.ops.layers import resize
from neuralgym.ops.loss_ops import *
from neuralgym.ops.summary_ops import *
from PIL import Image, ImageDraw
from tensorflow.c... |
#! usr/bin/python3.6
"""
Module initially auto generated using V5Automation files from CATIA V5 R28 on 2020-06-11 12:40:47.360445
.. warning::
The notes denoted "CAA V5 Visual Basic Help" are to be used as reference only.
They are there as a guide as to how the visual basic / catscript function... |
"""Actions for compiling Haskell source code"""
load(":private/java.bzl", "java_interop_info")
load(":private/path_utils.bzl",
"declare_compiled",
"target_unique_name",
"module_name",
"module_unique_name",
"get_external_libs_path",
)
load(":private/pkg_id.bzl", "pkg_id")
load(":private/providers.bzl", "Defau... |
from django.apps import AppConfig
class SysadminConfig(AppConfig):
name = 'sysadmin'
|
class Solution:
# @param {character[][]} matrix
# @return {integer}
def maximalSquare(self, matrix):
if not matrix:
return 0
max_square = 0
self.visited = []
for line in matrix:
row = []
for c in line:
row.append(0)
... |
print("1 commit in 1 day")
|
from builtins import str
import os, os.path
import subprocess
import sys
import tarfile
import wget
from htrc.volumes import download_volumes
from htrc.workset import path_to_volumes
MALLET_DIR = os.path.expanduser('~/mallet')
# Mallet is downloaded and intalled in user's home directory
def install_mallet():
if ... |
class Formatter:
"""Inherited class with methods called by numerous classes."""
def __init__(self, info_type, info):
self._type = info_type
self._info = info
def __str__(self):
return self._create_string()
def _create_string(self):
"""Create a multi-line string represen... |
"""Action for creating packages and registering them with ghc-pkg"""
load("@bazel_skylib//lib:paths.bzl", "paths")
load(":private/packages.bzl", "ghc_pkg_recache", "write_package_conf")
load(":private/path_utils.bzl", "get_lib_name", "is_hs_library", "target_unique_name")
load(":private/pkg_id.bzl", "pkg_id")
load(":p... |
#-------------
# HYPERPARAMS
#-------------
num_neg = 6
latent_features = 8
epochs = 20
batch_size = 256
learning_rate = 0.001
#-------------------------
# TENSORFLOW GRAPH
#-------------------------
graph = tf.Graph()
with graph.as_default():
# Define input placeholders for user, item and label.
user = t... |
from datetime import datetime
armstrong = datetime(1969, 7, 21, 14, 56, 15)
armstrong.year # 1969
armstrong.month # 7
armstrong.day # 21
armstrong.hour # 14
armstrong.minute # 56
armstrong.second # 15
armstrong.microsecond # 0
|
import requests
import json
from time import sleep
# lyrics
with open('lyrics.txt', 'r') as f:
all_lines = f.readlines()
token = "your token here"
while True:
for i in range(len(all_lines)):
#loop through lyrics.txt
content = {
"custom_status": {"text": all_lines[i]}
}
... |
from keras_segmentation.predict import predict,predict_multiple,predict_video
from keras_segmentation.models.all_models import model_from_name
test_image_path = "/home/mirap/database_folder/Menziesdata/ROI_examples_5_fold_whitehole/test_images/"
checkpoints_saving_path = "checkpoints/"
dataset_abbr = "MBf"
out_folder ... |
import torch
import numpy as np
import open3d as o3d
import trimesh
import mcubes
class SoftL1(torch.nn.Module):
def __init__(self):
super(SoftL1, self).__init__()
def forward(self, input, target, eps=0.0):
l1 = torch.abs(input - target)
ret = l1 - eps
ret = torch.clamp(ret, ... |
import os
import json
import logging
import requests
from urllib.parse import urljoin
logging.basicConfig(level=logging.INFO)
REQUEST_TIMEOUT = 10 # in seconds
API_V3_BASE = "https://api.github.com"
def api_request(url: str, http_request: str = 'get', check_response: bool = True, **kwargs):
url = urljoin(API_V... |
# Copyright 2020 The TensorFlow Authors. 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 applica... |
import requests
import json
from ..Config.config_handler import read_config
class ProcessBusDelays:
def __init__(self):
self.config_vals = read_config("Bus_API")
# Get the live data of Buses(Arrival Time, Departure Time, Delay) from API and returns.
def get_data_from_bus_api(self):
ur... |
'''
用来读取 cifar10 数据集
'''
import pickle
import re
import os
import numpy as np
import matplotlib.pyplot as plt
class Cifar10:
def __init__(self,path,one_hot = True):
self.path = path
self.one_hot = one_hot
self._epochs_completed = 0
self._index_in_epoch = 0
sel... |
file = open('input.txt', 'r')
Lines = file.readlines()
input = []
for line in Lines:
input.append(int(line.strip().split(' ')[0]))
my_dict = {}
for i, num1 in enumerate(input):
for j, num2 in enumerate(input):
if i != j and num1 + num2 <= 2020:
my_dict[num1+num2] = [i, j]
for i, num1 in enumerate(input):
i... |
# Generated by Django 2.2.10 on 2020-02-29 09:46
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [("approval", "0008_auto_20190506_1719")]
operations = [
migrations.AlterField(
... |
import logging
import re
from streamlink.plugin import Plugin, pluginmatcher
from streamlink.plugin.plugin import LOW_PRIORITY, stream_weight
from streamlink.stream.dash import DASHStream
from streamlink.utils.url import update_scheme
log = logging.getLogger(__name__)
@pluginmatcher(re.compile(
r"dash://(?P<url... |
"""
The Single Responsibility Principle
A class should have one, and only one, reason to change.
"""
food_bowl = 10
class Cat:
def __init__(self, name: str):
self.name = name
self.food_level = 30
self.cleanliness_level = 50
def meow(self):
print("meow")
def eat(self):
... |
import os
from itertools import chain
from .log import warn
from .entry import Entry, LoadError
DB_FILE_DEFAULT = os.path.expanduser(os.path.join("~", ".ripple.txt"))
DB_FILE = os.path.realpath(os.environ.get('RIPPLE_DB', DB_FILE_DEFAULT))
DB_DIR = os.environ.get('RIPPLE_DB_DIR', None)
if DB_DIR and os.path.isdir(DB_D... |
from contextlib import redirect_stdout
from io import StringIO
from pysweep.colors import SnakeColors
from pysweep.game import Board
class SnakeRenderer:
def __init__(self, with_chrome=True, colors=SnakeColors):
self._with_chrome = with_chrome
self._colors = colors
def render_board(self, gri... |
import os
import sys
from abc import ABCMeta, abstractmethod
from six import with_metaclass
modules = ["mod_unfilter", "mod_expand", "mod_sqli",
"mod_nosqli", "mod_lfi", "mod_crlf", "mod_exec", "mod_xss"]
themes = ["startbootstrap-agency-1.0.6", "startbootstrap-clean-blog-1.0.4"]
default = "unfilter"
clas... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import division
import os, sys, re
# Assumes SolidPython is in site-packages or elsewhwere in sys.path
from solid import *
from solid.utils import *
SEGMENTS = 24
# FIXME: ought to be 5
DFM = 5 # Default Material thickness
tab_width = 5
tab_offset = 4
tab_c... |
from dim import db
from dim.dns import get_ip_from_ptr_name
from dim.rrtype import validate_strings
from dim.errors import InvalidParameterError, AlreadyExistsError, InvalidZoneError, DimError
from tests.util import RPCTest, raises
def test_validate_strings():
validate_strings(None, 'strings', [r'''\"\\\223'''])
... |
""" Module to access the Saml endpoints """
# pylint: disable=too-many-lines,too-many-locals,too-many-public-methods,too-few-public-methods
from typing import Dict, Union
from pydantic import BaseModel
from ...models import (
MigrateAuthToSamlJsonBody,
ResetSamlAuthDataToEmailJsonBody,
ResetSamlAuthDataT... |
import logging
from datetime import datetime
from typing import Optional, Generator, Tuple
import shutil
from dateutil.parser import isoparse
from pathlib import Path
import pandas as pd
from collections import defaultdict
import calplot
from sqlite_utils import Database
from summary import update_daily_summaries
from ... |
from rbqwrapper import RbqWrapper, main
def test_init():
RbqWrapper()
def test_null():
main([])
|
from py_mplus.objects import MPData, MPObject
from py_mplus.objects.comment.comment_icon import CommentIcon
class SettingsView(MPObject):
def _decode(self, buffer: MPData, category, skip):
if category == 1:
self.my_icon = CommentIcon(buffer, buffer.uint32())
elif category == 2:
... |
from distutils.core import setup, Extension
xio = Extension('xio',
define_macros = [('MAJOR_VERSION', '0'),
('MINOR_VERSION', '9')],
include_dirs = ['/usr/local/include', '../../src', '../../include'],
libraries = ['xio'],
... |
# Lint as: python3
#
# Copyright 2020 The XLS 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... |
import re
from lib.settings import HTTP_HEADER
__product__ = "Sucuri Firewall (Sucuri Cloudproxy)"
def detect(content, **kwargs):
content = str(content)
headers = kwargs.get("headers", None)
detection_schema = (
re.compile(r"Access Denied - Sucuri Website Firewall"),
re.compile(r"Sucuri ... |
"""
This file is part of the openPMD-updater.
Copyright 2018 openPMD contributors
Authors: Axel Huebl
License: ISC
"""
from abc import abstractmethod
class ITransform(object):
"""Transform an openPMD file from one standard version to another.
"""
@abstractmethod
def __init__(self, backend):
... |
import numba as nb
import numpy as np
@nb.stencil(neighborhood=((-1,1),(-1,1)))
def _grad_x(arr):
""" Convolution with horizontal derivative kernel
H = [[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1]]
"""
dx = -(arr[-1,-1] + 2*arr[0,-1] + arr[1,-1]) + \
arr[-1, 1] + 2*arr[0, 1] + arr[... |
#!/usr/bin/env python
r"""Browse the given dataset
Example usage:
python browse.py \
--dataset=widerface \
--data_dir=/home/user/widerface/
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
import logging
import argparse
fr... |
from django.apps import AppConfig
class DjangoGuidConfig(AppConfig):
name = 'django_guid'
def ready(self) -> None:
"""
In order to avoid circular imports we import signals here.
"""
from django_guid import signals # noqa F401
from django_guid.config import settings
... |
import json
import requests
class Api:
"""Client for communicating with various APIs"""
BASE_URL = 'https://api-basketball.p.rapidapi.com'
def __init__(self, api_key: str):
self.HEADERS = {
'x-rapidapi-host': "api-basketball.p.rapidapi.com",
'x-rapidapi-key': api_key
... |
def insertionsort(array):
for x in range(1,len(array)):
key = array[x]
j = x - 1
while ( j >= 0 and key < array[j]):
array[j+1] = array[j]
j -= 1
array[j+1] = key
return array
l = []
for x in range(int(input("Enter no. of data: "))):
l.append(int(i... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
try:
import xml.etree.ElementTree as ET
except ImportError:
import xml.etree.cElementTree as ET
import HTMLParser
# 美化XML文件,缩进一致
def pretty_xml(elem, indent = " ", newline = "\n", null_str_keep = True, level = 0):
#print(level, len(elem), elem.text, ele... |
import tests.context.r4 as r4
import tests.context.stu3 as stu3
models = {
"r4": r4.model,
"stu3": stu3.model,
}
|
import torch
import models.utils.utils as utils #This lib is from original PGAN implementation.
def PGAN(pretrained=False, *args, **kwargs):
"""
Progressive growing model
pretrained (bool): load a pretrained model ?
model_name (string): if pretrained, load one of the following models
celebaHQ-256... |
#/usr/bin/env python3
import sys
if len(sys.argv) <= 1:
print("Usage: (path to repo list)+")
sys.exit(-1)
OPATH = "uniqTypedPrjs.txt"
lines = []
for ipath in sys.argv[1:]:
try:
with open(ipath, encoding="utf8") as f:
lines.extend(f.read().splitlines())
except IOError:
... |
import pydwarf
import raws
milk_beer_reaction = """
[REACTION:BREW_DRINK_FROM_ANIMAL_EXTRACT]
[NAME:brew drink from animal extract]
[BUILDING:STILL:CUSTOM_A]
[REAGENT:extract:150:LIQUID_MISC:NONE:NONE:NONE]
[HAS_MATERIAL_REACTION_PRODUCT:DRINK_MAT]
[UNROTTEN]
[REAGENT:extract container:... |
import datetime
import time
resolution_dict = {
'1': 60,
'5': 5 * 60,
'15': 15 * 60,
'30': 30 * 60,
'60': 60 * 60,
'240': 240 * 60,
'D': 3600 * 60
}
def convert_tv2ok_resolution(resolution):
return resolution_dict[resolution]
def convert_timestamp2ok(timestamp):
return datetime.... |
# Copyright (c) 2014 Museum Victoria
# This software is released under the MIT license (see license.txt for details)
from Queue import *
import threading
import atexit
remote_action_PowerOn = RemoteAction()
remote_action_PowerOff = RemoteAction()
remote_action_SetInput = RemoteAction()
def local_action_activate(x = ... |
import sqlite3
# Потокобезопасное подключение. Не открываем соединение в каждой функции, только в декораторе
def ensure_connection(funct):
def inlay(*args, **kwargs):
with sqlite3.connect('vault.db') as conn:
res = funct(*args, conn=conn, **kwargs)
return res
return inlay
@ensur... |
from django.test import TestCase
from django.test.client import RequestFactory
class TestRender(TestCase):
def _callFUT(self, request, template_name,
context=None, content_type=None, status=None, using=None):
from variantmpl.shortcuts import render
return render(request, templat... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from typing import Iterator, List, Optional
from collections import UserList
from torch import nn, Tensor
from torch.optim.optimizer import Optimizer
from torch.optim.lr_scheduler import _LRScheduler
from archai.common.utils import zi... |
from hostlookup_abstract.api.views import BaseHostView
from hostlookup_netdisco.utils import host_lookup
class HostView(BaseHostView):
def host_lookup(self, request, q=''):
return host_lookup(q)
|
from ark.tasks.task_check_for_update import Task_CheckForUpdates
from ark.tasks.task_list_players import Task_ListPlayers
from ark.tasks.task_get_chat import Task_GetChat
from ark.tasks.task_daily_restart import Task_DailyRestart
from ark.tasks.task_daily_restart import Task_DailyRestartRepopulate
from ark.tasks.task_s... |
import tensorflow as tf
# 对多个输入进行merge操作的层
class ReversedConcatenate1D(tf.keras.layers.Layer):
"""对输入进行反向拼接"""
def __init__(self, axis=-1, **kwargs):
super(ReversedConcatenate1D, self).__init__(**kwargs)
self.axis = axis
def call(self, inputs, mask=None):
if mask is None:
... |
def sieve(m):
l = [True]*(int(m**.5)+2)
l[0], l[1] = False, False
for i in range(2, len(l)):
if not l[i]:
continue
for j in range(i*2, len(l), i):
l[j] = False
return l
def solution(n):
k = 100000000000
c = 0
for i, prime in enumerate(sieve(k)):
... |
#Make the model now
class PowerPredictor(nn.Module):
def __init__(self,input_features,num_outputs,neuronslist):
super().__init__()
self.input_features = input_features
self.num_outputs = num_outputs
self.neuronslist = neuronslist
'''Here,
input_features : Number of different features i... |
from .apu import Apu
|
with open("12/nav.txt") as f:
lines = [x.strip() for x in f.readlines()]
instructions = list(map(lambda x: [x[0], x[1:]], lines))
direction = "E"
position = [0, 0]
def move(action: str, value: int):
if action == "N":
position[1] += value
elif action == "S":
position[1] -= value
elif a... |
#!/usr/bin/python
def edit_distance(x, y, n, m):
if m == 0:
return n
if n == 0:
return m
if x[n - 1] == y[m - 1]:
return edit_distance(x, y, n - 1, m - 1)
return 1 + min(
edit_distance(x, y, n - 1, m),
edit_distance(x, y, n, m - 1),
edit_distance(x, y, n - 1, m - 1)
)
def edit_distance_dp_recur... |
#!/usr/bin/env python3
"""
Validate if given list of files are encrypted with sops.
"""
from argparse import ArgumentParser
from ruamel.yaml import YAML
from ruamel.yaml.parser import ParserError
import sys
yaml = YAML(typ='safe')
def validate_enc(item):
"""
Validate given item is encrypted.
All leaf va... |
"""Top-level package for justice."""
__author__ = """Jakub Boukal"""
__email__ = '[email protected]'
__version__ = '0.1.8'
|
import codecs
import re
import argparse
import os
def is_chapter_name(line):
chapter_pattern = re.compile(r'第[0-9零一二三四五六七八九十百千]+章')
chapter_pattern2 = re.compile(r'^[0-9零一二三四五六七八九十百千]+$')
chapter_pattern3 = re.compile(r'^[0-9]')
b = re.search(chapter_pattern, line) is not None or \
re.search(ch... |
"""
Facilities for testing RL-related code.
"""
from .util import SimpleEnv, SimpleModel, TupleCartPole
__all__ = dir()
|
# Sudoku is a number-placement puzzle. The objective is to fill a 9 × 9 grid
# with digits so that each column, each row, and each of the nine 3 × 3 sub-grids
# that compose the grid contains all of the digits from 1 to 9.
#
# This algorithm should check if the given grid of numbers represents a correct solution to Su... |
import logging
import urllib3
from flask import Flask
from werkzeug.middleware.dispatcher import DispatcherMiddleware
from socorepo import config
from socorepo.config.loader import load_general_settings, load_remaining_config
from socorepo.log import setup_logging
def app_root_404(env, resp):
resp("404", [("Con... |
from seleniumpm.examples.wikipedia import Wikipedia
from seleniumpm.examples.widgets.WikipediaPersonal import WikipediaPersonal
from seleniumpm.webelements.link import Link
from seleniumpm.locator import Locator
class SuperWikipedia(Wikipedia):
"""
This is simply an example of how you could extend Webpage cla... |
from aoc_cas.aoc2019.IntCodeComputer import IntCodeComputerVM, read_program
def instructions(*inputs):
for i in inputs:
yield from map(ord, i + "\n")
def gogoSpringyBoi(program, inputs):
vm = IntCodeComputerVM(program)
vm.input_provided_from(inputs)
s = []
row = ""
for r in vm.run():... |
from pgfutils import save, setup_figure
setup_figure(width=1, height=1)
from matplotlib import pyplot as plt
from matplotlib.lines import Line2D
cmap = plt.cm.coolwarm
custom_lines = [
Line2D([0], [0], color=cmap(0), lw=4),
Line2D([0], [0], color=cmap(0.5), lw=4),
Line2D([0], [0], color=cmap(1), lw=4),... |
import sys
if sys.version_info < (3, 10):
from importlib_metadata import entry_points
else:
from importlib.metadata import entry_points
from . import (
cpu,
devices,
gpu,
memory,
)
__all__ = (
"cpu",
"devices",
"gpu",
"installed_plugins",
"memory",
)
installed_plugins = ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
:mod:`lse`
==================
.. module:: lse
:platform: Unix, Windows
:synopsis:
.. moduleauthor:: hbldh <[email protected]>
Created on 2015-11-05, 16:30
"""
from __future__ import division
from __future__ import print_function
from __future__ impo... |
"""
Tests whether NoMissingEmbeddings works
"""
import math
from inspect import cleandoc
from pandas import DataFrame
from testfixtures import compare
from mlinspect import DagNode, BasicCodeLocation, OperatorContext, OperatorType, FunctionInfo, DagNodeDetails, \
OptionalCodeInfo
from mlinspect._pipeline_inspecto... |
import numpy as np
import numba
# Склаярное произведение комплексных векторов
@numba.jit()
def complex_dot_prod(vec1, vec2):
return vec1.dot(np.conj(vec2))
# Проверка матрицы на квадратность
@numba.jit()
def check_square(H):
if H.shape.count(H.shape[0]) == len(H.shape):
return True
else:
... |
import json
from resource import Resource
class SubResource(Resource):
"""
Base class for resources that are purely subresources.
These resources should be handled through their corresponding
ParentResource classes.
"""
def update(self, **options):
"""
Updates the given subreso... |
#!/usr/bin/python
import os, sys
from wallaby import *
import drive as d
import constants as c
def waitForButton():
print("waiting for right button")
while right_button() == 0:
pass
print("right button pressed")
msleep(500)
def moveServo(servo, position, speed):
i = get_servo_position(s... |
###########################
# Implements Q and A functionality
###########################
from discord import NotFound
import db
# keep track of next question number
QUESTION_NUMBER = 1
# dictionary of questions with answers
QNA = {}
###########################
# Class: QuestionsAnswers
# Description: object with q... |
import os
class SignalListener:
def buy_signal(self, ticker, signal_name):
self.say("Buy " + self.split_chars(ticker) + ", " + signal_name)
def sell_signal(self, ticker, signal_name):
self.say("Sell " + self.split_chars(ticker) + ", " + signal_name)
def split_chars(self, stock_name):
... |
# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.db import models
class PoliticalParty(models.Model):
name = models.CharField(verbose_name=u"Naziv stranke", max_length=200)
short_name = models.CharField(verbose_name=u"Kratki naziv", max_length=50)
slug = models.SlugField(ver... |
from collections import defaultdict
from databird import Repository
from databird import utils
from typing import List
import datetime as dt
import logging
from databird.queue import MultiQueue
from redis import Redis
logger = logging.getLogger("databird.runner")
def retrieve_missing(
root_dir, repos: List[Repos... |
from pyomo.environ import sqrt, log, exp
Rgas = 8.3144598 # J/mol/K
pref = 101325 # Pa
Tref = 273.15 # K
class air:
'''
Thermodynamic data of water from US Bureau of Mines
for standard pressure (101325 Pa)'''
M = 28.8503972
def cp0(T):
'''Specific heat, J/mol/K '''
... |
# -*- encoding: utf-8 -*-
import sys
import threading
import time
import typing
import attr
from ddtrace.internal import nogevent
from ddtrace.internal import service
class PeriodicThread(threading.Thread):
"""Periodic thread.
This class can be used to instantiate a worker thread that will run its `run_per... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 11 14:16:25 2018
@author: Arpit
"""
from games.game import Game
class T3Game(Game):
WINNER_R = 1
LOSER_R = -1
DRAW_R = 0
def __init__(self, size=3, **kwargs):
super().__init__(**kwargs)
self.rows = siz... |
'''Leap year or not'''
def leapyear(year):
if (year % 4 == 0) and (year % 100 != 0) or (year % 400==0) : #checking for leap year
print(year," is a leap year") #input is a leap year
else:
print(year," is not a leap year") #input is not a leap year
year=int(input("Enter the year: "))
while year<=999 or year>=... |
from setuptools import setup, find_packages
exec(open("ddfs/_version.py", encoding="utf-8").read())
LONG_DESC = open("README.rst", encoding="utf-8").read()
setup(
name="ddfs",
version=__version__,
description="de-dup file system",
url="Project URL (for setup.py metadata)",
long_description=LONG_D... |
import os
import sys
import argparse
env_path = os.path.join(os.path.dirname(__file__), '..')
if env_path not in sys.path:
sys.path.append(env_path)
from pytracking.evaluation import Tracker
def run_video(tracker_name, tracker_param, videofile, optional_box=None, debug=None):
"""Run the tracker on your webc... |
def extractEuricetteWordpressCom(item):
'''
Parser for 'euricette.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('Greatest Alchemist', 'Someday Will I Be The Greatest A... |
import functools
from typing import Callable
import numpy as np
import pytest
from l5kit.data import AGENT_DTYPE, FRAME_DTYPE, ChunkedDataset
from l5kit.rasterization import StubRasterizer
from l5kit.sampling import generate_agent_sample
def get_partial(
cfg: dict, history_num_frames: int, history_step_size: in... |
import base64
import requests
from bleach import config
from bleach.models import pullrequest
def listPullRequests(owner, repository):
url = _getUrl(owner, repository)
headers = _getHeaders()
processedResults = []
keepFetchingResults = True
while keepFetchingResults:
response = requests.... |
from model.contact import Contact
import random
def test_delete_some_contact(app, db, check_ui):
if app.contact.count() == 0:
app.contact.create(Contact(firstname="Peter", lastname="Pyatochkin", company="System Group", address="Ukraine, Kiev, Vatslava Gavela blvd., 4",
mo... |
# coding=utf-8
import subprocess
__author__ = 'davis.peixoto'
class GitUtils(object):
cd = None
def __init__(self):
pass
def get_commits_strings(self, path):
pass
def get_tags_list(self):
pass
@staticmethod
def get_rep_name(project_repository_path):
command... |
from datetime import datetime
from typing import Any
from chaosplt_grpc import remote_channel
from chaosplt_grpc.scheduler.client import schedule_experiment, \
cancel_experiment
__all__ = ["SchedulerService"]
class SchedulerService:
def __init__(self, config):
grpc_config = config["grpc"]["scheduler... |
import numpy as np
from PIL import Image
from mmd_scripting.scratch_stuff.progprint import progprint, progclean
_SCRIPT_VERSION = "Script version: Nuthouse01 - v0.5.01 - 09/13/2020"
"""
Given a no-tattoo body and a tattoo body, and a single color, calc the transparency needed
to create the tattoo mask sitting on top... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 29 12:37:37 2019
@author: gaetandissez
"""
import numpy as np
import sklearn.metrics as metrics
from spherecluster import SphericalKMeans
from sklearn.cluster import KMeans
from scipy import sparse
class NMTF:
#First load and convert to numpy... |
import sys
from StringIO import StringIO
from django.test import TestCase
from django.core.management import call_command
from django_extensions.tests.models import Name
from django.conf import settings
from django.db.models import loading
class DumpScriptTests(TestCase):
def setUp(self):
self.real_stdout... |
import setuptools
__version__ = "0.0.1"
__description__ = 'The package targets to help user in playing the game wordle'
__author__ = 'ASK Jennie Developer <[email protected]>'
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name='guesstheword',
version=__version__... |
# Ivan Carvalho
# Solution to https://www.urionlinejudge.com.br/judge/problems/view/1020
# -*- coding: utf-8 -*-
'''
Escreva a sua solução aqui
Code your solution here
Escriba su solución aquí
'''
entrada = int(raw_input())
for a,b in [(365,"ano(s)"),(30,"mes(es)"),(1,"dia(s)")]:
total = int(entrada/a)
print "... |
import pandas as pd
def print_stage(stage_str):
count = 100
occupied_count = len(stage_str)
separator_num = int((count - occupied_count) / 2)
separator_str = "=" * separator_num
print_str = f"{separator_str}{stage_str}{separator_str}"
print(print_str)
def epoch_time(start_time, end_time):
... |
import os
# 调试模式
DEBUG = True
# session
SECRET_KEY = os.urandom(24)
# 本地数据密码是rootroot, 119.23.218.150的是123456
#数据库连接配置
# HOSTNAME = "119.23.218.150"
HOSTNAME = "118.190.2.84"
PORT = '3306'
DATABASE='multiLanguage'
USERNAME='root'
PASSWORD='Linghong2017'
# PASSWORD='123456'
DB_URI = 'mysql+mysqlconnecto... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.