code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function modify_search add=list remove=list begin set query = split get args string q string set query = list comprehension strip x for x in query if strip x for word in remove begin if word in query begin remove query word end end for word in add begin if word and word not in query begin append query word end end ret...
def modify_search(add=[], remove=[]): query = request.args.get('q', '').split() query = [x.strip() for x in query if x.strip()] for word in remove: if word in query: query.remove(word) for word in add: if word and word not in query: query.append(word) retu...
Python
nomic_cornstack_python_v1
function __init__ self input_dim latent_dim num_classes begin call __init__ set encoder_hidden_layer = list 512 128 128 set decoder_hidden_layer = list 128 128 512 set input_dim = input_dim set latent_dim = latent_dim set num_classes = num_classes comment Define encoder and decoder module set encoder = call CEncoder in...
def __init__(self, input_dim, latent_dim, num_classes): super().__init__() encoder_hidden_layer = [512, 128, 128] decoder_hidden_layer = [128, 128, 512] self.input_dim = input_dim self.latent_dim = latent_dim self.num_classes = num_classes # Define encoder and decoder module self.encoder = CEncoder(i...
Python
nomic_cornstack_python_v1
function longest_substring string begin comment Stores the last occurrence of each character set last_occurrence = dict set result = list 0 1 set start_index = 0 for tuple i char in enumerate string begin if char in last_occurrence begin set start_index = max start_index last_occurrence at char + 1 end comment We can ...
def longest_substring(string): # Stores the last occurrence of each character last_occurrence = {} result = [0, 1] start_index = 0 for i, char in enumerate(string): if char in last_occurrence: start_index = max(start_index, last_occurrence[char] + 1) # We can use result to store...
Python
jtatman_500k
string 일본어 데이터 정제 오상혁 나윤수 2020.3.30 월 데이터 정제하는 코드 인풋데이터 정제 및 문장부호 정리 import re function prepro text begin comment 문장기호 및 깨지는 공백문자 삭제 set sub_punc = sub string 。|!|\? string text set sub_u3000 = sub string string sub_punc comment 특수기호 〆를 しめ(시메)로 변경 set sub_sime = sub string 〆 string しめ sub_u3000 return sub_sime end f...
''' 일본어 데이터 정제 오상혁 나윤수 2020.3.30 월 데이터 정제하는 코드 인풋데이터 정제 및 문장부호 정리 ''' import re def prepro(text): # 문장기호 및 깨지는 공백문자 삭제 sub_punc = re.sub('。|!|\?', '', text) sub_u3000=re.sub(' ','',sub_punc) # 특수기호 〆를 しめ(시메)로 변경 sub_sime = re.sub('〆', 'しめ', sub_u3000) return sub_sime
Python
zaydzuhri_stack_edu_python
function match_test_cases player_name battle_tag cmdLargs=false begin set tuple responce url = call get_responce player_name battle_tag comment Here I am Using Recurson to try to match several test Cases for user Friendlieness if cmdLargs begin if status_code != 200 begin print format string Error ! Invalid Battle Tag!...
def match_test_cases(player_name, battle_tag, cmdLargs = False): responce, url = get_responce(player_name, battle_tag) # Here I am Using Recurson to try to match several test Cases for user Friendlieness if cmdLargs: if responce.status_code != 200: print("\nError ! Invalid Battle ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding: utf-8 comment In[2]: print 10 + 3.14 print 10 + 3.0 print 10 + 0.3 print 15 * 1.0 print 15.1 * 2 comment In[ ]:
#!/usr/bin/env python # coding: utf-8 # In[2]: print(10+3.14) print(10+3.0) print(10+0.3) print(15*1.0) print(15.1*2) # In[ ]:
Python
zaydzuhri_stack_edu_python
function importObject importStr *args **kwargs begin return call call importClass importStr *args keyword kwargs end function
def importObject(importStr, *args, **kwargs): return importClass(importStr)(*args, **kwargs)
Python
nomic_cornstack_python_v1
function affine_forward x w b begin set out = none comment TODO: Implement the affine forward pass. Store the result in out. You # comment will need to reshape the input into rows. # comment *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** set t = reshape np x tuple shape at 0 call prod call shape x at sli...
def affine_forward(x, w, b): out = None ########################################################################### # TODO: Implement the affine forward pass. Store the result in out. You # # will need to reshape the input into rows. # ################################...
Python
nomic_cornstack_python_v1
function create_parser self prog_name subcommand begin set parser = call CommandParser prog=string %s %s % tuple base name path prog_name subcommand description=help or none formatter_class=DjangoHelpFormatter missing_args_message=get attribute self string missing_args_message none called_from_command_line=get attribut...
def create_parser(self, prog_name, subcommand): parser = CommandParser( prog='%s %s' % (os.path.basename(prog_name), subcommand), description=self.help or None, formatter_class=DjangoHelpFormatter, missing_args_message=getattr(self, 'missing_args_message', None), ...
Python
nomic_cornstack_python_v1
import numpy as np import torch import plotly.graph_objects as go from plot_3d import Plot_3d function main begin set epochs = 1000 set tuple x1 x2 = tuple tensor list 4.0 requires_grad=true tensor list - 4.0 requires_grad=true set tuple x1_history x2_history losses = tuple list list list set optimizer = adam list x...
import numpy as np import torch import plotly.graph_objects as go from plot_3d import Plot_3d def main(): epochs = 1000 x1,x2 = torch.tensor([4.],requires_grad=True),torch.tensor([-4.],requires_grad=True) x1_history,x2_history,losses = [],[],[] optimizer = torch.optim.Adam([x1,x2], lr=0.1) p3 = Plo...
Python
zaydzuhri_stack_edu_python
string This file defines functionality to invert an RBIG transform import numpy as np from univariate_invert_normalization import univariate_invert_normalization function invert_rbig gaussian_data transform_params progress_report_interval=none begin string Inverts an RBIG transform by using the saved transform params P...
""" This file defines functionality to invert an RBIG transform """ import numpy as np from univariate_invert_normalization import univariate_invert_normalization def invert_rbig(gaussian_data, transform_params, progress_report_interval=None): """ Inverts an RBIG transform by using the saved transform params P...
Python
zaydzuhri_stack_edu_python
function test_get_class_weight_regression begin set atom = call ATOMRegressor X_reg y_reg random_state=1 with raises AttributeError begin call get_class_weight end end function
def test_get_class_weight_regression(): atom = ATOMRegressor(X_reg, y_reg, random_state=1) with pytest.raises(AttributeError): atom.get_class_weight()
Python
nomic_cornstack_python_v1
function get_output self socket=none begin return call get_socket socket type_=string out end function
def get_output(self, socket=None): return self.get_socket(socket, type_="out")
Python
nomic_cornstack_python_v1
for tuple i j in ids_labels begin set labels = split j string , for label in labels begin set out = out + string i + string + label + string end end set fileout = open string id-label.csv string w write fileout out close fileout
for i, j in ids_labels: labels = j.split(",") for label in labels: out=out+str(i)+"\t"+label+"\n" fileout = open ("id-label.csv", "w") fileout.write(out) fileout.close()
Python
zaydzuhri_stack_edu_python
function play self begin set playlist_playing = true end function
def play(self): self.playlist_playing = True
Python
nomic_cornstack_python_v1
function start self begin set paused = false call showMessage string start timer speed self update self end function
def start(self): self.paused = False self.statusBar().showMessage("") self.timer.start(self.speed, self) self.update()
Python
nomic_cornstack_python_v1
function _register_gym_monitor gym_env_name begin assert gym_env_name msg string gym_env_name must be a non-empty string assert type gym_env_name is str msg string gym_env_name is not a str set result : _MonitorTotalCounts with _lock begin if gym_env_name not in _monitor_total_counts begin set result = call _MonitorTot...
def _register_gym_monitor(gym_env_name: str) -> _MonitorTotalCounts: assert gym_env_name, "gym_env_name must be a non-empty string" assert type(gym_env_name) is str, "gym_env_name is not a str" result: _MonitorTotalCounts with _MonitorEnv._lock: if gym_env_name not in _MonitorEnv._monitor_total...
Python
nomic_cornstack_python_v1
function speed_list self begin return SPEED_LIST end function
def speed_list(self) -> list: return SPEED_LIST
Python
nomic_cornstack_python_v1
string In our first lesson on the minimax algorithm, we wrote a program that could play the perfect game of Tic-Tac-Toe. Our AI looked at all possible future moves and chose the one that would be most beneficial. This was a viable strategy because Tic Tac Toe is a small enough game that it wouldn’t take too long to rea...
""" In our first lesson on the minimax algorithm, we wrote a program that could play the perfect game of Tic-Tac-Toe. Our AI looked at all possible future moves and chose the one that would be most beneficial. This was a viable strategy because Tic Tac Toe is a small enough game that it wouldn’t take too long to reach ...
Python
zaydzuhri_stack_edu_python
import pymorphy2 function CountStartleFeatures_Verb tokens_parsed=list begin set counter = 0 if length tokens_parsed == 0 begin return 0 end for token in tokens_parsed begin if token at 1 in tuple string VERB string INFN and find token at 0 string подслушано_ == - 1 begin set counter = counter + 1 end end return counte...
import pymorphy2 def CountStartleFeatures_Verb(tokens_parsed=[]): counter = 0 if len(tokens_parsed) == 0: return 0 for token in tokens_parsed: if token[1] in ('VERB', 'INFN') and token[0].find('подслушано_') == -1: counter +=1 return counter / len(tokens_parsed) def Coun...
Python
zaydzuhri_stack_edu_python
import numpy as np from scipy.optimize import linprog string TABELA MOZLIWYCH POCIEC: Szerokosc | Bele 2,1 | Bele 4,2 | arkusza | | | ------------|---------------|---------------| 0,5 | 4 | 1 | 8 | 5 | 2 | 0 | ------------|-------|-------|---|---|---|---| 1,4 | 0 | 1 | 0 | 1 | 2 | 3 | ------------|-------|-------|---|-...
import numpy as np from scipy.optimize import linprog """TABELA MOZLIWYCH POCIEC: Szerokosc | Bele 2,1 | Bele 4,2 | arkusza | | | ------------|---------------|---------------| 0,5 | 4 | 1 | 8 | 5 | 2 | 0 | ------------|-------|-------|---|---|...
Python
zaydzuhri_stack_edu_python
if lado_a == lado_b and lado_c == lado_b begin print string Esse é um triângulo equilátero end else if lado_a == lado_b or lado_b == lado_c or lado_c == lado_a begin print string Esse é um triângulo isóceles end else if lado_a != lado_b and lado_b != lado_c and lado_c != lado_a begin print string Esse é um triângulo es...
if (lado_a == lado_b) and (lado_c == lado_b): print('Esse é um triângulo equilátero') elif (lado_a == lado_b) or (lado_b == lado_c) or (lado_c == lado_a) : print('Esse é um triângulo isóceles') elif (lado_a != lado_b) and (lado_b != lado_c) and (lado_c != lado_a): print('Esse é um triângulo escaleno') else: pr...
Python
zaydzuhri_stack_edu_python
comment import the necessary packages import time import cv2 import numpy as np import wiringpi from imutils.video import WebcamVideoStream from imutils.video import FPS import imutils print string [INFO] sampling THREADED frames from webcam... set vs = start call WebcamVideoStream src=0 set fps = start call FPS call w...
# import the necessary packages import time import cv2 import numpy as np import wiringpi from imutils.video import WebcamVideoStream from imutils.video import FPS import imutils print("[INFO] sampling THREADED frames from webcam...") vs = WebcamVideoStream(src=0).start() fps = FPS().start() wiringpi.wiringPiSetupGpi...
Python
zaydzuhri_stack_edu_python
function predict y_tr x_tr y_te x_te ids_te degree=9 lambda_=0.0001 begin set tuple y_tests x_tests = call subset y_te x_te set tuple y_trains x_trains = call subset y_tr x_tr set subset_weights = list set subset_tx_te = list for tuple ind tuple trains tests in enumerate zip zip y_trains x_trains zip y_tests x_tests ...
def predict(y_tr, x_tr, y_te, x_te, ids_te, degree=9, lambda_=0.0001): y_tests, x_tests = subset(y_te, x_te) y_trains, x_trains = subset(y_tr, x_tr) subset_weights = [] subset_tx_te = [] for ind, (trains, tests) in enumerate( zip(zip(y_trains, x_trains), zip(y_tests, x_tests)) ): ...
Python
nomic_cornstack_python_v1
function new_user_data preset_app begin set user_data = dict string username string new_user ; string password string my_pwd comment TODO(tr) make the username random yield user_data set bm_config = call config_from_client preset_app with call db_connection as conn begin set user = call find_user conn user_data at stri...
def new_user_data(preset_app): user_data = { # TODO(tr) make the username random 'username': 'new_user', 'password': 'my_pwd', } yield user_data bm_config = config_from_client(preset_app) with bm_config.db_connection() as conn: user = find_user(conn, user_data['userna...
Python
nomic_cornstack_python_v1
from datetime import datetime from PyQt5.QtCore import pyqtSignal from PyQt5.QtGui import QFont from PyQt5.QtWidgets import QWidget , QGridLayout , QLabel from src.session_item_widget import SessionItemWidget class SearchedSessionItemWidget extends QWidget begin set opening_button_clicked = call pyqtSignal int set clos...
from datetime import datetime from PyQt5.QtCore import (pyqtSignal) from PyQt5.QtGui import (QFont) from PyQt5.QtWidgets import (QWidget, QGridLayout, QLabel) from src.session_item_widget import SessionItemWidget class SearchedSessionItemWidget(QWidget): opening_button_clicked = pyq...
Python
zaydzuhri_stack_edu_python
from pymongo import MongoClient import pandas as pd function get_locations begin set client = call MongoClient string 127.0.0.1 27017 with client begin set db = client at string TwitterDump set locations = call distinct string location end for location in locations begin remove locations location set location = string ...
from pymongo import MongoClient import pandas as pd def get_locations(): client = MongoClient('127.0.0.1', 27017) with client: db = client["TwitterDump"] locations = db.cluster0Enhanced.distinct('location') for location in locations: locations.remove(location) location = ...
Python
zaydzuhri_stack_edu_python
function interactive umap_object labels=none values=none hover_data=none theme=none cmap=string Blues color_key=none color_key_cmap=string Spectral background=string white width=800 height=800 point_size=none subset_points=none interactive_text_search=false interactive_text_search_columns=none interactive_text_search_a...
def interactive( umap_object, labels=None, values=None, hover_data=None, theme=None, cmap="Blues", color_key=None, color_key_cmap="Spectral", background="white", width=800, height=800, point_size=None, subset_points=None, interactive_text_search=False, interac...
Python
nomic_cornstack_python_v1
string SevenAte9 Write a function that removes each 9 that it is in between 7s. seven_ate9('79712312') => '7712312' seven_ate9('79797') => '777' function seven_ate9 string begin set nums = list comprehension integer s for s in string set i = 1 end function
''' SevenAte9 Write a function that removes each 9 that it is in between 7s. seven_ate9('79712312') => '7712312' seven_ate9('79797') => '777' ''' def seven_ate9(string): nums = [ int(s) for s in string ] i = 1
Python
zaydzuhri_stack_edu_python
string --- Part Two --- To completely determine whether you have enough adapters, you'll need to figure out how many different ways they can be arranged. Every arrangement needs to connect the charging outlet to your device. The previous rules about when adapters can successfully connect still apply. The first example ...
""" --- Part Two --- To completely determine whether you have enough adapters, you'll need to figure out how many different ways they can be arranged. Every arrangement needs to connect the charging outlet to your device. The previous rules about when adapters can successfully connect still apply. The first example a...
Python
zaydzuhri_stack_edu_python
import requests from bs4 import BeautifulSoup from retrying import retry import re import os set headers = dict string User-Agent string Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36 ; string Referer string https://music.163.com/ decorator call retry wait_rand...
import requests from bs4 import BeautifulSoup from retrying import retry import re import os headers = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36', 'Referer': 'https://music.163.com/', } @retry(wait_random_min=1000, ...
Python
zaydzuhri_stack_edu_python
function project_admin func *args **kwargs begin return call require_roles set literal string project_admin string admin func *args keyword kwargs end function
def project_admin(func, *args, **kwargs): return require_roles({"project_admin", "admin"}, func, *args, **kwargs)
Python
nomic_cornstack_python_v1
function filename self begin return base_filename end function
def filename(self): return self.base_filename
Python
nomic_cornstack_python_v1
function middle inList begin return inList at slice 1 : length inList - 1 : end function function chop inList begin del inList at 0 del inList at length inList - 1 end function comment Understand the diffences between the four functions below! comment Try, in Python interpreter: comment >>> myList = [1,2,3] comment >>...
def middle(inList): return(inList[1:len(inList)-1]) def chop(inList): del inList[0] del inList[len(inList)-1] # Understand the diffences between the four functions below! # # Try, in Python interpreter: # >>> myList = [1,2,3] # >>> bar(myList) # >>> myList # >>> myList = [1,2,3] # >>> bar2(myList) # >>>...
Python
zaydzuhri_stack_edu_python
import exifread from geopy.geocoders import Nominatim function getImageExt path begin string get image exit : time and gps set img = call process_file open path string rb try begin set time = img at string Image DateTime set latitude = img at string GPS GPSLatitude set longitude = img at string GPS GPSLongitude return ...
import exifread from geopy.geocoders import Nominatim def getImageExt(path): """get image exit : time and gps""" img = exifread.process_file(open(path, 'rb')) try: time = img['Image DateTime'] latitude = img['GPS GPSLatitude'] longitude = img['GPS GPSLongitude'] return (time, latitude, longitude...
Python
zaydzuhri_stack_edu_python
from math import log import numpy as np import part1_train function test print_output=false begin string Return a tuple of (list, numpy array, numpy array): 1. list of tuples of (our classification, actual classification, classification score) 2. shape (10,) numpy array - histogram of our classifications 3. shape (10,)...
from math import log import numpy as np import part1_train def test(print_output=False): """Return a tuple of (list, numpy array, numpy array): 1. list of tuples of (our classification, actual classification, classification score) 2. shape (10,) numpy array - histogram of our classifications ...
Python
zaydzuhri_stack_edu_python
function read_td_table table_name engine index_col=none parse_dates=none columns=none time_range=none limit=10000 begin comment header set query = call create_header format string read_td_table('{0}') table_name comment SELECT set query = query + format string SELECT {0} if expression columns is none then string * else...
def read_td_table( table_name, engine, index_col=None, parse_dates=None, columns=None, time_range=None, limit=10000, ): # header query = engine.create_header("read_td_table('{0}')".format(table_name)) # SELECT query += "SELECT {0}\n".format("*" if columns is None else ", ".jo...
Python
nomic_cornstack_python_v1
comment !/bin/python3 import math import os import random import re import sys comment Complete the dayOfProgrammer function below. function dayOfProgrammer year begin if year == 1918 begin return string 26.09.1918 end else if year <= 1917 and year % 4 == 0 or year % 400 == 0 or year % 4 == 0 and year % 100 != 0 begin ...
#!/bin/python3 import math import os import random import re import sys # Complete the dayOfProgrammer function below. def dayOfProgrammer(year): if year == 1918: return '26.09.1918' elif (year <= 1917 and year % 4 == 0) or ((year % 400 == 0 or year % 4 == 0) and year % 100 != 0): return '12.09.%s' %year else:...
Python
zaydzuhri_stack_edu_python
from scipy.special import comb class Solution begin function uniquePaths self m n begin set m = m - 1 set n = n - 1 set res = integer call comb m + n n return res end function end class class Solution2 begin function uniquePaths self m n begin set dp = list comprehension list comprehension 0 for i in range n for j in r...
from scipy.special import comb class Solution: def uniquePaths(self, m: int, n: int) -> int: m -= 1 n -= 1 res = int(comb(m + n, n)) return res class Solution2: def uniquePaths(self, m: int, n: int) -> int: dp = [[0 for i in range(n)] for j in range(m)] for i i...
Python
zaydzuhri_stack_edu_python
function gen_primes begin set list_of_ints = list for i in range 2 101 begin for j in list_of_ints begin if i % j == 0 begin break end end for else begin append list_of_ints i end end return list_of_ints end function print call gen_primes comment for j in range(2, i):
def gen_primes(): list_of_ints = [] for i in range(2, 101): for j in list_of_ints: if i % j == 0: break else: list_of_ints.append(i) return list_of_ints print(gen_primes()) # for j in range(2, i):
Python
zaydzuhri_stack_edu_python
import numpy as np from time import time from scipy.stats import randint as sp_randint from sklearn.model_selection import RandomizedSearchCV from sklearn.datasets import load_digits from sklearn.ensemble import RandomForestClassifier comment get some data set labels = list model_FDM at target_col_name print type label...
import numpy as np from time import time from scipy.stats import randint as sp_randint from sklearn.model_selection import RandomizedSearchCV from sklearn.datasets import load_digits from sklearn.ensemble import RandomForestClassifier # get some data labels = list(model_FDM[target_col_name]) print(type(labels)) trai...
Python
zaydzuhri_stack_edu_python
function get_answer_without_question self begin set meetup_id = string 1 set question_id = string 1 set url = reverse string Get_all_answers args=list meetup_id question_id set response = get client url content_type=string application/json return response end function
def get_answer_without_question(self): meetup_id = str(1) question_id = str(1) url = reverse('Get_all_answers', args=[meetup_id, question_id]) response = self.client.get( url, content_type="application/json" ) return response
Python
nomic_cornstack_python_v1
function phymem_usage begin string Return the amount of total, used and free physical memory on the system in bytes plus the percentage usage. Deprecated by psutil.virtual_memory(). set mem = call virtual_memory return call _nt_sysmeminfo total used free percent end function
def phymem_usage(): """Return the amount of total, used and free physical memory on the system in bytes plus the percentage usage. Deprecated by psutil.virtual_memory(). """ mem = virtual_memory() return _nt_sysmeminfo(mem.total, mem.used, mem.free, mem.percent)
Python
jtatman_500k
comment Leetcode 404. Sum of Left Leaves comment DFS comment Definition for a binary tree node. comment class TreeNode: comment def __init__(self, val=0, left=None, right=None): comment self.val = val comment self.left = left comment self.right = right class Solution1 begin function sumOfLeftLeaves self root begin if n...
#Leetcode 404. Sum of Left Leaves #DFS # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution1: def sumOfLeftLeaves(self, root: TreeNode) -> int: if not ro...
Python
zaydzuhri_stack_edu_python
set invoer = string 5-9-7-1-7-8-3-2-4-8-7-9 set getallen = list map int split invoer string - print string Gesorteerde lijst van ints: { sorted getallen } print string Grootste getal: { max getallen } en kleinste getal: { min getallen } print string Aantal getallen: { length getallen } en som van de getallen { sum geta...
invoer = "5-9-7-1-7-8-3-2-4-8-7-9" getallen = list(map(int, invoer.split("-"))) print(f"Gesorteerde lijst van ints: {sorted(getallen)}") print(f"Grootste getal: {max(getallen)} en kleinste getal: {min(getallen)}") print(f"Aantal getallen: {len(getallen)} en som van de getallen {sum(getallen)}") print(f"Gemiddeld {su...
Python
zaydzuhri_stack_edu_python
comment list comprehension### set x = list comprehension i for i in range 10 print x
###list comprehension### x=[i for i in range (10)] print(x)
Python
zaydzuhri_stack_edu_python
string InterviewBit Largest Number Asked in: Amazon, Goldman Sachs, Microsoft Given a list of non negative integers, arrange them such that they form the largest number. For example: Given [3, 30, 34, 5, 9], the largest formed number is 9534330. Note: The result may be very large, so you need to return a string instead...
'''InterviewBit Largest Number Asked in: Amazon, Goldman Sachs, Microsoft Given a list of non negative integers, arrange them such that they form the largest number. For example: Given [3, 30, 34, 5, 9], the largest formed number is 9534330. Note: The result may be very large, so you need to return a string instead of ...
Python
zaydzuhri_stack_edu_python
function test_pep8_comformance_review self begin set pep8style = call StyleGuide quiet=true set result = call check_files list string models/review.py assert equal total_errors 0 string Found code style errors (and warnings). end function
def test_pep8_comformance_review(self): pep8style = pep8.StyleGuide(quiet=True) result = pep8style.check_files(['models/review.py']) self.assertEqual(result.total_errors, 0, "Found code style errors (and warnings).")
Python
nomic_cornstack_python_v1
import os import tensorflow as tf import pandas as pd import numpy as np import scipy from keras import Sequential from keras.layers import Conv1D , MaxPool1D , LSTM , Dense , Dropout , Flatten , TimeDistributed from keras import backend as K from matplotlib import pyplot as plt from scipy.io import wavfile from scipy....
import os import tensorflow as tf import pandas as pd import numpy as np import scipy from keras import Sequential from keras.layers import Conv1D, MaxPool1D, LSTM, Dense, Dropout, Flatten, TimeDistributed from keras import backend as K from matplotlib import pyplot as plt from scipy.io import wavfile from scipy.stats ...
Python
zaydzuhri_stack_edu_python
from geom_3dface_utils import * import unittest class TestFace extends TestCase begin string docstring for TestFace function test_load self begin set fault = call Face3D read fault string test_geom_3dface_utils_ex.ts assert equal length points 8286 assert equal length triangles 15857 assert equal name string 1 assert e...
from geom_3dface_utils import * import unittest class TestFace(unittest.TestCase): """docstring for TestFace""" def test_load(self): fault = Face3D() fault.read('test_geom_3dface_utils_ex.ts') self.assertEqual(len(fault.points),8286) self.assertEqual(len(fault.triangles),15857...
Python
zaydzuhri_stack_edu_python
string Created on May 3, 2016 @author: jwb33 from tkinter import * from soil import * from veg_list import * from profit_calc import * class Garden begin function __init__ self window begin set window = window call protocol string WM_DELETE_WINDOW safe_exit set terminated = false set _current = true set _row_count = 1 ...
''' Created on May 3, 2016 @author: jwb33 ''' from tkinter import * from soil import * from veg_list import * from profit_calc import * class Garden: def __init__(self, window): self.window = window self.window.protocol('WM_DELETE_WINDOW', self.safe_exit) self.termina...
Python
zaydzuhri_stack_edu_python
comment 집합 자료형 comment 집합에 관련된 것을 쉽게 처리하기 위해 만든 자료형 string * 특징 1. 중복을 허용하지 않는다. 2. 순서가 없다. set s1 = set list 1 2 3 print s1 set s2 = set string Hello print s2 comment 만약 set 자료형에 저장된 값을 인덱싱으로 접근하려면 리스트나 튜플로 변환한 후 해야한다. set s1 = set list 1 2 3 set l1 = list s1 print l1 print l1 at 0 set t1 = tuple s1 print t1 print t1 ...
# 집합 자료형 # 집합에 관련된 것을 쉽게 처리하기 위해 만든 자료형 """ * 특징 1. 중복을 허용하지 않는다. 2. 순서가 없다. """ s1 = set([1, 2, 3]) print(s1) s2 = set("Hello") print(s2) # 만약 set 자료형에 저장된 값을 인덱싱으로 접근하려면 리스트나 튜플로 변환한 후 해야한다. s1 = set([1, 2, 3]) l1 = list(s1) print(l1) print(l1[0]) t1 = tuple(s1) print(t1) print(t1[0]) s1 = set([1, 2, 3, 4, 5,...
Python
zaydzuhri_stack_edu_python
function getctime filename begin return st_ctime end function
def getctime(filename): return os.stat(filename).st_ctime
Python
nomic_cornstack_python_v1
function change_syntax self begin if string Plain text in get call settings string syntax begin call set_syntax_file string Packages/JavaScript/JSON.tmLanguage end end function
def change_syntax(self): if "Plain text" in self.view.settings().get('syntax'): self.view.set_syntax_file("Packages/JavaScript/JSON.tmLanguage")
Python
nomic_cornstack_python_v1
function split_list lista begin set lista1 = list comprehension x for x in lista at slice 1 : : 2 set lista2 = list comprehension x for x in lista at slice 0 : : 2 return tuple lista2 lista1 end function print call split_list list 1 3 5 7 10 11 12 13 comment Zwróci ([1,5,10,12], [3,7,11,13])
def split_list(lista): lista1 = [x for x in lista[1::2]] lista2 = [x for x in lista[0::2]] return lista2 , lista1 print(split_list([1, 3, 5, 7, 10, 11, 12, 13])) # Zwróci ([1,5,10,12], [3,7,11,13])
Python
zaydzuhri_stack_edu_python
class Solution begin comment @param A : tuple of integers comment @return an integer function trap self A begin set maxleft = list set maxright = list set maxi = 0 for el in A begin append maxleft maxi set maxi = max maxi el end set maxi = 0 for el in A at slice : : - 1 begin append maxright maxi set maxi = max max...
class Solution: # @param A : tuple of integers # @return an integer def trap(self, A): maxleft = [] maxright = [] maxi = 0 for el in A: maxleft.append(maxi) maxi = max(maxi,el) maxi = 0 for el in A[::-1]: maxright.append(max...
Python
zaydzuhri_stack_edu_python
function test_store_existance_within_a_company self begin set all_stores = all assert true length all_stores > 0 string No stores exist within the fixture. assert false company is none string At least one store should exist within a company. end function
def test_store_existance_within_a_company (self): all_stores = Store.objects.all ( ) self.assertTrue (len(all_stores) > 0, "No stores exist within the fixture.") self.assertFalse (all_stores[0].company is None, "At least one store should...
Python
nomic_cornstack_python_v1
if needle in haystack begin print string Yes! end else begin print string No! end
if needle in haystack: print ("Yes!") else: print("No!")
Python
zaydzuhri_stack_edu_python
function stop self new_status=INVALID begin debug string %s.stop()[%s] % tuple __name__ if expression status != new_status then string %s->%s % tuple status new_status else string %s % new_status if new_status == INVALID begin for child in children begin call stop new_status end end comment This part just replicates th...
def stop(self, new_status=Status.INVALID): self.logger.debug("%s.stop()[%s]" % (self.__class__.__name__, "%s->%s" % (self.status, new_status) if self.status != new_status else "%s" % new_status)) if new_status == Status.INVALID: for child in self.children: child.stop(new_stat...
Python
nomic_cornstack_python_v1
function set_rhs self *args begin function chgrhs a b begin call chgrhs _e _lp a b end function call apply_pairs chgrhs _conv *args end function
def set_rhs(self, *args): def chgrhs(a, b): CPX_PROC.chgrhs(self._env._e, self._cplex._lp, a, b) apply_pairs(chgrhs, self._conv, *args)
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import unittest class S25Test extends TestCase begin comment 单引号 function test_single_quote self begin set value = string hello assert equal value string hello end function comment 双引号 function test_double_quote self begin set value = string hello assert equal value string hello end functi...
# -*- coding: utf-8 -*- import unittest class S25Test(unittest.TestCase): # 单引号 def test_single_quote(self): value = 'hello' self.assertEqual(value, 'hello') # 双引号 def test_double_quote(self): value = "hello" self.assertEqual(value, 'hello') # 三引号 def test_thr...
Python
zaydzuhri_stack_edu_python
function language_model_graph self compute_loss=true begin set inputs = call _inputs string train pretrain=true bidir=true set lm_inputs = inputs set tuple f_inputs r_inputs = inputs set f_loss = call _lm_loss f_inputs compute_loss=compute_loss set r_loss = call _lm_loss r_inputs emb_key=string lm_embedded_reverse lstm...
def language_model_graph(self, compute_loss=True): inputs = _inputs('train', pretrain=True, bidir=True) self.lm_inputs = inputs f_inputs, r_inputs = inputs f_loss = self._lm_loss(f_inputs, compute_loss=compute_loss) r_loss = self._lm_loss( r_inputs, emb_key='lm_embedded_reverse', ...
Python
nomic_cornstack_python_v1
import numpy as np import copy class upsampling begin comment each upsampling instance can be set to have different points function __init__ self points begin set points = points end function comment main method of upsampling class function create self *args begin comment *args: list as input set input = array *args if...
import numpy as np import copy class upsampling: # each upsampling instance can be set to have different points def __init__(self, points): self.points = points # main method of upsampling class def create(self, *args): # *args: list as input input = np.arra...
Python
zaydzuhri_stack_edu_python
function formBBox x y begin comment this tuple can be passed direct into the Image.crop function return tuple x - boxsize // 2 y - boxsize // 2 x + boxsize // 2 y + boxsize // 2 end function
def formBBox(x, y): # this tuple can be passed direct into the Image.crop function return ( x - boxsize // 2, y - boxsize // 2, x + boxsize // 2, y + boxsize // 2 )
Python
nomic_cornstack_python_v1
function check_results field begin set result = call PartialResult set line_sets = list call get_h_lines call get_v_lines call get_diagonals for line_set in line_sets begin if call has_unfair_moves is none begin set unfair = call unfair_total_moves line_set if unfair begin return results at string fail end call set_unf...
def check_results(field): result = PartialResult() line_sets = [ field.get_h_lines(), field.get_v_lines(), field.get_diagonals() ] for line_set in line_sets: if result.has_unfair_moves() is None: unfair = unfair_total_moves(line_set) if unfair: ...
Python
nomic_cornstack_python_v1
function parse_duration duration start=none end=none begin string Attepmt to parse an ISO8601 formatted duration. Accepts a ``duration`` and optionally a start or end ``datetime``. ``duration`` must be an ISO8601 formatted string. Returns a ``datetime.timedelta`` object. if not start and not end begin return call parse...
def parse_duration(duration, start=None, end=None): """ Attepmt to parse an ISO8601 formatted duration. Accepts a ``duration`` and optionally a start or end ``datetime``. ``duration`` must be an ISO8601 formatted string. Returns a ``datetime.timedelta`` object. """ if not start and not end...
Python
jtatman_500k
class HeLanGuoQi begin function solution self nums begin set left = 0 set right = length nums - 1 set cursor = 0 while cursor <= right begin if nums at cursor == 0 begin set tuple nums at cursor nums at left = tuple nums at left nums at cursor set left = left + 1 set cursor = cursor + 1 end else if nums at cursor == 1 ...
class HeLanGuoQi: def solution(self,nums): left = 0 right = len(nums)-1 cursor = 0 while cursor<=right: if nums[cursor] == 0: nums[cursor],nums[left] = nums[left],nums[cursor] left += 1 cursor += 1 elif nums[curs...
Python
zaydzuhri_stack_edu_python
function test_finds_simple_regression_multivariate self begin set series = call full 30 50 dtype=int set series at slice 15 : 30 : = 100 set series = reshape series 10 3 set tuple points state = call _test_helper series=series assert points == list 5 end function
def test_finds_simple_regression_multivariate(self): series = np.full(30, 50, dtype=int) series[15:30] = 100 series = series.reshape(10, 3) points, state = self._test_helper(series=series) assert points == [5]
Python
nomic_cornstack_python_v1
from io import open comment leer archivo comment lectura y escritura set archivo_texto = open string archivo.txt string r+ print read archivo_texto comment Se ubica en la posicion 4 seek archivo_texto 4 comment Lee desde donde esta el puntero print read archivo_texto comment Se ubica en la posicion 0 seek archivo_texto...
from io import open # leer archivo archivo_texto = open('archivo.txt','r+') # lectura y escritura print(archivo_texto.read()) archivo_texto.seek(4) # Se ubica en la posicion 4 print(archivo_texto.read()) # Lee desde donde esta el puntero archivo_texto.seek(0) # Se ubica en la posicion 0 print(archivo_texto.read(11))...
Python
zaydzuhri_stack_edu_python
string 题目:输入某年某月某日,判断这一天是这一年的第几天? 程序分析:以3月5日为例,应该先把前两个月的加起来, 然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于2时需考虑多加一天: from practice.year import * set y = integer input string 请输入年: set mouth = integer input string 请输入月份: set day = integer input string 请输入日: set md = dict 1 31 ; 2 0 ; 3 31 ; 4 30 ; 5 31 ; 6 30 ; 7 31 ; 8 31 ; 9 30 ; 10 ...
''' 题目:输入某年某月某日,判断这一天是这一年的第几天? 程序分析:以3月5日为例,应该先把前两个月的加起来, 然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于2时需考虑多加一天: ''' from practice.year import * y = int(input('请输入年:')) mouth = int(input('请输入月份:')) day = int(input('请输入日:')) md = {1: 31, 2: 0, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31} days = day if mouth...
Python
zaydzuhri_stack_edu_python
function test_derivative_upward_order2 sample_potential sample_g_zz begin comment Pad the potential field grid to improve accuracy set pad_width = dict string easting size // 3 ; string northing size // 3 comment need to drop upward coordinate (bug in xrft) set potential_padded = call pad call drop_vars string upward p...
def test_derivative_upward_order2(sample_potential, sample_g_zz): # Pad the potential field grid to improve accuracy pad_width = { "easting": sample_potential.easting.size // 3, "northing": sample_potential.northing.size // 3, } # need to drop upward coordinate (bug in xrft) potentia...
Python
nomic_cornstack_python_v1
function get_response self begin return response end function
def get_response(self): return self.response
Python
nomic_cornstack_python_v1
function test_calibration_synthetic begin set tuple train_data train_labels = call generate_synthetic_data p_correct=0.7 N=50 K=10 set temperature = call fit_temperature train_data train_labels assert call compute_ece train_data train_labels lbda=temperature < call compute_ece train_data train_labels end function
def test_calibration_synthetic(): train_data, train_labels = generate_synthetic_data(p_correct=.7, N=50, K=10) temperature = calibration.fit_temperature(train_data, train_labels) assert calibration.compute_ece(train_data, train_labels, lbda=temperature) < \ calibration.compute_ece(train_data, t...
Python
nomic_cornstack_python_v1
comment To support print() function in older versions from __future__ import print_function import sys import re from general import * function main begin comment Checking correct usage if length argv != 3 begin print string Usage: print string Give command as: python laracasts.py <starting page no.> <ending page no.> ...
from __future__ import print_function # To support print() function in older versions import sys import re from general import * def main(): ### Checking correct usage if len(sys.argv)!=3: print("Usage:\n") print("Give command as:\n\tpython laracasts.py <starting page no.> <ending page no.>\n") print("Exampl...
Python
zaydzuhri_stack_edu_python
comment Exercicio 26 comment Faça um programa que leia uma frase pelo teclado e mostre: Quantas vezes aparece a letra ‘A’ comment Em que posição ela aparece a primeira vez Em que posição ela aparece a última vez set frase = lower strip string input string Escreva uma frase: set quantidade = count frase string a set fir...
#Exercicio 26 #Faça um programa que leia uma frase pelo teclado e mostre: Quantas vezes aparece a letra ‘A’ # Em que posição ela aparece a primeira vez Em que posição ela aparece a última vez frase = str(input('Escreva uma frase: ')).strip().lower() quantidade = frase.count('a') first = frase.find('a') + 1 last ...
Python
zaydzuhri_stack_edu_python
comment encoding=utf-8 import sys set type = call getfilesystemencoding function printMax x y begin string 打印两个数中的最大值。 两个值必须是整数。 set x = integer x set y = integer y if x > y begin print x call unicode string 最大 end else begin print y call unicode string 最大 end end function call printMax 3 5 print __doc__
#encoding=utf-8 import sys type=sys.getfilesystemencoding() def printMax(x, y): '''打印两个数中的最大值。 两个值必须是整数。''' x = int(x) y = int(y) if x > y: print(x,unicode("最大")) else: print(y,unicode("最大")) printMax(3, 5) print(printMax.__doc__)
Python
zaydzuhri_stack_edu_python
function explore_missing dataframe target=string begin set total = sort values sum ascending=false set percent = sort values sum / count is null dataframe * 100 ascending=false set missing_data = concat list total percent axis=1 keys=list string Total string Percent print string missing rank head missing_data if expres...
def explore_missing(dataframe, target=''): total = dataframe.isnull().sum().sort_values(ascending = False) percent = (dataframe.isnull().sum()/dataframe.isnull().count()*100).sort_values(ascending = False) missing_data = pd.concat([total, percent], axis=1, keys=['Total', 'Percent']) print('mi...
Python
nomic_cornstack_python_v1
function step_delete test checks=none begin if checks is none begin set checks = list end call cmd string az networkcloud virtualmachine console delete --resource-group {resourceGroup} --virtual-machine-name {virtualMachineName} --yes checks=checks end function
def step_delete(test, checks=None): if checks is None: checks = [] test.cmd( "az networkcloud virtualmachine console delete --resource-group {resourceGroup} " "--virtual-machine-name {virtualMachineName} --yes", checks=checks, )
Python
nomic_cornstack_python_v1
class Product begin set ID = 0 function __init__ self name price begin set name = name set price = price call zwieksz_ID end function function print_info self begin return string Produkt { name } , id: { ID } , cena: { price } PLN end function decorator classmethod function zwieksz_ID self begin set ID = ID + 1 end fun...
class Product: ID = 0 def __init__(self, name, price): self.name = name self.price = price self.zwieksz_ID() def print_info(self): return f'Produkt {self.name}, id: {self.ID}, cena: {self.price} PLN' @classmethod def zwieksz_ID(self): self.ID += 1 class Bask...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Thu Jan 7 12:42:05 2021 A program that will process the text of the extracted frames @author: Joanna Makary import cv2 import os import numpy as np import pytesseract import re import pandas as pd comment Tells pytesseract where the tesseract environment is installed on l...
# -*- coding: utf-8 -*- """ Created on Thu Jan 7 12:42:05 2021 A program that will process the text of the extracted frames @author: Joanna Makary """ import cv2 import os import numpy as np import pytesseract import re import pandas as pd # Tells pytesseract where the tesseract environment is installed on local com...
Python
zaydzuhri_stack_edu_python
function test_invalid_quarter_string_returns_none self begin set invalid_quarter_return = call get_wallet_coin string Invalid assert is none invalid_quarter_return end function
def test_invalid_quarter_string_returns_none(self): invalid_quarter_return = self.customer.get_wallet_coin("Invalid") self.assertIsNone(invalid_quarter_return)
Python
nomic_cornstack_python_v1
string # Author Shivam Vishwakarma # sv6375261073@gmail.com import requests from bs4 import BeautifulSoup function twit_post url begin set URL = replace url string twitter.com string mobile.twitter.com print format string Trying with : {} URL set tuple text image url = tuple string string string with call Session as...
""" # Author Shivam Vishwakarma # sv6375261073@gmail.com """ import requests from bs4 import BeautifulSoup def twit_post(url): URL=url.replace('twitter.com','mobile.twitter.com') print('Trying with : {}'.format(URL)) text,image,url='','','' with requests.Session() as session: try: ...
Python
zaydzuhri_stack_edu_python
function test_LinkedPriceCheck self begin comment Basic price check info string Price checking Linked Item 1 via PLU call click string Price Check call enter_keypad string 014 after=string enter comment Confirm the right item, at the right price call read_price_check string Linked Item 1 string $1.00 comment Add the it...
def test_LinkedPriceCheck(self): # Basic price check self.log.info("Price checking Linked Item 1 via PLU") pos.click("Price Check") pos.enter_keypad("014", after="enter") # Confirm the right item, at the right price self.read_price_check("Linked Item 1", "$1.00")...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding: utf-8 comment In[1]: comment !/usr/bin/python comment -*- coding: utf-8 -*- import sys import getopt from datetime import datetime import pandas as pd from sqlalchemy import create_engine import warnings filter warnings string ignore comment In[2]: import pip comment In[3]: ...
#!/usr/bin/env python # coding: utf-8 # In[1]: #!/usr/bin/python # -*- coding: utf-8 -*- import sys import getopt from datetime import datetime import pandas as pd from sqlalchemy import create_engine import warnings warnings.filterwarnings('ignore') # In[2]: import pip # In[3]: import psycopg2 # In[13]: ...
Python
zaydzuhri_stack_edu_python
function start_time self begin return get pulumi self string start_time end function
def start_time(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "start_time")
Python
nomic_cornstack_python_v1
import random set word_file = string words.txt set word_list = list with open word_file string r as words begin for word in words begin set word = lower strip word if 3 < length word < 8 begin append word_list word end end end function generate_password begin return random choice word_list + random choice word_list + ...
import random word_file = "words.txt" word_list = [] with open(word_file, 'r') as words: for word in words: word = word.strip().lower() if 3 < len(word) < 8: word_list.append(word) def generate_password(): return random.choice(word_list) + random.choice(word_list) + random.choice...
Python
zaydzuhri_stack_edu_python
comment ! /usr/bin/env python function look_early_day_in_old_case str_arg begin call important_time str_arg print string go_government end function function important_time str_arg begin print str_arg end function if __name__ == string __main__ begin call look_early_day_in_old_case string number end
#! /usr/bin/env python def look_early_day_in_old_case(str_arg): important_time(str_arg) print('go_government') def important_time(str_arg): print(str_arg) if __name__ == '__main__': look_early_day_in_old_case('number')
Python
zaydzuhri_stack_edu_python
function parse_individuals source strict=true encoding=string utf8 base64_metadata=true table=none begin set sep = none if strict begin set sep = string end if table is none begin set table = call IndividualTable end comment Read the header and find the indexes of the required fields. set header = split strip read lin...
def parse_individuals( source, strict=True, encoding='utf8', base64_metadata=True, table=None): sep = None if strict: sep = "\t" if table is None: table = tables.IndividualTable() # Read the header and find the indexes of the required fields. header = source.readline().strip(...
Python
nomic_cornstack_python_v1
comment Developed by Henrique Treza comment Jogo do Detetive print string Programa Detetive print string Responda as perguntas abaixo com S (sim) ou N (nao) set perguntas = tuple string Voce telefonou para a vitima? string Voce esteve no local do crime? string Voce mora perto da vitima? string Voce devia para a vitima?...
# Developed by Henrique Treza #Jogo do Detetive print('Programa Detetive') print('Responda as perguntas abaixo com S (sim) ou N (nao)') perguntas = ('Voce telefonou para a vitima? ', 'Voce esteve no local do crime? ', 'Voce mora perto da vitima? ', 'Voce devia para a vitima? ',...
Python
zaydzuhri_stack_edu_python
function sparse_cross_entropy y_true y_pred begin comment Calculate the loss. This outputs a 2-rank tensor of shape [batch_size, sequence_length] set loss = call sparse_softmax_cross_entropy_with_logits labels=y_true logits=y_pred set loss_mean = call reduce_mean loss return loss_mean end function
def sparse_cross_entropy(y_true, y_pred): # Calculate the loss. This outputs a 2-rank tensor of shape [batch_size, sequence_length] loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y_true, logits=y_pred) loss_mean = tf.reduce_mean(loss) return loss_mean
Python
nomic_cornstack_python_v1
function map_embarrassingly_parallel input_list mapper project n_jobs=- 1 batch_size=- 1 checkpoint=false cleanup=true **kwargs begin string Process items in a list in parallel (optionally, one smaller batch at a time). Args: input_list: An input object that has a list-like interface (indexing and slicing). mapper: A f...
def map_embarrassingly_parallel(input_list, mapper, project, n_jobs=-1, batch_size=-1, checkpoint=False, cleanup=True, **kwargs): """ Process items in a list in parallel (optionally, one smaller batch at a time). Args: input_list: An input object that has a list-like...
Python
jtatman_500k
comment !/usr/bin/python comment http://www.movable-type.co.uk/scripts/latlong.html from math import * import sys set R = 6371.0 function getDistance pointALat pointALon pointBLat pointBLon begin set dLat = call radians pointBLat - pointALat set dLon = call radians pointBLon - pointALon set lat1 = call radians pointALa...
#!/usr/bin/python #http://www.movable-type.co.uk/scripts/latlong.html from math import * import sys R = 6371.000 def getDistance(pointALat,pointALon, pointBLat, pointBLon): dLat = radians( (pointBLat-pointALat) ) dLon = radians( (pointBLon-pointALon) ) lat1 = radians( pointALat ) lat2 = radians( poi...
Python
zaydzuhri_stack_edu_python
function test_get_season_19_march self calendar expected begin set date = call date 2017 3 19 assert call get_season date == expected end function
def test_get_season_19_march(self, calendar, expected): date = datetime.date(2017, 3, 19) assert calendar.get_season(date) == expected
Python
nomic_cornstack_python_v1
function find_zero matrix begin comment Get the number of rows and columns in the matrix set rows = length matrix set cols = length matrix at 0 comment Iterate through each element in the matrix for row in range rows begin for col in range cols begin comment Check if the current element is zero if matrix at row at col ...
def find_zero(matrix): # Get the number of rows and columns in the matrix rows = len(matrix) cols = len(matrix[0]) # Iterate through each element in the matrix for row in range(rows): for col in range(cols): # Check if the current element is zero if matrix[row][col] ...
Python
jtatman_500k
function get_target_info_table self target time_start=none time_stop=none begin set history = call get_target_info target time_start=time_start time_stop=time_stop set text = string set format = string %-16s %-5s %-5s %-5s %-5s %-5s %-5s set header = tuple string Date Local string UTC string LMST string HA string PA s...
def get_target_info_table(self, target, time_start=None, time_stop=None): history = self.get_target_info(target, time_start=time_start, time_stop=time_stop) text = '' format = '%-16s %-5s %-5s %-5s %-5s %-5s %-5s\n' header = ('Date Local'...
Python
nomic_cornstack_python_v1
import urllib from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup set url = string https://www.wartaekonomi.co.id/read223367/grab-incar-bidang-travel-dan-kesehatan.html set uClient = call uReq url set page_html = read uClient close uClient set page_soup = call soup page_html string html.par...
import urllib from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup url = 'https://www.wartaekonomi.co.id/read223367/grab-incar-bidang-travel-dan-kesehatan.html' uClient = uReq(url) page_html = uClient.read() uClient.close() page_soup = soup(page_html, "html.parser") containers = ...
Python
zaydzuhri_stack_edu_python
function test_cmdlineproc_test7 begin set parameters = dict string debug false ; string disconnect false ; string executable string ; string executableargs string ; string hosts string ; string job string ; string jobname string ; string log string ; string recover string ; string resource string ; string repli...
def test_cmdlineproc_test7(): parameters = { "debug": False, "disconnect": False, "executable": "", "executableargs": "", "hosts": "", "job": "", "jobname": "", "log": "", "recover": "", "resource": "", "replicates": "", ...
Python
nomic_cornstack_python_v1
comment calendar comment import calendar import datetime import time print call weekheader 3 print print call firstweekday print print call month 2020 4 print print call monthcalendar 2020 4 print call calendar 2020 set day_of_the_week = call weekday 2020 4 25 print print day_of_the_week set is_leap = call isleap 2020 ...
# calendar # import calendar import datetime import time print(calendar.weekheader(3)) print() print(calendar.firstweekday()) print() print(calendar.month(2020, 4)) print() print(calendar.monthcalendar(2020, 4)) print(calendar.calendar(2020)) day_of_the_week = calendar.weekday(2020, 4, 25) print() print(day_of_the...
Python
zaydzuhri_stack_edu_python
class Student begin function __init__ self first abc last=string abcd age=1 begin set first = first set last = last set age = age set abc = abc end function function display self begin return first + string + last end function function abcd hello begin return first end function end class comment a=Student('vamsi') set...
class Student: def __init__(self,first,abc,last="abcd",age=1): self.first=first self.last=last self.age=age self.abc=abc def display(self): return self.first+" "+self.last def abcd(hello): return hello.first #a=Student('vamsi') b=Student('harsha','abcd',10) ...
Python
zaydzuhri_stack_edu_python
function unpack_be16 data begin call _check_input_array data 2 return data at 1 + data at 0 ? 8 end function
def unpack_be16(data): _check_input_array(data, 2) return data[1] + (data[0] << 8)
Python
nomic_cornstack_python_v1