content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# -*- coding: utf-8 -*-
"""
meraki
This file was automatically generated for meraki by APIMATIC v2.0 ( https://apimatic.io ).
"""
class EncryptionModeEnum(object):
"""Implementation of the 'EncryptionMode' enum.
The psk encryption mode for the SSID ('wpa', 'wep' or 'wpa-eap')
Att... | """
meraki
This file was automatically generated for meraki by APIMATIC v2.0 ( https://apimatic.io ).
"""
class Encryptionmodeenum(object):
"""Implementation of the 'EncryptionMode' enum.
The psk encryption mode for the SSID ('wpa', 'wep' or 'wpa-eap')
Attributes:
WPA: TODO: type descrip... |
class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
n = len(nums)
candidates = [x for x in range(1,n+1)]
for num in nums:
if candidates[num-1] == num:
candidates[num-1] = 0
else:
candidates[num-1] = num*2
cur... | class Solution:
def find_duplicates(self, nums: List[int]) -> List[int]:
n = len(nums)
candidates = [x for x in range(1, n + 1)]
for num in nums:
if candidates[num - 1] == num:
candidates[num - 1] = 0
else:
candidates[num - 1] = num * ... |
SCREEN_TITLE = "Arcade game"
SCREEN_WIDTH = 1280
SCREEN_HEIGHT = 960
CAMERA_WIDTH = 700
CAMERA_HEIGHT = 500
SPRITE_SCALING = 0.5
SPRITE_PIXEL_SIZE = 32
SPRITE_NATIVE_SIZE = 32
SPRITE_SIZE = int(SPRITE_NATIVE_SIZE * SPRITE_SCALING)
MAP_WIDTH = 120
MAP_HEIGHT = 100
# Movement speed of player, in pixels per frame and is... | screen_title = 'Arcade game'
screen_width = 1280
screen_height = 960
camera_width = 700
camera_height = 500
sprite_scaling = 0.5
sprite_pixel_size = 32
sprite_native_size = 32
sprite_size = int(SPRITE_NATIVE_SIZE * SPRITE_SCALING)
map_width = 120
map_height = 100
movement_speed = 75 |
def check_categories(session, categories_list):
if "diagnosis_previous_choices" in session.checker:
for category in categories_list:
if category in session.checker["diagnosis_previous_choices"]:
return True
return False
| def check_categories(session, categories_list):
if 'diagnosis_previous_choices' in session.checker:
for category in categories_list:
if category in session.checker['diagnosis_previous_choices']:
return True
return False |
#!/usr/bin/python
#
# Kazdy node oznacza pewien sp-graf.
# Liscie to pojedyncze krawedzie, type=edge.
# Node z type=series oznacza wynik polaczenia szeregowego.
# Node z type=parallel oznacza wynik polaczenia rownoleglego.
# Node z type=jackknife oznacza wynik operacji jackknife.
class Node:
"""The class defining ... | class Node:
"""The class defining a node."""
def __init__(self, source=None, target=None, type=None, left=None, right=None):
self.source = source
self.target = target
self.type = type
self.left = left
self.right = right
def __str__(self):
return "Node({0}, {... |
# Config file to guide the execution of the provided code
config = {
# Top level module
'module': 'network.train.Train',
# Output data location
'target_path': 'logs/plush',
'override': True,
# Randomness seed for reproducability
'seed': 0,
# Dataset options
'train_dataset_con... | config = {'module': 'network.train.Train', 'target_path': 'logs/plush', 'override': True, 'seed': 0, 'train_dataset_config': {'module': 'network.dataset.Dataset', 'data_loader_config': {'module': 'network.dataset.TFRecord', 'tfr_path': '/media/hendrik/Share/datasets/materials/patch/public/plush/tfr/train.tfr'}, 'pixel_... |
# 1. Union of 2 fuzzy sets
# Example to Demonstrate the Union of Two Fuzzy Sets
a = dict()
b = dict()
max_set = dict()
a = {"a": 1 , "b": .3 , "c": .5 , "d": 0.2 }
b = {"a": 0.5 , "b": 0.4 , "c": 0.1 , "d": 1}
print('The First Fuzzy Set is :', a)
print('The Second Fuzzy Set is :', b)
for i, j in zip(... | a = dict()
b = dict()
max_set = dict()
a = {'a': 1, 'b': 0.3, 'c': 0.5, 'd': 0.2}
b = {'a': 0.5, 'b': 0.4, 'c': 0.1, 'd': 1}
print('The First Fuzzy Set is :', a)
print('The Second Fuzzy Set is :', b)
for (i, j) in zip(a, b):
m = a[i]
n = b[j]
if m > n:
max_set[i] = m
else:
max_set[j] = n... |
# Copyright 2019 GreenWaves Technologies, SAS
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to i... | quote = lambda s: '"' + s + '"'
class Codeblock:
def __init__(self, starting_indent=0, indent_char=' '):
self._indent = starting_indent
self._indent_char = indent_char
self._lines = []
def indent(self):
self._indent += 1
return self
def deindent(self):
... |
{
"targets": [
{
"target_name": "zlib_sync",
"dependencies": [
"deps/binding.gyp:zlib",
],
"sources": [
"src/zlib_sync.cc",
],
"include_dirs": [
"<!(node -e \"require('nan')\")",
... | {'targets': [{'target_name': 'zlib_sync', 'dependencies': ['deps/binding.gyp:zlib'], 'sources': ['src/zlib_sync.cc'], 'include_dirs': ['<!(node -e "require(\'nan\')")'], 'xcode_settings': {'OTHER_CPLUSPLUSFLAGS': ['-fPIC', '-O3']}, 'cflags': ['-fPIC', '-O3']}]} |
""":mod:`asuka.urls` --- URL resolver
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
__all__ = 'commit', 'repository', 'service_config_file'
def repository(app):
"""GitHub repository."""
return app.repository.html_url
def commit(commit):
"""Commit changeset page."""
return repository(commit.app) + '/co... | """:mod:`asuka.urls` --- URL resolver
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
__all__ = ('commit', 'repository', 'service_config_file')
def repository(app):
"""GitHub repository."""
return app.repository.html_url
def commit(commit):
"""Commit changeset page."""
return repository(commit.app) + '/com... |
class DeviceTypes:
BITBOX02 = "bitbox02"
BITCOINCORE = "bitcoincore"
BITCOINCORE_WATCHONLY = "bitcoincore_watchonly"
COBO = "cobo"
COLDCARD = "coldcard"
ELECTRUM = "electrum"
ELEMENTSCORE = "elementscore"
GENERICDEVICE = "other"
JADE = "jade"
KEEPKEY = "keepkey"
LEDGER = "led... | class Devicetypes:
bitbox02 = 'bitbox02'
bitcoincore = 'bitcoincore'
bitcoincore_watchonly = 'bitcoincore_watchonly'
cobo = 'cobo'
coldcard = 'coldcard'
electrum = 'electrum'
elementscore = 'elementscore'
genericdevice = 'other'
jade = 'jade'
keepkey = 'keepkey'
ledger = 'led... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `opendata_cacem_dechets` package."""
def empty_test():
assert True
| """Tests for `opendata_cacem_dechets` package."""
def empty_test():
assert True |
class Student:
def hello(self, name=None, email=None):
if name is not None:
print(f'Hello: {name}')
if email is not None:
print(f'Email: {email}')
else:
print('No value provided')
s = Student()
s.hello('Pop', 'pop@')
| class Student:
def hello(self, name=None, email=None):
if name is not None:
print(f'Hello: {name}')
if email is not None:
print(f'Email: {email}')
else:
print('No value provided')
s = student()
s.hello('Pop', 'pop@') |
# model settings
model = dict(
type='FastRCNN',
backbone=dict(
type='ResNet_I3D',
pretrained=None,
pretrained2d=False,
depth=50,
num_stages=3,
spatial_strides=(1, 2, 2),
temporal_strides=(1, 1, 1),
dilations=(1, 1, 1),
out_indices=(2,),
... | model = dict(type='FastRCNN', backbone=dict(type='ResNet_I3D', pretrained=None, pretrained2d=False, depth=50, num_stages=3, spatial_strides=(1, 2, 2), temporal_strides=(1, 1, 1), dilations=(1, 1, 1), out_indices=(2,), frozen_stages=-1, inflate_freq=((1, 1, 1), (1, 0, 1, 0), (1, 0, 1, 0, 1, 0)), inflate_style='3x1x1', n... |
#
# PySNMP MIB module SVRCLU-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SVRCLU-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:12:19 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, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_union, value_range_constraint, constraints_intersection, value_size_constraint) ... |
class Repository:
def register_data_loaders(self, registry):
return registry
| class Repository:
def register_data_loaders(self, registry):
return registry |
'''
For 300 points, create a game of Tron Light Cycles inspired by this clip:
www.youtube.com/watch?v=-3ODe9mqoDE
One player will use the arrow keys to change the direction of a red square.
The other player will use the wasd keys to change the direction of a blue square.
If either player's square runs into the other ... | """
For 300 points, create a game of Tron Light Cycles inspired by this clip:
www.youtube.com/watch?v=-3ODe9mqoDE
One player will use the arrow keys to change the direction of a red square.
The other player will use the wasd keys to change the direction of a blue square.
If either player's square runs into the other ... |
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def deleteDuplicates(head):
if not head:
return head
init = head
while init.next:
if init.val == init.next.val:
init.next = init.next.next
else:
... | class Listnode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def delete_duplicates(head):
if not head:
return head
init = head
while init.next:
if init.val == init.next.val:
init.next = init.next.next
else:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2017-2022 Anderson Bravalheri, Univertity of Bristol
# High Performance Networks Group
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# Yo... | """Reusable functions related to common optical math."""
speed_of_light = 299792458
'Speed of light in vacuum.'
def wavelength_to_frequency_si(wavelength, speed_of_light=SPEED_OF_LIGHT):
"""Converts wavelength values to frequency.
Arguments
---------
wavelength : float
Spatial period of the wa... |
# Python3 program to sort an array
# using bucket sort
def insertionSort(b):
for i in range(1, len(b)):
up = b[i]
j = i - 1
while j >= 0 and b[j] > up:
b[j + 1] = b[j]
j -= 1
b[j + 1] = up
return b
def bucketSort(input_list):
# Find maximum value in ... | def insertion_sort(b):
for i in range(1, len(b)):
up = b[i]
j = i - 1
while j >= 0 and b[j] > up:
b[j + 1] = b[j]
j -= 1
b[j + 1] = up
return b
def bucket_sort(input_list):
max_value = max(input_list)
size = max_value / len(input_list)
buckets... |
alpha=['ABC','DEF','GHI','JKL','MNO','PQRS','TUV','WXYZ']
word = input()
num=0
for i in word:
for j in alpha:
if i in j:
num += alpha.index(j)+3
print(num)
| alpha = ['ABC', 'DEF', 'GHI', 'JKL', 'MNO', 'PQRS', 'TUV', 'WXYZ']
word = input()
num = 0
for i in word:
for j in alpha:
if i in j:
num += alpha.index(j) + 3
print(num) |
def clamp(coord, lower, upper):
"""
Clamp coord to lay between lower and upper.
"""
return min(upper, max(coord, lower))
| def clamp(coord, lower, upper):
"""
Clamp coord to lay between lower and upper.
"""
return min(upper, max(coord, lower)) |
class Contest:
__slots__ = ('name', 'site_tag', 'site_name', 'url', 'start', 'length')
def __init__(self, name, site_tag, site_name, url, start, length):
"""Represents a competitive programming contest.
:param name: the name of the contest
:param site_tag: the site tag
:param s... | class Contest:
__slots__ = ('name', 'site_tag', 'site_name', 'url', 'start', 'length')
def __init__(self, name, site_tag, site_name, url, start, length):
"""Represents a competitive programming contest.
:param name: the name of the contest
:param site_tag: the site tag
:param s... |
#
# PySNMP MIB module DFL1660-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DFL1660-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:42: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, 0... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_size_constraint, constraints_intersection, value_range_constraint, constraints_union) ... |
answer = 1000 - int(int(input())%1000)
if answer == 1000:
print(0)
else:
print(answer) | answer = 1000 - int(int(input()) % 1000)
if answer == 1000:
print(0)
else:
print(answer) |
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
z = x + y;
print('Sum of', x, 'and', y, 'is: ', z) | x = int(input('Enter first number: '))
y = int(input('Enter second number: '))
z = x + y
print('Sum of', x, 'and', y, 'is: ', z) |
#Conditional Tests
time = 'morning'
print("is it morning? i would say True")
print(time == 'morning')
print("is it not morning? i would say False")
print(time != 'morning')
print("is it evening then? i would say False")
print(time == 'evening')
time = 'afternoon'
print("if its not evening then it may be afternoon? I... | time = 'morning'
print('is it morning? i would say True')
print(time == 'morning')
print('is it not morning? i would say False')
print(time != 'morning')
print('is it evening then? i would say False')
print(time == 'evening')
time = 'afternoon'
print('if its not evening then it may be afternoon? I would say lets chec... |
""" Several mostly undocumented scripts with unknown functionality
.. todo:: Documentation of scripts is to sparse
.. todo:: link source code of scripts
"""
| """ Several mostly undocumented scripts with unknown functionality
.. todo:: Documentation of scripts is to sparse
.. todo:: link source code of scripts
""" |
class WFError(Exception):
def __init__(self, msg):
super().__init__(msg)
self.message = msg
def __repr__(self):
return self.message
class WFFileUnsupportedFormat(WFError):
def __init__(self, msg=''):
txt = 'Unsupported Watchface file'
if msg:
txt += f':... | class Wferror(Exception):
def __init__(self, msg):
super().__init__(msg)
self.message = msg
def __repr__(self):
return self.message
class Wffileunsupportedformat(WFError):
def __init__(self, msg=''):
txt = 'Unsupported Watchface file'
if msg:
txt += f'... |
class Enum(object):
def __new__(cls, *args, **kwargs):
raise AttributeError("Cannot create/instantiate enum data type")
def __init__(self):
raise AttributeError("Cannot create/instantiate enum data type")
| class Enum(object):
def __new__(cls, *args, **kwargs):
raise attribute_error('Cannot create/instantiate enum data type')
def __init__(self):
raise attribute_error('Cannot create/instantiate enum data type') |
"""
import requests
type = "all"
url = f"http://localhost:5000/notice?type={type}"
result = requests.get(url)
print(result)
"""
| """
import requests
type = "all"
url = f"http://localhost:5000/notice?type={type}"
result = requests.get(url)
print(result)
""" |
'''
crie um programa que leia varios numeros e coloqueos em uma lista
- diga quantos foram digitados
- a lista de valores ordenadas de forma decrescente
- se o valor 5 foi digitado e esta ou nao na lista
'''
lista = []
while True:
num = int(input("diga um numero"))
continuar = str(input("Quer continuar [S/N]" ... | """
crie um programa que leia varios numeros e coloqueos em uma lista
- diga quantos foram digitados
- a lista de valores ordenadas de forma decrescente
- se o valor 5 foi digitado e esta ou nao na lista
"""
lista = []
while True:
num = int(input('diga um numero'))
continuar = str(input('Quer continuar [S/N]'))... |
def get_text_after_another_text():
text1 = input("Insert some text: ")
included_text = input('Insert text that is included in the above text: ')
print(text1.split(included_text, 1)[-1])
# index = text1.find(included_text)
# if index > 0:
# print(text1[index + len(included_text):], end='')
... | def get_text_after_another_text():
text1 = input('Insert some text: ')
included_text = input('Insert text that is included in the above text: ')
print(text1.split(included_text, 1)[-1])
get_text_after_another_text() |
FILTERS = {}
def register_filter(name):
def wraps(f):
FILTERS[name] = f
return f
return wraps
| filters = {}
def register_filter(name):
def wraps(f):
FILTERS[name] = f
return f
return wraps |
class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
ans, codex = [], defaultdict()
def translate(c: str) -> str:
if c not in codex:
codex[c] = chr(97 + len(codex))
return codex[c]
def compare(word: str) -> None... | class Solution:
def find_and_replace_pattern(self, words: List[str], pattern: str) -> List[str]:
(ans, codex) = ([], defaultdict())
def translate(c: str) -> str:
if c not in codex:
codex[c] = chr(97 + len(codex))
return codex[c]
def compare(word: st... |
"""
Unique Paths
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths ... | """
Unique Paths
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths ... |
# for stmt
for i in range(5):
print("range(5) values =",i)
for i in range(1, 5):
print("range(1,5) values =",i)
for i in range(1, 11, 2):
print("range(1,11,2) values =",i)
| for i in range(5):
print('range(5) values =', i)
for i in range(1, 5):
print('range(1,5) values =', i)
for i in range(1, 11, 2):
print('range(1,11,2) values =', i) |
"""
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
for _ in[0]*int(input()):
n=int(input())
k=[x for x in range(1,31) if n%((2<<x)-1)<1][0]
print(n//((2<<k)-1)) | """
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
for _ in [0] * int(input()):
n = int(input())
k = [x for x in range(1, 31) if n % ((2 << x) - 1) < 1][0]
print(n // ((2 << k) - 1)) |
# O(n)time | O(n) space
# count from index 1, length = 1; if not add to res; handle last case
def runLengthEncoding(string):
res = []
length = 1
for i in range(1, len(string)):
if string[i] != string[i - 1] or length == 9:
res.append(str(length))
res.append(string[i - 1])
... | def run_length_encoding(string):
res = []
length = 1
for i in range(1, len(string)):
if string[i] != string[i - 1] or length == 9:
res.append(str(length))
res.append(string[i - 1])
length = 1
else:
length += 1
res.append(str(length))
re... |
"""Contains Various Classes for storing telescope positions.
"""
class HorizontalPosition:
"""Contains horizontal on sky position (ra, dec).
ra in hours as float
dec in degrees as float
"""
def __init__(self, ra, dec):
"""Construct instance.
Input: instance
... | """Contains Various Classes for storing telescope positions.
"""
class Horizontalposition:
"""Contains horizontal on sky position (ra, dec).
ra in hours as float
dec in degrees as float
"""
def __init__(self, ra, dec):
"""Construct instance.
Input: instance
... |
"""
Constants and Enums used by Grading.
"""
class ScoreDatabaseTableEnum:
"""
The various database tables that store scores.
"""
courseware_student_module = 'csm'
submissions = 'submissions'
overrides = 'overrides'
class GradeOverrideFeatureEnum:
proctoring = 'PROCTORING'
gradebook ... | """
Constants and Enums used by Grading.
"""
class Scoredatabasetableenum:
"""
The various database tables that store scores.
"""
courseware_student_module = 'csm'
submissions = 'submissions'
overrides = 'overrides'
class Gradeoverridefeatureenum:
proctoring = 'PROCTORING'
gradebook = ... |
# Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
__version__ = '0.2.4'
| __version__ = '0.2.4' |
""" Calculate spins (2S) from spin multiplicities.
"""
def spin(mult):
""" Calculate the spin (2Ms) from using the spin multiplicity
which is equivalent to the number of unpaired electrons.
:param mult: multiplicity
:type mult: int
:rtype: int
"""
return mult - 1
| """ Calculate spins (2S) from spin multiplicities.
"""
def spin(mult):
""" Calculate the spin (2Ms) from using the spin multiplicity
which is equivalent to the number of unpaired electrons.
:param mult: multiplicity
:type mult: int
:rtype: int
"""
return mult - 1 |
#: Module purely exists to test patching things.
thing = True
it = lambda: False
def get_thing():
global thing
return thing
def get_it():
global it
return it
def get_prop():
return ThingClass.prop
class ThingClass(object):
prop = True
| thing = True
it = lambda : False
def get_thing():
global thing
return thing
def get_it():
global it
return it
def get_prop():
return ThingClass.prop
class Thingclass(object):
prop = True |
__version__ = "1.0"
# from .miniglbase import genelist, location, glload
# import .miniglbase
__all__ = ["genelist", "location", "glload",]
| __version__ = '1.0'
__all__ = ['genelist', 'location', 'glload'] |
def get(self,key):
if self.root:
res = self._get(key,self.root)
if res:
return res.payload
else:
return None
else:
return None
def _get(self,key,currentNode):
if not currentNode:
return None
elif currentNode.key == key:
return curr... | def get(self, key):
if self.root:
res = self._get(key, self.root)
if res:
return res.payload
else:
return None
else:
return None
def _get(self, key, currentNode):
if not currentNode:
return None
elif currentNode.key == key:
return ... |
# Useful script for splitting a concatenated SDF (for eg: those from PubChem)
# Courtesy of someone on StackOverflow
f= "compound" # name of SDF file from database
split_number= 1000 # required #molecules per chopped file
number_of_sdfs=0
i=0
j=0
f2=open(f+'_'+str(j)+'.sdf','w')
for line in open(f+'.sdf'):
f2.write(l... | f = 'compound'
split_number = 1000
number_of_sdfs = 0
i = 0
j = 0
f2 = open(f + '_' + str(j) + '.sdf', 'w')
for line in open(f + '.sdf'):
f2.write(line)
if line[:4] == '$$$$':
i += 1
if i > number_of_sdfs:
number_of_sdfs += split_number
f2.close()
j += 1
f2 = open(f +... |
"""
Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
Example 1:
Input: root = [1,2,3,null,5,null,4]
Output: [1,3,4]
Example 2:
Input: root = [1,null,3]
Output: [1,3]
Example 3:
Input: root = []
Output: []
... | """
Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
Example 1:
Input: root = [1,2,3,null,5,null,4]
Output: [1,3,4]
Example 2:
Input: root = [1,null,3]
Output: [1,3]
Example 3:
Input: root = []
Output: []
... |
class Car(object):
def __init__(self, name='General', model='GM', vehicle_type=None):
self.speed = 0
self.name = name
self.model = model
self.vehicle_type = vehicle_type
if self.name in ['Porshe', 'Koenigsegg']:
self.num_of_doors = 2
else:
self.num_of_doors = 4
if self.vehic... | class Car(object):
def __init__(self, name='General', model='GM', vehicle_type=None):
self.speed = 0
self.name = name
self.model = model
self.vehicle_type = vehicle_type
if self.name in ['Porshe', 'Koenigsegg']:
self.num_of_doors = 2
else:
sel... |
# Author: btjanaka (Bryon Tjanaka)
# Problem: (CodeJam) 2020-1a-pascal-walk
# Title: Pascal Walk
# Link: https://codingcompetitions.withgoogle.com/codejam/round/000000000019fd74/00000000002b1353
# Idea: Since the i-th row of Pascal's triangle sums to 2^(i-1), we can
# represent n as a binary number and choose to traver... | for ca in range(1, int(input()) + 1):
n = int(input())
print('Case #{}:'.format(ca))
if n <= 30:
for i in range(n):
print(i + 1, i + 1)
else:
n2 = n - 30
n2bin = bin(n2)[2:][::-1]
tot = 0
side = True
for row in range(len(n2bin)):
if... |
aux = 0
num = int(input("Ingrese un numero entero positivo: "))
if num>0:
for x in range(0,num+1):
aux = aux + x
print (aux) | aux = 0
num = int(input('Ingrese un numero entero positivo: '))
if num > 0:
for x in range(0, num + 1):
aux = aux + x
print(aux) |
def max_steps(self, A):
steps = [0] * (A+1)
steps[0] = 0
steps[1] = 1
steps[2] = 2
p = 10**9+7
for i in range(3,A+1):
steps[i] = steps[i-1]%p ++ steps[i-2]%p
return steps[A]%p
| def max_steps(self, A):
steps = [0] * (A + 1)
steps[0] = 0
steps[1] = 1
steps[2] = 2
p = 10 ** 9 + 7
for i in range(3, A + 1):
steps[i] = steps[i - 1] % p + +steps[i - 2] % p
return steps[A] % p |
s = 'RLLLLRRRLR'
count = 0
output = 0
for i in range(len(s)):
if s[i] == 'R':
count += -1
if count == 0:
output += 1
else:
count += 1
if count == 0:
output += 1
print(output) | s = 'RLLLLRRRLR'
count = 0
output = 0
for i in range(len(s)):
if s[i] == 'R':
count += -1
if count == 0:
output += 1
else:
count += 1
if count == 0:
output += 1
print(output) |
set_name(0x8013570C, "GameOnlyTestRoutine__Fv", SN_NOWARN)
set_name(0x80135714, "GetDamageAmt__FiPiT1", SN_NOWARN)
set_name(0x80135D0C, "CheckBlock__Fiiii", SN_NOWARN)
set_name(0x80135DC0, "FindClosest__Fiii", SN_NOWARN)
set_name(0x80135F4C, "GetSpellLevel__Fii", SN_NOWARN)
set_name(0x80135FC0, "GetDirection8__Fiiii", ... | set_name(2148751116, 'GameOnlyTestRoutine__Fv', SN_NOWARN)
set_name(2148751124, 'GetDamageAmt__FiPiT1', SN_NOWARN)
set_name(2148752652, 'CheckBlock__Fiiii', SN_NOWARN)
set_name(2148752832, 'FindClosest__Fiii', SN_NOWARN)
set_name(2148753228, 'GetSpellLevel__Fii', SN_NOWARN)
set_name(2148753344, 'GetDirection8__Fiiii', ... |
class BaseAuth:
RESERVED_KWARGS = ['verify']
def __init__(self, *args, **kwargs):
"""Create auth object and establish connection
Args:
**kwargs: Keyword arguments specific to Auth engine
"""
for k, v in kwargs.items():
if k not in self.RESERVED_KWARGS:
... | class Baseauth:
reserved_kwargs = ['verify']
def __init__(self, *args, **kwargs):
"""Create auth object and establish connection
Args:
**kwargs: Keyword arguments specific to Auth engine
"""
for (k, v) in kwargs.items():
if k not in self.RESERVED_KWARGS:... |
"""
the Trivial FTP protocol
"""
| """
the Trivial FTP protocol
""" |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Password Encryption',
'version': '2.0',
'author': ['Odoo SA', 'FS3'],
'maintainer': 'Odoo SA',
'category': 'Extra Tools',
'description': """
Encrypted passwords
===================
Rep... | {'name': 'Password Encryption', 'version': '2.0', 'author': ['Odoo SA', 'FS3'], 'maintainer': 'Odoo SA', 'category': 'Extra Tools', 'description': "\nEncrypted passwords\n===================\n\nReplaces the default password storage with a strong cryptographic\nhash.\n\nThe key derivation function currently used is RSA ... |
def iter_fact(n):
'''
assumes that n is an int > 0
returns n!
'''
result = 1
while n > 1:
result *= n
n -= 1
return result
iter_fact(5)
| def iter_fact(n):
"""
assumes that n is an int > 0
returns n!
"""
result = 1
while n > 1:
result *= n
n -= 1
return result
iter_fact(5) |
def calculate_metrics(predictions, labels, adjust):
tp = 0
tn = 0
fp = 0
fn = 0
if adjust:
preds = adjust_predictions(predictions, labels)
for i in range(len(predictions)):
if preds[i] == 1 and labels[i] == 1:
tp = tp + 1
elif preds[i] == 0 and labels[i] == 0:
tn = tn + 1
elif p... | def calculate_metrics(predictions, labels, adjust):
tp = 0
tn = 0
fp = 0
fn = 0
if adjust:
preds = adjust_predictions(predictions, labels)
for i in range(len(predictions)):
if preds[i] == 1 and labels[i] == 1:
tp = tp + 1
elif preds[i] == 0 and labels[i] == 0:... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
class SlackAdapterOptions:
"""
Class for defining implementation of the SlackAdapter Options.
"""
def __init__(
self,
slack_verification_token: str,
slack_bot_token: str,
... | class Slackadapteroptions:
"""
Class for defining implementation of the SlackAdapter Options.
"""
def __init__(self, slack_verification_token: str, slack_bot_token: str, slack_client_signing_secret: str):
"""
Initializes new instance of SlackAdapterOptions
:param slack_verificat... |
# Copyright 2018 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
config_type='sweetberry'
# the names j2, j3, and j4 are the white banks on sweetberry
# Note that here the bank name in the mux position is optional
# as... | config_type = 'sweetberry'
inas = [('sweetberry', '0x40:3', 'pp975_io', 7.7, 0.1, 'j2', True), ('sweetberry', '0x40:1', 'pp850_prim_core', 0.9, 0.01, 'j2', True), ('sweetberry', '0x40:2', 'pp3300_dsw', 3.3, 0.01, 'j2', True), ('sweetberry', '0x40:0', 'pp3300_a', 3.3, 0.005, 'j2', True), ('sweetberry', '0x41:3', 'pp1800... |
class Snake:
"""
class representing the snake
"""
pass | class Snake:
"""
class representing the snake
"""
pass |
class Settings:
IPS = 1 # default IPS value, 1 image per second
WIDTH = 128
HEIGHT = 72
EXT = ".jpeg"
ROWS = 30
COLS = 30
FILENAME_FORMAT = "%04d{ext}"
PREFIX = ""
@classmethod
def load(cls, width=None, height=None, ips=None, ext=None, rows=None, cols=None, prefix=None):
... | class Settings:
ips = 1
width = 128
height = 72
ext = '.jpeg'
rows = 30
cols = 30
filename_format = '%04d{ext}'
prefix = ''
@classmethod
def load(cls, width=None, height=None, ips=None, ext=None, rows=None, cols=None, prefix=None):
cls.IPS = ips or cls.IPS
cls.EX... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 11 11:45:19 2017
@author: dhingratul
"""
class Node:
def __init__(self,key):
self.left=None
self.right=None
self.val=key
# create root
root = Node(1)
''' following is the tree after above statement
1
/ \... | """
Created on Sat Feb 11 11:45:19 2017
@author: dhingratul
"""
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
root = node(1)
' following is the tree after above statement\n 1\n / None None'
root.left = node(2)
root.right = node(... |
k=int(input())
l=int(input())
m=int(input())
n=int(input())
d=int(input())
ans=0
for i in range(1,d+1):
if i%k==0 or i%l==0 or i%m==0 or i%n==0:
ans+=1
print(ans) | k = int(input())
l = int(input())
m = int(input())
n = int(input())
d = int(input())
ans = 0
for i in range(1, d + 1):
if i % k == 0 or i % l == 0 or i % m == 0 or (i % n == 0):
ans += 1
print(ans) |
"""
Settings specific to Country module
"""
FLAG_SOURCE = 'https://raw.githubusercontent.com/cristiroma/countries' \
'/master/data/flags/SVG/{alpha_2}.svg?sanitize=true'
# put in global settings.py to override
GEOCODING_SERVICE = 'pelias'
# put in global settings.py to override
GEOCODER_PELIAS_URL = 'h... | """
Settings specific to Country module
"""
flag_source = 'https://raw.githubusercontent.com/cristiroma/countries/master/data/flags/SVG/{alpha_2}.svg?sanitize=true'
geocoding_service = 'pelias'
geocoder_pelias_url = 'https://api.geocode.earth/v1'
geocoder_pelias_key = ''
geocoder_google_key = ''
geocoding_service_setti... |
# -*- coding: utf-8 -*-
class ScrapbookException(ValueError):
"""Raised when an exception is encountered when operating on a notebook."""
class ScrapbookMissingEncoder(ScrapbookException):
"""Raised when no encoder is found to tranforming data"""
class ScrapbookDataException(ScrapbookException):
"""Ra... | class Scrapbookexception(ValueError):
"""Raised when an exception is encountered when operating on a notebook."""
class Scrapbookmissingencoder(ScrapbookException):
"""Raised when no encoder is found to tranforming data"""
class Scrapbookdataexception(ScrapbookException):
"""Raised when a data translation... |
print('''
is_male = True
if is_male:
print("Male")
''')
is_male = True
if is_male:
print("Male")
print('''
is_male = False
if is_male:
print("Male")
''')
print('''
is_male = False
if is_male:
print("Male")
else:
print(" Not Male")
''')
print('''
is_male = True
is_... | print('\nis_male = True\n\nif is_male:\n print("Male")\n')
is_male = True
if is_male:
print('Male')
print('\nis_male = False\n\nif is_male:\n print("Male")\n')
print('\nis_male = False\nif is_male:\n print("Male")\nelse:\n print(" Not Male")\n')
print('\nis_male = True\nis_Tall = True\n\nif is_male and ... |
class Item:
"""
This is out domain! The item hold the details of its inventory item
"""
def __init__(self, name, code, unit_price):
self.name = name
self.code = code
self.quantity = 0
self.unit_price = unit_price
self.total_price = 0
def increment(self):
... | class Item:
"""
This is out domain! The item hold the details of its inventory item
"""
def __init__(self, name, code, unit_price):
self.name = name
self.code = code
self.quantity = 0
self.unit_price = unit_price
self.total_price = 0
def increment(self):
... |
year = int(input("Which year do you want to check?\n"))
# **every** year that is evenly divisible by 4
# **except** every year that is evenly divisible by 100
# **unless** the year is also evenly divisible by 400
leap_1 = year % 4 == 0 # if result is equal 0 then leap year
non_leap_1 = year % 100 != 0 # but if resu... | year = int(input('Which year do you want to check?\n'))
leap_1 = year % 4 == 0
non_leap_1 = year % 100 != 0
leap_2 = year % 400 == 0
if leap_1 and non_leap_1 == True:
print('Leap year. ')
elif leap_2 == True:
print('Leap year')
else:
print('Non leap year') |
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 23 11:24:13 2019
@author: Administrator
"""
class Solution:
def countSubstrings(self, s: str) -> int:
count = 0#ans = []#
for k in range(len(s)):
m = 0
while 0<=k-m and k+m<=len(s)-1 and s[k-m] == s[k+m]:
count ... | """
Created on Sun Jun 23 11:24:13 2019
@author: Administrator
"""
class Solution:
def count_substrings(self, s: str) -> int:
count = 0
for k in range(len(s)):
m = 0
while 0 <= k - m and k + m <= len(s) - 1 and (s[k - m] == s[k + m]):
count += 1
... |
class Solution:
def sequenceReconstruction(self, org: List[int], seqs: List[List[int]]) -> bool:
seqs = [seq for seq in seqs if seq]
if not seqs:
return False
n = len(org)
degrees = [0] * (n + 1)
follows = collections.defaultdict(list)
seen = set()
... | class Solution:
def sequence_reconstruction(self, org: List[int], seqs: List[List[int]]) -> bool:
seqs = [seq for seq in seqs if seq]
if not seqs:
return False
n = len(org)
degrees = [0] * (n + 1)
follows = collections.defaultdict(list)
seen = set()
... |
class OleFileError(IOError):
"""
Generic base error for this module.
"""
pass
class NotOleFileError(OleFileError):
"""
Error raised when the opened file is not an OLE file.
"""
pass
class OleFileIONotClosed(RuntimeWarning):
"""
Warning type used when OleFileIO is destructed... | class Olefileerror(IOError):
"""
Generic base error for this module.
"""
pass
class Notolefileerror(OleFileError):
"""
Error raised when the opened file is not an OLE file.
"""
pass
class Olefileionotclosed(RuntimeWarning):
"""
Warning type used when OleFileIO is destructed but... |
#define a value holder class
class switch(object):
value = None
def __new__(class_, value):
class_.value = value
return True
# function to verify matching case
# => True or False
def case(*args):
iterator = (arg == switch.value for arg in args)
return any(iterator)
# Switch example:
f... | class Switch(object):
value = None
def __new__(class_, value):
class_.value = value
return True
def case(*args):
iterator = (arg == switch.value for arg in args)
return any(iterator)
for n in range(0, 10):
print(n, ':', end='', flush=True)
while switch(n):
if case(0):
... |
# Apr 12
class Solution:
def totalFruit(self, tree: List[int]) -> int:
left = 0
result = 0
seen = dict()
cur = 0
for i, n in enumerate(tree):
seen[n] = seen.get(n, 0) + 1
if len(seen) <= 2:
result = max(result, i - left + 1)
... | class Solution:
def total_fruit(self, tree: List[int]) -> int:
left = 0
result = 0
seen = dict()
cur = 0
for (i, n) in enumerate(tree):
seen[n] = seen.get(n, 0) + 1
if len(seen) <= 2:
result = max(result, i - left + 1)
... |
class ExampleFaceDetector:
"""It doesn't really work!"""
def __init__(self, example_parameter):
self.example_parameter = example_parameter
@staticmethod
def detect_faces(_binary_data):
return [((110, 120), (130, 140)),
((220, 240), (230, 250)),
((300, 300... | class Examplefacedetector:
"""It doesn't really work!"""
def __init__(self, example_parameter):
self.example_parameter = example_parameter
@staticmethod
def detect_faces(_binary_data):
return [((110, 120), (130, 140)), ((220, 240), (230, 250)), ((300, 300), (310, 310))] |
def campo(txt):
esp = len(txt) + 2
print('~'*esp)
print(f' {txt} ')
print('~'*esp)
campo('eeita porra consegui')
| def campo(txt):
esp = len(txt) + 2
print('~' * esp)
print(f' {txt} ')
print('~' * esp)
campo('eeita porra consegui') |
# cases where ComprehensionsAchievement should not unlock
# >> CASE
for _ in range(10):
pass
# >> CASE
set([4, 5, 6])
# >> CASE
{4, 5, 6}
| for _ in range(10):
pass
set([4, 5, 6])
{4, 5, 6} |
class Z80BINFileHandler:
def __init__(self):
self.execAddr = 0x8000
self.baseAddr = 0x8000
def genS3Rec(self, startCh, addr, data, leng, offset):
s3Rec = startCh + "3" + "{:0>2x}".format(leng + 5)
csum = leng + 5
s3Rec += "{:0>8x}".format(addr)
csum +=... | class Z80Binfilehandler:
def __init__(self):
self.execAddr = 32768
self.baseAddr = 32768
def gen_s3_rec(self, startCh, addr, data, leng, offset):
s3_rec = startCh + '3' + '{:0>2x}'.format(leng + 5)
csum = leng + 5
s3_rec += '{:0>8x}'.format(addr)
csum += (addr &... |
# -*- coding: utf-8 -*-
#
# Copyright 2019 SoloKeys Developers
#
# Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
# http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
# http://opensource.org/licenses/MIT>, at your option. This file may not be
# copied, modified, or distribute... | class Basepynkexception(Exception):
pass
class Nonuniquedeviceerror(Exception):
"""When specifying a potentially destructive command...
we check that either there is exactly one applicable device,
or demand passing the serial number (same for ST DFU bootloader
and Nitrokey bootloader+firmware.
... |
""" Parameters of the Agresti data sets, as documented for SoftKinect camera"""
resolution = [240, 320]
fov = [74, 58]
| """ Parameters of the Agresti data sets, as documented for SoftKinect camera"""
resolution = [240, 320]
fov = [74, 58] |
# https://leetcode.com/problems/flood-fill
class Solution:
def dfs(self, image, y, x, oldColor, newColor):
image[y][x] = newColor
nexts = [(y + 1, x), (y - 1, x), (y, x + 1), (y, x - 1)]
for ny, nx in nexts:
if (
0 <= ny < len(image)
and 0 <= nx ... | class Solution:
def dfs(self, image, y, x, oldColor, newColor):
image[y][x] = newColor
nexts = [(y + 1, x), (y - 1, x), (y, x + 1), (y, x - 1)]
for (ny, nx) in nexts:
if 0 <= ny < len(image) and 0 <= nx < len(image[0]) and (image[ny][nx] == oldColor):
self.dfs(im... |
list_of_strings=input().split()
list_of_integers=[]
reversed_integers=[]
for index in list_of_strings:
list_of_integers.append(int(index))
for el in list_of_integers:
reversed_integers.append(el*(-1))
print(reversed_integers)
| list_of_strings = input().split()
list_of_integers = []
reversed_integers = []
for index in list_of_strings:
list_of_integers.append(int(index))
for el in list_of_integers:
reversed_integers.append(el * -1)
print(reversed_integers) |
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
class CommunicationUser(object):
"""
Represents a user in Azure Communication Service.
:ivar identifier: Communication user identifier.
:vartype identif... | class Communicationuser(object):
"""
Represents a user in Azure Communication Service.
:ivar identifier: Communication user identifier.
:vartype identifier: str
:param identifier: Identifier to initialize CommunicationUser.
:type identifier: str
"""
def __init__(self, identifier):
... |
class Neuron(object):
"""
This Class is representing a Neuron which is corresponding to an action to perform.
.. note:: Neurons are defined in the brain file
"""
def __init__(self, name=None, parameters=None):
self.name = name
self.parameters = parameters
def serialize(self):
... | class Neuron(object):
"""
This Class is representing a Neuron which is corresponding to an action to perform.
.. note:: Neurons are defined in the brain file
"""
def __init__(self, name=None, parameters=None):
self.name = name
self.parameters = parameters
def serialize(self):
... |
__all__ = ['Content']
class Content(object):
def __init__(self, value):
if value is None:
value = ''
if not isinstance(value, str):
raise TypeError('`value` should be a string')
self.value = value
def __str__(self):
return self.value
def write(self... | __all__ = ['Content']
class Content(object):
def __init__(self, value):
if value is None:
value = ''
if not isinstance(value, str):
raise type_error('`value` should be a string')
self.value = value
def __str__(self):
return self.value
def write(sel... |
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
result = ''
input_str = s.split(' ')
for each in input_str:
result = result + each[::-1] + ' '
return result[:-1]
# return ' '.join(x[::-1] for x i... | class Solution(object):
def reverse_words(self, s):
"""
:type s: str
:rtype: str
"""
result = ''
input_str = s.split(' ')
for each in input_str:
result = result + each[::-1] + ' '
return result[:-1] |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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 applicab... | class Animationtransformtype(object):
"""
Const Class
Specifies the transformation type for an XAnimateTransform.
See Also:
`API AnimationTransformType <https://api.libreoffice.org/docs/idl/ref/namespacecom_1_1sun_1_1star_1_1animations_1_1AnimationTransformType.html>`_
"""
__ooo_ns__: ... |
# SNN
TIME_STEP_IN_MSEC = 0.1
THRESHOLD_THETA_INCREMENT_RATE = 0.2
THRESHOLD_THETA_DECAY_RATE = 0.01 * TIME_STEP_IN_MSEC # (0, 1), lower value means slower decay
MAX_THRESHOLD_THETA = 20.0
LIF_MEMBRANE_POTENTIAL_THRESHOLD = 1.0
LIF_SPIKE_VOLTAGE = 1.0
IZ_MEMBRANE_POTENTIAL_THRESHOLD = 30.0
IZ_SPIKE_VOLTAGE = 100
# Iz... | time_step_in_msec = 0.1
threshold_theta_increment_rate = 0.2
threshold_theta_decay_rate = 0.01 * TIME_STEP_IN_MSEC
max_threshold_theta = 20.0
lif_membrane_potential_threshold = 1.0
lif_spike_voltage = 1.0
iz_membrane_potential_threshold = 30.0
iz_spike_voltage = 100
regular_spiking_params = {'a': 0.02, 'b': 0.2, 'c': -... |
# https://leetcode.com/problems/dice-roll-simulation/
# simple dp
class Solution:
def rec(self, i, prev, prev_cnt):
if prev_cnt > self.rollMax[prev]:
return 0
if i > self.n: # reached a solution
return 1
if self.dp[i][prev][prev_cnt] !=-1:
return self.dp[... | class Solution:
def rec(self, i, prev, prev_cnt):
if prev_cnt > self.rollMax[prev]:
return 0
if i > self.n:
return 1
if self.dp[i][prev][prev_cnt] != -1:
return self.dp[i][prev][prev_cnt]
m = 1000000000 + 7
ans = 0
for k in range(1... |
# Title : Remove duplicate list
# Author : Kiran raj R.
# Date : 23:10:2020
def remove_dup(nested_list):
out_list = []
for i in range(len(nested_list)):
for j in range(1, len(nested_list)):
if nested_list[i] == nested_list[j]:
break
if i == j:
out_list... | def remove_dup(nested_list):
out_list = []
for i in range(len(nested_list)):
for j in range(1, len(nested_list)):
if nested_list[i] == nested_list[j]:
break
if i == j:
out_list.append(nested_list[i])
print(f'List without duplicates : {out_list}')
remov... |
KEYWORDS = {
'if',
'else',
'return',
'\\',
}
OPERATORS = {
'=', '-', '+', '/', '*', '>', '<', '|', '^', '&', '~',
}
class MalformedInput(Exception):
pass
class Lexeme:
def __init__(self, type, value):
self.type = type
self.value = value
def __repr__(self):
... | keywords = {'if', 'else', 'return', '\\'}
operators = {'=', '-', '+', '/', '*', '>', '<', '|', '^', '&', '~'}
class Malformedinput(Exception):
pass
class Lexeme:
def __init__(self, type, value):
self.type = type
self.value = value
def __repr__(self):
return '<Lexeme {} {}>'.forma... |
print("Hello World from %s!" % __name__)
if __name__ == '__main__':
print("Hello World again from %s!" % __name__)
#python a.py
#python b.py | print('Hello World from %s!' % __name__)
if __name__ == '__main__':
print('Hello World again from %s!' % __name__) |
def get_weights(vs):
# :brief Get the weights for some set of update vectorsself.
# :param vs [array<array<float>>] some update vectors
# :return a [array<float>] a list of weights in the same order
ls = []
for v in vs:
l = 0.0
for e in v:
l += e**2
l = l**0.5
... | def get_weights(vs):
ls = []
for v in vs:
l = 0.0
for e in v:
l += e ** 2
l = l ** 0.5
ls.append(l)
s = 0.0
ret = []
for l in ls:
x = 1.0 / l
s += x
ret.append(x)
for k in range(len(ls)):
ret[k] /= s
return ret |
class Animal():
def __init__(self,name,id):
self.name=name
self.id=id
def getId(self):
return self.id
def setId(self,id):
self.id=id
dog = Animal('dog',1)
id = dog.getId()
print(id)
dog.setId(2)
id = dog.getId()
print(id)
| class Animal:
def __init__(self, name, id):
self.name = name
self.id = id
def get_id(self):
return self.id
def set_id(self, id):
self.id = id
dog = animal('dog', 1)
id = dog.getId()
print(id)
dog.setId(2)
id = dog.getId()
print(id) |
# 1025. Divisor Game
"""
Alice and Bob take turns playing a game, with Alice starting first.
Initially, there is a number N on the chalkboard. On each player's turn, that player makes a move consisting of:
Choosing any x with 0 < x < N and N % x == 0.
Replacing the number N on the chalkboard with N ... | """
Alice and Bob take turns playing a game, with Alice starting first.
Initially, there is a number N on the chalkboard. On each player's turn, that player makes a move consisting of:
Choosing any x with 0 < x < N and N % x == 0.
Replacing the number N on the chalkboard with N - x.
Also, if a pl... |
#!/usr/bin/python
array1 = [1, 2, 3]
array2 = array1
array1[0] = 4
print (array1)
print (array2)
| array1 = [1, 2, 3]
array2 = array1
array1[0] = 4
print(array1)
print(array2) |
def dH_atoms(at):
"""
Returns the enthalpy corrections of the element.
Parameters:
at (char): Symbol of the element
Returns:
dH_atoms (float): Enthalpy corrections of the element
"""
h = 6.626070040*(10**-34) #6.626070040d-34
Ry =... | def d_h_atoms(at):
"""
Returns the enthalpy corrections of the element.
Parameters:
at (char): Symbol of the element
Returns:
dH_atoms (float): Enthalpy corrections of the element
"""
h = 6.62607004 * 10 ** (-34)
ry = 10973731.568508
... |
video = "NET20070331_thlep_1_2"
training = 0
if training:
file_path = "mouth_features_train/" + video
mouth_features = open(file_path + "/mouth_features_train.txt", "r")
mouth_features_clear = open(file_path + "/mouth_features_clear.txt", "w")
else:
file_path = "mouth_features_test/" + video
mouth_features = ope... | video = 'NET20070331_thlep_1_2'
training = 0
if training:
file_path = 'mouth_features_train/' + video
mouth_features = open(file_path + '/mouth_features_train.txt', 'r')
mouth_features_clear = open(file_path + '/mouth_features_clear.txt', 'w')
else:
file_path = 'mouth_features_test/' + video
mouth_f... |
class Solution:
def maxDistToClosest(self, seats: List[int]) -> int:
result = 0
for seat, group in itertools.groupby(seats):
if seat: continue
K = len(list(group))
result = max(result, (K + 1) // 2)
return max(result, seats.index(1), seats[::-1].index(1)... | class Solution:
def max_dist_to_closest(self, seats: List[int]) -> int:
result = 0
for (seat, group) in itertools.groupby(seats):
if seat:
continue
k = len(list(group))
result = max(result, (K + 1) // 2)
return max(result, seats.index(1), ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.