code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function recall_password cipher_grille ciphered_password begin set mystr = string set mystr = mystr + call find4 cipher_grille ciphered_password comment rotate 90 set rotate1 = list zip *cipher_grille[::-1] set mystr = mystr + call find4 rotate1 ciphered_password comment rotate 90 set rotate2 = list zip *rotate1[::-1]...
def recall_password(cipher_grille, ciphered_password): mystr = '' mystr += find4(cipher_grille, ciphered_password) #rotate 90 rotate1 = list(zip(*cipher_grille[::-1])) mystr += find4(rotate1, ciphered_password) #rotate 90 rotate2 = list(zip(*rotate1[::-1])) mystr += find4(rotate2, ciphe...
Python
zaydzuhri_stack_edu_python
set tuple n m = map int split input if m != 1 begin print 1 end else begin print 2 end
n,m=map(int,input().split()) if(m!=1): print(1) else: print(2)
Python
zaydzuhri_stack_edu_python
function assign_variable self variable value begin call assign_variable variable=variable value=value end function
def assign_variable(self, variable, value): self.model.assign_variable(variable=variable, value=value)
Python
nomic_cornstack_python_v1
function idf_corpus corpus begin comment build idf score for all terms in the corpus comment first, build a vocab of the corpus set vocab = set for document in corpus begin set vocab = vocab ? set document end comment then, calculate the idf for each term in the vocab set idf_set = call IdfDict length corpus for term i...
def idf_corpus(corpus): #build idf score for all terms in the corpus #first, build a vocab of the corpus vocab = set() for document in corpus: vocab |= set(document) #then, calculate the idf for each term in the vocab idf_set = IdfDict(len(corpus)) for term in vocab: idf_se...
Python
nomic_cornstack_python_v1
function get_courses_by_title request begin set body_unicode = decode body string utf-8 set body = loads body_unicode set courses = filter title__contains=get body string course_title_contain set response_data = list for course in courses begin append response_data dict string course_title title ; string course_start_...
def get_courses_by_title(request): body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) courses = Course.objects.filter(title__contains = body.get('course_title_contain')) response_data = [] for course in courses: response_data.append({ ...
Python
nomic_cornstack_python_v1
function cells self begin set manager = call _get_manager set my_cells = get pin_to_cells self list return list comprehension target for c in my_cells end function
def cells(self): manager = self._get_manager() my_cells = manager.pin_to_cells.get(self, []) return [c.target for c in my_cells]
Python
nomic_cornstack_python_v1
function test_deregister_post_import_hook_after_register_multiple self begin comment Enforce a spec so that hasattr doesn't vacuously return True. set test_hook = call MagicMock spec=list set test_hook2 = call MagicMock spec=list call register_post_import_hook string tests.utils.test_module test_hook call register_post...
def test_deregister_post_import_hook_after_register_multiple(self): # Enforce a spec so that hasattr doesn't vacuously return True. test_hook = mock.MagicMock(spec=[]) test_hook2 = mock.MagicMock(spec=[]) register_post_import_hook('tests.utils.test_module', test_hook) register_po...
Python
nomic_cornstack_python_v1
function _forecast_dict_to_obj self forecast_dict forecast_start_date item_id info begin raise call NotImplementedError end function
def _forecast_dict_to_obj( self, forecast_dict: Dict, forecast_start_date: pd.Timestamp, item_id: Optional[str], info: Dict, ) -> Forecast: raise NotImplementedError()
Python
nomic_cornstack_python_v1
function cosine_similarity embedding valid_size=16 valid_window=100 device=string cpu begin comment Here we're calculating the cosine similarity between some random words and comment our embedding vectors. With the similarities, we can look at what words are comment close to our random words. comment sim = (a . b) / |a...
def cosine_similarity(embedding, valid_size=16, valid_window=100, device='cpu'): # Here we're calculating the cosine similarity between some random words and # our embedding vectors. With the similarities, we can look at what words are # close to our random words. # sim = (a . b) / |a||b| ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment @Time : 2017/10/9 18:24 comment @Author : wangdechang set n = 22 set primes = list 17 2 3 5 7 set size = length primes set res = list 0 * n set times = list 0 * n set res at 0 = 1 import sys for i in range 1 n begin set min_val = maxsize for j in range ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/10/9 18:24 # @Author : wangdechang n = 22 primes = [17, 2, 3, 5, 7] size = len(primes) res = [0] * n times = [0] * n res[0] = 1 import sys for i in range(1, n): min_val = sys.maxsize for j in range(size): min_val = min(min_val, primes[j...
Python
zaydzuhri_stack_edu_python
from utils.audio_experiment_util import * import wave import sys from models.deep_speech import Speech2Text import numpy as np function load_audio_file wav_audio_path begin set sample_rate = 16000 set fin = open wav_audio_path string rb set frame_rate = call getframerate if frame_rate != sample_rate begin print format ...
from utils.audio_experiment_util import * import wave import sys from models.deep_speech import Speech2Text import numpy as np def load_audio_file(wav_audio_path): sample_rate = 16000 fin = wave.open(wav_audio_path, 'rb') frame_rate = fin.getframerate() if frame_rate != sample_rate: print( ...
Python
zaydzuhri_stack_edu_python
function DAVIDenrich database categories user ids ids_bg=none name=string name_bg=string verbose=false p=0.1 n=2 begin set ids = join string , list comprehension string i for i in ids set use_bg = 0 if ids_bg is not none begin set ids_bg = join string , list comprehension string i for i in ids_bg end set _create_defa...
def DAVIDenrich(database, categories, user, ids, ids_bg = None, name = '', name_bg = '', verbose = False, p = 0.1, n = 2): ids = ','.join([str(i) for i in ids]) use_bg = 0 if ids_bg is not None: ids_bg = ','.join([str(i) for i in ids_bg]) ssl._create_default_https_context = ssl._create_unverified...
Python
nomic_cornstack_python_v1
function test_resultset_error self begin with assert raises InfluxDBClientError begin call ResultSet dict string series list ; string error string Big error, many problems. end end function
def test_resultset_error(self): with self.assertRaises(InfluxDBClientError): ResultSet({ "series": [], "error": "Big error, many problems." })
Python
nomic_cornstack_python_v1
for i in range n - k + 1 begin if candle at i < 0 and candle at i + k - 1 > 0 begin set temp = min absolute candle at i candle at i + k - 1 * 2 + max absolute candle at i candle at i + k - 1 end else if candle at i + k - 1 <= 0 begin set temp = absolute candle at i end else if candle at i >= 0 begin set temp = candle a...
for i in range(n-k+1): if candle[i]<0 and candle[i+k-1]>0: temp=min(abs(candle[i]), candle[i+k-1])*2+max(abs(candle[i]), candle[i+k-1]) elif candle[i+k-1]<=0: temp=abs(candle[i]) elif candle[i]>=0: temp=candle[i+k-1] ans=min(temp, ans) print(ans)
Python
zaydzuhri_stack_edu_python
comment /usr/bin/env python comment encoding: utf-8 string 写法非常精悍。 - 用一个dummy节点表示头,这样子不需要初始化,最后再返回dummy.next - 交换的方式得到当前最小的节点 - l1 or l2的方式得到有效的链表 comment Definition for singly-linked list. class ListNode begin function __init__ self x begin set val = x set next = none end function end class class Solution begin functi...
#/usr/bin/env python #encoding: utf-8 ''' 写法非常精悍。 - 用一个dummy节点表示头,这样子不需要初始化,最后再返回dummy.next - 交换的方式得到当前最小的节点 - l1 or l2的方式得到有效的链表 ''' # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def mergeTwoLists(self, l1, l2): ...
Python
zaydzuhri_stack_edu_python
comment 有 N 件物品和一个容量为 V 的背包。 comment 第 i 件物品的体积是Ci,价值是Wi。 comment 求解将哪些物品装入背包可使价值总和最大。 comment 子问题:另 f(i, V) 为 前i个元素中所能获取的价值最大值,则有: comment f(i, V) = max( f(i-1, V), f(i-1, V-items[i])+values[i] ) comment ↑ ↑ comment 放 不放 comment 边界条件:当V小于0或者i<0时,return 0 import functools set cache = dict function _cache func begin fu...
# 有 N 件物品和一个容量为 V 的背包。 # 第 i 件物品的体积是Ci,价值是Wi。 # 求解将哪些物品装入背包可使价值总和最大。 # 子问题:另 f(i, V) 为 前i个元素中所能获取的价值最大值,则有: # f(i, V) = max( f(i-1, V), f(i-1, V-items[i])+values[i] ) # ↑ ↑ # 放 不放 # 边界条件:当V小于0或者i<0时,return 0 import functools cache = {} def _cache(fu...
Python
zaydzuhri_stack_edu_python
import json import requests class MeetUpDriver extends object begin set key = none set api_url = string https://api.meetup.com function __init__ self begin set key = read line open string api_key.txt end function end class
import json import requests class MeetUpDriver(object): key = None api_url = "https://api.meetup.com" def __init__(self): self.key = open("api_key.txt").readline()
Python
zaydzuhri_stack_edu_python
comment 2020/02/18 Is a Prime number? comment 該程式碼將判斷輸入的數字是否為質數 comment 質數的定義: comment 大於 1 的正整數,且該整數之因數只有 1 與 本身 set num = integer input string 輸入一正整數: if num == 1 begin print string 質數為大於 1 的正整數... end else if num > 1 begin comment 放置因數 set divisor = list for i in range 1 num + 1 begin if num % i == 0 begin append d...
# 2020/02/18 Is a Prime number? # 該程式碼將判斷輸入的數字是否為質數 # # 質數的定義: # 大於 1 的正整數,且該整數之因數只有 1 與 本身 num = int(input('輸入一正整數: ')) if num == 1: print('質數為大於 1 的正整數...') elif num > 1: divisor=[] # 放置因數 for i in range(1, num+1): if num % i == 0: divisor.append(i) if len(divisor) == 2: ...
Python
zaydzuhri_stack_edu_python
function get_imlist path begin return list comprehension join path path f for f in list directory path if ends with f string .JPG end function
def get_imlist(path): return [os.path.join(path,f) for f in os.listdir(path) if f.endswith('.JPG')]
Python
nomic_cornstack_python_v1
function register_implementation implementation_name expansion_cls node_cls begin if not is subclass expansion_cls ExpandTransformation begin raise call TypeError format string Expected ExpandTransformation class, got: {} __name__ end if not is subclass node_cls LibraryNode begin raise call TypeError format string Expe...
def register_implementation(implementation_name, expansion_cls, node_cls): if not issubclass(expansion_cls, ExpandTransformation): raise TypeError("Expected ExpandTransformation class, got: {}".format(type(node_cls).__name__)) if not issubclass(node_cls, LibraryNode): raise TypeError("Expected L...
Python
nomic_cornstack_python_v1
function ids_samples_get self begin return _samples_order end function
def ids_samples_get(self): return self._samples_order
Python
nomic_cornstack_python_v1
comment %load q01_longest_even_word/build.py comment Default imports import sys import numpy as np import nltk call download string punkt import re from nltk.tokenize import word_tokenize comment nltk.download('punkt') set sentence = string One great way to make predictions about an unfamiliar nonfiction text is to tak...
# %load q01_longest_even_word/build.py # Default imports import sys import numpy as np import nltk nltk.download('punkt') import re from nltk.tokenize import word_tokenize #nltk.download('punkt') sentence='One great way to make predictions about an unfamiliar nonfiction text is to take a walk through the book before re...
Python
zaydzuhri_stack_edu_python
string Exercicio 41 - function imc a b c begin print string Calculando o imc de { a } , que possui altura { b } e peso em kilos { c } return c / b * b end function function calc_altura begin while true begin try begin set al = input string Informe sua altura em metros: set al = replace al string , string . set al = dec...
""" Exercicio 41 - """ def imc(a, b, c): print(f"Calculando o imc de {a}, que possui altura {b} e peso em kilos {c}") return c / (b * b) def calc_altura(): while True: try: al = input(f"Informe sua altura em metros: ") al = al.replace(',', '.') al = float(al) ...
Python
zaydzuhri_stack_edu_python
function msg self begin if string msg in _json begin return _json at string msg end else if string detail in _json begin return _json at string detail end else begin return _json end end function
def msg(self): if "msg" in self._json: return self._json["msg"] elif "detail" in self._json: return self._json["detail"] else: return self._json
Python
nomic_cornstack_python_v1
import torch.nn as nn import torch.nn.functional as F class TripletNet extends Module begin function __init__ self embedding_net begin call __init__ set embedding_net = embedding_net end function function forward self x y z begin set embedded_x = call embedding_net x set embedded_y = call embedding_net y set embedded_z...
import torch.nn as nn import torch.nn.functional as F class TripletNet(nn.Module): def __init__(self, embedding_net): super(TripletNet, self).__init__() self.embedding_net = embedding_net def forward(self, x, y, z): embedded_x = self.embedding_net(x) embedded_y = self.embeddin...
Python
zaydzuhri_stack_edu_python
import time comment from locust import HttpUser, task, between from locust import HttpUser , task , constant comment See https://docs.locust.io/en/stable/quickstart.html class QuickstartUser extends HttpUser begin comment the simulated users wait between 1 and 2.5 seconds after each task (see below) is executed. commen...
import time #from locust import HttpUser, task, between from locust import HttpUser, task, constant # See https://docs.locust.io/en/stable/quickstart.html class QuickstartUser(HttpUser): # the simulated users wait between 1 and 2.5 seconds after each task (see below) is executed. #wait_time = between(1, 2.5)...
Python
zaydzuhri_stack_edu_python
comment dp solution class Solution extends object begin function uniquePathsWithObstacles self obstacleGrid begin set tuple m n = tuple length obstacleGrid at 0 length obstacleGrid set dp = list comprehension list comprehension 0 for _ in call xrange m for _ in call xrange n for i in call xrange n begin for j in call x...
# dp solution class Solution(object): def uniquePathsWithObstacles(self, obstacleGrid): m, n = len(obstacleGrid[0]), len(obstacleGrid) dp = [[0 for _ in xrange(m)] for _ in xrange(n)] for i in xrange(n): for j in xrange(m): if obstacleGrid[i][j] != 0: ...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- comment !/usr/bin/env python comment @Time: 2020-05-01 7:52 p.m. 未做 string The letters of the alphabet can be constructed from a moderate number of basic ele- ments, like vertical and horizontal lines and a few curves. Design an alphabet that can be drawn with a minimal number of basic ele...
# -*- coding: utf-8 -*- # !/usr/bin/env python # @Time: 2020-05-01 7:52 p.m. 未做 """The letters of the alphabet can be constructed from a moderate number of basic ele- ments, like vertical and horizontal lines and a few curves. Design an alphabet that can be drawn with a minimal number of basic elements and then w...
Python
zaydzuhri_stack_edu_python
comment dict是一種課變容器模型,且可儲存任意類型物件,由(key->value)組成 comment 不允許同一個key出現兩次以上,建立時若同一個key被設定兩次,後值會覆蓋前值 comment key不可變,可用數字、字串、元組,但不可用列表 comment 字典是無序的,元素沒有順序之分(不須透過位置尋找元素),所以在儲存元素時保持最佳化 comment 建立字典 set dict = dict string name string shizu ; string age 22 ; string sex string male print string dict['name']: dict at string nam...
# dict是一種課變容器模型,且可儲存任意類型物件,由(key->value)組成 ## 不允許同一個key出現兩次以上,建立時若同一個key被設定兩次,後值會覆蓋前值 ## key不可變,可用數字、字串、元組,但不可用列表 ## 字典是無序的,元素沒有順序之分(不須透過位置尋找元素),所以在儲存元素時保持最佳化 # 建立字典 dict = {'name':'shizu', 'age':22,'sex':'male'} print("dict['name']: ", dict['name']) # 修改字典 dict = {'name':'shizu', 'age':22,'sex':'male'} dict['name'] ...
Python
zaydzuhri_stack_edu_python
import sys from math import * for line in stdin begin set l = split line set a = integer l at 0 set x = integer l at 1 set y = integer l at 2 comment print a,x,y set flag = 1 if y % a == 0 begin set flag = 0 end set det = y - a set d = det / 2 * a set e = det % 2 * a set ans = 1 + d + 1 * 3 comment print '\t',d,e comme...
import sys from math import * for line in sys.stdin: l = line.split() a = int(l[0]) x = int(l[1]) y = int(l[2]) # print a,x,y flag = 1 if y % a == 0: flag = 0 det = (y - a) d = det / ( 2 * a) e = det % (2 * a) ans = 1 + (d+1) * 3 #print '\t',d,e # print ans if y < a: if abs(x) >= a / 2.0: flag = 0 ...
Python
zaydzuhri_stack_edu_python
from db.run_sql import run_sql from models.booking import Booking from models.member import Member import repositories.lesson_repository as lesson_repository import repositories.member_repository as member_repository function save booking begin set sql = string INSERT INTO bookings (member_id, lesson_id) VALUES (%s, %s...
from db.run_sql import run_sql from models.booking import Booking from models.member import Member import repositories.lesson_repository as lesson_repository import repositories.member_repository as member_repository def save(booking): sql = "INSERT INTO bookings (member_id, lesson_id) VALUES (%s, %s) RETURNING id...
Python
zaydzuhri_stack_edu_python
import pandas as pd from sklearn.metrics import accuracy_score , mean_squared_error , log_loss from tqdm.notebook import trange , tqdm from IPython.display import HTML import warnings import torch filter warnings string ignore import torch.nn as nn import torch.nn.functional as F from torch import optim import numpy as...
import pandas as pd from sklearn.metrics import accuracy_score, mean_squared_error, log_loss from tqdm.notebook import trange, tqdm from IPython.display import HTML import warnings import torch warnings.filterwarnings('ignore') import torch.nn as nn import torch.nn.functional as F from torch import optim import num...
Python
zaydzuhri_stack_edu_python
comment coding: utf-8 comment In[1]: from keras.datasets import cifar10 set tuple tuple X_train Y_train tuple X_test Y_test = call load_data comment # Keras comment In[2]: print shape print shape comment In[3]: comment print(X_train[0]) comment In[4]: comment we have pixel values here let's convert into between 0 and 1...
# coding: utf-8 # In[1]: from keras.datasets import cifar10 (X_train,Y_train),(X_test,Y_test)=cifar10.load_data() # # Keras # In[2]: print(X_train.shape) print(X_test.shape) # In[3]: #print(X_train[0]) # In[4]: #we have pixel values here let's convert into between 0 and 1 X_train=X_train/255.0 X_test=X_test...
Python
zaydzuhri_stack_edu_python
import numpy as np function calculate_array_sum_and_product N begin comment Generate the random array set arr = random integer - 1000 1001 N comment Initialize variables for sum and product set negative_sum = 0 set positive_product = 1 comment Iterate over the array for num in arr begin comment Check if the number is n...
import numpy as np def calculate_array_sum_and_product(N): # Generate the random array arr = np.random.randint(-1000, 1001, N) # Initialize variables for sum and product negative_sum = 0 positive_product = 1 # Iterate over the array for num in arr: # Check if the number is negativ...
Python
jtatman_500k
function already_running self begin if _already is none begin comment Attempt to acquire a lock. call _acquire_lock end return _already end function
def already_running(self): if self._already is None: # Attempt to acquire a lock. self._acquire_lock() return self._already
Python
nomic_cornstack_python_v1
import numpy as np seed 0 from sklearn.ensemble import RandomForestClassifier as RFC from sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_score function classify begin set train_features = call genfromtxt string computed_data/train_feature_vectors.csv delimiter=string , set train_labels = c...
import numpy as np np.random.seed(0) from sklearn.ensemble import RandomForestClassifier as RFC from sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_score def classify(): train_features = np.genfromtxt('computed_data/train_feature_vectors.csv', delimiter=',') train_labels = np.gen...
Python
zaydzuhri_stack_edu_python
string Generate a base64 random string comment !/usr/bin/python set __author__ = string dev import sys , os , base64 comment defaults set intdeflen = 10 if length argv <= 1 begin print format string Defaulting to {0} intdeflen print format string python {0} <length of random base64 string> argv at 0 end else begin try ...
""" Generate a base64 random string """ #!/usr/bin/python __author__ = 'dev' import sys, os, base64 # defaults intdeflen = 10 if len(sys.argv) <= 1: print("Defaulting to {0}".format(intdeflen)) print("python {0} <length of random base64 string>".format(sys.argv[0])) else: try: intdeflen = int(sys...
Python
zaydzuhri_stack_edu_python
comment Name: Sabur Khan comment Date: 10/10/19 comment Course: COSC 2316 Fall 2019 (Dr. Shebaro) comment Program Description: Spanish-English Dictionary comment Algorithm/Psuedocode ######## comment 1. create function that reads/updates through the dictionary.txt file and stores it into a dictionary, even count will r...
# Name: Sabur Khan # Date: 10/10/19 # Course: COSC 2316 Fall 2019 (Dr. Shebaro) # Program Description: Spanish-English Dictionary ######### Algorithm/Psuedocode ######## #1. create function that reads/updates through the dictionary.txt file and stores it into a dictionary, even count will represent english, odd-...
Python
zaydzuhri_stack_edu_python
function sendEmail message begin set message_string = join string message set recipients = list string nadavo@campus.technion.ac.il string olegzendel@campus.technion.ac.il set msg = call EmailMessage set msg at string Subject = string Finished training and predicting MEMM set msg at string From = string someserver@tec...
def sendEmail(message): message_string = '\n'.join(message) recipients = ['nadavo@campus.technion.ac.il', 'olegzendel@campus.technion.ac.il'] msg = EmailMessage() msg['Subject'] = 'Finished training and predicting MEMM' msg['From'] = 'someserver@technion.ac.il' msg['To'] = ', '.join(recipients) ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding=utf-8 comment list 列表 set list1 = list 1 2 3 4 5 6 print list1 print string ==================================== set list2 = list 1 1.1 string Test string Fan print list2 print string ==================================== set list3 = list 2 3 list1 print list3
#!/usr/bin/env python #coding=utf-8 #list 列表 list1 = [1, 2,3,4,5,6] print (list1) print ("====================================") list2 = [1, 1.1, 'Test', "Fan"] print (list2) print ("====================================") list3 = [2, 3, list1] print (list3)
Python
zaydzuhri_stack_edu_python
function makePermutations n begin set half = n // 2 set full = half * 2 set swap = call rand half > 0.5 set px = array range n set px at slice : full : 2 = px at slice : full : 2 + swap set px at slice 1 : full : 2 = px at slice 1 : full : 2 - swap return px end function
def makePermutations(n): half = n // 2 full = half * 2 swap = np.random.rand(half) > 0.5 px = np.arange(n) px[:full:2] += swap px[1:full:2] -= swap return px
Python
nomic_cornstack_python_v1
class Solution begin function findAnagrams self s p begin set base = dict set indices = list for val in p begin if val not in base begin set base at val = 0 end set base at val = base at val + 1 end set length = length p set word = dict for i in range 0 length s begin set current = s at slice i : i + length : comme...
class Solution: def findAnagrams(self, s: str, p: str) -> List[int]: base = {} indices = [] for val in p: if val not in base: base[val]= 0 base[val] += 1 length = len(p) word = {} for i in range(0,len(s)): current = ...
Python
zaydzuhri_stack_edu_python
string Markup database type Converts to string on bind. Returns Markup on process result. from flask import Markup from sqlalchemy.types import Text , TypeDecorator class MarkupType extends TypeDecorator begin set impl = Text function process_bind_param self value dialect begin return if expression value is not none th...
"""Markup database type Converts to string on bind. Returns Markup on process result. """ from flask import Markup from sqlalchemy.types import Text, TypeDecorator class MarkupType(TypeDecorator): impl = Text def process_bind_param(self, value, dialect): return str(value) if value is not None else ...
Python
zaydzuhri_stack_edu_python
function stochastic_neighborSameType agent otherAgent cutoff=1 begin set result = type == type and name != name set draw = random if draw > cutoff begin return 0 end else begin return 1 * result end end function
def stochastic_neighborSameType(agent, otherAgent, cutoff=1): result = agent.type == otherAgent.type \ and agent.name != otherAgent.name draw = np.random.random() if draw > cutoff: return 0 else: return 1*result
Python
nomic_cornstack_python_v1
comment @lc app=leetcode id=763 lang=python3 comment [763] Partition Labels comment @lc code=start class Solution begin function partitionLabels self S begin set last = dictionary comprehension c : i for tuple i c in enumerate S set output = list set anchor = 0 set end = 0 for tuple i c in enumerate S begin set end = ...
# # @lc app=leetcode id=763 lang=python3 # # [763] Partition Labels # # @lc code=start class Solution: def partitionLabels(self, S: str) -> List[int]: last = {c: i for i, c in enumerate(S)} output = [] anchor = end = 0 for i, c in enumerate(S): end = max(end, last[c]) ...
Python
zaydzuhri_stack_edu_python
comment BOJ13549 숨바꼭질3 20210511 import sys from collections import deque set input = readline function main begin set tuple n k = map int split right strip input set q = deque if n > k begin return print n - k end append q tuple n 0 set visited = dict set visited at n = 0 set f = list lambda x -> x - 1 lambda x -> x +...
#BOJ13549 숨바꼭질3 20210511 import sys from collections import deque input = sys.stdin.readline def main(): n, k = map(int,input().rstrip().split()) q = deque() if n > k: return print(n-k) q.append((n,0)) visited = {} visited[n] = 0 f = [lambda x: x-1, lambda x: x+1, lambda x:2*x] ...
Python
zaydzuhri_stack_edu_python
function build_input_files filename base_path=string input_files out=stdout begin set calling_dir = get current directory comment I'm doing this because I need it later set tuple file_path file_name = split path filename with open filename string r as f begin set txt = read f end comment First Parse the FDS file set tu...
def build_input_files(filename, base_path = 'input_files', out = sys.stdout): calling_dir = os.getcwd() # I'm doing this because I need it later file_path, file_name = os.path.split(filename) with open(filename, 'r') as f: txt = f.read() ## First Parse the FDS file param_d...
Python
nomic_cornstack_python_v1
function validateEdge cls start_socket end_socket begin for validator in call getEdgeValidators begin if not call validator start_socket end_socket begin return false end end return true end function
def validateEdge(cls, start_socket: 'Socket', end_socket: 'Socket') -> bool: for validator in cls.getEdgeValidators(): if not validator(start_socket, end_socket): return False return True
Python
nomic_cornstack_python_v1
function score self begin return integer property3 end function
def score(self): return int(self.property3)
Python
nomic_cornstack_python_v1
function pos3dTo2dWindow _pos begin set proj = call pos3dTo2dViewport _pos if proj is not none begin return tuple integer proj at 0 / 2.0 + 0.5 * width integer 1 - proj at 1 / 2.0 + 0.5 * height end return none end function
def pos3dTo2dWindow(_pos): proj = pos3dTo2dViewport(_pos) if proj is not None: return int((proj[0] / 2.0 + 0.5) * Window.width), int( (1 - (proj[1] / 2.0 + 0.5)) * Window.height) return None
Python
nomic_cornstack_python_v1
import sys append path string /Users/Timothy/Code/Poloniex/trading_bot/python import requests import threading import imp import time from api.poloniex_wrapper import poloniex from constants.api_key import API_KEY , SECRET_KEY comment poloniex class macd_bot extends Thread begin function __init__ self polo pair begin c...
import sys sys.path.append("/Users/Timothy/Code/Poloniex/trading_bot/python") import requests import threading import imp import time from api.poloniex_wrapper import poloniex from constants.api_key import API_KEY, SECRET_KEY #poloniex class macd_bot(threading.Thread): def __init__(self, polo, pair): super().__in...
Python
zaydzuhri_stack_edu_python
comment Imports print string Welcome to Drowsiness Script import os import argparse from PreprocessOneVideo import Preprocessing comment from blink_video import blink_detector from Prediction import Predict print string Import successfully comment adjust video path here set video_path_global = string ./Videos/Müdigkeit...
# Imports print("Welcome to Drowsiness Script") import os import argparse from PreprocessOneVideo import Preprocessing #from blink_video import blink_detector from Prediction import Predict print("Import successfully") # adjust video path here video_path_global = "./Videos/Müdigkeit_Video_ingrid.mov" # Kalibrierungsvi...
Python
zaydzuhri_stack_edu_python
import json from abc import abstractmethod class BaseDBConnector extends object begin function __init__ self config_path begin set config = call load_config_file config_path end function decorator staticmethod function load_config_file config_path begin with open config_path as json_file begin set data = load json json...
import json from abc import abstractmethod class BaseDBConnector(object): def __init__(self, config_path): self.config = self.load_config_file(config_path) @staticmethod def load_config_file(config_path): with open(config_path) as json_file: data = json.load(json_file) ...
Python
zaydzuhri_stack_edu_python
from enum import Enum from src.data.cardConfig import simple_game import random class CardPackage begin function __init__ self begin set all_cards = simple_game end function function random_card self begin set element = random choice all_cards remove all_cards element return element end function function distribute_car...
from enum import Enum from src.data.cardConfig import simple_game import random class CardPackage: def __init__(self): self.all_cards = simple_game def random_card(self): element = random.choice(self.all_cards) self.all_cards.remove(element) return element def distri...
Python
zaydzuhri_stack_edu_python
comment TODO: Copy all of your 04-Drawing.py program and put it below this comment. comment My first Pygame program. comment Authors: Many people and Saujin import pygame import sys set screenSize = tuple 640 480 set backroundcolor = tuple 0 200 220 set circlecolor = tuple 0 0 0 set circleradius = 20 set rectY = 100 se...
# TODO: Copy all of your 04-Drawing.py program and put it below this comment. # My first Pygame program. # Authors: Many people and Saujin import pygame import sys screenSize = (640,480) backroundcolor = (0,200,220) circlecolor = (0,0,0) circleradius = 20 rectY = 100 rectspeed = 5 pygame.init() screen = pygame...
Python
zaydzuhri_stack_edu_python
function evaluate_simple embeddings labels normalize=false standardize=false alpha=0.5 begin set tuple N dim = shape if normalize begin set embeddings = embeddings / reshape norm embeddings axis=1 - 1 1 end if standardize begin set mu = mean np embeddings axis=0 set std = standard deviation np embeddings axis=0 + tiny ...
def evaluate_simple(embeddings, labels, normalize=False, standardize=False, alpha=0.5): N, dim = embeddings.shape if normalize: embeddings /= np.linalg.norm(embeddings, axis=1).reshape(-1,1) if standardize: mu = np.mean(embeddings, axis=0) std = np.std(embeddings, axis=0) + np.finfo...
Python
nomic_cornstack_python_v1
from scipy.sparse import lil_matrix from scipy.spatial import distance function convert_values_to_float cntr begin for tuple k v in items cntr begin set cntr at k = decimal v end end function function mtx_from_cntrs cntrs begin comment Convert all the values in the counters to floats for i in range length cntrs begin c...
from scipy.sparse import lil_matrix from scipy.spatial import distance def convert_values_to_float(cntr): for k, v in cntr.items(): cntr[k] = float(v) def mtx_from_cntrs(cntrs): # Convert all the values in the counters to floats for i in range(len(cntrs)): convert_values_to_float(cntrs[i]...
Python
zaydzuhri_stack_edu_python
import logging import threading import time from queue import Queue import visa from pyvisa import VisaIOError call basicConfig level=DEBUG format=string (%(threadName)-9s) %(message)s class Agilent33220A begin function __init__ self BUF_SIZE=10 begin set command_queue = queue BUF_SIZE set c = call ConsumerThread comma...
import logging import threading import time from queue import Queue import visa from pyvisa import VisaIOError logging.basicConfig(level=logging.DEBUG, format='(%(threadName)-9s) %(message)s') class Agilent33220A(): def __init__(self, BUF_SIZE=10): self.command_queue = Queue(BUF_SIZE)...
Python
zaydzuhri_stack_edu_python
function writeIndented self text begin write self oneIndent * indentLevel + text end function
def writeIndented(self,text): self.write(self.oneIndent*self.indentLevel + text)
Python
nomic_cornstack_python_v1
for i in range 3 begin if a at i > b at i begin set A = A + 1 end else if a at i < b at i begin set B = B + 1 end end print string A + string + string B
for i in range(3): if a[i] > b[i]: A += 1 elif a[i] < b[i]: B += 1 print(str(A) + ' ' + str(B))
Python
zaydzuhri_stack_edu_python
function coding_strand_to_AA dna begin set h = length dna set dna_list = list dna set aminoacid = list set aminoacid_s = string for i in range 0 h 3 begin try begin set codon = dna_list at i + dna_list at i + 1 + dna_list at i + 2 end except IndexError begin break end set amino_acid = aa_table at codon set aminoacid ...
def coding_strand_to_AA(dna): h= len(dna) dna_list= list(dna) aminoacid=[] aminoacid_s ="" for i in range(0, h, 3): try: codon=dna_list[i]+dna_list[i+1]+dna_list[i+2] except IndexError: break amino_acid=aa_table[codon] aminoacid+=amino_acid ...
Python
nomic_cornstack_python_v1
function GetUseLookupTable self begin return call itkAdaptiveHistogramEqualizationImageFilterISS3_GetUseLookupTable self end function
def GetUseLookupTable(self) -> "bool": return _itkAdaptiveHistogramEqualizationImageFilterPython.itkAdaptiveHistogramEqualizationImageFilterISS3_GetUseLookupTable(self)
Python
nomic_cornstack_python_v1
for letter in upper att begin set total_att = total_att + ordinal letter end for letter in upper itl begin set total_itl = total_itl + ordinal letter end for letter in upper klg begin set total_klg = total_klg + ordinal letter end print format string Total of Attitude is: {} total_att / length att print format string T...
for letter in att.upper(): total_att += ord(letter) for letter in itl.upper(): total_itl += ord(letter) for letter in klg.upper(): total_klg += ord(letter) print("Total of Attitude is: {}".format(total_att/len(att))) print("Total of Intelligent is: {}".format(total_itl/len(itl))) print("Total of Knowledge ...
Python
zaydzuhri_stack_edu_python
comment Copyright (C) 2019 Fajar prasetio <fajarprstyo05@gmail.com> import urllib , os , random from core.percuma_logging import * function get_good_filename filename begin comment ceated this method because our program may not differenciate between the of the / in the URL and the / in the directories" set buf = string...
# Copyright (C) 2019 Fajar prasetio <fajarprstyo05@gmail.com> # import urllib, os, random from core.percuma_logging import * def get_good_filename(filename): #ceated this method because our program may not differenciate between the of the / in the URL and the / in the directories" buf = "" for c in filen...
Python
zaydzuhri_stack_edu_python
for i in range length s begin for j in range i length s begin if call issubset set literal string A string C string G string T begin set max_l = max max_l j + 1 - i end end end print max_l
for i in range(len(s)): for j in range(i, len(s)): if set(s[i:j+1]).issubset({'A', 'C', 'G', 'T'}): max_l = max(max_l, j+1 - i) print(max_l)
Python
zaydzuhri_stack_edu_python
function add_op2_data cls data comment=string begin set sid = data at 0 set node = data at 1 set mag = data at 2 set g1 = data at 3 set g2 = data at 4 set g3 = data at 5 set g4 = data at 6 return call cls sid node mag g1 g2 g3 g4 comment=comment end function
def add_op2_data(cls, data, comment=''): sid = data[0] node = data[1] mag = data[2] g1 = data[3] g2 = data[4] g3 = data[5] g4 = data[6] return cls(sid, node, mag, g1, g2, g3, g4, comment=comment)
Python
nomic_cornstack_python_v1
function make_path params begin if not is directory path result_path begin make directories result_path end if not is directory path ckpt_path begin make directories ckpt_path end if not is directory path string log begin make directories string log end end function
def make_path(params): if not os.path.isdir(params.result_path): os.makedirs(params.result_path) if not os.path.isdir(params.ckpt_path): os.makedirs(params.ckpt_path) if not os.path.isdir("log"): os.makedirs("log")
Python
nomic_cornstack_python_v1
function delete_folder folder_id begin if method == string DELETE begin set connection = call connect set cursor = call cursor try begin execute cursor string DELETE FROM `folder` WHERE id = %s folder_id commit connection close cursor close connection return string Success end except MySQLError begin close cursor close...
def delete_folder(folder_id): if request.method == 'DELETE': connection = mysql.connect() cursor = connection.cursor() try: cursor.execute("DELETE FROM `folder` WHERE id = %s", folder_id) connection.commit() cursor.close() connection.close() ...
Python
nomic_cornstack_python_v1
function prime_factorization number begin set i = 2 set factors = list while i * i <= number begin if number % i begin set i = i + 1 end else begin set number = number // i append factors i end end if number > 1 begin append factors number end return factors end function call prime_factorization number
def prime_factorization(number): i = 2 factors = [] while i * i <= number: if number % i: i += 1 else: number //= i factors.append(i) if number > 1: factors.append(number) return factors prime_factorization(number)
Python
jtatman_500k
function test_binary_search_odd_inputs begin set array = list 1 2 3 4 5 set pos = call search_in_ordered_array array 4 assert pos == 3 end function
def test_binary_search_odd_inputs(): array = [1, 2, 3, 4, 5] pos = search_in_ordered_array(array, 4) assert pos == 3
Python
nomic_cornstack_python_v1
comment Title: gateway.py comment Author: Luke McEvoy comment Created: May 18, 2020 comment Summary: Optimized space between passengers on mass transit from algorithms import * comment Function when row count is multiple of one function single rows cols passengers seats capacity_percentage begin call A_dynamic rows col...
# Title: gateway.py # Author: Luke McEvoy # Created: May 18, 2020 # Summary: Optimized space between passengers on mass transit from algorithms import * # Function when row count is multiple of one def single(rows, cols, passengers, seats, capacity_percentage): A_dynamic(rows, cols, passengers, seats) # Functi...
Python
zaydzuhri_stack_edu_python
function tokenize text begin return split upper text end function
def tokenize(text: str) -> list[str]: return text.upper().split()
Python
zaydzuhri_stack_edu_python
import pandas as pa import numpy as np import matplotlib.pyplot as plt set x = linear space 0 20 1000 set y = sin x plot x y label=string My First Application title plt string My simple data display x label string X axis y label string Y axis grid true call figtext 0.995 0.01 string Footnote ha=string right va=string b...
import pandas as pa import numpy as np import matplotlib.pyplot as plt x=np.linspace(0,20,1000) y=np.sin(x) plt.plot(x,y,label="My First Application") plt.title("My simple data display") plt.xlabel("X axis") plt.ylabel("Y axis") plt.grid(True) plt.figtext(0.995,0.01,'Footnote',ha='right',va='bottom') plt.le...
Python
zaydzuhri_stack_edu_python
string class for encoding and decoding jwt from jwt import encode as encode_jwt from jwt import decode as decode_jwt from jwt.exceptions import InvalidSignatureError , ExpiredSignatureError , InvalidTokenError class JWT begin string class that represents jwt encode/decoder function __init__ self refresh_secret access_s...
"""class for encoding and decoding jwt""" from jwt import encode as encode_jwt from jwt import decode as decode_jwt from jwt.exceptions import InvalidSignatureError, ExpiredSignatureError, InvalidTokenError class JWT: """class that represents jwt encode/decoder""" def __init__(self, refresh_secret: str, access...
Python
zaydzuhri_stack_edu_python
comment Create a ParametricHenneberg mesh. import pyvista set mesh = call ParametricHenneberg plot color=string w smooth_shading=true
# Create a ParametricHenneberg mesh. # import pyvista mesh = pyvista.ParametricHenneberg() mesh.plot(color='w', smooth_shading=True)
Python
zaydzuhri_stack_edu_python
function textify html begin comment Remove html tags and continuous whitespaces set text_only = sub string [ ]+ string call strip_tags html comment Strip single spaces in the beginning of each line return strip replace text_only string string end function
def textify(html: str) -> str: # Remove html tags and continuous whitespaces text_only = re.sub("[ \t]+", " ", strip_tags(html)) # Strip single spaces in the beginning of each line return text_only.replace('\n ', '\n').strip()
Python
nomic_cornstack_python_v1
import goslate set text = input string Enter your text: set gs = call Goslate set translateText = call translate text string fr print translateText
import goslate text=input("Enter your text:") gs=goslate.Goslate() translateText=gs.translate(text,'fr') print(translateText)
Python
zaydzuhri_stack_edu_python
import hashlib set string_data = input string Enter string data: set result = md5 encode string_data print string The hash is print string hash in byte foramt print call digest print string hash in hexadecimal format print hex digest result
import hashlib string_data = input("Enter string data: ") result = hashlib.md5(string_data.encode()) print("The hash is ") print("hash in byte foramt") print(result.digest()) print("hash in hexadecimal format") print(result.hexdigest())
Python
zaydzuhri_stack_edu_python
function __call__ self inputs state scope=none begin return call __call__ inputs state scope or _name end function
def __call__(self, inputs, state, scope=None): return super(StackedRNNCell, self).__call__( inputs, state, (scope or self._name))
Python
nomic_cornstack_python_v1
function a_update n begin return n * 16807 % 2147483647 end function function b_update n begin return n * 48271 % 2147483647 end function set N = 40000000 set count = 0 set a_tmp = a set b_tmp = b for i in range N begin set a_tmp = call a_update a_tmp set b_tmp = call b_update b_tmp if a_tmp ? 65535 == b_tmp ? 65535 be...
def a_update(n): return (n * 16807) % 2147483647 def b_update(n): return (n * 48271) % 2147483647 N = 40000000 count = 0 a_tmp = a b_tmp = b for i in range(N): a_tmp = a_update(a_tmp) b_tmp = b_update(b_tmp) if (a_tmp & 0xffff) == (b_tmp & 0xffff): count += 1 print(count) N = 5000000 count = 0 a_tmp...
Python
zaydzuhri_stack_edu_python
function fib a b begin return tuple b a + b end function set a = 1 set b = 2 set ans = 2 while b < 4 * 10 ^ 6 begin set tuple a b = call fib a b set ans = if expression b % 2 == 0 then ans + b else ans end
def fib(a, b): return (b, a+b) a = 1 b = 2 ans = 2 while (b < 4*10**6): a, b = fib(a, b) ans = ans + b if b%2 ==0 else ans
Python
zaydzuhri_stack_edu_python
function mysum x y begin print x + y end function call mysum 1 2 call mysum string 1 string 2 function print_even n begin for i in range 2 n 2 begin print i end end function call print_even 10
def mysum(x,y): print(x + y) mysum(1,2) mysum('1','2') def print_even(n): for i in range(2,n,2): print(i) print_even(10)
Python
zaydzuhri_stack_edu_python
function sadd self *args begin if _cluster begin return execute self string SADD *args shard_key=args at 0 end return execute self string SADD *args end function
def sadd(self, *args): if self._cluster: return self.execute(u'SADD', *args, shard_key=args[0]) return self.execute(u'SADD', *args)
Python
nomic_cornstack_python_v1
function memoize fun begin decorator wraps fun function wrapper *args **kwargs begin set key = tuple args call frozenset sorted items kwargs end function end function
def memoize(fun): @wraps(fun) def wrapper(*args, **kwargs): key = (args, frozenset(sorted(kwargs.items())))
Python
nomic_cornstack_python_v1
function get self request slug begin comment Find article set article = call find_article_helper slug comment Find all reactions on this article try begin set article_reactions = filter article=article set formatted_reactions = list comprehension call format_response reaction for reaction in article_reactions set respo...
def get(self, request, slug): # Find article article = find_article_helper(slug) # Find all reactions on this article try: article_reactions = UserReaction.objects.filter( article=article) formatted_reactions = [ format_response(re...
Python
nomic_cornstack_python_v1
function update_user_data user_id **data begin set user_data = call get_user_data user_id update user_data data call put_user_data user_id keyword user_data return true end function
def update_user_data(user_id, **data): user_data = get_user_data(user_id) user_data.update(data) put_user_data(user_id, **user_data) return True
Python
nomic_cornstack_python_v1
comment coding: utf-8 set alunos = integer input set notas = list map int split input string set notas = sorted notas comment frequencia modal set frequencia1 = 0 comment frequencia do número i set frequencia2 = 0 set moda = 0 for i in notas begin if frequencia1 == 0 and frequencia2 == 0 and moda == 0 begin set moda = ...
# coding: utf-8 alunos = int(input()) notas = list(map(int, input().split(' '))) notas = sorted(notas) frequencia1 = 0 # frequencia modal frequencia2 = 0 # frequencia do número i moda = 0 for i in notas: if frequencia1 == 0 and frequencia2 == 0 and moda == 0: moda = i frequencia1 = notas.count(i) ...
Python
zaydzuhri_stack_edu_python
import pickle with open string ./model/spam_mail_filter.model string rb as file begin set spamFilterModel = load pickle file end print string 스팸메일 아닌 예시 set hamExam = read open string ./example/hamExam.txt string r print hamExam set pre = predict spamFilterModel hamExam print string 결과 = pre print string --------------...
import pickle with open('./model/spam_mail_filter.model', 'rb') as file: spamFilterModel = pickle.load(file) print("스팸메일 아닌 예시") hamExam = open("./example/hamExam.txt", 'r').read() print(hamExam) pre = spamFilterModel.predict(hamExam) print("결과 =", pre) print("-----------------------------------...
Python
zaydzuhri_stack_edu_python
import Queue import threading from lxml import html import requests import time comment url_dict : dictionary containing metadata and it's url, example {'asd' : 'http:google.com'} comment num_thread : number of thread comment timeout : HTTP get timeout comment return : dictionary containing metadata and http tree, exam...
import Queue import threading from lxml import html import requests import time # url_dict : dictionary containing metadata and it's url, example {'asd' : 'http:google.com'} # num_thread : number of thread # timeout : HTTP get timeout # return : dictionary containing metadata and http tree, example {'asd' : <http ...
Python
zaydzuhri_stack_edu_python
import nltk from collections import Counter from nltk.tokenize import TreebankWordTokenizer with open string kite.txt string r as f begin set kite_text = read f end set tokenizer = call TreebankWordTokenizer set tokens = call tokenize lower kite_text set token_counts = counter tokens print token_counts print 20 * strin...
import nltk from collections import Counter from nltk.tokenize import TreebankWordTokenizer with open('kite.txt','r') as f: kite_text = f.read() tokenizer = TreebankWordTokenizer() tokens = tokenizer.tokenize(kite_text.lower()) token_counts = Counter(tokens) print(token_counts) print(20 *'-') nltk.download('stopw...
Python
zaydzuhri_stack_edu_python
string Utilities for (non-)overlapping-tile (or sliding window) predictions. import numpy as np from skimage.util import pad from skimage.transform import resize function _get_extended_image_size height width patch_size stride begin string Calculate extended height and width for given stride. set tuple ext_height ext_w...
""" Utilities for (non-)overlapping-tile (or sliding window) predictions. """ import numpy as np from skimage.util import pad from skimage.transform import resize def _get_extended_image_size(height, width, patch_size, stride): """Calculate extended height and width for given stride.""" ext_height, ext_widt...
Python
zaydzuhri_stack_edu_python
comment The idea behind the algorithm is very simple and in two steps comment We start with the base case comment If the input number is a 0, then there are no variations of this and we return [""] comment Our goal is to keep reducing the number in two fashions. One where we take two right most digits comment Second to...
# The idea behind the algorithm is very simple and in two steps # We start with the base case # If the input number is a 0, then there are no variations of this and we return [""] # Our goal is to keep reducing the number in two fashions. One where we take two right most digits # Second to take the right most digit # I...
Python
zaydzuhri_stack_edu_python
function update_node_attrs self node_id attrs normalize=true begin pass end function
def update_node_attrs(self, node_id, attrs, normalize=True): pass
Python
nomic_cornstack_python_v1
function test_do_not_ignore_different_scalar_coords products begin set stat = string mean set output = call PreprocessorFile set output_products = dict string dict stat output set kwargs = dict string statistics list stat ; string span string full ; string output_products output_products ; string keep_input_datasets f...
def test_do_not_ignore_different_scalar_coords(products): stat = 'mean' output = PreprocessorFile() output_products = {'': {stat: output}} kwargs = { 'statistics': [stat], 'span': 'full', 'output_products': output_products, 'keep_input_datasets': False, } msg = (...
Python
nomic_cornstack_python_v1
import serial import time import struct import numpy as np comment bluetooth comm port set port = string COM4 comment baud rate of UART set baud = 9600 set ser = call Serial port baud EIGHTBITS PARITY_NONE STOPBITS_ONE timeout=1 if call isOpen begin print name + string is open print string format time time string %a, %...
import serial import time import struct import numpy as np port = "COM4" # bluetooth comm port baud = 9600 # baud rate of UART ser = serial.Serial(port, baud, serial.EIGHTBITS, serial.PARITY_NONE, serial.STOPBITS_ONE, timeout=1) if ser.isOpen(): print(ser.name + " is open") print(time.strftime("%a, %d %...
Python
zaydzuhri_stack_edu_python
function get self request begin comment Retrieve all reactions if any set reactions = all comment Return reactions in a list set list_reactions = list comment Format reaction for reaction in reactions begin set formatted_reaction = call format_response reaction comment Append reaction to list of reactions append list_...
def get(self, request): # Retrieve all reactions if any reactions = UserReaction.objects.all() # Return reactions in a list list_reactions = [] # Format reaction for reaction in reactions: formatted_reaction = format_response(reaction) # Append ...
Python
nomic_cornstack_python_v1
import requests from bs4 import BeautifulSoup import json function get_html begin set url = string https://www.bbc.com/news set r = get requests url return text end function function get_news begin set html = call get_html set soup = call BeautifulSoup html string html.parser set news = find all soup string div class_=...
import requests from bs4 import BeautifulSoup import json def get_html(): url = 'https://www.bbc.com/news' r = requests.get(url) return r.text def get_news(): html = get_html() soup = BeautifulSoup(html, 'html.parser') news = soup.find_all('div', class_='gs-c-promo') return news def mai...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment coding = utf-8 function square l begin set l = sorted l return l at - 1 - l at 0 + l at - 2 - l at 1 end function comment 正方形四条边的长度一样,最长的边最后一定会变得和最短的边一样长 if __name__ == string __main__ begin set l = list map int split input print call square l end
#!/usr/bin/env python3 #coding = utf-8 def square(l: [int]) -> int: l = sorted(l) return l[-1] - l[0] + l[-2] -l[1] # 正方形四条边的长度一样,最长的边最后一定会变得和最短的边一样长 if __name__ == "__main__": l = list(map(int, input().split())) print(square(l))
Python
zaydzuhri_stack_edu_python
function available_results self begin set out = list for i in range length self begin append out call _get_result i end return out end function
def available_results(self): out = [] for i in range(len(self)): out.append(self._get_result(i)) return out
Python
nomic_cornstack_python_v1
import os class Node begin function __init__ self name option layer parent is_head=false begin set name = name set option = option set layer = layer set parent = parent set is_head = is_head set children = list set exec_nodes = list end function function force_add_on_layer self parent_ident name_ident layer option be...
import os class Node: def __init__(self, name, option, layer, parent, is_head=False): self.name = name self.option = option self.layer = layer self.parent = parent self.is_head = is_head self.children = [] self.exec_nodes = [] def force_add_on_layer(sel...
Python
zaydzuhri_stack_edu_python