code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
string @author: Yawar Azad function knn data query k begin set neighbor_distances_and_indices = list for tuple index example in enumerate data begin set distance = call euclidean_distance example at slice : - 1 : query append neighbor_distances_and_indices tuple distance index end set sorted_neighbor_distances_and_i...
''' @author: Yawar Azad ''' def knn(data, query, k): neighbor_distances_and_indices = [] for index, example in enumerate(data): distance = euclidean_distance(example[:-1], query) neighbor_distances_and_indices.append((distance, index)) sorted_neighbor_distances_and_indices = sorted(n...
Python
zaydzuhri_stack_edu_python
comment Two arrays merged in ascending order comment ex- arr=[1 ,2 ,4,6, 8 ] comment arr1 = [3,5,6,7] function place arr m begin set n = length arr for i in range n begin if m <= arr at i begin append arr 0 for j in range n i - 1 begin set arr at j = arr at j - 1 end set arr at i = m break end else if arr at i <= m and...
#Two arrays merged in ascending order #ex- arr=[1 ,2 ,4,6, 8 ] # arr1 = [3,5,6,7] def place(arr,m): n = len(arr) for i in range(n): if m <= arr[i]: arr.append(0) for j in range(n,i,-1): arr[j] = arr[j-1] arr[i] = m break elif arr[i...
Python
zaydzuhri_stack_edu_python
function adjust_transition_probabilities self probabilities min_prob penalty_multiplier=1.0 begin set variable_region = 1 - min_prob set scale_ratio = 1 / variable_region set adjusted_probabilities = dict for k in probabilities begin set adjusted_probabilities at k = probabilities at k * penalty_multiplier / scale_rat...
def adjust_transition_probabilities(self, probabilities, min_prob, penalty_multiplier=1.0): variable_region = 1 - min_prob scale_ratio = 1 / variable_region adjusted_probabilities = {} for k in probabilities: adjusted_probabilities[k] = ((probabilities[k]*penalty_multiplier) ...
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.model_selection import KFold function question_10_b_c set_d set_t sigma begin string :param set_d: :param set_t: :return: set set_s = set_d at tuple slice : 500 : 0 set labels_s = set_d at tuple slice ...
import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.model_selection import KFold def question_10_b_c(set_d, set_t, sigma): """ :param set_d: :param set_t: :return: """ set_s = set_d[:500, 0] labels_s = set_d[:500, 1] se...
Python
zaydzuhri_stack_edu_python
from rest_framework import serializers from django.contrib.auth.models import User comment from .models import * from django.db.models import Q class UserProfileSerializer extends ModelSerializer begin class Meta begin set model = User set fields = tuple string pk string password string last_login string is_superuser s...
from rest_framework import serializers from django.contrib.auth.models import (User) # from .models import * from django.db.models import Q class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('pk', 'password', 'last_login', 'is_superuser', 'username', ...
Python
zaydzuhri_stack_edu_python
function PostMessage self codereview_url message begin raise call NotImplemented end function
def PostMessage(self, codereview_url, message): raise NotImplemented()
Python
nomic_cornstack_python_v1
import numpy as np import pandas as pd from sklearn import svm set nsample = 4000 set X_train = array read csv string X_train.csv header=none set y_train = array ix at tuple slice : : 0 set X_test = array read csv string X_test.csv header=none comment use the first 4000 samples for training set XTrain = X_train at t...
import numpy as np import pandas as pd from sklearn import svm nsample = 4000 X_train = np.array(pd.read_csv("X_train.csv",header=None)) y_train = np.array(pd.read_csv("y_train.csv",header=None).ix[:,0]) X_test = np.array(pd.read_csv("X_test.csv",header=None)) XTrain = X_train[:nsample,:] #use the first 4000 samples...
Python
zaydzuhri_stack_edu_python
function number_of_days_past_start_date config begin set start_date_parts = split config at string start_date string - set start_date = call date integer start_date_parts at 2 integer start_date_parts at 1 integer start_date_parts at 0 comment Get the day - starting from one set todays_date = today set days_past_start_...
def number_of_days_past_start_date(config): start_date_parts = config['start_date'].split('-') start_date = date(int(start_date_parts[2]), int(start_date_parts[1]), int(start_date_parts[0])) # Get the day - starting from one todays_date = date.today() days_past_start_date = (todays_date - start_dat...
Python
nomic_cornstack_python_v1
function remote_url self begin return get config string remote-server end function
def remote_url(self): return self.config.get('remote-server')
Python
nomic_cornstack_python_v1
function getInputSpecification cls begin set specs = call getInputSpecification set description = string The \xmlNode{NuSVR} \textit{Nu-Support Vector Regression} is an Nu-Support Vector Regressor. It is very similar to SVC but with the addition of the hyper-parameter Nu for controlling the number of support vectors. H...
def getInputSpecification(cls): specs = super(NuSVR, cls).getInputSpecification() specs.description = r"""The \xmlNode{NuSVR} \textit{Nu-Support Vector Regression} is an Nu-Support Vector Regressor. It is very similar to SVC but with the addition of the hyper-parameter Nu for control...
Python
nomic_cornstack_python_v1
import requests from bs4 import BeautifulSoup import os set url = string https://en.wikipedia.org/wiki/Deep_learning set source_code = get requests url set plain_text = text set soup = call BeautifulSoup plain_text string html.parser comment result_list=soup.findALL("a") for div in find all string a begin print get div...
import requests from bs4 import BeautifulSoup import os url="https://en.wikipedia.org/wiki/Deep_learning" source_code=requests.get(url) plain_text=source_code.text soup=BeautifulSoup(plain_text,"html.parser") #result_list=soup.findALL("a") for div in soup.findAll('a'): print(div.get("href"))
Python
zaydzuhri_stack_edu_python
string This Example sends harcoded data to Ubidots using the request HTTP library. Please install the library using pip install requests Made by Jose García @https://github.com/jotathebest/ import requests import random import time string global variables set ENDPOINT = string things.ubidots.com set DEVICE_LABEL = stri...
''' This Example sends harcoded data to Ubidots using the request HTTP library. Please install the library using pip install requests Made by Jose García @https://github.com/jotathebest/ ''' import requests import random import time ''' global variables ''' ENDPOINT = "things.ubidots.com" DEVICE_LABEL = "flaskServ...
Python
zaydzuhri_stack_edu_python
comment ************************************************************************ comment Apple Store Data Set Preparation comment ************************************************************************ comment Some of the exercises use the app store data set, which is available from Kaggla at comment https://www.kaggl...
# ************************************************************************ # Apple Store Data Set Preparation # ************************************************************************ # Some of the exercises use the app store data set, which is available from Kaggla at # https://www.kaggle.com/ramamet4/app-store-appl...
Python
zaydzuhri_stack_edu_python
function get_badges ids start_date=none end_date=none begin set path = string badges/%s % call __join ids set params = call __translate copy locals _tag_badge_orders return call fetch path string badges keyword params end function
def get_badges(ids, start_date=None, end_date=None): path = "badges/%s" % __join(ids) params = __translate(locals().copy(), _tag_badge_orders) return _site.fetch(path, "badges", **params)
Python
nomic_cornstack_python_v1
function download_fasta protein_list folder begin set sequence_folder = format string {}/protein_sequences folder for protein in protein_list begin if ends with protein string .DS_Store begin continue end set url = string http://www.uniprot.org/uniprot/ + protein + string .fasta set wait = uniform 0.1 1.0 set result = ...
def download_fasta(protein_list, folder): sequence_folder = "{}/protein_sequences".format(folder) for protein in protein_list: if protein.endswith('.DS_Store'): continue url = 'http://www.uniprot.org/uniprot/' + protein + '.fasta' wait = random.uniform(0.1, 1.0) resul...
Python
nomic_cornstack_python_v1
comment 先練習小數除法、整數除法、餘數的語法 comment 小數除法 set x = 7 / 5 print string 這是 7 除以 5 的r: x comment 整數除法 set x = 7 // 5 print string 這是 7 除以 5 的整除部分: x comment 餘數 set x = 7 % 5 print string 這是 7 除以 5 的餘數: x
# 先練習小數除法、整數除法、餘數的語法 # 小數除法 x=7/5 print("這是 7 除以 5 的r: ", x) # 整數除法 x=7//5 print("這是 7 除以 5 的整除部分: ", x) # 餘數 x=7%5 print("這是 7 除以 5 的餘數: ", x)
Python
zaydzuhri_stack_edu_python
function get_coordinates self params begin set element = params at string element set coordination = params at string coordination set OH_frac = params at string OH set OH2_frac = params at string OH2 set Nmax = params at string Nmax set dMOH = params at string dMOH set dMOH2 = params at string dMOH2 set angle = params...
def get_coordinates(self,params): element = params['element'] coordination = params['coordination'] OH_frac = params['OH'] OH2_frac = params['OH2'] Nmax = params['Nmax'] dMOH = params['dMOH'] dMOH2 = params['dMOH2'] angle = params['<MOH'] if(coord...
Python
nomic_cornstack_python_v1
comment Escreva um programa que leia um valor em metros e exiba o valor convertido em centimetros e milimetros set valor_metros = integer input string Digite um valor em metros: print format string valor em centrimetros : {} valor em milimetros: {} valor_metros * 100 valor_metros * 1000
#Escreva um programa que leia um valor em metros e exiba o valor convertido em centimetros e milimetros valor_metros = int(input('Digite um valor em metros: ')) print('valor em centrimetros : {} valor em milimetros: {}'.format(valor_metros*100,valor_metros*1000))
Python
zaydzuhri_stack_edu_python
string Contains all the attacks on discretized inputs. The attacks implemented are Discrete Gradient Ascent (DGA) and Logit Space-Projected Gradient Ascent (LS-PGA). from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf im...
"""Contains all the attacks on discretized inputs. The attacks implemented are Discrete Gradient Ascent (DGA) and Logit Space-Projected Gradient Ascent (LS-PGA). """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf...
Python
zaydzuhri_stack_edu_python
function initWorker begin print string Initializing new poolWorker process: %s. % call current_process comment Ignore signal interrupts in the poolWorker process call signal SIGINT SIG_IGN end function
def initWorker(): print("Initializing new poolWorker process: %s." % multiprocessing.current_process()) # Ignore signal interrupts in the poolWorker process signal.signal(signal.SIGINT, signal.SIG_IGN)
Python
nomic_cornstack_python_v1
import sys import os set target_dir = argv at 1 set file_list = list directory target_dir for file in file_list begin set f = open target_dir + file string r comment print("file: %s" %file) set dump = read f if string 0000 in dump begin print file end close f end
import sys import os target_dir=sys.argv[1] file_list=os.listdir(target_dir) for file in file_list: f=open(target_dir+file, 'r') #print("file: %s" %file) dump=f.read() if "0000" in dump: print(file) f.close()
Python
zaydzuhri_stack_edu_python
function get_contributors self begin raise NotImplementedError end function
def get_contributors(self): raise NotImplementedError
Python
nomic_cornstack_python_v1
function ferret_init id begin set axes_values = list AXIS_DOES_NOT_EXIST * MAX_FERRET_NDIM set axes_values at 0 = AXIS_CUSTOM set false_influences = list false * MAX_FERRET_NDIM set retdict = dict string numargs 1 ; string descript string Returns the (unweighted) mean, variance, skew, and excess kurtosis of an array of...
def ferret_init(id): axes_values = [ pyferret.AXIS_DOES_NOT_EXIST ] * pyferret.MAX_FERRET_NDIM axes_values[0] = pyferret.AXIS_CUSTOM false_influences = [ False ] * pyferret.MAX_FERRET_NDIM retdict = { "numargs": 1, "descript": "Returns the (unweighted) mean, variance, skew, and excess ku...
Python
nomic_cornstack_python_v1
function construct_seq ind_i begin set track_i = track_list at ind_i set select_indices_i = call sample_rois set seq_roi_list = list comprehension roi_list at i for i in select_indices_i return seq_roi_list end function
def construct_seq(ind_i): track_i = track_list[ind_i] select_indices_i = track_i.sample_rois() seq_roi_list = [track_i.roi_list[i] for i in select_indices_i] return seq_roi_list
Python
nomic_cornstack_python_v1
import re print string dir(re): directory re set matched_var = compile string \d\d-\d\d\d-\d\d\d set str_var = string 11-111-111 is my number set holder = search str_var print string Searched Pattern: call group set emails = string law@email.com is the orig and not the lawrence@yopmail.com also not this one 24.353 set ...
import re print("dir(re): ", dir(re)) matched_var = re.compile(r'\d\d-\d\d\d-\d\d\d') str_var = "11-111-111 is my number" holder = matched_var.search(str_var) print("Searched Pattern: ", holder.group()) emails = "law@email.com is the orig and not the lawrence@yopmail.com also not this one 24.353" emails_holder = re....
Python
zaydzuhri_stack_edu_python
function test_create_order_status_code self begin assert equal status_code HTTP_201_CREATED end function
def test_create_order_status_code(self): self.assertEqual(self.response.status_code, status.HTTP_201_CREATED)
Python
nomic_cornstack_python_v1
from sklearn import svm , metrics from sklearn.model_selection import train_test_split import pandas as pd set csv = read csv string iris.csv set csv_data = csv at list string SepalLength string SepalWidth string PetalLength string PetalWidth set csv_label = csv at string Name set total_len = length csv set train_len =...
from sklearn import svm, metrics from sklearn.model_selection import train_test_split import pandas as pd csv = pd.read_csv('iris.csv') csv_data = csv[["SepalLength","SepalWidth","PetalLength","PetalWidth"]] csv_label = csv["Name"] total_len = len(csv) train_len = int(total_len *2 / 3) train_data, test_data, train_l...
Python
zaydzuhri_stack_edu_python
function setUp self begin set staff = call create_user email=string staff@curesio.com password=string staffpassword1234 username=string staffusername set is_staff = true save call refresh_from_db set client = call APIClient call force_authenticate user=staff set speciality = call create name=string Speciality set paylo...
def setUp(self): self.staff = get_user_model().objects.create_user( email='staff@curesio.com', password='staffpassword1234', username='staffusername' ) self.staff.is_staff = True self.staff.save() self.staff.refresh_from_db() self.clie...
Python
nomic_cornstack_python_v1
function task_completed self completion_time begin set completed_tasks_count = completed_tasks_count + 1 set end_time = max completion_time end_time assert completed_tasks_count <= num_tasks return num_tasks == completed_tasks_count end function
def task_completed(self, completion_time): self.completed_tasks_count += 1 self.end_time = max(completion_time, self.end_time) assert self.completed_tasks_count <= self.num_tasks return self.num_tasks == self.completed_tasks_count
Python
nomic_cornstack_python_v1
function n_remaining_samples self begin return - 1 end function
def n_remaining_samples(self): return -1
Python
nomic_cornstack_python_v1
function can_remove_spec self cluster_spec begin set msg = call attempt_remove_spec cluster_spec return length msg == 0 end function
def can_remove_spec(self, cluster_spec): msg = self.attempt_remove_spec(cluster_spec) return len(msg) == 0
Python
nomic_cornstack_python_v1
function primary_key_tuple self item begin if hash_key is none begin raise call ValueError string Missing hash key end if range_key is none begin return tuple item at name end else begin return tuple item at name item at name end end function
def primary_key_tuple(self, item: Dict) -> Union[Tuple[str], Tuple[str, str]]: if self.hash_key is None: raise ValueError("Missing hash key") if self.range_key is None: return (item[self.hash_key.name],) else: return (item[self.hash_key.name], item[self.range_...
Python
nomic_cornstack_python_v1
import os , operator , sys import pandas as pd set dirpath = absolute path path argv at 0 set dirpath = join string / split dirpath string / at slice : - 1 : + string /csv files comment make a generator for all file paths within dirpath set all_files = generator expression join path basedir filename for tuple basedir ...
import os, operator, sys import pandas as pd dirpath = os.path.abspath(sys.argv[0]) dirpath = "/".join(dirpath.split("/")[:-1]) + "/csv files" # make a generator for all file paths within dirpath all_files = (os.path.join(basedir, filename) for basedir, dirs, files in os.walk(dirpath) for filename in files) # sort f...
Python
zaydzuhri_stack_edu_python
function create_subparser self parent storage begin call create_subparser parent storage import argparse comment Create 'cot deploy ... esxi' parser set p = call add_parser string esxi parents=list generic_parser usage=call fill_usage string deploy PACKAGE esxi list string LOCATOR [-u USERNAME] [-p PASSWORD] [-c CONFIG...
def create_subparser(self, parent, storage): super(COTDeployESXi, self).create_subparser(parent, storage) import argparse # Create 'cot deploy ... esxi' parser p = self.subparsers.add_parser( 'esxi', parents=[self.generic_parser], usage=self.UI.fill_usage("deploy...
Python
nomic_cornstack_python_v1
import urllib2 , socket call setdefaulttimeout 180 set fproxy = string proxylist.txt with open fproxy as f begin set proxyList = read lines f end set proxyList = list comprehension strip x for x in proxyList set fsite = string urllist.txt with open fsite as f begin set siteList = read lines f end set siteList = list co...
import urllib2, socket socket.setdefaulttimeout(180) fproxy = "proxylist.txt" with open(fproxy) as f: proxyList = f.readlines() proxyList = [x.strip() for x in proxyList] fsite = "urllist.txt" with open(fsite) as f: siteList = f.readlines() siteList = [x.strip() for x in siteList]
Python
zaydzuhri_stack_edu_python
import json import tensorflow as tf import torch from math import log class Tokenizer begin function __init__ self begin set eos_token = string <|endoftext|> set eos_token_id = 0 set name = string オリバー comment Taken from https://stackoverflow.com/questions/8870261/how-to-split-text-without-spaces-into-list-of-words set...
import json import tensorflow as tf import torch from math import log class Tokenizer: def __init__(self) -> None: self.eos_token = "<|endoftext|>" self.eos_token_id = 0 self.name = "オリバー" # Taken from https://stackoverflow.com/questions/8870261/how-to-split-text-without-spaces-int...
Python
zaydzuhri_stack_edu_python
string You are given a number N, you have to print the number of integers less than N in the sample space S. The first line contains an integer N, denoting the number. Print the count 9 2 36 5 1000000 999 5 1 24 3 From sample: Numbers are 4 = 1^2 * 2^2, 9 = 1^2 * 3^2, 16 = 1^2 * 4^2, 25 = 1^2 * 5^2, 36 = 1^2 * 6^2 coun...
""" You are given a number N, you have to print the number of integers less than N in the sample space S. The first line contains an integer N, denoting the number. Print the count 9 2 36 5 1000000 999 5 1 24 3 From sample: Numbers are 4 = 1^2 * 2^2, 9 = 1^2 * 3^2, 16 = 1^2 ...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- comment @Time : 2020/7/5 21:48 class Solution begin function lengthOfLongestSubstring self s begin comment 哈希集合,记录每个字符是否出现过 set occ = set set n = length s comment 右指针,初始值为 -1,相当于我们在字符串的左边界的左侧,还没有开始移动 set tuple rk ans = tuple - 1 0 for i in range n begin if i != 0 begin comment 左指针向右移动一格,移除...
# -*- coding: utf-8 -*- # @Time : 2020/7/5 21:48 class Solution: def lengthOfLongestSubstring(self, s: str) -> int: # 哈希集合,记录每个字符是否出现过 occ = set() n = len(s) # 右指针,初始值为 -1,相当于我们在字符串的左边界的左侧,还没有开始移动 rk, ans = -1, 0 for i in range(n): if i != 0: ...
Python
zaydzuhri_stack_edu_python
from Tkinter import * import sys
from Tkinter import * import sys
Python
zaydzuhri_stack_edu_python
function match_loop npc_boss begin string This is a description of the functions executed in a loop of each match looks like: shop(): Player decides whether to purchase the cards (items) in the shop prepare(): Player chooses the chamber to insert the bullet and spin the gun use_buff(): Player decides whether to use buf...
def match_loop(npc_boss): """ This is a description of the functions executed in a loop of each match looks like: shop(): Player decides whether to purchase the cards (items) in the shop prepare(): Player chooses the chamber to insert the bullet and spin the gun use_...
Python
nomic_cornstack_python_v1
function test_save_dict test_app redis_service begin set test_dict = dict 1 string test ; 2 string test1 ; 3 string test2 assert not call save_dict test_dict end function function test_validate_for_keys test_app redis_service begin set test_keys = set literal string 1 string 2 string 3 set result = call validate_for_ke...
def test_save_dict(test_app, redis_service): test_dict = { 1: 'test', 2: 'test1', 3: 'test2' } assert not redis_service.save_dict(test_dict) def test_validate_for_keys(test_app, redis_service): test_keys = {'1', '2', '3'} result = redis_service.validate_for_keys(test_keys...
Python
zaydzuhri_stack_edu_python
function compute_sum array begin set sum = 0 for element in array begin set sum = sum + element end return sum end function if __name__ == string __main__ begin set array = list 1 2 3 4 5 print call compute_sum array end
def compute_sum(array): sum = 0 for element in array: sum += element return sum if __name__ == '__main__': array = [1, 2, 3, 4, 5] print(compute_sum(array))
Python
iamtarun_python_18k_alpaca
function final_output self outputs keys_length begin comment [B, T, H] set tuple batch_size hist_len _ = shape set mask = repeat batch_size 1 == view keys_length - 1 1 - 1 return outputs at mask end function
def final_output(self, outputs, keys_length): batch_size, hist_len, _ = outputs.shape # [B, T, H] mask = torch.arange(hist_len, device=keys_length.device).repeat( batch_size, 1 ) == (keys_length.view(-1, 1) - 1) return outputs[mask]
Python
nomic_cornstack_python_v1
comment -*- coding:utf-8 -*- import tensorflow as tf import numpy as np from utils.feature.normalization import Normalization as norm comment 模型数据 comment 1.模型 class Linear begin function __init__ self dic_config begin set logger = get dic_config string logger none set model_path = dic_config at string model_path set m...
# -*- coding:utf-8 -*- import tensorflow as tf import numpy as np from utils.feature.normalization import Normalization as norm # 模型数据 # 1.模型 class Linear: def __init__(self, dic_config): self.logger = dic_config.get('logger', None) self.model_path = dic_config['model_path'] self.mean_std_...
Python
zaydzuhri_stack_edu_python
while f begin set ele = call raw_input string Enter the text: write fd ele write fd string set opt = call raw_input string Do you want to continue: yes or no if lower opt in list string yes string y begin set f = true end else begin set f = false end end close fd
while f: ele=raw_input("Enter the text:") fd.write(ele) fd.write('\n') opt=raw_input("Do you want to continue: yes or no") if opt.lower() in ['yes','y']: f=True else: f=False fd.close()
Python
zaydzuhri_stack_edu_python
function get_results_json self begin set res = dictionary set res at string test_name = test_name set res at string test_duration = test_time set res at string total_auths = total_auths set res at string nanoseconds_since_auth = list set res at string nanoseconds_since_registration = list for name in call get_names beg...
def get_results_json(self) -> str: res = dict() res["test_name"] = self.test_name res["test_duration"] = self.test_time res["total_auths"] = self.total_auths res["nanoseconds_since_auth"] = list() res["nanoseconds_since_registration"] = list() for name in self.get...
Python
nomic_cornstack_python_v1
import numpy as np from Bio.Seq import Seq function hamming_distance s t begin set counter = 0 set first_seq = call Seq s set second_seq = call Seq t for i in range length first_seq begin if first_seq at i != second_seq at i begin set counter = counter + 1 end else begin continue end end return counter end function fun...
import numpy as np from Bio.Seq import Seq def hamming_distance(s,t): counter=0 first_seq = Seq(s) second_seq = Seq(t) for i in range(len(first_seq)): if first_seq[i]!= second_seq[i]: counter+=1 else: continue return counter def LastSymbol(Pattern): ...
Python
zaydzuhri_stack_edu_python
for i in range n begin append d at arr at i % k arr at i end set count = 0 if length d at 0 > 0 begin set count = 1 end set S = set list comprehension tuple x k - x for x in range 1 k // 2 + 1 for tuple i j in S begin if i != j begin if length d at i > length d at j begin set count = count + length d at i end else begi...
for i in range(n): d[arr[i]%k].append(arr[i]) count = 0 if len(d[0]) > 0: count = 1 S = set([(x,k-x) for x in range(1,k//2+1)]) for i,j in S: if i != j: if len(d[i]) > len(d[j]): count += len(d[i]) else: count += len(d[j]) else: if len(d[i]) > 0: ...
Python
zaydzuhri_stack_edu_python
function fastHealing self begin for q in _parsedSpecialQualities begin if type == string fastHealing begin return amount end end end function
def fastHealing(self): for q in self._parsedSpecialQualities: if q.type == 'fastHealing': return q.amount
Python
nomic_cornstack_python_v1
import urllib.request from bs4 import BeautifulSoup from JobDiary.scraper import dictionary class MilkroundScraper begin function __init__ self url begin set page = url open url set soup = call BeautifulSoup page string html.parser end function function get_credentials self begin return list call get_title call get_com...
import urllib.request from bs4 import BeautifulSoup from JobDiary.scraper import dictionary class MilkroundScraper: def __init__(self, url): page = urllib.request.urlopen(url) self.soup = BeautifulSoup(page, 'html.parser') def get_credentials(self): return [self.get_title(), ...
Python
zaydzuhri_stack_edu_python
function delete key begin set path = string %s/%s % tuple DROPBOX_PROJECT_PATH key while string // in path begin set path = replace path string // string / end try begin set res = call files_delete_v2 path end except ApiError as err begin raise call BadRequest DELETE_FAILED end set data = metadata return data end funct...
def delete(key): path = '%s/%s' % (DROPBOX_PROJECT_PATH, key) while '//' in path: path = path.replace('//', '/') try: res = dbx.files_delete_v2(path) except dropbox.exceptions.ApiError as err: raise BadRequest(Code.DELETE_FAILED) data = res.metadata return data
Python
nomic_cornstack_python_v1
import tensorflow as tf function extract_data file_path begin comment string input producer to read file a line set filename_queue = call string_input_producer list file_path comment skip the header skip_header_lines=1 set reader = call TextLineReader skip_header_lines=1 set tuple key value = read reader filename_queue...
import tensorflow as tf def extract_data(file_path): #string input producer to read file a line filename_queue = tf.train.string_input_producer([file_path]) #skip the header skip_header_lines=1 reader = tf.TextLineReader(skip_header_lines=1) key, value = reader.read(filename_queue) rec...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 class Solution begin function __init__ self begin set posX = 0 set posY = 0 end function function validateInput self moves begin if type moves != str begin raise call TypeError string Moves shoud be string. end end function function judgeCircle self moves begin call validateInput moves for...
#!/usr/bin/env python3 class Solution: def __init__(self): self.posX = 0 self.posY = 0 def validateInput(self, moves): if type(moves) != str: raise TypeError("Moves shoud be string.") def judgeCircle(self, moves: str) -> bool: self.validateInput(moves) ...
Python
zaydzuhri_stack_edu_python
function remove_repetidos lista_numeros begin set listaSemNumeroRepetido = list for n in lista_numeros begin if not n in listaSemNumeroRepetido begin append listaSemNumeroRepetido n end end return sorted listaSemNumeroRepetido end function print call remove_repetidos list 2 4 2 2 3 3 1
def remove_repetidos(lista_numeros): listaSemNumeroRepetido = [] for n in lista_numeros: if not n in listaSemNumeroRepetido: listaSemNumeroRepetido.append(n) return sorted(listaSemNumeroRepetido) print(remove_repetidos([2,4,2,2,3,3,1]))
Python
zaydzuhri_stack_edu_python
string Created on Jun 2, 2014 @author: Sean from math import sqrt from sys import argv import random function add_vectors a b begin string Add vectors a and b return list comprehension a at i + b at i for i in range length a end function function multiply_scalar_vector alpha vec begin string Multiply vector vec with sc...
''' Created on Jun 2, 2014 @author: Sean ''' from math import sqrt from sys import argv import random def add_vectors(a, b): '''Add vectors a and b ''' return [a[i]+b[i] for i in range(len(a))] def multiply_scalar_vector(alpha, vec): '''Multiply vector vec with scalar alpha ''' return [alpha*f for f...
Python
zaydzuhri_stack_edu_python
comment noqa: E501 # noqa: E501 function __init__ self assign_names_using=none prestage_device_names=none device_name_prefix=none device_name_suffix=none single_device_name=none manage_names=none device_naming_configured=none local_vars_configuration=none begin if local_vars_configuration is none begin set local_vars_c...
def __init__(self, assign_names_using=None, prestage_device_names=None, device_name_prefix=None, device_name_suffix=None, single_device_name=None, manage_names=None, device_naming_configured=None, local_vars_configuration=None): # noqa: E501 # noqa: E501 if local_vars_configuration is None: local_...
Python
nomic_cornstack_python_v1
function semver begin return join string . list comprehension string v for v in VERSION end function
def semver(): return ".".join([str(v) for v in VERSION])
Python
nomic_cornstack_python_v1
function guestCount self begin return length guests end function
def guestCount(self): return len( self.guests )
Python
nomic_cornstack_python_v1
function get_retcode self begin if retcode is none begin set retcode = poll process end return retcode end function
def get_retcode(self): if self.retcode is None: self.retcode = self.process.poll() return self.retcode
Python
nomic_cornstack_python_v1
function _to_lems_unit unit begin if type unit == str begin set strunit = unit end else begin set strunit = call in_best_unit comment here we substract '1. ' set strunit = strunit at slice 3 : : end comment in LEMS there is no ^ set strunit = replace strunit string ^ string return strunit end function
def _to_lems_unit(unit): if type(unit) == str: strunit = unit else: strunit = unit.in_best_unit() strunit = strunit[3:] # here we substract '1. ' strunit = strunit.replace('^', '') # in LEMS there is no ^ return strunit
Python
nomic_cornstack_python_v1
string Implements armasubsets in R, using naive feature subset search (exhaustive, beam forward or beam backward) rather than R's regsubsets. import numpy as np import pandas as pd from itertools import chain , combinations import heapq from statsmodels.tsa.ar_model import AutoReg from statsmodels.regression.linear_mod...
""" Implements armasubsets in R, using naive feature subset search (exhaustive, beam forward or beam backward) rather than R's regsubsets. """ import numpy as np import pandas as pd from itertools import chain, combinations import heapq from statsmodels.tsa.ar_model import AutoReg from statsmodels.regression.linear_...
Python
zaydzuhri_stack_edu_python
function reverse_string my_str begin set rev_str = string for i in my_str begin set rev_str = i + rev_str end return rev_str end function set my_str = string Hello World call reverse_string my_str
def reverse_string(my_str): rev_str = "" for i in my_str: rev_str = i + rev_str return rev_str my_str = 'Hello World' reverse_string(my_str)
Python
jtatman_500k
function filter_by_freq tsv_name begin comment open the tsv to be filtered set tsv = open tsv_name string r comment create names for the new tsvs by adding _u1 and _u5 to the end of the original tsv name set filtered_5_tsv_name = string u5.tsv comment tsv_name.split('.')[0] + '_u5.tsv' set filtered_1_tsv_name = string ...
def filter_by_freq(tsv_name): #open the tsv to be filtered tsv = open(tsv_name, 'r') #create names for the new tsvs by adding _u1 and _u5 to the end of the original tsv name filtered_5_tsv_name = 'u5.tsv' #tsv_name.split('.')[0] + '_u5.tsv' filtered_1_tsv_name = 'u1.tsv' #tsv_name.spl...
Python
nomic_cornstack_python_v1
function amount_paid self begin return call Decimal sum list comprehension amount for x in all end function
def amount_paid(self) -> Decimal: return Decimal(sum([x.amount for x in self.payments.all()]))
Python
nomic_cornstack_python_v1
import math function samesign a b begin return a * b > 0 end function function bisect func low high begin assert not call samesign call func low call func high for i in range 50 begin set midpoint = low + high / 2.0 if call samesign call func low call func midpoint begin set low = midpoint end else begin set high = mid...
import math def samesign(a,b): return a*b >0 def bisect(func,low,high): assert not samesign(func(low),func(high)) for i in range(50): midpoint=(low + high)/2.0 if samesign(func(low),func(midpoint)): low=midpoint else: high=midpoint return midpoint def f(x): return 2*math.sin(0.9*x)-math.tan(x) x=bi...
Python
zaydzuhri_stack_edu_python
function _save_data self begin call export end function
def _save_data(self): self.widgets.exporter.export()
Python
nomic_cornstack_python_v1
function docstring_section obj section lines indent begin set docs = list for line in lines begin set replaced = false for tuple pattern replacer in PATTERNS begin set match = match pattern strip line if match begin set key = call groups at 0 set context = lower __name__ if section begin set context = context + lower ...
def docstring_section(obj: Any, section: str, lines: List[str], indent: str): docs = [] for line in lines: replaced = False for pattern, replacer in PATTERNS: match = re.match(pattern, line.strip()) if match: key = match.groups()[0] context...
Python
nomic_cornstack_python_v1
import copy import logging from collections import Counter from pathlib import Path from typing import List , Optional , Union import numpy as np from tqdm import tqdm from utils import loadpkl , savepkl set LOGGER = call getLogger __name__ set __all__ = list string Vocab string prepare_unkprob class Vocab begin string...
import copy import logging from collections import Counter from pathlib import Path from typing import List, Optional, Union import numpy as np from tqdm import tqdm from utils import loadpkl, savepkl LOGGER = logging.getLogger(__name__) __all__ = [ 'Vocab', 'prepare_unkprob', ] class Vocab: """Simple...
Python
zaydzuhri_stack_edu_python
function post_build self packet payload begin string Compute the 'sources_number' field when needed if sources_number is none begin set srcnum = call pack string !H length sources set packet = packet at slice : 26 : + srcnum + packet at slice 28 : : end return call post_build self packet payload end function
def post_build(self, packet, payload): """Compute the 'sources_number' field when needed""" if self.sources_number is None: srcnum = struct.pack("!H", len(self.sources)) packet = packet[:26] + srcnum + packet[28:] return _ICMPv6.post_build(self, packet, payload)
Python
jtatman_500k
function transition_message transition begin set last = last set fr = from_slot set to = to_slot return string { last } : { fr } -> { to } end function
def transition_message(transition): last = transition.player.last fr = transition.from_slot to = transition.to_slot return f"{last}: {fr}->{to}"
Python
nomic_cornstack_python_v1
string Load some test data in the database, update, and test for expected results. import json import sys , os import redis , time import logging from lazyupdredis import * comment Note: don't call flushall on actualredis. This functionality isn't available comment to the user and will blow away the version information...
""" Load some test data in the database, update, and test for expected results. """ import json import sys, os import redis, time import logging from lazyupdredis import * # Note: don't call flushall on actualredis. This functionality isn't available # to the user and will blow away the version information def reset...
Python
zaydzuhri_stack_edu_python
function stitch_pores network pores1 pores2 mode=string gabriel begin from openpnm.network import Delaunay , Gabriel set pores1 = call _parse_indices pores1 set pores2 = call _parse_indices pores2 set C1 = coords at tuple pores1 slice : : set C2 = coords at tuple pores2 slice : : set crds = vertical stack tuple C...
def stitch_pores(network, pores1, pores2, mode='gabriel'): from openpnm.network import Delaunay, Gabriel pores1 = network._parse_indices(pores1) pores2 = network._parse_indices(pores2) C1 = network.coords[pores1, :] C2 = network.coords[pores2, :] crds = np.vstack((C1, C2)) if mode == 'delaun...
Python
nomic_cornstack_python_v1
function handleEvent self event begin if source_field not in event begin yield event return end if not is instance event at source_field basestring begin warning string Data in event[%s] not of type string. Skipping. % source_field yield event return end set string_to_match = event at source_field set matches_dict = fa...
def handleEvent(self, event): if self.source_field not in event: yield event return if not isinstance(event[self.source_field], basestring): self.logger.warning("Data in event[%s] not of type string. Skipping." % self.source_field) yield event ...
Python
nomic_cornstack_python_v1
function attachments self begin return call AttachmentCollectionRequestBuilder call append_to_request_url string attachments _client end function
def attachments(self): return attachment_collection.AttachmentCollectionRequestBuilder(self.append_to_request_url("attachments"), self._client)
Python
nomic_cornstack_python_v1
function call self inputs state begin with call variable_scope string gates begin set input_to_gates = dense inputs 2 * _num_units name=string input_proj kernel_initializer=call glorot_normal_initializer use_bias=use_input_bias comment Nematus does the orthogonal initialization probably differently set state_to_gates =...
def call(self, inputs, state): with tf.variable_scope("gates"): input_to_gates = tf.layers.dense( inputs, 2 * self._num_units, name="input_proj", kernel_initializer=tf.glorot_normal_initializer(), use_bias=self.use_input_bias) # Nematus do...
Python
nomic_cornstack_python_v1
import datetime import boto3 from botocore.exceptions import ClientError set sns = call client string sns function lambda_handler event context begin set CurrentDate = now set Leave = string 30/01/2020 15:00 set Leave = string parse time Leave string %d/%m/%Y %H:%M set countdown = Leave - CurrentDate call publish Topic...
import datetime import boto3 from botocore.exceptions import ClientError sns = boto3.client('sns') def lambda_handler(event, context): CurrentDate = datetime.datetime.now() Leave = "30/01/2020 15:00" Leave = datetime.datetime.strptime(Leave, "%d/%m/%Y %H:%M") countdown = Leave - CurrentDate sns.p...
Python
zaydzuhri_stack_edu_python
function from_dataframe cls order begin return list comprehension item name width depth height weight for tuple _ i in call iterrows end function
def from_dataframe(cls, order): return [Item(i.name, i.width, i.depth, i.height, i.weight) for _, i in order.iterrows()]
Python
nomic_cornstack_python_v1
import hashlib import struct import binascii import random set ver = 541065216 set prev_block = string 00000000000000000006a4a234288a44e715275f1775b77b2fddb6c02eb6b72f set mrkl_root = string 2dc60c563da5368e0668b81bc4d8dd369639a1134f68e425a9a74e428801e5b8 set time_ = 1572383582 set bits = 387223263 set exp = bits ? 24 ...
import hashlib import struct import binascii import random ver = 0x20400000 prev_block = "00000000000000000006a4a234288a44e715275f1775b77b2fddb6c02eb6b72f" mrkl_root = "2dc60c563da5368e0668b81bc4d8dd369639a1134f68e425a9a74e428801e5b8" time_ = 0x5DB8AB5E bits = 0x17148EDF exp = bits >> 24 mant = bits & 0xffffff target...
Python
zaydzuhri_stack_edu_python
function test_trid self begin set fun = call get_problem string trid dimension=2 call assertAlmostEqual call fun array list 2.0 2.0 - 2.0 end function
def test_trid(self): fun = get_problem('trid', dimension=2) self.assertAlmostEqual(fun(np.array([2.0, 2.0])), -2.0)
Python
nomic_cornstack_python_v1
function sequentialSearch the_list item begin set position = 0 set found = false while position < length the_list and not found begin if the_list at position == item begin found == true end else begin set position = position + 1 end end return found end function print call sequentialSearch eksamplelist 9
def sequentialSearch(the_list, item): position = 0 found = False while position < len(the_list) and not found: if the_list[position] == item: found == True else: position += 1 return found print(sequentialSearch(eksamplelist, 9))
Python
zaydzuhri_stack_edu_python
function getResultQueueSize self REQUEST=none begin set size = length _results return size end function
def getResultQueueSize(self, REQUEST=None): size = len(self._results) return size
Python
nomic_cornstack_python_v1
function __init__ self data_type src_path tgt_path fields src_seq_length=0 tgt_seq_length=0 src_seq_length_trunc=0 tgt_seq_length_trunc=0 use_filter_pred=true dynamic_dict=true src_dir=none sample_rate=0 window_size=0 window_stride=0 window=none normalize_audio=true **kwargs begin set data_type = data_type if data_type...
def __init__(self, data_type, src_path, tgt_path, fields, src_seq_length=0, tgt_seq_length=0, src_seq_length_trunc=0, tgt_seq_length_trunc=0, use_filter_pred=True, dynamic_dict=True, src_dir=None, sample_rate=0, window_size=0, window_s...
Python
nomic_cornstack_python_v1
function create_op_set_id_version_map table begin set result : VersionMapType = dict function process release_version ir_version *args begin comment Unused del release_version for pair in zip list string ai.onnx string ai.onnx.ml string ai.onnx.training args begin if pair not in result begin set result at pair = ir_ve...
def create_op_set_id_version_map(table: VersionTableType) -> VersionMapType: result: VersionMapType = {} def process(release_version: str, ir_version: int, *args: Any) -> None: del release_version # Unused for pair in zip(["ai.onnx", "ai.onnx.ml", "ai.onnx.training"], args): if pai...
Python
nomic_cornstack_python_v1
import requests import os import re import bs4 import traceback from bs4 import BeautifulSoup function getHtmlText1 url begin try begin set hd = dict string user-agent string Chrome/10 set r = call request string GET url headers=hd call raise_for_status set encoding = string utf-8 comment print(r.text) comment print(r....
import requests import os import re import bs4 import traceback from bs4 import BeautifulSoup def getHtmlText1(url): try: hd = {'user-agent':'Chrome/10'} r = requests.request('GET',url,headers=hd) r.raise_for_status() r.encoding = 'utf-8' # print(r.text) # p...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string This provides password hashing and validate functions which can be This uses passlib.hash sha512_crypt to implement strong passord hashing rather then some home brew approach. from passlib.hash import sha512_crypt function hash_password plaintext_password begin string Securely hash ...
# -*- coding: utf-8 -*- """ This provides password hashing and validate functions which can be This uses passlib.hash sha512_crypt to implement strong passord hashing rather then some home brew approach. """ from passlib.hash import sha512_crypt def hash_password(plaintext_password): """Securely hash the plain ...
Python
zaydzuhri_stack_edu_python
comment %% try begin from tkinter import * end except any begin from Tkinter import * end import sys from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import tkinter.filedialog as tkFileDialog from time import sleep import datetime from datetime import date , timedelta...
#%% try: from tkinter import * except: from Tkinter import * import sys from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import tkinter.filedialog as tkFileDialog from time import sleep import datetime from datetime import date, timedelta ...
Python
zaydzuhri_stack_edu_python
function visit_subscript self node parent begin set newnode = call Subscript call _lineno_parent node newnode parent set tuple subcontext asscontext = tuple asscontext none set value = call visit value newnode set slice = call visit slice newnode set asscontext = subcontext call set_line_info call last_child return new...
def visit_subscript(self, node, parent): newnode = new.Subscript() _lineno_parent(node, newnode, parent) subcontext, self.asscontext = self.asscontext, None newnode.value = self.visit(node.value, newnode) newnode.slice = self.visit(node.slice, newnode) self.assconte...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 import codecs set s = input string Message do Decode here: print decode codecs s string rot-13
#!/usr/bin/python3 import codecs s = input("Message do Decode here:") print(codecs.decode(s, "rot-13"))
Python
zaydzuhri_stack_edu_python
import random string take the least value in every iteration and swap it with ith index . Second loop start 1+i makes sense check it O(N2) function selction_sort arr begin set l = length arr for i in range l - 1 begin set imin = i for j in range i + 1 l begin if arr at j < arr at imin begin set imin = j end end set tup...
import random ''' take the least value in every iteration and swap it with ith index . Second loop start 1+i makes sense check it O(N2)''' def selction_sort(arr): l= len(arr) for i in range(l-1): imin = i for j in range(i+1,l): if arr[j] < arr[imin]: imin=j ...
Python
zaydzuhri_stack_edu_python
function __display_login_info self begin print string Your card has been created Your card number: { card_number } Your card PIN: { __account_pin } end function comment f'{self.__card_display()}\n' # uncomment this line and comment out line below for pretty display
def __display_login_info(self): print(f'\nYour card has been created\n' f'Your card number:\n' # f'{self.__card_display()}\n' # uncomment this line and comment out line below for pretty display f'{self.card_number}\n' f'Your card PIN:\n' f'...
Python
nomic_cornstack_python_v1
function sgd_choice self steps=1000 begin comment local variables to track algorithm ----------------- set misses = 0 set tries = 0 function choice_heuristic search family_id cur_day n_day stp begin comment for the basic heuristic, I will move the family if delta_choice + .1 * delta_accounting > 0 comment parameter 1, ...
def sgd_choice(self, steps=1000): # local variables to track algorithm ----------------- misses = 0 tries = 0 def choice_heuristic(search, family_id, cur_day, n_day, stp): # for the basic heuristic, I will move the family if delta_choice + .1 * delta_accounting > 0 ...
Python
nomic_cornstack_python_v1
function lockComponents self uids hashcheck uid=none ranges=tuple updates=false deletion=false sendEvent=false meta_type=none keys=none start=0 limit=50 sort=string name dir=string ASC name=none begin set data = copy locals del data at string self set resp = call make_request url_path string DeviceRouter string lockCo...
def lockComponents(self, uids, hashcheck, uid=None, ranges=(), updates=False, deletion=False, sendEvent=False, meta_type=None, keys=None, start=0, limit=50, sort='name', dir='ASC', name=None): data = locals().copy() del data["self"] resp = client.make_request(self.url_path, "DeviceRouter", "lock...
Python
nomic_cornstack_python_v1
function get_class x mus Sigmas begin set C = length mus return argument maximum list comprehension call pdf x mean=mus at c cov=Sigmas at c for c in range C end function
def get_class(x, mus, Sigmas) -> int: C = len(mus) return np.argmax([stats.multivariate_normal.pdf(x, mean=mus[c], cov=Sigmas[c]) for c in range(C)])
Python
nomic_cornstack_python_v1
import games import heuristicas set tuple player dif = tuple string 0 while player not in list string X string O begin set player = call raw_input string Who moves first? (X,O): end set difficulty = dict string Easy 2 ; string Normal 3 ; string Hard 5 while dif not in difficulty begin set dif = call raw_input string C...
import games import heuristicas player, dif = '', 0 while player not in ['X', 'O']: player = raw_input("Who moves first? (X,O): ") difficulty = {"Easy": 2, "Normal": 3, "Hard": 5} while dif not in difficulty: dif = raw_input("Choose difficulty (Easy, Normal, Hard): ") # game = games.TicTacToe(h=3, v=3, k=3)...
Python
zaydzuhri_stack_edu_python
function __rtruediv__ self value begin return call RasterCoverage___rtruediv__ self value end function
def __rtruediv__(self, value): return _ilwisobjects.RasterCoverage___rtruediv__(self, value)
Python
nomic_cornstack_python_v1
function __bool__ self begin return call __getValueWithType bool end function
def __bool__(self): return self.__getValueWithType(bool)
Python
nomic_cornstack_python_v1
function next_batch self batch_size shuffle=true begin set start = _index_in_epoch comment Shuffle for first epoch if _epochs_completed == 0 and start == 0 and shuffle begin set permute = array range _num_examples shuffle random permute set _X = _X at permute set _y = _y at permute end comment Go to next batch if start...
def next_batch(self, batch_size, shuffle=True): start = self._index_in_epoch # Shuffle for first epoch if self._epochs_completed == 0 and start == 0 and shuffle: permute = np.arange(self._num_examples) np.random.shuffle(permute) self._X = self._X[permute] ...
Python
nomic_cornstack_python_v1
string Poly: many Morphism: forms polymorphism: one thing with different forms Objects have different forms. uses: 1. Loose Coupling 2. Dependency Injection 3. Interface four ways of defining polymoorphism: 1. Duck typing 2. Operator Overloading 3. Method overloading 4. Method overriding comment Duck Typing: string If ...
""" Poly: many Morphism: forms polymorphism: one thing with different forms Objects have different forms. uses: 1. Loose Coupling 2. Dependency Injection 3. Interface four ways of defining polymoorphism: 1. Duck typing 2. Operator Overloading 3. Method overloading 4. Method overriding """ # Duck Typi...
Python
zaydzuhri_stack_edu_python
import gevent.monkey call patch_all import gevent import requests import pymongo import json import io import time from contextlib import suppress import get_listings_by_location as l import get_reviews_by_listing as r set SAMPLES = list string Hollywood, LA string Venice, LA string Oakland, SF string Manhattan, NYC st...
import gevent.monkey gevent.monkey.patch_all() import gevent import requests import pymongo import json import io import time from contextlib import suppress import get_listings_by_location as l import get_reviews_by_listing as r SAMPLES = ['Hollywood, LA', 'Venice, LA', 'Oakland, SF', 'Manhattan, NYC', 'Brooklyn, NYC...
Python
zaydzuhri_stack_edu_python
function test_contributors_limit self begin call create_batch 110 set top_contributors = call with_translation_counts call assert_equal count top_contributors 100 end function
def test_contributors_limit(self): TranslationFactory.create_batch(110) top_contributors = User.translators.with_translation_counts() assert_equal(top_contributors.count(), 100)
Python
nomic_cornstack_python_v1