code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function match self url begin comment check if pattern is already compiled if _pattern_compiled begin return match url end if not _contains_asterisk begin if not _contains_dollar begin comment answer directly for patterns without wildcards return starts with url _pattern end comment pattern only contains $ wildcard. re...
def match(self, url): # check if pattern is already compiled if self._pattern_compiled: return self._pattern.match(url) if not self._contains_asterisk: if not self._contains_dollar: # answer directly for patterns without wildcards return u...
Python
nomic_cornstack_python_v1
from selenium import webdriver from pages.cart_page import CartPage from pages.main_page import MainPage from pages.product_page import ProductPage from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC class Application begin function __init__ self be...
from selenium import webdriver from pages.cart_page import CartPage from pages.main_page import MainPage from pages.product_page import ProductPage from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC class Application: def __init__(self): ...
Python
zaydzuhri_stack_edu_python
import sys , math from collections import defaultdict function required graph n k begin set target = 1 set tuple curr flow = tuple n k while curr != 1 begin set tuple parent part power = graph at curr if power == 1 begin set flow = square root flow end set flow = flow / part set curr = parent end return flow end functi...
import sys, math from collections import defaultdict def required(graph, n, k): target = 1 curr, flow = n,k while curr != 1: parent,part,power = graph[curr] if power == 1: flow = math.sqrt(flow) flow = flow/part curr = parent return flow def main(): l = lambda : sys.stdin.readline().st...
Python
zaydzuhri_stack_edu_python
function db_instance_endpoint_description self begin return get pulumi self string db_instance_endpoint_description end function
def db_instance_endpoint_description(self) -> pulumi.Output[str]: return pulumi.get(self, "db_instance_endpoint_description")
Python
nomic_cornstack_python_v1
function test_batch_delete_users_mark_for_deletion_when_last_login_is_present self begin comment Given: call batch_setup comment When: set criteria = dict string account_creation_date call datetime 1999 1 1 0 0 call update_test_data user_0 criteria call update_test_data user_2 criteria call update_test_data user_2 dict...
def test_batch_delete_users_mark_for_deletion_when_last_login_is_present(self): # Given: self.batch_setup() # When: criteria = {"account_creation_date": datetime(1999, 1, 1, 0, 0)} self.update_test_data(self.user_0, criteria) self.update_test_data(self.user_2, criteria) ...
Python
nomic_cornstack_python_v1
string Copyright - 2015-2017 Gaurav Gupta (Now at Univ. of Heidelberg) Department of Mechanical Enginering (ME769A) Indian Institute of Technology, Kanpur (India) import random , pygame , math , numpy , pyevolve from pyevolve import G1DBinaryString from pyevolve import GSimpleGA from pyevolve import Selectors from pyev...
""" Copyright - 2015-2017 Gaurav Gupta (Now at Univ. of Heidelberg) Department of Mechanical Enginering (ME769A) Indian Institute of Technology, Kanpur (India) """ import random, pygame, math, numpy, pyevolve from pyevolve import G1DBinaryString from pyevolve import GSimpleGA from pyevolve import Selectors from pyevo...
Python
zaydzuhri_stack_edu_python
function test_upload_new_vdisk self mock_create_file begin comment traits are already set to use the REST API upload comment First need to load in the various test responses. set vg_orig = call load_file UPLOAD_VOL_GRP_ORIG adpt set vg_post_crt = call load_file UPLOAD_VOL_GRP_NEW_VDISK adpt set return_value = vg_orig s...
def test_upload_new_vdisk(self, mock_create_file): # traits are already set to use the REST API upload # First need to load in the various test responses. vg_orig = tju.load_file(UPLOAD_VOL_GRP_ORIG, self.adpt) vg_post_crt = tju.load_file(UPLOAD_VOL_GRP_NEW_VDISK, self.adpt) s...
Python
nomic_cornstack_python_v1
function read_user user_id q=none db=call Depends get_db begin comment get user by the id set user = call get_user_by_id db user_id return user end function
def read_user(user_id: str, q: str = None, db: Session = Depends(get_db)): #get user by the id user = crud.get_user_by_id(db, user_id) return user
Python
nomic_cornstack_python_v1
function read_input fname=string day11.in begin with open fname as f begin return list comprehension integer strip v for v in split next f string , end end function
def read_input(fname="day11.in"): with open(fname) as f: return [int(v.strip()) for v in next(f).split(",")]
Python
nomic_cornstack_python_v1
comment -*- coding: utf8 -*- import logging import jieba.analyse from snownlp import SnowNLP call basicConfig level=NOTSET function FromSnowNlp text summary_num begin set s = call SnowNLP text return call summary summary_num end function function FromJieba text keywords_type keywords_num begin if keywords_type == strin...
# -*- coding: utf8 -*- import logging import jieba.analyse from snownlp import SnowNLP logging.basicConfig(level=logging.NOTSET) def FromSnowNlp(text, summary_num): s = SnowNLP(text) return s.summary(summary_num) def FromJieba(text, keywords_type, keywords_num): if keywords_type == "tfidf": ret...
Python
zaydzuhri_stack_edu_python
comment 第一次 最小位次排序 for i in d0 begin append d1 at i % 10 i end print d1 set d0_1 = list for i in d1 begin if i begin for j in i begin append d0_1 j end end end print d0_1 comment 第二次 次低位排序 set d2 = list comprehension list for x in range 10 for i in d0_1 begin append d2 at integer i / 10 i end print d2 set d0_2 = list...
# 第一次 最小位次排序 for i in d0: d1[i % 10].append(i) print(d1) d0_1 = [] for i in d1: if i: for j in i: d0_1.append(j) print(d0_1) # 第二次 次低位排序 d2 = [[] for x in range(10)] for i in d0_1: d2[int(i/10)].append(i) print(d2) d0_2 = [] for i in d2: if i: for j in i: d0_2...
Python
zaydzuhri_stack_edu_python
import sys insert path 0 string evoman from controller import Controller class RNNController extends Controller begin function __init__ self ctrnn time_const begin set ctrnn = ctrnn set time_const = time_const end function function control self inputs controller begin set output = call advance inputs time_const time_co...
import sys sys.path.insert(0, 'evoman') from controller import Controller class RNNController(Controller): def __init__(self, ctrnn, time_const): self.ctrnn = ctrnn self.time_const = time_const def control(self, inputs, controller): output = self.ctrnn.advance(inputs, self.time_const,...
Python
zaydzuhri_stack_edu_python
comment Main Menu comment https://www.sourcecodester.com/tutorials/python/11784/python-pygame-simple-main-menu-selection.html function main_menu begin set menu = true set selected = string start while menu begin for event in get event begin if type == QUIT begin call quit call quit end if type == KEYDOWN begin if key =...
# Main Menu #https://www.sourcecodester.com/tutorials/python/11784/python-pygame-simple-main-menu-selection.html def main_menu(): menu=True selected="start" while menu: for event in pygame.event.get(): if event.type==pygame.QUIT: pygame.quit() quit() ...
Python
zaydzuhri_stack_edu_python
function save_to_file self fp sep=string begin set n = 0 set m = read self while m begin set n = n + 1 write fp call get_body if sep begin write fp sep end call delete_message m set m = read self end return n end function
def save_to_file(self, fp, sep='\n'): n = 0 m = self.read() while m: n += 1 fp.write(m.get_body()) if sep: fp.write(sep) self.delete_message(m) m = self.read() return n
Python
nomic_cornstack_python_v1
function init_feature_encode self encode begin set feature_encode_list = list for m in range M begin if m == 0 begin set layers = list dim + encode at string hlayers at m + list encode at string Klist at m end else begin set layers = list dim + 1 + encode at string hlayers at m + list encode at string Klist at m end c...
def init_feature_encode(self, encode): feature_encode_list = [] for m in range(self.M): if m == 0: layers = [self.dim] + encode['hlayers'][m] + [encode['Klist'][m]] else: layers = [self.dim+1] + encode['hlayers'][m] + [encode['Klist'][m]] ...
Python
nomic_cornstack_python_v1
import matplotlib import numpy as np import pandas as pd import warnings import matplotlib.pyplot as plt import seaborn as sns comment 忽略弹出的warnings信息 filter warnings string ignore set data = read csv string ../datasets/WA_Fn-UseC_-Telco-Customer-Churn.csv comment 显示所有列 call set_option string display.max_columns none p...
import matplotlib import numpy as np import pandas as pd import warnings import matplotlib.pyplot as plt import seaborn as sns warnings.filterwarnings('ignore') # 忽略弹出的warnings信息 data = pd.read_csv('../datasets/WA_Fn-UseC_-Telco-Customer-Churn.csv') pd.set_option('display.max_columns', None) # 显示所有列 pr...
Python
zaydzuhri_stack_edu_python
function calculate_precision gts preds threshold=0.5 form=string coco ious=none begin set n = length preds set tp = 0 set fp = 0 comment for pred_idx, pred in enumerate(preds_sorted): for pred_idx in range n begin set best_match_gt_idx = call find_best_match gts preds at pred_idx pred_idx threshold=threshold form=form ...
def calculate_precision(gts, preds, threshold = 0.5, form = 'coco', ious=None): n = len(preds) tp = 0 fp = 0 # for pred_idx, pred in enumerate(preds_sorted): for pred_idx in range(n): best_match_gt_idx = find_best_match(gts, preds[pred_idx], pred_idx, ...
Python
nomic_cornstack_python_v1
comment 2.在控制台获取年龄 comment 如果小于0 打印输入错误 comment 如果 小于2 打印是婴儿 comment 如果 小于2~13 儿童 comment 13~20 青年 comment 20~65 成年人 comment 65~130 老年人 comment 超过130 不可能 set age = integer input string 请输入年龄: if age < 0 begin print string 输入错误 end else if age < 2 begin print string 是婴儿 end else if age < 13 begin print string 是儿童 end el...
# 2.在控制台获取年龄 # 如果小于0 打印输入错误 # 如果 小于2 打印是婴儿 # 如果 小于2~13 儿童 # 13~20 青年 # 20~65 成年人 # 65~130 老年人 # 超过130 不可能 age = int(input('请输入年龄:')) if age<0: print('输入错误') elif age<2: print('是婴儿') elif age<13: print('是儿童') elif age<20: print('青年') elif age<65: print('成年人') elif age...
Python
zaydzuhri_stack_edu_python
function _top2gap score zi=none begin set sc_sort = sort np score if zi is none begin return tuple sc_sort at - 1 - sc_sort at - 2 none end else begin set sc_argsort = call argsort score if sc_argsort at - 1 == zi begin return tuple sc_sort at - 1 - sc_sort at - 2 sc_argsort at - 2 end else begin return tuple score at ...
def _top2gap( score: np.ndarray, zi: Optional[int] = None ) -> Tuple[np.ndarray, Optional[int]]: sc_sort = np.sort(score) if zi is None: return (sc_sort[-1] - sc_sort[-2]), None else: sc_argsort = np.argsort(score) if sc_argsort[-1] == zi: return (sc_sort[-1] - sc_so...
Python
nomic_cornstack_python_v1
import math function gcd a b begin if b == 0 begin return a end return call gcd b a % b end function function is_prime n begin if n <= 1 begin return false end for i in range 2 integer square root n + 1 begin if n % i == 0 begin return false end end return true end function function sum_of_digits n begin return sum gen...
import math def gcd(a, b): if b == 0: return a return gcd(b, a % b) def is_prime(n): if n <= 1: return False for i in range(2, int(math.sqrt(n)) + 1): if n % i == 0: return False return True def sum_of_digits(n): return sum(int(digit) for digit in str(n)) ...
Python
jtatman_500k
function createjob self search_query begin set data = dictionary search=search_query output_mode=output_mode count=string -1 set search_url = format string /servicesNS/{0}/search/search/jobs/ username set request = call Request format string {0}{1} url search_url data=url encode data headers=auth_header set connection ...
def createjob(self, search_query): data = dict(search=search_query, output_mode=self.output_mode, count='-1') search_url = '/servicesNS/{0}/search/search/jobs/'.format(self.username) request = urllib2.Request('{0}{1}'.format(self.url, search_url), data=urllib.ur...
Python
nomic_cornstack_python_v1
function triangle_to_rectangle triangle_points rectangle_center rectangle_axes rectangle_lengths begin comment compare edges of triangle to the interior of rectangle set best_dist = MAX_FLOAT set i0 = 2 set i1 = 0 while i1 < 3 begin set segment_start = triangle_points at i0 set segment_end = triangle_points at i1 set t...
def triangle_to_rectangle( triangle_points, rectangle_center, rectangle_axes, rectangle_lengths): # compare edges of triangle to the interior of rectangle best_dist = MAX_FLOAT i0 = 2 i1 = 0 while i1 < 3: segment_start = triangle_points[i0] segment_end = triangle_points[i1] ...
Python
nomic_cornstack_python_v1
function _get_v6_default_link_metric_l1_adv self begin return __v6_default_link_metric_l1_adv end function
def _get_v6_default_link_metric_l1_adv(self): return self.__v6_default_link_metric_l1_adv
Python
nomic_cornstack_python_v1
from pages.courses.register_courses_pages import RegisterCoursesPages from utilities.teststatus import TestStatus import unittest import pytest from ddt import ddt , data , unpack import time decorator call usefixtures string oneTimeSetUp string setUp decorator ddt class RegisterCoursesTest extends TestCase begin decor...
from pages.courses.register_courses_pages import RegisterCoursesPages from utilities.teststatus import TestStatus import unittest import pytest from ddt import ddt, data, unpack import time @pytest.mark.usefixtures("oneTimeSetUp", "setUp") @ddt class RegisterCoursesTest(unittest.TestCase): @pytest.fixture(autous...
Python
zaydzuhri_stack_edu_python
function rotate cls a b c begin return tuple c - b a end function
def rotate(cls, a, b, c): return (c,-b,a)
Python
nomic_cornstack_python_v1
import discord import os import colorama from colorama import Fore , Style import requests import time from colorama import Fore function Cls begin call system string cls end function call Cls set b = BRIGHT set message = input string PROVIDE A TEXT FOR YRUS MASS DM call Cls set token = input string PASTE TOKEN HERE: c...
import discord import os import colorama from colorama import Fore, Style import requests import time from colorama import Fore def Cls(): os.system('cls') Cls() b = Style.BRIGHT message = input("PROVIDE A TEXT FOR YRUS MASS DM") Cls() token = input("PASTE TOKEN HERE: ") Cls() b = Style.BRIGHT print(f""" {b+F...
Python
zaydzuhri_stack_edu_python
from datetime import datetime from typing import List from enum import Enum from pprint import pprint from acaisdk.utils.utils import bytes_to_size class Alignment extends Enum begin set LEFT = string {{:{}}} set RIGHT = string {{:>{}}} end class class PrettyPrint begin decorator staticmethod function single_col data l...
from datetime import datetime from typing import List from enum import Enum from pprint import pprint from acaisdk.utils.utils import bytes_to_size class Alignment(Enum): LEFT = '{{:{}}}' RIGHT = '{{:>{}}}' class PrettyPrint: @staticmethod def single_col(data: List, lexi_sort=False): if lexi...
Python
zaydzuhri_stack_edu_python
function add_heat heatmap bbox_list begin for box in bbox_list begin comment Add += 1 for all pixels inside each bbox comment Assuming each "box" takes the form ((x1, y1), (x2, y2)) set heatmap at tuple slice box at 0 at 1 : box at 1 at 1 : slice box at 0 at 0 : box at 1 at 0 : = heatmap at tuple slice box at 0 at 1 ...
def add_heat(heatmap, bbox_list): for box in bbox_list: # Add += 1 for all pixels inside each bbox # Assuming each "box" takes the form ((x1, y1), (x2, y2)) heatmap[box[0][1]:box[1][1], box[0][0]:box[1][0]] += 1 # Return updated heatmap return heatmap
Python
nomic_cornstack_python_v1
class Colors extends object begin function __init__ self begin set red = 1 set orange = 2 set yellow = 3 end function function do_nothing self begin pass end function end class set c = call Colors print __dict__
class Colors(object): def __init__(self): self.red = 1 self.orange = 2 self.yellow = 3 def do_nothing(self): pass c = Colors() print(c.__dict__)
Python
zaydzuhri_stack_edu_python
function get_random_position start_position end_position begin return random integer start_position end_position end function
def get_random_position(start_position, end_position): return random.randint(start_position, end_position)
Python
nomic_cornstack_python_v1
comment creatign a reptile class which inherits from the Animal class from animal import Animal class Reptile extends Animal begin function __init__ self begin comment we have a keyword called super, which inherits everything from the parent class at the time of initialisation of the class. call __init__ set cold_blood...
#creatign a reptile class which inherits from the Animal class from animal import Animal class Reptile(Animal): def __init__(self): #we have a keyword called super, which inherits everything from the parent class at the time of initialisation of the class. super().__init__() self.cold_blo...
Python
zaydzuhri_stack_edu_python
set tuple q h s d n = map int split read open 0 print n // 2 * min 8 * q 4 * h 2 * s d + n % 2 * min 4 * q 2 * h s
q,h,s,d,n = map(int,open(0).read().split()) print(n//2*min(8*q,4*h,2*s,d)+(n%2)*min(4*q,2*h,s))
Python
zaydzuhri_stack_edu_python
function load cls filepath begin return load BaseProfiler filepath end function
def load(cls, filepath): return BaseProfiler.load(filepath)
Python
nomic_cornstack_python_v1
function decode self shortUrl begin comment Assumes the URL has been encoded previously, use the TinyURL extension as key to retrieve from the dictionary return urlDict at shortUrl at slice 19 : : end function
def decode(self, shortUrl): # Assumes the URL has been encoded previously, use the TinyURL extension as key to retrieve from the dictionary return urlDict[shortUrl[19:]]
Python
nomic_cornstack_python_v1
comment Michael Li comment Computers 10 comment 2021/6/9 comment user types in something then the program prints out the initials of user's response function initialsfunction user_response begin set user_response = strip upper user_response string ., set initials = user_response at 0 for i in range length user_response...
#Michael Li #Computers 10 #2021/6/9 #user types in something then the program prints out the initials of user's response def initialsfunction(user_response): user_response = user_response.upper().strip(".,") initials = user_response[0] for i in range(len(user_response)): if user_response[i] ==" ": ...
Python
zaydzuhri_stack_edu_python
import numpy as np import random as r class MathExpression begin set intRange = 9 set minDepth = 2 set maxDepth = 12 function __init__ self begin pass end function function genExp begin set exp = dict set boolean = false comment determine if the expression should be correct or not if random < 0.5 begin set boolean = t...
import numpy as np import random as r class MathExpression: intRange = 9 minDepth = 2 maxDepth = 12 def __init__(self): pass def genExp(): exp = {} boolean = False #determine if the expression should be correct or not if r.random() < 0.5: boole...
Python
zaydzuhri_stack_edu_python
function _validate_number_base self begin if not is instance _number_base int begin raise call NumberException string Base is not an int end if _number_base < 2 or _number_base > 16 begin raise call NumberException string Please choose a base between 2 and 16 end end function
def _validate_number_base(self): if not isinstance(self._number_base, int): raise NumberException("Base is not an int") if self._number_base < 2 or self._number_base > 16: raise NumberException("Please choose a base between 2 and 16")
Python
nomic_cornstack_python_v1
class Solution begin function floodFill self image sr sc newColor begin function helper image x y newColor color begin comment print(x,y) if x < 0 or x >= length image or y < 0 or y >= length image at 0 begin return end if image at x at y == color begin set image at x at y = newColor call helper image x y + 1 newColor ...
class Solution: def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]: def helper(image,x,y,newColor,color): # print(x,y) if(x<0 or x>=len(image) or y<0 or y>=len(image[0])): return ...
Python
zaydzuhri_stack_edu_python
function random_vertical_flip_quad image quads classes p=0.5 begin assert p >= 0 msg string p must be larger than or equal to zero assert p <= 1 msg string p must be less than or equal to 1 comment if (random.random() > p): comment return image, quads, classes set temp_quads = copy quads set temp_quads at tuple slice ...
def random_vertical_flip_quad( image, quads, classes, p=0.5 ): assert p >= 0, "p must be larger than or equal to zero" assert p <= 1, "p must be less than or equal to 1" # if (random.random() > p): # return image, quads, classes temp_quads = quads.copy() temp_quads[:, :, 1...
Python
nomic_cornstack_python_v1
import os from collections import Counter from itertools import product from PIL import Image , ImageDraw set WHITE = tuple 255 255 255 set BLACK = tuple 0 0 0 set RED = tuple 255 0 0 set GREEN = tuple 0 255 0 set BLUE = tuple 0 0 255 set PINK = tuple 255 0 255 function get_brightness img begin string Find brightness l...
import os from collections import Counter from itertools import product from PIL import Image, ImageDraw WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) PINK = (255, 0, 255) def get_brightness(img): """ Find brightness level of each pixel :param img: P...
Python
zaydzuhri_stack_edu_python
function CopyMaterial source_index destination_index begin if source_index == destination_index begin return false end set source = Materials at source_index if source is none begin return false end set rc = call Modify source destination_index true if rc begin call Redraw end return rc end function
def CopyMaterial(source_index, destination_index): if source_index==destination_index: return False source = scriptcontext.doc.Materials[source_index] if source is None: return False rc = scriptcontext.doc.Materials.Modify(source, destination_index, True) if rc: scriptcontext.doc.Views.Redraw() ...
Python
nomic_cornstack_python_v1
function random cls n=5 d=2 nm=2 nv=3 borns=list - 1 1 begin set anatomy = random n=n d=d borns=borns call recenter centroid set motions = list if nm >= 1 begin append motions random n=nv d=d end if nm >= 2 begin append motions random n=nv d=d end if nm >= 3 begin extend motions list comprehension random n=nv d=d for ...
def random(cls, n=5, d=2, nm=2, nv=3, borns=[-1, 1]): anatomy = FormAnatomy.random(n=n, d=d, borns=borns) anatomy.recenter(anatomy.centroid) motions = [] if nm >= 1: motions.append(Motion.random(n=nv, d=d)) if nm >= 2: motions.append(Moment.random(n=nv, d=...
Python
nomic_cornstack_python_v1
function get_labels self labels_from_json begin set raw_labels = labels_from_json end function
def get_labels(self, labels_from_json): self.raw_labels = labels_from_json
Python
nomic_cornstack_python_v1
function get_dev_examples self begin raise call NotImplementedError end function
def get_dev_examples(self): raise NotImplementedError()
Python
nomic_cornstack_python_v1
function payload self begin set payload = dict string aps aps if extra begin update payload extra end return payload end function
def payload(self): payload = { 'aps': self.aps, } if self.extra: payload.update(self.extra) return payload
Python
nomic_cornstack_python_v1
function get_data data_file label_file begin with open data_file string r as data ; open label_file string r as label begin set data_reader = reader data set label_reader = reader label set data = list set label = list for data_line in data_reader begin set line_int = list comprehension integer i for i in data_line a...
def get_data(data_file,label_file): with open(data_file,"r") as data, open(label_file,"r") as label: data_reader = csv.reader(data) label_reader = csv.reader(label) data = [] label = [] for data_line in data_reader: line_int = [int(i) for i in data_line] ...
Python
nomic_cornstack_python_v1
function CountsOfMotifs motifs initCount begin set k = length motifs at 0 for kmer in motifs begin assert k == length kmer end set counts = list for i in range k begin set count_i = list initCount * 4 for kmer in motifs begin set count_i at call indexOfAcid kmer at i = count_i at call indexOfAcid kmer at i + 1 end app...
def CountsOfMotifs(motifs, initCount): k = len(motifs[0]) for kmer in motifs: assert k == len(kmer) counts = [] for i in range(k): count_i = [initCount] * 4 for kmer in motifs: count_i[indexOfAcid(kmer[i])] += 1 counts.append(count_i) return counts
Python
nomic_cornstack_python_v1
function solve weight_0 weight_1 weight_2 begin set arreglo = list weight_0 weight_1 weight_2 set maximo = max arreglo if maximo == weight_0 begin return 0 end else if maximo == weight_1 begin return 1 end else begin return 2 end end function comment return maximo print call solve 195 18 500
def solve(weight_0, weight_1, weight_2): arreglo=[weight_0,weight_1,weight_2] maximo=max(arreglo) if maximo==weight_0: return 0 elif maximo==weight_1: return 1 else: return 2 #return maximo print(solve(195,18,500))
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment coding:utf-8 import os import random import time from typing import List , Tuple from urllib.request import urlopen import json set GAME_SERVER = call getenv string GAME_SERVER string https://contest.gbc-2020.tenka1.klab.jp set TOKEN = call getenv string TOKEN string function call_...
#!/usr/bin/env python3 #coding:utf-8 import os import random import time from typing import List, Tuple from urllib.request import urlopen import json GAME_SERVER = os.getenv('GAME_SERVER', 'https://contest.gbc-2020.tenka1.klab.jp') TOKEN = os.getenv('TOKEN', '') def call_api(x) -> str: with urlopen(f'{GAME_SERVER}...
Python
zaydzuhri_stack_edu_python
import random comment これがないとエラーになる set b = 0 for i in range 10000 begin comment 101のとき 0~100 set rand = random * 101 if integer rand == 100 begin set b = b + 1 end end comment 100%表記の乱数 print b string print(2**5) #2^5 との違い a = [114, 514, 187, 810] print (len(a)) #4 print (a[2]) #187 a[0] == 114 print (810 in a) #True b...
import random b = 0 #これがないとエラーになる for i in range(10000): rand = random.random()*101 #101のとき 0~100 if int(rand) == 100: b+=1 print(b) #100%表記の乱数 """ print(2**5) #2^5 との違い a = [114, 514, 187, 810] print (len(a)) #4 print (a[2]) #187 a[0] == 114 print (810 in a) #True b = sorted(a) print (...
Python
zaydzuhri_stack_edu_python
function spectralKurtosis_thresholds M p=0.0013499 N=1 d=1 begin set Nd = N * d comment Statistical moments set moment_1 = 1 set moment_2 = 2 * M ^ 2 * Nd * 1 + Nd / M - 1 * 6 + 5 * M * Nd + M ^ 2 * Nd ^ 2 set moment_3 = 8 * M ^ 3 * Nd * 1 + Nd * - 2 + Nd * - 5 + M * 4 + Nd / M - 1 ^ 2 * 2 + M * Nd * 3 + M * Nd * 4 + M...
def spectralKurtosis_thresholds(M, p = 0.0013499, N = 1, d = 1): Nd = N * d #Statistical moments moment_1 = 1 moment_2 = ( 2*(M**2) * Nd * (1 + Nd) ) / ( (M - 1) * (6 + 5*M*Nd + (M**2)*(Nd**2)) ) moment_3 = ( 8*(M**3)*Nd * (1 + Nd) * (-2 + Nd * (-5 + M * (4+Nd))) ) / ( ((M-1)**2) * (2+M*Nd) *(3+M*...
Python
nomic_cornstack_python_v1
import numpy as np from PIL import Image import sys comment from most black to most white set INVERSED_SPECTRUM = string $@B%8&WM#\*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,"^`'. comment same as above but from most white to most black set FULL_SPECTRUM = inversed_spectrum at slice : : - 1 comment 10 leve...
import numpy as np from PIL import Image import sys INVERSED_SPECTRUM = '$@B%8&WM#\*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,"^`\'. ' #from most black to most white FULL_SPECTRUM = inversed_spectrum[::-1] #same as above but from most white to most black SMALL_SPECTRUM = " .:-=+*#%@" #10 levels from most w...
Python
zaydzuhri_stack_edu_python
function test_open_ped_multifamily self begin write temp string A B 0 0 1 1 write temp string C D 0 0 1 1 flush temp set families = call open_ped name set fam1 = call Family string A call add_person call Person string A string B string 0 string 0 string 1 string 1 set fam2 = call Family string C call add_person call Pe...
def test_open_ped_multifamily(self): self.temp.write('A B 0 0 1 1\n') self.temp.write('C D 0 0 1 1\n') self.temp.flush() families = open_ped(self.temp.name) fam1 = Family('A') fam1.add_person(Person('A', 'B', '0', '0', '1', '1')) fam2 = ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python2 import sys import string function create length begin if length > 20280 begin return string Maximum limit exceeded end set pattern = string for i in range 10 begin for j in list lowercase begin for k in list uppercase begin set pattern = pattern + string i + string j + string k if length ...
#!/usr/bin/env python2 import sys import string def create(length): if length>20280: return "Maximum limit exceeded" pattern="" for i in range(10): for j in list(string.lowercase): for k in list(string.uppercase): pattern=pattern+str(i)+str(j)+str(k) ...
Python
zaydzuhri_stack_edu_python
import json from django.db import models from django.db.models import Q from models import Rule , RuleType class RuleController extends object begin function __init__ self begin pass end function function create self pattern warning name scope type user begin string Create a rule and save it to the database set rule = ...
import json from django.db import models from django.db.models import Q from .models import ( Rule, RuleType ) class RuleController(object): def __init__(self): pass def create(self, pattern, warning, name, scope, type, user): """ Create a rule and save it to the database """ ru...
Python
zaydzuhri_stack_edu_python
comment Python code that combines all gathered comment from twitter, facebook and cnet texts in two files comment amazon_echo_combined_text.txt and google_home_combined_text.txt comment These files are used for Topic Analysis import time import pandas as pd comment AMAZON comment Open the Amazon combined text set amazo...
# Python code that combines all gathered comment from twitter, facebook and cnet texts in two files # amazon_echo_combined_text.txt and google_home_combined_text.txt # These files are used for Topic Analysis import time import pandas as pd # AMAZON # Open the Amazon combined text amazonFulltext_filename = '../../dat...
Python
zaydzuhri_stack_edu_python
function certificate_chain self begin return get pulumi self string certificate_chain end function
def certificate_chain(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "certificate_chain")
Python
nomic_cornstack_python_v1
import matplotlib.pyplot as plt import numpy as np set Fs = 70 set f = 1 set sample = 1000 set x = array range sample set y = sin 2 * pi * f * x / Fs subplot 311 plot x y set Fs1 = 80 set f = 1 set sample = 1000 set a = array range sample set b = sin 2 * pi * f * a / Fs1 subplot 312 plot a b string g set z = y + b subp...
import matplotlib.pyplot as plt import numpy as np Fs=70 f=1 sample = 1000 x= np.arange(sample) y=np.sin(2*np.pi*f*x/Fs) plt.subplot(311) plt.plot(x,y) Fs1=80 f=1 sample=1000 a=np.arange(sample) b=np.sin(2*np.pi*f*a/Fs1) plt.subplot(312) plt.plot(a,b,'g') z=y+b plt.subplot(313) plt.plot(a,z) plt.xlabel('sample(n)') plt...
Python
zaydzuhri_stack_edu_python
comment RANDOM FOREST from base_model import BaseModel import numpy as np from sklearn import metrics from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import GridSearchCV class Model extends BaseModel begin function __init__ self begin call __init__ string RF end function function train ...
# RANDOM FOREST from base_model import BaseModel import numpy as np from sklearn import metrics from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import GridSearchCV class Model (BaseModel): def __init__ (self): super().__init__('RF') def train (self, Xt, Xv, Yt, Yv, verbose=False...
Python
zaydzuhri_stack_edu_python
function handle_stop_test self test begin pass end function
def handle_stop_test(self, test): pass
Python
nomic_cornstack_python_v1
function SetMaskImage self _arg begin return call itkConnectedComponentImageFilterIUC3IUL3_SetMaskImage self _arg end function
def SetMaskImage(self, _arg: 'itkImageUC3') -> "void": return _itkConnectedComponentImageFilterPython.itkConnectedComponentImageFilterIUC3IUL3_SetMaskImage(self, _arg)
Python
nomic_cornstack_python_v1
function _start_run_binary self remote_command begin set command_list = list RUN if alias is not none begin extend command_list list string -as alias end if wait begin append command_list string -w end append command_list command set command = join string command_list + string call sendall command end function
def _start_run_binary(self, remote_command): command_list = [ process_manager.ProcessManager.RUN ] if remote_command.alias is not None: command_list.extend(['-as', remote_command.alias]) if remote_command.wait: command_list.append('-w') command_list.appen...
Python
nomic_cornstack_python_v1
class BuildingCost begin string This class represents the costs for building a settlement function __init__ self material construction cost settlement_min begin set material = material set construction = construction set cost = cost set settlement_min = settlement_min end function function getCosts self begin string Th...
class BuildingCost: """This class represents the costs for building a settlement""" def __init__(self, material, construction, cost, settlement_min): self.material = material self.construction = construction self.cost = cost self.settlement_min = settlement_min def getCosts...
Python
zaydzuhri_stack_edu_python
function test_install_binary_iterating_remotes_different_rrev self begin set pref = call create ref conanfile=call with_build_msg string REv1 call upload_all ref remote=string default run format string remove {} -p {} -f -r default ref id comment Same RREV, different PREV set pref = call create ref conanfile=call with_...
def test_install_binary_iterating_remotes_different_rrev(self): pref = self.c_v2.create(self.ref, conanfile=GenConanfile().with_build_msg("REv1")) self.c_v2.upload_all(self.ref, remote="default") self.c_v2.run("remove {} -p {} -f -r default".format(self.ref, pref.id)) # Same RREV, diff...
Python
nomic_cornstack_python_v1
function get_chunks dims chunk_y chunk_x begin comment First determine the number of chunks in each dimension set tuple Ny Nx = dims set Ny_chunk = integer Ny // chunk_y set Nx_chunk = integer Nx // chunk_x if Ny % chunk_y != 0 begin set Ny_chunk = Ny_chunk + 1 end if Nx % chunk_x != 0 begin set Nx_chunk = Nx_chunk + 1...
def get_chunks(dims, chunk_y, chunk_x): # First determine the number of chunks in each dimension Ny, Nx = dims Ny_chunk = int(Ny // chunk_y) Nx_chunk = int(Nx // chunk_x) if Ny % chunk_y != 0: Ny_chunk += 1 if Nx % chunk_x != 0: Nx_chunk += 1 # Now construct chunk bounds ...
Python
nomic_cornstack_python_v1
string @author: Dmitry from common.dataset.DatasetBase import * import pickle as pkl import tarfile import os.path import numpy as np string import time import os import urllib.request from scipy.io import loadmat import sys function random_translate image vbound=tuple - 2 2 hbound=tuple - 2 2 begin set v = random inte...
''' @author: Dmitry ''' from common.dataset.DatasetBase import * import pickle as pkl import tarfile import os.path import numpy as np ''' import time import os import urllib.request from scipy.io import loadmat import sys ''' def random_translate(image, vbound = (-2, 2), hbound = (-2, 2)): v = np.random.randint...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment Given an integer, , perform the following conditional actions: comment If n is odd, print Weird comment If n is even and in the inclusive range of 2 to 5, print Not Weird comment If n is even and in the inclusive range of 6 to 20, print Weird comment If n is even and greater than 2...
#!/usr/bin/env python3 #Given an integer, , perform the following conditional actions: #If n is odd, print Weird #If n is even and in the inclusive range of 2 to 5, print Not Weird #If n is even and in the inclusive range of 6 to 20, print Weird #If n is even and greater than 20, print Not Weird #Input Format #A sin...
Python
zaydzuhri_stack_edu_python
function allow_log_file self begin return _allow_log_file end function
def allow_log_file(self): return self._allow_log_file
Python
nomic_cornstack_python_v1
string 112. Path Sum https://leetcode.com/problems/path-sum/ Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. Note: A leaf is a node with no children. Example: Given the below binary tree and sum = 22, 5 / 4 8 / / 11 13 ...
''' 112. Path Sum https://leetcode.com/problems/path-sum/ Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. Note: A leaf is a node with no children. Example: Given the below binary tree and sum = 22, 5 / \...
Python
zaydzuhri_stack_edu_python
import os , shutil comment declare the paths of downloaded folder; Training, Validation and Test folder set downloaded_dir = string /Users/bathuy/Downloads/fruits-360 comment downloaded_dir = '/home/ubuntu/DeepLearning/Fruit-Images-Dataset' set valid_dir = join path downloaded_dir string Validation set training_dir = j...
import os, shutil # declare the paths of downloaded folder; Training, Validation and Test folder downloaded_dir = '/Users/bathuy/Downloads/fruits-360' # downloaded_dir = '/home/ubuntu/DeepLearning/Fruit-Images-Dataset' valid_dir = os.path.join(downloaded_dir, 'Validation') training_dir = os.path.join(downloaded_dir, '...
Python
zaydzuhri_stack_edu_python
function _get_ipv4 self begin return __ipv4 end function
def _get_ipv4(self): return self.__ipv4
Python
nomic_cornstack_python_v1
function triangle_area a b c begin comment calculate the semi-perimeter set semi_perimeter = a + b + c / 2 comment calculate the area set area = semi_perimeter * semi_perimeter - a * semi_perimeter - b * semi_perimeter - c ^ 0.5 return area end function call triangle_area 5 6 7
def triangle_area(a,b,c): # calculate the semi-perimeter semi_perimeter = (a + b + c) / 2 # calculate the area area = (semi_perimeter * (semi_perimeter - a) * (semi_perimeter - b) * (semi_perimeter - c)) ** 0.5 return area triangle_area(5, 6, 7)
Python
zaydzuhri_stack_edu_python
function finder files queries begin comment hash the queries as the key and the file path as the value for quick look up set cache = dict set results = list comment for q in queries: comment if 'nofile' in q: comment continue comment else: comment print(q) comment for path in files: comment if q in path: comment prin...
def finder(files, queries): # hash the queries as the key and the file path as the value for quick look up cache = {} results = [] # for q in queries: # if 'nofile' in q: # continue # else: # print(q) # for path in files: # ...
Python
zaydzuhri_stack_edu_python
function register_delimiters self *delimiters begin for m in delimiters begin append _delim m end end function
def register_delimiters(self, *delimiters): for m in delimiters: self._delim.append(m)
Python
nomic_cornstack_python_v1
function _F begin pass end function
def _F(): pass
Python
nomic_cornstack_python_v1
class BooleanComparator begin function compare self bool1 bool2 begin if bool2 == false or none and bool1 == true begin return - 1 end else if bool1 == false or none and bool2 == true begin return 1 end else begin comment Both booleans have the same value return 0 end end function end class
class BooleanComparator: def compare(self, bool1, bool2): if bool2 == False or None and bool1 == True: return -1 elif bool1 == False or None and bool2 == True: return 1 # Both booleans have the same value else: return 0
Python
zaydzuhri_stack_edu_python
from reflective_listening import ReflectiveListening comment "Today is a bad day, I'm feeling lonely" set input_text = string why don't you go outside and do some exercies set reflector = call ReflectiveListening set rephrase = call get_response input_text print string Original text is: input_text string for i in rephr...
from reflective_listening import ReflectiveListening input_text = "why don't you go outside and do some exercies" #"Today is a bad day, I'm feeling lonely" reflector = ReflectiveListening() rephrase = reflector.get_response(input_text) print('\nOriginal text is: ', input_text, '\n') for i in rephrase: print('Par...
Python
zaydzuhri_stack_edu_python
function sigmoid Z begin set A = 1 / 1 + exp - Z set cache = Z return tuple A cache end function
def sigmoid(Z): A = 1/(1 + np.exp(-Z)) cache = Z return A, cache
Python
nomic_cornstack_python_v1
from typing import List class Solution begin function maxProfit self prices begin set profit = 0 for i in range 1 length prices begin set tmp = prices at i - prices at i - 1 if tmp > 0 begin set profit = profit + tmp end end return profit end function end class if __name__ == string __main__ begin set solution = call S...
from typing import List class Solution: def maxProfit(self, prices: List[int]) -> int: profit = 0 for i in range(1, len(prices)): tmp = prices[i] - prices[i-1] if tmp > 0: profit += tmp return profit if __name__ == '__main__': solution = Solution...
Python
zaydzuhri_stack_edu_python
function logout begin clear session return call redirect call url_for string index end function
def logout(): session.clear() return redirect(url_for('index'))
Python
nomic_cornstack_python_v1
import cv2 import numpy as np comment input set Video_in = string data\formwork.mp4 comment output set Video_out = string output/progress.mp4 comment Video Settings set winName = string output call resizeWindow winName 500 500 set cap = call VideoCapture Video_in set fps = integer get cap CAP_PROP_FPS set length_video ...
import cv2 import numpy as np # input Video_in = "data\\formwork.mp4" # output Video_out = "output/progress.mp4" # Video Settings winName = 'output' cv2.resizeWindow(winName, 500, 500) cap = cv2.VideoCapture(Video_in) fps = int(cap.get(cv2.CAP_PROP_FPS)) length_video = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) width ...
Python
zaydzuhri_stack_edu_python
function getConnections self begin pass end function
def getConnections(self): pass
Python
nomic_cornstack_python_v1
function get_context self begin set ctx = dict for clause in where_clauses or list begin call update_context ctx end return ctx end function
def get_context(self): ctx = {} for clause in self.where_clauses or []: clause.update_context(ctx) return ctx
Python
nomic_cornstack_python_v1
function _cname self account_id begin set company = company_id set caddress = call _cadd company return name end function
def _cname(self,account_id): company = self.pool.get('account.account').browse(self.cr, self.uid, account_id).company_id self.caddress = self._cadd(company) return company.name
Python
nomic_cornstack_python_v1
function allocate_device_array self shape dtype stream begin raise NotImplementedError end function
def allocate_device_array(self, shape, dtype, stream): raise NotImplementedError
Python
nomic_cornstack_python_v1
from setuptools import setup , find_packages setup name=string pierre version=string 1.0.0 py_modules=list string pierre install_requires=list string Click string mistune package_dir=dict string string pierre entry_points=dict string console_scripts list string pierre = pierre:main
from setuptools import setup, find_packages setup( name = "pierre", version = "1.0.0", py_modules = ["pierre"], install_requires = [ "Click", "mistune", ], package_dir = {"": "pierre"}, entry_points = { "console_scripts": [ "pierre = pierre:main" ...
Python
jtatman_500k
function EncodeMultipartFormData fields files begin set BOUNDARY = string -M-A-G-I-C---B-O-U-N-D-A-R-Y- set CRLF = string set lines = list for tuple key value in fields begin append lines string -- + BOUNDARY append lines string Content-Disposition: form-data; name="%s" % key append lines string append lines value en...
def EncodeMultipartFormData(fields, files): BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-' CRLF = '\r\n' lines = [] for (key, value) in fields: lines.append('--' + BOUNDARY) lines.append('Content-Disposition: form-data; name="%s"' % key) lines.append('') lines.append(value) for (key, filename, val...
Python
nomic_cornstack_python_v1
function displayEmptyInputWarningBox display=true parent=none begin string Displays a warning box for the 'input' parameter. if version_info at 0 >= 3 begin from tkinter.messagebox import showwarning end else begin from tkMessageBox import showwarning end if display begin set msg = string No valid input files found! + ...
def displayEmptyInputWarningBox(display=True, parent=None): """ Displays a warning box for the 'input' parameter. """ if sys.version_info[0] >= 3: from tkinter.messagebox import showwarning else: from tkMessageBox import showwarning if display: msg = 'No valid input files fo...
Python
jtatman_500k
import urllib import urllib.request try begin set site = url open string http://www.pudim.com.br/ end except URLError begin print string Site não acessivel end try else begin print string Site acessivel print read site end
import urllib import urllib.request try: site = urllib.request.urlopen('http://www.pudim.com.br/') except urllib.error.URLError: print("Site não acessivel") else: print("Site acessivel") print(site.read())
Python
zaydzuhri_stack_edu_python
comment 선행조건을 리스트를 이용해 스택을 쌓아서 만든다. import sys comment sys.stdin = open("작업순서.txt") set stdin = open string test.txt set T = 1 comment DPS_route로 경로 찾기 function DPS_route begin global visited test V set stack = list start stack comment test>1이면 선행조건이 있으므로 새로운 시작점 찾기 comment if sum(test[S]) > 1: comment start() comment...
#선행조건을 리스트를 이용해 스택을 쌓아서 만든다. import sys # sys.stdin = open("작업순서.txt") sys.stdin = open("test.txt") T = 1 # DPS_route로 경로 찾기 def DPS_route(): global visited, test, V stack=[] start(stack) # test>1이면 선행조건이 있으므로 새로운 시작점 찾기 # if sum(test[S]) > 1: # start() # else: while len(stack) != 0...
Python
zaydzuhri_stack_edu_python
function render_to_string template_name dictionary=none context_instance=none begin set dictionary = dictionary or dict if is instance template_name tuple list tuple begin set t = call select_template template_name end else begin set t = call get_template template_name end if not context_instance begin return call ren...
def render_to_string(template_name, dictionary=None, context_instance=None): dictionary = dictionary or {} if isinstance(template_name, (list, tuple)): t = select_template(template_name) else: t = get_template(template_name) if not context_instance: return t.render(Context(dictio...
Python
nomic_cornstack_python_v1
import re , markdown , dateutil , json from datetime import timedelta , datetime function yamlfile f begin from yaml import load try begin from yaml import CLoader as Loader end except ImportError begin from yaml import Loader end if type f is str begin with open f as stream begin set data = load stream Loader=Loader e...
import re, markdown, dateutil, json from datetime import timedelta, datetime def yamlfile(f): from yaml import load try: from yaml import CLoader as Loader except ImportError: from yaml import Loader if type(f) is str: with open(f) as stream: data = load(stream, Loa...
Python
zaydzuhri_stack_edu_python
from flask import Blueprint , request , jsonify , session , g , abort from werkzeug.security import generate_password_hash , check_password_hash from comma_board import db from comma_board.models import User set bp = call Blueprint string auth __name__ url_prefix=string /auth decorator call route string /signup methods...
from flask import Blueprint, request, jsonify, session, g, abort from werkzeug.security import generate_password_hash, check_password_hash from comma_board import db from comma_board.models import User bp = Blueprint('auth', __name__, url_prefix = '/auth') @bp.route('/signup', methods = ('GET', 'POST')) def signup(...
Python
zaydzuhri_stack_edu_python
function move self direction begin if direction == 0 begin set top = top - speed end else if direction == 1 begin set left = left - speed end else if direction == 2 begin set top = top + speed end else if direction == 3 begin set left = left + speed end end function
def move(self, direction): if direction == 0: self.rect.top -= self.speed elif direction == 1: self.rect.left -= self.speed elif direction == 2: self.rect.top += self.speed elif direction == 3: self.rect.left += self.speed
Python
nomic_cornstack_python_v1
import re from word_blacklist import BLACKLIST import time import numpy as np set ARTICLES_PATH = string articles/ set MAX_VALID_WORD_LENGTH = 20 set MIN_VALID_WORD_LENGTH = 1 class Analyzer begin function __init__ self begin comment A list of articles read from file set rawArticles = list comment A list of words_coun...
import re from word_blacklist import BLACKLIST import time import numpy as np ARTICLES_PATH = "articles/" MAX_VALID_WORD_LENGTH = 20 MIN_VALID_WORD_LENGTH = 1 class Analyzer(): def __init__(self): # A list of articles read from file self.rawArticles = [] # A list of words_count_dict der...
Python
zaydzuhri_stack_edu_python
function select self selectors begin set obj : CommandObject = self for tuple name selector in selectors begin set tuple root items = items obj name comment if non-root object and no selector given if root is false and selector is none begin raise call SelectError string name selectors end comment if no items in conta...
def select(self, selectors: List[SelectorType]) -> CommandObject: obj: CommandObject = self for name, selector in selectors: root, items = obj.items(name) # if non-root object and no selector given if root is False and selector is None: raise SelectErr...
Python
nomic_cornstack_python_v1
function to_celluloid self array begin set celluloid_array = copy array comment Define the color threshold for the celluloid filter set tuple min_val max_val = tuple min max set thresholds = linear space min_val max_val 5 comment Apply the thresolds for i in range 1 length thresholds begin set mask = celluloid_array > ...
def to_celluloid(self, array): celluloid_array = array.copy() # Define the color threshold for the celluloid filter min_val, max_val = celluloid_array.min(), celluloid_array.max() thresholds = np.linspace(min_val, max_val, 5) # Apply the thresolds for i in range(1, len(...
Python
nomic_cornstack_python_v1
function related_words self templates word threshold=5 **kwargs begin return call _wordnet_stuff templates word string related threshold=threshold keyword kwargs end function
def related_words(self, templates, word, threshold=5, **kwargs): return self._wordnet_stuff(templates, word, 'related', threshold=threshold, **kwargs)
Python
nomic_cornstack_python_v1
string 可以发现,int型数据可以支持记录巨长的数字,资料显示32位机器int有32位,64位机器int有64位, 此外还有长整型,几乎就是无限长度。 但是float只能记录17位有效数字,但是对于很大或很小的浮点数,就必须用科学计数法表示,把10用e替代。 整数和浮点数在计算机内部存储的方式是不同的,整数运算永远是精确的(除法难道也是精确的?是的!),而浮点数运算则可能会有四舍五入的误差。 复数支持小数点。
''' 可以发现,int型数据可以支持记录巨长的数字,资料显示32位机器int有32位,64位机器int有64位, 此外还有长整型,几乎就是无限长度。 但是float只能记录17位有效数字,但是对于很大或很小的浮点数,就必须用科学计数法表示,把10用e替代。 整数和浮点数在计算机内部存储的方式是不同的,整数运算永远是精确的(除法难道也是精确的?是的!),而浮点数运算则可能会有四舍五入的误差。 复数支持小数点。 '''
Python
zaydzuhri_stack_edu_python
function __call__ self data random_state begin raise NotImplementedError end function
def __call__(self, data, random_state): raise NotImplementedError
Python
nomic_cornstack_python_v1