code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment the right hand side is a tuple ! set tuple x y z = tuple 1 2 76 print x y z print string Unpacking a tuple set data = tuple 1 2 76 set tuple x y z = data print x y z comment works also with other sequence types set data = list 1 2 76 set tuple x y z = data print x y z for t in enumerate string abcdefgh begin se...
# the right hand side is a tuple ! x, y, z = 1, 2, 76 print(x, y, z) print("Unpacking a tuple") data = 1, 2, 76 x, y, z = data print(x, y, z) # works also with other sequence types data = [1, 2, 76] x, y, z = data print(x, y, z) for t in enumerate(("abcdefgh")): index, character = t print(index, character) ...
Python
zaydzuhri_stack_edu_python
comment pylint: disable=too-many-instance-attributes string Required imports Pygame Height (from Utilities) Width (from Utilities) import random import pygame from Utilities import HEIGHT , WIDTH class Ball extends Sprite begin string Class to keep track of the ball. function __init__ self begin call __init__ set surf ...
# pylint: disable=too-many-instance-attributes """ Required imports Pygame Height (from Utilities) Width (from Utilities) """ import random import pygame from Utilities import HEIGHT, WIDTH class Ball(pygame.sprite.Sprite): """Class to keep track of the ball.""" def __init__(self): super(...
Python
zaydzuhri_stack_edu_python
if password == string Swordfish begin print string Access Granted end else begin print string Wrong Password end
if password == 'Swordfish': print ('Access Granted') else: print ('Wrong Password')
Python
zaydzuhri_stack_edu_python
function set_broker self broker begin set _broker = broker end function
def set_broker(self, broker): self._broker = broker
Python
nomic_cornstack_python_v1
import numpy as N from vectors import * from quad import Quad from transform import * class ParametricSurface begin function __init__ self uSteps=tuple 0.0 1.0 0.1 vSteps=tuple 0.0 1.0 0.1 transform=call identity color=tuple 1 1 1 begin set uSteps = call makeVector uSteps set vSteps = call makeVector vSteps set transfo...
import numpy as N from vectors import * from quad import Quad from transform import * class ParametricSurface(): def __init__(self, uSteps = (0.0, 1.0, 0.1), vSteps = (0.0, 1.0, 0.1), transform = identity(), color = (1,1,1)): self.uSteps =...
Python
zaydzuhri_stack_edu_python
for i in range 2 1000000 begin print format string trying {} i set l = 1 set n = i while i != 1 begin if i % 2 == 0 begin set i = i / 2 end else begin set i = 3 * i + 1 end set l = l + 1 end if l > cl begin set cl = l set cn = n end end print cn
for i in range(2, 1000000): print("trying {}".format(i)) l=1 n=i while i!=1: if i%2==0: i=i/2 else: i=3*i+1 l+=1 if l>cl: cl=l cn=n print(cn)
Python
zaydzuhri_stack_edu_python
string Replicated command: pwd Print the current working directory. import argparse import os function main begin string Parse and handle user's call. set parser = call setup_argument_parser comment There should be no arguments set arguments = call parse_args call print_working_dir end function function setup_argument_...
""" Replicated command: pwd Print the current working directory. """ import argparse import os def main(): """ Parse and handle user's call. """ parser = setup_argument_parser() # There should be no arguments arguments = parser.parse_args() print_working_dir() def setup_argument_parser(): """ Setup argumen...
Python
zaydzuhri_stack_edu_python
from big_ol_pile_of_manim_imports import * class NMFIntro extends Scene begin function construct self begin set textNMFTitle = call TexMobject string \text{Non-negative Matrix Factorization} call to_edge UP call set_color BLUE call scale 1.5 set textMathEqualtoFrist = call TexMobject string {=} call set_color YELLOW ca...
from big_ol_pile_of_manim_imports import * class NMFIntro(Scene): def construct(self): textNMFTitle = TexMobject("""\\text{Non-negative Matrix Factorization}""") textNMFTitle.to_edge(UP) textNMFTitle.set_color(BLUE) textNMFTitle.scale(1.5) textMathEqualtoFrist = TexMobject("""{=}""") textMathEqualtoFrist...
Python
zaydzuhri_stack_edu_python
import requests from bs4 import BeautifulSoup import lxml import json set flag = true function get_user begin while true begin set input_url = input string Enter the url of the account or the username: comment checking if url or username if input_url at slice : 5 : == string https begin set url_link = input_url end e...
import requests from bs4 import BeautifulSoup import lxml import json flag = True def get_user(): while True: input_url = input("Enter the url of the account or the username: ") #checking if url or username if input_url[:5] == "https": url_link = input_url else: ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python from pyspark import SparkContext from pyspark import SparkConf from pyspark import StorageLevel import datetime import pytz function load_part_cassandra part begin string Write data to Cassandra database if part begin from cassandra.cluster import Cluster comment Original cluster comment cluste...
#!/usr/bin/python from pyspark import SparkContext from pyspark import SparkConf from pyspark import StorageLevel import datetime import pytz def load_part_cassandra(part): """ Write data to Cassandra database """ if part: from cassandra.cluster import Cluster # Original cluster # clust...
Python
zaydzuhri_stack_edu_python
comment Un equipo de albañiles de una obra, tiene que planificar la colocación de pisos. comment Dicha tarea se realiza teniendo algunas consideraciones específicas, que tienen que ver con el corte de las baldosas, comment con el material de pegado y la cantidad de trabajadores que hay en cada momento. comment En el ar...
# Un equipo de albañiles de una obra, tiene que planificar la colocación de pisos. # Dicha tarea se realiza teniendo algunas consideraciones específicas, que tienen que ver con el corte de las baldosas, # con el material de pegado y la cantidad de trabajadores que hay en cada momento. # En el arranque, el día uno (1...
Python
zaydzuhri_stack_edu_python
function name self begin return get pulumi self string name end function
def name(self) -> pulumi.Input[str]: return pulumi.get(self, "name")
Python
nomic_cornstack_python_v1
import tkinter as tk set root = call Tk call geometry string 1500x1000 set passwords = list tuple string Staff string lab set failure_max = 3 function Back begin call destroy call quit from Home import Home set next = call Home end function function submit failures=list begin print get User_Name1 get Password1 if tuple...
import tkinter as tk root=tk.Tk() root.geometry("1500x1000") passwords = [('Staff', 'lab')] failure_max=3 def Back(): root.destroy() root.quit() from Home import Home next = Home() def submit(failures=[]): print(User_Name1.get(), Password1.get()) if (User_Name1.get(), Password1.get()...
Python
zaydzuhri_stack_edu_python
from tkinter import * function btncmd begin comment 0 : 체크해제 , 1 : 체크 print get chkvar print get chkvar2 end function comment print("chkvar1 is {0} - chkvar2 is {1}".format(chkvar, chkvar2 )) set root = call Tk title root string Nado GUI comment 가로 세로 크기 정의 call geometry string 640x480 comment chkvar에 int형으로 값을 저장한다 se...
from tkinter import * def btncmd(): print(chkvar.get()) # 0 : 체크해제 , 1 : 체크 print(chkvar2.get()) # print("chkvar1 is {0} - chkvar2 is {1}".format(chkvar, chkvar2 )) root = Tk() root.title("Nado GUI") root.geometry("640x480") #가로 세로 크기 정의 chkvar = IntVar() #chkvar에 int형으로 값을 저장한다 chkbox = Checkbutton(roo...
Python
zaydzuhri_stack_edu_python
comment Enter your code here. Read input from STDIN. Print output to STDOUT set x = input set n = map int split strip call raw_input string set t = tuple n
# Enter your code here. Read input from STDIN. Print output to STDOUT x=input() n = map(int,raw_input().strip().split(' ')) t=tuple(n)
Python
zaydzuhri_stack_edu_python
function test_set_new_model_parameters self begin set set_features_columns_options = call MagicMock return_value=dict call set_new_model_parameters assert equal get training_input call get_training_data_path assert equal get test_input call get_test_data_path assert equal get results_input call get_results_path end fun...
def test_set_new_model_parameters(self): self.app.set_features_columns_options = MagicMock(return_value={}) self.new_model_window.set_new_model_parameters() self.assertEqual(self.new_model_window.training_input.get(), InputSettings.get_training_data_path()) self.assertEqual(self.new_mod...
Python
nomic_cornstack_python_v1
function __init__ self node_path start_time pid is_root_pipeline=false node_ids=none interactively_started=false begin call __init__ list set node_path = node_path set start_time = start_time set pid = pid set interactively_started = interactively_started set is_root_pipeline = is_root_pipeline set node_ids = node_ids ...
def __init__(self, node_path: t.List[str], start_time: datetime.datetime, pid: int, is_root_pipeline: bool = False, node_ids: t.Optional[t.List[str]] = None, interactively_started: bool = False) -> None: super().__init__([]) ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 string Binary tree from scratch from math import inf class BinTree begin function __init__ self begin set root = none set l = none set r = none end function function in_order self begin string Left, current, right if is instance l BinTree begin call in_order end else begin print l end prin...
#!/usr/bin/env python3 """ Binary tree from scratch """ from math import inf class BinTree: def __init__(self): self.root = self.l = self.r = None def in_order(self): """ Left, current, right """ if isinstance(self.l, BinTree): self.l.in_order() else: ...
Python
zaydzuhri_stack_edu_python
import json_lines import re set doc_count = 0 set dictOfDocs = dict set listOfIds = list string 049739753ce2e539d8dc2165daaf6aa6 string 02ae7136-006d-11e3-9711-3708310f6f4d with open string D:\Course Content\Thesis\WashingtonPost.v2.tar\WashingtonPost.v2\data\TREC_Washington_Post_collection.v2.jl string rb as f begin ...
import json_lines import re doc_count=0 dictOfDocs = {} listOfIds = ['049739753ce2e539d8dc2165daaf6aa6','02ae7136-006d-11e3-9711-3708310f6f4d'] with open("D:\\Course Content\\Thesis\\WashingtonPost.v2.tar\\WashingtonPost.v2\\data\\TREC_Washington_Post_collection.v2.jl", 'rb') as f: for item in json_lines.reader(f):...
Python
zaydzuhri_stack_edu_python
import random comment def make_HTML_heading(f): comment txt = f() comment def inner(): comment print(txt) comment return '<h1>' + txt + '</h1>' comment return inner function make_HTML_heading f begin function inner begin return string <h1> + f dist + string </h1> end function return inner end function decorator make_HT...
import random # def make_HTML_heading(f): # txt = f() # def inner(): # print(txt) # return '<h1>' + txt + '</h1>' # return inner def make_HTML_heading(f): def inner(): return '<h1>' + f() + '</h1>' return inner #greet = make_HTML_heading(greet) the @make_HTML_heading does ...
Python
zaydzuhri_stack_edu_python
comment Steven Raaijmakers comment Programma vindt dominante waarde in een array (van integers) of in een array comment bestaande uit RGB kleuren (zie RGB klasse) comment Bronnen: comment http://stackoverflow.com/questions/14743890/find-dominant-mode-of-an-unsorted-array comment http://www.cs.rug.nl/~wim/pub/whh348.pdf...
# Steven Raaijmakers # Programma vindt dominante waarde in een array (van integers) of in een array # bestaande uit RGB kleuren (zie RGB klasse) # Bronnen: # http://stackoverflow.com/questions/14743890/find-dominant-mode-of-an-unsorted-array # http://www.cs.rug.nl/~wim/pub/whh348.pdf # http://stackoverflow.com/questio...
Python
zaydzuhri_stack_edu_python
function sortasciixyz infile outfile seperator begin set comments = string try begin set array = list set count = 0 with open infile string r as i begin for l in i begin set count = count + 1 if length l > 0 begin append array split l seperator end else begin set comment = comment + string empty line %s % count print...
def sortasciixyz(infile, outfile, seperator): comments = "" try: array=[] count = 0 with open(infile,"r") as i: for l in i: count +=1 if len(l) > 0: array.append(l.split(seperator)) else: ...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Mon Mar 1 15:55:58 2021 @author: jagadeesan import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap import seaborn as sns from mpl_toolkits.mplot3d import Axes3D from sklearn.model_selection import * from sklearn...
# -*- coding: utf-8 -*- """ Created on Mon Mar 1 15:55:58 2021 @author: jagadeesan """ import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap import seaborn as sns from mpl_toolkits.mplot3d import Axes3D from sklearn.model_selection import...
Python
zaydzuhri_stack_edu_python
function unsetenv varname begin pass end function
def unsetenv(varname): pass
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import math set a = decimal input string Digite a: set b = decimal input string Digite b: set c = decimal input string Digite c: set d = decimal input string Digite d: if a < b and b < c and c < d begin print string S end else if a < b and b > c and c > d begin print string S end else if a...
# -*- coding: utf-8 -*- import math a=float(input('Digite a: ')) b=float(input('Digite b: ')) c=float(input('Digite c: ')) d=float(input('Digite d: ')) if a<b and b<c and c<d: print('S') elif a<b and b>c and c>d: print('S') elif a<b and b<c and c>d: print('S') elif a>b and b>c and c>d: print('S') elif...
Python
zaydzuhri_stack_edu_python
comment Definition for a binary tree node. comment class TreeNode: comment def __init__(self, x): comment self.val = x comment self.left = None comment self.right = None import math class Solution begin comment The key here is tracking the "bounds" which subtree values must fall under function isValidBST self root base...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None import math class Solution: # The key here is tracking the "bounds" which subtree values must fall under def isValidBST(self, root, base=-math.inf, c...
Python
zaydzuhri_stack_edu_python
function newList a begin set b = list append b a at 0 append b a at length a - 1 return b end function set c = call newList a print c
def newList (a): b = [] b.append(a[0]) b.append(a[len(a)-1]) return b c=newList(a) print(c)
Python
zaydzuhri_stack_edu_python
function get_ols_matrix sep_df apr_df sep_order apr_order begin set regression_df = call DataFrame T index=apr_order columns=sep_order return regression_df end function
def get_ols_matrix(sep_df, apr_df, sep_order, apr_order): regression_df = pd.DataFrame((sep_df.T.values @ apr_df.values @ np.linalg.pinv(apr_df.T.values @ apr_df.values)).T, index=apr_order, columns=sep_order) return regression_df
Python
nomic_cornstack_python_v1
function symbol self begin return token end function
def symbol(self): return self.token
Python
nomic_cornstack_python_v1
comment !/usr/bin/python import numpy as np import matplotlib as mpl from matplotlib import pyplot as plt import os comment Run the executable integrate_bernus.out call system string ./integrate_bernus.out comment Read plain text data set data = call loadtxt string bernus.txt set t = data at tuple slice : : 0 set V0...
#!/usr/bin/python import numpy as np import matplotlib as mpl from matplotlib import pyplot as plt import os # Run the executable integrate_bernus.out os.system("./integrate_bernus.out") # Read plain text data data = np.loadtxt("bernus.txt") t = data[:,0] V0 = data[:,1] m = data[:,2] v = data[:,3] f = d...
Python
zaydzuhri_stack_edu_python
function getBusinessTemplateList self begin return tuple string erp5_base string erp5_pdm string erp5_trade string erp5_simulation string erp5_syncml string erp5_tiosafe_core string erp5_tiosafe_test string erp5_tiosafe_virtuemart string erp5_tiosafe_virtuemart_test end function
def getBusinessTemplateList(self): return ( 'erp5_base', 'erp5_pdm', 'erp5_trade', 'erp5_simulation', 'erp5_syncml', 'erp5_tiosafe_core', 'erp5_tiosafe_test', 'erp5_tiosafe_virtuemart', 'erp5_tiosafe_virtuemart_test', )
Python
nomic_cornstack_python_v1
function _get_orders self begin set episodes = filter series=id if length episodes == 0 begin return 0 end set total_orders = 0 for episode in episodes begin set total_orders = total_orders + orders end return total_orders / length episodes end function
def _get_orders(self): episodes = SeriesEpisode.objects.filter(series=self.id) if len(episodes) == 0: return 0 total_orders = 0 for episode in episodes: total_orders += episode.orders return total_orders / len(episodes)
Python
nomic_cornstack_python_v1
function get_small_joker_value deck_of_cards begin set big_joker_value = call get_big_joker_value deck_of_cards set small_joker_value = min deck_of_cards for card in deck_of_cards begin if card < big_joker_value and card > small_joker_value begin set small_joker_value = card end end comment Goes through each card in th...
def get_small_joker_value(deck_of_cards): big_joker_value = get_big_joker_value(deck_of_cards) small_joker_value = min(deck_of_cards) for card in deck_of_cards: if card < big_joker_value and card > small_joker_value: small_joker_value = card # Goes through each card in the dec...
Python
nomic_cornstack_python_v1
function new_group self begin if servtype in tuple string thread string mpi begin set groupn = groupn + 1 return groupn end if servtype == string dc begin try begin return call EMDCsendonecom addr string NGRP none end except any begin call wait_for_server return call EMDCsendonecom self addr string NCPU none end end en...
def new_group(self): if self.servtype in ("thread","mpi"): self.groupn+=1 return self.groupn if self.servtype=="dc" : try: return EMDCsendonecom(self.addr,"NGRP",None) except: self.wait_for_server() return EMDCsendonecom(self,addr,"NCPU",None)
Python
nomic_cornstack_python_v1
function sort_stack stk begin set temp_stack = call MyStack while call is_empty is false begin set curr_val = pop stk if call top is not none and curr_val >= integer call top begin call push curr_val end else begin while call is_empty is false begin call push pop temp_stack end call push curr_val end end while not call...
def sort_stack(stk: MyStack) -> MyStack: temp_stack = MyStack() while stk.is_empty() is False: curr_val = stk.pop() if temp_stack.top() is not None and curr_val >= int(temp_stack.top()): temp_stack.push(curr_val) else: while temp_stack.is_empty() is False: ...
Python
nomic_cornstack_python_v1
function test_fma_nan_param_ninfarray_infnum_nanarray_okarray_a_460 self begin comment This version is expected to pass. call fma okarrayx oknumy okarrayz arrayout matherrors=true comment This should raise an error. with assert raises ArithmeticError begin call fma ninfarrayx infnumy nanarrayz arrayout end end function
def test_fma_nan_param_ninfarray_infnum_nanarray_okarray_a_460(self): # This version is expected to pass. arrayfunc.fma(self.okarrayx, self.oknumy, self.okarrayz, self.arrayout, matherrors=True) # This should raise an error. with self.assertRaises(ArithmeticError): arrayfunc.fma(self.ninfarrayx, self.infnum...
Python
nomic_cornstack_python_v1
comment Blackjack primer from cardgame import * function blackjack begin print string Welcome to Softopia Casino set deck = call fresh_deck set chips = 0 while true begin print string ----- comment hands out two cards each set dealer = list set player = list set tuple card deck = call hit deck append player card set ...
# Blackjack primer from cardgame import * def blackjack(): print("Welcome to Softopia Casino") deck = fresh_deck() chips = 0 while True: print("-----") ## hands out two cards each dealer = [] player = [] card, deck = hit(deck) player.append(card) ...
Python
zaydzuhri_stack_edu_python
function load_file self begin set info = list with open file_path string r as fin begin for line in fin begin set filename = strip line if data_prefix is not none begin set filename = join osp data_prefix filename end if suffix is not none begin set filename = filename + suffix end append info dictionary filename=file...
def load_file(self): info = [] with open(self.file_path, 'r') as fin: for line in fin: filename = line.strip() if self.data_prefix is not None: filename = osp.join(self.data_prefix, filename) if self.suffix is not None: ...
Python
nomic_cornstack_python_v1
import numpy as np from collections import defaultdict comment from start_state import get_start_state import model from world_master import World import plot_world_v2 class Qlearn extends object begin function __init__ self begin print length call action_space comment state_size = x_size * y_size * v_size * theta_size...
import numpy as np from collections import defaultdict #from start_state import get_start_state import model from world_master import World import plot_world_v2 class Qlearn(object): def __init__(self): print(len(model.action_space())) # state_size = x_size * y_size * v_size * theta_size # ...
Python
zaydzuhri_stack_edu_python
import feedparser import re import json import urllib.request function download_file download_url filename begin set response = url open download_url set file = open filename + string .pdf string wb write file read response close file end function function shortTitle str begin set short = str if match string ^zur short...
import feedparser import re import json import urllib.request def download_file(download_url, filename): response = urllib.request.urlopen(download_url) file = open(filename + ".pdf", 'wb') file.write(response.read()) file.close() def shortTitle(str): short = str if re.match(r"^zur",...
Python
zaydzuhri_stack_edu_python
function buildMove self moveType space pose radius=0 begin if moveType == string l begin set acceleration = 0.3 set speed = 0.3 end else begin comment Joint acceleration in rad/s^2 set acceleration = 1.0 comment Joint speed in rad/s set speed = 1.0 end comment Time the move must take set time = 0 set array = list pose ...
def buildMove(self, moveType, space, pose, radius=0): if moveType == "l": acceleration = 0.3 speed = 0.3 else: acceleration = 1.0 #Joint acceleration in rad/s^2 speed = 1.0 #Joint speed in rad/s time = 0 #Time the move must take array = li...
Python
nomic_cornstack_python_v1
function db_client_application_name postgres_url application_name monkeypatch begin call setenv string TENTACLIO__PG_APPLICATION_NAME application_name with call PostgresClient postgres_url as client begin yield client end end function
def db_client_application_name(postgres_url, application_name, monkeypatch): monkeypatch.setenv("TENTACLIO__PG_APPLICATION_NAME", application_name) with clients.PostgresClient(postgres_url) as client: yield client
Python
nomic_cornstack_python_v1
function dashboard request begin comment Ci pensa datatables a popolare la tabella set title = call _ string Pannello di controllo set sub_title = call _ string Gestisci i tuoi ticket o aprine di nuovi set template = string user/dashboard.html set tickets = filter created_by=user set not_closed = filter is_closed=false...
def dashboard(request): # Ci pensa datatables a popolare la tabella title =_("Pannello di controllo") sub_title = _("Gestisci i tuoi ticket o aprine di nuovi") template = "user/dashboard.html" tickets = Ticket.objects.filter(created_by=request.user) not_closed = tickets.filter(is_closed=False) ...
Python
nomic_cornstack_python_v1
comment Связанный список. comment Состоит из отдельных узлов (данные + связь/ссылка на следующий узел) comment класс Node определяет узел: class Node begin function __init__ self v begin comment данное set value = v comment Next - связь (указатель на следующий узел. Для последнего next будет хранить None set next = non...
# Связанный список. # Состоит из отдельных узлов (данные + связь/ссылка на следующий узел) class Node: # класс Node определяет узел: def __init__(self, v): self.value = v # данное self.next = None # Next - связь (указатель на следующий узел. Для последнего next будет хранить None n1 = Node(1)...
Python
zaydzuhri_stack_edu_python
function addBuildOnlyDependency self mods begin for modname in mods begin comment if one adds a dependency that is found in optional modules comment change it from optional to required to build if modname in optmodules begin call buildWithout list modname end comment if one adds a dependency that is found in external d...
def addBuildOnlyDependency(self, mods): for modname in mods: # if one adds a dependency that is found in optional modules # change it from optional to required to build if( modname in self.optmodules ): self.buildWithout([modname]) # if one adds a...
Python
nomic_cornstack_python_v1
import argparse from collections import defaultdict from tokenizer import tokenize from tokenizer import compute_word_frequencies from tokenizer import print_sorted_order function combine_frequency_map frequency_map1 frequency_map2 begin set map = default dictionary int for tuple k v in items frequency_map1 begin set m...
import argparse from collections import defaultdict from tokenizer import tokenize from tokenizer import compute_word_frequencies from tokenizer import print_sorted_order def combine_frequency_map(frequency_map1, frequency_map2): map = defaultdict(int) for k, v in frequency_map1.items(): map[k] = v ...
Python
zaydzuhri_stack_edu_python
comment -*- coding:utf-8 -*- from PySide2.QtCore import * from PySide2.QtGui import * from PySide2.QtWidgets import * from view import TitleView from view import GameView class PoemMaster extends QWidget begin function __init__ self begin call __init__ call setWindowTitle string 古诗词背诵软件 call setLayout call QVBoxLayout ...
# -*- coding:utf-8 -*- from PySide2.QtCore import * from PySide2.QtGui import * from PySide2.QtWidgets import * from view import TitleView from view import GameView class PoemMaster(QWidget): def __init__(self): super(PoemMaster,self).__init__() self.setWindowTitle(u"古诗词背诵软件") self.setLayo...
Python
zaydzuhri_stack_edu_python
function json self begin return dumps ordered dictionary list tuple string metadata metadata tuple string records values records end function
def json(self): return json.dumps(OrderedDict([('metadata', self.metadata), ('records', self.records.values())]))
Python
nomic_cornstack_python_v1
function get_dimensions response begin return response at string reports at 0 at string columnHeader at string dimensions end function
def get_dimensions(response): return response['reports'][0]['columnHeader']['dimensions']
Python
nomic_cornstack_python_v1
function ida_calc self *args begin return call get_output call eval_expr join string args end function
def ida_calc(self, *args): return get_output(eval_expr("".join(args)))
Python
nomic_cornstack_python_v1
comment ! /usr/bin/env python comment -*- coding: UTF-8 -*- import sys append path string ./common import unittest import log function raise_error *args **kwds begin raise call ValueError string invalid value: %s%s % tuple args kwds end function class SimpleTestCase extends TestCase begin function setUp self begin info...
#! /usr/bin/env python # -*- coding: UTF-8 -*- import sys sys.path.append('./common') import unittest import log def raise_error(*args, **kwds): raise ValueError('invalid value: %s%s' % (args, kwds)) class SimpleTestCase(unittest.TestCase): def setUp(self): log.info("start...") self.fixtu...
Python
zaydzuhri_stack_edu_python
comment installing/importing library to our code import requests from bs4 import BeautifulSoup import pandas import argparse comment importing our connect.py as also a library import connect comment creating an object called parser to access web set parser = call ArgumentParser comment giving a parameter to get no.page...
import requests #installing/importing library to our code from bs4 import BeautifulSoup import pandas import argparse import connect #importing our connect.py as also a library parser = argparse.ArgumentParser() #creating an object called parser to access web parser.add_argument("--page_nu...
Python
zaydzuhri_stack_edu_python
comment A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. comment Return a deep copy of the list. comment MY SOL: Create a hashmap to map original node and copy node in first iteration. In second iteration, put the wires at right place st...
# A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. # Return a deep copy of the list. ##MY SOL: Create a hashmap to map original node and copy node in first iteration. In second iteration, put the wires at right place """ # Definition ...
Python
zaydzuhri_stack_edu_python
function get_updates self **kwargs begin set req_str = BASE_URL + BOT_REQUEST at co_name set data = dictionary if get kwargs string offset none is not none begin set data at string offset = pop kwargs string offset end if get kwargs string limit none is not none begin set data at string limit = pop kwargs string limit ...
def get_updates(self, **kwargs): req_str = SETTING.BASE_URL + SETTING.BOT_REQUEST[inspect.currentframe().f_code.co_name] data = dict() if kwargs.get('offset', None) is not None: data['offset'] = kwargs.pop('offset') if kwargs.get('limit', None) is not None: data['limit'] = kwargs.pop('l...
Python
nomic_cornstack_python_v1
function merge_files_to_list begin set content = list for f in files begin with open f string r as file begin for line in file begin append content right strip line string end end end return content end function
def merge_files_to_list(): content=[] for f in files: with open(f ,"r") as file: for line in file: content.append(line.rstrip("\n")) return content
Python
nomic_cornstack_python_v1
function _u_naught_simple self begin comment Random is better to give different multipliers in the subgradient phase return call rand mrows * 1.0 end function
def _u_naught_simple(self): # Random is better to give different multipliers in the subgradient phase return np.random.rand(self.mrows)*1.
Python
nomic_cornstack_python_v1
function get_random_title file_name begin set total_bytes = st_size set random_point = random integer 0 total_bytes with open file_name as file begin seek file random_point comment skip this line to clear the partial line read line file return replace replace right strip read line file string string _ string string , s...
def get_random_title(file_name): total_bytes = os.stat(file_name).st_size random_point = random.randint(0, total_bytes) with open(file_name) as file: file.seek(random_point) file.readline() # skip this line to clear the partial line return file.readline().rstrip('\n').replace('_', ' ').replace(',', '')
Python
nomic_cornstack_python_v1
comment 2. Для списка реализовать обмен значений соседних элементов, т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 comment и т.д. При нечетном количестве элементов последний сохранить на своем месте. Для заполнения списка элементов необходимо comment использовать функцию input().
#2. Для списка реализовать обмен значений соседних элементов, т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 # и т.д. При нечетном количестве элементов последний сохранить на своем месте. Для заполнения списка элементов необходимо # использовать функцию input().
Python
zaydzuhri_stack_edu_python
function Search self search_text=string search_location=string search_start_time=none search_end_time=none max_results=20 begin comment Dummy implementations returns nothing. return list end function
def Search(self, search_text='', search_location='', search_start_time=None, search_end_time=None, max_results=20): # Dummy implementations returns nothing. return []
Python
nomic_cornstack_python_v1
comment Imports comment import requests comment from app import app comment from flask import render_template comment from flask import request from qpylib import qpylib comment import json class WhoisInformation extends object begin string Object model for information returned through the whois api function __init__ s...
#Imports #import requests #from app import app #from flask import render_template #from flask import request from qpylib import qpylib #import json class WhoisInformation(object): """ Object model for information returned through the whois api """ def __init__(self): self.network = None self.organisation = N...
Python
zaydzuhri_stack_edu_python
from copy import deepcopy class MiniMaxAI begin function __init__ self number begin set number = number end function decorator staticmethod function check_win board begin set conds = tuple board at 0 at 0 == board at 1 at 1 == board at 2 at 2 != 0 board at 2 at 0 == board at 1 at 1 == board at 0 at 2 != 0 if any conds ...
from copy import deepcopy class MiniMaxAI: def __init__(self, number): self.number = number @staticmethod def check_win(board): conds = (board[0][0] == board[1][1] == board[2][2] != 0, board[2][0] == board[1][1] == board[0][2] != 0) if any(conds): retu...
Python
zaydzuhri_stack_edu_python
comment Project name : SPOJ: ARMY - Army Strength comment Author : Wojciech Raszka comment E-mail : gitpistachio@gmail.com comment Date created : 2019-11-18 comment Description : comment Status : Accepted (24893661) comment Tags : python, game theory comment Comment : from sys import stdin , stdout set T = integer read...
# Project name : SPOJ: ARMY - Army Strength # Author : Wojciech Raszka # E-mail : gitpistachio@gmail.com # Date created : 2019-11-18 # Description : # Status : Accepted (24893661) # Tags : python, game theory # Comment : from sys import stdin, stdout T = int(stdin.readline()) while T ...
Python
zaydzuhri_stack_edu_python
comment Modules & Packages comment A module in Python is just a script file that contains some code/classes/whatever else. # A package is a directory comment that contains modules. comment Instead of just having one giant script that contains all the code that you need, using modules & packages allows us comment to sep...
## Modules & Packages # A module in Python is just a script file that contains some code/classes/whatever else. # A package is a directory # that contains modules. # Instead of just having one giant script that contains all the code that you need, using modules & packages allows us # to separate Python code into chunk...
Python
zaydzuhri_stack_edu_python
comment leg5@nyu.edu import os import scipy.io.wavfile as wave import numpy as np function save_synthesised_speech speaker speech_rate save_dest text_file=none utterance=none begin string speaker: OSX built-in speaker name. e.g., Samantha, Alex speech_rate: number of words per minute save_dest: where to save the file. ...
# leg5@nyu.edu import os import scipy.io.wavfile as wave import numpy as np def save_synthesised_speech(speaker, speech_rate, save_dest, text_file=None, utterance=None): """ speaker: OSX built-in speaker name. e.g., Samantha, Alex speech_rate: number of words...
Python
zaydzuhri_stack_edu_python
function set_model_parameters self model_name mode=string train debug=false begin if mode != string train and mode != string test begin raise call TypeError string Invalid string entered. Must be either 'train' or 'test'. return end with open parameters_path string r as f begin set json_file = load json f set classes =...
def set_model_parameters(self, model_name:str, mode="train", debug=False): if mode != "train" and mode != "test": raise TypeError("Invalid string entered. Must be either 'train' or 'test'.") return with open(self.parameters_path, "r") as f: json_file...
Python
nomic_cornstack_python_v1
set mat1 = list list 1 2 3 4 list 5 6 7 8 list 9 10 11 12 set mat2 = list list 1 2 3 4 list 5 6 7 8 list 9 10 11 12 print list comprehension list comprehension mat1 at i at j + mat2 at i at j for j in range 4 for i in range 3
mat1 = [ [1,2,3,4], [5,6,7,8], [9,10,11,12], ] mat2 = [ [1,2,3,4], [5,6,7,8], [9,10,11,12], ] print ([[mat1[i][j]+mat2[i][j] for j in range(4)] for i in range(3)])
Python
zaydzuhri_stack_edu_python
from math import gcd function modify_array nums begin set i = 1 while i < length nums begin if call gcd nums at i - 1 nums at i > 1 begin insert nums i 1 set i = i + 1 end set i = i + 1 end return nums end function
from math import gcd def modify_array(nums): i = 1 while i < len(nums): if gcd(nums[i-1], nums[i]) > 1: nums.insert(i, 1) i += 1 i += 1 return nums
Python
jtatman_500k
function spsolve_gpu A b begin comment NOTE: we can pass csc indices directly because we can! comment Just kidding. This is because the matrix A is symmetric :) comment TODO: Ravel and unravel this! set x = call spsolve_jax data indices indptr b at tuple slice : : 0 set y = call spsolve_jax data indices indptr b at ...
def spsolve_gpu(A, b): # NOTE: we can pass csc indices directly because we can! # Just kidding. This is because the matrix A is symmetric :) # TODO: Ravel and unravel this! x = spsolve_jax(A.data, A.indices, A.indptr, b[:, 0]) y = spsolve_jax(A.data, A.indices, A.indptr, b[:, 1]) z = spsolve_ja...
Python
nomic_cornstack_python_v1
function cluster self det ovr=0.5 maxcl=20 inclusion=false begin set cllist = list for ls in det begin set found = false for cl in cllist begin for cle in cl begin if not inclusion begin set myovr = call overlap ls at string bbox cle at string bbox end else begin set myovr = call inclusion ls at string bbox cle at str...
def cluster(self,det,ovr=0.5,maxcl=20,inclusion=False): cllist=[] for ls in det: found=False for cl in cllist: for cle in cl: if not(inclusion): myovr=util.overlap(ls["bbox"],cle["bbox"]) else: ...
Python
nomic_cornstack_python_v1
string http://adventofcode.com/2017/day/16 import pytest function step_s s size begin return s at slice - size : : + s at slice : - size : end function function step_x s a b begin if a > b begin set tuple a b = tuple b a end return s at slice : a : + s at b + s at slice a + 1 : b : + s at a + s at slice b + 1 : ...
""" http://adventofcode.com/2017/day/16 """ import pytest def step_s(s, size): return s[-size:] + s[:-size] def step_x(s, a, b): if a > b: a, b = b, a return s[:a] + s[b] + s[a+1:b] + s[a] + s[b+1:] def step_p(s, a, b): return step_x(s, s.index(a), s.index(b)) @pytest.mark.parametrize("s, ...
Python
zaydzuhri_stack_edu_python
from email.mime.multipart import MIMEMultipart from email.header import Header comment SMTP即简单邮件传输协议 import smtplib comment 1 邮件信息 set email_from = string wwuhnwu@163.com set sender = email_from set email_to = list string wwuhnwu@163.com string 2283517648@qq.com set receiver = join string , email_to set password = stri...
from email.mime.multipart import MIMEMultipart from email.header import Header import smtplib # SMTP即简单邮件传输协议 # 1 邮件信息 email_from = "wwuhnwu@163.com" sender = email_from email_to = ["wwuhnwu@163.com","2283517648@qq.com"] receiver = ",".join(email_to) password = "63695694Wu" email_subject = "witiso html file ...
Python
zaydzuhri_stack_edu_python
function evaluate_ranking encoded_idf_scores queries documents query_names doc_names gt_file run_to_rerank begin set docs_to_rerank_by_query = call compute_docs_to_rerank_by_query run_to_rerank query_names set rel_docs_by_qry = dict set sim_scores_by_qry = dict for i in call tqdm range length queries begin print stri...
def evaluate_ranking(encoded_idf_scores, queries, documents, query_names, doc_names, gt_file, run_to_rerank): docs_to_rerank_by_query = compute_docs_to_rerank_by_query(run_to_rerank, query_names) rel_docs_by_qry = {} sim_scores_by_qry = {} for i in tqdm(range(len(queries))): print('query: %d/%d'...
Python
nomic_cornstack_python_v1
function get_base_url begin set base = call get_default_version_hostname if string appspot.com in base begin return string https://%s % base end return string http://%s % base end function
def get_base_url(): base = get_default_version_hostname() if "appspot.com" in base: return "https://%s" % base return "http://%s" % base
Python
nomic_cornstack_python_v1
function eia_json_to_dataframe eia_json state=none series_name=none begin set data = eia_json at string series at 0 at string data comment setting state and series name if not state begin set state = eia_json at string series at 0 at string geography end if not series_name begin set series_name = eia_json at string ser...
def eia_json_to_dataframe(eia_json, state=None, series_name=None): data = eia_json['series'][0]['data'] # setting state and series name if not state: state = eia_json['series'][0]['geography'] if not series_name: series_name = eia_json['series'][0]['name'] # then convert to datafra...
Python
nomic_cornstack_python_v1
string File: dimensions.py Original Author: C. D. Lima comment In Python a 'tuple' is an immutable object. The difference between a list and comment tuple is the brackets. For a tuple one uses parentheses instead of sqaure brackets. set dimensions = tuple 200 50 print dimensions at 0 print dimensions at 1 comment Now l...
""" File: dimensions.py Original Author: C. D. Lima """ # In Python a 'tuple' is an immutable object. The difference between a list and # tuple is the brackets. For a tuple one uses parentheses instead of sqaure brackets. dimensions = (200, 50) print(dimensions[0]) print(dimensions[1]) # Now let's try changing the v...
Python
zaydzuhri_stack_edu_python
import numpy as np import scipy.special as sp import matplotlib.pyplot as plt import scipy.optimize as opt import scipy.interpolate as interpolate import scipy.integrate as integ import time function params lam gam eta k sw sst s1 begin string need to make sure R!=0 set R = gam * eta - lam set pi = lam / eta * s1 - sst...
import numpy as np import scipy.special as sp import matplotlib.pyplot as plt import scipy.optimize as opt import scipy.interpolate as interpolate import scipy.integrate as integ import time def params(lam, gam, eta, k, sw, sst, s1): '''need to make sure R!=0''' R = gam*eta-lam pi = lam/eta*(s1-sst) th...
Python
zaydzuhri_stack_edu_python
function quantile_radius pan quant begin set indices = sorted keys pan key=int set number = integer quant * length indices end function
def quantile_radius(pan, quant): indices = sorted(pan.keys(), key=int) number = int(quant*len(indices))
Python
nomic_cornstack_python_v1
function applyFlatCal self calSolnPath verbose=false begin set baseh5path = split calSolnPath string .h5 set flatList = glob glob baseh5path at 0 + string *.h5 assert exists path flatList at 0 msg format string {0} does not exist flatList at 0 assert not info at string isSpecCalibrated msg string the data is already Fl...
def applyFlatCal(self, calSolnPath,verbose=False): baseh5path=calSolnPath.split('.h5') flatList=glob.glob(baseh5path[0]+'*.h5') assert os.path.exists(flatList[0]), "{0} does not exist".format(flatList[0]) assert not self.info['isSpecCalibrated'], \ "the data is alre...
Python
nomic_cornstack_python_v1
function get_current_basis self begin set l = length basis_stack return basis_stack at l - 1 end function
def get_current_basis(self): l = len(self.basis_stack) return self.basis_stack[l-1]
Python
nomic_cornstack_python_v1
function plotData filepath outFiles out_extension plotname flag header begin set fig = figure set ax = call add_subplot 111 set L = length outFiles comment Divide the colorbar into "L" number of divisions, where "L" is the number of outFiles set color_idx = linear space 0 1 L comment Open text file to dump out last-val...
def plotData(filepath, outFiles, out_extension, plotname, flag, header): fig = plt.figure() ax = fig.add_subplot(111) L = len(outFiles) color_idx = np.linspace(0, 1, L) # Divide the colorbar into "L" number of divisions, where "L" is the number of outFiles # Open text file to dump out last...
Python
nomic_cornstack_python_v1
function read_image image_path begin return array call load_img image_path color_mode=string grayscale / 255 end function
def read_image(image_path): return np.array(load_img(image_path, color_mode='grayscale')) / 255
Python
nomic_cornstack_python_v1
function test_find_node_mock_with_empty_list self begin comment Assign set root = call Node string Root node set tree = call Tree root_node=root comment Act set returned_node = call find_node list comment Assert assert equal root returned_node end function
def test_find_node_mock_with_empty_list(self): # Assign root = Node("Root node") tree = Tree(root_node=root) # Act returned_node = tree.find_node([]) # Assert self.assertEqual(root, returned_node)
Python
nomic_cornstack_python_v1
comment template of code for Problem 4 of Problem Set 2, Fall 2008 comment variable that keeps track of largest number set bestSoFar = 0 comment of McNuggets that cannot be bought in exact quantity comment variable that contains package sizes set packages = tuple 6 9 20 comment only search for solutions up to size 150 ...
### ### template of code for Problem 4 of Problem Set 2, Fall 2008 ### bestSoFar = 0 # variable that keeps track of largest number # of McNuggets that cannot be bought in exact quantity packages = (6,9,20) # variable that contains package sizes # only search for solutions up to size 150 ...
Python
zaydzuhri_stack_edu_python
if input_string begin set count = dict for l in input_string begin if l in count begin set count at l = count at l + 1 end else begin set count at l = 1 end end set values = list values count sort values for tuple k v in items count begin if v == values at - 1 begin print k end end end else begin print string INVALID ...
if input_string: count = {} for l in input_string: if l in count: count[l] += 1 else: count[l] = 1 values = list(count.values()) values.sort() for k, v in count.items(): if v == values[-1]: print(k) else: print("INVALID INPUT")
Python
zaydzuhri_stack_edu_python
string Pure Python wrapper to the Yajl C library .. data:: __version__ Version of yajl-py .. data:: yajl_version Version of the yajl library that was loaded from yajl_common import * from yajl_parse import * from yajl_gen import * from yajl_simple import * set __version__ = string 1.0.12 set yajl_version = call get_yaj...
''' Pure Python wrapper to the Yajl C library .. data:: __version__ Version of yajl-py .. data:: yajl_version Version of the yajl library that was loaded ''' from yajl_common import * from yajl_parse import * from yajl_gen import * from yajl_simple import * __version__ = '1.0.12' yajl_version = get_yajl_v...
Python
zaydzuhri_stack_edu_python
string Provide one and only one object of a particular type. string Use case: Implement a CacheClient which provides an interface to fetch cached data. class Cache begin set __instance = none decorator staticmethod function get_instance begin if __instance is none begin cache end return __instance end function function...
""" Provide one and only one object of a particular type. """ """ Use case: Implement a CacheClient which provides an interface to fetch cached data. """ class Cache: __instance = None @staticmethod def get_instance(): if Cache.__instance is None: Cache() return Cache.__inst...
Python
zaydzuhri_stack_edu_python
if n == 2 begin print 3 print 2 1 2 end else begin set shoots = list comprehension i for i in range 2 n + 1 2 + list comprehension i for i in range 1 n + 1 2 + list comprehension i for i in range 2 n + 1 2 print length shoots print join string map str shoots end
if n == 2: print(3) print(2, 1, 2) else: shoots = [i for i in range(2, n + 1, 2)] + [i for i in range(1, n + 1, 2)] + [i for i in range(2, n + 1, 2)] print(len(shoots)) print(" ".join(map(str, shoots)))
Python
jtatman_500k
function isLetter c begin set ret = call xmlIsLetter c return ret end function
def isLetter(c): ret = libxml2mod.xmlIsLetter(c) return ret
Python
nomic_cornstack_python_v1
class User begin string User class holds information about users To create user you have to state Name and email address. Users have methods: get_email change_email read_book get_average_rating function __init__ self name email begin set name = name set email = email set books = dict end function function get_email se...
class User: '''User class holds information about users To create user you have to state Name and email address. Users have methods: get_email change_email read_book get_average_rating''' def __init__(self, name, email): self.name = name self.email = email self....
Python
zaydzuhri_stack_edu_python
import re comment This function gives you a priority of the string function separate string begin comment for example sulaiman = {"s" :"1", "u": "1" , "l":"1" , "a"" :"2" , "i" : "1","m" : 1, "n" : "1"} set string1 = string set count = 0 set str3 = dict for i in string begin set count = 0 for j in string1 begin if i =...
import re def separate(string) : # This function gives you a priority of the string string1 = string # for example sulaiman = {"s" :"1", "u": "1" , "l":"1" , "a"" :"2" , "i" : "1","m" : 1, "n" : "1"} count = 0 str3 ={} for i in string : count = 0 for j in string1 : if(i==j) : ...
Python
zaydzuhri_stack_edu_python
function extract_response_options template column begin set options = call translate none string []', set options = split options return options end function
def extract_response_options(template, column): options = template.loc['response_options', column].translate(None, "[]',") options = options.split() return options
Python
nomic_cornstack_python_v1
function read self begin set string = call recv set values = split string string at 1 set float_values = list for item in split values string , begin append float_values decimal item end return float_values end function
def read(self): string = self.socket.recv() values = string.split(" ")[1] float_values = [] for item in values.split(","): float_values.append(float(item)) return float_values
Python
nomic_cornstack_python_v1
function test_get_posts_missing_ids client begin set response = call simulate_get string /page/get_records assert status_code == 400 end function
def test_get_posts_missing_ids(client): response = client.simulate_get('/page/get_records') assert response.status_code == 400
Python
nomic_cornstack_python_v1
function property_names self begin set property_names : Set at str = set for engraver in engravers begin update property_names property_names end return tuple sorted property_names end function
def property_names(self) -> typing.Tuple[str, ...]: property_names: typing.Set[str] = set() for engraver in self.engravers: property_names.update(engraver.property_names) return tuple(sorted(property_names))
Python
nomic_cornstack_python_v1
string Crie um program onde o usuário digite a expressão qualquer que user parênteses. Seu app deverá analisar se a expressão passada está com os parênteses abertos e fechados na ordem correta. set expr = input string Digite a expressão: set pilha = list for símb in expr begin if símb == string ( begin append pilha st...
"""Crie um program onde o usuário digite a expressão qualquer que user parênteses. Seu app deverá analisar se a expressão passada está com os parênteses abertos e fechados na ordem correta.""" expr = input('Digite a expressão: ') pilha = [] for símb in expr: if símb == '(': pilha.append('(') elif sím...
Python
zaydzuhri_stack_edu_python
comment 10.4 存储数据 10.4.1 使用json.dump() 和json.load() import json set numbers = list 2 3 5 7 11 13 set filename = string pi_digits with open filename string w as f_obj begin dump numbers f_obj end with open filename as r_obj begin print load json r_obj end
# 10.4 存储数据 10.4.1 使用json.dump() 和json.load() import json numbers = [2, 3, 5, 7, 11, 13] filename = 'pi_digits' with open(filename,'w') as f_obj: json.dump(numbers,f_obj) with open(filename) as r_obj: print(json.load(r_obj))
Python
zaydzuhri_stack_edu_python
comment cannot find CLR method function __init__ self *args begin pass end function
def __init__(self, *args): #cannot find CLR method pass
Python
nomic_cornstack_python_v1
function from_server cls server_dict begin comment type: "EventingFunctionSettings" comment type: Dict[str, Any] if not server_dict begin raise call InvalidArgumentException string No server content provided. end set value = get server_dict string dcp_stream_boundary none if value is not none and split value begin set ...
def from_server( cls, # type: "EventingFunctionSettings" server_dict, # type: Dict[str, Any] ) -> "EventingFunctionSettings": if not server_dict: raise InvalidArgumentException("No server content provided.") value = server_dict.get("dcp_stream_boundary", None) ...
Python
nomic_cornstack_python_v1
function pipe self func *args **kwargs begin if is instance func tuple begin set tuple func target = func if target in kwargs begin raise call ValueError string %s is both the pipe target and a keyword argument % target end set kwargs at target = self return call func *args keyword kwargs end else begin return call fun...
def pipe(self, func: Callable[..., Any], *args: Any, **kwargs: Any) -> Any: if isinstance(func, tuple): func, target = func if target in kwargs: raise ValueError("%s is both the pipe target and a keyword " "argument" % target) kwargs[target] = self ...
Python
nomic_cornstack_python_v1
function longestSubstringWithoutRepeatingCharacters string begin set longest = string set current = string for c in string begin if c not in current begin set current = current + c end else begin if length current > length longest begin set longest = current end set current = c end end if length current > length long...
def longestSubstringWithoutRepeatingCharacters(string): longest = "" current = "" for c in string: if c not in current: current += c else: if len(current) > len(longest): longest = current current = c if len(current) > len(longest): ...
Python
flytech_python_25k