content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def Values_Sum_Greater(Test_Dict):
return sum(list(Test_Dict.keys())) < sum(list(Test_Dict.values()))
Test_Dict = {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}
print(Values_Sum_Greater(Test_Dict))
| def values__sum__greater(Test_Dict):
return sum(list(Test_Dict.keys())) < sum(list(Test_Dict.values()))
test__dict = {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}
print(values__sum__greater(Test_Dict)) |
class Concept:
ID = None
descriptions = None
definition = None
def __init__(self, ID=None, descriptions=None, definition = None):
self.ID = ID
self.descriptions = [] if descriptions is None else descriptions
self.definition = None
class Description:
ID = None
concept_ID... | class Concept:
id = None
descriptions = None
definition = None
def __init__(self, ID=None, descriptions=None, definition=None):
self.ID = ID
self.descriptions = [] if descriptions is None else descriptions
self.definition = None
class Description:
id = None
concept_id =... |
expected_output = {
'pvst': {
'a': {
'pvst_id': 'a',
'vlans': {
2: {
'vlan_id': 2,
'designated_root_priority': 32768,
'designated_root_address': '0021.1bff.d973',
'designated_root_max_ag... | expected_output = {'pvst': {'a': {'pvst_id': 'a', 'vlans': {2: {'vlan_id': 2, 'designated_root_priority': 32768, 'designated_root_address': '0021.1bff.d973', 'designated_root_max_age': 20, 'designated_root_forward_delay': 15, 'bridge_priority': 32768, 'sys_id_ext': 0, 'bridge_address': '8cb6.4fff.6588', 'bridge_max_age... |
t1 = (1, 2, 3, 'a')
t2 = 4, 5, 6, 'b'
t3 = 1,
# print(t1[3])
# for v in t1:
# print(v)
# print(t1 + t2)
n1, n2, *n = t1
print(n1)
# Processo para mudar valor de uma tupla
t1 = list(t1)
t1[1] = 3000
t1 = tuple(t1)
print(t1)
| t1 = (1, 2, 3, 'a')
t2 = (4, 5, 6, 'b')
t3 = (1,)
(n1, n2, *n) = t1
print(n1)
t1 = list(t1)
t1[1] = 3000
t1 = tuple(t1)
print(t1) |
# Medium
# for loop with twoSum
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
result = []
for i in range(len(nums)):
if i>0 and nums[i] == nums[i-1]:
continue
tmp = self.twoSum(nums,i+1,0-nums[i])
... | class Solution:
def three_sum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
result = []
for i in range(len(nums)):
if i > 0 and nums[i] == nums[i - 1]:
continue
tmp = self.twoSum(nums, i + 1, 0 - nums[i])
for t in tmp:
... |
def minion_game(string):
string = string.lower()
scoreStuart = 0
scoreKevin = 0
vowels = 'aeiou'
for j, i in enumerate(string):
if i not in vowels:
scoreStuart += len(string) - j
if i in vowels:
scoreKevin += len(string) - j
if scoreStuart > scoreKevin:
... | def minion_game(string):
string = string.lower()
score_stuart = 0
score_kevin = 0
vowels = 'aeiou'
for (j, i) in enumerate(string):
if i not in vowels:
score_stuart += len(string) - j
if i in vowels:
score_kevin += len(string) - j
if scoreStuart > scoreKev... |
class CoachAthleteTable:
def __init__(self):
pass
TABLE_NAME = "Coach_Athlete"
ATHLETE_ID = "Athlete_Id"
COACH_ID = "Coach_Id"
CAN_ACCESS_TRAINING_LOG = "Can_Access_Training_Log"
CAN_ACCESS_TARGETS = "Can_Access_Targets"
IS_ACTIVE = "Is_Active"
START_DATE = "Start_Date"
IN... | class Coachathletetable:
def __init__(self):
pass
table_name = 'Coach_Athlete'
athlete_id = 'Athlete_Id'
coach_id = 'Coach_Id'
can_access_training_log = 'Can_Access_Training_Log'
can_access_targets = 'Can_Access_Targets'
is_active = 'Is_Active'
start_date = 'Start_Date'
invi... |
T=int(input())
def is_anagram(str1, str2):
list_str1 = list(str1)
list_str1.sort()
list_str2 = list(str2)
#list_str2.sort()
return (list_str1 == list_str2)
for i in range(T):
opt=0
L=int(input())
A=str(input())
B=str(input())
for j in range(len(A)):
f... | t = int(input())
def is_anagram(str1, str2):
list_str1 = list(str1)
list_str1.sort()
list_str2 = list(str2)
return list_str1 == list_str2
for i in range(T):
opt = 0
l = int(input())
a = str(input())
b = str(input())
for j in range(len(A)):
for k in range(len(A)):
... |
__title__ = 'tmuxp'
__package_name__ = 'tmuxp'
__version__ = '0.1.12'
__description__ = 'Manage tmux sessions thru JSON, YAML configs. Features Python API'
__email__ = 'tony@git-pull.com'
__author__ = 'Tony Narlock'
__license__ = 'BSD'
__copyright__ = 'Copyright 2013 Tony Narlock'
| __title__ = 'tmuxp'
__package_name__ = 'tmuxp'
__version__ = '0.1.12'
__description__ = 'Manage tmux sessions thru JSON, YAML configs. Features Python API'
__email__ = 'tony@git-pull.com'
__author__ = 'Tony Narlock'
__license__ = 'BSD'
__copyright__ = 'Copyright 2013 Tony Narlock' |
list=linkedlist()
list.head=node("Monday")
list1=node("Tuesday")
list2=node("Thursday")
list.head.next=list1
list1.next=list2
print("Before insertion:")
list.printing()
print('\n')
list.push_after(list1,"Wednesday")
print("After insertion:")
list.printing()
print('\n')
list.deletion(3)
print("After deleting 4th node")
... | list = linkedlist()
list.head = node('Monday')
list1 = node('Tuesday')
list2 = node('Thursday')
list.head.next = list1
list1.next = list2
print('Before insertion:')
list.printing()
print('\n')
list.push_after(list1, 'Wednesday')
print('After insertion:')
list.printing()
print('\n')
list.deletion(3)
print('After deletin... |
# -*- coding: utf-8 -*-
DB_LOCATION = 'timeclock.db'
DEBUG = True
| db_location = 'timeclock.db'
debug = True |
#
# Copyright (c) 2020-present, Weibo, Inc. 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 app... | """Build rule for generating C or C++ sources with fbthrift thrift1.
"""
def _fbthrift_cc_library_impl(ctx):
output_path_attr = ctx.attr.name
if ctx.attr.output_path:
output_path_attr = ctx.attr.output_path
outputs = [ctx.actions.declare_file('%s/gen-cpp2/%s_%s.h' % (output_path_attr, ctx.attr.name... |
"""
--- Day 23: Coprocessor Conflagration ---
You decide to head directly to the CPU and fix the printer from there. As you get close, you find an experimental coprocessor doing so much work that the local programs are afraid it will halt and catch fire. This would cause serious issues for the rest of the computer, so... | """
--- Day 23: Coprocessor Conflagration ---
You decide to head directly to the CPU and fix the printer from there. As you get close, you find an experimental coprocessor doing so much work that the local programs are afraid it will halt and catch fire. This would cause serious issues for the rest of the computer, so... |
class Sources:
"""
Sources class to define source object
"""
def __init__(self, id, name, description, url):
self.id = id
self.name = name
self.description = description
self.url = url
class Articles:
"""
Articles class to define articles object
"""
def... | class Sources:
"""
Sources class to define source object
"""
def __init__(self, id, name, description, url):
self.id = id
self.name = name
self.description = description
self.url = url
class Articles:
"""
Articles class to define articles object
"""
def... |
class Vehicle(object):
"""A generic vehicle class."""
def __init__(self, position):
self.position = position
def travel(self, destination):
print('Travelling...')
class RadioMixin(object):
def play_song_on_station(self, station):
print('Playing station...')
class Car(Vehicl... | class Vehicle(object):
"""A generic vehicle class."""
def __init__(self, position):
self.position = position
def travel(self, destination):
print('Travelling...')
class Radiomixin(object):
def play_song_on_station(self, station):
print('Playing station...')
class Car(Vehicle... |
#!/usr/bin/env python3
n = int(input())
print(n * ((n - 1) % 2))
| n = int(input())
print(n * ((n - 1) % 2)) |
result = True
another_result = result
print(id(result))
print(id(another_result))
# bool is immutable
result = False
print(id(result))
print(id(another_result))
| result = True
another_result = result
print(id(result))
print(id(another_result))
result = False
print(id(result))
print(id(another_result)) |
region='' # GCP region e.g. us-central1 etc,
dbusername=''
dbpassword=''
rabbithost=''
rabbitusername=''
rabbitpassword=''
awskey='' # if you intend to import data from S3
awssecret='' # if you intend to import data from S3
mediabucket=''
secretkey=''
superuser=''
superpass=''
superemail=''
cloudfsprefix='gs'
cors_orig... | region = ''
dbusername = ''
dbpassword = ''
rabbithost = ''
rabbitusername = ''
rabbitpassword = ''
awskey = ''
awssecret = ''
mediabucket = ''
secretkey = ''
superuser = ''
superpass = ''
superemail = ''
cloudfsprefix = 'gs'
cors_origin = ''
redishost = 'redis-master'
redispassword = 'sadnnasndaslnk' |
CheckNumber = float(input("enter your number"))
print(str(CheckNumber) +' setnumber')
while CheckNumber != 1:
numcheck = CheckNumber
if CheckNumber % 2 == 0:
CheckNumber = CheckNumber / 2
print(str(CheckNumber) +' output reduced')
else:
CheckNumber = CheckNumber * 3 + 1
print(str(CheckNumber) +' output ... | check_number = float(input('enter your number'))
print(str(CheckNumber) + ' setnumber')
while CheckNumber != 1:
numcheck = CheckNumber
if CheckNumber % 2 == 0:
check_number = CheckNumber / 2
print(str(CheckNumber) + ' output reduced')
else:
check_number = CheckNumber * 3 + 1
... |
class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
'''
T: (n) and S: O(n)
'''
stack = []
for asteroid in asteroids:
# Case 1: Collision occurs
while stack and (asteroid < 0 and stack[-1] > 0):
if st... | class Solution:
def asteroid_collision(self, asteroids: List[int]) -> List[int]:
"""
T: (n) and S: O(n)
"""
stack = []
for asteroid in asteroids:
while stack and (asteroid < 0 and stack[-1] > 0):
if stack[-1] < -asteroid:
stack... |
#
# PySNMP MIB module ENTERASYS-SERVICE-LEVEL-REPORTING-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ENTERASYS-SERVICE-LEVEL-REPORTING-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:50:17 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
#... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_range_constraint, value_size_constraint, constraints_intersection, constraints_union) ... |
#
# @lc app=leetcode id=4 lang=python3
#
# [4] Median of Two Sorted Arrays
#
# https://leetcode.com/problems/median-of-two-sorted-arrays/description/
#
# algorithms
# Hard (30.86%)
# Likes: 9316
# Dislikes: 1441
# Total Accepted: 872.2K
# Total Submissions: 2.8M
# Testcase Example: '[1,3]\n[2]'
#
# Given two sor... | class Solution_Quickselect:
def find_median_sorted_arrays(self, nums1: List[int], nums2: List[int]) -> float:
nums = nums1[:] + nums2[:]
length = len(nums)
if length % 2 == 0:
return (self._quick_select(nums, 0, length - 1, length // 2 + 1) + self._quick_select(nums, 0, length -... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def recoverFromPreorder(self, S: str) -> TreeNode:
def dfs(parent, s, lev):
print(parent.val, s, lev)
if ... | class Solution:
def recover_from_preorder(self, S: str) -> TreeNode:
def dfs(parent, s, lev):
print(parent.val, s, lev)
if not s:
return
i = lev
l = 0
while i < len(s) and s[i].isdigit():
l = l * 10 + int(s[i])
... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
n=int(input())
country_name=set(input() for i in range(n))
print(len(country_name))
| n = int(input())
country_name = set((input() for i in range(n)))
print(len(country_name)) |
OP_CODES = {
"inp": 0,
"cla": 1,
"add": 2,
"tac": 3,
"sft": 4,
"out": 5,
"sto": 6,
"sub": 7,
"jmp": 8,
"hlt": 9,
"mul": 10,
"div": 11,
"noop": 12
}
class InstructionError(Exception):
pass
class Assembler(object):
def __init__(self, inputfile):
sel... | op_codes = {'inp': 0, 'cla': 1, 'add': 2, 'tac': 3, 'sft': 4, 'out': 5, 'sto': 6, 'sub': 7, 'jmp': 8, 'hlt': 9, 'mul': 10, 'div': 11, 'noop': 12}
class Instructionerror(Exception):
pass
class Assembler(object):
def __init__(self, inputfile):
self.contents = [line.rstrip('\n') for line in inputfile.re... |
PIPELINE = {
#'PIPELINE_ENABLED': True,
'STYLESHEETS': {
'global': {
'source_filenames': (
'foundation-sites/dist/foundation.min.css',
'pikaday/css/pikaday.css',
'jt.timepicker/jquery.timepicker.css',
'foundation-icon-fonts/foun... | pipeline = {'STYLESHEETS': {'global': {'source_filenames': ('foundation-sites/dist/foundation.min.css', 'pikaday/css/pikaday.css', 'jt.timepicker/jquery.timepicker.css', 'foundation-icon-fonts/foundation-icons.css', 'routes/css/routes.css'), 'output_filename': 'css/global.css', 'extra_context': {'media': 'screen,projec... |
#-------------------------------------------------------------------------
# Copyright (c) Microsoft. 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://ww... | class Resourcebase(object):
def __init__(self, **kwargs):
self._location = kwargs.get('location')
self._tags = kwargs.get('tags')
@property
def location(self):
"""
Gets the location of the resource.
"""
return self._location
@location.setter
def lo... |
#
# @lc app=leetcode id=430 lang=python3
#
# [430] Flatten a Multilevel Doubly Linked List
#
# @lc code=start
"""
# Definition for a Node.
class Node:
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
class Solution:... | """
# Definition for a Node.
class Node:
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
class Solution:
def flatten(self, head: 'Node') -> 'Node':
if not head:
return
save_ls = []
... |
TITLE = "Jump game"
WIDTH = 480
HEIGHT = 600
FPS = 30
WHITE = (255, 255, 255)
BLACK = (0,0,0)
RED = (240, 55, 66) | title = 'Jump game'
width = 480
height = 600
fps = 30
white = (255, 255, 255)
black = (0, 0, 0)
red = (240, 55, 66) |
class Tool:
def __init__(self, name, make):
self.name = name
self.make = make
| class Tool:
def __init__(self, name, make):
self.name = name
self.make = make |
colors = {
"bg0": " #fbf1c7",
"bg1": " #ebdbb2",
"bg2": " #d5c4a1",
"bg3": " #bdae93",
"bg4": " #a89984",
"gry": " #928374",
"fg4": " #7c6f64",
"fg3": " #665c54",
"fg2": " #504945",
"fg1": " #3c3836",
"fg0": " #282828",
"red": " #cc241d",
"red2": " #9d0006",
"oran... | colors = {'bg0': ' #fbf1c7', 'bg1': ' #ebdbb2', 'bg2': ' #d5c4a1', 'bg3': ' #bdae93', 'bg4': ' #a89984', 'gry': ' #928374', 'fg4': ' #7c6f64', 'fg3': ' #665c54', 'fg2': ' #504945', 'fg1': ' #3c3836', 'fg0': ' #282828', 'red': ' #cc241d', 'red2': ' #9d0006', 'orange': ' #d65d0e', 'orange2': ' #af3a03', 'yellow': ' #d799... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
result = ListNode(0)
result_tail = result
carry = 0
... | class Solution:
def add_two_numbers(self, l1: ListNode, l2: ListNode) -> ListNode:
result = list_node(0)
result_tail = result
carry = 0
while l1 or l2 or carry:
val1 = l1.val if l1 else 0
val2 = l2.val if l2 else 0
(carry, out) = divmod(val1 + val... |
class User:
"""
Class that generates new users login system
"""
def __init__(self,fullname, email, username, password):
self.fullname = fullname
self.email = email
self.username = username
self.password = password
user_list = []
def save_user(self)... | class User:
"""
Class that generates new users login system
"""
def __init__(self, fullname, email, username, password):
self.fullname = fullname
self.email = email
self.username = username
self.password = password
user_list = []
def save_user(self):
"""... |
budget = float(input())
season = str(input())
region = str()
final_budget = 0
accommodation = str()
if budget <= 100:
region = "Bulgaria"
if season == "summer":
accommodation = "Camp"
final_budget = budget * 0.7
else:
accommodation = "Hotel"
final_budget = budget * 0.30
eli... | budget = float(input())
season = str(input())
region = str()
final_budget = 0
accommodation = str()
if budget <= 100:
region = 'Bulgaria'
if season == 'summer':
accommodation = 'Camp'
final_budget = budget * 0.7
else:
accommodation = 'Hotel'
final_budget = budget * 0.3
elif 1... |
class RequestConnectionError(Exception):
pass
class ReferralError(Exception):
pass
class DataRegistryCaseUpdateError(Exception):
pass
| class Requestconnectionerror(Exception):
pass
class Referralerror(Exception):
pass
class Dataregistrycaseupdateerror(Exception):
pass |
class ATTR:
CAND_CSV = "cand_csv"
CANDIDATE = "candidate"
COLOR = "color"
CONFIRMED = "confirmed"
CSV_ENDING = ".csv"
EMAIL = "Email"
FIRST_NAME = "First Name"
LAST_NAME = "Last Name"
NEXT = "next"
NUM_BITBYTES = "num_bitbytes"
NUM_CONFIRMED = "num_confirmed"
NUM_PENDING ... | class Attr:
cand_csv = 'cand_csv'
candidate = 'candidate'
color = 'color'
confirmed = 'confirmed'
csv_ending = '.csv'
email = 'Email'
first_name = 'First Name'
last_name = 'Last Name'
next = 'next'
num_bitbytes = 'num_bitbytes'
num_confirmed = 'num_confirmed'
num_pending ... |
class PartOfSpeech:
NOUN = 'noun'
VERB = 'verb'
ADJECTIVE = 'adjective'
ADVERB = 'adverb'
pos2con = {
'n': [
'NN', 'NNS', 'NNP', 'NNPS', # from WordNet
'NP' # from PPDB
],
'v': [
'VB', 'VBD', 'VBG', 'VBN', 'VBZ', # from WordNet
... | class Partofspeech:
noun = 'noun'
verb = 'verb'
adjective = 'adjective'
adverb = 'adverb'
pos2con = {'n': ['NN', 'NNS', 'NNP', 'NNPS', 'NP'], 'v': ['VB', 'VBD', 'VBG', 'VBN', 'VBZ', 'VBP'], 'a': ['JJ', 'JJR', 'JJS', 'IN'], 's': ['JJ', 'JJR', 'JJS', 'IN'], 'r': ['RB', 'RBR', 'RBS']}
con2pos = {}
... |
def superTuple(name, attributes):
"""Creates a Super Tuple class."""
dct = {}
#Create __new__.
nargs = len(attributes)
def _new_(cls, *args):
if len(args) != nargs:
raise TypeError("%s takes %d arguments (%d given)." % (cls.__name__,
... | def super_tuple(name, attributes):
"""Creates a Super Tuple class."""
dct = {}
nargs = len(attributes)
def _new_(cls, *args):
if len(args) != nargs:
raise type_error('%s takes %d arguments (%d given).' % (cls.__name__, nargs, len(args)))
return tuple.__new__(cls, args)
d... |
my_first_name = str(input("My first name is "))
neighbor_first_name = str(input("My neighbor's first name is "))
my_coding = int(input("How many months have I been coding? "))
neighbor_coding = int(input("How many months has my neighbor been coding? "))
print("I am " + my_first_name + " and my neighbor is " + neighbor... | my_first_name = str(input('My first name is '))
neighbor_first_name = str(input("My neighbor's first name is "))
my_coding = int(input('How many months have I been coding? '))
neighbor_coding = int(input('How many months has my neighbor been coding? '))
print('I am ' + my_first_name + ' and my neighbor is ' + neighbor_... |
class MethodPropertyNotFoundError(Exception):
"""Exception to raise when a class is does not have an expected method or property."""
pass
class PipelineNotFoundError(Exception):
"""An exception raised when a particular pipeline is not found in automl search results"""
pass
class ObjectiveNotFoundE... | class Methodpropertynotfounderror(Exception):
"""Exception to raise when a class is does not have an expected method or property."""
pass
class Pipelinenotfounderror(Exception):
"""An exception raised when a particular pipeline is not found in automl search results"""
pass
class Objectivenotfounderror... |
data_nascimento = 9
mes_nascimento = 10
ano_nascimento = 1985
print(data_nascimento, mes_nascimento, ano_nascimento, sep="/", end=".\n")
contador = 1
while(contador <= 10):
print(contador)
contador = contador + 2
if(contador == 5):
contador = contador + 2
| data_nascimento = 9
mes_nascimento = 10
ano_nascimento = 1985
print(data_nascimento, mes_nascimento, ano_nascimento, sep='/', end='.\n')
contador = 1
while contador <= 10:
print(contador)
contador = contador + 2
if contador == 5:
contador = contador + 2 |
def even_spread(M, N):
"""Return a list of target sizes for an even spread.
Output sizes are either M//N or M//N+1
Args:
M: number of elements
N: number of partitons
Returns:
target_sizes : [int]
len(target_sizes) == N
sum(target_sizes) == M
"... | def even_spread(M, N):
"""Return a list of target sizes for an even spread.
Output sizes are either M//N or M//N+1
Args:
M: number of elements
N: number of partitons
Returns:
target_sizes : [int]
len(target_sizes) == N
sum(target_sizes) == M
"... |
BASE_URL = 'https://caseinfo.arcourts.gov/cconnect/PROD/public/'
### Search Results ###
PERSON_SUFFIX = 'ck_public_qry_cpty.cp_personcase_srch_details?backto=P&'
JUDGEMENT_SUFFIX = 'ck_public_qry_judg.cp_judgment_srch_rslt?'
CASE_SUFFIX = 'ck_public_qry_doct.cp_dktrpt_docket_report?backto=D&'
DATE_SUFFIX = 'ck_publi... | base_url = 'https://caseinfo.arcourts.gov/cconnect/PROD/public/'
person_suffix = 'ck_public_qry_cpty.cp_personcase_srch_details?backto=P&'
judgement_suffix = 'ck_public_qry_judg.cp_judgment_srch_rslt?'
case_suffix = 'ck_public_qry_doct.cp_dktrpt_docket_report?backto=D&'
date_suffix = 'ck_public_qry_doct.cp_dktrpt_new_c... |
value = 2 ** 1000
value_string = str(value)
value_sum = 0
for _ in value_string:
value_sum += int(_)
print(value_sum) | value = 2 ** 1000
value_string = str(value)
value_sum = 0
for _ in value_string:
value_sum += int(_)
print(value_sum) |
# parsetab.py
# This file is automatically generated. Do not edit.
# pylint: disable=W,C,R
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'leftplusminusnonassocadvdisadvadv dice disadv div minus newline number plus space star tabcommand : roll_list\n | mod_list\n ... | _tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'leftplusminusnonassocadvdisadvadv dice disadv div minus newline number plus space star tabcommand : roll_list\n | mod_list\n |\n roll_list : roll\n | roll roll_list\n roll : number d... |
output = 'Char\tisdigit\tisdecimal\tisnumeric'
html_output = '''<table border="1">
<thead>
<tr>
<th>Char</th>
<th>isdigit</th>
<th>isdecimal</th>
<th>isnumeric</th>
</tr>
</thead>
<tbody>'''
for i in range(1, 1114111):
if chr(i).isdigit() or chr(i).isdecimal() or chr(i).isnu... | output = 'Char\tisdigit\tisdecimal\tisnumeric'
html_output = '<table border="1">\n<thead>\n <tr>\n <th>Char</th>\n <th>isdigit</th>\n <th>isdecimal</th>\n <th>isnumeric</th>\n </tr>\n</thead>\n<tbody>'
for i in range(1, 1114111):
if chr(i).isdigit() or chr(i).isdecimal() or chr(i).... |
# question can be found at leetcode.com/problems/sqrtx/
# The original implementation does a Binary search
class Solution:
def mySqrt(self, x: int) -> int:
if x == 0 or x == 1:
return x
i, result = 1, 1
while result <= x:
i += 1
result = pow(i, 2)
... | class Solution:
def my_sqrt(self, x: int) -> int:
if x == 0 or x == 1:
return x
(i, result) = (1, 1)
while result <= x:
i += 1
result = pow(i, 2)
return i - 1 |
'''
Problem 13
@author: mat.000
'''
numbers = """37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676
89261670696623... | """
Problem 13
@author: mat.000
"""
numbers = '37107287533902102798797998220837590246510135740250\n46376937677490009712648124896970078050417018260538\n74324986199524741059474233309513058123726617309629\n91942213363574161572522430563301811072406154908250\n23067588207539346171171980310421047513778063246676\n892616706966... |
"""ct.py: Constant time(ish) functions"""
# WARNING: Pure Python is not amenable to the implementation of truly
# constant time cryptography. For more information, please see the
# "Security Notice" section in python/README.md.
def select(subject, result_if_one, result_if_zero):
# type: (int, int, int) -> int
... | """ct.py: Constant time(ish) functions"""
def select(subject, result_if_one, result_if_zero):
"""Perform a constant time(-ish) branch operation"""
return ~(subject - 1) & result_if_one | subject - 1 & result_if_zero |
# indices for weight, magnitude, and phase lists
M, P, W = 0, 1, 2
# Set max for model weighting. Minimum is 1.0
MAX_MODEL_WEIGHT = 100.0
# Rich text control for red font
RICH_TEXT_RED = "<FONT COLOR='red'>"
# Color definitions
# (see http://www.w3schools.com/tags/ref_colorpicker.asp )
M_COLOR = "#6f93ff" # magnitude... | (m, p, w) = (0, 1, 2)
max_model_weight = 100.0
rich_text_red = "<FONT COLOR='red'>"
m_color = '#6f93ff'
p_color = '#ffcc00'
dm_color = '#3366ff'
dp_color = '#b38f00'
dw_color = '#33cc33'
mm_color = '000000'
mp_color = '000000'
mm_style = '-'
mp_style = '--'
allow_neg = True
param_file = 'params.csv'
editor = 'notepad++... |
# Lost Memories Found [Hayato] (57172)
recoveredMemory = 7081
mouriMotonari = 9130008
sm.setSpeakerID(mouriMotonari)
sm.sendNext("I've been watching you fight for Maple World, Hayato. "
"Your dedication is impressive.")
sm.sendSay("I, Mouri Motonari, hope that you will call me an ally. "
"The two of us have a great ... | recovered_memory = 7081
mouri_motonari = 9130008
sm.setSpeakerID(mouriMotonari)
sm.sendNext("I've been watching you fight for Maple World, Hayato. Your dedication is impressive.")
sm.sendSay('I, Mouri Motonari, hope that you will call me an ally. The two of us have a great future together.')
sm.sendSay('Continue your q... |
"""
##################################################################################################
# Copyright Info : Copyright (c) Davar Lab @ Hikvision Research Institute. All rights reserved.
# Filename : test_base_setting.py
# Abstract : Base recognition Model test setting
# Current Versio... | """
##################################################################################################
# Copyright Info : Copyright (c) Davar Lab @ Hikvision Research Institute. All rights reserved.
# Filename : test_base_setting.py
# Abstract : Base recognition Model test setting
# Current Versio... |
def enc():
code=input('Write what you want to encrypt: ')
new_code_1=''
for i in range(0,len(code)-1,1):
new_code_1=new_code_1+code[i+1]
new_code_1=new_code_1+code[i]
print(new_code_1)
def dec():
code=input('Write what you want to deccrypt: ')
new_code=''
if len(cod... | def enc():
code = input('Write what you want to encrypt: ')
new_code_1 = ''
for i in range(0, len(code) - 1, 1):
new_code_1 = new_code_1 + code[i + 1]
new_code_1 = new_code_1 + code[i]
print(new_code_1)
def dec():
code = input('Write what you want to deccrypt: ')
new_code = ''
... |
class Node:
def __init__(self, key):
self.data = key
self.left = None
self.right = None
def getNodeCount(root : Node) -> int:
if root is None:
return 0
count = 0
count += 1
count += (getNodeCount(root.left) + getNodeCount(root.right))
return count
if __name__... | class Node:
def __init__(self, key):
self.data = key
self.left = None
self.right = None
def get_node_count(root: Node) -> int:
if root is None:
return 0
count = 0
count += 1
count += get_node_count(root.left) + get_node_count(root.right)
return count
if __name__... |
# Copyright 2021 The gRPC Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | """
Contains generic helper utilities.
"""
_upper_segments_list = ['url', 'http', 'https']
def strip_extension(str):
return str.rpartition('.')[0]
def capitalize(word):
if word in _upper_segments_list:
return word.upper()
else:
return word.capitalize()
def lower_underscore_to_upper_camel(... |
"""Possible user action events"""
EVENT_BROWSE_FILES = "BrowseFiles"
EVENT_DELETE_SONG = "DeleteSong"
EVENT_PLAY_SONG = "PlaySong"
EVENT_SELECT_SONGS = "SelectSingleSong"
EVENT_CREATE_PLAYLIST = "CreatePlaylist"
EVENT_DELETE_PLAYLIST = "DeletePlaylist"
EVENT_SELECT_PLAYLIST = "SelectPlaylist"
EVENT_PLAY_PLAYLIST = "Pla... | """Possible user action events"""
event_browse_files = 'BrowseFiles'
event_delete_song = 'DeleteSong'
event_play_song = 'PlaySong'
event_select_songs = 'SelectSingleSong'
event_create_playlist = 'CreatePlaylist'
event_delete_playlist = 'DeletePlaylist'
event_select_playlist = 'SelectPlaylist'
event_play_playlist = 'Pla... |
# import torch
# import torch.nn as nn
# import numpy as np
class NetworkFit(object):
def __init__(self, model, optimizer, soft_criterion):
self.model = model
self.optimizer = optimizer
self.soft_criterion = soft_criterion
def train(self, inputs, labels):
self.optimizer.zero_... | class Networkfit(object):
def __init__(self, model, optimizer, soft_criterion):
self.model = model
self.optimizer = optimizer
self.soft_criterion = soft_criterion
def train(self, inputs, labels):
self.optimizer.zero_grad()
self.model.train()
outputs = self.model... |
#!/usr/bin/python3
def no_c(my_string):
newStr = ""
for i in range(len(my_string)):
if my_string[i] != "c" and my_string[i] != "C":
newStr += my_string[i]
return (newStr)
| def no_c(my_string):
new_str = ''
for i in range(len(my_string)):
if my_string[i] != 'c' and my_string[i] != 'C':
new_str += my_string[i]
return newStr |
height = int(input())
for i in range(1, height + 1):
for j in range(1, height + 1):
if(i == 1 or i == height or j == 1 or j == height):
print(1,end=" ")
else:
print(0,end=" ")
print()
# Sample Input :- 5
# Output :-
# 1 1 1 1 1
# 1 0 0 0 1
# 1 0 0 ... | height = int(input())
for i in range(1, height + 1):
for j in range(1, height + 1):
if i == 1 or i == height or j == 1 or (j == height):
print(1, end=' ')
else:
print(0, end=' ')
print() |
class Trie(object):
def __init__(self):
self.root = TrieNode()
def add(self, word):
"""
Add `word` to trie
"""
current_node = self.root
for char in word:
current_node = current_node.children[char]
current_node.is_word = True
def exi... | class Trie(object):
def __init__(self):
self.root = trie_node()
def add(self, word):
"""
Add `word` to trie
"""
current_node = self.root
for char in word:
current_node = current_node.children[char]
current_node.is_word = True
def exi... |
input = """
p(1) :- #count{X:q(X)}=1.
q(X) :- p(X).
"""
output = """
p(1) :- #count{X:q(X)}=1.
q(X) :- p(X).
"""
| input = '\np(1) :- #count{X:q(X)}=1.\nq(X) :- p(X).\n'
output = '\np(1) :- #count{X:q(X)}=1.\nq(X) :- p(X).\n' |
def _find_patterns(content, pos, patterns):
max = len(content)
for i in range(pos, max):
for p in enumerate(patterns):
if content.startswith(p[1], i):
return struct(
pos = i,
pattern = p[0]
)
return None
_find_endi... | def _find_patterns(content, pos, patterns):
max = len(content)
for i in range(pos, max):
for p in enumerate(patterns):
if content.startswith(p[1], i):
return struct(pos=i, pattern=p[0])
return None
_find_ending_escapes = {'(': ')', '"': '"', "'": "'", '{': '}'}
def _find... |
# Time: O(n)
# Space: O(n)
# 946
# Given two sequences pushed and popped with distinct values, return true if and only if this could have been the
# result of a sequence of push and pop operations on an initially empty stack.
# 0 <= pushed.length == popped.length <= 1000
# 0 <= pushed[i], popped[i] < 1000
# pushed i... | class Solution(object):
def validate_stack_sequences(self, pushed, popped):
"""
:type pushed: List[int]
:type popped: List[int]
:rtype: bool
"""
j = 0
stk = []
for v in pushed:
stk.append(v)
while stk and stk[-1] == popped[j]:
... |
def num_of_likes(names):
if len(names) == 0:
return 'no one likes this'
elif len(names) == 1:
return names[0] + ' likes this'
elif len(names) == 2:
return names[0] + ' and ' + names[1] + ' like this'
elif len(names) == 3:
return names[0] + ', ' + names[1] + ' and ' + nam... | def num_of_likes(names):
if len(names) == 0:
return 'no one likes this'
elif len(names) == 1:
return names[0] + ' likes this'
elif len(names) == 2:
return names[0] + ' and ' + names[1] + ' like this'
elif len(names) == 3:
return names[0] + ', ' + names[1] + ' and ' + name... |
def singleton(theClass):
""" decorator for a class to make a singleton out of it """
classInstances = {}
def getInstance(*args, **kwargs):
""" creating or just return the one and only class instance.
The singleton depends on the parameters used in __init__ """
key = (theClass, a... | def singleton(theClass):
""" decorator for a class to make a singleton out of it """
class_instances = {}
def get_instance(*args, **kwargs):
""" creating or just return the one and only class instance.
The singleton depends on the parameters used in __init__ """
key = (theClass,... |
"""
These are functions that create a sequence by adding the first number to the
second number and then adding the third number to the second, and so on.
"""
def fibonacci(n):
"""
This function assumed the first number is 0 and the second number is 1.
fibonacci(nth number in sequence you want returned)
... | """
These are functions that create a sequence by adding the first number to the
second number and then adding the third number to the second, and so on.
"""
def fibonacci(n):
"""
This function assumed the first number is 0 and the second number is 1.
fibonacci(nth number in sequence you want returned)
... |
def is_none_us_symbol(symbol: str) -> bool:
return symbol.endswith(".HK") or symbol.endswith(".SZ") or symbol.endswith(".SH")
def is_us_symbol(symbol: str) -> bool:
return not is_none_us_symbol(symbol)
| def is_none_us_symbol(symbol: str) -> bool:
return symbol.endswith('.HK') or symbol.endswith('.SZ') or symbol.endswith('.SH')
def is_us_symbol(symbol: str) -> bool:
return not is_none_us_symbol(symbol) |
# table definition
table = {
'table_name' : 'adm_functions',
'module_id' : 'adm',
'short_descr' : 'Functions',
'long_descr' : 'Functional breakdwon of the organisation',
'sub_types' : None,
'sub_trans' : None,
'sequence' : ['seq', ['parent_id'], None],
'tree_para... | table = {'table_name': 'adm_functions', 'module_id': 'adm', 'short_descr': 'Functions', 'long_descr': 'Functional breakdwon of the organisation', 'sub_types': None, 'sub_trans': None, 'sequence': ['seq', ['parent_id'], None], 'tree_params': [None, ['function_id', 'descr', 'parent_id', 'seq'], ['function_type', [['root'... |
# Commutable Islands
#
# There are n islands and there are many bridges connecting them. Each bridge has
# some cost attached to it.
#
# We need to find bridges with minimal cost such that all islands are connected.
#
# It is guaranteed that input data will contain at least one possible scenario in which
# all islands ... | class Solution:
class Edges(list):
def __lt__(self, other):
for i in [2, 0, 1]:
if self[i] == other[i]:
continue
return self[i] < other[i]
class Disjoinset:
def __init__(self, i):
self.parent = i
self.lvl... |
x=[2,25,34,56,72,34,54]
val=int(input("Enter the value you want to get searched : "))
for i in x:
if i==val:
print(x.index(i))
break
elif x.index(i)==(len(x)-1) and i!=val:
print("The Val u want to search is not there in the list")
| x = [2, 25, 34, 56, 72, 34, 54]
val = int(input('Enter the value you want to get searched : '))
for i in x:
if i == val:
print(x.index(i))
break
elif x.index(i) == len(x) - 1 and i != val:
print('The Val u want to search is not there in the list') |
# subsequence: a sequence that can be derived from another sequence by deleting one or more elements,
# without changing the order
# unlike substrings, subsequences are not required to occupy consecutive positions within the parent sequence
# so ACE is a valid subsequence of ABCDE
# find the length of the longest comm... | def longest_common_subsequence(s1, s2, i1=0, i2=0):
if i1 >= len(s1) or i2 >= len(s2):
return 0
if s1[i1] == s2[i2]:
return 1 + longest_common_subsequence(s1, s2, i1 + 1, i2 + 1)
branch_1 = longest_common_subsequence(s1, s2, i1, i2 + 1)
branch_2 = longest_common_subsequence(s1, s2, i1 + ... |
"""Constants for the Purple Air integration."""
AQI_BREAKPOINTS = {
'pm2_5': [
{ 'pm_low': 500.5, 'pm_high': 999.9, 'aqi_low': 501, 'aqi_high': 999 },
{ 'pm_low': 350.5, 'pm_high': 500.4, 'aqi_low': 401, 'aqi_high': 500 },
{ 'pm_low': 250.5, 'pm_high': 350.4, 'aqi_low': 301, 'aqi_high': 400... | """Constants for the Purple Air integration."""
aqi_breakpoints = {'pm2_5': [{'pm_low': 500.5, 'pm_high': 999.9, 'aqi_low': 501, 'aqi_high': 999}, {'pm_low': 350.5, 'pm_high': 500.4, 'aqi_low': 401, 'aqi_high': 500}, {'pm_low': 250.5, 'pm_high': 350.4, 'aqi_low': 301, 'aqi_high': 400}, {'pm_low': 150.5, 'pm_high': 250.... |
# Input: arr[] = {1, 20, 2, 10}
# Output: 72
def single_rotation(arr,l):
temp=arr[0]
for i in range(l-1):
arr[i]=arr[i+1]
arr[l-1]=temp
def sum_calculate(arr,l):
sum=0
for i in range(l):
sum=sum+arr[i]*(i)
return sum
def max_finder(arr,l):
max=arr[0]
for i in range(l):... | def single_rotation(arr, l):
temp = arr[0]
for i in range(l - 1):
arr[i] = arr[i + 1]
arr[l - 1] = temp
def sum_calculate(arr, l):
sum = 0
for i in range(l):
sum = sum + arr[i] * i
return sum
def max_finder(arr, l):
max = arr[0]
for i in range(l):
if max < arr[i... |
class UsageError(Exception):
"""Error in plugin usage."""
__module__ = "builtins"
| class Usageerror(Exception):
"""Error in plugin usage."""
__module__ = 'builtins' |
"""Constants for the Nuvo Multi-zone Amplifier Media Player component."""
DOMAIN = "nuvo_serial"
CONF_ZONES = "zones"
CONF_SOURCES = "sources"
ZONE = "zone"
SOURCE = "source"
CONF_SOURCE_1 = "source_1"
CONF_SOURCE_2 = "source_2"
CONF_SOURCE_3 = "source_3"
CONF_SOURCE_4 = "source_4"
CONF_SOURCE_5 = "source_5"
CONF_SO... | """Constants for the Nuvo Multi-zone Amplifier Media Player component."""
domain = 'nuvo_serial'
conf_zones = 'zones'
conf_sources = 'sources'
zone = 'zone'
source = 'source'
conf_source_1 = 'source_1'
conf_source_2 = 'source_2'
conf_source_3 = 'source_3'
conf_source_4 = 'source_4'
conf_source_5 = 'source_5'
conf_sourc... |
# Script will correct .hoc file from neuromorpho.org.
# In order to make the correction, same data is needed from
# Neuron's import3D tool.
# CNS-GROUP, Tampere University
def fix_commas(IMPORT3D_FILE, _3DVIEWER_FILE):
"""
This will correct commas, change "user7" to "dendrite"
and will seek "OrginalDen... | def fix_commas(IMPORT3D_FILE, _3DVIEWER_FILE):
"""
This will correct commas, change "user7" to "dendrite"
and will seek "OrginalDendrite" value. Returns False if
there was a problem opening the file.
:return orgdend = OrginalDendrite
"""
k = 0
a = 0
orgdend = 'Error'
try:
... |
# program checks if the string is palindrome or not.
def function(string):
if(string == string[:: - 1]):
print("This is a Palindrome String")
else:
print("This is Not a Palindrome String")
string = input("Please enter your own String : ")
function(string)
| def function(string):
if string == string[::-1]:
print('This is a Palindrome String')
else:
print('This is Not a Palindrome String')
string = input('Please enter your own String : ')
function(string) |
#!/usr/bin/env python
# coding: utf8
""" Pythonic Redis backed data structure """
__version__ = '1.0.0'
__authors__ = 'Felix Voituret <felix@voituret.fr>'
| """ Pythonic Redis backed data structure """
__version__ = '1.0.0'
__authors__ = 'Felix Voituret <felix@voituret.fr>' |
_base_ = './deit-small_pt-4xb256_in1k.py'
# model settings
model = dict(
backbone=dict(type='DistilledVisionTransformer', arch='deit-base'),
head=dict(type='DeiTClsHead', in_channels=768),
)
# data settings
data = dict(samples_per_gpu=64, workers_per_gpu=5)
| _base_ = './deit-small_pt-4xb256_in1k.py'
model = dict(backbone=dict(type='DistilledVisionTransformer', arch='deit-base'), head=dict(type='DeiTClsHead', in_channels=768))
data = dict(samples_per_gpu=64, workers_per_gpu=5) |
class Solution:
def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:
h = {v: i for i, v in enumerate(list1)}
result = []
m = inf
for i, v in enumerate(list2):
if v in h:
r = h[v] + i
if r < m:
m = r... | class Solution:
def find_restaurant(self, list1: List[str], list2: List[str]) -> List[str]:
h = {v: i for (i, v) in enumerate(list1)}
result = []
m = inf
for (i, v) in enumerate(list2):
if v in h:
r = h[v] + i
if r < m:
... |
#
# This helps us not have to pass so many things (caches, resolvers,
# transcoders...) around by letting us set class properties on the IIIFRequest
# at startup. Here's a basic example of how this pattern works:
#
# >>> class MyMeta(type): # Note we subclass type, not object
# ... _something = None
# ... def _... | class Metarequest(type):
_compliance = None
_info_cache = None
_extractors = None
_app_configs = None
_transcoders = None
_resolvers = None
def _get_compliance(self):
return self._compliance
def _set_compliance(self, compliance):
self._compliance = compliance
compli... |
def anderson_iteration(X, U, V, labels, p, logger):
def multi_update_V(V, U, X):
delta_V = 100
while delta_V > 1e-1:
new_V = update_V(V, U, X, epsilon)
delta_V = l21_norm(new_V - V)
V = new_V
return V
V_len = V.flatten().shape[0]
mAA = 0
V... | def anderson_iteration(X, U, V, labels, p, logger):
def multi_update_v(V, U, X):
delta_v = 100
while delta_V > 0.1:
new_v = update_v(V, U, X, epsilon)
delta_v = l21_norm(new_V - V)
v = new_V
return V
v_len = V.flatten().shape[0]
m_aa = 0
v_old... |
"""Set metadata for chat-downloader"""
__title__ = 'chat-downloader'
__program__ = 'chat_downloader'
__summary__ = 'A simple tool used to retrieve chat messages from livestreams, videos, clips and past broadcasts. No authentication needed!'
__author__ = 'xenova'
__email__ = 'admin@xenova.com'
__copyright__ = '2020, 20... | """Set metadata for chat-downloader"""
__title__ = 'chat-downloader'
__program__ = 'chat_downloader'
__summary__ = 'A simple tool used to retrieve chat messages from livestreams, videos, clips and past broadcasts. No authentication needed!'
__author__ = 'xenova'
__email__ = 'admin@xenova.com'
__copyright__ = '2020, 202... |
def move(cc, order, value):
if order == "N":
cc[1] += value
if order == "S":
cc[1] -= value
if order == "E":
cc[0] += value
if order == "W":
cc[0] -= value
return cc
def stage1(inp):
direct = ["S", "W", "N", "E"]
facing = "E"
current_coord = [0, 0]
... | def move(cc, order, value):
if order == 'N':
cc[1] += value
if order == 'S':
cc[1] -= value
if order == 'E':
cc[0] += value
if order == 'W':
cc[0] -= value
return cc
def stage1(inp):
direct = ['S', 'W', 'N', 'E']
facing = 'E'
current_coord = [0, 0]
fo... |
A = int(input('Enter the value of A: '))
B = int(input('Enter the value of B: '))
#A = int(A)
#B = int(B)
C = A
A = B
B = C
print('Value of A', A, 'Value of B', B)
| a = int(input('Enter the value of A: '))
b = int(input('Enter the value of B: '))
c = A
a = B
b = C
print('Value of A', A, 'Value of B', B) |
# Input:
# 1
# 8
# 1 2 2 4 5 6 7 8
#
# Output:
# 2 1 4 2 6 5 8 7
def pairWiseSwap(head):
if head == None or head.next == None:
return head
prev = None
cur = head
count = 2
while count > 0 and cur != None:
temp = cur.next
cur.next = prev
prev = cur
cur = te... | def pair_wise_swap(head):
if head == None or head.next == None:
return head
prev = None
cur = head
count = 2
while count > 0 and cur != None:
temp = cur.next
cur.next = prev
prev = cur
cur = temp
count -= 1
head.next = pair_wise_swap(cur)
retur... |
#!/usr/bin/env python
#
# Test function for sct_dmri_concat_b0_and_dwi
#
# Copyright (c) 2019 Polytechnique Montreal <www.neuro.polymtl.ca>
# Author: Julien Cohen-Adad
#
# About the license: see the file LICENSE.TXT
def init(param_test):
"""
Initialize class: param_test
"""
# initialization
defaul... | def init(param_test):
"""
Initialize class: param_test
"""
default_args = ['-i dmri/dmri_T0000.nii.gz dmri/dmri.nii.gz -bvec dmri/bvecs.txt -bval dmri/bvals.txt -order b0 dwi -o b0_dwi_concat.nii -obval bvals_concat.txt -obvec bvecs_concat.txt']
if not param_test.args:
param_test.args = defa... |
a = 5 > 3
b = 5 > 4
c = 5 > 5
d = 5 > 6
e = 5 > 7
| a = 5 > 3
b = 5 > 4
c = 5 > 5
d = 5 > 6
e = 5 > 7 |
names = []
startingletter = ""
# Open file and getting all names from it
with open("./Input/Names/invited_names.txt") as file:
for line in file:
names.append(line.strip())
# Getting the text from the starting letter
with open("./Input/Letters/starting_letter.txt") as file:
startingletter = file.read()... | names = []
startingletter = ''
with open('./Input/Names/invited_names.txt') as file:
for line in file:
names.append(line.strip())
with open('./Input/Letters/starting_letter.txt') as file:
startingletter = file.read()
for name in names:
with open(f'./Output/ReadyToSend/letter_for_{name}', 'w') as rea... |
def Counting_Sort(A, k=-1):
if(k==-1): k=max(A)
C = [0 for x in range(k+1)]
for x in A: C[x]+=1
for x in range(1, k+1):C[x]+=C[x-1]
B = [0 for x in range(len(A))]
for i in range(len(A)-1, -1, -1):
x = A[i]
B[C[x]-1] = x
C[x]-=1
return B
A = [13,20,18,20,12,15,7]
print(Counting_Sort(A))
| def counting__sort(A, k=-1):
if k == -1:
k = max(A)
c = [0 for x in range(k + 1)]
for x in A:
C[x] += 1
for x in range(1, k + 1):
C[x] += C[x - 1]
b = [0 for x in range(len(A))]
for i in range(len(A) - 1, -1, -1):
x = A[i]
B[C[x] - 1] = x
C[x] -= 1... |
class Solution:
def minWindow(self, s: str, t: str) -> str:
target, window = defaultdict(int), defaultdict(int)
left, right, match = 0, 0, 0
d = float("inf")
for c in t:
target[c] += 1
while right < len(s):
c = s[right]
if c in target:
... | class Solution:
def min_window(self, s: str, t: str) -> str:
(target, window) = (defaultdict(int), defaultdict(int))
(left, right, match) = (0, 0, 0)
d = float('inf')
for c in t:
target[c] += 1
while right < len(s):
c = s[right]
if c in ta... |
# From: http://wiki.python.org/moin/SimplePrograms, with permission from the author, Steve Howell
BOARD_SIZE = 8
def under_attack(col, queens):
return col in queens or \
any(abs(col - x) == len(queens)-i for i,x in enumerate(queens))
def solve(n):
solutions = [[]]
for row in range(n):
s... | board_size = 8
def under_attack(col, queens):
return col in queens or any((abs(col - x) == len(queens) - i for (i, x) in enumerate(queens)))
def solve(n):
solutions = [[]]
for row in range(n):
solutions = [solution + [i + 1] for solution in solutions for i in range(BOARD_SIZE) if not under_attack(... |
# -*- coding: utf-8 -*-
""" VITA Person Registry, Controllers
@author: nursix
@see: U{http://eden.sahanafoundation.org/wiki/BluePrintVITA}
"""
prefix = request.controller
resourcename = request.function
# -----------------------------------------------------------------------------
# Options Menu (availabl... | """ VITA Person Registry, Controllers
@author: nursix
@see: U{http://eden.sahanafoundation.org/wiki/BluePrintVITA}
"""
prefix = request.controller
resourcename = request.function
def shn_menu():
response.menu_options = [[t('Home'), False, url(r=request, f='index')], [t('Search for a Person'), False, url(... |
#!/usr/bin/env python3
# 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.
INITIAL_DATA_TO_COMPLETE = [
'valid_0',
'valid_1',
'valid_10',
'valid_100',
'valid_101',
'valid... | initial_data_to_complete = ['valid_0', 'valid_1', 'valid_10', 'valid_100', 'valid_101', 'valid_102', 'valid_103', 'valid_105', 'valid_106', 'valid_107', 'valid_108', 'valid_109', 'valid_11', 'valid_110', 'valid_111', 'valid_112', 'valid_115', 'valid_116', 'valid_117', 'valid_119', 'valid_12', 'valid_120', 'valid_121', ... |
def inicio():
print ("--PRINCIPAL--")
print("1. AGREGAR")
print("2. ELIMINAR")
print("3. VER")
opc = input ("------> ")
return opc
| def inicio():
print('--PRINCIPAL--')
print('1. AGREGAR')
print('2. ELIMINAR')
print('3. VER')
opc = input('------> ')
return opc |
n, m = map(int, input().strip().split())
matrix = [list(map(int, input().strip().split())) for _ in range(n)]
k = int(input().strip())
for lst in sorted(matrix, key=lambda l: l[k]):
print(*lst)
| (n, m) = map(int, input().strip().split())
matrix = [list(map(int, input().strip().split())) for _ in range(n)]
k = int(input().strip())
for lst in sorted(matrix, key=lambda l: l[k]):
print(*lst) |
Nsweeps = 100
size = 32
for beta in [0.1, 0.8, 1.6]:
g = Grid(size, beta)
m = g.do_sweeps(0, Nsweeps)
grid = g.cells
mag = g.magnetisation(grid)
e_plus = np.zeros((size, size))
e_minus = np.zeros((size, size))
for i in np.arange(size):
for j in np.arange(size):
e_plus[i,... | nsweeps = 100
size = 32
for beta in [0.1, 0.8, 1.6]:
g = grid(size, beta)
m = g.do_sweeps(0, Nsweeps)
grid = g.cells
mag = g.magnetisation(grid)
e_plus = np.zeros((size, size))
e_minus = np.zeros((size, size))
for i in np.arange(size):
for j in np.arange(size):
(e_plus[i,... |
class Listing:
def extrem(self, nvar1="", nvar2="", ninc="", **kwargs):
"""Lists the extreme values for variables.
APDL Command: EXTREM
Parameters
----------
nvar1, nvar2, ninc
List extremes for variables NVAR1 through NVAR2 in steps of NINC.
Variab... | class Listing:
def extrem(self, nvar1='', nvar2='', ninc='', **kwargs):
"""Lists the extreme values for variables.
APDL Command: EXTREM
Parameters
----------
nvar1, nvar2, ninc
List extremes for variables NVAR1 through NVAR2 in steps of NINC.
Variab... |
load("@rules_maven_third_party//:import_external.bzl", import_external = "import_external")
def dependencies():
import_external(
name = "org_apache_maven_resolver_maven_resolver_api",
artifact = "org.apache.maven.resolver:maven-resolver-api:1.4.0",
artifact_sha256 = "85aac254240e8bf387d737a... | load('@rules_maven_third_party//:import_external.bzl', import_external='import_external')
def dependencies():
import_external(name='org_apache_maven_resolver_maven_resolver_api', artifact='org.apache.maven.resolver:maven-resolver-api:1.4.0', artifact_sha256='85aac254240e8bf387d737acf5fcd18f07163ae55a0223b107c7e2af... |
# Generic uwsgi_param headers
CONTENT_LENGTH = 'CONTENT_LENGTH'
CONTENT_TYPE = 'CONTENT_TYPE'
DOCUMENT_ROOT = 'DOCUMENT_ROOT'
QUERY_STRING = 'QUERY_STRING'
PATH_INFO = 'PATH_INFO'
REMOTE_ADDR = 'REMOTE_ADDR'
REMOTE_PORT = 'REMOTE_PORT'
REQUEST_METHOD = 'REQUEST_METHOD'
REQUEST_URI = 'REQUEST_URI'
SERVER_ADDR = 'SERVER... | content_length = 'CONTENT_LENGTH'
content_type = 'CONTENT_TYPE'
document_root = 'DOCUMENT_ROOT'
query_string = 'QUERY_STRING'
path_info = 'PATH_INFO'
remote_addr = 'REMOTE_ADDR'
remote_port = 'REMOTE_PORT'
request_method = 'REQUEST_METHOD'
request_uri = 'REQUEST_URI'
server_addr = 'SERVER_ADDR'
server_name = 'SERVER_NA... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.