code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function g s
begin
set i = 0
set new_s = string
while i < length s - 1
begin
set new_s = new_s + s at i + 1
set i = i + 1
end
return new_s
end function | def g(s):
i =0
new_s =''
while i < len(s)-1:
new_s = new_s+s[i+1]
i = i+1
return new_s
| Python | zaydzuhri_stack_edu_python |
function passed_muons det_coord direction voxel_list size=1
begin
set mass_passed = 0.0
comment x0,y0,z0 = detector
if size < 2
begin
set direction = tuple direction 1
end
for tuple *vox mass in voxel_list
begin
comment vox -= det_coord
if call line_x_cube vox size / 2 det_coord direction
begin
comment print(vox)
set m... | def passed_muons(det_coord, direction, voxel_list, size=1):
mass_passed = 0.0
#x0,y0,z0 = detector
if np.array(direction).size<2: direction = (direction,1)
for *vox, mass in voxel_list:
#vox -= det_coord
if line_x_cube(vox, size/2, det_coord, direction):
#print(vox)
... | Python | nomic_cornstack_python_v1 |
function create_friends user existing_friends
begin
comment ToDo Add error handling
set bulk_insert = list
set existing_friend_ids = list
for friend in existing_friends
begin
append bulk_insert call FriendData uid=user friend_id=user
append bulk_insert call FriendData uid=user friend_id=user
append existing_friend_id... | def create_friends(user, existing_friends):
#ToDo Add error handling
bulk_insert = []
existing_friend_ids = []
for friend in existing_friends:
bulk_insert.append(pm.FriendData(uid=user, friend_id=friend.user))
bulk_insert.append(pm.FriendData(uid=friend.user, friend_id=user))
exi... | Python | nomic_cornstack_python_v1 |
function parameter_combinations cls
begin
return call generate_parameter_combinations dict string proportion list 0.1 0.25 0.5 0.75 1.0 1.5 2.0 ; string n_clusters list 5 10 15 ; string noise_th list 1 3
end function | def parameter_combinations(cls):
return cls.generate_parameter_combinations({'proportion': [0.1, 0.25, 0.5, 0.75, 1.0, 1.5, 2.0],
'n_clusters': [5, 10, 15],
'noise_th': [1, 3]}) | Python | nomic_cornstack_python_v1 |
comment Description:
comment Given an array (arr) as an argument complete the function countSmileys
comment that should return the total number of smiling faces.
comment Rules for a smiling face:
comment -Each smiley face must contain a valid pair of eyes. Eyes can be marked as : or ;
comment -A smiley face can have a ... | # Description:
# Given an array (arr) as an argument complete the function countSmileys
# that should return the total number of smiling faces.
# Rules for a smiling face:
# -Each smiley face must contain a valid pair of eyes. Eyes can be marked as : or ;
# -A smiley face can have a nose but it does not have to. Valid... | Python | zaydzuhri_stack_edu_python |
import socket
import sys
import thread
from _socket import SOL_SOCKET , SO_REUSEADDR
import config
import json_utils
import web_app_client_handler
import controller
set address = local_address
set port = 10002
set num_of_connection = 5
class WebServer
begin
function __init__ self
begin
set server_socket = call socket A... | import socket
import sys
import thread
from _socket import SOL_SOCKET, SO_REUSEADDR
import config
import json_utils
import web_app_client_handler
import controller
address = config.local_address
port = 10002
num_of_connection = 5
class WebServer:
def __init__(self):
self.server_socket = socket.socket(so... | Python | zaydzuhri_stack_edu_python |
string Find the uncommon letters and look around for a clue ASNWER: grammaphobia
import random
set CLUE_1 = string LOOKAROUNDEVERYLETTER
set CLUE_2 = string fearofalphabetletters
set UNIQUE_LETTER_SET = set CLUE_1
set ASCII_CHAR_RANGE = tuple 32 126
set CHAR_DUMP_SIZE_RANGE = tuple 128 256
function generate
begin
set g... | '''
Find the uncommon letters and look around for a clue
ASNWER: grammaphobia
'''
import random
CLUE_1 = 'LOOKAROUNDEVERYLETTER'
CLUE_2 = 'fearofalphabetletters'
UNIQUE_LETTER_SET = set(CLUE_1)
ASCII_CHAR_RANGE = (32, 126)
CHAR_DUMP_SIZE_RANGE = (128, 256)
def generate():
gen_string = ''
for let1, let2 in zip... | Python | zaydzuhri_stack_edu_python |
async function scrape_submissions self
begin
set subreddit_origin = await call subreddit subreddit
set submission_count = 0
async_for submission in call new limit=limit
begin
if call contains id
begin
continue
end
add memory id
comment Parse Submission
set submission = call parse_submission submission
comment Save in P... | async def scrape_submissions(self):
subreddit_origin = await self.reddit.subreddit(self.subreddit)
submission_count = 0
async for submission in subreddit_origin.new(limit=self.limit):
if self.memory.contains(submission.id):
continue
self.memory.add(submi... | Python | nomic_cornstack_python_v1 |
function get_subprocess_output command log raise_on_empty_output=true
begin
return call subprocess_output command raise_on_empty_output
end function | def get_subprocess_output(command, log, raise_on_empty_output=True):
return subprocess_output(command, raise_on_empty_output) | Python | nomic_cornstack_python_v1 |
function txpool_status self
begin
string https://github.com/ethereum/go-ethereum/wiki/Management-APIs#txpool_status :rtype: dict
set result = yield from call rpc_call string txpool_status
return dictionary comprehension k : call hex_to_dec v for tuple k v in items result
end function | def txpool_status(self):
"""https://github.com/ethereum/go-ethereum/wiki/Management-APIs#txpool_status
:rtype: dict
"""
result = yield from self.rpc_call('txpool_status')
return {k: hex_to_dec(v) for k, v in result.items()} | Python | jtatman_500k |
function print_recursive self indents
begin
set ind = string
set output = indents * ind + name
print output
for i in children
begin
call print_recursive indents + 1
end
end function | def print_recursive(self, indents):
ind = "\t"
output = indents * ind + self.name
print(output)
for i in self.children:
i.print_recursive(indents+1) | Python | nomic_cornstack_python_v1 |
function startElement self *args
begin
return call XMLOutputStream_startElement self *args
end function | def startElement(self, *args):
return _libsbml.XMLOutputStream_startElement(self, *args) | Python | nomic_cornstack_python_v1 |
function post_container self container headers=none query=none cdn=false body=none
begin
set path = call _container_path container
return call _request string POST path body or string headers query=query cdn=cdn
end function | def post_container(self, container, headers=None, query=None, cdn=False,
body=None):
path = self._container_path(container)
return self._request(
'POST', path, body or '', headers, query=query, cdn=cdn) | Python | nomic_cornstack_python_v1 |
function create_variables self input_spaces action_space
begin
pass
end function | def create_variables(self, input_spaces, action_space):
pass | Python | nomic_cornstack_python_v1 |
from copy import deepcopy
import sys
import re
from itertools import chain
import re
import sys
import itertools
from copy import deepcopy
set f1 = input string which data file do you want to use?
comment try:
set f = open f1
set data = list list
comment make a dictionary which will have capital A-Z as keys and either... | from copy import deepcopy
import sys
import re
from itertools import chain
import re
import sys
import itertools
from copy import deepcopy
f1=input('which data file do you want to use? ')
##try:
f = open(f1)
data=[[]]
#make a dictionary which will have capital A-Z as keys and either of line enders as valu... | Python | zaydzuhri_stack_edu_python |
function getBestPath self
begin
set bestProbability = 0.0
set bestPath = none
for path in call getMatchedPaths
begin
set pathProbability = call computeProbability path
if pathProbability > bestProbability
begin
set bestProbability = pathProbability
set bestPath = path
end
end
return bestPath
end function | def getBestPath (self):
bestProbability = 0.0
bestPath = None
for path in self.getMatchedPaths ():
pathProbability = self.computeProbability (path)
if pathProbability > bestProbability:
bestProbability = pathProbability
bestPath = p... | Python | nomic_cornstack_python_v1 |
function fetch_complete_courses job_config data_bucket data_dir=string morf-data/ n_train=1
begin
set complete_courses = list
for course in call fetch_courses job_config data_bucket data_dir
begin
set training_sessions = call fetch_sessions job_config data_bucket data_dir course fetch_holdout_session_only=false
set te... | def fetch_complete_courses(job_config, data_bucket, data_dir ="morf-data/", n_train=1):
complete_courses = []
for course in fetch_courses(job_config, data_bucket, data_dir):
training_sessions = fetch_sessions(job_config, data_bucket, data_dir, course, fetch_holdout_session_only=False)
testing_se... | Python | nomic_cornstack_python_v1 |
function primes_sieve2 limit
begin
comment Initialize the primality list
set a = list true * limit
set a at 0 = false
set a at 1 = false
for tuple i isprime in enumerate a
begin
if isprime
begin
yield i
comment Mark factors non-prime
for n in call xrange i * i limit i
begin
set a at n = false
end
end
end
end function
i... | def primes_sieve2(limit):
a = [True] * limit # Initialize the primality list
a[0] = a[1] = False
for (i, isprime) in enumerate(a):
if isprime:
yield i
for n in xrange(i*i, limit, i): # Mark factors non-prime
a[n] = False
if __nam... | Python | zaydzuhri_stack_edu_python |
function subs input_string
begin
set length = length input_string
return list comprehension input_string at slice i : j + 1 : for i in call xrange length for j in call xrange i length
end function | def subs(input_string):
length = len(input_string)
return [input_string[i:j+1] for i in xrange(length) for j in xrange(i,length)] | Python | nomic_cornstack_python_v1 |
if i % 2 == 0
begin
print string %s是偶数 % i
end
else
begin
print string %s是奇数 % i
end | if i%2 == 0:
print("%s是偶数"%i)
else:
print("%s是奇数"%i)
| Python | zaydzuhri_stack_edu_python |
comment Largest palindrom product
set n = 3
set s = string
set f = false
for i in range n
begin
set s = s + string 9
end
set s = integer s
for i in range s + 1 1 - 1
begin
for j in range s + 1 - i 2 - 1
begin
set x = string i * j
if x at slice : : == x at slice : : - 1
begin
print i string X j
set f = true
break
... | #Largest palindrom product
n=3
s=""
f=False
for i in range (n):
s=s+'9'
s=int(s)
for i in range (s+1,1,-1):
for j in range (s+1-i,2,-1):
x=str(i*j)
if(x[:]==x[::-1]):
print(i,"X",j)
f=True
break
if(f):
break | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
from __future__ import division
import sys
import re
import os
import argparse
from util import mkdir
function read_params args
begin
set parser = call ArgumentParser description=string convert uc to otutab | v1.0 at 2015/09/16 by liangzb
call add_argument string -i string --infile dest=str... | #!/usr/bin/env python
from __future__ import division
import sys
import re
import os
import argparse
from util import mkdir
def read_params(args):
parser = argparse.ArgumentParser(description='convert uc to otutab | v1.0 at 2015/09/16 by liangzb')
parser.add_argument('-i', '--infile', dest='infile', metavar='... | Python | zaydzuhri_stack_edu_python |
function predict self images batch_size=1
begin
set predictions = list
for image in as type images string float
begin
set filtered_image = call apply_filter image
set tuple _ pred = call threshold as type filtered_image string uint8 0 1 THRESH_BINARY + THRESH_OTSU
append predictions pred
end
return reshape np predicti... | def predict(self, images, batch_size=1):
predictions = []
for image in images.astype("float"):
filtered_image = self.apply_filter(image)
_, pred = cv2.threshold(filtered_image.astype('uint8'), 0, 1, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
predictions.append(pred)
... | Python | nomic_cornstack_python_v1 |
function __str__ self
begin
if _stringified
begin
return _stringified
end
set _stringified = call _stringify_yamlpath_segments unescaped separator
return _stringified
end function | def __str__(self) -> str:
if self._stringified:
return self._stringified
self._stringified = YAMLPath._stringify_yamlpath_segments(
self.unescaped, self.separator)
return self._stringified | Python | nomic_cornstack_python_v1 |
import random
from candidate import Candidate
from evolution_chamber_util import swap_str_character
function evaluate_candidate candidate target
begin
for i in range 0 length target
begin
if word at i == target at i
begin
set truth_list at i = 1
end
else
begin
set truth_list at i = 0
end
end
return candidate
end functi... | import random
from candidate import Candidate
from evolution_chamber_util import swap_str_character
def evaluate_candidate(candidate: Candidate, target: str):
for i in range(0, len(target)):
if candidate.word[i] == target[i]:
candidate.truth_list[i] = 1
else:
candidate.tru... | Python | zaydzuhri_stack_edu_python |
function save_file filename data
begin
call savetxt filename array data fmt=string %.0f delimiter=string ,
end function | def save_file(filename,data):
np.savetxt(filename, np.array(data), fmt="%.0f", delimiter=",") | Python | nomic_cornstack_python_v1 |
function jwks self
begin
return get pulumi self string jwks
end function | def jwks(self) -> Optional[str]:
return pulumi.get(self, "jwks") | Python | nomic_cornstack_python_v1 |
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
set PATH_DB = string database.sqlite3
class Repository
begin
function __init__ self path_db
begin
set engine = call create_engine string sqlite:/// { path_db } ?check_same_thread=False
ca... | from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
PATH_DB = 'database.sqlite3'
class Repository:
def __init__(self, path_db):
self.engine = create_engine(f'sqlite:///{path_db}?check_same_thread=False')
self.create_... | Python | zaydzuhri_stack_edu_python |
function _get_format_from_document self token document
begin
set tuple code html = next call _format_lines list tuple token string dummy
call setHtml html
return call charFormat
end function | def _get_format_from_document(self, token, document):
code, html = next(self._formatter._format_lines([(token, u'dummy')]))
self._document.setHtml(html)
return QtGui.QTextCursor(self._document).charFormat() | Python | nomic_cornstack_python_v1 |
import scrapy
from items import TutorialItem
class QuoteSpider extends Spider
begin
set name = string quote
set pageNumber = 2
comment def start_requests(self):
set start_urls = list string http://quotes.toscrape.com/page/1/
comment 'http://quotes.toscrape.com/page/1/',
comment 'http://quotes.toscrape.com/page/2/',
com... | import scrapy
from ..items import TutorialItem
class QuoteSpider(scrapy.Spider):
name = 'quote'
pageNumber = 2
# def start_requests(self):
start_urls = [
'http://quotes.toscrape.com/page/1/'
# 'http://quotes.toscrape.com/page/1/',
# 'http://quotes.toscrape.com/page/2/',
]
... | Python | zaydzuhri_stack_edu_python |
function __check_ssh self
begin
set sfcs = sshTunnelDict at string target_ip
set cmd = string ps aux | grep ssh | awk '{print $20}'
set result = popen cmd shell=true stdout=PIPE stderr=PIPE
set tuple stdout stderr = communicate result
if sfcs not in decode stdout
begin
return false
end
else
begin
return true
end
end fu... | def __check_ssh(self):
sfcs = self.sshTunnelDict["target_ip"]
cmd = "ps aux | grep ssh | awk '{print $20}'"
result = subprocess.Popen(cmd,
shell= True,
stdout=subprocess.PIPE,
stderr=subp... | Python | nomic_cornstack_python_v1 |
for _ in range n
begin
set tuple t k = map int split input
if t == 1
begin
for i in range BITS
begin
if k ? 1 ? i == 0
begin
continue
end
if basis at i == 0
begin
set bs = list comprehension v for v in basis if v != 0
for p in pretty at slice : :
begin
append pretty p ? k
end
sort pretty
set basis at i = k
break
end... | for _ in range(n):
t, k = map(int, input().split())
if t == 1:
for i in range(BITS):
if (k & (1 << i)) == 0:
continue
if basis[i] == 0:
bs = [v for v in basis if v != 0]
for p in pretty[:]:
pretty.append(p ^ k)
... | Python | zaydzuhri_stack_edu_python |
import sys , os
import requests
from html.parser import HTMLParser
from queue import Queue
import uuid
from stack import Stack
from collections import OrderedDict
from pprint import pprint
append path join path directory name path __file__ string ..
from tree_ds import *
class HtmlNodeInfo
begin
function __init__ self ... | import sys, os
import requests
from html.parser import HTMLParser
from queue import Queue
import uuid
from stack import Stack
from collections import OrderedDict
from pprint import pprint
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from tree_ds import *
class HtmlNodeInfo:
def __init__(self, k... | Python | zaydzuhri_stack_edu_python |
function getGCost self
begin
return __gCost
end function | def getGCost(self):
return self.__gCost | Python | nomic_cornstack_python_v1 |
function outputMsg self jdata node values forward
begin
comment Tiene que ver con los contextos
print values
set queryResult = get jdata string queryResult
if forward
begin
set response = call makeWebhookResult jdata
if response at string payload at string returnCode == string 0
begin
set msgString = msgAns
set pattern... | def outputMsg(self, jdata, node, values, forward):
# Tiene que ver con los contextos
print(values)
queryResult = jdata.get("queryResult")
if forward:
response = self.makeWebhookResult(jdata)
if response["payload"]["returnCode"] == "0":
msgString = ... | Python | nomic_cornstack_python_v1 |
string This module contains the MainScene class that controls the main scene of the game (the map scene).
import os
import sys
import random
import datetime
import math
import ctypes
import pygame
from pygame import font
import OBJECTS as OBJ
import GENERAL as GEN
import AREA
class MainScene
begin
string This class con... | """ This module contains the MainScene class
that controls the main scene of the game
(the map scene). """
import os
import sys
import random
import datetime
import math
import ctypes
import pygame
from pygame import font
import OBJECTS as OBJ
import GENERAL as GEN
import AREA
class ... | Python | zaydzuhri_stack_edu_python |
comment encoding: utf-8
class Solution
begin
function isValid self s
begin
string :type s: str :rtype: bool
if length s % 2 == 1
begin
return false
end
set s_list = list
set s_dict = dict string ) string ( ; string } string { ; string ] string [
for i in range length s
begin
if s at i in string ({[
begin
append s_list... | # encoding: utf-8
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s) % 2 == 1:
return False
s_list = []
s_dict = {')': '(', '}': '{', ']': '['}
for i in range(len(s)):
if s[i] in '({[':
... | Python | zaydzuhri_stack_edu_python |
function correct_tail body tail
begin
return if expression body at - 1 == tail then true else false
end function | def correct_tail(body, tail):
return True if body[-1]==tail else False | Python | zaydzuhri_stack_edu_python |
import requests
import enum
import time
import datetime
from util import log
class ServerState extends Enum
begin
set Running = call auto
set Crashed = call auto
set Busy = call auto
end class
set CONFIG_DB_ADDR = string
function checkstates
begin
set t = now
set res = get requests string { CONFIG_DB_ADDR } /_all_docs... | import requests
import enum
import time
import datetime
from util import log
class ServerState(enum.Enum):
Running = enum.auto()
Crashed = enum.auto()
Busy = enum.auto()
CONFIG_DB_ADDR = ""
def checkstates():
t = datetime.datetime.now()
res = requests.get(f"{CONFIG_DB_ADDR}/_all_docs")
con... | Python | zaydzuhri_stack_edu_python |
function nested_sum l
begin
set total = 0
for lst in l
begin
set total = total + sum lst
end
return total
end function
function cumsum l
begin
set total = 0
set retList = list
for num in l
begin
append retList num + total
set total = total + num
end
return retList
end function
function middle lst
begin
return lst at s... | def nested_sum(l):
total = 0
for lst in l:
total += sum(lst)
return total
def cumsum(l):
total=0
retList = []
for num in l:
retList.append(num + total)
total += num
return retList
def middle(lst):
return lst[1:-1]
def chop(lst):
lst.pop()
del lst[0]
de... | Python | zaydzuhri_stack_edu_python |
function horisontal_check board
begin
for row in board
begin
set row = list comprehension sign for sign in row if sign != string * and sign != string
if length row != length set row
begin
return false
end
end
return true
end function | def horisontal_check(board: List[str]) -> bool:
for row in board:
row = [sign for sign in row
if sign != '*' and sign != ' ']
if len(row) != len(set(row)):
return False
return True | Python | nomic_cornstack_python_v1 |
function basic_config self logger_name=string logfile_name=string log logfile_path=string logs file_level=INFO console_level=CRITICAL
begin
set logger_name = logger_name
set logfile_name = logfile_name
set logifle_path = logfile_path
set file_level = file_level
set console_level = console_level
end function | def basic_config(self, logger_name= '', logfile_name= 'log', logfile_path= 'logs',
file_level= logging.INFO, console_level= logging.CRITICAL):
self.logger_name = logger_name
self.logfile_name= logfile_name
self.logifle_path= logfile_path
self.file_level= file_lev... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import sys
from collections import deque , defaultdict
from math import sqrt , factorial , gcd , ceil
comment def input(): return sys.stdin.readline()[:-1] # warning not \n
comment def input(): return sys.stdin.buffer.readline().strip() # warning bytes
comment def input(): return sys.stdin... | # -*- coding: utf-8 -*-
import sys
from collections import deque, defaultdict
from math import sqrt, factorial, gcd, ceil
# def input(): return sys.stdin.readline()[:-1] # warning not \n
# def input(): return sys.stdin.buffer.readline().strip() # warning bytes
# def input(): return sys.stdin.buffer.readline().decode('u... | Python | zaydzuhri_stack_edu_python |
function test_model_manager_will_return_same_instance_when_instantiated_many_times self
begin
comment arrange, act
comment instantiating the model manager class twice
set first_model_manager = call ModelManager
set second_model_manager = call ModelManager
comment loading the MLModel objects from configuration
call load... | def test_model_manager_will_return_same_instance_when_instantiated_many_times(self):
# arrange, act
# instantiating the model manager class twice
first_model_manager = ModelManager()
second_model_manager = ModelManager()
# loading the MLModel objects from configuration
f... | Python | nomic_cornstack_python_v1 |
function make_specialfields unique_id id1 id2 size fieldtext hgf_field help_text sbmfield config typ inst
begin
set specialfields = config at string default at string specialfields
if string specialfields in keys config at inst
begin
if hgf_field in keys config at inst at string specialfields
begin
set specialfields = ... | def make_specialfields(unique_id,id1,id2,size,fieldtext,hgf_field,help_text,sbmfield,config,typ,inst):
specialfields = config["default"]["specialfields"]
if "specialfields" in config[inst].keys():
if hgf_field in config[inst]["specialfields"].keys():
specialfields = config[inst]["specialfields"]
else:
warn... | Python | nomic_cornstack_python_v1 |
function is_protected cls key **kwargs
begin
set setting = call get_setting_definition key keyword kwargs
return get setting string protected false
end function | def is_protected(cls, key, **kwargs):
setting = cls.get_setting_definition(key, **kwargs)
return setting.get('protected', False) | Python | nomic_cornstack_python_v1 |
function search A v
begin
for i in call xrange length A
begin
if A at i == v
begin
return i
end
end
return none
end function
set A = list 1 2 3 4
set v = 5 | def search(A, v):
for i in xrange(len(A)):
if A[i] == v:
return i
return None
A = [1, 2, 3, 4]
v = 5 | Python | zaydzuhri_stack_edu_python |
function create_token_type_ids_from_sequences self token_ids_0 token_ids_1=none
begin
set sep = list sep_token_id
set cls = list cls_token_id
if token_ids_1 is none
begin
return length cls + token_ids_0 + sep * list 0
end
return length cls + token_ids_0 + sep * list 0 + length token_ids_1 + sep * list 1
end function | def create_token_type_ids_from_sequences(self, token_ids_0, token_ids_1=None):
sep = [self.sep_token_id]
cls = [self.cls_token_id]
if token_ids_1 is None:
return len(cls + token_ids_0 + sep) * [0]
return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1] | Python | nomic_cornstack_python_v1 |
function test_two_lc
begin
set tuple rv out = call getstatusoutput string { prg } { two_lines } { call line_flag } { call character_flag }
assert rv == 0
assert right strip out == string 2 4 ./inputs/two.txt
end function | def test_two_lc():
rv, out = getstatusoutput(f'{prg} {two_lines} {line_flag()} {character_flag()}')
assert rv == 0
assert out.rstrip() == ' 2 4 ./inputs/two.txt' | Python | nomic_cornstack_python_v1 |
from src import BaseCrawler
from bs4 import BeautifulSoup
import requests
from src.CrawlerEnums import BaseEnums
from uuid import uuid4
import json
class BaseCrawlerImpl extends BaseCrawler
begin
function __init__ self
begin
set _state_wise_serial_map = dict
set _key_check_obj = none
set _processed_states = list
set ... | from src import BaseCrawler
from bs4 import BeautifulSoup
import requests
from src.CrawlerEnums import BaseEnums
from uuid import uuid4
import json
class BaseCrawlerImpl(BaseCrawler):
def __init__(self):
self._state_wise_serial_map = {}
self._key_check_obj = None
self._processed_states = [... | Python | zaydzuhri_stack_edu_python |
string Shared classes used between different steps in lexer and parser
class TokenMetadata
begin
string Holds meta data for each token such as line number and character number
set line_range = none
set char_range = none
decorator staticmethod
function initialized obj
begin
return line_range is not none and char_range i... | """
Shared classes used between different steps in lexer and parser
"""
class TokenMetadata:
"""
Holds meta data for each token such as line number and character number
"""
line_range = None
char_range = None
@staticmethod
def initialized(obj):
return obj.line_range is not None an... | Python | zaydzuhri_stack_edu_python |
function bitstr_to_int a
begin
return integer a 2
end function | def bitstr_to_int(a):
return int(a, 2) | Python | nomic_cornstack_python_v1 |
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import cm
import scipy.cluster.hierarchy as sch
from scipy.spatial.distance import cdist
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_samples , silhouette_score
comment Displays an elbow... | import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import cm
import scipy.cluster.hierarchy as sch
from scipy.spatial.distance import cdist
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_samples, silhouette_score
# Displays an e... | Python | zaydzuhri_stack_edu_python |
comment Task1
print string Task_1
function avg num1 num2
begin
print string avg: end=string
return num1 + num2 / 2
end function
print call avg 15 23
print call avg 2 15
print call avg 88 13
comment Task3
print string Task_3
function cube num
begin
print string num cube: end=string
return num ^ 3
end function
print call... | #Task1
print("Task_1")
def avg(num1,num2):
print("avg: ",end="")
return (num1+num2)/2
print(avg(15, 23))
print(avg(2, 15))
print(avg(88, 13))
#Task3
print("Task_3")
def cube(num):
print("num cube: ",end="")
return num**3
print(cube(9))
print(cube(2))
print(cube(15))
#Task4
print("Task_4")
def m(num1,n... | Python | zaydzuhri_stack_edu_python |
import math
function count_change denominations total
begin
set dp = list comprehension list comprehension - 1 for x in range total + 1 for y in range length denominations
set res = call check_coin dp denominations total 0
return if expression res == decimal string inf then - 1 else res
end function
function check_coin... | import math
def count_change(denominations, total):
dp = [[-1 for x in range(total+1)] for y in range(len(denominations))]
res = check_coin(dp, denominations, total, 0)
return -1 if res == float('inf') else res
def check_coin(dp, denominations, total, index):
if total == 0:
return 0
... | Python | zaydzuhri_stack_edu_python |
comment Input handler for QueueBot
comment Created by Ghodamus (Mark), January 2017
comment User guide in Google Drive: https://goo.gl/3Xv8ib
comment This class creates an object that parses and responds to messages from QueueBot.
comment Most of the processing work is done by a track_queue object from QueueTracker.
im... | # Input handler for QueueBot
# Created by Ghodamus (Mark), January 2017
# User guide in Google Drive: https://goo.gl/3Xv8ib
# This class creates an object that parses and responds to messages from QueueBot.
# Most of the processing work is done by a track_queue object from QueueTracker.
import discord
class handler(... | Python | zaydzuhri_stack_edu_python |
function insertRow self row
begin
return call insertRow row
end function | def insertRow(self, row):
return super(InsertCursor, self).insertRow(row) | Python | nomic_cornstack_python_v1 |
function login
begin
set auth_data = authorization
if not auth_data or not username or not password
begin
return call make_response string incorrect login detail1 401 dict string WWW-Authenticate string Basic realm="Login required"
end
set user = first filter by query email=username
if not user
begin
return call make_r... | def login():
auth_data = request.authorization
if not auth_data or not auth_data.username or not auth_data.password:
return make_response(
"incorrect login detail1",
401,
{"WWW-Authenticate": 'Basic realm="Login required"'},
)
user = users.query.fi... | Python | nomic_cornstack_python_v1 |
string Times are expressed in minutes. CSV file format: label[str],category[str],flag[bool],minutes[int/float] label1,category1,true,minutes1 label2,category1,false,minutes2 ...,...
import pygal
from pygal.style import NeonStyle as Style
from daily_activity_time.activity import Activity , ActivityList
from daily_activi... | """
Times are expressed in minutes.
CSV file format:
label[str],category[str],flag[bool],minutes[int/float]
label1,category1,true,minutes1
label2,category1,false,minutes2
...,...
"""
import pygal
from pygal.style import NeonStyle as Style
from daily_activity_time.activity import Activity, ActivityList
from daily_act... | Python | zaydzuhri_stack_edu_python |
comment USAGE
comment python classify_image.py --image images/soccer_ball.jpg --model vgg16
comment The text version of the tutorial can be found at the following address
comment https://www.pyimagesearch.com/2017/03/20/imagenet-vggnet-resnet-inception-xception-keras/
comment It is highly recommended to read this tutor... | # USAGE
# python classify_image.py --image images/soccer_ball.jpg --model vgg16
# The text version of the tutorial can be found at the following address
# https://www.pyimagesearch.com/2017/03/20/imagenet-vggnet-resnet-inception-xception-keras/
# It is highly recommended to read this tutorial prior to using the video ... | Python | zaydzuhri_stack_edu_python |
function test_factorial_array_none_a2 self
begin
comment This version is expected to pass.
call factorial inparray1a maxlen=testmaxlen
comment This is the actual test.
with assert raises TypeError
begin
call factorial inparray1b maxlen=string a
end
end function | def test_factorial_array_none_a2(self):
# This version is expected to pass.
arrayfunc.factorial(self.inparray1a, maxlen=self.testmaxlen)
# This is the actual test.
with self.assertRaises(TypeError):
arrayfunc.factorial(self.inparray1b, maxlen='a') | Python | nomic_cornstack_python_v1 |
function connect
begin
set mailBox = call IMAP4_SSL string imap.gmail.com
if TESTING
begin
call login string sapphirephoenix call getpass
end
else
begin
call login call raw_input string Username: call getpass
end
comment INBOX [Gmail]/All Mail
set tuple result data = select mailBox string INBOX true
end function | def connect():
mailBox = IMAP4_SSL('imap.gmail.com')
if TESTING:
mailBox.login("sapphirephoenix", getpass.getpass())
else:
mailBox.login(raw_input("\nUsername: "), getpass.getpass())
result, data = mailBox.select('INBOX', True) # INBOX [Gmail]/All Mail
| Python | nomic_cornstack_python_v1 |
function extract obj arr key
begin
if is instance obj dict
begin
for tuple k v in items obj
begin
if is instance v tuple dict list
begin
extract v arr key
end
else
if k == key
begin
append arr v
end
end
end
else
if is instance obj list
begin
for item in obj
begin
if string token in item
begin
set token = dumps item at ... | def extract(obj, arr, key):
if isinstance(obj, dict):
for k, v in obj.items():
if isinstance(v, (dict, list)):
extract(v, arr, key)
elif k == key:
arr.append(v)
elif isinstance(obj, list):
for item in obj:
... | Python | nomic_cornstack_python_v1 |
function node_act_diffusion self agent_num
begin
set utility = array list list 1 1 list 0 2
comment Get adjacent actions
set neighbors = call adjacent_nodes agent_num
set n_policies = call adjacent_actions 0
set temp = list 0 0
for p in n_policies
begin
set temp at 0 = temp at 0 + utility at 1 at p
set temp at 1 = temp... | def node_act_diffusion(self, agent_num):
utility = np.array([[1,1],
[0,2]])
# Get adjacent actions
neighbors = self.adjacent_nodes(agent_num)
n_policies = self.adjacent_actions(0)
temp = [0,0]
for p in n_policies:
temp[0] += utili... | Python | nomic_cornstack_python_v1 |
function createExtLegend self
begin
if hasLegend == true and selectedLegendPosition == 4
begin
return string <div id="extLgnd"></div>
end
else
begin
return string
end
end function | def createExtLegend(self):
if self.outVars.hasLegend == True and self.outVars.selectedLegendPosition == 4:
return """ <div id="extLgnd"></div>"""
else:
return "" | Python | nomic_cornstack_python_v1 |
import csv
import re
from time import *
from os import path
from datetime import date
function write_execution_time_log github_repo method_name execution_time
begin
set workspace = split github_repo string / at 1 + string /statistics/
if exists path workspace + string execution_time_log.csv
begin
set timeLogCsvFile = o... | import csv
import re
from time import *
from os import path
from datetime import date
def write_execution_time_log(github_repo, method_name, execution_time):
workspace = github_repo.split("/")[1] + '/statistics/'
if path.exists(workspace + 'execution_time_log.csv'):
timeLogCsvFile = open(workspace + 'e... | Python | zaydzuhri_stack_edu_python |
function move maze node
begin
set output_has_poke = 0
set poks = list
comment print(node.state.pok_locations)
if ori == East
begin
if not y + 1 >= call __len__
begin
if not is_wall
begin
if has_poke
begin
if tuple x y + 1 not in pok_locations
begin
set output_has_poke = 1
set poks = list tuple x y + 1
end
end
comment ... | def move(maze, node):
output_has_poke = 0
poks = []
# print(node.state.pok_locations)
if node.state.ori == Direction.Direction.East:
if not node.state.cell.y + 1 >= maze.grid.__len__():
if not maze.grid[node.state.cell.x][node.state.cell.y + 1].is_wall:
... | Python | nomic_cornstack_python_v1 |
function fibonacci n
begin
if n < 0
begin
print string Error: Input value should be non-negative.
return
end
if n == 0
begin
return 0
end
else
if n == 1
begin
return 1
end
else
begin
set tuple a b = tuple 0 1
for _ in range 2 n + 1
begin
set tuple a b = tuple b a + b
end
return b
end
end function
comment Print the firs... | def fibonacci(n):
if n < 0:
print("Error: Input value should be non-negative.")
return
if n == 0:
return 0
elif n == 1:
return 1
else:
a, b = 0, 1
for _ in range(2, n+1):
a, b = b, a + b
return b
# Print the first 20 Fibonacci numbers... | Python | jtatman_500k |
function GetAverageResidual self
begin
return call itkSLICImageFilterIUS3IULL3_GetAverageResidual self
end function | def GetAverageResidual(self) -> "double":
return _itkSLICImageFilterPython.itkSLICImageFilterIUS3IULL3_GetAverageResidual(self) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string XHR資料: XMLHttpRequest 使用網頁的情況下更新資料 使用函式:(自定函式) convertDate:民國年份日期字串至轉為西元年字串 def convertDate(date): str1=str(date) yearst=str1[:3] ryear=str(int(yearst)+1911) findate=ryear+str1[4:6]+str1[7:9] return findate 查股票 pip install twstock
import twstock
comment 股票代號 S要大寫
set stock = call St... | # -*- coding: utf-8 -*-
"""
XHR資料:
XMLHttpRequest
使用網頁的情況下更新資料
使用函式:(自定函式)
convertDate:民國年份日期字串至轉為西元年字串
def convertDate(date):
str1=str(date)
yearst=str1[:3]
ryear=str(int(yearst)+1911)
findate=ryear+str1[4:6]+str1[7:9]
return findate
查股票 pip install twstock
"""
import twstock
st... | Python | zaydzuhri_stack_edu_python |
function DM_from_qcfile fname
begin
import CCParser as cc
set data = call Parser fname software=string qchem to_console=false
comment only closed shell now!!!
set dm = call DM call get_last call get_last
return dm
end function | def DM_from_qcfile(fname):
import CCParser as cc
data=cc.Parser(fname,software="qchem",to_console=False)
dm=DM(data.results.P_alpha.get_last(),data.results.P_alpha.get_last())#only closed shell now!!!
return dm | Python | nomic_cornstack_python_v1 |
function add_node_disk cmd
begin
set exaconf = call read_exaconf exaconf
set devices = if expression devices then list comprehension strip d for d in split devices string , if strip d != string else none
set drives = if expression drives then list comprehension strip d for d in split drives string , if strip d != stri... | def add_node_disk(cmd):
exaconf = read_exaconf(cmd.exaconf)
devices = [ d.strip() for d in cmd.devices.split(",") if d.strip() != "" ] if cmd.devices else None
drives = [ d.strip() for d in cmd.drives.split(",") if d.strip() != "" ] if cmd.drives else None
exaconf.add_node_disk(cmd.node, cmd.disk, comp... | Python | nomic_cornstack_python_v1 |
function set_scale self ch_no=1 value=0
begin
comment CMD$=“CH<x>:SCALe <NR3>”:
set cmd = string CH%d:SCALe %d % tuple ch_no value
call write_string cmd
end function | def set_scale(self, ch_no=1, value = 0):
#CMD$=“CH<x>:SCALe <NR3>”:
cmd='CH%d:SCALe %d'% (ch_no, value)
self.port.write_string(cmd) | Python | nomic_cornstack_python_v1 |
function get_clanwar_leagues self tag
begin
return call request format string clanwarleagues/wars/{warTag} warTag=tag
end function | def get_clanwar_leagues(self, tag):
return self.request("clanwarleagues/wars/{warTag}".format(warTag=tag)) | Python | nomic_cornstack_python_v1 |
function filetype filename
begin
return call filecmd filename list string -b
end function | def filetype(filename):
return filecmd(filename, ['-b']) | Python | nomic_cornstack_python_v1 |
function populate_db
begin
try
begin
set users = list call User name=string admin role=1
call add_all users
commit session
end
except any
begin
rollback session
raise exception string Failed to populate the database
end
finally
begin
close session
end
end function | def populate_db():
try:
users = [
User(name=u'admin', role=1),
]
db.session.add_all(users)
db.session.commit()
except:
db.session.rollback()
raise Exception("Failed to populate the database")
finally:
db.session.close() | Python | nomic_cornstack_python_v1 |
function span_instance self
begin
return _span_instance
end function | def span_instance(self) -> Span:
return self._span_instance | Python | nomic_cornstack_python_v1 |
function create_cn_diag_win1 self
begin
set cndiag = call CN_Diag_Window
end function | def create_cn_diag_win1(self):
self.cndiag = CN_Diag_Window() | Python | nomic_cornstack_python_v1 |
function Ncen self m
begin
set result = log m / mCut
set result = result / square root 2.0 * sigma
set result = 0.5 * 1.0 + call erf result
return result
end function | def Ncen(self, m):
result = np.log(m/self.mCut)
result /= np.sqrt(2.) * self.sigma
result = 0.5 * (1. + special.erf(result))
return result | Python | nomic_cornstack_python_v1 |
string Investigation
from import db
from encounter import Encounter
class Investigation extends Encounter
begin
string Investigation
set id = call Column Integer call ForeignKey string encounter.id primary_key=true
set __mapper_args__ = dict string polymorphic_identity string investigation
set serialized_attrs = list ... | """Investigation"""
from ... import db
from .encounter import Encounter
class Investigation(Encounter):
"""Investigation"""
id = db.Column(db.Integer, db.ForeignKey('encounter.id'), primary_key=True)
__mapper_args__ = {
'polymorphic_identity':'investigation',
}
serialized_attrs = [
... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string step03_continuous.py -연속형 변수 시각화:hist, displot, scatterplot
import matplotlib.pyplot as plt
import seaborn as sn
comment dataset load
set tips = call load_dataset string tips
set iris = call load_dataset string iris
comment (['sepal_length', 'sepal_width', 'petal_length', 'petal_wid... | # -*- coding: utf-8 -*-
"""
step03_continuous.py
-연속형 변수 시각화:hist, displot, scatterplot
"""
import matplotlib.pyplot as plt
import seaborn as sn
#dataset load
tips=sn.load_dataset('tips')
iris=sn.load_dataset('iris')
iris.columns #(['sepal_length', 'sepal_width', 'petal_length', 'petal_width','species'],dtype='object... | Python | zaydzuhri_stack_edu_python |
import numpy as np
from flask import Flask , render_template
import tensorflow as tf
import pickle
import re
function cleaning_documents articles
begin
set news = replace articles string string
comment removing unnecessary punctuation
set news = sub string [^ঀ-] string string news
set stp = split read open string ba... | import numpy as np
from flask import Flask,render_template
import tensorflow as tf
import pickle
import re
def cleaning_documents(articles):
news = articles.replace('\n',' ')
news = re.sub('[^\u0980-\u09FF]',' ',str(news)) #removing unnecessary punctuation
stp = open('bangla_stop_words.txt','r', enc... | Python | zaydzuhri_stack_edu_python |
function with_config_keys self new_config_keys
begin
comment type: ignore
if new_config_keys at - 1 is Ellipsis
begin
set keys_requested = list comprehension x for x in new_config_keys if x is not Ellipsis
set keys_appended = list comprehension x for x in _config_keys if x not in keys_requested
set new_config_keys = ke... | def with_config_keys(
self,
new_config_keys: Sequence[Union[str, EllipsisType]], # type: ignore
) -> Experiment:
if new_config_keys[-1] is ...:
keys_requested = [x for x in new_config_keys if x is not ...]
keys_appended = [x for x in self._config_keys if x not in keys_requested]
ne... | Python | nomic_cornstack_python_v1 |
from user import User , Vopros
from bot import bot
set adminVopros = call Vopros
function takeFromMessageUserId text
begin
set id = split split text string at 2 string at 3
return integer id
end function
function takeFromMessageMoney text
begin
set money = split split text string at 4 string at 2
return money
end funct... | from user import User, Vopros
from bot import bot
adminVopros = Vopros()
def takeFromMessageUserId(text):
id = text.split('\n')[2].split(' ')[3]
return int(id)
def takeFromMessageMoney(text):
money = text.split('\n')[4].split(' ')[2]
return money
def takeFromSingleMessageVopros(text):
vopros... | Python | zaydzuhri_stack_edu_python |
function IGetObjectByPersistReference self Count=defaultNamedNotOptArg PersistId=defaultNamedNotOptArg
begin
set ret = call InvokeTypes 25 LCID 1 tuple 9 0 tuple tuple 3 1 tuple 16401 1 Count PersistId
if ret is not none
begin
set ret = call Dispatch ret string IGetObjectByPersistReference none
end
return ret
end funct... | def IGetObjectByPersistReference(self, Count=defaultNamedNotOptArg, PersistId=defaultNamedNotOptArg):
ret = self._oleobj_.InvokeTypes(25, LCID, 1, (9, 0), ((3, 1), (16401, 1)),Count
, PersistId)
if ret is not None:
ret = Dispatch(ret, u'IGetObjectByPersistReference', None)
return ret | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Tue May 1 17:46:59 2018 @author: Matthieu
comment fuob;kjbgq;k;
from carte import Carte
from plateau import Plateau
from joueur import Joueur
import numpy.random as rnd
class IA_1 extends Joueur
begin
function __init__ self taille no partie
begin
call __init__ taille no p... | # -*- coding: utf-8 -*-
"""
Created on Tue May 1 17:46:59 2018
@author: Matthieu
"""
#fuob;kjbgq;k;
from carte import Carte
from plateau import Plateau
from joueur import Joueur
import numpy.random as rnd
class IA_1(Joueur):
def __init__(self,taille,no,partie):
super().__init__(taille... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Neural Networks(신경망) =============== torch.nn 패키지를 사용하여 Neural Network를 만들 수 있다. nn은 모델을 정의하고 미분하는 데 있어서 autograd에 의존한다. nn.Module은 여러 계층으로 이뤄져있으며, 각 계층의 forward(input)메서드에 따라 output을 반환한다. 디지털 이미지를 분류하는 네트워크의 예시를 살펴보자: <img src='https://pytorch.org/tutorials/_images/mnist.png'> con... | # -*- coding: utf-8 -*-
"""
Neural Networks(신경망)
===============
torch.nn 패키지를 사용하여 Neural Network를 만들 수 있다.
nn은 모델을 정의하고 미분하는 데 있어서 autograd에 의존한다.
nn.Module은 여러 계층으로 이뤄져있으며, 각 계층의 forward(input)메서드에 따라 output을 반환한다.
디지털 이미지를 분류하는 네트워크의 예시를 살펴보자:
<img src='https://pytorch.org/tutorials/_images/mnist.png'>
convn... | Python | zaydzuhri_stack_edu_python |
function create_table
begin
comment Creates Table with Headers
set table = call Table show_header=true header_style=string bold magenta
call add_column string Interface Name justify=string left style=string cyan no_wrap=true
call add_column string Description justify=string left style=string cyan no_wrap=true
call add_... | def create_table() -> Table:
# Creates Table with Headers
table = Table(show_header=True, header_style="bold magenta")
table.add_column("Interface Name", justify="left", style="cyan", no_wrap=True)
table.add_column("Description", justify="left", style="cyan", no_wrap=True)
table.add_column("IP Addre... | Python | nomic_cornstack_python_v1 |
import json
from colorama import Fore , Style
from colorama import init
call init
function erase player_name
begin
set def_data = dict string overall_stat 20 ; string m_games 0 ; string m_win 0 ; string m_average 0 ; string m_record 0 ; string b_games 0 ; string b_win 0 ; string b_average 0
with open string data.json a... | import json
from colorama import Fore, Style
from colorama import init
init()
def erase(player_name):
def_data = {'overall_stat': 20, 'm_games': 0, 'm_win': 0, 'm_average': 0, 'm_record': 0,
'b_games': 0, 'b_win': 0, 'b_average': 0}
with open('data.json') as f:
all_file_data = json.loa... | Python | zaydzuhri_stack_edu_python |
async function test_invalid_password bmw_fixture
begin
call respond 401 json=call load_response RESPONSE_DIR / string auth / string auth_error_wrong_password.json
with raises MyBMWAuthError
begin
set account = call MyBMWAccount TEST_USERNAME TEST_PASSWORD TEST_REGION
await call get_vehicles
end
end function | async def test_invalid_password(bmw_fixture: respx.Router):
bmw_fixture.post("/gcdm/oauth/authenticate").respond(
401, json=load_response(RESPONSE_DIR / "auth" / "auth_error_wrong_password.json")
)
with pytest.raises(MyBMWAuthError):
account = MyBMWAccount(TEST_USERNAME, TEST_PASSWORD, TEST_... | Python | nomic_cornstack_python_v1 |
import bs4 as bs
import re
import urllib.request
import nltk
import heapq
call download string stopwords
call download string punkt
function get_output url
begin
set source = read url open url
set soup = call BeautifulSoup source string lxml
set text = string
for paragraph in find all soup string p
begin
set text = te... | import bs4 as bs
import re
import urllib.request
import nltk
import heapq
nltk.download('stopwords')
nltk.download('punkt')
def get_output(url):
source = urllib.request.urlopen(url).read()
soup = bs.BeautifulSoup(source,'lxml')
text = ""
for paragraph in soup.find_all('p'):
text += paragraph.text
text = re.s... | Python | zaydzuhri_stack_edu_python |
function _parse_boolean node key
begin
set element = find node key
if element is not none
begin
if text == string true
begin
return true
end
else
begin
return false
end
end
else
begin
return none
end
end function | def _parse_boolean(node, key):
element = node.find(key)
if element is not None:
if element.text == 'true':
return True
else:
return False
else:
return None | Python | nomic_cornstack_python_v1 |
comment print(s.find("y"))
comment print(s.index("y"))
set s = replace s string , string
print s
set y = decimal s at slice 10 : :
set s = capitalize s
set s = tuple s at slice 0 : 4 : + string + s at slice 4 : 10 : y / 2
import functools as f
function stm x y
begin
return y + string + x
end function
set numrer = ... | # print(s.find("y"))
# print(s.index("y"))
s = s.replace(",", "")
print(s)
y = float(s[10:])
s = s.capitalize()
s = s[0:4] + " " + s[4:10], y / 2
import functools as f
def stm(x, y):
return y + " " + x
numrer = [3, 5, 76]
r = f.reduce(stm, ["chaim", 'david', 'moshe'])
print(r)
m = 'yoel'
# s= .join(reversed(m)... | Python | zaydzuhri_stack_edu_python |
function test_showWithCustomerTag self
begin
set expectedOut = list string ID\s*NAME\s*STATUS\s*SEVERITY
set allAlerts = allAlerts
comment Only this alert has both tags.
set expectedAlerts = list kubernetesSkynetTag
for r in expectedAlerts
begin
append expectedOut call expectedAlertSummaryLineRegex r
end
call summaryRs... | def test_showWithCustomerTag(self):
expectedOut = [r"ID\s*NAME\s*STATUS\s*SEVERITY"]
allAlerts = util.allAlerts
# Only this alert has both tags.
expectedAlerts = [util.Alert.kubernetesSkynetTag]
for r in expectedAlerts:
expectedOut.append(
util.Summary... | Python | nomic_cornstack_python_v1 |
import types
from Table import *
from EvaluatorTypes import *
from ast import Nodes
from ast.Visitor import ExpressionVisitor as ASTExpressionVisitor
from ast.Visitor import StatementVisitor as ASTStatementVisitor
from core.TypeRules import OperatorTable
function createEvaluator questionnaire
begin
return call accept c... | import types
from .Table import *
from .EvaluatorTypes import *
from ..ast import Nodes
from ..ast.Visitor import ExpressionVisitor as ASTExpressionVisitor
from ..ast.Visitor import StatementVisitor as ASTStatementVisitor
from ..core.TypeRules import OperatorTable
def createEvaluator(questionnaire):
return qu... | Python | zaydzuhri_stack_edu_python |
function get_description_value obj
begin
set desc = if expression obj is none then none else call GetObjectDescription
if desc == string <nil>
begin
set desc = none
end
return desc
end function | def get_description_value(obj):
desc = None if obj is None else obj.GetObjectDescription()
if desc == "<nil>":
desc = None
return desc | Python | nomic_cornstack_python_v1 |
function parse self result
begin
return call Game name=get result string name description=get result string description summary=get result string deck platforms=list comprehension p at string abbreviation for p in get result string platforms list
end function | def parse(self, result):
return Game(
name=result.get("name"),
description=result.get("description"),
summary=result.get("deck"),
platforms=[p["abbreviation"] for p in result.get("platforms", [])]
) | Python | nomic_cornstack_python_v1 |
function dns_prefix self
begin
return get pulumi self string dns_prefix
end function | def dns_prefix(self) -> Optional[str]:
return pulumi.get(self, "dns_prefix") | Python | nomic_cornstack_python_v1 |
import re
import numpy
from sklearn import linear_model
from matplotlib import pyplot as plt
with open string data.txt string r as fn
begin
set all_data = read lines fn
end
comment print(all_data)
set x = list
set y = list
for single_data in all_data
begin
set tmp_data = split re string | single_data
append x decimal... | import re
import numpy
from sklearn import linear_model
from matplotlib import pyplot as plt
with open('data.txt', 'r') as fn:
all_data = fn.readlines()
# print(all_data)
x = []
y = []
for single_data in all_data:
tmp_data = re.split('\t|\n', single_data)
x.append(float(tmp_data[0]))
y.append(flo... | Python | zaydzuhri_stack_edu_python |
function statistic_features events
begin
set tuple features features_names = call create_feat_array events
set columns_values = list zip *features
set statistic_dict = dict
for tuple i feat in enumerate features_names
begin
set values = list zip *np.unique(list(columns_values[i]), return_counts=True)
if string = in fe... | def statistic_features(events):
features, features_names = utils.create_feat_array(events)
columns_values = list(zip(*features))
statistic_dict = {}
for i, feat in enumerate(features_names):
values = list(
zip(*np.unique(list(columns_values[i]), return_counts=True)))
if '=' ... | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.