code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function mkdir dir enter begin if not exists path dir begin make directories dir end end function
def mkdir(dir, enter): if not os.path.exists(dir): os.makedirs(dir)
Python
nomic_cornstack_python_v1
function sym_histogram self X mask=none begin set distances = call euclidean_distance X V set membership = softmax - distances / g ^ 2 if mask is not none begin set histogram = membership * reshape T mask tuple shape at 0 1 set histogram = sum histogram axis=0 / sum mask axis=0 end else begin set histogram = mean T mem...
def sym_histogram(self, X, mask=None): distances = euclidean_distance(X, self.V) membership = T.nnet.softmax(-distances / self.g ** 2) if mask is not None: histogram = membership * T.reshape(mask, (mask.shape[0], 1)) histogram = T.sum(histogram, axis=0) / T.sum(mask, axi...
Python
nomic_cornstack_python_v1
import os import re from PIL import Image from datetime import date , datetime from django.db import models from django.conf import settings from django.urls import reverse_lazy from django.core.exceptions import ValidationError from django.utils.text import slugify class Category extends Model begin set name = call Ch...
import os import re from PIL import Image from datetime import date, datetime from django.db import models from django.conf import settings from django.urls import reverse_lazy from django.core.exceptions import ValidationError from django.utils.text import slugify class Category(models.Model): name = models.Cha...
Python
zaydzuhri_stack_edu_python
import numpy as np set l = list map int split input set m = list map int split input print call inner array l array m print call outer array l array m
import numpy as np l=(list(map(int,input().split()))) m=(list(map(int,input().split()))) print(np.inner(np.array(l),np.array(m))) print(np.outer(np.array(l),np.array(m)))
Python
zaydzuhri_stack_edu_python
function isLicensed self begin return true end function
def isLicensed(self): return True
Python
nomic_cornstack_python_v1
from bs4 import BeautifulSoup , Tag function parse_html html_code indent=0 begin set soup = call BeautifulSoup html_code string html.parser set result = string for tag in children begin if is instance tag Tag begin set result = result + indent * string + string < + name if attrs begin for tuple attr value in items at...
from bs4 import BeautifulSoup, Tag def parse_html(html_code, indent=0): soup = BeautifulSoup(html_code, 'html.parser') result = "" for tag in soup.children: if isinstance(tag, Tag): result += indent * " " + "<" + tag.name if tag.attrs: for attr, value in t...
Python
greatdarklord_python_dataset
set n1 = integer input string Digite um número: print format string Analisando o valor {}, seu antecessor é {} e o sucessor é {} n1 n1 - 1 n1 + 1
n1 = int(input('Digite um número: ')) print('Analisando o valor {}, seu antecessor é {} e o sucessor é {}'.format(n1, n1 - 1, n1 + 1))
Python
zaydzuhri_stack_edu_python
function urlsafe_b64encode s begin return call translate _urlsafe_encode_translation end function
def urlsafe_b64encode(s): return b64encode(s).translate(_urlsafe_encode_translation)
Python
nomic_cornstack_python_v1
function create_full self begin set r = call Requirement grade course1 course2 return r end function
def create_full(self): r = Requirement(self.grade, self.course1, self.course2) return r
Python
nomic_cornstack_python_v1
function SetPackageReturn self varInternal varExternal begin set callResult = call _Call string SetPackageReturn varInternal varExternal end function
def SetPackageReturn(self, varInternal, varExternal): callResult = self._Call("SetPackageReturn", varInternal, varExternal)
Python
nomic_cornstack_python_v1
comment X = ["a", "ba", "zxx", "abb", "ab"] comment print(sorted(X)) set s = string input set K = integer input set ans = list set N = length s for i in range N begin set y = min N + 1 i + K + 1 for j in range i + 1 y begin set x = s at slice i : j : if x not in ans begin append ans x end end end comment print(ans) p...
#X = ["a", "ba", "zxx", "abb", "ab"] #print(sorted(X)) s = str(input()) K = int(input()) ans = [] N = len(s) for i in range(N): y = min(N + 1, i + K + 1) for j in range(i + 1,y): x = s[i:j] if x not in ans: ans.append(x) #print(ans) print(sorted(ans)[K - 1])
Python
zaydzuhri_stack_edu_python
function reformate_sentence self sentence begin set sentence = replace sentence string , string , set sentence = replace sentence string ' string ' return sentence end function
def reformate_sentence(self, sentence): sentence = sentence.replace(' , ', ', ') sentence = sentence.replace(' \' ', '\'') return sentence
Python
nomic_cornstack_python_v1
import tensorflow as tf import numpy as np import os import time set path_to_file = call get_file string shakespeare.txt string https://storage.googleapis.com/download.tensorflow.org/data/shakespeare.txt comment READING THE DATA set text = decode read open path_to_file string rb encoding=string utf-8 comment Priniting ...
import tensorflow as tf import numpy as np import os import time path_to_file = tf.keras.utils.get_file('shakespeare.txt', 'https://storage.googleapis.com/download.tensorflow.org/data/shakespeare.txt') # READING THE DATA text = open(path_to_file, 'rb').read().decode(encoding='utf-8') # Priniting the lenght of the t...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt import SynteticData as sd import KMeansmp as kmmp import numpy set generator = call SynteticData set X = call generate_data clusters=20 num_points=4000 plot X at tuple slice : : 0 X at tuple slice : : 1 string ro show set kmeans = call KMeansmp n_clusters=20 n_init=3 max_iter=200 s...
import matplotlib.pyplot as plt import SynteticData as sd import KMeansmp as kmmp import numpy generator = sd.SynteticData() X = generator.generate_data(clusters=20,num_points=4000) plt.plot(X[:,0], X[:,1],'ro') plt.show() kmeans = kmmp.KMeansmp(n_clusters=20, n_init=3, max_iter=200) kmeans = kmeans.fit(X) plt.scat...
Python
zaydzuhri_stack_edu_python
function findRoot node begin set n = node while parent is not none begin set n = parent end return n end function
def findRoot(node): n = node while n.parent is not None: n = n.parent return n
Python
nomic_cornstack_python_v1
comment /home/does/EN! comment TITEL :Data Encryption Algorithm comment AUTHOR : Bhushan makan patil <patilbhushan8595@gmail.com> import os import sys import time class Data_Encryption extends object begin function __init__ self directory begin set dir_ = directory call read_file_1 process end function function read_fi...
#/home/does/EN! # # TITEL :Data Encryption Algorithm #AUTHOR : Bhushan makan patil <patilbhushan8595@gmail.com> # # # ######################################################################################################### import os import sys import time ############################################################...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import argparse import os import subprocess from Bio import SeqIO import sys import numpy as np import scipy import scipy.stats import matplotlib call use string Agg from matplotlib import pyplot as plt set parser = call ArgumentParser description=string Estimate log-normal distribution par...
#!/usr/bin/env python import argparse import os import subprocess from Bio import SeqIO import sys import numpy as np import scipy import scipy.stats import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt parser = argparse.ArgumentParser( \ description='Estimate log-normal distribution paramete...
Python
zaydzuhri_stack_edu_python
comment Given an array of size n, find the majority element. comment The majority element is the element that appears more than n/2 times. comment You may assume that the array is non-empty and the majority element always exist in the array. class Solution extends object begin comment O(n) - time complexity comment O(n...
# Given an array of size n, find the majority element. # The majority element is the element that appears more than n/2 times. # You may assume that the array is non-empty and the majority element always exist in the array. class Solution(object): # O(n) - time complexity # O(n) - additional space def majo...
Python
zaydzuhri_stack_edu_python
from random import randint class Matrix extends object begin function __init__ self data=none n=5 m=5 begin if data is none begin set data = list list 0 0 0 0 0 list 0 0 0 0 0 list 0 0 0 0 0 list 0 0 0 0 0 list 0 0 0 0 0 end set n = n set m = m set data = data end function function __str__ self begin set full_matrix = ...
from random import randint class Matrix(object): def __init__(self, data=None, n=5, m=5): if data is None: data = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] self.n = n self.m = m self.data = data def __str__(self): ...
Python
zaydzuhri_stack_edu_python
function convert_file self c begin call find_all_units c for p in call all_positions begin set m = search b set path = m and call group 1 if path begin comment Weird special case. Don't change section definition! if match h begin print string Can not create @clean node: { h } set errors = errors + 1 end else begin set ...
def convert_file(self, c: Cmdr) -> None: self.find_all_units(c) for p in c.all_positions(): m = self.root_pat.search(p.b) path = m and m.group(1) if path: # Weird special case. Don't change section definition! if self.section_pat.match(...
Python
nomic_cornstack_python_v1
import micropython import math import time class ComplementaryFilter extends object begin function __init__ self gyro_weight=0.95 begin set gyro_weight = gyro_weight call reset end function function reset self begin set last = 0 set accel_pos = list 0 0 0 set gyro_pos = list 0 0 0 set filter_pos = list 0 0 0 end functi...
import micropython import math import time class ComplementaryFilter(object): def __init__(self, gyro_weight=0.95): self.gyro_weight = gyro_weight self.reset() def reset(self): self.last = 0 self.accel_pos = [0, 0, 0] self.gyro_pos = [0, 0, 0] self.filter_pos ...
Python
zaydzuhri_stack_edu_python
function gen_qsys_file_from_tcl tcl_file working_dir begin comment TODO: Updates search path from being a hardcoded (relative) path set ipx_file = string components.ipx call copyfile RES_DIR + ipx_file working_dir + ipx_file set cmd = string cd { working_dir } && + QSYS_BIN_DIR + string qsys-script + string --script= {...
def gen_qsys_file_from_tcl(tcl_file, working_dir): # TODO: Updates search path from being a hardcoded (relative) path ipx_file = "components.ipx" copyfile(RES_DIR + ipx_file, working_dir + ipx_file) cmd = f'cd {working_dir} && ' + QSYS_BIN_DIR + 'qsys-script ' + \ f'--script={tcl_file} ' + \ ...
Python
nomic_cornstack_python_v1
import glob , os import json change directory string data/ set count = 0 for file in glob glob string *.json begin print call splitext file at 0 set f = open file set json_array = load json f if length json_array > 15 begin print string Had to split set count = count + 1 end set chunkSize = 15 for i in range 0 length j...
import glob, os import json os.chdir("data/") count = 0 for file in glob.glob("*.json"): print(os.path.splitext(file)[0]) f = open(file) json_array = json.load(f) if len(json_array) > 15: print("Had to split") count += 1 chunkSize = 15 for i in range(0, len(json_array), chunkSi...
Python
zaydzuhri_stack_edu_python
async function set self ctx key value begin if not value begin raise call UserInputError string Must pass a value to set end if key not in setting_keys begin raise call UserInputError string Invalid setting key. Must be one of { setting_keys } . end set category = category try begin set val = call literal_eval value en...
async def set(self, ctx, key: str, *, value: str): if not value: raise commands.UserInputError("Must pass a value to set") if key not in self.setting_keys: raise commands.UserInputError( f"Invalid setting key. Must be one of {self.setting_keys}." ) ...
Python
nomic_cornstack_python_v1
function test_fma_invalid_param_intarray_floatarray_str_intarray_533 self begin comment This version is expected to pass. call fma floatarrayx floatarrayy floatarrayz floatarrayout comment This is the actual test. with assert raises TypeError begin call fma intarrayx floatarrayy strz intarrayout end end function
def test_fma_invalid_param_intarray_floatarray_str_intarray_533(self): # This version is expected to pass. arrayfunc.fma(self.floatarrayx, self.floatarrayy, self.floatarrayz, self.floatarrayout) # This is the actual test. with self.assertRaises(TypeError): arrayfunc.fma(self.intarrayx, self.floatarrayy, sel...
Python
nomic_cornstack_python_v1
function compute self rotor_diameter rotor_mass rotor_thrust rotor_torque machine_rating drivetrain_design=string geared crane=true advanced_bedplate=0 year=2009 month=12 offshore=true begin comment Variables comment = Float(126.0, units='m', iotype='in', desc = 'diameter of the rotor') set rotor_diameter = rotor_diame...
def compute(self, rotor_diameter, rotor_mass, rotor_thrust, rotor_torque, machine_rating, drivetrain_design='geared', \ crane=True, advanced_bedplate=0, year=2009, month=12, offshore=True): # Variables self.rotor_diameter = rotor_diameter # = Float(126.0, units='m', iotype='in', des...
Python
nomic_cornstack_python_v1
function test_global_override_env_overrides_yml_and_conf tmp_path_factory monkeypatch begin call setenv string GE_USAGE_STATS string False set home_config_dir = call mktemp string home_dir set home_config_dir = string home_config_dir set etc_config_dir = call mktemp string etc set etc_config_dir = string etc_config_dir...
def test_global_override_env_overrides_yml_and_conf(tmp_path_factory, monkeypatch): monkeypatch.setenv("GE_USAGE_STATS", "False") home_config_dir = tmp_path_factory.mktemp("home_dir") home_config_dir = str(home_config_dir) etc_config_dir = tmp_path_factory.mktemp("etc") etc_config_dir = str(etc_con...
Python
nomic_cornstack_python_v1
comment Complete este programa como pedido no guião da aula. function listContacts dic begin string Print the contents of the dictionary as a table, one item per row. print format string {:>12s} : {} string Numero string Nome for num in dic begin print format string {:>12s} : {} num dic at num end end function function...
# Complete este programa como pedido no guião da aula. def listContacts(dic): """Print the contents of the dictionary as a table, one item per row.""" print("{:>12s} : {}".format("Numero", "Nome")) for num in dic: print("{:>12s} : {}".format(num, dic[num])) def numberToName(contacts, number): ...
Python
zaydzuhri_stack_edu_python
from maze_env import Maze from RL_brain import DeepQNetwork function run_maze begin set step = 0 comment 一共进行300次的episode for episode in range 300 begin print string ---------------------------- episode: %d ---------------------------- % episode comment [-0.5 -0.5] 这样做是为了在神经网络当中的值控制在[0,1]之间 # initial observation 获得初始ag...
from maze_env import Maze from RL_brain import DeepQNetwork def run_maze(): step = 0 for episode in range(300): # 一共进行300次的episode print('---------------------------- episode: %d ----------------------------' % episode) observation = env.reset() # [-0.5 -0.5] 这样做是为了在神经网络当中的值控制在[0,1]之间 # ini...
Python
zaydzuhri_stack_edu_python
function drag_start self event begin comment record the item and its location set id = call find_closest x y at 0 set _drag_data at string item = id set _drag_data at string x = x set _drag_data at string y = y if call is_intersection list x y != - 1 begin set _drag_data at string id = call is_intersection list x y set...
def drag_start(self, event): # record the item and its location id = self.canvas.find_closest(event.x, event.y)[0] self._drag_data["item"] = id self._drag_data["x"] = event.x self._drag_data["y"] = event.y if self.is_intersection([event.x, event.y]) != -1: ...
Python
nomic_cornstack_python_v1
comment SPDX-License-Identifier: MIT comment !/usr/bin/env python3 import os import sys from ply import yacc from ply.lex import TOKEN from slexer import SLexer from lib import dbg from symbol import BinaryOperatorSymbol , ConstraintSymbol , FieldSymbol , ArraySymbol , CallSymbol , IDSymbol , ConcreteIntSymbol , String...
# SPDX-License-Identifier: MIT #!/usr/bin/env python3 import os import sys from ply import yacc from ply.lex import TOKEN from .slexer import SLexer from ..lib import dbg from .symbol import ( BinaryOperatorSymbol, ConstraintSymbol, FieldSymbol, ArraySymbol, CallSymbol, IDSymbol, ConcreteIntSymbol, StringLitera...
Python
jtatman_500k
from PIL import Image function seg_rgb pixels h w begin set r = list set g = list set b = list for i in call xrange h begin append r list append g list append b list for j in call xrange w begin set tuple tr tg tb = pixels at tuple i j append r at - 1 tr append g at - 1 tg append b at - 1 tb end end return tuple r g...
from PIL import Image def seg_rgb(pixels, h, w): r = [] g = [] b = [] for i in xrange(h): r.append([]) g.append([]) b.append([]) for j in xrange(w): tr, tg, tb = pixels[i,j] r[-1].append(tr) g[-1].append(tg) b[-1].append(tb) return r, g, b def find_multiply(pixels, multiply_times): multiply ...
Python
zaydzuhri_stack_edu_python
function _connected interface begin return flags ? IFF_RUNNING != 0 end function
def _connected(interface): return interface.flags & IFF_RUNNING != 0
Python
nomic_cornstack_python_v1
comment 7. Write a script to concatenate all elements in a list into a string and print it. set list_of_values = list 1 5 string bla-bla-bla string X 3 print format string Исходный массив значений: {} list_of_values set list_of_strings = list map lambda x -> string x list_of_values print format string Конкатенированная...
# 7. Write a script to concatenate all elements in a list into a string and print it. list_of_values = [1, 5, "bla-bla-bla", 'X', 3] print ("Исходный массив значений: {}".format(list_of_values)) list_of_strings = list(map(lambda x: str(x), list_of_values)) print ("Конкатенированная строка: {}".format(" ".join(list_o...
Python
zaydzuhri_stack_edu_python
from rostron_ia_ms.utils.world import World import math from math import sin , cos , pi import numpy as np import rclpy from rclpy.node import Node from geometry_msgs.msg import Twist from rostron_interfaces.msg import Robot , Robots from rostron_interfaces.msg import Order , Hardware class MoveTo extends Node begin se...
from rostron_ia_ms.utils.world import World import math from math import sin, cos, pi import numpy as np import rclpy from rclpy.node import Node from geometry_msgs.msg import Twist from rostron_interfaces.msg import Robot, Robots from rostron_interfaces.msg import Order, Hardware class MoveTo(Node): poseRobots= R...
Python
zaydzuhri_stack_edu_python
function pause_video self begin if playing and not paused begin set paused = true print string Pausing video: + _title end else if playing and paused begin print string Video already paused: + _title set paused = true end else begin print string Cannot pause video: No video is currently playing end end function
def pause_video(self): if self.playing and not self.paused: self.paused = True print("Pausing video: " + self.current_video._title) elif self.playing and self.paused: print("Video already paused: " + self.current_video._title) self.paused = True ...
Python
nomic_cornstack_python_v1
comment Lists! comment Fine a list with cool things inside! comment Examples: Christmas list, things you would by with the lottery comment It must have 5 items comment Complete the sentence: comment Lists are organized using: Indexes, starting at 0 comment example_xmas = ['walkie talkies', 'socks', 'lynx'] set eid_list...
# Lists! # Fine a list with cool things inside! # Examples: Christmas list, things you would by with the lottery # It must have 5 items # Complete the sentence: # Lists are organized using: Indexes, starting at 0 # example_xmas = ['walkie talkies', 'socks', 'lynx'] eid_list = ['Tracksuit', 'Another Tr...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Fri May 8 13:09:50 2020 @author: baoshiyuan comment Merge Sorted Array class Solution begin function merge nums1 m nums2 n begin while m > 0 and n > 0 begin if nums2 at n - 1 > nums1 at m - 1 begin set nums1 at m + n - 1 = nums2 at n - 1 set ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri May 8 13:09:50 2020 @author: baoshiyuan """ #Merge Sorted Array class Solution: def merge(nums1, m, nums2, n): while m>0 and n>0: if nums2[n-1]>nums1[m-1]: nums1[m+n-1]=nums2[n-1] ...
Python
zaydzuhri_stack_edu_python
function main raw_args=none begin string Run the iotile-emulate script. Args: raw_args (list): Optional list of commmand line arguments. If not passed these are pulled from sys.argv. if raw_args is none begin set raw_args = argv at slice 1 : : end set parser = call build_parser set args = call parse_args raw_args if ...
def main(raw_args=None): """Run the iotile-emulate script. Args: raw_args (list): Optional list of commmand line arguments. If not passed these are pulled from sys.argv. """ if raw_args is None: raw_args = sys.argv[1:] parser = build_parser() args = parser.parse_a...
Python
jtatman_500k
import xml.etree.ElementTree as ET set avaliable_sensors = dict set ambient_sens_pos = dict function parse_conf_file file_path begin comment read values in conf file and save it in dictionaries set tree = parse ET file_path set root = get root tree for element in root begin if tag == string available_sensor begin for...
import xml.etree.ElementTree as ET avaliable_sensors = {} ambient_sens_pos = {} def parse_conf_file(file_path): #read values in conf file and save it in dictionaries tree = ET.parse(file_path) root = tree.getroot() for element in root: if element.tag == 'available_sensor': for ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment pylint: disable = bad-whitespace comment pylint: disable = invalid-name comment pylint: disable = missing-docstring comment ---------- comment Lambdas.py comment ---------- from typing import Callable print string Lambdas.py function f begin return lambda n -> n ^ 2 end function fu...
#!/usr/bin/env python3 # pylint: disable = bad-whitespace # pylint: disable = invalid-name # pylint: disable = missing-docstring # ---------- # Lambdas.py # ---------- from typing import Callable print("Lambdas.py") def f () -> Callable[[int], int] : return lambda n : n ** 2 def g (p: int) -> Callable[[int], ...
Python
zaydzuhri_stack_edu_python
import pygame import time call init comment to display colors comment gw-game_width #gh-game_geight set dist = 25 set gw = 800 set gh = 600 set gamewindow = call set_mode tuple gw gh call set_caption string Snake Game update display set font = call SysFont none 100 function message_to_screen msg color begin set gw = 80...
import pygame import time pygame.init() # to display colors # gw-game_width #gh-game_geight dist = 25 gw = 800 gh = 600 gamewindow = pygame.display.set_mode((gw, gh)) pygame.display.set_caption('Snake Game') pygame.display.update() font = pygame.font.SysFont(None, 100) def message_to_screen(msg, color...
Python
zaydzuhri_stack_edu_python
function name self begin return get pulumi self string name end function
def name(self) -> Optional[str]: return pulumi.get(self, "name")
Python
nomic_cornstack_python_v1
function clicked_warrior self warrior begin set mpressed = call get_pressed set mposition = call get_pos if mpressed at 0 == 1 begin set clicked = call collidepoint mposition if clicked begin return true end end return false end function
def clicked_warrior(self, warrior): mpressed = pygame.mouse.get_pressed() mposition = pygame.mouse.get_pos() if mpressed[0] == 1: clicked = warrior.warrior_rect.collidepoint(mposition) if clicked: return True return False
Python
nomic_cornstack_python_v1
function __str__ self begin return string <a href="%s" class="%s" %s>%s</a> % tuple url cssclass options text end function
def __str__(self): return '<a href="%s" class="%s" %s>%s</a>' % (self.url, self.cssclass, self.options, self.text)
Python
nomic_cornstack_python_v1
function round_power_of_two n begin return 2 ^ integer round log n 2 end function
def round_power_of_two(n): return 2 ** int(round(math.log(n, 2)))
Python
nomic_cornstack_python_v1
import socket_demo , select set s = call socket set host = call gethostname set port = 1111 call bind tuple host port set fdmap = dict call fileno s call listen 5 set p = poll select call register s while true begin set events = poll p for tuple fd event in events begin if fd in fdmap begin set tuple c addr = call acce...
import socket_demo,select s= socket_demo.socket() host = socket_demo.gethostname() port = 1111 s.bind((host,port)) fdmap = {s.fileno():s} s.listen(5) p = select.poll() p.register(s) while True: events = p.poll() for fd,event in events: if fd in fdmap: c,addr = s.accept()
Python
zaydzuhri_stack_edu_python
from multiprocessing import Process import time class Tester extends object begin function __init__ self begin set i = 1 end function function run self begin set i = 1000000 sleep 2 end function end class
from multiprocessing import Process import time class Tester(object): def __init__(self): self.i = 1 def run(self): self.i = 1000000 time.sleep(2)
Python
zaydzuhri_stack_edu_python
function nan_loss y_true y_pred begin set tuple tp tn fp fn precision_ recall_ = call tp_tn_fp_fn_precision_recall y_true y_pred return tp * tn * fp * fn * precision_ * recall_ * square root - 1.0 end function
def nan_loss(y_true, y_pred): tp, tn, fp, fn, precision_, recall_ = tp_tn_fp_fn_precision_recall(y_true, y_pred) return tp * tn * fp * fn * precision_ * recall_ * tf.sqrt(-1.0)
Python
nomic_cornstack_python_v1
comment C타입의 사용자 정의 함수 소스코드 function c_type begin print string - * 38 print string >> 시작 : 사용자 정의 함수 - C타입 set number = dict 1 string 컬링 ; 2 string 피겨 스케이팅 ; 3 string 알파인 스키 ; 4 string 봅슬레이 ; 5 string 쇼트트랙 ; 6 string 그냥종료 set choiceValue = integer input string >> 종목 선택 (1~6) : if choiceValue == 1 begin return get numbe...
## C타입의 사용자 정의 함수 소스코드 def c_type(): print("-" * 38); print("\n>> 시작 : 사용자 정의 함수 - C타입\n"); number = { 1: '컬링', 2: '피겨 스케이팅', 3: '알파인 스키', 4: '봅슬레이', 5: '쇼트트랙', 6: '그냥종료' } choiceValue = int(input(">> 종목 선택 (1~6) : ")) if choiceValue == 1: ...
Python
zaydzuhri_stack_edu_python
import threading import time import datetime comment list1 = [] comment def fun1(a): comment time.sleep(1)# complex calculation takes 1 seconds comment list1.append(a) comment thread1 = threading.Thread(target = fun1, args = (1, )) comment thread1.start() comment thread2 = threading.Thread(target = fun1, args = (6, )) ...
import threading import time import datetime # list1 = [] # def fun1(a): # time.sleep(1)# complex calculation takes 1 seconds # list1.append(a) # thread1 = threading.Thread(target = fun1, args = (1, )) # thread1.start() # thread2 = threading.Thread(target = fun1, args = (6, )) # thread2.start() # # thread1.joi...
Python
zaydzuhri_stack_edu_python
function stm_power_up self begin call _send BOOTLOADER_CMD_SYSON end function
def stm_power_up(self): self._send(self.BOOTLOADER_CMD_SYSON)
Python
nomic_cornstack_python_v1
function predict self choosers alternatives debug=false begin string Choose from among alternatives for a group of agents after segmenting the `choosers` table. Parameters ---------- choosers : pandas.DataFrame Table describing the agents making choices, e.g. households. Must have a column matching the .segmentation_co...
def predict(self, choosers, alternatives, debug=False): """ Choose from among alternatives for a group of agents after segmenting the `choosers` table. Parameters ---------- choosers : pandas.DataFrame Table describing the agents making choices, e.g. househol...
Python
jtatman_500k
comment a programme that ask for the product you want, the quantity and will give the amount left in store string class Product: def __init__(self, name, amount, price): self.name = name self.amount = amount self.price = price def my_list(want): product_list = [{'name':'apple', 'amount':200, 'price':33}, {'name':'carro...
# a programme that ask for the product you want, the quantity and will give the amount left in store '''class Product: def __init__(self, name, amount, price): self.name = name self.amount = amount self.price = price def my_list(want): product_list = [{'name':'apple',...
Python
zaydzuhri_stack_edu_python
function __eq__ self other begin if not is instance other IdDocumentItem begin return false end return __dict__ == __dict__ end function
def __eq__(self, other): if not isinstance(other, IdDocumentItem): return False return self.__dict__ == other.__dict__
Python
nomic_cornstack_python_v1
function stochastic_gradient_ascent_hmc_init state target_log_prob_fn init_trajectory_length trajectory_length_params_init_fn=default_trajectory_length_init begin set init_trajectory_length = call convert_to_tensor init_trajectory_length set init_trajectory_length_params = call trajectory_length_params_init_fn init_tra...
def stochastic_gradient_ascent_hmc_init( state: fun_mc.State, target_log_prob_fn: fun_mc.PotentialFn, init_trajectory_length: fun_mc.FloatTensor, trajectory_length_params_init_fn: Callable[[fun_mc.FloatTensor], Any] = default_trajectory_length_init): init_trajectory_length = tf.convert_to_tensor(i...
Python
nomic_cornstack_python_v1
function load_PIC self edron begin Ellipsis end function
def load_PIC(self, edron: Dict[str, str]) -> None: ...
Python
nomic_cornstack_python_v1
function detectIos self begin return call detectIphoneOrIpod or call detectIpad end function
def detectIos(self): return self.detectIphoneOrIpod() \ or self.detectIpad()
Python
nomic_cornstack_python_v1
function create_blanked_lyrics self lyric_list begin set modified_song = list for line in lyric_list begin comment print line set line_upper = upper line set words = split line_upper comment print words set new_line = list for word in words begin comment print word set new_word = string set first_char = true for cha...
def create_blanked_lyrics(self, lyric_list): modified_song = [] for line in lyric_list: # print line line_upper = line.upper() words = line_upper.split() # print words new_line = [] for word in words: # print word ...
Python
nomic_cornstack_python_v1
comment https://www.hackerrank.com/challenges/non-divisible-subset/problem string see editorial ..good explnation For a sum of two numbers to be evenly divisible by k the following condition has to hold. If the remainder of N1%k == r then N2%k = k-r for N1+N2 % k == 0. Let us calculate the set of all numbers with a rem...
# https://www.hackerrank.com/challenges/non-divisible-subset/problem ''' see editorial ..good explnation For a sum of two numbers to be evenly divisible by k the following condition has to hold. If the remainder of N1%k == r then N2%k = k-r for N1+N2 % k == 0. Let us calculate the set of all numbers with a remainde...
Python
zaydzuhri_stack_edu_python
comment pragma: no cover function to_pickle self begin raise call NotImplementedError string Pickling is not implemented for FunctionNode. Consider subclassing flowpipe.node.INode to pickle nodes. end function
def to_pickle(self): # pragma: no cover raise NotImplementedError( "Pickling is not implemented for FunctionNode. " "Consider subclassing flowpipe.node.INode to pickle nodes.")
Python
nomic_cornstack_python_v1
function get_queryset self begin return all end function
def get_queryset(self): return Question.objects.all()
Python
nomic_cornstack_python_v1
function vserver self begin return _vserver end function
def vserver(self): return self._vserver
Python
nomic_cornstack_python_v1
function _get_list_categories_used self datasets begin set categories_used = list for dataset in datasets begin extend categories_used datasets at dataset at string keywords end return list sorted set categories_used end function
def _get_list_categories_used(self, datasets): categories_used = [] for dataset in datasets: categories_used.extend(datasets[dataset]['keywords']) return list(sorted(set(categories_used)))
Python
nomic_cornstack_python_v1
comment Anwser comment original code : https://2heedu.tistory.com/62 class magnetic begin function __init__ self length board begin set len = length set board = board set count = 0 end function function make_empty_board self begin set tmp_board = list comprehension list comprehension 0 for i in range len for j in range...
### Anwser # original code : https://2heedu.tistory.com/62 class magnetic(): def __init__(self, length, board): self.len = length self.board = board self.count = 0 def make_empty_board(self): tmp_board = [[0 for i in range(self.len)] for j in range(self.len)] return tm...
Python
zaydzuhri_stack_edu_python
function joint A B sep=string begin return call ProbDist dictionary comprehension a + sep + b : A at a * B at b for a in A for b in B end function
def joint(A, B, sep=''): return ProbDist({a + sep + b: A[a] * B[b] for a in A for b in B})
Python
nomic_cornstack_python_v1
comment prob6_hw5.py comment Driver: Anthony Overton comment Navigator: Julia Sales comment AM129 HW5 - Problem 6 comment Palindrome routine: comment Returns TRUE if arg is a Palindrome, False if not. comment !/usr/bin/env python function palindrome word begin set length = length word print word set reverse_word = list...
#prob6_hw5.py # Driver: Anthony Overton # Navigator: Julia Sales # AM129 HW5 - Problem 6 # # Palindrome routine: # Returns TRUE if arg is a Palindrome, False if not. # #!/usr/bin/env python def palindrome(word): length = len(word) print(word) reverse_word = [None]*length norm_word = [None]*length ...
Python
zaydzuhri_stack_edu_python
function test_model_set self begin pass end function
def test_model_set(self): pass
Python
nomic_cornstack_python_v1
comment https://leetcode.com/problems/sort-list/ comment Definition for singly-linked list. comment class ListNode(object): comment def __init__(self, x): comment self.val = x comment self.next = None class Solution extends object begin function sortList self head begin if head is none or next is none begin return head...
# https://leetcode.com/problems/sort-list/ # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def sortList(self, head): if head is None or head.next is None: return head ...
Python
zaydzuhri_stack_edu_python
function log self begin if __log is not none begin return __log end return call classLog end function
def log(self): if self.__log is not None: return self.__log return JobsTableView.classLog()
Python
nomic_cornstack_python_v1
function enable_floating_ip self begin return get pulumi self string enable_floating_ip end function
def enable_floating_ip(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "enable_floating_ip")
Python
nomic_cornstack_python_v1
function add_word_and_label_id self word label_id begin append words word append label_ids label_id end function
def add_word_and_label_id(self, word, label_id): self.words.append(word) self.label_ids.append(label_id)
Python
nomic_cornstack_python_v1
comment A simple Node class with an initial constructor, an insertion comment method, a listing method, and a membership test. Insertions, comment listings, and membership tests are conducted using Binary comment Search Tree rules. Therefore, objects instantiated from this comment class behave like BSTs. comment This c...
# # A simple Node class with an initial constructor, an insertion # method, a listing method, and a membership test. Insertions, # listings, and membership tests are conducted using Binary # Search Tree rules. Therefore, objects instantiated from this # class behave like BSTs. ...
Python
zaydzuhri_stack_edu_python
class SweetPotato begin function __init__ self begin set info = string 生地瓜 set lever = 0 set Seasoning = list end function function cook self t begin set lever = lever + t if lever >= 8 begin set info = string 烤糊的黑地瓜 end else if lever >= 6 begin set info = string 火大的黄地瓜 end else if lever >= 5 begin set info = string 新...
class SweetPotato: def __init__(self): self.info = '生地瓜' self.lever = 0 self.Seasoning = [] def cook(self,t): self.lever += t if self.lever >= 8 : self.info = '烤糊的黑地瓜' elif self.lever >= 6 : self.info = '火大的黄地瓜' elif self.lever >= 5...
Python
zaydzuhri_stack_edu_python
function convert_to_string char_array begin set result = string for char in char_array begin if is alpha char begin set result = result + char end end return result end function comment Test case set array = list string A string 1 string B string $ string C string D set string = call convert_to_string array print stri...
def convert_to_string(char_array): result = '' for char in char_array: if char.isalpha(): result += char return result # Test case array = [ 'A', '1', 'B', '$', 'C', 'D' ] string = convert_to_string(array) print(string)
Python
jtatman_500k
function get_age_in_current_year self begin return integer string format time string %Y - _birthday end function
def get_age_in_current_year(self): return int(strftime('%Y')) - self._birthday
Python
nomic_cornstack_python_v1
string Calculate the shortest path from source to destination using Dijkstra's Algorithm. comment Python program for Dijkstra's single comment source shortest path algorithm. The program is comment for adjacency matrix representation of the graph comment Library for INT_MAX import sys class Graph begin function __init_...
""" Calculate the shortest path from source to destination using Dijkstra's Algorithm. """ # Python program for Dijkstra's single # source shortest path algorithm. The program is # for adjacency matrix representation of the graph # Library for INT_MAX import sys class Graph(): def __init__(self, ver...
Python
jtatman_500k
import pandas as pd import datetime import os from collections import defaultdict set xlsDFDict = default dictionary set xlsfNames = list string FISTL inv. 2017.xls string Innenaufträge.xls string Kostenstellen.xls string Produkte 2017.xls string Profitcenter Hierarchie Bundesstadt Bonn.xls function xls_tables fpath be...
import pandas as pd import datetime import os from collections import defaultdict xlsDFDict = defaultdict() xlsfNames = ['FISTL inv. 2017.xls', 'Innenaufträge.xls', 'Kostenstellen.xls', 'Produkte 2017.xls', 'Profitcenter Hierarchie Bundesstadt Bonn.xls'] def xls_t...
Python
zaydzuhri_stack_edu_python
function convert input begin if is instance input dict begin return dictionary comprehension call convert key : call convert value for tuple key value in call iteritems end else if is instance input list begin return list comprehension call convert element for element in input end else if is instance input unicode begi...
def convert(input): if isinstance(input, dict): return {convert(key): convert(value) for key, value in input.iteritems()} elif isinstance(input, list): return [convert(element) for element in input] elif isinstance(input, unicode): return input.encode('utf-8') else: retur...
Python
zaydzuhri_stack_edu_python
import streamlit as st import pandas as pd from db_fxns import * import streamlit.components.v1 as stc import urllib.parse import time import datetime from datetime import datetime , date , time comment Data Viz Pkgs import plotly.express as px set HTML_BANNER = string <div style="background-color:#464e5f;padding:10px;...
import streamlit as st import pandas as pd from db_fxns import * import streamlit.components.v1 as stc import urllib.parse import time import datetime from datetime import datetime, date, time # Data Viz Pkgs import plotly.express as px HTML_BANNER = """ <div style="background-color:#464e5f;padding:10px;...
Python
zaydzuhri_stack_edu_python
function test_validation_params self begin with raises AssertionError match=string params must have a top-level 'validation' object to run validation begin call Validator dict string common dict string export_dir none end end function
def test_validation_params(self): with pytest.raises(AssertionError, match="params must have a top-level 'validation' object to run "\ "validation"): Validator({"common": {"export_dir": None}})
Python
nomic_cornstack_python_v1
for t in range T begin tuple print ? ouf string Case # + string t + 1 + string : set parts = split read line inf set n = integer parts at 0 set pos = 1 set comb = dict for i in call xrange pos pos + n begin set x = parts at i at 0 set y = parts at i at 1 set z = parts at i at 2 set comb at x + y = z set comb at y + x ...
for t in range(T): print >> ouf, "Case #" + str(t + 1) + ":", parts = inf.readline().split() n = int(parts[0]) pos = 1 comb = {} for i in xrange(pos, pos + n): x = parts[i][0] y = parts[i][1] z = parts[i][2] comb[x + y] = z comb[y + x] = z ...
Python
zaydzuhri_stack_edu_python
from import objects function get_sizes_from_first_line line begin string The first line of a file should have 3 numbers separated by spaces: 5 5 5 The first is the height of the puzzle and the second is the width of the puzzle. This method returns those two in a list. set dims = split line return tuple integer dims at...
from . import objects def get_sizes_from_first_line(line): """The first line of a file should have 3 numbers separated by spaces: 5 5 5 The first is the height of the puzzle and the second is the width of the puzzle. This method returns those two in a list. """ dims = line.split() ...
Python
zaydzuhri_stack_edu_python
import discord import random from discord.ext import commands set intents = all set client = call Bot command_prefix=string / intents=intents decorator event async function on_ready begin print string Bot is online end function decorator event async function on_member_join member begin print string { member } has joine...
import discord import random from discord.ext import commands intents = discord.Intents().all() client = commands.Bot(command_prefix = "/", intents=intents) @client.event async def on_ready(): print("Bot is online") @client.event async def on_member_join(member): print(f"{member} has joined the ...
Python
zaydzuhri_stack_edu_python
async function kick self ctx member *args begin if administrator begin set embed = call Embed title=string Error! description=string User has Admin permissions. color=config at string error await call send embed=embed end else begin try begin set reason = join string args await call kick reason=reason set embed = call...
async def kick(self, ctx, member: discord.Member, *args): if member.guild_permissions.administrator: embed = discord.Embed( title="Error!", description="User has Admin permissions.", color=config["error"] ) await ctx.send(embed=...
Python
nomic_cornstack_python_v1
function activate_ruleset arg rulesengine_db=_rulesengine_db begin from src.praxxis.rulesengine import activate_ruleset call activate_ruleset arg rulesengine_db return end function
def activate_ruleset(arg, rulesengine_db=_rulesengine_db): from src.praxxis.rulesengine import activate_ruleset activate_ruleset.activate_ruleset(arg, rulesengine_db) return
Python
nomic_cornstack_python_v1
import urllib.request from selenium import webdriver import time import os function get_taxi_urls driver url begin set all_urls = list print string Initiating driver. get driver url sleep 3 print string Iterating through urls. for a in call find_elements_by_xpath string .//a begin append all_urls call get_attribute st...
import urllib.request from selenium import webdriver import time import os def get_taxi_urls(driver, url): all_urls = [] print('Initiating driver.') driver.get(url) time.sleep(3) print('Iterating through urls.') for a in driver.find_elements_by_xpath('.//a'): all_urls....
Python
zaydzuhri_stack_edu_python
import sys from pathlib import Path import pandas as pd import numpy as np import re append path string parent / string ../.. from torchai.utils import parse_log_record , SequenceCollector function read_log path begin with open as logfile begin set parsed_records = generator expression call parse_log_record record for ...
import sys from pathlib import Path import pandas as pd import numpy as np import re sys.path.append(str((Path(__file__).parent / '../..'))) from torchai.utils import parse_log_record, SequenceCollector def read_log(path: Path) -> pd.DataFrame: with path.open() as logfile: parsed_records = (parse_log_re...
Python
zaydzuhri_stack_edu_python
function is_prime n begin if n <= 1 begin return false end if n == 2 begin return true end if n % 2 == 0 begin return false end set i = 3 while i * i <= n begin if n % i == 0 begin return false end set i = i + 2 end return true end function function find_smallest_prime n begin set num = n + 1 while true begin if call i...
def is_prime(n): if n <= 1: return False if n == 2: return True if n % 2 == 0: return False i = 3 while i * i <= n: if n % i == 0: return False i += 2 return True def find_smallest_prime(n): num = n + 1 while True: if is_prime(...
Python
jtatman_500k
function get_current_player_type self name begin return _dict_of_players at name at 1 end function
def get_current_player_type(self, name): return self._dict_of_players[name][1]
Python
nomic_cornstack_python_v1
function _get_model_list self begin set model_arch_file = join path model_dir model_name + string .prototxt set model_weight_file = join path model_dir model_name + string .caffemodel append filelist model_arch_file append filelist model_weight_file end function
def _get_model_list(self): self.model_arch_file = os.path.join(self.model_dir, self.model_name + '.prototxt') self.model_weight_file = os.path.join(self.model_dir, self.model_name + '.caffemodel') self.filelist.append(self.model_arch_file) self.filelist.append(self.model_weight_file)
Python
nomic_cornstack_python_v1
from django.shortcuts import render , HttpResponse , redirect from models import user from django.contrib import messages function index request begin set context = dict string users all return call render request string tv_show_app/page1.html context end function function display_page2 request begin return call render...
from django.shortcuts import render, HttpResponse, redirect from .models import user from django.contrib import messages def index(request): context = { 'users' : user.objects.all() } return render(request, "tv_show_app/page1.html", context) def display_page2(request): return render(request,"tv...
Python
zaydzuhri_stack_edu_python
import qcc.config function qprint *args **kwargs begin string The lower the priority, the likelier a print is to take place. The default priority is 2, and the verbosity is typically 2; if priority is set to 1, then something _will_ print. if string priority in kwargs begin set priority = pop kwargs string priority end...
import qcc.config def qprint(*args, **kwargs): """ The lower the priority, the likelier a print is to take place. The default priority is 2, and the verbosity is typically 2; if priority is set to 1, then something _will_ print. """ if 'priority' in kwargs: priority = kwargs.pop('p...
Python
zaydzuhri_stack_edu_python
print string Hello world! print strip string Hello world! print split string 1. 2. 3. 4. 5. 6 string . print split string 1 2 3 4 5 6
print(" \tHello world! ") print(" Hello world! ".strip()) print("1. 2. 3. 4. 5. 6".split(". ")) print("1 2 3 4 5 6".split())
Python
zaydzuhri_stack_edu_python
function _truncate_seq_pair tokens_a tokens_b max_length begin comment This is a simple heuristic which will always truncate the longer sequence comment one token at a time. This makes more sense than truncating an equal percent comment of tokens from each, since if one sequence is very short then each token comment th...
def _truncate_seq_pair(tokens_a, tokens_b, max_length): # This is a simple heuristic which will always truncate the longer sequence # one token at a time. This makes more sense than truncating an equal percent # of tokens from each, since if one sequence is very short then each token # that's truncated...
Python
nomic_cornstack_python_v1
for i in range integer input begin set tuple n k1 k2 = map int split input set tuple p1 p2 p3 p4 = map int split input set l = list comprehension - 1 for i in range n for j in range k1 k2 + 1 begin for k in range length l begin if k + 1 % j == 0 begin set l at k = l at k + 1 end end end set s = 0 for j in l begin if j ...
for i in range(int(input())): n, k1, k2 = map(int, input().split()) p1, p2, p3, p4 = map(int, input().split()) l = [-1 for i in range(n)] for j in range(k1, k2 + 1): for k in range(len(l)): if (k + 1) % j == 0: l[k] += 1 s = 0 for j in l: if ...
Python
zaydzuhri_stack_edu_python
from keras import Sequential from keras import layers from keras.preprocessing.text import Tokenizer import pandas as pd from sklearn import preprocessing from sklearn.model_selection import train_test_split from keras.layers import Flatten from keras.layers import Dense from keras.layers.embeddings import Embedding im...
from keras import Sequential from keras import layers from keras.preprocessing.text import Tokenizer import pandas as pd from sklearn import preprocessing from sklearn.model_selection import train_test_split from keras.layers import Flatten from keras.layers import Dense from keras.layers.embeddings import Embedding im...
Python
zaydzuhri_stack_edu_python
function get_intger help_text=string give me a number: begin return integer input help_text end function set age = call get_intger string give me your age: set grade = call get_intger if age < 15 begin print age print string Your age is: + string age end print string you are in grade: + string grade
def get_intger(help_text="give me a number:"): return int(input(help_text)) age = get_intger("give me your age: ") grade = get_intger() if age < 15: print(age) print("Your age is:" + str(age)) print("you are in grade: " + str(grade))
Python
zaydzuhri_stack_edu_python
from enum import Enum import numpy as np import mip import networkx as nx from scipy import optimize import itertools import mip from plotly.subplots import make_subplots from plotly import graph_objects as go import plotly.figure_factory as ff comment fun = pointer to fun e.g. delta_hat_fun_1D comment params = definin...
from enum import Enum import numpy as np import mip import networkx as nx from scipy import optimize import itertools import mip from plotly.subplots import make_subplots from plotly import graph_objects as go import plotly.figure_factory as ff # fun = pointer to fun e.g. delta_hat_fun_1D # params = defining pa...
Python
zaydzuhri_stack_edu_python
function get_backbone begin set backbone = call ResNet50 include_top=false input_shape=list none none 3 set tuple c3_output c4_output c5_output = list comprehension output for layer_name in list string conv3_block4_out string conv4_block6_out string conv5_block3_out return model inputs=list inputs outputs=list c3_outpu...
def get_backbone(): backbone = keras.applications.ResNet50( include_top=False, input_shape=[None, None, 3] ) c3_output, c4_output, c5_output = [ backbone.get_layer(layer_name).output for layer_name in ["conv3_block4_out", "conv4_block6_out", "conv5_block3_out"] ] return keras...
Python
nomic_cornstack_python_v1