code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
from flask import Flask , request , jsonify set app = call Flask __name__ decorator call route string /reverse methods=list string POST function reverse begin set data = call get_json set text = data at string text set reversed_text = text at slice : : - 1 return call jsonify dict string reversed_text reversed_text e...
from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/reverse', methods=['POST']) def reverse(): data = request.get_json() text = data['text'] reversed_text = text[::-1] return jsonify({'reversed_text': reversed_text}) if __name__ == '__main__': app.run()
Python
flytech_python_25k
comment ticker kata comment https://www.codewars.com/kata/5a959662373c2e761d000183 function ticker text width tick begin set text = string * width + text set text = list text set output_text = string for num in range tick tick + width begin set index = num % length text set output_text = output_text + text at index e...
#ticker kata #https://www.codewars.com/kata/5a959662373c2e761d000183 def ticker(text, width, tick): text = ' '*width + text text = list(text) output_text = '' for num in range(tick, tick+width): index = num % len(text) output_text += text[index] return output_text
Python
zaydzuhri_stack_edu_python
function account_add self account is_default=false begin comment true if ok, false if duplicate (any other possible reasons? otherwise we need to throw exceptions) if account in accounts begin return false end if label is not none and call account_get_by_label label is not none begin raise call ValueError string Label ...
def account_add(self, account: Account, is_default=False) -> bool: # true if ok, false if duplicate (any other possible reasons? otherwise we need to throw exceptions) if account in self.accounts: return False if account.label is not None and self.account_get_by_label(account.label)...
Python
nomic_cornstack_python_v1
string Processing the data import pandas as pd import simplejson set acc_all_data = dict set cas_all_data = dict function save_obj o f_name begin with open f_name string w+ as of begin dump o of ignore_nan=true end end function comment for yr in range(1975, 2015):
""" Processing the data """ import pandas as pd import simplejson acc_all_data = {} cas_all_data = {} def save_obj(o, f_name): with open(f_name, "w+") as of: simplejson.dump(o, of, ignore_nan=True) # for yr in range(1975, 2015):
Python
zaydzuhri_stack_edu_python
function _get_scan_action_def self a_class begin if a_class == ServiceScan begin set cost = service_scan_cost end else if a_class == OSScan begin set cost = os_scan_cost end else if a_class == SubnetScan begin set cost = subnet_scan_cost end else if a_class == ProcessScan begin set cost = process_scan_cost end else beg...
def _get_scan_action_def(self, a_class): if a_class == ServiceScan: cost = self.scenario.service_scan_cost elif a_class == OSScan: cost = self.scenario.os_scan_cost elif a_class == SubnetScan: cost = self.scenario.subnet_scan_cost elif a_class == Proce...
Python
nomic_cornstack_python_v1
function setPixmaps self start end out begin set _start_pixmap = start set _end_pixmap = end set _out_pixmap = out end function
def setPixmaps(self, start, end, out): self._start_pixmap = start self._end_pixmap = end self._out_pixmap = out
Python
nomic_cornstack_python_v1
async function find_dialog self dialog_id begin string If the dialog cannot be found within the current `DialogSet`, the parent `DialogContext` will be searched if there is one. :param dialog_id: ID of the dialog to search for. :return: set dialog = await find dialogs dialog_id if dialog == none and parent != none begi...
async def find_dialog(self, dialog_id: str) -> Dialog: """ If the dialog cannot be found within the current `DialogSet`, the parent `DialogContext` will be searched if there is one. :param dialog_id: ID of the dialog to search for. :return: """ dialog = await self...
Python
jtatman_500k
function read_trace filename dataname k=100 begin set tracedef_path = absolute path path filename + string .dat with open tracedef_path string rb as f1 begin set text = read f1 end set blocks = split text b'#BEGINCHANNELHEADER' set time_block = blocks at 1 if find time_block b'Zeit' == - 1 begin pass end set ts = decim...
def read_trace(filename, dataname, k=100): tracedef_path = os.path.abspath(filename + '.dat') with open(tracedef_path, "rb") as f1: text = f1.read() blocks = text.split(b'#BEGINCHANNELHEADER') time_block = blocks[1] if time_block.find(b"Zeit") == -1: pass ...
Python
nomic_cornstack_python_v1
function test_publish_without_reviewer_or_group self begin set review_request = call create_review_request set draft = call create review_request set summary = string New summary set description = string New description set testing_done = string New testing done set branch = string New branch set bugs_closed = string 1...
def test_publish_without_reviewer_or_group(self): review_request = self.create_review_request() draft = ReviewRequestDraft.create(review_request) draft.summary = 'New summary' draft.description = 'New description' draft.testing_done = 'New testing done' draft.branch = 'Ne...
Python
nomic_cornstack_python_v1
from collections import Counter function scramble s1 s2 begin set counter1 = counter s1 set counter2 = counter s2 return length counter2 - counter1 == 0 end function if __name__ == string __main__ begin assert call scramble string rkqodlw string world assert call scramble string cedewaraaossoqqyt string codewars assert...
from collections import Counter def scramble(s1, s2): counter1 = Counter(s1) counter2 = Counter(s2) return len(counter2 - counter1) == 0 if __name__ == '__main__': assert scramble('rkqodlw', 'world') assert scramble('cedewaraaossoqqyt', 'codewars') assert not scramble('katas', 's...
Python
zaydzuhri_stack_edu_python
function write_error self status_code **kwargs begin set message = get responses status_code string set default_message = get responses status_code string comment HTTPError exceptions may have a log_message attribute if string exc_info in kwargs begin set tuple _ exc _ = kwargs at string exc_info if has attribute exc s...
def write_error(self, status_code, **kwargs): message = default_message = httplib.responses.get(status_code, '') # HTTPError exceptions may have a log_message attribute if 'exc_info' in kwargs: (_, exc, _) = kwargs['exc_info'] if hasattr(exc, 'log_message'): ...
Python
nomic_cornstack_python_v1
import os import sys import graph import generate_instance function generate_dataset output_dir begin for iteration in range 1 11 1 begin set tuple n1 n2 k cap = tuple 2000 20 5 10 set file_path = join path output_dir format string {}_{}_{}_{}_{}.txt n1 n2 k cap iteration set G = call mahadian_model_generator n1 n2 k c...
import os import sys import graph import generate_instance def generate_dataset(output_dir): for iteration in range(1, 11, 1): n1, n2, k, cap = 2000, 20, 5, 10 file_path = os.path.join(output_dir, '{}_{}_{}_{}_{}.txt'.format(n1, n2, k, cap, iteration)) G = generate_instance.mahadian_model_...
Python
zaydzuhri_stack_edu_python
string str → list[str] rows = ["", "", ""] So what is rows? rows represents each row in the verical orientation of our string if len(e) > len(rows): append "e" if len(e) == len(rows): rows[i] += e[e] if len(e) < len(rows): add " " for all missing spaces. given a string s = "HOW ARE YOU" s = ["HOW", "ARE", "YOU"] rows =...
''' str → list[str] rows = ["", "", ""] So what is rows? rows represents each row in the verical orientation of our string if len(e) > len(rows): append "e" if len(e) == len(rows): rows[i] += e[e] if len(e) < len(rows): add " " for all missing spaces. given a string s = "HOW ARE YOU" s = ["HOW", "ARE", "YOU"] ro...
Python
zaydzuhri_stack_edu_python
for i in arr begin if i + 1 not in arr or i - 1 not in arr begin set c = c + 1 end end print c
for i in arr: if i+1 not in arr or i-1 not in arr: c+=1 print(c)
Python
zaydzuhri_stack_edu_python
function path self begin return get pulumi self string path end function
def path(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "path")
Python
nomic_cornstack_python_v1
function _get_user_from_id cls id begin set me = call get_by_id integer id call get_points_log return me end function
def _get_user_from_id(cls, id): me = cls.get_by_id(int(id)) me.get_points_log() return me
Python
nomic_cornstack_python_v1
function signout begin call sign_out end function
def signout(): sign_out()
Python
nomic_cornstack_python_v1
comment -*- coding: UTF-8 -*- comment Dependencies import csv comment File Names set input_file1 = string election_data_1.csv set output_file1 = string output/election_results_1.txt set input_file2 = string election_data_2.csv set output_file2 = string output/election_results_2.txt comment parameters set total_votes_ca...
# -*- coding: UTF-8 -*- # Dependencies import csv # File Names input_file1 = "election_data_1.csv" output_file1 = "output/election_results_1.txt" input_file2 = "election_data_2.csv" output_file2 = "output/election_results_2.txt" # parameters total_votes_cast = 0 candidates_list = [] candidate_votes = {} perc_votes = ...
Python
zaydzuhri_stack_edu_python
function __load_ids self begin set table = table set UID = UID set pkey = name if UID in fields begin set has_uid = true set fields = tuple pkey UID end else begin set has_uid = false set fields = tuple pkey end set rfilter = rfilter set multiple = if expression rfilter is not none then multiple else true if not multip...
def __load_ids(self): table = self.table UID = current.xml.UID pkey = table._id.name if UID in table.fields: has_uid = True fields = (pkey, UID) else: has_uid = False fields = (pkey, ) rfilter = self.rfilter mult...
Python
nomic_cornstack_python_v1
function __eq__ self other begin if is instance other Listener begin return call is_equivalent callback details_filter=_details_filter end else begin return NotImplemented end end function
def __eq__(self, other): if isinstance(other, Listener): return self.is_equivalent(other.callback, details_filter=other._details_filter) else: return NotImplemented
Python
nomic_cornstack_python_v1
import os import argparse set file_dir = directory name path __file__ class TrainingOptions begin function __init__ self begin set parser = call ArgumentParser description=string Cityscape training options call add_argument string --data_path type=str help=string path to the training data default=join path file_dir str...
import os import argparse file_dir = os.path.dirname(__file__) class TrainingOptions: def __init__(self): self.parser = argparse.ArgumentParser(description="Cityscape training options") self.parser.add_argument("--data_path", type=str, ...
Python
zaydzuhri_stack_edu_python
import numpy as np function check_grad grad model params loss_class X Y_ begin comment Numerički izačunati gradijent set numGrad = call compute_numerical_gradient model params loss_class X Y_ comment Usporedi set brojnik = norm grad - numGrad set nazivnik = norm grad + norm numGrad set diff = brojnik / nazivnik if diff...
import numpy as np def check_grad(grad, model, params, loss_class, X, Y_): # Numerički izačunati gradijent numGrad = compute_numerical_gradient(model, params, loss_class, X, Y_) # Usporedi brojnik = np.linalg.norm(grad - numGrad) nazivnik = np.linalg.norm(grad) + np.linalg.norm(numGrad) diff ...
Python
zaydzuhri_stack_edu_python
function do_page_up self begin if cur_page <= 0 begin set cur_page = 0 end else begin set cur_page = cur_page - 1 call display_page cur_page end end function
def do_page_up(self): if self.cur_page <= 0: self.cur_page = 0 else: self.cur_page -= 1 self.display_page(self.cur_page)
Python
nomic_cornstack_python_v1
function get_conn self begin return __conn end function
def get_conn(self): return self.__conn
Python
nomic_cornstack_python_v1
comment Variables comment No declaration of variables required set a = 1 comment Python variables do not need explicit declaration to reserve memory space. set b = 2 comment The declaration happens automatically when you assign a value to a variable. comment The equal sign (=) is used to assign values to variables. set...
#Variables a=1 # No declaration of variables required b=2 # Python variables do not need explicit declaration to reserve memory space. # The declaration happens automatically when you assign a value to a variable. # The equal sign (=) is used to assign values to variables. c=a+b d=2...
Python
zaydzuhri_stack_edu_python
function descend_graph decision_graph node_name prng begin set node = decision_graph at node_name try begin set choice = call make_choice node at string choices prng if choice == string begin set decision = dict end else begin set decision = call descend_graph decision_graph choice prng end end except IndexError begi...
def descend_graph(decision_graph, node_name, prng): node = decision_graph[node_name] try: choice = make_choice(node['choices'], prng) if choice == '': decision = {} else: decision = descend_graph(decision_graph, choice, prng) except IndexError: decisi...
Python
nomic_cornstack_python_v1
string "********************************** Autor : Bristela Muñoz Burgos Carrera : Ingeniería en Informática Ramo : Programación Básica Modulo : M1-E1 Ejercicio 4 : Con lo aprendido hasta el momento, realiza un programa que de manera totalmente matemática (ocupando solo lo visto hasta el momento), muestre el digito ver...
""""********************************** Autor : Bristela Muñoz Burgos Carrera : Ingeniería en Informática Ramo : Programación Básica Modulo : M1-E1 Ejercicio 4 : Con lo aprendido hasta el momento, realiza un programa que de manera totalmente matemática (ocupando solo lo visto hasta el momento), mue...
Python
zaydzuhri_stack_edu_python
function evaluation self begin return _evaluation end function
def evaluation(self): return self._evaluation
Python
nomic_cornstack_python_v1
import os import csv import requests from bs4 import BeautifulSoup call system string clear function getLink value begin set pages = list for i in value begin set name = get text find i string span dict string class string company strip=true set link = find i string a at string href set brand_dict = dict string compan...
import os import csv import requests from bs4 import BeautifulSoup os.system("clear") def getLink(value): pages = [] for i in value: name = i.find("span", {"class": "company"}).get_text(strip=True) link = i.find("a")["href"] brand_dict = {"company": name, "link": link} pages....
Python
zaydzuhri_stack_edu_python
function ComovingRadialDistance self z0 z begin if call isscalar z begin if approx_highz begin set temp = 2.0 * c * 1.0 + z0 ^ - 0.5 - 1.0 + z ^ - 0.5 / hubble_0 / square root omega_m_0 end else begin comment Otherwise, do the integral - normalize to H0 for numerical reasons set integrand = lambda z -> hubble_0 / call ...
def ComovingRadialDistance(self, z0, z): if np.isscalar(z): if self.approx_highz: temp = 2. * c * ((1. + z0)**-0.5 - (1. + z)**-0.5) / self.hubble_0 / np.sqrt(self.omega_m_0) else: # Otherwise, do the integral - normalize to H0 for numerical reasons ...
Python
nomic_cornstack_python_v1
import scraperwiki import lxml.html import xlrd import re function get_policy root begin try begin set content = call text_content if string Pet Policy: in content begin return content at slice find content string Pet Policy: + 12 : : end else begin return string Empty Policy end end except IndexError begin return st...
import scraperwiki import lxml.html import xlrd import re def get_policy(root): try: content = root.cssselect('div#h-header div:last-child')[0].text_content() if ( 'Pet Policy:' in content): return content[content.find('Pet Policy:') + 12:] else: return 'Empty Policy...
Python
zaydzuhri_stack_edu_python
function contact request begin if method == string POST begin set message_name = POST at string message-name set message_email = POST at string message-email set message = POST at string message comment send an email call send_mail string message from + message_name message message_email list string leilynn78@gmail.com...
def contact(request): if request.method == "POST": message_name = request.POST['message-name'] message_email = request.POST['message-email'] message = request.POST['message'] # send an email send_mail( 'message from ' + message_name, # subject messag...
Python
nomic_cornstack_python_v1
comment iterando for v in s1 begin print v end comment para add comment adicionando elemento eme um set vazio set s1 = set comment ou update, mas o update adicona tudo quebrado dentro do python add s1 1 add s1 2 add s1 3 comment eliminando um elemnto discard s1 2 print s1 comment set não respeita ordem, podem aparecer ...
for v in s1: #iterando print(v) #para add s1 = set () #adicionando elemento eme um set vazio s1.add(1) #ou update, mas o update adicona tudo quebrado dentro do python s1.add(2) s1.add(3) s1.discard(2) #eliminando um elemnto print(s1) #set não respeita ordem, podem aparecer em qualquer ordem, e o set não aceita e...
Python
zaydzuhri_stack_edu_python
function main begin comment Print the docstring at the top of the file so your instructor can see your name. print __doc__ comment Sing each individual verse/chorus; comment/un-comment these lines as you work. title call verse1 string New York call verse2 call chorus1 4 call verse3 string good call verse4 string Delila...
def main(): # Print the docstring at the top of the file so your instructor can see your name. print( __doc__ ) # Sing each individual verse/chorus; comment/un-comment these lines as you work. title() verse1( "New York" ) verse2() chorus1( 4 ) verse3( "good" ) verse4( "Delilah" ) ...
Python
nomic_cornstack_python_v1
function decode_token_appengine credentials token verify=false begin return call _decode_token credentials token false end function
def decode_token_appengine(credentials, token, verify=False): return _decode_token(credentials, token, False)
Python
nomic_cornstack_python_v1
function creation_date_video path_to_file begin print string Last modified: %s % call ctime call getmtime path_to_file print string Created: %s % call ctime call getctime path_to_file end function comment return os.path.getctime(path_to_file)
def creation_date_video(path_to_file): print("Last modified: %s" % time.ctime(os.path.getmtime(path_to_file))) print("Created: %s" % time.ctime(os.path.getctime(path_to_file))) # return os.path.getctime(path_to_file)
Python
nomic_cornstack_python_v1
function get_hilo_activation_examples storm_activations num_high_activation_examples num_low_activation_examples unique_storm_cells full_storm_id_strings=none begin call assert_is_numpy_array storm_activations num_dimensions=1 call assert_is_boolean unique_storm_cells set num_examples = length storm_activations if uniq...
def get_hilo_activation_examples( storm_activations, num_high_activation_examples, num_low_activation_examples, unique_storm_cells, full_storm_id_strings=None): error_checking.assert_is_numpy_array(storm_activations, num_dimensions=1) error_checking.assert_is_boolean(unique_storm_cells)...
Python
nomic_cornstack_python_v1
function isspace a begin return call _vec_string a bool_ string isspace end function
def isspace(a): return _vec_string(a, bool_, 'isspace')
Python
nomic_cornstack_python_v1
function returnpivots pdo pdh pdl pdc begin set p = pdh + pdl + pdc / 3 set r1 = 2 * p - pdl set r2 = p + pdh - pdl set r3 = r1 + pdh - pdl set s1 = 2 * p - pdh set s2 = p - pdh - pdl set s3 = s1 - pdh - pdl set listpivots = list r3 r2 r1 p s1 s2 s3 return listpivots end function set pivotlist = call returnpivots 14237...
def returnpivots(pdo,pdh,pdl,pdc): p=(pdh+pdl+pdc)/3 r1=(2*p)-pdl r2=p+(pdh-pdl) r3=r1+(pdh-pdl) s1=(2*p)-pdh s2=p-(pdh-pdl) s3=s1-(pdh-pdl) listpivots=[r3,r2,r1,p,s1,s2,s3] return listpivots pivotlist=returnpivots(14237.95,14237.95,13929.3,13967.5) print("Pivots are:",pivotlist)
Python
zaydzuhri_stack_edu_python
import numpy as np import matplotlib.pyplot as plt from matplotlib import style from sklearn import svm function exampleVisualizationToUnderstandSVMBetter begin call use string ggplot set x = list 1 5 1.5 8 1 9 set y = list 2 8 1.8 8 0.6 11 scatter plt x y show end function function svcOnDataWithMultipleFeatures begin ...
import numpy as np import matplotlib.pyplot as plt from matplotlib import style from sklearn import svm def exampleVisualizationToUnderstandSVMBetter(): style.use("ggplot") x = [1, 5, 1.5, 8, 1, 9] y = [2, 8, 1.8, 8, 0.6 ,11] plt.scatter(x, y) plt.show() def svcOnDataWithMultipleFeatures(): X = np.array([[1,...
Python
zaydzuhri_stack_edu_python
function test_good_address_release self begin set ctx = call mock_ctx string test_good_address_delete set ctx=ctx set address = call get_address set runtime_properties at string aws_resource_id = public_ip set runtime_properties at string allocation_id = string random delete ctx=ctx assert not in string aws_resource_id...
def test_good_address_release(self): ctx = self.mock_ctx('test_good_address_delete') current_ctx.set(ctx=ctx) address = self.get_address() ctx.instance.runtime_properties['aws_resource_id'] = \ address.public_ip ctx.instance.runtime_properties['allocation_id'] = 'ran...
Python
nomic_cornstack_python_v1
function form_valid self form begin set url = cleaned_data at string url set crop_feed = cleaned_data at string crop_feed set service = call WeiboCaptureService url auto_login=true set user_media_path = call generate_user_media_image_path name=string capture prefix=string weibo set file_path = join path MEDIA_ROOT user...
def form_valid(self, form): url = form.cleaned_data['url'] crop_feed = form.cleaned_data['crop_feed'] service = WeiboCaptureService(url, auto_login=True) self.user_media_path = utils.generate_user_media_image_path(name='capture', prefix='weibo') file_path = os.path.join(settings....
Python
nomic_cornstack_python_v1
function get_paths_cfg sys_file=string pythran.cfg platform_file=format string pythran-{}.cfg platform user_file=string .pythranrc begin string >>> os.environ['HOME'] = '/tmp/test' >>> get_paths_cfg()['user'] '/tmp/test/.pythranrc' >>> os.environ['HOME'] = '/tmp/test' >>> os.environ['XDG_CONFIG_HOME'] = '/tmp/test2' >>...
def get_paths_cfg( sys_file='pythran.cfg', platform_file='pythran-{}.cfg'.format(sys.platform), user_file='.pythranrc' ): """ >>> os.environ['HOME'] = '/tmp/test' >>> get_paths_cfg()['user'] '/tmp/test/.pythranrc' >>> os.environ['HOME'] = '/tmp/test' >>> os.environ['XDG_CONFIG_HOME']...
Python
jtatman_500k
function ssh_message begin comment Sample message: comment Apr 27 02:20:28 server sshd[10587]: Failed password for root from 10.0.10.1 port 46899 ssh2 set dte = string format time now string %b %d %Y %H:%M:%S set host = call gethostname set pid = call randrange 5000 10000 comment standard Linux ephemeral port range bel...
def ssh_message(): # Sample message: # Apr 27 02:20:28 server sshd[10587]: Failed password for root from 10.0.10.1 port 46899 ssh2 dte = datetime.datetime.now().strftime('%b %d %Y %H:%M:%S') host = socket.gethostname() pid = random.randrange(5000, 10000) # standard Linux ephemeral port range be...
Python
nomic_cornstack_python_v1
string Nombre: Traductor de Assembly a Binario y Hexadecimal a Assembly. Autores: Luis Alberto Salazar y Guido Ernesto Salazar. Fecha: febrero/marzo 2021. from FuncionesBin import assemblyBin , bin_a_hexa from FuncionesHexa import hexaAssem function main begin set ver = true while ver begin print string print string ==...
""" Nombre: Traductor de Assembly a Binario y Hexadecimal a Assembly. Autores: Luis Alberto Salazar y Guido Ernesto Salazar. Fecha: febrero/marzo 2021. """ from FuncionesBin import assemblyBin, bin_a_hexa from FuncionesHexa import hexaAssem def main(): ver = True while ver: print("") print("==...
Python
zaydzuhri_stack_edu_python
function test_update_with_multiple_values self begin set rendered_result = call _render_tag tag=string {% querystring "update" "foo=bar=baz" %} query_str=string foo=foo assert true starts with rendered_result string ? assert equal call QueryDict rendered_result at slice 1 : : call QueryDict string foo=bar=baz end func...
def test_update_with_multiple_values(self): rendered_result = self._render_tag( tag='{% querystring "update" "foo=bar=baz" %}', query_str='foo=foo') self.assertTrue(rendered_result.startswith('?')) self.assertEqual(QueryDict(rendered_result[1:]), ...
Python
nomic_cornstack_python_v1
from flask_restplus import Resource from app.set_api import api from app.vg_sales_search.api_models import VG from data_base.db_model import Vgsales from sqlalchemy import desc from flask import request from app.vg_sales_search.parsing import parse_arguments , parse_arguments_2 , parse_arguments_3 from werkzeug.excepti...
from flask_restplus import Resource from app.set_api import api from app.vg_sales_search.api_models import VG from data_base.db_model import Vgsales from sqlalchemy import desc from flask import request from app.vg_sales_search.parsing import parse_arguments, parse_arguments_2, parse_arguments_3 from werkzeug.exception...
Python
zaydzuhri_stack_edu_python
function set_log_dir self model_path=none begin comment Set date and epoch counter as if starting a new model set epoch = 0 set now = now comment If we have a model path with date and epochs use them if model_path begin comment Continue from we left of. Get epoch and date from the file name comment A sample model path ...
def set_log_dir(self, model_path=None): # Set date and epoch counter as if starting a new model self.epoch = 0 now = datetime.datetime.now() # If we have a model path with date and epochs use them if model_path: # Continue from we left of. Get epoch and date from the...
Python
nomic_cornstack_python_v1
comment Lab 6-1-2 question 7 comment By Julan Ray Avila Gutierrez, jra0108@arastudent.ac.nz set SUCCESSFUL_CLEAR = string All the items have been removed from the list. set EMPTY_LIST_MSG = string Sorry, the list is empty. function empty_list user_list begin string Clears the items from the list and returns boolean Tru...
# Lab 6-1-2 question 7 # By Julan Ray Avila Gutierrez, jra0108@arastudent.ac.nz SUCCESSFUL_CLEAR = "All the items have been removed from the list." EMPTY_LIST_MSG = "Sorry, the list is empty." def empty_list(user_list): """ Clears the items from the list and returns boolean True. If there...
Python
zaydzuhri_stack_edu_python
function BoundingBox self frame begin return call EnlargeBounds frame list array list list inf list inf list inf array list list - inf list - inf list - inf end function
def BoundingBox(self, frame): return self.EnlargeBounds(frame, [np.array([[np.inf], [np.inf], [np.inf]]), np.array([[-np.inf], [-np.inf], [-np.inf]])])
Python
nomic_cornstack_python_v1
comment coding:utf-8 from tkinter import * from tkinter.filedialog import * set root = call Tk call geometry string 530x200 function text01 begin with call askopenfile title=string 上传文件 initialdir=string e: filetypes=list tuple string 可读文件 string .txt as f begin set show at string text = read f end end function call pa...
# coding:utf-8 from tkinter import * from tkinter.filedialog import * root = Tk() root.geometry('530x200') def text01(): with askopenfile(title='上传文件', initialdir='e:', filetypes=[('可读文件', '.txt')])as f: show['text'] = f.read() Button(root, text='选择读取的文本', command=text01).pack() show = Label(root, width...
Python
zaydzuhri_stack_edu_python
import datatable as dtbl import os as os from pathlib import Path import zipfile , urllib.request , shutil , tarfile string The file handles **ALL** type of data sources (wish list) The datatable import $ pip install datatable. If this command fails for newer version of python then un following directly from git repo $...
import datatable as dtbl import os as os from pathlib import Path import zipfile, urllib.request, shutil, tarfile """ The file handles **ALL** type of data sources (wish list) The datatable import $ pip install datatable. If this command fails for newer version of python then un following directly from git repo $ pip...
Python
zaydzuhri_stack_edu_python
import argparse import tensorflow as tf from tensorflow.python.keras.applications import vgg16 from tensorflow.python.keras.optimizers import SGD from cifar_data_loader import Cifar10Loader from tools import get_logger function create_vgg16 num_classes begin set model = call VGG16 include_top=true weights=none input_te...
import argparse import tensorflow as tf from tensorflow.python.keras.applications import vgg16 from tensorflow.python.keras.optimizers import SGD from cifar_data_loader import Cifar10Loader from tools import get_logger def create_vgg16(num_classes): model = vgg16.VGG16(include_top=True, weights=None, input_tens...
Python
zaydzuhri_stack_edu_python
import os import cv2 import glob import math import logging import numpy as np import matplotlib.pyplot as plt from scipy.spatial.kdtree import KDTree function get_img_id i begin set num_digits = length string i set id = string 0 * 4 - num_digits set id = id + string i return id end function function create_dir dir_pat...
import os import cv2 import glob import math import logging import numpy as np import matplotlib.pyplot as plt from scipy.spatial.kdtree import KDTree def get_img_id(i): num_digits = len(str(i)) id = "0" * (4 - num_digits) id += str(i) return id def create_dir(dir_path): if not os.path.exists(di...
Python
zaydzuhri_stack_edu_python
function precommit self begin set order = call order set blinder = random comment Set the value of the two internal secrets set value = value * blinder % order set value = - blinder % order set precommitment = blinder * value * h - lhs at 1 return precommitment end function
def precommit(self): order = self.g.group.order() blinder = order.random() # Set the value of the two internal secrets self.alpha.value = self.x.value * blinder % order self.beta.value = -blinder % order precommitment = blinder * (self.x.value * self.h - self.lhs[1]) ...
Python
nomic_cornstack_python_v1
function remove_longnan_uc uc fhr num=20 begin comment Calculate streaks, filter out streaks that are too short, apply global mask set nan_spots = where call isnan uc set diff = diff np nan_spots at 0 set streaks = split np nan_spots at 0 where diff != 1 at 0 + 1 set long_streaks = set horizontal stack list comprehensi...
def remove_longnan_uc(uc: np.array, fhr: np.array, num: int = 20) -> Tuple[np.array, np.array]: # Calculate streaks, filter out streaks that are too short, apply global mask nan_spots = np.where(np.isnan(uc)) diff = np.diff(nan_spots)[0] streaks = np.split(nan_spots[0], np.where(diff != 1)[0]+1) lon...
Python
nomic_cornstack_python_v1
function ape begin return call OKJSONResponse APE_CODE end function
def ape(): return OKJSONResponse(APE_CODE)
Python
nomic_cornstack_python_v1
comment 读取 POSCAR 文件, 输出原胞基矢以及倒格矢基矢.2019年4月3日. function Write filepath begin try begin with open filepath string r encoding=string utf-8 as f begin set content = read lines f end end except any begin print string POSCAR不存在或文件名错误! end set line1 = strip content at 0 string print format string {0:-^73} string 该体系为: + line...
##读取 POSCAR 文件, 输出原胞基矢以及倒格矢基矢.2019年4月3日. def Write(filepath): try: with open(filepath,'r',encoding = 'utf-8') as f: content = f.readlines() except: print('POSCAR不存在或文件名错误!') line1 = content[0].strip('\n') print('{0:-^73}'.format('该体系为:'+ line1)+'\n') line3 = content[2].sp...
Python
zaydzuhri_stack_edu_python
function main_parse_args begin set parser = call ArgumentParser set parser = call add_config_args parser set args = call parse_args set config_opts = argv at slice 1 : : comment add working_dir to config_opts set found_wd = false for opt in list string -wd string --working_dir begin if opt in config_opts begin set fo...
def main_parse_args(): parser = ArgumentParser() parser = cf.add_config_args(parser) args = parser.parse_args() config_opts = sys.argv[1:] # add working_dir to config_opts found_wd = False for opt in ['-wd', '--working_dir']: if opt in config_opts: found_wd = True if ...
Python
nomic_cornstack_python_v1
import sys import requests from requests.auth import HTTPBasicAuth set Backend = string http://localhost:10000/clipboard if length argv == 5 begin set tuple Program User Pwd Content Expiry = argv set Expiry = integer Expiry set payload = dict string User User ; string Pwd Pwd ; string Content Content ; string Expiry Ex...
import sys import requests from requests.auth import HTTPBasicAuth Backend = 'http://localhost:10000/clipboard' if len(sys.argv) == 5: Program, User, Pwd, Content, Expiry = sys.argv Expiry = int(Expiry) payload = { 'User':User, 'Pwd':Pwd, 'Content':Content, 'Expiry':Expiry } elif len(sys.ar...
Python
zaydzuhri_stack_edu_python
function git_branch_rename new_name begin comment type: (str) -> None string Rename the current branch Args: new_name (str): New name for the current branch. set curr_name = name if curr_name not in call protected_branches begin info format string Renaming branch from <33>{}<32> to <33>{} curr_name new_name run format ...
def git_branch_rename(new_name): # type: (str) -> None """ Rename the current branch Args: new_name (str): New name for the current branch. """ curr_name = git.current_branch(refresh=True).name if curr_name not in git.protected_branches(): log.info("Renaming branch ...
Python
jtatman_500k
comment Pratice task: set name = string bob print string Hello + name comment Challenge: set word1 = string the set word2 = string cat set word3 = string sat set word4 = string on set word5 = string the set word6 = string mat print string ' + word1 + word2 + word3 + word4 + word5 + word6 + string ' comment Yes I comple...
#Pratice task: name='bob' print('Hello '+name) #Challenge: word1='the ' word2='cat ' word3='sat ' word4='on ' word5='the ' word6='mat ' print("'" + word1 + word2 + word3 + word4 + word5 + word6 + "'") #Yes I completed it succesfullythe assignment. #I encountered only one error, it was when I tired to add spaces to the ...
Python
zaydzuhri_stack_edu_python
import math function is_prime n begin if n <= 1 begin return false end for i in range 2 integer square root n + 1 begin if n % i == 0 begin return false end end return true end function function unique_prime_elements arr1 arr2 begin set unique_elements = set arr1 + arr2 set prime_elements = list for element in unique_...
import math def is_prime(n): if n <= 1: return False for i in range(2, int(math.sqrt(n)) + 1): if n % i == 0: return False return True def unique_prime_elements(arr1, arr2): unique_elements = set(arr1 + arr2) prime_elements = [] for element in unique_elements: ...
Python
jtatman_500k
function write_to_config key value section=string BLENDER_SETUP begin set config = config parser if exists path config_file begin read config config_file end if section not in config begin set config at section = dict end set config at section at key = value with open config_file string w as configfile begin write con...
def write_to_config(key, value, section='BLENDER_SETUP'): config = configparser.ConfigParser() if os.path.exists(config_file): config.read(config_file) if section not in config: config[section] = {} config[section][key] = value with open(config_file, 'w') as configfile: config.write(configfile)
Python
nomic_cornstack_python_v1
import scrapy from scrapy.spiders import CrawlSpider , Rule from scrapy.linkextractors import LinkExtractor from DataCrawler.items import CrawlersItem from datetime import datetime class GazpromSpider extends CrawlSpider begin set name = string Gazprom set allowed_domains = list string gazpromvacancy.ru set start_urls ...
import scrapy from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor from DataCrawler.items import CrawlersItem from datetime import datetime class GazpromSpider(CrawlSpider): name = 'Gazprom' allowed_domains = ['gazpromvacancy.ru'] start_urls = ['https://www.gazpromva...
Python
zaydzuhri_stack_edu_python
import pandas as pd import numpy as np import copy comment %matplotlib inline set df_graduates = read csv string graduates_raw.csv print head df_graduates print info call boxplot string Sexe string Ani rot=30 figsize=tuple 5 6
import pandas as pd import numpy as np import copy #%matplotlib inline df_graduates = pd.read_csv('graduates_raw.csv') print(df_graduates.head()) print(df_graduates.info()) df_graduates.boxplot('Sexe','Ani',rot = 30,figsize=(5,6))
Python
zaydzuhri_stack_edu_python
function test_amin_general_function_06 self begin set result = call amin maxvaltest maxlen=5 nosimd=true assert equal result min maxvaltest at slice : 5 : end function
def test_amin_general_function_06(self): result = arrayfunc.amin(self.maxvaltest, maxlen=5 , nosimd=True) self.assertEqual(result, min(self.maxvaltest[:5]))
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Fri Oct 13 18:29:16 2017 import pandas as pd import nltk import pickle set filename = string subjclueslen1-HLTEMNLP05.tff set data = list set words_with_value = dict with open filename as f begin for line in f begin set line = split line string at 0 set line = split lin...
# -*- coding: utf-8 -*- """ Created on Fri Oct 13 18:29:16 2017 """ import pandas as pd import nltk import pickle filename = "subjclueslen1-HLTEMNLP05.tff" data= [] words_with_value = {} with open(filename) as f: for line in f: line = line.split("\n")[0] line = line.split("\r")[0] ...
Python
zaydzuhri_stack_edu_python
import random function main begin set txt = open string RawInputs.txt string w set numLen = random integer 50 100 set numList = list for i in range numLen begin append numList string random integer 0 100 end write txt join string numList close txt print string Done end function call main
import random def main(): txt = open("RawInputs.txt",'w') numLen = random.randint(50,100) numList = [] for i in range(numLen): numList.append(str(random.randint(0,100))) txt.write(" ".join(numList)) txt.close() print('Done') main()
Python
zaydzuhri_stack_edu_python
import gym import numpy as np import matplotlib.pyplot as plt import itertools from collections import defaultdict import tqdm import gym_gridworld from pylab import * set mapFiles = list string map1.txt string map2.txt string map3.txt set figuretitle = list string Policy Gradient Problem A string Policy Gradient Probl...
import gym import numpy as np import matplotlib.pyplot as plt import itertools from collections import defaultdict import tqdm import gym_gridworld from pylab import * mapFiles = ["map1.txt", "map2.txt", "map3.txt"] figuretitle = ['Policy Gradient Problem A', 'Policy Gradient Problem B', 'Pol...
Python
zaydzuhri_stack_edu_python
if a * b == c begin print string a умножить на b равно c end else begin print string a умножить на b не равно c end if a * c + b == 0 begin print string c является решением линейного уравнения ax + b = 0 end else begin print string c не является решением линейного уравнения ax + b = 0 end
if (a*b==c): print("a умножить на b равно c") else: print("a умножить на b не равно c") if (a*c+b==0): print("c является решением линейного уравнения ax + b = 0") else: print("c не является решением линейного уравнения ax + b = 0")
Python
zaydzuhri_stack_edu_python
function f s begin if length s == 1 begin return d at s end if ends with s string + begin return f dist s at slice : - 1 : end else if starts with s string - begin return 1 + f dist join string list comprehension dict string - string + ; string + string - at c for c in s end else begin return 1 + f dist string - * fi...
def f(s): if len(s) == 1: return d[s] if s.endswith('+'): return f(s[:-1]) elif s.startswith('-'): return 1 + f("".join([{"-":"+", "+":"-"}[c] for c in s])) else: return 1 + f('-'*s.find('-')+s[s.find('-'):])
Python
zaydzuhri_stack_edu_python
function test_pk_fields self begin class TestSerializer extends DocumentSerializer begin class Meta begin set model = AutoFieldModel set fields = tuple string pk string auto_field end class end class set expected = call dedent string TestSerializer(): pk = IntegerField(read_only=True) auto_field = IntegerField(read_onl...
def test_pk_fields(self): class TestSerializer(DocumentSerializer): class Meta: model = AutoFieldModel fields = ('pk', 'auto_field') expected = dedent(""" TestSerializer(): pk = IntegerField(read_only=True) auto_fie...
Python
nomic_cornstack_python_v1
for i in range L R + 1 begin for j in range i + 1 R + 1 begin set ans = min ans i * j % 2019 if ans == 0 begin print 0 exit end end end print ans
for i in range(L, R+1): for j in range(i+1, R+1): ans = min(ans, i * j % 2019) if ans == 0: print(0) exit() print(ans)
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- set n = integer input set i = 2 while true begin print format string {}^2 = {} i i ^ 2 set i = i + 2 if i > n begin break end end
# -*- coding: utf-8 -*- n = int(input()) i = 2 while True: print('{}^2 = {}'.format(i, i**2)) i += 2 if i > n: break
Python
zaydzuhri_stack_edu_python
function update_user_stat_item_value_1 stat_code user_id additional_key=none body=none namespace=none x_additional_headers=none **kwargs begin if namespace is none begin set tuple namespace error = call get_services_namespace if error begin return tuple none error end end set request = call create stat_code=stat_code u...
def update_user_stat_item_value_1( stat_code: str, user_id: str, additional_key: Optional[str] = None, body: Optional[StatItemUpdate] = None, namespace: Optional[str] = None, x_additional_headers: Optional[Dict[str, str]] = None, **kwargs ): if namespace is None: namespace, error...
Python
nomic_cornstack_python_v1
comment from collections import deque # queue LIFO & FIFO comment # LIFO - Last in first out comment # FIFO - First in first out comment class MemorizingDict(dict): comment history = deque(maxlen=10) comment def set(self, key, value): comment self.history.append(key) # MemorizingDict.history comment self[key] = value #...
# from collections import deque # queue LIFO & FIFO # # # # LIFO - Last in first out # # # FIFO - First in first out # # class MemorizingDict(dict): # history = deque(maxlen=10) # # def set(self, key, value): # self.history.append(key) # MemorizingDict.history # self[key] = value # memDict = ...
Python
zaydzuhri_stack_edu_python
function url_filename_conditions self begin return get pulumi self string url_filename_conditions end function
def url_filename_conditions(self) -> Optional[Sequence['outputs.FrontdoorRuleConditionsUrlFilenameCondition']]: return pulumi.get(self, "url_filename_conditions")
Python
nomic_cornstack_python_v1
import torch from torch.autograd import Function class DiceCoeff extends Function begin function forward self input target begin call saved input target set eps = 0.0001 set inter = dot view input - 1 view target - 1 set union = sum input + sum target + eps return 2 * decimal + eps / decimal end function function backw...
import torch from torch.autograd import Function class DiceCoeff(Function): def forward(self, input, target): self.saved(input, target) eps = 0.0001 self.inter = torch.dot(input.view(-1), target.view(-1)) self.union = torch.sum(input) + torch.sum(target) + eps return (2*sel...
Python
zaydzuhri_stack_edu_python
function find_average num1 num2 num3 begin return num1 + num2 + num3 / 3 end function
def find_average(num1, num2, num3): return (num1 + num2 + num3) / 3
Python
flytech_python_25k
function removeAdopted credInstances orphanedInstances begin comment Make sure we have a copy of the keys not just an iterator comment since we'll be deleting for k in list keys credInstances begin if k not in orphanedInstances begin pop credInstances k end end end function
def removeAdopted(credInstances, orphanedInstances): # Make sure we have a copy of the keys not just an iterator # since we'll be deleting for k in list(credInstances.keys()): if k not in orphanedInstances: credInstances.pop(k)
Python
nomic_cornstack_python_v1
function create_tokenizer_from_hub_module begin set bert_module = call Module bert_path set tokenization_info = call bert_module signature=string tokenization_info as_dict=true set tuple vocab_file do_lower_case = run list tokenization_info at string vocab_file tokenization_info at string do_lower_case return call Full...
def create_tokenizer_from_hub_module(): bert_module = hub.Module(bert_path) tokenization_info = bert_module(signature="tokenization_info", as_dict=True) vocab_file, do_lower_case = sess.run( [ tokenization_info["vocab_file"], tokenization_info["do_lower_case"], ] ...
Python
nomic_cornstack_python_v1
import unittest from location import * class TestLab1 extends TestCase begin function test_repr self begin set loc = call Location string SLO 35.3 - 120.7 assert equal call repr loc string Location('SLO', 35.3, -120.7) end function comment Add more tests! function test_equal self begin set loc1 = call Location string S...
import unittest from location import * class TestLab1(unittest.TestCase): def test_repr(self): loc = Location("SLO", 35.3, -120.7) self.assertEqual(repr(loc), "Location('SLO', 35.3, -120.7)") # Add more tests! def test_equal(self): loc1 = Location("SLO", 35.3, -120.7) loc...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python string Remove an rpm from an active distrobution and copy it to the attic import os import shutil import sys import cp_rpm import rpm_config
#!/usr/bin/env python """ Remove an rpm from an active distrobution and copy it to the attic """ import os import shutil import sys import cp_rpm import rpm_config
Python
zaydzuhri_stack_edu_python
function ensure_memoryview obj begin if not is instance obj memoryview begin set obj = call memoryview obj end if not nbytes begin comment Drop `obj` reference to permit freeing underlying data return call memoryview bytearray end else if not contiguous begin comment Copy to contiguous form of expected shape & type ret...
def ensure_memoryview(obj: bytes | bytearray | memoryview | PickleBuffer) -> memoryview: if not isinstance(obj, memoryview): obj = memoryview(obj) if not obj.nbytes: # Drop `obj` reference to permit freeing underlying data return memoryview(bytearray()) elif not obj.contiguous: ...
Python
nomic_cornstack_python_v1
function f begin global x set x = 20 end function print x f dist print x
def f(): global x x = 20 print(x) f() print(x)
Python
zaydzuhri_stack_edu_python
function etree_to_string root pretty_print=true xml_declaration=true encoding=string utf-8 begin string Dump XML etree as a string. return decode call tostring root pretty_print=pretty_print xml_declaration=xml_declaration encoding=encoding string utf-8 end function
def etree_to_string(root, pretty_print=True, xml_declaration=True, encoding='utf-8'): """Dump XML etree as a string.""" return etree.tostring( root, pretty_print=pretty_print, xml_declaration=xml_declaration, encoding=encoding, ).decode('utf-8')
Python
jtatman_500k
string " 3. Given two integers a and b, you need to concatenate them so the output is ab. function utility begin comment The two lines below take input. set a = integer input set b = integer input comment Complete the code below to concatenate a and b set ans = string a + string b comment Complete the code above to con...
"""" 3. Given two integers a and b, you need to concatenate them so the output is ab. """ def utility(): #The two lines below take input. a=int(input()) b=int(input()) #Complete the code below to concatenate a and b ans= str(a) + str(b) #Complete the code above to concatenate a and b ...
Python
zaydzuhri_stack_edu_python
print join string list comprehension string i * 2 for i in range 1 16 3 if i % 2 == 0
print(" ".join([str(i * 2) for i in range(1, 16, 3) if i % 2 == 0]))
Python
zaydzuhri_stack_edu_python
string 4. Experiment with 'glob' (see below) Using the glob library you can more easily open a set of files. Notice how I use the shell '*' character to match *_cdp.txt. I could then open all of these files and process the data inside of them. >>>> CODE <<<< # This code assumes that all of the CDP files are in a subdir...
''' 4. Experiment with 'glob' (see below) Using the glob library you can more easily open a set of files. Notice how I use the shell '*' character to match *_cdp.txt. I could then open all of these files and process the data inside of them. >>>> CODE <<<< # This code assumes that all of the CDP files are in a subd...
Python
zaydzuhri_stack_edu_python
function full self begin function merge _df _newdf begin return merge loc at tuple slice : : difference columns list string date how=string outer on=list string timestamp left_index=true right_index=true end function set df = reduce merge generator expression _df for tuple _property _filetype in _specs for _df in li...
def full(self): def merge(_df, _newdf): return _df.merge( _newdf.loc[:, _newdf.columns.difference(["date"])], how="outer", on=["timestamp"], left_index=True, right_index=True, ) df = reduce( ...
Python
nomic_cornstack_python_v1
from selenium import webdriver from uuid import uuid4 function test_registration_and_login begin set url = string http://selenium1py.pythonanywhere.com/ru/accounts/login/ try begin set browser = call Chrome get browser url call implicitly_wait 5 comment Генерируем данные для регистрации set email = string { uuid 4 } @c...
from selenium import webdriver from uuid import uuid4 def test_registration_and_login(): url = "http://selenium1py.pythonanywhere.com/ru/accounts/login/" try: browser = webdriver.Chrome() browser.get(url) browser.implicitly_wait(5) # Генерируем данные для регистрации e...
Python
zaydzuhri_stack_edu_python
function hill X Y begin set x0 = 71.6 set z0 = 1.1159 - 3.0 set slope = tan - 31.0 * pi / 180.0 set Z = z0 + slope * X - x0 + 0.5 * cos X - x0 * sin Y return Z end function
def hill(X,Y): x0 = 71.60 z0 = 1.1159 - 3.0 slope = np.tan(-31.0*np.pi/180.0) Z = z0 + slope*(X-x0) + 0.5*np.cos(X-x0)*np.sin(Y) return Z
Python
nomic_cornstack_python_v1
function __init__ self db event_handler begin set db = db set cur = call get_cursor set event_handler = event_handler set stored_answer = true end function
def __init__(self, db, event_handler): self.db = db self.cur = db.get_cursor() self.event_handler = event_handler self.stored_answer = True
Python
nomic_cornstack_python_v1
function scrape self keyword quantity begin print string .....................Scraping { keyword } listings from eBay..................... Please be patient as this would take some time try begin set __keyword = keyword set baseurl = string https://www.ebay.com/sch/i.html?_from=R40&_nkw= { __keyword } &_sacat=0 set __p...
def scrape(self, keyword: str, quantity: int) -> pd.DataFrame: print(f""".....................Scraping {keyword} listings from eBay..................... Please be patient as this would take some time""") try: self.__keyword = keyword baseurl = f"https://www.ebay.co...
Python
nomic_cornstack_python_v1
function oneBitHalfSubtractor X Y begin set D = list set B = list for i in range 0 4 begin set b = not X at i and Y at i if b begin append B 1 end else begin append B 0 end end comment D.append(d) for i in range 0 4 begin set d = not X at i and Y at i or not X at i or Y at i if d begin append D 1 end else begin appen...
def oneBitHalfSubtractor(X,Y): D=[] B=[] for i in range (0,4): b = not X[i] and Y[i] if b: B.append(1) else: B.append(0) # D.append(d) for i in range(0,4): d = not((X[i] and Y[i]) or (not (X[i] or Y[i]))) if d: D.append(1...
Python
zaydzuhri_stack_edu_python
function test_bookmark_model_string_representation self begin set bookmark = call create keyword bookmark_data set username = username set article_title = title set bm_id = id set rep = format string Bookmark - id:{} username: {}, title: {} bm_id username article_title assert in string rep string bookmark end function
def test_bookmark_model_string_representation(self): bookmark = Bookmark.objects.create(**self.bookmark_data) username = bookmark.profile.user.username article_title = bookmark.article.title bm_id = bookmark.id rep = "Bookmark - id:{} username: {}, title: {}".format( ...
Python
nomic_cornstack_python_v1
function Connect self node1_idx node2_idx arrow=false weight=0 capacity=- 1 flow=0 begin if node1_idx == node2_idx or node1_idx > call NodesCount or node2_idx > call NodesCount begin return false end for n in nodes begin if index == node1_idx begin set a = n end else if index == node2_idx begin set b = n end end if isN...
def Connect(self, node1_idx, node2_idx, arrow=False, weight = 0, capacity = -1, flow = 0): if node1_idx == node2_idx or node1_idx > self.NodesCount() or node2_idx > self.NodesCount(): return False for n in self.nodes: if n.index == node1_idx: a = n el...
Python
nomic_cornstack_python_v1
function getAtomChars t swipl begin set s = call c_char_p if call PL_get_atom_chars t call byref s begin return value end else begin raise call InvalidTypeError string atom end end function
def getAtomChars(t, swipl): s = c_char_p() if swipl.PL_get_atom_chars(t, byref(s)): return s.value else: raise InvalidTypeError("atom")
Python
nomic_cornstack_python_v1
function solve self board begin if not board begin return end set tuple n m = tuple length board length board at 0 set que = deque for i in range n begin if board at i at 0 == string O begin append que tuple i 0 end if board at i at m - 1 == string O begin append que tuple i m - 1 end end for i in range 1 m - 1 begin i...
def solve(self, board: List[List[str]]) -> None: if not board: return n, m = len(board), len(board[0]) que = collections.deque() for i in range(n): if board[i][0] == 'O': que.append((i, 0)) if board[i][m - 1] == 'O': ...
Python
nomic_cornstack_python_v1