code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
import functools import itertools import multiprocessing import random from chemate.board import Board from chemate.core import Position , Player , Movement class DecisionTree extends object begin set _central = list call from_char string d4 call from_char string e4 call from_char string d5 call from_char string e5 str...
import functools import itertools import multiprocessing import random from chemate.board import Board from chemate.core import Position, Player, Movement class DecisionTree(object): _central = [Position.from_char('d4'), Position.from_char('e4'), Position.from_char('d5'), ...
Python
zaydzuhri_stack_edu_python
comment !/bin/python3 import math import os import random import re import sys function counter fruit s t begin set cnt = 0 for i in fruit begin if i >= s and i <= t begin set cnt = cnt + 1 end end return cnt end function function countApplesAndOranges s t a b apples oranges begin for i in range length apples begin set...
#!/bin/python3 import math import os import random import re import sys def counter(fruit,s,t): cnt = 0 for i in fruit: if i>=s and i<=t: cnt += 1 return cnt def countApplesAndOranges(s, t, a, b, apples, oranges): for i in range(len(apples)): appl...
Python
zaydzuhri_stack_edu_python
function ocr_conf_mean bts dpi=150 begin comment pdf handler set pages = call convert_from_bytes bts dpi=dpi set str_list = list for i in range length pages begin comment for multi-page pdfs: concatenate each pages data to one list set page_data = call image_to_data pages at i if i == 0 begin comment keep the column n...
def ocr_conf_mean(bts: bytes, dpi=150): # pdf handler pages = convert_from_bytes(bts, dpi=dpi) str_list = [] for i in range(len(pages)): # for multi-page pdfs: concatenate each pages data to one list page_data = pytesseract.image_to_data(pages[i]) if i == 0: # keep t...
Python
nomic_cornstack_python_v1
function transpose_matrix self a begin if not a begin return list list end set n = length a at 0 set m = length a set u = list for i in range n begin set v = list for j in range m begin append v a at j at i end append u v end return u end function
def transpose_matrix(self, a): if not a: return list(list()) n = len(a[0]) m = len(a) u = list() for i in range(n): v = list() for j in range(m): v.append(a[j][i]) u.append(v) return u
Python
nomic_cornstack_python_v1
import unittest import hail as hl from src.plotgen.table_utils import TableUtils class TableUtilsSuite extends TestCase begin function setUp self begin pass end function function test_check_schema self begin set ht = call range_table 4 assert true call check_schema ht list string idx assert false call check_schema ht l...
import unittest import hail as hl from src.plotgen.table_utils import TableUtils class TableUtilsSuite(unittest.TestCase): def setUp(self): pass def test_check_schema(self): ht = hl.utils.range_table(4) self.assertTrue(TableUtils.check_schema(ht, ['idx'])) self.assertFalse(Tab...
Python
zaydzuhri_stack_edu_python
function get_extremist_network Nx Dx begin set N = zeros list Nx Nx dtype=int comment Iterate over the upper diagonal only for i in range 0 Nx begin for j in range i + 1 Nx begin comment r is in [0.0, 1.0) set r = random if r <= Dx begin set N at i at j = 1 set N at j at i = 1 end end end return N end function
def get_extremist_network(Nx, Dx): N = np.zeros([Nx, Nx], dtype=int) for i in range(0, Nx): # Iterate over the upper diagonal only for j in range(i+1, Nx): r = rg.random() # r is in [0.0, 1.0) if r <= Dx: N[i][j] = 1 N[j][i] = 1 return N
Python
nomic_cornstack_python_v1
function rotate self matrix tol=0.001 begin string Applies a rotation directly, and tests input matrix to ensure a valid rotation. Args: matrix (3x3 array-like): rotation matrix to be applied to tensor tol (float): tolerance for testing rotation matrix validity set matrix = call SquareTensor matrix if not call is_rotat...
def rotate(self, matrix, tol=1e-3): """ Applies a rotation directly, and tests input matrix to ensure a valid rotation. Args: matrix (3x3 array-like): rotation matrix to be applied to tensor tol (float): tolerance for testing rotation matrix validity """ ...
Python
jtatman_500k
function fToC temp begin return temp - 32 * 5 / 9 end function
def fToC(temp): return (temp-32)*5/9
Python
nomic_cornstack_python_v1
for i in range 2 n + 1 begin set nth = t1 + t2 print nth end=string , set t1 = t2 set t2 = nth end
for i in range(2,n+1): nth=t1+t2 print(nth,end=',') t1=t2 t2=nth
Python
zaydzuhri_stack_edu_python
string Encapsulamento º Encapsulamento diz respeito à proteção dos atributos ou métodos de uma classe º Consiste em separar aspectos externos de um objeto dos detalhes internos de implementação º Evita que dados específicos de uma aplicação possa ser acessado diretamente Em Python, ao aplicar o conceito de encapsulamen...
""" Encapsulamento º Encapsulamento diz respeito à proteção dos atributos ou métodos de uma classe º Consiste em separar aspectos externos de um objeto dos detalhes internos de implementação º Evita que dados específicos de uma aplicação possa ser acessado diretamente Em Python, ao aplicar o conceito de encapsulamento...
Python
zaydzuhri_stack_edu_python
import unittest from Ejercicio2 import verificaExtension class VerificaExtensionTestCase extends TestCase begin function test_envio_cadena_txt_lista_sin_txt_devuelve_false self begin assert equal false call verificaExtension string /home/user/listado.txt list string mp3 string wav string mpeg end function function test...
import unittest from Ejercicio2 import verificaExtension class VerificaExtensionTestCase(unittest.TestCase): def test_envio_cadena_txt_lista_sin_txt_devuelve_false(self): self.assertEqual(False, verificaExtension('/home/user/listado.txt',['mp3','wav','mpeg'])) def test_envio_cadena_txt_lista_txt_devu...
Python
zaydzuhri_stack_edu_python
function get_move_positions move begin set move_positions = list for tuple xi yi in orientation begin set tuple x y = tuple xi + x yi + y append move_positions tuple y x end return move_positions end function
def get_move_positions(move): move_positions = [] for (xi, yi) in move.orientation: (x, y) = (xi + move.x, yi + move.y) move_positions.append((y, x)) return move_positions
Python
nomic_cornstack_python_v1
from pymongo import MongoClient from collections import Counter from general import cleaning from stemming.porter2 import stem set client = call MongoClient set db = webSE set docs = find data dict comment print(docs[0]) set title_combined = list for doc in docs begin set title = doc at string title set title_clean = ...
from pymongo import MongoClient from collections import Counter from general import cleaning from stemming.porter2 import stem client = MongoClient() db=client.webSE docs=db.data.find({}) #print(docs[0]) title_combined=[] for doc in docs: title=doc['title'] title_clean = cleaning(title) for word in title...
Python
zaydzuhri_stack_edu_python
import tkFileDialog import sys function main begin set infile = length argv > 1 and argv at 1 or call askopenfilename title=string Select input file initialdir=string . filetypes=list tuple string Input string .in set outfile = replace infile string .in string .out 1 end function
import tkFileDialog import sys def main(): infile = (len(sys.argv) > 1 and sys.argv[1]) or tkFileDialog.askopenfilename(title="Select input file", initialdir='.', filetypes = [('Input','.in')]) outfile = infile.replace(".in", ".out", 1);
Python
zaydzuhri_stack_edu_python
from flask import Flask , render_template , request import datetime import sqlite3 comment GLOBAL VARIABLES ####################################### comment Creating a Data Base Object (Probably with the cs50 library) comment db = sqlite3.connect('ariza.db') comment cursor = db.cursor() comment Creating an variable to s...
from flask import Flask, render_template, request import datetime import sqlite3 ########################################################## # GLOBAL VARIABLES ####################################### ########################################################## # Creating a Data Base Object (Probably with the cs50 librar...
Python
zaydzuhri_stack_edu_python
comment Author : Pranjal Dubey comment Created : 29 Dec 2015 comment Last Modified : comment Version : 1.0 comment Modifications : comment Description : Parse text data from file/clipboard memory, count the number of words in it and copy the estimated reading time embeded in html into clipboard, assuming that average r...
# Author : Pranjal Dubey # Created : 29 Dec 2015 # Last Modified : # Version : 1.0 # Modifications : # Description : Parse text data from file/clipboard memory, count the number of words in it and copy the estimated reading time embeded in html into clipboard, assuming that average reading time is 200 wpm and w...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 comment CLI tool for demo # comment What it does # comment Runs NB and SVM on voicemail audio # comment files to determine if it's a potential # comment phishing voicemail # comment # comment How to run: # comment ./pds.py # comment Takes one argument at most - string or # comment audio file t...
#!/usr/bin/python3 ################################################## # CLI tool for demo # # What it does # # Runs NB and SVM on voicemail audio # # files to determine if it's a potential # # phishing voicemail # # # # How to run: # # ./pds.py # # Takes one a...
Python
zaydzuhri_stack_edu_python
for i in range n begin set x = list comprehension i for i in split input append y x end for i in y begin if i at 1 == string Sell begin append sellers_price integer i at 3 append sellers_companies i at 2 append sellers_quantity integer i at 4 end else begin append buyers_price integer i at 3 append buyers_companies i a...
for i in range(n): x=[i for i in input().split()] y.append(x) for i in y: if(i[1]=="Sell"): sellers_price.append(int(i[3])) sellers_companies.append(i[2]) sellers_quantity.append(int(i[4])) else: buyers_price.append(int(i[3])) buyers_companies.append(i[2]) ...
Python
zaydzuhri_stack_edu_python
function train self s a r s_prime begin set tuple policy value = call forward s set tuple _ v_prime = call forward s_prime set td_target = r + gamma * data set advantage = td_target - data set probs = softmax policy dim=0 set log_probs = call log_softmax policy dim=0 set log_action_probs = gather log_probs 0 call Varia...
def train(self, s, a, r, s_prime): self.policy, self.value = self.forward(s) _, v_prime = self.forward(s_prime) td_target = r + self.gamma * v_prime.data advantage = td_target - self.value.data probs = F.softmax(self.policy, dim=0) log_probs = F.log_softmax(self.policy,...
Python
nomic_cornstack_python_v1
function test_reprocess_handler async_kwik_e_mart_app kwik_e_mart_app_path begin set convo = call Conversation app=async_kwik_e_mart_app app_path=kwik_e_mart_app_path force_sync=true process string When does that open? call assert_target_dialogue_state convo string send_store_hours_flow set directives = directives call...
def test_reprocess_handler(async_kwik_e_mart_app, kwik_e_mart_app_path): convo = Conversation( app=async_kwik_e_mart_app, app_path=kwik_e_mart_app_path, force_sync=True ) convo.process("When does that open?") assert_target_dialogue_state(convo, "send_store_hours_flow") directives = convo.pro...
Python
nomic_cornstack_python_v1
import abc class BaseModel extends object begin set __metaclass__ = ABCMeta decorator abstractmethod function __init__ self begin pass end function decorator abstractmethod function train_op self begin pass end function decorator abstractmethod function predict_op self begin pass end function decorator abstractmethod f...
import abc class BaseModel(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def __init__(self): pass @abc.abstractmethod def train_op(self): pass @abc.abstractmethod def predict_op(self): pass @abc.abstractmethod def loss_op(self): pass ...
Python
zaydzuhri_stack_edu_python
import sys import os import numpy as np import collections with open string day6.txt as a begin set puzzleinput = read lines a end set puzzleinput = list comprehension strip x for x in puzzleinput string example input comment puzzleinput = [ comment 'COM)B', comment 'B)C', comment 'C)D', comment 'D)E', comment 'E)F', c...
import sys import os import numpy as np import collections with open('day6.txt')as a: puzzleinput=a.readlines() puzzleinput = [x.strip() for x in puzzleinput] 'example input' ##puzzleinput = [ ##'COM)B', ##'B)C', ##'C)D', ##'D)E', ##'E)F', ##'B)G', ##'G)H', ##'D)I', ##'E)J', ##'J)K', ##'K)L'] puzzleinput = [x.sp...
Python
zaydzuhri_stack_edu_python
function do_up self arg begin if curindex == 0 begin error string Oldest frame return end try begin set count = integer arg or 1 end except ValueError begin error string Invalid frame count (%s) % arg return end if count < 0 begin set newframe = 0 end else begin set newframe = max 0 curindex - count end call _select_fr...
def do_up(self, arg): if self.curindex == 0: self.error('Oldest frame') return try: count = int(arg or 1) except ValueError: self.error('Invalid frame count (%s)' % arg) return if count < 0: newframe = 0 else...
Python
nomic_cornstack_python_v1
function plot_weights weights alphas title fname=string save_plot=false begin for tuple i tuple weight alpha in enumerate zip weights alphas begin bar x=call asarray range 1 length weight + 1 + 0.5 - 1 / length weights * i width=1 / length weights height=weight label=string alpha: { alpha } end y label string y legend...
def plot_weights(weights, alphas, title, fname="", save_plot=False): for i, (weight, alpha) in enumerate(zip(weights, alphas)): plt.bar(x=np.asarray(range(1,len(weight)+1))+.5-1/len(weights)*i, width=1/len(weights), height=weight, label=f'alpha: {alpha}') plt.ylabel('y') plt.legend(l...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 string Addison Partida & Henry Pearson Phase5 - API.py CS257 Jeff Ondich import sys import flask import json import psycopg2 set app = call Flask __name__ function get_connection begin set password = string set database = string partidaa set user = string partidaa set connection = none tr...
#!/usr/bin/env python3 ''' Addison Partida & Henry Pearson Phase5 - API.py CS257 Jeff Ondich ''' import sys import flask import json import psycopg2 app = flask.Flask(__name__) def get_connection(): password = '' database = 'partidaa' user = 'partidaa' connection = None try: connection = p...
Python
zaydzuhri_stack_edu_python
import sys set input = readline function main begin set rate = integer input if rate < 1200 begin print string ABC end else if rate < 2800 begin print string ARC end else begin print string AGC end end function if __name__ == string __main__ begin call main end
import sys input = sys.stdin.readline def main(): rate = int(input()) if rate < 1200: print("ABC") elif rate < 2800: print("ARC") else: print("AGC") if __name__ == "__main__": main()
Python
zaydzuhri_stack_edu_python
string Trabajo práctico numero 2: Medición en antenas de WiFi from pathlib import Path from process_data import process_s1p_files comment MAIN PROGRAM ########################################## function main begin comment Dictrionary comment Map file stem to anntena set anntenas_t = dict string AutoSave1 string Biquad ...
""" Trabajo práctico numero 2: Medición en antenas de WiFi """ from pathlib import Path from process_data import process_s1p_files ################################## MAIN PROGRAM ########################################## def main(): ####### Dictrionary # Map file stem to anntena anntenas_t = { ...
Python
zaydzuhri_stack_edu_python
import numpy as np import pandas as pd call set_printoptions suppress=true precision=4 set samples = 1000 function get_data id begin if id is string normal begin return call multivariate_normal list 0 0 0 call diag list 2 3 5 size=samples end if id is string uniform begin set bounds = array list 30 15 24 return uniform...
import numpy as np import pandas as pd np.set_printoptions(suppress=True, precision=4) samples = 1000 def get_data(id): if id is 'normal': return np.random.multivariate_normal([0, 0, 0], np.diag([2, 3, 5]), size=samples) if id is 'uniform': bounds = np.array([30, 15, 24]) return np....
Python
zaydzuhri_stack_edu_python
import classes import numpy as np if __name__ == string __main__ begin comment Create a schematic set test_schematic_1 = call Schematic comment Setup the inital states of the components and test adding them to the schematic set c1 = dict string id 0 ; string component_type string Capacitor call add_component c1 set c2 ...
import classes import numpy as np if __name__ == "__main__": # Create a schematic test_schematic_1 = classes.Schematic() # Setup the inital states of the components and test adding them to the schematic c1 = {"id": 0, "component_type": "Capacitor"} test_schematic_1.add_component(c1) c2 = {"id"...
Python
zaydzuhri_stack_edu_python
function write_without_log self key value begin set maps at 1 at key = value end function
def write_without_log(self, key: str, value: Any) -> None: self.maps[1][key] = value
Python
nomic_cornstack_python_v1
function test_encrypt_pair_row begin set pair = string KI set result = call transform_pair pair grid assert result == string ER end function
def test_encrypt_pair_row(): pair = 'KI' result = playfair.transform_pair(pair, grid,) assert result == 'ER'
Python
nomic_cornstack_python_v1
class Queue begin comment write your __init__ method here that should store a 'total' value which is the total number of elements in the Queue and a 'queue' value which is an array of stored values in the Queue function __init__ self begin comment every time we add to queue need to increment a counter set queue = list ...
class Queue: # write your __init__ method here that should store a 'total' value which is the total number of elements in the Queue and a 'queue' value which is an array of stored values in the Queue def __init__(self): # every time we add to queue need to increment a counter self.queue = [] self.total ...
Python
zaydzuhri_stack_edu_python
function common_elements self begin return intersection call relevant_elements call selected_elements end function
def common_elements(self): return self.relevant_elements().\ intersection(self.selected_elements())
Python
nomic_cornstack_python_v1
function compareDates date1 date2 begin if date1 == date2 begin return 0 end else if date1 > date2 begin return 1 end else begin return - 1 end end function
def compareDates(date1, date2): if (date1 == date2): return 0 elif (date1 > date2): return 1 else: return -1
Python
nomic_cornstack_python_v1
import re import sqlite3 function validate_password password begin string This function validates the strength of a password based on the following rules: - At least 8 characters long - Contains at least one uppercase letter - Contains at least one lowercase letter - Contains at least one digit - Contains at least one ...
import re import sqlite3 def validate_password(password): """ This function validates the strength of a password based on the following rules: - At least 8 characters long - Contains at least one uppercase letter - Contains at least one lowercase letter - Contains at least one digit - Conta...
Python
jtatman_500k
from flask import Flask , request , jsonify , render_template from flask_cors import CORS import numpy as np import pandas as pd from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences import tensorflow as tf import re set loaded_model = call load_mode...
from flask import Flask, request, jsonify, render_template from flask_cors import CORS import numpy as np import pandas as pd from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences import tensorflow as tf import re loaded_model = tf.keras.models.load...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding:utf-8 -*- function pre tarStr begin set p = dict set shirt = 1 for i in range length tarStr begin if tarStr at i in p begin set p at tarStr at i = p at tarStr at i ? shirt end else begin set p at tarStr at i = shirt end set shirt = shirt ? 1 end return p end function fu...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- def pre(tarStr): p = {} shirt = 1 for i in range(len(tarStr)): if tarStr[i] in p: p[tarStr[i]] |= shirt else: p[tarStr[i]] = shirt shirt <<= 1 return p def shift_and(findStr, tarStr, start = 0): mask = 1 <...
Python
zaydzuhri_stack_edu_python
function add_to_ans_lst tree zipped_words ans_lst current begin if length zipped_words != 0 begin comment base case if left is none and right is none begin append ans_lst val call add_to_ans_lst tree zipped_words ans_lst tree end else if zipped_words at 0 == string 0 begin call add_to_ans_lst tree zipped_words at slice...
def add_to_ans_lst(tree, zipped_words, ans_lst, current): if len(zipped_words) != 0: # base case if current.left is None and current.right is None: ans_lst.append(current.val) add_to_ans_lst(tree, zipped_words, ans_lst, tree) else: if zipped_words[0] == '0...
Python
nomic_cornstack_python_v1
function location_of_stops self choice distance begin set avg_dist = 0 set min_dist = 1000 set max_dist = 0 if choice == 1 begin comment for dist_ in distance: comment if int(dist_) < min_dist: comment min_dist = dist_ return min distance end else if choice == 2 begin for dist_ in distance begin if integer dist_ > max_...
def location_of_stops(self, choice, distance): avg_dist = 0 min_dist = 1000 max_dist = 0 if choice == 1: #for dist_ in distance: # if int(dist_) < min_dist: # min_dist = dist_ return min(distance) elif choice == 2: ...
Python
nomic_cornstack_python_v1
function server evt serv dataq=none begin call listen 5 set try begin set tuple conn addr = call accept if dataq begin set data = string set new_data = get dataq true 0.5 call task_done for item in new_data begin if item == EOF_sigil begin break end if type item in list int float begin sleep item end else begin set da...
def server(evt, serv, dataq=None): serv.listen(5) evt.set() try: conn, addr = serv.accept() if dataq: data = '' new_data = dataq.get(True, 0.5) dataq.task_done() for item in new_data: if item == EOF_sigil: ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string No matter how long is a student's name, this code creates a new list with name of student and grades separated. If the student has no grades, append [] set data = list list string Harry string Potter 100 list string James string Bond 7 list string Malal...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ No matter how long is a student's name, this code creates a new list with name of student and grades separated. If the student has no grades, append [] """ data = [['Harry', 'Potter', 100], ['James', 'Bond', 7], ['Malala', 'Yusafzai'], ['Sher...
Python
zaydzuhri_stack_edu_python
function _check_play_button self mouse_pos begin if call collidepoint mouse_pos and not game_active begin call reset_stats call initialize_dynamic_settings set game_active = true comment Hide mouse cursor call set_visible false comment Get rid of any leftover aliens and bullets call empty call empty comment Create a ne...
def _check_play_button(self, mouse_pos): if self.play_button.rect.collidepoint(mouse_pos) and not self.stats.game_active: self.stats.reset_stats() self.settings.initialize_dynamic_settings() self.stats.game_active = True #Hide mouse cursor pygame.mous...
Python
nomic_cornstack_python_v1
function _collect_scene_data self config begin set _config = config set scenes_root_path = config at string scenes_root_path assert is directory path scenes_root_path set _scene_dict = dictionary comment each one is a list of scenes set _all_image_paths = dict string train list ; string test list for tuple key val in...
def _collect_scene_data(self, config): self._config = config self.scenes_root_path = config['scenes_root_path'] assert(os.path.isdir(self.scenes_root_path)) self._scene_dict = dict() # each one is a list of scenes self._all_image_paths = {"train": [], "test": []} ...
Python
nomic_cornstack_python_v1
import cv2 , os import numpy as np import matplotlib.pyplot as plt import seaborn as sns import tensorflow as tf from keras.backend.tensorflow_backend import set_session import keras , sys , time , warnings from keras.models import * from keras.layers import * from sklearn.utils import shuffle from keras import optimiz...
import cv2, os import numpy as np import matplotlib.pyplot as plt import seaborn as sns import tensorflow as tf from keras.backend.tensorflow_backend import set_session import keras, sys, time, warnings from keras.models import * from keras.layers import * from sklearn.utils import shuffle from keras import optimizers ...
Python
zaydzuhri_stack_edu_python
comment https://www.hackerrank.com/challenges/the-birthday-bar/problem function solve values day month begin set total = 0 return total end function print call solve list 1 2 1 3 2 3 2
# https://www.hackerrank.com/challenges/the-birthday-bar/problem def solve(values, day, month): total = 0 return total print(solve([1, 2, 1, 3, 2], 3, 2))
Python
zaydzuhri_stack_edu_python
function remove_duplicates arr begin string Helper function to remove duplicates from a list while preserving order. return list call fromkeys arr end function function sort_odd_numbers arr begin string Helper function to sort odd numbers in descending order. return sorted arr reverse=true end function function filter_...
def remove_duplicates(arr): """ Helper function to remove duplicates from a list while preserving order. """ return list(dict.fromkeys(arr)) def sort_odd_numbers(arr): """ Helper function to sort odd numbers in descending order. """ return sorted(arr, reverse=True) def filter_odd_num...
Python
jtatman_500k
from checking_account import CheckingAccount from credit_account import CreditAccount from savings_account import SavingsAccount from terminal_colors import TerminalColors as tc function main begin set checking = call CheckingAccount initial_amount=100 set savings = call SavingsAccount initial_amount=1000 set credit = ...
from checking_account import CheckingAccount from credit_account import CreditAccount from savings_account import SavingsAccount from terminal_colors import TerminalColors as tc def main(): checking = CheckingAccount(initial_amount=100) savings = SavingsAccount(initial_amount=1000) credit = CreditAccount(initial...
Python
zaydzuhri_stack_edu_python
from itertools import chain function column matrix i begin return list comprehension row at i for row in matrix end function function check_win board numbers begin set numbers = set numbers for row in board begin if call issubset numbers begin return true end end for i in range length board at 0 begin if call issubset ...
from itertools import chain def column(matrix, i): return [row[i] for row in matrix] def check_win(board, numbers): numbers = set(numbers) for row in board: if (set(row).issubset(numbers)): return True for i in range(len(board[0])): if (set(column(board, i)).issubset(numbe...
Python
zaydzuhri_stack_edu_python
function draw self begin try begin comment Get values for daily entries from fields. set mo = integer get __entry_monday set tu = integer get __entry_tuesday set we = integer get __entry_wednesday set th = integer get __entry_thursday set fr = integer get __entry_friday set sa = integer get __entry_saturday set su = in...
def draw(self): try: # Get values for daily entries from fields. mo = int(self.__entry_monday.get()) tu = int(self.__entry_tuesday.get()) we = int(self.__entry_wednesday.get()) th = int(self.__entry_thursday.get()) fr = int(self....
Python
nomic_cornstack_python_v1
from typing import List class Solution begin function partitionLabels self S begin set alphabet = ordered dictionary for i in range length S begin if not S at i in alphabet begin set alphabet at S at i = list i i end else begin set alphabet at S at i at 1 = i end end set ans = list set last = - 1 set tuple k v = pop i...
from typing import List class Solution: def partitionLabels(self, S: str) -> List[int]: alphabet = OrderedDict() for i in range(len(S)): if not S[i] in alphabet: alphabet[S[i]] = [i, i] else: alphabet[S[i]][1] = i ans = [] last ...
Python
zaydzuhri_stack_edu_python
comment s="akasaka" function kaibun x begin set ans = 1 for i in range length x // 2 begin if x at i != x at - i - 1 begin set ans = 0 break end end return ans end function set n = length s set a1 = call kaibun s set a2 = call kaibun s at slice 0 : n - 1 // 2 : set a3 = call kaibun s at slice - 1 + n + 3 // 2 : n : if ...
#s="akasaka" def kaibun(x): ans=1 for i in range(len(x)//2): if x[i]!=x[-i-1]: ans=0 break return ans n=len(s) a1=kaibun(s) a2=kaibun(s[0:(n-1)//2]) a3=kaibun(s[-1+(n+3)//2:n]) if a1==1 and a2==1 and a3==1: print("Yes") else: print("No")
Python
zaydzuhri_stack_edu_python
function names self begin return list comprehension e for e in list call force_unicode country call force_unicode region_name call force_unicode subregion_name call force_unicode district_name call force_unicode name if e end function
def names(self): return [e for e in [ force_unicode(self.country), force_unicode(self.region_name), force_unicode(self.subregion_name), force_unicode(self.district_name), force_unicode(self.name), ] if e]
Python
nomic_cornstack_python_v1
function average_donation self begin set average = call sum_donations / call donation_count return round average 2 end function
def average_donation(self): average = self.sum_donations() / self.donation_count() return round(average, 2)
Python
nomic_cornstack_python_v1
async function fetch_character self name test=false begin set response = await call _request string GET call get_url strip name test=test set start_time = performance counter set char = call from_content content set parsing_time = performance counter - start_time return call TibiaResponse response char parsing_time end...
async def fetch_character(self, name, *, test=False): response = await self._request("GET", Character.get_url(name.strip()), test=test) start_time = time.perf_counter() char = Character.from_content(response.content) parsing_time = time.perf_counter() - start_time return TibiaRes...
Python
nomic_cornstack_python_v1
function bollinger_lband_indicator close n=20 ndev=2 fillna=false begin set df = transpose call DataFrame list close set mavg = mean call rolling n set mstd = standard deviation call rolling n set lband = mavg - ndev * mstd set df at string lband = 0.0 set loc at tuple close < lband string lband = 1.0 set lband = df at...
def bollinger_lband_indicator(close, n=20, ndev=2, fillna=False): df = pd.DataFrame([close]).transpose() mavg = close.rolling(n).mean() mstd = close.rolling(n).std() lband = mavg - ndev * mstd df['lband'] = 0.0 df.loc[close < lband, 'lband'] = 1.0 lband = df['lband'] if fillna: l...
Python
nomic_cornstack_python_v1
function repositories self begin pass end function
def repositories(self): pass
Python
nomic_cornstack_python_v1
import pandas as pd function main begin set url = string https://raw.githubusercontent.com/kjhealy/fips-codes/master/state_and_county_fips_master.csv set df = call assign state=lambda x -> as type str at slice : 2 : int county=lambda x -> as type str at slice 3 : : int comment .fillna(dict(state_abbr="NA")) return ...
import pandas as pd def main(): url = "https://raw.githubusercontent.com/kjhealy/fips-codes/master/state_and_county_fips_master.csv" df = ( pd.read_csv(url) .rename(columns=dict(name="county_name", state="state_abbr")) .assign( state=lambda x: x["fips"].astype(str).str.zfil...
Python
zaydzuhri_stack_edu_python
function my_delete_medical_consultation request cm_id begin set mi_template = call get_template string Medics/GestionTurnos/borrar-consulta-medica.html set dict = call generate_base_keys request comment requiere permiso del medico if true begin set cm = get objects id=cm_id if method == string POST begin delete return ...
def my_delete_medical_consultation(request, cm_id): mi_template = get_template('Medics/GestionTurnos/borrar-consulta-medica.html') dict = generate_base_keys(request) if True: #requiere permiso del medico cm = MedicalConsultation.objects.get(id=cm_id) if request.method == 'POST': ...
Python
nomic_cornstack_python_v1
try begin from commands.managment.management_commands import ManagementCommands end except ImportError begin print string Need to fix the installation raise end string Save Command. command: save <seq> [<file_name>] seq might be a seq id: #id, or a seq name: #name. if the file name is not provided, the sequence name is...
try: from commands.managment.management_commands import ManagementCommands except ImportError: print("Need to fix the installation") raise ''' Save Command. command: save <seq> [<file_name>] seq might be a seq id: #id, or a seq name: #name. if the file name is not provided, the sequence name is being used. ...
Python
zaydzuhri_stack_edu_python
comment import regex module import re comment Make a regex object set phoneNumRegex = compile string (\d{3})-?(\d{4}-\d{3}) set testString = string This is a test string it has my number767-6424-299 in various formats like -6424-299, 767-6424-299,767 6424 299, 7676 4242 99, 7676424299, 76764 24299(767)-6424-299 and so ...
# import regex module import re # Make a regex object phoneNumRegex = re.compile(u'(\d{3})-?(\d{4}-\d{3})') testString = 'This is a test string it has my number\ 767-6424-299 in various formats like -6424-299, 767-6424-299,\ 767 6424 299, 7676 4242 99, 7676424299, 76764 24299\ (767)-6424-299 and so on.' testStri...
Python
zaydzuhri_stack_edu_python
function createAsset assFolder *args begin call createAssetUI assFolder end function
def createAsset(assFolder, *args): createAssetUI(assFolder)
Python
nomic_cornstack_python_v1
import enum class MyState extends Enum begin set stateA = 1 set stateB = 2 set stateC = 4 set stateD = 3 set stateM = 54 end class set state = stateM
import enum class MyState(enum.Enum): stateA=1 stateB=2 stateC=4 stateD=3 stateM=54 state = MyState.stateM
Python
zaydzuhri_stack_edu_python
function __build_segmentation_model backbone num_channels num_classes final_activation use_pretrained_imagenet_weights base_model **base_model_args begin assert final_activation in SUPPORTED_ACTIVATIONS msg string unsupported activation: { final_activation } . final activaiton must be one of: { SUPPORTED_ACTIVATIONS } ...
def __build_segmentation_model(backbone: __Union[Backbone, str], num_channels: int, num_classes: int, final_activation: str, use_pretrained_imagenet_weights: bool, base_model: __Callable[..., __Model], **base_model_args) -> __Model: assert final_activati...
Python
nomic_cornstack_python_v1
function disposeModel model begin import gurobipy as gb set mstatus = Status del model call disposeDefaultEnv return mstatus end function
def disposeModel(model): import gurobipy as gb mstatus = model.Status del model gb.disposeDefaultEnv() return mstatus
Python
nomic_cornstack_python_v1
from __future__ import print_function , division set char = string H set space = string function text_align width begin set lines = list for n in range width begin append lines call center width * 2 - 1 space end set offset = space * width * 4 - width * 2 - 1 for n in range width + 1 begin append lines call center wi...
from __future__ import print_function, division char = 'H' space = ' ' def text_align(width): lines = [] for n in range(width): lines.append((char*(n*2+1)).center(width*2-1, space)) offset = space*(width*4 - (width*2-1)) for n in range(width+1): lines.append((char*width).center(width...
Python
zaydzuhri_stack_edu_python
comment coding=utf-8 string question url: https://leetcode.com/problems/3sum-closest/ class Solution extends object begin function threeSumClosest self nums target begin string :type nums: List[int] :type target: int :rtype: int sort nums if length nums < 3 begin return end set result = nums at 0 + nums at 1 + nums at ...
# coding=utf-8 """ question url: https://leetcode.com/problems/3sum-closest/ """ class Solution(object): def threeSumClosest(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ nums.sort() if len(nums) < 3: return...
Python
zaydzuhri_stack_edu_python
string A format for expressing an ordered list of integers is to use a comma separated list of either: - individual integers - or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. The range includes all integers in the interval including both endpoints. It i...
""" A format for expressing an ordered list of integers is to use a comma separated list of either: - individual integers - or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. The range includes all integers in the interval including both endpoints. It is ...
Python
zaydzuhri_stack_edu_python
function run self runs=5 begin comment Matrix mutiplications. for i in range runs begin call multiply_matrices end comment Build the final dictionary. set sentiment = dict for tuple lemma score in items s begin comment This check on inclusion in a is crucial: during parallel comment runs, we need to take care not to a...
def run(self, runs=5): # Matrix mutiplications. for i in range(runs): self.multiply_matrices() # Build the final dictionary. sentiment = {} for lemma,score in self.s.items(): # This check on inclusion in a is crucial: during parallel # ...
Python
nomic_cornstack_python_v1
string Array Addition I from Codersbyte November 2020 Jakub Kazimierski from itertools import chain , combinations function all_subsets arr begin string Returns chain of all possible combinations of elements in given at input array comment chain() -It is a function that takes a series of iterables and returns one itera...
''' Array Addition I from Codersbyte November 2020 Jakub Kazimierski ''' from itertools import chain, combinations def all_subsets(arr): ''' Returns chain of all possible combinations of elements in given at input array ''' # chain() -It is a function that takes a series of iterab...
Python
zaydzuhri_stack_edu_python
function extract self inputs params begin set tuple outputs params = call preprocess inputs params if string ensemble in name begin comment run full ensemble together and change logits key to get logits per model update params dict string layer_key LOGITS_MULTIMODEL set tuple outputs params = call run_model_and_get_anc...
def extract(self, inputs, params): outputs, params = self.preprocess(inputs, params) if "ensemble" in params["model"].name: # run full ensemble together and change logits key to get logits per model params.update({"layer_key": DataKeys.LOGITS_MULTIMODEL}) outputs, pa...
Python
nomic_cornstack_python_v1
import math function encryption s begin set res = string set c = ceil square root length s return join string list comprehension s at slice i : : c for i in range c end function print call encryption string haveaniceday
import math def encryption(s): res = '' c = math.ceil(math.sqrt(len(s))) return ' '.join([s[i::c] for i in range(c)]) print(encryption('haveaniceday'))
Python
zaydzuhri_stack_edu_python
function event_m50_37_12020 begin string State 0,2: [Lib] [Preset] Elevator lever_SubState assert call event_m50_37_x15 z309=50372502 z310=50372404 z311=40 string State 1: Rerun call RestartMachine end function
def event_m50_37_12020(): """State 0,2: [Lib] [Preset] Elevator lever_SubState""" assert event_m50_37_x15(z309=50372502, z310=50372404, z311=40) """State 1: Rerun""" RestartMachine()
Python
nomic_cornstack_python_v1
function has_car self i lane_index begin return call has_car lane_index end function
def has_car(self, i, lane_index): return self._spots[i].has_car(lane_index)
Python
nomic_cornstack_python_v1
comment @Time :2018/6/7 comment @Author :LiuYinxing class Solution begin comment 方法1, 使用zip() function rotate self matrix begin set matrix at slice : : = zip *matrix[::-1] return matrix end function comment 方法2 function rotate1 self matrix begin comment 逆序操作 set matrix = matrix at slice : : - 1 comment 转置 for i in...
# @Time :2018/6/7 # @Author :LiuYinxing class Solution: def rotate(self, matrix): # 方法1, 使用zip() matrix[::] = zip(*matrix[::-1]) return matrix def rotate1(self, matrix): # 方法2 matrix = matrix[::-1] # 逆序操作 for i in range(len(matrix)): # 转置 for j in range(i): ...
Python
zaydzuhri_stack_edu_python
comment Andrew Tennant comment DSCI-15310-001 -- Computational Thinking and Programming comment 09/26/2017 comment Program #2 -- Mortgage Calculator comment Calculates annual salary after a raise comment Get the current salary and raise percentage set originalSalary = decimal input string What is your current salary?) ...
# Andrew Tennant # DSCI-15310-001 -- Computational Thinking and Programming # 09/26/2017 # Program #2 -- Mortgage Calculator # Calculates annual salary after a raise # Get the current salary and raise percentage originalSalary = float(input("What is your current salary?)\t$")) raisePercentage = float(input("What is th...
Python
zaydzuhri_stack_edu_python
function addChild self childNode begin append children childNode set parent = self set depth = depth + 1 end function
def addChild(self, childNode): self.children.append(childNode) childNode.parent = self childNode.depth = self.depth + 1
Python
nomic_cornstack_python_v1
function discover uuids begin if not uuids begin raise call DiscoveryFailed string No nodes to discover end set ironic = call get_client debug string Validating nodes %s uuids set nodes = list for uuid in uuids begin try begin set node = get node uuid end except NotFound begin error string Node %s cannot be found uuid...
def discover(uuids): if not uuids: raise utils.DiscoveryFailed("No nodes to discover") ironic = utils.get_client() LOG.debug('Validating nodes %s', uuids) nodes = [] for uuid in uuids: try: node = ironic.node.get(uuid) except exceptions.NotFound: LOG....
Python
nomic_cornstack_python_v1
import bpy function set_last_or_first_image context image_index begin set images_count = length images if images_count > 0 begin set active_image = image if active_image begin set image = images at image_index set image = image end end end function class ImageScroller extends Operator begin decorator classmethod functi...
import bpy def set_last_or_first_image(context, image_index): images_count = len(bpy.data.images) if images_count > 0: active_image = context.area.spaces[0].image if active_image: image = bpy.data.images[image_index] context.area.spaces[0].image = image class ImageScr...
Python
zaydzuhri_stack_edu_python
function __init__ self units batch_norm=false bn_momentum=0.99 drop_rate=0.0 kernel_initializer=none return_sequences=true dtype=float trainable=true begin call __init__ dtype=dtype trainable=trainable set _batch_norm = batch_norm set _bn_momentum = bn_momentum set _drop_rate = drop_rate set _dtype = dtype set _hidden_...
def __init__(self, units: int, batch_norm=False, bn_momentum=0.99, drop_rate=0., kernel_initializer=None, return_sequences=True, dtype=float, trainable=True): super(BGRUwDropout, self).__init__(dtype=dtype, trainable=trainable) self._batch_norm = batch_norm self._bn_momentum = b...
Python
nomic_cornstack_python_v1
from flask import json from db import get_db class Record begin function __init__ self id_ username image_url createdAt begin set id = id_ set username = username set image_url = image_url set createdAt = createdAt end function decorator staticmethod function get id_ begin print id_ set db = call get_db set result = ex...
from flask import json from .db import get_db class Record(): def __init__(self, id_, username, image_url, createdAt): self.id = id_ self.username = username self.image_url = image_url self.createdAt = createdAt @staticmethod def get(id_): print(id_) db = g...
Python
zaydzuhri_stack_edu_python
string Construct an acceptable matching of students to offerings (no age, grade, or capacity violations) without taking any priority into account, Modifies student and offering object properties to create pairs DOES NOT add ghost students from random import randint , uniform from util import * comment backtracking solu...
""" Construct an acceptable matching of students to offerings (no age, grade, or capacity violations) without taking any priority into account, Modifies student and offering object properties to create pairs DOES NOT add ghost students """ from random import randint, uniform from ..util import * # backtracking sol...
Python
zaydzuhri_stack_edu_python
function to self device begin call _check_init set device = device for m in call modules begin to m device end for nm in _savable begin set m = __dict__ at nm if has attribute m string to begin set __dict__ at nm = to m device end end return self end function
def to(self, device): self._check_init() self.device = device for m in self.modules(): m.to(self.device) for nm in self._savable: m = self.__dict__[nm] if hasattr(m, 'to'): self.__dict__[nm] = m.to(self.device) return self
Python
nomic_cornstack_python_v1
function add_color_labels_to_raw_plot labels_data raw_data ax=call gca ylims=tuple - 3 3 begin if labels_data is none begin return end for tuple idx label_times in call iterrows begin comment st_xvalue = label_times[0] comment et_xvalue = label_times[1] comment xmin = ax.get_xlim()[0] comment xmax = ax.get_xlim()[1] co...
def add_color_labels_to_raw_plot(labels_data, raw_data, ax=pyplot.gca() ,ylims=(-3,3)): if labels_data is None: return for idx, label_times in labels_data[[s_annotation.st_col, s_annotation.et_col]].iterrows(): # st_xvalue = label_times[0] # et_xvalue = label_times[1] # xmin = ax.get_xlim()[0] ...
Python
nomic_cornstack_python_v1
function ReverseArray listOfChars begin string Takes a list (not a string!) of characters and returns them as a string in reverse order. reverse listOfChars return join string listOfChars end function comment above is functionally identical to this but not O(n^2) comment for reversedChar in listOfChars: comment revers...
def ReverseArray(listOfChars): """ Takes a list (not a string!) of characters and returns them as a string in reverse order.""" listOfChars.reverse() return "".join(listOfChars) # above is functionally identical to this but not O(n^2) #for reversedChar in listOfChars: # reversedString += reve...
Python
zaydzuhri_stack_edu_python
function twenty_nineteen begin return 20 * 19 + 20 * 5 + 19 end function
def twenty_nineteen(): return (((20 * 19)+20)*(5)) + 19
Python
nomic_cornstack_python_v1
comment Copyright 2012-2013, Sinclair R.F., Inc. import math import re from ssbccPeripheral import SSBCCperipheral from ssbccUtil import SSBCCException class latch extends SSBCCperipheral begin string Latch a large input port for piecewise input to the processor core. This peripheral is used to input large counters and...
################################################################################ # # Copyright 2012-2013, Sinclair R.F., Inc. # ################################################################################ import math; import re; from ssbccPeripheral import SSBCCperipheral from ssbccUtil import SSBCCException; cl...
Python
zaydzuhri_stack_edu_python
import numpy as np from gensim.models import KeyedVectors , FastText class WordModels begin string Class to load, train or save word embeddings. Attributes: __embedding (gensim.models.keyedvectors.*): word embedding __model (type): word embedding model Methods: get_embedding(): Retrieves the embedding from the attribut...
import numpy as np from gensim.models import KeyedVectors, FastText class WordModels: """ Class to load, train or save word embeddings. Attributes: __embedding (gensim.models.keyedvectors.*): word embedding __model (type): word embedding model Methods: get_embedding(): Retrie...
Python
zaydzuhri_stack_edu_python
import pandas as pd from pandas.core.algorithms import unique import plotly.express as px import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Output , Input comment Read data set df = read csv string data/suicide_rates.csv print unique comment Create a range ...
import pandas as pd from pandas.core.algorithms import unique import plotly.express as px import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Output, Input # Read data df = pd.read_csv("data/suicide_rates.csv") print(df['year'].unique()) # Create a range ...
Python
zaydzuhri_stack_edu_python
string Created on Sep 28, 2017 @author: bhatsubh from flask_restful import Resource , reqparse from flask_jwt import jwt_required from models.item_model import ItemModel class Item extends Resource begin set parser = call RequestParser call add_argument string price type=float required=true help=string This field canno...
''' Created on Sep 28, 2017 @author: bhatsubh ''' from flask_restful import Resource,reqparse from flask_jwt import jwt_required from models.item_model import ItemModel class Item(Resource): parser = reqparse.RequestParser() parser.add_argument('price', type=float, required=True, ...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Fri Jan 6 10:13:58 2017 @author: mindovermiles262 Codecademy Python Print the value of ship_col. Print the value of ship_row. from random import randint set board = list for x in range 0 5 begin append board list string O * 5 end function print_board board begin for row ...
# -*- coding: utf-8 -*- """ Created on Fri Jan 6 10:13:58 2017 @author: mindovermiles262 Codecademy Python Print the value of ship_col. Print the value of ship_row. """ from random import randint board = [] for x in range(0,5): board.append(["O"] * 5) def print_board(board): for row in board: p...
Python
zaydzuhri_stack_edu_python
class Solution begin function makeFancyString self s begin set res = list for c in s begin if length res >= 2 and res at - 1 == res at - 2 == c begin continue end append res c end return join string res end function end class
class Solution: def makeFancyString(self, s: str) -> str: res = [] for c in s: if len(res) >= 2 and res[-1] == res[-2] == c: continue res.append(c) return ''.join(res)
Python
zaydzuhri_stack_edu_python
function __init__ self mass name com=_zero3 I=_zero3x3 begin set name = name set _mass = mass set _com = com set _rg_sq = I / _mass set points = dict string com call Point location=_com dcm_obj2body=_zero3x3 end function
def __init__ (self, mass, name, com = _zero3, I = _zero3x3): self.name = name self._mass = mass self._com = com self._rg_sq = I / self._mass self.points = { "com": Point( location = self._com, dcm_obj2body=_zero3x3 ) ...
Python
nomic_cornstack_python_v1
function list_computers self kwargs begin set resolve = string resolve in kwargs and kwargs at string resolve set dns = get kwargs string dns string set dc = get kwargs string dc false set hostnames = list if not dc begin set results = query engine call COMPUTERS_FILTER list string name end else begin set results = qu...
def list_computers(self, kwargs): resolve = "resolve" in kwargs and kwargs["resolve"] dns = kwargs.get("dns", "") dc = kwargs.get("dc", False) hostnames = [] if not dc: results = self.engine.query(self.engine.COMPUTERS_FILTER(), ["name"]) else: re...
Python
nomic_cornstack_python_v1
function execute_node self node verbatim_exe=false begin string Execute this node immediately on the local machine set executed = true comment Check that the PFN is for a file or path if needs_fetching begin try begin comment The pfn may have been marked local... set pfn = call get_pfn end except any begin comment or i...
def execute_node(self, node, verbatim_exe = False): """ Execute this node immediately on the local machine """ node.executed = True # Check that the PFN is for a file or path if node.executable.needs_fetching: try: # The pfn may have been marked local...
Python
jtatman_500k
import os set path = string pages/ function renameAll path begin set filelist = list directory path for file in filelist begin set filename = file set oldpath = join path path filename comment print(filename) if find filename string _ >= 0 begin set filename = replace filename string _ string end if find filename strin...
import os path = r'pages/' def renameAll(path): filelist = os.listdir(path) for file in filelist: filename = file oldpath = os.path.join(path, filename) # print(filename) if filename.find('_') >= 0: filename = filename.replace('_', '') if filename.find('-...
Python
zaydzuhri_stack_edu_python
function _is_invalid_signature self header payload token_signature begin set server_signature = call _generate_signature header payload if token_signature != server_signature begin return true end return false end function
def _is_invalid_signature(self, header, payload, token_signature): server_signature = self._generate_signature(header, payload) if token_signature != server_signature: return True return False
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python set nb = integer input string Nombre: if nb % 5 == 0 begin print string Votre nombre est un multiple de 5 end else begin print string Votre nombre n'est pas un multiple de 5 end
#!/usr/bin/env python nb = int(input("Nombre: ")) if nb%5==0: print("Votre nombre est un multiple de 5") else: print("Votre nombre n'est pas un multiple de 5")
Python
zaydzuhri_stack_edu_python
function isAllowedToReexecute begin return allow_reexecute end function
def isAllowedToReexecute(): return options.allow_reexecute
Python
nomic_cornstack_python_v1
comment Time Complextiy : O(n) comment Space Complexity : O(n) comment https://www.hackerrank.com/challenges/sparse-arrays?h_r=next-challenge&h_v=zen function count_occurences Ar queryAr begin set hash_table = dict for item in Ar begin if call __contains__ item == false begin set hash_table at item = 1 end else begin ...
#Time Complextiy : O(n) # Space Complexity : O(n) # https://www.hackerrank.com/challenges/sparse-arrays?h_r=next-challenge&h_v=zen def count_occurences(Ar, queryAr): hash_table = {} for item in Ar: if hash_table.__contains__(item) == False: hash_table[item] = 1 else: hash...
Python
zaydzuhri_stack_edu_python
comment import the random library import random comment read all the list of words set words = list with open string sowpods.txt string r as f begin set line = strip read line f append words line while line begin set line = strip read line f append words line end end comment generate a random number set random_index =...
# import the random library import random # read all the list of words words = [] with open('sowpods.txt', 'r') as f: line = f.readline().strip() words.append(line) while line: line = f.readline().strip() words.append(line) # generate a random number random_index = random.randint(0, len(wo...
Python
zaydzuhri_stack_edu_python