content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------
class DashboardInfo:
MODEL_ID_KEY = "id" # To match Model schema
MODEL_INFO_FILENAME = "model_info.json"
RAI_INSIGHTS_MODEL_... | class Dashboardinfo:
model_id_key = 'id'
model_info_filename = 'model_info.json'
rai_insights_model_id_key = 'model_id'
rai_insights_run_id_key = 'rai_insights_parent_run_id'
rai_insights_parent_filename = 'rai_insights.json'
class Propertykeyvalues:
rai_insights_type_key = '_azureml.responsibl... |
#4 lines: Fibonacci, tuple assignment
parents, babies = (1, 1)
while babies < 100:
print ('This generation has {0} babies'.format(babies))
parents, babies = (babies, parents + babies) | (parents, babies) = (1, 1)
while babies < 100:
print('This generation has {0} babies'.format(babies))
(parents, babies) = (babies, parents + babies) |
# Copyright 2014 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... | """Public definitions for Go rules.
All public Go rules, providers, and other definitions are imported and
re-exported in this file. This allows the real location of definitions
to change for easier maintenance.
Definitions outside this file are private unless otherwise noted, and
may change without notice.
"""
load(... |
# model settings
norm_cfg = dict(type='BN', requires_grad=True)
model = dict(
type='EncoderDecoder',
pretrained='pretrain/vit_base_patch16_224.pth',
backbone=dict(
type='VisionTransformer',
img_size=(224, 224),
patch_size=16,
in_channels=3,
embed_dim=768,
dept... | norm_cfg = dict(type='BN', requires_grad=True)
model = dict(type='EncoderDecoder', pretrained='pretrain/vit_base_patch16_224.pth', backbone=dict(type='VisionTransformer', img_size=(224, 224), patch_size=16, in_channels=3, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4, qkv_bias=True, drop_rate=0.0, attn_drop_rate=0... |
# Copyright (C) 2019 Intel Corporation. All rights reserved.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
load("@bazel_tools//tools/build_defs/cc:action_names.bzl", "ACTION_NAMES")
load(
"@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl",
"feature",
"flag_group",
"flag_set",
"tool_p... | load('@bazel_tools//tools/build_defs/cc:action_names.bzl', 'ACTION_NAMES')
load('@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl', 'feature', 'flag_group', 'flag_set', 'tool_path')
all_compile_actions = [ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile]
all_link_actions = [ACTION_NAMES.cpp_link_executable, ACTION_N... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Contains core logic for Rainman2
"""
__author__ = 'Ari Saha (arisaha@icloud.com), Mingyang Liu(liux3941@umn.edu)'
__date__ = 'Wednesday, February 14th 2018, 11:42:09 am'
| """
Contains core logic for Rainman2
"""
__author__ = 'Ari Saha (arisaha@icloud.com), Mingyang Liu(liux3941@umn.edu)'
__date__ = 'Wednesday, February 14th 2018, 11:42:09 am' |
train_data_path = "../data/no_cycle/train.data"
dev_data_path = "../data/no_cycle/dev.data"
test_data_path = "../data/no_cycle/test.data"
word_idx_file_path = "../data/word.idx"
word_embedding_dim = 100
train_batch_size = 32
dev_batch_size = 500
test_batch_size = 500
l2_lambda = 0.000001
learning_rate = 0.001
epoch... | train_data_path = '../data/no_cycle/train.data'
dev_data_path = '../data/no_cycle/dev.data'
test_data_path = '../data/no_cycle/test.data'
word_idx_file_path = '../data/word.idx'
word_embedding_dim = 100
train_batch_size = 32
dev_batch_size = 500
test_batch_size = 500
l2_lambda = 1e-06
learning_rate = 0.001
epochs = 100... |
class Input(object):
def __init__(self, type, data):
self.__type = type
self.__data = deepcopy(data)
def __repr__(self):
return repr(self.__data)
def __str__(self):
return str(self.__type) + str(self.__data)
| class Input(object):
def __init__(self, type, data):
self.__type = type
self.__data = deepcopy(data)
def __repr__(self):
return repr(self.__data)
def __str__(self):
return str(self.__type) + str(self.__data) |
class SnakeGame(object):
def __init__(self, width,height,food):
"""
Initialize your data structure here.
@param width - screen width
@param height - screen height
@param food - A list of food positions
E.g food = [[1,1], [1,0]] means the first food is positioned at ... | class Snakegame(object):
def __init__(self, width, height, food):
"""
Initialize your data structure here.
@param width - screen width
@param height - screen height
@param food - A list of food positions
E.g food = [[1,1], [1,0]] means the first food is positioned a... |
class Player:
def __init__(self, nickname, vapor_id, player_id, ip):
self.nickname = nickname
self.vapor_id = vapor_id
self.player_id = player_id
self.ip = ip
self.not_joined = True
self.loads_map = True
self.joined_after_change_map = True
class Players:
... | class Player:
def __init__(self, nickname, vapor_id, player_id, ip):
self.nickname = nickname
self.vapor_id = vapor_id
self.player_id = player_id
self.ip = ip
self.not_joined = True
self.loads_map = True
self.joined_after_change_map = True
class Players:
... |
# 377 Combination Sum IV
# Given an integer array with all positive numbers and no duplicates,
# find the number of possible combinations that add up to a positive integer target.
#
# Example:
#
# nums = [1, 2, 3]
# target = 4
#
# The possible combination ways are:
# (1, 1, 1, 1)
# (1, 1, 2)
# (1, 2, 1)
# (1, 3)
# (2,... | class Solution:
def combination_sum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
res = [0] * (target + 1)
for i in range(1, len(res)):
for num in nums:
if num > i:
... |
#
# PySNMP MIB module DABING-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file://..\DABING-MIB.mib
# Produced by pysmi-0.3.4 at Tue Mar 22 12:53:47 2022
# On host ? platform ? version ? by user ?
# Using Python version 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (Intel)]
#
OctetString, Objec... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, value_range_constraint, single_value_constraint, value_size_constraint) ... |
def solve(polynomial):
"""
input is polynomial
if more than one variable, returns 'too many variables'
looks for formula to apply to coefficients
returns solution or 'I cannot solve yet...'
"""
if len(polynomial.term_matrix[0]) > 2:
return 'too many variables'
elif len(polynomial... | def solve(polynomial):
"""
input is polynomial
if more than one variable, returns 'too many variables'
looks for formula to apply to coefficients
returns solution or 'I cannot solve yet...'
"""
if len(polynomial.term_matrix[0]) > 2:
return 'too many variables'
elif len(polynomial... |
class TreeNode:
def __init__(self, name, data, parent=None):
self.name = name
self.parent = parent
self.data = data
self.childs = {}
def add_child(self, name, data):
self.childs.update({name:(type(self))(name, data, self)})
def rm_branch(self, name, ansistors_n: lis... | class Treenode:
def __init__(self, name, data, parent=None):
self.name = name
self.parent = parent
self.data = data
self.childs = {}
def add_child(self, name, data):
self.childs.update({name: type(self)(name, data, self)})
def rm_branch(self, name, ansistors_n: lis... |
api_key = "9N7hvPP9yFrjBnELpBdthluBjiOWzJZw"
mongo_url = 'mongodb://localhost:27017'
mongo_db = 'CarPopularity'
mongo_collections = ['CarSalesByYear', 'PopularCarsByRegion']
years_data = ['2019', '2018', '2017', '2016', '2015']
test_mode = True | api_key = '9N7hvPP9yFrjBnELpBdthluBjiOWzJZw'
mongo_url = 'mongodb://localhost:27017'
mongo_db = 'CarPopularity'
mongo_collections = ['CarSalesByYear', 'PopularCarsByRegion']
years_data = ['2019', '2018', '2017', '2016', '2015']
test_mode = True |
class Solution:
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if not nums:
return [-1, -1]
low = 0
high = len(nums) - 1
f = 0
while low<=high:
mid = (low+h... | class Solution:
def search_range(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if not nums:
return [-1, -1]
low = 0
high = len(nums) - 1
f = 0
while low <= high:
mid = (l... |
#
# PySNMP MIB module MWORKS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MWORKS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:16:04 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, constraints_union, value_size_constraint, constraints_intersection) ... |
# == 1 ==
bar = [1, 2]
def foo(bar):
bar = sum(bar)
return bar
print(foo(bar))
# == 2 ==
bar = [1, 2]
def foo(bar):
bar[0] = 1
return sum(bar)
print(foo(bar))
# == 3 ==
bar = [1, 2]
def foo():
bar = sum(bar)
return bar
print(foo())
# == 4 ==
bar = [1, 2]
def foo(bar):
bar =... | bar = [1, 2]
def foo(bar):
bar = sum(bar)
return bar
print(foo(bar))
bar = [1, 2]
def foo(bar):
bar[0] = 1
return sum(bar)
print(foo(bar))
bar = [1, 2]
def foo():
bar = sum(bar)
return bar
print(foo())
bar = [1, 2]
def foo(bar):
bar = [1, 2, 3]
return sum(bar)
print(foo(bar), bar)
ba... |
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose with or without fee is hereby granted,
# provided that the above copyright notice and ... | """Class ANY (generic) rdata type classes."""
__all__ = ['AFSDB', 'AMTRELAY', 'AVC', 'CAA', 'CDNSKEY', 'CDS', 'CERT', 'CNAME', 'CSYNC', 'DLV', 'DNAME', 'DNSKEY', 'DS', 'EUI48', 'EUI64', 'GPOS', 'HINFO', 'HIP', 'ISDN', 'LOC', 'MX', 'NINFO', 'NS', 'NSEC', 'NSEC3', 'NSEC3PARAM', 'OPENPGPKEY', 'OPT', 'PTR', 'RP', 'RRSIG', ... |
n = int(input())
row = 0
for i in range(100):
if 2 ** i <= n <= 2 ** (i + 1) - 1:
row = i
break
def seki(k, n):
for _ in range(n):
k = 4 * k + 2
return k
k = 0
if row % 2 != 0:
k = 2
cri = seki(k, row // 2)
if n < cri:
print("Aoki")
else:
print("Ta... | n = int(input())
row = 0
for i in range(100):
if 2 ** i <= n <= 2 ** (i + 1) - 1:
row = i
break
def seki(k, n):
for _ in range(n):
k = 4 * k + 2
return k
k = 0
if row % 2 != 0:
k = 2
cri = seki(k, row // 2)
if n < cri:
print('Aoki')
else:
print('Takah... |
bino = int(input())
cino = int(input())
if (bino+cino)%2==0:
print("Bino")
else:
print("Cino")
| bino = int(input())
cino = int(input())
if (bino + cino) % 2 == 0:
print('Bino')
else:
print('Cino') |
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 2 11:06:59 2019
@author: Paul
"""
def read_data(filename):
"""
Reads csv file into a list, and converts to ints
"""
data = []
f = open(filename, 'r')
for line in f:
data += line.strip('\n').split(',')
... | """
Created on Mon Dec 2 11:06:59 2019
@author: Paul
"""
def read_data(filename):
"""
Reads csv file into a list, and converts to ints
"""
data = []
f = open(filename, 'r')
for line in f:
data += line.strip('\n').split(',')
int_data = [int(i) for i in data]
f.close()
retur... |
class Rectangle:
"""A rectangle shape that can be drawn on a Canvas object"""
def __init__(self, x, y, width, height, color):
self.x = x
self.y = y
self.width = width
self.height = height
self.color = color
def draw(self, canvas):
"""Draws itself into the Ca... | class Rectangle:
"""A rectangle shape that can be drawn on a Canvas object"""
def __init__(self, x, y, width, height, color):
self.x = x
self.y = y
self.width = width
self.height = height
self.color = color
def draw(self, canvas):
"""Draws itself into the Ca... |
print(b)
print(c)
print(d)
print(e)
print(f)
print(g) | print(b)
print(c)
print(d)
print(e)
print(f)
print(g) |
print("hiiiiiiiiiiiiiiiix")
def sayhi():
print("2nd pkg said hi")
| print('hiiiiiiiiiiiiiiiix')
def sayhi():
print('2nd pkg said hi') |
base = int(input('Digite o valor da base: '))
expoente = 0
while expoente <= 0:
expoente = int(input('Digite o valor do expoente: '))
if expoente <= 0:
print('O expoente tem que ser positivo')
potencia = 1
for c in range(1, expoente + 1):
potencia *= base
print(f'{base}^ {expoente} = {potencia}'... | base = int(input('Digite o valor da base: '))
expoente = 0
while expoente <= 0:
expoente = int(input('Digite o valor do expoente: '))
if expoente <= 0:
print('O expoente tem que ser positivo')
potencia = 1
for c in range(1, expoente + 1):
potencia *= base
print(f'{base}^ {expoente} = {potencia}') |
# 084
# Ask the user to type in their postcode.Display the first two
# letters in uppercase.
# very simple
print(input('Enter your postcode: ')[0:2].upper()) | print(input('Enter your postcode: ')[0:2].upper()) |
test = """forward 5
down 5
forward 8
up 3
down 8
forward 2
"""
def part1(lines):
h = 0
d = 0
for line in lines:
direction, delta = line.split()
delta = int(delta)
if direction == 'forward':
h += delta
elif direction == 'down':
d += delta
elif... | test = 'forward 5\ndown 5\nforward 8\nup 3\ndown 8\nforward 2\n'
def part1(lines):
h = 0
d = 0
for line in lines:
(direction, delta) = line.split()
delta = int(delta)
if direction == 'forward':
h += delta
elif direction == 'down':
d += delta
e... |
MANDRILL_API_KEY = 'MANDRILL_API_KEY'
UNSET_MANDRILL_API_KEY_MSG = f"Mandrill API key not set in environment variable {MANDRILL_API_KEY}"
CONTACT_LIST_QUERY = """
SELECT *
FROM `{{project}}.{{dataset}}.{{contact_table}}`
"""
EHR_OPERATIONS = 'EHR Ops'
EHR_OPS_ZENDESK = 'support@aou-ehr-ops.zendesk.com'
DATA_CURATION_... | mandrill_api_key = 'MANDRILL_API_KEY'
unset_mandrill_api_key_msg = f'Mandrill API key not set in environment variable {MANDRILL_API_KEY}'
contact_list_query = '\nSELECT *\nFROM `{{project}}.{{dataset}}.{{contact_table}}`\n'
ehr_operations = 'EHR Ops'
ehr_ops_zendesk = 'support@aou-ehr-ops.zendesk.com'
data_curation_lis... |
MAP = 1
SPEED = 1.5
VELOCITYRESET = 6
WIDTH = 1280
HEIGHT = 720
X = WIDTH / 2 - 50
Y = HEIGHT / 2 - 50
MOUSER = 325
TICKRATES = 120
nfc = False
raspberry = False | map = 1
speed = 1.5
velocityreset = 6
width = 1280
height = 720
x = WIDTH / 2 - 50
y = HEIGHT / 2 - 50
mouser = 325
tickrates = 120
nfc = False
raspberry = False |
def main():
n = 111
gen = (n * 7 for x in range(10))
if 777 in gen:
print("Yes!")
if __name__ == '__main__':
main()
| def main():
n = 111
gen = (n * 7 for x in range(10))
if 777 in gen:
print('Yes!')
if __name__ == '__main__':
main() |
class BaseStorageManager(object):
def __init__(self, adpter):
self.adapter = adpter
def put(self, options):
try:
return self.adapter.put(options)
except Exception:
raise Exception('Failed to write data to storage')
def get(self, options):
try:
... | class Basestoragemanager(object):
def __init__(self, adpter):
self.adapter = adpter
def put(self, options):
try:
return self.adapter.put(options)
except Exception:
raise exception('Failed to write data to storage')
def get(self, options):
try:
... |
def keychain_value_iter(d, key_chain=None, allowed_values=None):
key_chain = [] if key_chain is None else list(key_chain).copy()
if not isinstance(d, dict):
if allowed_values is not None:
assert isinstance(d, allowed_values), 'Value needs to be of type {}!'.format(
allowed_v... | def keychain_value_iter(d, key_chain=None, allowed_values=None):
key_chain = [] if key_chain is None else list(key_chain).copy()
if not isinstance(d, dict):
if allowed_values is not None:
assert isinstance(d, allowed_values), 'Value needs to be of type {}!'.format(allowed_values)
yie... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
def getstatus(code):
if code == "1000":
value = "Success!"
elif code == "1001":
value = "Unknown Message Received"
elif code == "1002":
value = "Connection to Fishbowl Server was lost"
elif code == "1003":
value = "Some Requests ... | def getstatus(code):
if code == '1000':
value = 'Success!'
elif code == '1001':
value = 'Unknown Message Received'
elif code == '1002':
value = 'Connection to Fishbowl Server was lost'
elif code == '1003':
value = "Some Requests had errors -- now isn't that helpful..."
... |
# -*- coding: utf-8 -*-
"""This sub module provides a global variable to check for checking if the non-interactive argument was set
Exported variable:
interactive -- False, if the main the non-interactive argument was set, True, if it was not set
"""
global interactive
interactive = True; | """This sub module provides a global variable to check for checking if the non-interactive argument was set
Exported variable:
interactive -- False, if the main the non-interactive argument was set, True, if it was not set
"""
global interactive
interactive = True |
ans = dict()
pairs = dict()
def create_tree(p):
if p in ans:
return ans[p]
else:
try:
res = 0
if p in pairs:
for ch in pairs[p]:
res += create_tree(ch) + 1
ans[p] = res
return res
except:
pass... | ans = dict()
pairs = dict()
def create_tree(p):
if p in ans:
return ans[p]
else:
try:
res = 0
if p in pairs:
for ch in pairs[p]:
res += create_tree(ch) + 1
ans[p] = res
return res
except:
pas... |
def italicize(s):
b = False
res = ''
for e in s:
if e == '"':
if b:
res += '{\\i}' + e
else:
res += e + '{i}'
b=not b
else:
res += e
return res
def main():
F=open('test_in.txt','r')
X=F.read()
F... | def italicize(s):
b = False
res = ''
for e in s:
if e == '"':
if b:
res += '{\\i}' + e
else:
res += e + '{i}'
b = not b
else:
res += e
return res
def main():
f = open('test_in.txt', 'r')
x = F.read()... |
#!venv/bin/python3
cs = [int(c) for c in open("inputs/23.in", "r").readline().strip()]
def f(cs, ts):
p,cc = {n: cs[(i+1)%len(cs)] for i,n in enumerate(cs)},cs[-1]
for _ in range(ts):
cc,dc = p[cc],p[cc]-1 if p[cc]-1 > 0 else max(p.keys())
hc,p[cc] = [p[cc], p[p[cc]], p[p[p[cc]]]],p[p[p[p[cc]]... | cs = [int(c) for c in open('inputs/23.in', 'r').readline().strip()]
def f(cs, ts):
(p, cc) = ({n: cs[(i + 1) % len(cs)] for (i, n) in enumerate(cs)}, cs[-1])
for _ in range(ts):
(cc, dc) = (p[cc], p[cc] - 1 if p[cc] - 1 > 0 else max(p.keys()))
(hc, p[cc]) = ([p[cc], p[p[cc]], p[p[p[cc]]]], p[p[... |
entrada = input("palabra")
listaDeLetras = []
for i in entrada:
listaDeLetras.append(i)
| entrada = input('palabra')
lista_de_letras = []
for i in entrada:
listaDeLetras.append(i) |
class Machine():
def __init__(self):
self.pointer = 0
self.accum = 0
self.visited = []
def run(self,program):
salir = False
while (salir == False):
if (self.pointer in self.visited):
return False
if (self.pointer >= len(progr... | class Machine:
def __init__(self):
self.pointer = 0
self.accum = 0
self.visited = []
def run(self, program):
salir = False
while salir == False:
if self.pointer in self.visited:
return False
if self.pointer >= len(program):
... |
"""
Round a number
--------------
Input (float) A floating point number
(int) Number of decimals
Default value is: 0
Output (float) Rounded number
(int) Whether using the default decimals value, the return number
will be the nearest ... | """
Round a number
--------------
Input (float) A floating point number
(int) Number of decimals
Default value is: 0
Output (float) Rounded number
(int) Whether using the default decimals value, the return number
will be the nearest integer
... |
class PayabbhiError(Exception):
def __init__(self, description=None, http_status=None,
field=None):
self.description = description
self.http_status = http_status
self.field = field
self._message = self.error_message()
super(PayabbhiError, self).__init__(self... | class Payabbhierror(Exception):
def __init__(self, description=None, http_status=None, field=None):
self.description = description
self.http_status = http_status
self.field = field
self._message = self.error_message()
super(PayabbhiError, self).__init__(self._message)
d... |
class OrderedStream:
def __init__(self, n: int):
self.data = [None]*n
self.ptr = 0
def insert(self, id: int, value: str) -> List[str]:
id -= 1
self.data[id] = value
if id > self.ptr: return []
while self.ptr < len(self.data) and self.data[self.ptr]: ... | class Orderedstream:
def __init__(self, n: int):
self.data = [None] * n
self.ptr = 0
def insert(self, id: int, value: str) -> List[str]:
id -= 1
self.data[id] = value
if id > self.ptr:
return []
while self.ptr < len(self.data) and self.data[self.ptr]... |
"""
The constants used in FLV files and their meanings.
"""
# Tag type
(TAG_TYPE_AUDIO, TAG_TYPE_VIDEO, TAG_TYPE_SCRIPT) = (8, 9, 18)
# Sound format
(SOUND_FORMAT_PCM_PLATFORM_ENDIAN,
SOUND_FORMAT_ADPCM,
SOUND_FORMAT_MP3,
SOUND_FORMAT_PCM_LITTLE_ENDIAN,
SOUND_FORMAT_NELLYMOSER_16KHZ,
SOUND_FORMAT_NELLYMOSER_8KH... | """
The constants used in FLV files and their meanings.
"""
(tag_type_audio, tag_type_video, tag_type_script) = (8, 9, 18)
(sound_format_pcm_platform_endian, sound_format_adpcm, sound_format_mp3, sound_format_pcm_little_endian, sound_format_nellymoser_16_khz, sound_format_nellymoser_8_khz, sound_format_nellymoser, soun... |
# convert2.py
# A program to convert Celsius temps to Fahrenheit.
# This version issues heat and cold warnings.
def main():
celsius = float(input("What is the Celsius temperature? "))
fahrenheit = 9 / 5 * celsius + 32
print("The temperature is", fahrenheit, "degrees fahrenheit.")
if fahrenhei... | def main():
celsius = float(input('What is the Celsius temperature? '))
fahrenheit = 9 / 5 * celsius + 32
print('The temperature is', fahrenheit, 'degrees fahrenheit.')
if fahrenheit >= 90:
print("It's really hot out there, be careful!")
if fahrenheit <= 30:
print('Brrrrr. Be sure to... |
class LevenshteinDistance:
def solve(self, str_a, str_b):
a, b = str_a, str_b
dist = {(x,y):0 for x in range(len(a)) for y in range(len(b))}
for x in range(len(a)): dist[(x,-1)] = x+1
for y in range(len(b)): dist[(-1,y)] = y+1
dist[(-1,-1)] = 0
for i in range(len(a)):... | class Levenshteindistance:
def solve(self, str_a, str_b):
(a, b) = (str_a, str_b)
dist = {(x, y): 0 for x in range(len(a)) for y in range(len(b))}
for x in range(len(a)):
dist[x, -1] = x + 1
for y in range(len(b)):
dist[-1, y] = y + 1
dist[-1, -1] = 0... |
# -*- coding: utf-8 -*-
BROKER_URL = 'amqp://guest@localhost//'
CELERY_ACCEPT_CONTENT = ['json'],
CELERY_RESULT_BACKEND = 'amqp://guest@localhost//'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TASK_SERIALIZER = 'json'
CELERY_TIMEZONE = 'Asia/Shanghai'
CELERY_ENABLE_UTC = False
| broker_url = 'amqp://guest@localhost//'
celery_accept_content = (['json'],)
celery_result_backend = 'amqp://guest@localhost//'
celery_result_serializer = 'json'
celery_task_serializer = 'json'
celery_timezone = 'Asia/Shanghai'
celery_enable_utc = False |
def structural_loss_dst68j3d(p_pred, v_pred):
v_pred = K.stop_gradient(v_pred)
def getlength(v):
return K.sqrt(K.sum(K.square(v), axis=-1))
"""Arms segments"""
joints_arms = p_pred[:, :, 16:37+1, :]
conf_arms = v_pred[:, :, 16:37+1]
diff_arms_r = joints_arms[:, :, 2:-1:2, :] - joint... | def structural_loss_dst68j3d(p_pred, v_pred):
v_pred = K.stop_gradient(v_pred)
def getlength(v):
return K.sqrt(K.sum(K.square(v), axis=-1))
'Arms segments'
joints_arms = p_pred[:, :, 16:37 + 1, :]
conf_arms = v_pred[:, :, 16:37 + 1]
diff_arms_r = joints_arms[:, :, 2:-1:2, :] - joints_ar... |
'''
Created on 2011-6-22
@author: dholer
'''
| """
Created on 2011-6-22
@author: dholer
""" |
"""Tests for the `sendoff` library."""
"""
The `sendoff` library tests validate the expected function of the library.
"""
| """Tests for the `sendoff` library."""
'\nThe `sendoff` library tests validate the expected function of the library.\n' |
total = 0
for n in range(1000, 1000000):
suma = 0
for i in str(n):
suma += int(i)**5
if (n == suma):
total += n
print(total) | total = 0
for n in range(1000, 1000000):
suma = 0
for i in str(n):
suma += int(i) ** 5
if n == suma:
total += n
print(total) |
class Solution:
@staticmethod
def naive(board,word):
rows,cols,n = len(board),len(board[0]),len(word)
visited = set()
def dfs(i,j,k):
idf = str(i)+','+str(j)
if i<0 or j<0 or i>cols-1 or j>rows-1 or \
board[j][i]!=word[k] or idf in visited:
... | class Solution:
@staticmethod
def naive(board, word):
(rows, cols, n) = (len(board), len(board[0]), len(word))
visited = set()
def dfs(i, j, k):
idf = str(i) + ',' + str(j)
if i < 0 or j < 0 or i > cols - 1 or (j > rows - 1) or (board[j][i] != word[k]) or (idf i... |
# ----------------------------------------------------------------------
# CISCO-VLAN-MEMBERSHIP-MIB
# Compiled MIB
# Do not modify this file directly
# Run ./noc mib make-cmib instead
# ----------------------------------------------------------------------
# Copyright (C) 2007-2020 The NOC Project
# See LICENSE for de... | name = 'CISCO-VLAN-MEMBERSHIP-MIB'
last_updated = '2007-12-14'
compiled = '2020-01-19'
mib = {'CISCO-VLAN-MEMBERSHIP-MIB::ciscoVlanMembershipMIB': '1.3.6.1.4.1.9.9.68', 'CISCO-VLAN-MEMBERSHIP-MIB::ciscoVlanMembershipMIBObjects': '1.3.6.1.4.1.9.9.68.1', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVmps': '1.3.6.1.4.1.9.9.68.1.1', 'CIS... |
# module for adapting templates on the fly if components are reused
# check that all reused components are defined consistently -> else: exception
def check_consistency(components):
for j1 in components:
for j2 in components: # compare all components
if j1 == j2 and j1.__dict__ != j2.__dict__: # same n... | def check_consistency(components):
for j1 in components:
for j2 in components:
if j1 == j2 and j1.__dict__ != j2.__dict__:
raise value_error('Inconsistent definition of reused component {}.'.format(j1))
def reuses(component, arcs):
times = set()
for k in range(component.... |
"""Declare runtime dependencies
These are needed for local dev, and users must install them as well.
See https://docs.bazel.build/versions/main/skylark/deploying.html#dependencies
"""
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
#... | """Declare runtime dependencies
These are needed for local dev, and users must install them as well.
See https://docs.bazel.build/versions/main/skylark/deploying.html#dependencies
"""
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
load('@bazel_tools//tools/build_defs/repo:utils.bzl', 'maybe')
de... |
def findDecision(obj): #obj[0]: Passanger, obj[1]: Time, obj[2]: Coupon, obj[3]: Gender, obj[4]: Age, obj[5]: Education, obj[6]: Occupation, obj[7]: Bar, obj[8]: Coffeehouse, obj[9]: Restaurant20to50, obj[10]: Direction_same, obj[11]: Distance
# {"feature": "Age", "instances": 51, "metric_value": 0.9662, "depth": 1}
... | def find_decision(obj):
if obj[4] > 0:
if obj[6] > 1:
if obj[7] <= 1.0:
if obj[5] > 0:
if obj[0] <= 2:
if obj[1] <= 2:
if obj[9] > 0.0:
if obj[8] <= 2.0:
... |
"""
A simple python module for converting kilometers to miles or vice versa.
So simple that it doesn't even have any dependencies.
"""
def kilometers_to_miles(dist_in_km):
"""
Actually does the conversion of distance from km to mi.
PARAMETERS
--------
dist_in_km: float
A distance in kilometers.
RETURNS
-... | """
A simple python module for converting kilometers to miles or vice versa.
So simple that it doesn't even have any dependencies.
"""
def kilometers_to_miles(dist_in_km):
"""
Actually does the conversion of distance from km to mi.
PARAMETERS
--------
dist_in_km: float
A distance in kilometers.
RETURNS ... |
# -*- coding: utf-8 -*-
PIXIVUTIL_VERSION = '20191220-beta1'
PIXIVUTIL_LINK = 'https://github.com/Nandaka/PixivUtil2/releases'
PIXIVUTIL_DONATE = 'https://bit.ly/PixivUtilDonation'
# Log Settings
PIXIVUTIL_LOG_FILE = 'pixivutil.log'
PIXIVUTIL_LOG_SIZE = 10485760
PIXIVUTIL_LOG_COUNT = 10
PIXIVUTIL_LOG_FORMAT = "%(asct... | pixivutil_version = '20191220-beta1'
pixivutil_link = 'https://github.com/Nandaka/PixivUtil2/releases'
pixivutil_donate = 'https://bit.ly/PixivUtilDonation'
pixivutil_log_file = 'pixivutil.log'
pixivutil_log_size = 10485760
pixivutil_log_count = 10
pixivutil_log_format = '%(asctime)s - %(name)s - %(levelname)s - %(mess... |
'''
Created on 10/11/2017
@author: jschmid3@stevens.edu
Pledge: I pledge my honor that I have abided by the Stevens Honor System -Joshua Schmidt
CS115 - Lab 6
'''
def isOdd(n):
'''Returns whether or not the integer argument is odd.'''
#question 1: base_2 of 42: 101010
if n == 0:
return False
... | """
Created on 10/11/2017
@author: jschmid3@stevens.edu
Pledge: I pledge my honor that I have abided by the Stevens Honor System -Joshua Schmidt
CS115 - Lab 6
"""
def is_odd(n):
"""Returns whether or not the integer argument is odd."""
if n == 0:
return False
if n % 2 != 0:
return Tru... |
class Solution:
def destCity(self, paths: List[List[str]]) -> str:
bads = set()
cities = set()
for u, v in paths:
cities.add(u)
cities.add(v)
bads.add(u)
ans = cities - bads
return list(ans)[0]
| class Solution:
def dest_city(self, paths: List[List[str]]) -> str:
bads = set()
cities = set()
for (u, v) in paths:
cities.add(u)
cities.add(v)
bads.add(u)
ans = cities - bads
return list(ans)[0] |
#!/usr/bin/env python3
# The format of your own localizable method.
# This is an example of '"string".localized'
SUFFIX = '.localized'
KEY = r'"(?:\\.|[^"\\])*"'
LOCALIZABLE_RE = r'%s%s' % (KEY, SUFFIX)
# Specify the path of localizable files in project.
LOCALIZABLE_FILE_PATH = ''
LOCALIZABLE_FILE_NAMES = ['Localizab... | suffix = '.localized'
key = '"(?:\\\\.|[^"\\\\])*"'
localizable_re = '%s%s' % (KEY, SUFFIX)
localizable_file_path = ''
localizable_file_names = ['Localizable']
localizable_file_types = ['strings']
search_types = ['swift', 'm', 'json']
source_file_exclusive_paths = ['Assets.xcassets', 'Carthage', 'ThirdParty', 'Pods', '... |
def longest_common_prefix(s1: str, s2: str) -> str:
"""
Finds the longest common prefix (substring) given two strings
s1: First string to compare
s2: Second string to compare
Returns:
Longest common prefix between s1 and s2
>>> longest_common_prefix("ACTA", "GCCT")
''
>>> long... | def longest_common_prefix(s1: str, s2: str) -> str:
"""
Finds the longest common prefix (substring) given two strings
s1: First string to compare
s2: Second string to compare
Returns:
Longest common prefix between s1 and s2
>>> longest_common_prefix("ACTA", "GCCT")
''
>>> long... |
def task_pos_args():
def show_params(param1, pos):
print('param1 is: {0}'.format(param1))
for index, pos_arg in enumerate(pos):
print('positional-{0}: {1}'.format(index, pos_arg))
return {'actions':[(show_params,)],
'params':[{'name':'param1',
'shor... | def task_pos_args():
def show_params(param1, pos):
print('param1 is: {0}'.format(param1))
for (index, pos_arg) in enumerate(pos):
print('positional-{0}: {1}'.format(index, pos_arg))
return {'actions': [(show_params,)], 'params': [{'name': 'param1', 'short': 'p', 'default': 'default ... |
# Lets create a linked list that has the following elements
'''
1. FE
2. SE
3. TE
4. BE
'''
# Creating a Node class to create individual Nodes
class Node:
def __init__(self,data):
self.__data = data
self.__next = None
def get_data(self):
return self.__data
... | """
1. FE
2. SE
3. TE
4. BE
"""
class Node:
def __init__(self, data):
self.__data = data
self.__next = None
def get_data(self):
return self.__data
def set_data(self, data):
self.__data = data
def get_next(self):
return self.__next
def set_next(self, next... |
ten_things = "Apples Oranges cows Telephone Light Sugar"
print ("Wait there are not 10 things in that list. Let's fix")
stuff = ten_things.split(' ')
more_stuff = {"Day", "Night", "Song", "Firebee",
"Corn", "Banana", "Girl", "Boy"}
while len(stuff) !=10:
next_one = more_stuff.pop()
print("Adding: ", next_one)
... | ten_things = 'Apples Oranges cows Telephone Light Sugar'
print("Wait there are not 10 things in that list. Let's fix")
stuff = ten_things.split(' ')
more_stuff = {'Day', 'Night', 'Song', 'Firebee', 'Corn', 'Banana', 'Girl', 'Boy'}
while len(stuff) != 10:
next_one = more_stuff.pop()
print('Adding: ', next_one)
... |
"""
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
For C programmers: Try to solve it in-place in O(1) space.
Clarification:
* What constitutes a word?
A sequence of non-space characters constitutes a word.
* Could the inp... | """
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
For C programmers: Try to solve it in-place in O(1) space.
Clarification:
* What constitutes a word?
A sequence of non-space characters constitutes a word.
* Could the input string con... |
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | """Python equivalent of jdbc_type.h.
Python definition of the JDBC type constant values defined in Java class
java.sql.Types. Since the values don't fall into the range allowed by
a protocol buffer enum, we use Python constants instead.
If you update this, update jdbc_type.py also.
"""
bit = -7
tinyint = -6
smallint... |
_base_ = './pspnet_r50-d8_512x512_80k_loveda.py'
model = dict(
backbone=dict(
depth=18,
init_cfg=dict(
type='Pretrained', checkpoint='open-mmlab://resnet18_v1c')),
decode_head=dict(
in_channels=512,
channels=128,
),
auxiliary_head=dict(in_channels=256, channel... | _base_ = './pspnet_r50-d8_512x512_80k_loveda.py'
model = dict(backbone=dict(depth=18, init_cfg=dict(type='Pretrained', checkpoint='open-mmlab://resnet18_v1c')), decode_head=dict(in_channels=512, channels=128), auxiliary_head=dict(in_channels=256, channels=64)) |
# Easy
# https://leetcode.com/problems/palindrome-number/
# Time Complexity: O(log(x) to base 10)
# Space Complexity: O(1)
class Solution:
def isPalindrome(self, x: int) -> bool:
temp = x
rev = 0
while temp > 0:
rev = rev * 10 + temp % 10
temp //= 10
return re... | class Solution:
def is_palindrome(self, x: int) -> bool:
temp = x
rev = 0
while temp > 0:
rev = rev * 10 + temp % 10
temp //= 10
return rev == x |
"""Constants about the Gro ontology that can be imported and re-used anywhere."""
REGION_LEVELS = {
'world': 1,
'continent': 2,
'country': 3,
'province': 4, # Equivalent to state in the United States
'district': 5, # Equivalent to county in the United States
'city': 6,
'market': 7,
'o... | """Constants about the Gro ontology that can be imported and re-used anywhere."""
region_levels = {'world': 1, 'continent': 2, 'country': 3, 'province': 4, 'district': 5, 'city': 6, 'market': 7, 'other': 8, 'coordinate': 9}
entity_types_plural = ['metrics', 'items', 'regions', 'frequencies', 'sources', 'units']
data_se... |
# Use zip() to create a new variable called names_and_dogs_names that combines owners and dogs_names lists into a zip object.
# Then, create a new variable named list_of_names_and_dogs_names by calling the list() function on names_and_dogs_names.
# Print list_of_names_and_dogs_names.
owners = ["Jenny", "Alexus", "Sa... | owners = ['Jenny', 'Alexus', 'Sam', 'Grace']
dogs_names = ['Elphonse', 'Dr. Doggy DDS', 'Carter', 'Ralph']
names_and_dogs_names = zip(owners, dogs_names)
list_of_names_and_dogs_names = list(names_and_dogs_names)
print(list_of_names_and_dogs_names) |
# -*- coding: utf-8 -*-
def ordered_set(iter):
"""Creates an ordered set
@param iter: list or tuple
@return: list with unique values
"""
final = []
for i in iter:
if i not in final:
final.append(i)
return final
def class_slots(ob):
"""Get object attributes from... | def ordered_set(iter):
"""Creates an ordered set
@param iter: list or tuple
@return: list with unique values
"""
final = []
for i in iter:
if i not in final:
final.append(i)
return final
def class_slots(ob):
"""Get object attributes from child class attributes
... |
class RegipyException(Exception):
"""
This is the parent exception for all regipy exceptions
"""
pass
class RegipyGeneralException(RegipyException):
"""
General exception
"""
pass
class RegistryValueNotFoundException(RegipyException):
pass
class NoRegistrySubkeysException(Regipy... | class Regipyexception(Exception):
"""
This is the parent exception for all regipy exceptions
"""
pass
class Regipygeneralexception(RegipyException):
"""
General exception
"""
pass
class Registryvaluenotfoundexception(RegipyException):
pass
class Noregistrysubkeysexception(RegipyEx... |
def _replace_formatted(ctx, manifest, files):
out = ctx.actions.declare_file(ctx.label.name)
# this makes it easier to add variables
file_lines = [
"""#!/bin/bash -e
WORKSPACE_ROOT="${1:-$BUILD_WORKSPACE_DIRECTORY}" """,
"""RUNPATH="${TEST_SRCDIR-$0.runfiles}"/""" + ctx.workspace_name,
... | def _replace_formatted(ctx, manifest, files):
out = ctx.actions.declare_file(ctx.label.name)
file_lines = ['#!/bin/bash -e\nWORKSPACE_ROOT="${1:-$BUILD_WORKSPACE_DIRECTORY}" ', 'RUNPATH="${TEST_SRCDIR-$0.runfiles}"/' + ctx.workspace_name, 'RUNPATH=(${RUNPATH//bin/ })\nRUNPATH="${RUNPATH[0]}"bin\necho $WORKSPACE... |
r, c, m = map(int, input().split())
n = int(input())
op = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(n)]
board = [[0 for _ in range(c)] for _ in range(r)]
for ra, rb, ca, cb in op:
for j in range(ra, rb + 1):
for k in range(ca, cb + 1):
board[j][k] += 1
cnt = 0
for i in ra... | (r, c, m) = map(int, input().split())
n = int(input())
op = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(n)]
board = [[0 for _ in range(c)] for _ in range(r)]
for (ra, rb, ca, cb) in op:
for j in range(ra, rb + 1):
for k in range(ca, cb + 1):
board[j][k] += 1
cnt = 0
for i in... |
"""Drop-in replacement for collections.OrderedDict by Raymond Hettinger
http://code.activestate.com/recipes/576693/
"""
try:
all
except NameError:
def all(seq):
for elem in seq:
if not elem:
return False
return True
class OrderedDict(dict, DictMixin):
def __init__(self, *args, **kwds):
if len(args) > 1:... | """Drop-in replacement for collections.OrderedDict by Raymond Hettinger
http://code.activestate.com/recipes/576693/
"""
try:
all
except NameError:
def all(seq):
for elem in seq:
if not elem:
return False
return True
class Ordereddict(dict, DictMixin):
def __ini... |
# Convert a Number to a String!
# We need a function that can transform a number into a string.
# What ways of achieving this do you know?
def number_to_string(num: int) -> str:
str_num = str(num)
return str_num
print(number_to_string(123))
print(type(number_to_string(123))) | def number_to_string(num: int) -> str:
str_num = str(num)
return str_num
print(number_to_string(123))
print(type(number_to_string(123))) |
floatVar = 1.0
listVar = [3, "hello"]
dictVar = {
"myField": "value"
}
aotVar = [dictVar, dictVar]
intVar = 1 | float_var = 1.0
list_var = [3, 'hello']
dict_var = {'myField': 'value'}
aot_var = [dictVar, dictVar]
int_var = 1 |
# Python3 program to print
# given matrix in spiral form
def spiralPrint(m, n, a):
start_row_index = 0
start_col_index = 0
l = 0
''' start_row_index - starting row index
m - ending row index
start_col_index - starting column index
n - ending column index
i - iterator '''
while (start... | def spiral_print(m, n, a):
start_row_index = 0
start_col_index = 0
l = 0
' start_row_index - starting row index \n\t\tm - ending row index \n\t\tstart_col_index - starting column index \n\t\tn - ending column index \n\t\ti - iterator '
while start_row_index < m and start_col_index < n:
for i... |
"""
********************************************************************************
compas_blender.forms
********************************************************************************
.. currentmodule:: compas_blender.forms
"""
__all__ = []
| """
********************************************************************************
compas_blender.forms
********************************************************************************
.. currentmodule:: compas_blender.forms
"""
__all__ = [] |
# configs for the model training
class model_training_configs:
VALIDATION_ERRORS_DIRECTORY = 'results/validation_errors/'
INFO_FREQ = 1
# configs for the model testing
class model_testing_configs:
RNN_FORECASTS_DIRECTORY = 'results/rnn_forecasts/'
RNN_ERRORS_DIRECTORY = 'results/errors'
PROCESSED_R... | class Model_Training_Configs:
validation_errors_directory = 'results/validation_errors/'
info_freq = 1
class Model_Testing_Configs:
rnn_forecasts_directory = 'results/rnn_forecasts/'
rnn_errors_directory = 'results/errors'
processed_rnn_forecasts_directory = '/results/processed_rnn_forecasts/'
cla... |
name = "cluster"
num_cores = 1000
GENERAL_PARTITIONS = ["regular"]
GPU_PARTITIONS = ["gpu"]
PARTITIONS = GENERAL_PARTITIONS + GPU_PARTITIONS
ACTIVE_JOB_STATES = ["RUNNING", "COMPLETING"]
FINISHED_JOB_STATES = ["COMPLETED", "NODE_FAIL", "TIMEOUT", "FAILED", "CANCELLED"]
JOB_STATES = ACTIVE_JOB_STATES + FINISHED_JOB_... | name = 'cluster'
num_cores = 1000
general_partitions = ['regular']
gpu_partitions = ['gpu']
partitions = GENERAL_PARTITIONS + GPU_PARTITIONS
active_job_states = ['RUNNING', 'COMPLETING']
finished_job_states = ['COMPLETED', 'NODE_FAIL', 'TIMEOUT', 'FAILED', 'CANCELLED']
job_states = ACTIVE_JOB_STATES + FINISHED_JOB_STAT... |
workdays = float(input())
daily_tips = float(input())
exchange_rate = float(input())
salary = workdays * daily_tips
annual_income = salary * 12 + salary * 2.5
net_income = annual_income - annual_income * 25 / 100
result = net_income / 365 * exchange_rate
print('%.2f' % result)
| workdays = float(input())
daily_tips = float(input())
exchange_rate = float(input())
salary = workdays * daily_tips
annual_income = salary * 12 + salary * 2.5
net_income = annual_income - annual_income * 25 / 100
result = net_income / 365 * exchange_rate
print('%.2f' % result) |
def main():
# Pass a string to show_mammal_info...
show_mammal_info('I am a string')
# The show_mammal_info function accepts an object
# as an argument, and calls its show_species
# and make_sound methods.
def show_mammal_info(creature):
creature.show_species()
creature.make_sound()
# Call th... | def main():
show_mammal_info('I am a string')
def show_mammal_info(creature):
creature.show_species()
creature.make_sound()
main() |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 21 08:09:31 2020
@author: Shivadhar SIngh
"""
def count_capitals(string):
count = 0
for ch in string:
if ord(ch) >= 65 and ord(ch) <= 90:
count += 1
return count
def remove_substring_everywhere(string, substring):
'''
Remove all o... | """
Created on Tue Apr 21 08:09:31 2020
@author: Shivadhar SIngh
"""
def count_capitals(string):
count = 0
for ch in string:
if ord(ch) >= 65 and ord(ch) <= 90:
count += 1
return count
def remove_substring_everywhere(string, substring):
"""
Remove all occurrences of substring ... |
COLOR_BLUE = '\033[0;34m'
COLOR_GREEN = '\033[0;32m'
COLOR_CYAN = '\033[0;36m'
COLOR_RED = '\033[0;31m'
COLOR_PURPLE = '\033[0;35m'
COLOR_BROWN = '\033[0;33m'
COLOR_YELLOW = '\033[1;33m'
COLOR_GRAY = '\033[1;30m'
COLOR_RESET = '\033[0m'
FG_COLORS = [
# COLOR_BLUE,
COLOR_GREEN,
# COLOR_CYAN,
# COLOR_R... | color_blue = '\x1b[0;34m'
color_green = '\x1b[0;32m'
color_cyan = '\x1b[0;36m'
color_red = '\x1b[0;31m'
color_purple = '\x1b[0;35m'
color_brown = '\x1b[0;33m'
color_yellow = '\x1b[1;33m'
color_gray = '\x1b[1;30m'
color_reset = '\x1b[0m'
fg_colors = [COLOR_GREEN]
def next_color(color):
assert color in FG_COLORS
... |
class Hey:
def __init__(jose, name="mours"):
jose.name = name
def get_name(jose):
return jose.name
class Person(object):
def __init__(self, name, phone):
self.name = name
self.phone = phone
class Teenager(Person):
def __init__(self, *args, **kwargs):
self.website... | class Hey:
def __init__(jose, name='mours'):
jose.name = name
def get_name(jose):
return jose.name
class Person(object):
def __init__(self, name, phone):
self.name = name
self.phone = phone
class Teenager(Person):
def __init__(self, *args, **kwargs):
self.we... |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""IIIF API for Invenio."""
IIIF_API_PREFIX = '/iiif/'
"""URL prefix to IIIF API."""
III... | """IIIF API for Invenio."""
iiif_api_prefix = '/iiif/'
'URL prefix to IIIF API.'
iiif_ui_url = '/api{}'.format(IIIF_API_PREFIX)
'URL to IIIF API endpoint (allow hostname).'
iiif_previewer_params = {'size': '750,'}
'Parameters for IIIF image previewer extension.'
iiif_preview_template = 'invenio_iiif/preview.html'
'Temp... |
def sysrc(value):
"""Call sysrc.
CLI Example:
.. code-block:: bash
salt '*' freebsd_common.sysrc sshd_enable=YES
salt '*' freebsd_common.sysrc static_routes
"""
return __salt__['cmd.run_all']("sysrc %s" % value)
| def sysrc(value):
"""Call sysrc.
CLI Example:
.. code-block:: bash
salt '*' freebsd_common.sysrc sshd_enable=YES
salt '*' freebsd_common.sysrc static_routes
"""
return __salt__['cmd.run_all']('sysrc %s' % value) |
# Autor: Anuj Sharma (@optider)
# Github Profile: https://github.com/Optider/
# Problem Link: https://leetcode.com/problems/contains-duplicate/
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
count = {}
for n in nums :
if count.get(n) != None :
ret... | class Solution:
def contains_duplicate(self, nums: List[int]) -> bool:
count = {}
for n in nums:
if count.get(n) != None:
return True
count[n] = 1
return False |
{
'target_defaults': {
'win_delay_load_hook': 'false',
'conditions': [
['OS=="win"', {
'msvs_disabled_warnings': [
4530, # C++ exception handler used, but unwind semantics are not enabled
4506, # no definition for inline function
],
}],
],
},
'targets'... | {'target_defaults': {'win_delay_load_hook': 'false', 'conditions': [['OS=="win"', {'msvs_disabled_warnings': [4530, 4506]}]]}, 'targets': [{'target_name': 'fs_admin', 'defines': ['NAPI_VERSION=<(napi_build_version)'], 'cflags!': ['-fno-exceptions'], 'cflags_cc!': ['-fno-exceptions'], 'xcode_settings': {'GCC_ENABLE_CPP_... |
DEBUG = True
USE_TZ = True
SECRET_KEY = "dummy"
DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}}
INSTALLED_APPS = [
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sites",
"rest_framework",
"django_filters",
"belt",
"tests.app",
]... | debug = True
use_tz = True
secret_key = 'dummy'
databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}}
installed_apps = ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sites', 'rest_framework', 'django_filters', 'belt', 'tests.app']
site_id = 1
root_urlconf = 'tests... |
#!/usr/bin/env python
''' This module provides configuration options for OS project. No more magic numbers! '''
BLOCK_SIZE = 16 # words
WORD_SIZE = 4 # bytes
# length od RS in blocks
RESTRICTED_LENGTH = 1
# length of DS in blocks
DS_LENGTH = 6
# timer value
TIMER_VALUE = 10
# buffer size
BUFFER_SIZE = 16
# num... | """ This module provides configuration options for OS project. No more magic numbers! """
block_size = 16
word_size = 4
restricted_length = 1
ds_length = 6
timer_value = 10
buffer_size = 16
hd_blocks_size = 500
root_priority = 40
vm_priority = 50
loader_priority = 60
interrupt_priority = 70
print_priority = 70
running_... |
class Solution:
def jump(self, nums: List[int]) -> int:
n = len(nums)
dp = [float('inf')] * n
dp[0] = 0
tail = 1
for i in range(n):
limit = min(n, i + nums[i] + 1)
for j in range(tail, limit):
dp[j] = min(dp[j], dp[i] + 1)
... | class Solution:
def jump(self, nums: List[int]) -> int:
n = len(nums)
dp = [float('inf')] * n
dp[0] = 0
tail = 1
for i in range(n):
limit = min(n, i + nums[i] + 1)
for j in range(tail, limit):
dp[j] = min(dp[j], dp[i] + 1)
... |
class Solution:
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
if not height:
return 0
left = 0
right = len(height)-1
total_area = 0
if height[left] <= height[right]:
m = left
else:
m =right
while(left < right):
if height[left] <= height[right]:
# move m... | class Solution:
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
if not height:
return 0
left = 0
right = len(height) - 1
total_area = 0
if height[left] <= height[right]:
m = left
else:
m = right
... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
load("//antlir/bzl:maybe_export_file.bzl", "maybe_export_file")
load("//antlir/bzl:shape.bzl", "shape")
load(
"//antlir/bzl:target_tagger.... | load('//antlir/bzl:maybe_export_file.bzl', 'maybe_export_file')
load('//antlir/bzl:shape.bzl', 'shape')
load('//antlir/bzl:target_tagger.bzl', 'image_source_as_target_tagged_shape', 'new_target_tagger', 'target_tagged_image_source_shape', 'target_tagger_to_feature')
tarball_t = shape.shape(force_root_ownership=shape.fi... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 3 19:02:33 2019
@author: sercangul
"""
def maxConsecutiveOnes(x):
# Initialize result
count = 0
# Count the number of iterations to
# reach x = 0.
while (x!=0):
# This operation reduces length
... | """
Created on Mon Jun 3 19:02:33 2019
@author: sercangul
"""
def max_consecutive_ones(x):
count = 0
while x != 0:
x = x & x << 1
count = count + 1
return count
if __name__ == '__main__':
n = int(input())
result = max_consecutive_ones(n)
print(result) |
#! /usr/bin/python3
# Description: Data_Ghost, concealing data into spaces and tabs making it imperceptable to human eyes.
# Author: Ajay Dyavathi
# Github: Radical Ajay
class Ghost():
def __init__(self, file_name, output_format='txt'):
''' Converts ascii text to spaces and tabs '''
self.file_name... | class Ghost:
def __init__(self, file_name, output_format='txt'):
""" Converts ascii text to spaces and tabs """
self.file_name = file_name
self.output_format = output_format
def ascii2bin(self, asc):
""" Converting ascii to bianry """
return ''.join(('{:08b}'.format(ord... |
class Solution:
def defangIPaddr(self, address: str) -> str:
i=0
j=0
strlist=list(address)
defang=[]
while i< len(strlist):
if strlist[i] == '.':
defang.append('[')
defang.append('.')
defang.append(']')
... | class Solution:
def defang_i_paddr(self, address: str) -> str:
i = 0
j = 0
strlist = list(address)
defang = []
while i < len(strlist):
if strlist[i] == '.':
defang.append('[')
defang.append('.')
defang.append(']')
... |
class Node:
def __init__(self, path, libgraphql_type, location, name):
self.path = path
self.parent = None
self.children = []
self.libgraphql_type = libgraphql_type
self.location = location
self.name = name
def __repr__(self):
return "%s(%s)" % (self.libg... | class Node:
def __init__(self, path, libgraphql_type, location, name):
self.path = path
self.parent = None
self.children = []
self.libgraphql_type = libgraphql_type
self.location = location
self.name = name
def __repr__(self):
return '%s(%s)' % (self.lib... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.