code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function get_num_workers begin set tf_config = loads environ at string TF_CONFIG set num_workers = length tf_config at string cluster at string worker return num_workers end function
def get_num_workers(): tf_config = json.loads(os.environ["TF_CONFIG"]) num_workers = len(tf_config["cluster"]["worker"]) return num_workers
Python
nomic_cornstack_python_v1
string This module contains tests for the scheduler. import collections import itertools from typing import Dict , List import pytest from scheduler import Game , Team , create_schedule function create_flattened_schedule team_count return_game begin string Creates a flattened schedule with the given team count. Paramet...
""" This module contains tests for the scheduler. """ import collections import itertools from typing import Dict, List import pytest from scheduler import Game, Team, create_schedule def create_flattened_schedule(team_count: int, return_game: bool) -> List[Game]: """ Creates a flattened schedule with the given...
Python
zaydzuhri_stack_edu_python
function update self values begin if not __show begin return end for tuple index value in enumerate values begin set __bars at index at 0 = value end call __remove_displayed_lines set __lines = call __update_lines write stdout join string __lines flush stdout end function
def update(self, values: List[int]) -> None: if not self.__show: return for index, value in enumerate(values): self.__bars[index][0] = value self.__remove_displayed_lines() self.__lines = self.__update_lines() sys.stdout.write("\n".join(self.__lines)) ...
Python
nomic_cornstack_python_v1
comment ! /usr/bin/python comment -*- coding: utf-8 -*- comment 邮件发送测试 from smtplib import SMTP comment 定义输入函数 function prompt prompt begin return strip call raw_input prompt end function set fromaddr = call prompt string From: set toaddr = split call prompt string To: string ,|\s
#! /usr/bin/python # -*- coding: utf-8 -*- # 邮件发送测试 from smtplib import SMTP # 定义输入函数 def prompt(prompt): return raw_input(prompt).strip() fromaddr = prompt("From: ") toaddr = prompt("To:").split(",|\s")
Python
zaydzuhri_stack_edu_python
from urllib.request import Request , urlopen import ssl set url = string https://www.12306.cn/mormhweb/ set headers = dict string User-Agent string Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36 comment 创建request对象 set request = call Request url headers=head...
from urllib.request import Request,urlopen import ssl url = "https://www.12306.cn/mormhweb/" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36" } #创建request对象 request = Request(url,headers=headers) #请求12306网站的时候,忽略ca认证 context ...
Python
zaydzuhri_stack_edu_python
function get_discount self price begin pass end function
def get_discount(self, price): pass
Python
nomic_cornstack_python_v1
comment Think Python 2nd Edition book_Ch11.Dictionaries_p113 comment Exercise 11.4. If you did Exercise 10.7, you already have a function named has_duplicates that comment takes a list as a parameter and returns True if there is any object that appears more than once in the list. comment Use a dictionary to write a fas...
# Think Python 2nd Edition book_Ch11.Dictionaries_p113 # Exercise 11.4. If you did Exercise 10.7, you already have a function named has_duplicates that # takes a list as a parameter and returns True if there is any object that appears more than once in the list. # Use a dictionary to write a faster, simpler version of...
Python
zaydzuhri_stack_edu_python
async function async_setup_entry hass entry begin comment remove unique_id for beta users if unique_id is not none begin call async_update_entry entry unique_id=none end set pushover_api = call PushoverAPI data at CONF_API_KEY try begin await call async_add_executor_job validate data at CONF_USER_KEY end except tuple B...
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: # remove unique_id for beta users if entry.unique_id is not None: hass.config_entries.async_update_entry(entry, unique_id=None) pushover_api = PushoverAPI(entry.data[CONF_API_KEY]) try: await hass.async_add_e...
Python
nomic_cornstack_python_v1
set x = 384400 set m = input string 請輸入火箭的飛行速度: set y = x / integer m print string 地球飛到月球需要多少分鐘:%6d % y
x = 384400 m = input("請輸入火箭的飛行速度:") y = x / int(m) print("地球飛到月球需要多少分鐘:%6d" % y)
Python
zaydzuhri_stack_edu_python
comment encoding=utf-8 string The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime. There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. How many circular primes are there below one million? comment Runs in 0.56...
#encoding=utf-8 """ The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime. There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. How many circular primes are there below one million? """ #Runs in 0.560243 second...
Python
zaydzuhri_stack_edu_python
comment --------------------------------------------- comment Nathan Saccon (20576843) comment CS 116 Winter 2015 comment Assignment 5 Question 4 (Multiple Of Seven) comment --------------------------------------------- import math import check comment * Multiple of Seven Function * comment mult_of_7(n) Checks if 'n' i...
#--------------------------------------------- # Nathan Saccon (20576843) # CS 116 Winter 2015 # Assignment 5 Question 4 (Multiple Of Seven) #--------------------------------------------- import math import check # * Multiple of Seven Function * # mult_of_7(n) Checks if 'n' is a multiple of 7. # mult_of_7: Nat -> Boo...
Python
zaydzuhri_stack_edu_python
import sys set products = list string ананас string макароны string помидоры string яблоки set new_products = split argv at 1 string , extend products new_products sort products key=str print products string import sys products = ["ананас", "макароны", "помидоры", "яблоки"] # Получаем новые товары. new_products = sys.a...
import sys products = ["ананас", "макароны", "помидоры", "яблоки"] new_products = sys.argv[1].split(", ") products.extend(new_products) products.sort(key=str) print(products) """ import sys products = ["ананас", "макароны", "помидоры", "яблоки"] # Получаем новые товары. new_products = sys.argv[1] # Создаем списо...
Python
zaydzuhri_stack_edu_python
function writeback self key value begin set logger = call getLogger if value at 0 begin comment logger.info("purge key:{0}".format(key)) set filename = call key_to_filename key call imwrite filename value at 1 if hook is not none begin call hook key value at 1 end end end function
def writeback(self, key, value): logger = logging.getLogger() if value[0]: #logger.info("purge key:{0}".format(key)) filename = self.key_to_filename(key) cv2.imwrite(filename, value[1]) if self.hook is not None: self.hook(key, value[1])
Python
nomic_cornstack_python_v1
comment by WW 3-2018 function main begin string main function comment list that contains a list of 26 fruit names set fruits = list try begin comment open file unsorted_fruits.txt in read mode set infile = open string /users/raven/documents/uop/cs-1101/unsorted_fruits.txt string r comment open file sorted_fruits.txt i...
# by WW 3-2018 def main(): """ main function """ #list that contains a list of 26 fruit names fruits = []; try: # open file unsorted_fruits.txt in read mode infile = open("/users/raven/documents/uop/cs-1101/unsorted_fruits.txt", "r") # open file sorted_fruits.tx...
Python
zaydzuhri_stack_edu_python
function _identify_outliers table column_names which factor=1.5 merge=string and begin if is instance table dict begin set table = call DataFrame table end comment True if values are good, False if outliers set indices = ones tuple length column_names length table dtype=bool set indices at tuple slice : : index = fa...
def _identify_outliers( table: pd.DataFrame, column_names: list, which: list, factor: float = 1.5, merge: float = "and", ) -> np.ndarray: if isinstance(table, dict): table = pd.DataFrame(table) # True if values are good, False if outliers indices = np.ones((len(column_names), le...
Python
nomic_cornstack_python_v1
function system_data self begin return get pulumi self string system_data end function
def system_data(self) -> pulumi.Output['outputs.SystemDataResponse']: return pulumi.get(self, "system_data")
Python
nomic_cornstack_python_v1
comment coding=utf-8 import json import urllib.request import time import traceback comment 模拟成浏览器 set headers = dict string Accept string text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 ; string Accept-Encoding string gbk,utf-8,gb2312 ; string Accept-Language string zh-CN,zh;q=0.8 ; string U...
#coding=utf-8 import json import urllib.request import time import traceback #模拟成浏览器 headers={"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "Accept-Encoding":"gbk,utf-8,gb2312", "Accept-Language":"zh-CN,zh;q=0.8", "User-Agent":"Mozilla/5.0(Windows NT 1...
Python
zaydzuhri_stack_edu_python
function __init__ self begin set x = random integer 100 750 set y = 60 set r = 5 end function
def __init__(self): self.x = randint(100, 750) self.y = 60 self.r = 5
Python
nomic_cornstack_python_v1
function interpolate2dStructuredCrossAvg grid mask kernel=15 power=2 begin string ####### usefull if large empty areas need to be filled set vals = call empty shape=4 dtype=dtype set dist = call empty shape=4 dtype=uint16 set weights = call empty shape=4 dtype=float32 set valid = call empty shape=4 dtype=bool return ca...
def interpolate2dStructuredCrossAvg(grid, mask, kernel=15, power=2): ''' ####### usefull if large empty areas need to be filled ''' vals = np.empty(shape=4, dtype=grid.dtype) dist = np.empty(shape=4, dtype=np.uint16) weights = np.empty(shape=4, dtype=np.float32) valid = np.em...
Python
jtatman_500k
function disk self begin return get pulumi self string disk end function
def disk(self) -> pulumi.Input[str]: return pulumi.get(self, "disk")
Python
nomic_cornstack_python_v1
import requests , json , spotipy import spotipy.util as util from spotipy.oauth2 import SpotifyClientCredentials comment Gets track id and track info based on track name using Spotify APIs function getTrack song_name begin set cid = string c191fdd1e95f4383aafa976bf4ec761a set csecret = string 3d39f727fb764ea79a715bdff6...
import requests, json, spotipy import spotipy.util as util from spotipy.oauth2 import SpotifyClientCredentials # Gets track id and track info based on track name using Spotify APIs def getTrack(song_name): cid = "c191fdd1e95f4383aafa976bf4ec761a" csecret = "3d39f727fb764ea79a715bdff69e0d54" client_credentials_...
Python
zaydzuhri_stack_edu_python
from itertools import combinations_with_replacement if __name__ == string __main__ begin set tuple string size = split input string print string print size set comb = list call combinations_with_replacement sorted string integer size comment for i in comb: comment print("".join(i)) print *comb end
from itertools import combinations_with_replacement if __name__ == "__main__": string, size = input().split(" ") print(string) print(size) comb = list(combinations_with_replacement(sorted(string),int(size))) #for i in comb: # print("".join(i)) print(*comb)
Python
zaydzuhri_stack_edu_python
comment La lista está compuesta por diccionarios anidados. Cada diccionario se llamará 'worker' comment <-- DATA es una constante. Cuando usamos una variable en mayusculas significa que no esperamos modificarla. set DATA = list dict string name string Facundo ; string age 72 ; string organization string Platzi ; string...
#La lista está compuesta por diccionarios anidados. Cada diccionario se llamará 'worker' DATA = [ ## <-- DATA es una constante. Cuando usamos una variable en mayusculas significa que no esperamos modificarla. { 'name': 'Facundo', 'age': 72, 'organization': 'Platzi', 'position': 'Te...
Python
zaydzuhri_stack_edu_python
class Node begin function __init__ self val begin set val = val set next = none end function function traverse self begin set node = self while node != none begin print val set node = next end end function function partition node n begin set head = node set tail = none while node != none begin if val < n begin set temp...
class Node: def __init__(self, val): self.val = val self.next = None def traverse(self): node = self while node!=None: print(node.val) node = node.next def partition(node, n): head = node tail = None while node!=None: if node.val < n: temp = node.next node...
Python
zaydzuhri_stack_edu_python
for t in range integer input begin set n = integer input set tuple *a = map int split input set tuple l r = tuple 0 n - 1 while l < n and a at l == 0 begin set l = l + 1 end while r >= 0 and a at r == 0 begin set r = r - 1 end set l = min l n - 1 set r = max 0 r set ans = 0 for i in range l r + 1 begin if a at i == 0 b...
for t in range(int(input())): n = int(input()) *a, = map(int, input().split()) l, r = 0, n-1 while l < n and a[l] == 0: l += 1 while r >= 0 and a[r] == 0: r -= 1 l = min(l, n-1) r = max(0, r) ans = 0 for i in range(l, r+1): if a[i] == 0: ans += 1 ...
Python
zaydzuhri_stack_edu_python
function train_step_disc self z y begin with call GradientTape as tape begin set loss = call Dloss disc_model z y end set gradients = call gradient loss trainable_variables call apply_gradients generator expression tuple g v for tuple g v in zip gradients trainable_variables call log_d_loss loss end function
def train_step_disc(self, z, y): with tf.GradientTape() as tape: loss = Dloss(self.disc_model, z, y) gradients = tape.gradient(loss, self.disc_model.trainable_variables) self.disc_optimizer.apply_gradients( (g, v) for (g,v) in zip(gradients, self.disc_model.trainable_vari...
Python
nomic_cornstack_python_v1
function run self *args **kwargs begin set loop = loop async function runner begin try begin await start self *args keyword kwargs end finally begin await close self end end function try begin call run_until_complete call runner end except KeyboardInterrupt begin info string Received signal to terminate the client and ...
def run(self, *args, **kwargs) -> None: loop = self.loop async def runner(): try: await self.start(*args, **kwargs) finally: await self.close() try: loop.run_until_complete(runner()) except KeyboardInterrupt: ...
Python
nomic_cornstack_python_v1
function _remove self package_name time_out begin set cmd = string sudo yum --color=never -y remove %s % package_name set output_expects = list string \[sudo\] password for .*: string No Packages marked for removal string Removed: set tuple i match = call pexpect_run cmd output_expects time_out if i == 0 begin raise ca...
def _remove(self, package_name, time_out): cmd = "sudo yum --color=never -y remove %s" % package_name output_expects = ['\[sudo\] password for .*:', 'No Packages marked for removal', 'Removed:'] i, match = self.pexpect_run(cmd, output_expe...
Python
nomic_cornstack_python_v1
for a in range 3 1001 begin set hold = list comment kept on testing cap until reached same number twice for n in range 1 2000 begin set rem = a - 1 ^ n + a + 1 ^ n % a ^ 2 append hold rem end append res max hold end
for a in range(3,1001): hold = [] for n in range(1,2000): #kept on testing cap until reached same number twice rem = (((a-1)**n)+((a+1)**n))%(a**2) hold.append(rem) res.append(max(hold))
Python
zaydzuhri_stack_edu_python
function get_user_info credentials begin set user_info_service = call build serviceName=string oauth2 version=string v2 http=call authorize call Http set user_info = none end function
def get_user_info(credentials): user_info_service = build( serviceName='oauth2', version='v2', http=credentials.authorize(httplib2.Http())) user_info = None
Python
nomic_cornstack_python_v1
function inv_transform self points begin return call tensordot horizontal stack list points ones tuple shape at 0 1 s2c tuple 1 1 end function
def inv_transform(self, points): return np.tensordot(np.hstack([points, np.ones((points.shape[0], 1))]), self.s2c, (1, 1))
Python
nomic_cornstack_python_v1
function close self begin return close _http end function
def close(self): return self._http.close()
Python
nomic_cornstack_python_v1
comment continue string se van a imprimir los números pares % modulo % 2 = dividido en 2 todos los números pares % 2, da 0 != 0, es distinto explicación: si contador al dividirlo por 2, el resto de la división es distinto a 0, se salta la vuelta del ciclo, lo que esta debajo de continue no se va a ejecutar ejemplo solo...
# continue """ se van a imprimir los números pares % modulo % 2 = dividido en 2 todos los números pares % 2, da 0 != 0, es distinto explicación: si contador al dividirlo por 2, el resto de la división es distinto a 0, se salta la vuelta del ciclo, lo que esta debajo de continue no se va a ejecutar ejemplo solo va a im...
Python
zaydzuhri_stack_edu_python
import pytest from application.models import User , bcrypt decorator call usefixtures string create_db class TestUser begin string Unit test the User model class function test_new_user self begin string Test the creation of a new User instance 1. Create a non-admin User instance with predefined values 2. Verify the att...
import pytest from application.models import User, bcrypt @pytest.mark.usefixtures('create_db') class TestUser(): """ Unit test the User model class """ def test_new_user(self): """ Test the creation of a new User instance 1. Create a non-admin User instance with predefined v...
Python
zaydzuhri_stack_edu_python
function list self low_key high_key begin set result = list set lca = call lca low_key high_key if lca is not none begin list low_key high_key result end return result end function
def list(self, low_key, high_key): result = [] lca = self.lca(low_key, high_key) if lca is not None: lca.list(low_key, high_key, result) return result
Python
nomic_cornstack_python_v1
string The way we’ll simulate this is to write a function that generates a string that is 28 characters long by choosing random letters from the 26 letters in the alphabet plus the space. We’ll write another function that will score each generated string by comparing the randomly generated string to the goal. A third f...
"""The way we’ll simulate this is to write a function that generates a string that is 28 characters long by choosing random letters from the 26 letters in the alphabet plus the space. We’ll write another function that will score each generated string by comparing the randomly generated string to the goal. A third fun...
Python
zaydzuhri_stack_edu_python
function _parse_progress_line self line begin comment handle comment Counting objects: 4, done. comment Compressing objects: 50% (1/2) comment Compressing objects: 100% (2/2) comment Compressing objects: 100% (2/2), done. comment mypy argues about ternary assignment if is instance line bytes begin set line_str = decode...
def _parse_progress_line(self, line: AnyStr) -> None: # handle # Counting objects: 4, done. # Compressing objects: 50% (1/2) # Compressing objects: 100% (2/2) # Compressing objects: 100% (2/2), done. if isinstance(line, bytes): # mypy argues about ternary assignment ...
Python
nomic_cornstack_python_v1
function print_primes min max begin for num in range min max + 1 begin if num > 1 begin for i in range 2 num begin if num % i == 0 begin break end end for else begin print num end end end end function comment Driver Code set min = 1 set max = 10 call print_primes min max comment Output: comment 2 comment 3 comment 5 co...
def print_primes(min, max): for num in range(min, max+1): if num > 1: for i in range(2, num): if (num % i) == 0: break else: print(num) # Driver Code min = 1 max = 10 print_primes(min, max) # Output: # 2 # 3 # 5 # 7
Python
jtatman_500k
function test_recipes_recipe_id_consume_post self begin pass end function
def test_recipes_recipe_id_consume_post(self): pass
Python
nomic_cornstack_python_v1
function compute_solar_lines self bmap wp_vertices wp_heights wp_times solartype begin comment calculate distances and times set tuple body difftype = solartype set times = list comprehension call datetime_to_jsec _wp_time for _wp_time in wp_times set tuple x y = list zip *wp_vertices set tuple wp_lons wp_lats = call b...
def compute_solar_lines(self, bmap, wp_vertices, wp_heights, wp_times, solartype): # calculate distances and times body, difftype = solartype times = [datetime_to_jsec(_wp_time) for _wp_time in wp_times] x, y = list(zip(*wp_vertices)) wp_lons, wp_lats = bmap(x, y, inverse=True) ...
Python
nomic_cornstack_python_v1
function categorical_crossentropy y_true y_pred from_logits=false label_smoothing=0 axis=- 1 begin set y_pred = call convert_to_tensor_v2_with_dispatch y_pred set y_true = call cast y_true dtype set label_smoothing = call convert_to_tensor_v2_with_dispatch label_smoothing dtype=call floatx function _smooth_labels begin...
def categorical_crossentropy(y_true, y_pred, from_logits=False, label_smoothing=0, axis=-1): y_pred = tensor_conversion.convert_to_tensor_v2_with_dispatch(y_pred) y_true = math_ops.cast(y_true, y_pred...
Python
nomic_cornstack_python_v1
from django.conf import settings from ncclient import manager class Connector begin string 该类实现对纳管设备的NETCONF会话进行管理. connect方发实现会话的建立和保存,返回连接对象. disconnect方法用于关闭已打开的会话. function connect self ip user begin comment 返回连接对象 set m = dict try begin comment 5.使用设备用户连接设备 comment 先判断是否存在会话 comment 获取所有的连接对象 set sessions = SSH_S...
from django.conf import settings from ncclient import manager class Connector: """ 该类实现对纳管设备的NETCONF会话进行管理. connect方发实现会话的建立和保存,返回连接对象. disconnect方法用于关闭已打开的会话. """ def connect(self, ip, user): # 返回连接对象 m = {} try: # 5.使用设备用户连接设备 # 先判断是否存在会话 ...
Python
zaydzuhri_stack_edu_python
while true begin try begin set tuple n m q = list map int split input set matrix = list list 0 * m + 1 set dif_matrix = list comprehension list 0 * m + 2 for _ in range n + 2 function insert x1 y1 x2 y2 c begin set dif_matrix at x1 at y1 = dif_matrix at x1 at y1 + c set dif_matrix at x1 at y2 + 1 = dif_matrix at x1 at ...
while True: try: n, m, q = list(map(int, input().split())) matrix = [[0] * (m + 1)] dif_matrix = [[0] * (m + 2) for _ in range(n + 2)] def insert(x1, y1, x2, y2, c): dif_matrix[x1][y1] += c dif_matrix[x1][y2 + 1] -= c dif_matrix[x2 + 1][y1] -= c ...
Python
zaydzuhri_stack_edu_python
comment test_attr_generic_optional.py comment This should fail. from typing import Optional function f x begin return foo end function comment def test_attr_generic_optional(self): comment codestr = """ comment from typing import Optional comment def f(x: Optional): comment return x.foo comment """ comment with self.as...
# test_attr_generic_optional.py # This should fail. from typing import Optional def f(x: Optional): return x.foo # def test_attr_generic_optional(self): # codestr = """ # from typing import Optional # def f(x: Optional): # return x.foo # """ # with self.assertRaisesRegex( # ...
Python
zaydzuhri_stack_edu_python
import sys , file_mang from classes import CoderMachine , CypherMachine , Gear set PATH_CONFIG = string config-cif-lorenz.txt set WHEELS_NUMBER = 12 function _create_gears configs begin set gears = list for line in configs begin set pins = list extend pins line remove pins string append gears call Gear pins end retur...
import sys, file_mang from classes import CoderMachine, CypherMachine, Gear PATH_CONFIG = "config-cif-lorenz.txt" WHEELS_NUMBER = 12 def _create_gears(configs): gears = [] for line in configs: pins = [] pins.extend(line) pins.remove('\n') gears.append(Gear(pins)) return gears if __name__ == '__main__':...
Python
zaydzuhri_stack_edu_python
comment built-in comment int, float, str, long, complex, bool set x = 1 print decimal x set y = string 0.0 print integer y set z = 3.4243 print string z
# built-in # int, float, str, long, complex, bool x = 1 print(float(x)) y = "0.0" print(int(y)) z = 3.4243 print(str(z))
Python
zaydzuhri_stack_edu_python
string This problem basically for C, C++, Java I tried to do with python but got TL errors. For functionally python is slow then c, c++ from math import sin , cos while true begin try begin set tuple p a b c d n = map int split input set max_decline = 0 set temp_max = p * sin a + b + cos c + d + 2 for i in range 2 n + ...
'''This problem basically for C, C++, Java I tried to do with python but got TL errors. For functionally python is slow then c, c++''' from math import sin, cos while True: try: p, a, b, c, d, n = map(int, input().split()) max_decline = 0 temp_max = p*( sin(a + b) + cos(c + d ) + 2) ...
Python
zaydzuhri_stack_edu_python
function test_intersect_volume self begin set intersect_shape = call ExtrudeCircleShape points=list tuple 30 0 radius=5 distance=50 set intersected_shape = call ExtrudeCircleShape points=list tuple 30 0 radius=10 distance=50 intersect=list test_shape intersect_shape assert call volume == approx pi * 5 ^ 2 * 30 end func...
def test_intersect_volume(self): intersect_shape = ExtrudeCircleShape(points=[(30, 0)], radius=5, distance=50) intersected_shape = ExtrudeCircleShape( points=[(30, 0)], radius=10, distance=50, intersect=[self.test_shape, intersect_shape], ) ...
Python
nomic_cornstack_python_v1
function load_trie counts begin if exists path string words_trie.marisa begin set trie = call Trie load trie string words_trie.marisa end else begin set trie = call Trie keys counts save string words_trie.marisa end return trie end function
def load_trie(counts): if os.path.exists('words_trie.marisa'): trie = marisa_trie.Trie() trie.load('words_trie.marisa') else: trie = marisa_trie.Trie(counts.keys()) trie.save('words_trie.marisa') return trie
Python
nomic_cornstack_python_v1
function overprovision self begin return get pulumi self string overprovision end function
def overprovision(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "overprovision")
Python
nomic_cornstack_python_v1
import csv from lxml import etree import re import scraperwiki from StringIO import StringIO from urllib import urlencode comment code inspired by https://scraperwiki.com/scrapers/dbpedia-us-hospitals/edit/ comment code build using yql library doesn't seem to work, get a SSLHandshakeError when using code based on https...
import csv from lxml import etree import re import scraperwiki from StringIO import StringIO from urllib import urlencode #code inspired by https://scraperwiki.com/scrapers/dbpedia-us-hospitals/edit/ #code build using yql library doesn't seem to work, get a SSLHandshakeError when using code based on https://scraperwik...
Python
zaydzuhri_stack_edu_python
comment THIS EXAMPLE IS USING THE DRIVER MENTIONED ON a SYSTEM VARIABLE, NOT ON THE CODE. comment importing selenium webdriver from selenium import webdriver import os comment CLASE class PruebaFF begin comment METODO function FF_Method self begin set driver = call Firefox get driver string http://www.letskodeit.com cl...
#THIS EXAMPLE IS USING THE DRIVER MENTIONED ON a SYSTEM VARIABLE, NOT ON THE CODE. from selenium import webdriver #importing selenium webdriver import os class PruebaFF(): #CLASE def FF_Method(self): #METODO driver = webdriver.Firefox() driver.get("http://www.letskodeit.com") driver.close(...
Python
zaydzuhri_stack_edu_python
string Unit tests for binary_search_tree import unittest import binary_search_tree class BSTNodeTestCase extends TestCase begin function setUp self begin set SUT = call BSTNode 7 end function function tearDown self begin set SUT = none end function function test_value_set self begin assert equal val 7 end function end ...
""" Unit tests for binary_search_tree """ import unittest import binary_search_tree class BSTNodeTestCase(unittest.TestCase): def setUp(self): self.SUT = binary_search_tree.BSTNode(7) def tearDown(self): self.SUT = None def test_value_set(self): self.assertEqual(self.SUT.val, 7)...
Python
zaydzuhri_stack_edu_python
function student id name grade *marks begin string print(f"ID : {id}") print(f"Name : {name}") print(f"Grade : {grade}") print(f"Marks : {marks}") print string Report Card for Stduent : { id } print string Hello { name } print string Your marks : { marks } set avg = sum marks / length marks print string Your average ma...
def student(id,name,grade,*marks): ''' print(f"ID : {id}") print(f"Name : {name}") print(f"Grade : {grade}") print(f"Marks : {marks}") ''' print(f"Report Card for Stduent : {id}") print(f"Hello {name}") print(f"Your marks : {marks}") avg = sum(marks) / len(marks) p...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import numpy as np , cv from freenect import sync_get_video as get_video , sync_get_depth as get_depth function cv2array im begin set depth2dtype = dict IPL_DEPTH_8U string uint8 ; IPL_DEPTH_8S string int8 ; IPL_DEPTH_16U string uint16 ; IPL_DEPTH_16S string int16 ; IPL_DEPTH_32S string int...
#!/usr/bin/env python import numpy as np, cv from freenect import sync_get_video as get_video, sync_get_depth as get_depth def cv2array(im): depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPT...
Python
zaydzuhri_stack_edu_python
function delete_operations self print_operation_id if_match=none **kwargs begin comment type: str comment type: Optional[str] comment type: Any comment type: (...) -> None comment type: ClsType[None] set cls = pop kwargs string cls none set error_map = dict 401 ClientAuthenticationError ; 404 ResourceNotFoundError ; 40...
def delete_operations( self, print_operation_id, # type: str if_match=None, # type: Optional[str] **kwargs # type: Any ): # type: (...) -> None cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 40...
Python
nomic_cornstack_python_v1
function __init__ self jars_dir mongo_host mongo_db mongo_type_db auth_url root_temp_dir mongo_user=none mongo_pwd=none begin call _check_params jars_dir mongo_host mongo_db mongo_type_db auth_url root_temp_dir mongo_user mongo_pwd set _db = mongo_db set jars_dir = call resolve set class_path = call _get_class_path jar...
def __init__( self, jars_dir: _Path, mongo_host: str, mongo_db: str, mongo_type_db: str, auth_url: str, root_temp_dir: _Path, mongo_user: str = None, mongo_pwd: str = None, ): self._check_params( jars_dir, mongo_...
Python
nomic_cornstack_python_v1
function main num_trials num_actions begin for i in call xrange integer num_trials begin call trial i + 1 integer num_actions end end function
def main(num_trials, num_actions): for i in xrange(int(num_trials)): trial(i+1, int(num_actions))
Python
nomic_cornstack_python_v1
function configure_action request begin set required_fields = set list string action_provider if not call issubset POST begin return call render request string error.html dict string error string Invalid Parameters in POST end set provider_name = POST at string action_provider set action_options = call get_options_for_...
def configure_action(request): required_fields = set(["action_provider"]) if not required_fields.issubset(request.POST): return render(request, "error.html", {"error": "Invalid Parameters in POST"}) provider_name = request.POST["action_provider"] action_options = action_provider.get_options_fo...
Python
nomic_cornstack_python_v1
function parse_cli begin from argparse import ArgumentParser , ArgumentDefaultsHelpFormatter set p = call ArgumentParser description=string Generate disp.dat data from an ls-dyna nodout file. formatter_class=ArgumentDefaultsHelpFormatter call add_argument string --nodout help=string ASCII file containing nodout data de...
def parse_cli(): from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter p = ArgumentParser(description="Generate disp.dat " "data from an ls-dyna nodout file.", formatter_class=ArgumentDefaultsHelpFormatter) p.add_argument("--nodout", ...
Python
nomic_cornstack_python_v1
function _concat_char_vector self encode words begin set return_encode = array list for tuple i vec_list word_list in zip range length encode encode words begin for tuple j vec word in zip range length vec_list vec_list word_list begin set word = if expression length word > char_max_len then word at slice : char_max_l...
def _concat_char_vector(self, encode, words): return_encode = np.array([]) for i, vec_list, word_list in zip(range(len(encode)), encode, words) : for j, vec, word in zip(range(len(vec_list)), vec_list, word_list) : word = word[:self.char_max_len-1] if len(word) > self.char_ma...
Python
nomic_cornstack_python_v1
if diasParaEntrega >= 0 and diasParaEntrega <= 6 begin if diasParaEntrega == 0 begin print string chega hoje! end else begin for x in range call __len__ begin if dia at x == diaDaCompra begin set diaAtual = x end end while diasParaEntrega > 0 begin set diaAtual = diaAtual + 1 set diasParaEntrega = diasParaEntrega - 1 i...
if diasParaEntrega >= 0 and diasParaEntrega <= 6: if diasParaEntrega == 0: print('chega hoje!') else: for x in range(dia.__len__()): if dia[x] == diaDaCompra: diaAtual = x while diasParaEntrega > 0: diaAtual = diaAtual + 1 diasParaEn...
Python
zaydzuhri_stack_edu_python
function test_database self begin set review = call Review project=new_project user=new_user design=7 usability=6 content=5 comment=string This is a nice website. save set reviews = all assert true length reviews > 0 end function
def test_database(self): review = Review(project=self.new_project, user=self.new_user, design=7, usability=6, content=5, comment="This is a nice website.") review.save() reviews = Review.objects.all() self.assertTrue(len(reviews) > 0)
Python
nomic_cornstack_python_v1
function get_largest_sum nums begin sort nums return nums at - 1 + nums at - 2 end function
def get_largest_sum(nums): nums.sort() return nums[-1] + nums[-2]
Python
jtatman_500k
class DatabaseConnection begin function __init__ self begin set conn = call connect host=string localhost database=string mydb end function function __del__ self begin close conn end function end class
class DatabaseConnection: def __init__(self): self.conn = psycopg2.connect(host="localhost", database="mydb") def __del__(self): self.conn.close()
Python
flytech_python_25k
from typing import * class Solution begin function generate self numRows begin comment if numRows == 0: comment return [] comment res = [[1]] comment for i in range(numRows - 1): comment prev = res[-1] comment curr_level = [] comment curr_level.append(1) comment for i in range(len(prev)-1): comment curr_level.append(pr...
from typing import * class Solution: def generate(self, numRows: int) -> List[List[int]]: # if numRows == 0: # return [] # res = [[1]] # for i in range(numRows - 1): # prev = res[-1] # curr_level = [] # curr_level.append(1) # for i in range(len(prev)-1): ...
Python
zaydzuhri_stack_edu_python
function calculate_direction raw_route begin set tuple start end err = call parse_route raw_route if err is not none begin return tuple err none end set diff = dict string longitude end at string longitude - start at string longitude ; string latitude end at string latitude - start at string latitude set tuple angle er...
def calculate_direction(raw_route): start, end, err = parse_route(raw_route) if err is not None: return err, None diff = { 'longitude': end['longitude'] - start['longitude'], 'latitude': end['latitude'] - start['latitude']} angle, err = vector_angle_to_north(diff) if err is n...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Tue Jul 12 09:37:51 2016 @author: student import hashlib function md5 fname begin set hash_md5 = md5 with open fname string rb as f begin for chunk in iterate lambda -> read f 4096 b'' begin update hash_md5 chunk end end return hex digest hash_md5 end function print md5 ...
# -*- coding: utf-8 -*- """ Created on Tue Jul 12 09:37:51 2016 @author: student """ import hashlib def md5(fname): hash_md5 = hashlib.md5() with open(fname, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) return hash_md5.hexdigest() print(md5("faceboo...
Python
zaydzuhri_stack_edu_python
comment 문제 설명 : 차들이 같은 방향으로 다른 속도로 움직임. 충돌하면 하나로 합쳐져서 느린 차의 속도로 움직임 comment 충돌하게 되는 시간을 구하라. comment 오른쪽에서 시작해서 이웃된 노드를 기준으로 구해나가면됨. comment 현재 차의 속도는 이전차와는 무관함. 자기가 부딪히는 차와만 관련이 있음. comment 다음차가 그 다음차와 먼저 부딪혀버리면 시간 계산이 그 다음차를 기준으로 되어야함. comment 충돌 시간이 작아지는 순서대로 index에 대한 스택을 쌓음. 뒷부분 차들의 더 짧은 충돌시간은 고려할 필요 없음. comment 충...
# 문제 설명 : 차들이 같은 방향으로 다른 속도로 움직임. 충돌하면 하나로 합쳐져서 느린 차의 속도로 움직임 # 충돌하게 되는 시간을 구하라. # 오른쪽에서 시작해서 이웃된 노드를 기준으로 구해나가면됨. # 현재 차의 속도는 이전차와는 무관함. 자기가 부딪히는 차와만 관련이 있음. # 다음차가 그 다음차와 먼저 부딪혀버리면 시간 계산이 그 다음차를 기준으로 되어야함. # 충돌 시간이 작아지는 순서대로 index에 대한 스택을 쌓음. 뒷부분 차들의 더 짧은 충돌시간은 고려할 필요 없음. # 충돌 시간을 고려할때 각 뒷차에서의 충돌시간을 고려하고 점점 커지는 순서대...
Python
zaydzuhri_stack_edu_python
comment 부모클래스 comment 자식의 생성자 정의시 부모의 생성자를 super()로 명시적으로 호출하지 않으면 comment 부모 생성자는 호출되지 않는다 comment 즉 부모의 생성자를 호출하여 부모의 속성을 초기화 하려면 반드시 comment super().__init__()를 호출해 해야 한다 class Person begin function __init__ self name age begin print string 부모의 __init__()메소드(생성자) set name = name set age = age end function function e...
#부모클래스 #자식의 생성자 정의시 부모의 생성자를 super()로 명시적으로 호출하지 않으면 #부모 생성자는 호출되지 않는다 #즉 부모의 생성자를 호출하여 부모의 속성을 초기화 하려면 반드시 #super().__init__()를 호출해 해야 한다 class Person: def __init__(self,name,age): print('부모의 __init__()메소드(생성자)') self.name = name self.age=age def eat(self): print(self...
Python
zaydzuhri_stack_edu_python
function plot_food_over_time result num_epochs=4 begin set res_dict = call res_to_dict result set food = res_dict at string food set epochs = list comprehension i + 1 * length food // num_epochs for i in range num_epochs for e in epochs begin plot food at tuple e - 1 0 slice : : end legend epochs show pass end functi...
def plot_food_over_time(result, num_epochs=4): res_dict = res_to_dict(result) food = res_dict["food"] epochs = [(i + 1) * len(food) // num_epochs for i in range(num_epochs)] for e in epochs: plt.plot(food[e - 1, 0, :]) plt.legend(epochs) plt.show() pass
Python
nomic_cornstack_python_v1
function define_tuner_hparam_space hparam_space_type begin if hparam_space_type not in tuple string pg string pg-topk string topk string is begin raise call ValueError string Hparam space is not valid: "%s" % hparam_space_type end comment Discrete hparam space is stored as a dict from hparam name to discrete comment va...
def define_tuner_hparam_space(hparam_space_type): if hparam_space_type not in ('pg', 'pg-topk', 'topk', 'is'): raise ValueError('Hparam space is not valid: "%s"' % hparam_space_type) # Discrete hparam space is stored as a dict from hparam name to discrete # values. hparam_space = {} if hparam_space_type...
Python
nomic_cornstack_python_v1
class Solution begin function numTrees self n begin comment Intuition: comment - For each n we try to build BST with node i from 1 -> n as root node comment - If n = 0 or 1 then only 1 way to form a BST tree comment - For each i we have i - 1 nodes on left subtree and n - i nodes on right subtree comment - The result i...
class Solution: def numTrees(self, n: int) -> int: # Intuition: # - For each n we try to build BST with node i from 1 -> n as root node # - If n = 0 or 1 then only 1 way to form a BST tree # - For each i we have i - 1 nodes on left subtree and n - i nodes on right subtree ...
Python
zaydzuhri_stack_edu_python
import datetime import functions import re import task function find_by_date begin comment Get data from csv file set data = call entry_reader comment Use a set to get unique dates comment Convert to list for indexing set date_list = list set generator expression val at string date for val in data sort date_list set me...
import datetime import functions import re import task def find_by_date(): # Get data from csv file data = task.entry_reader() # Use a set to get unique dates # Convert to list for indexing date_list = list(set(val['date'] for val in data)) date_list.sort() menu_dates = functions.menu( ...
Python
zaydzuhri_stack_edu_python
function servers self begin set response = call _request string GET list ROUTE_SERVERS return call parse_response CBWServer response end function
def servers(self): response = self._request("GET", [ROUTE_SERVERS]) return CBWParser().parse_response(CBWServer, response)
Python
nomic_cornstack_python_v1
function map self begin return call map_digis group end function
def map(self): return self.map_digis(self.group)
Python
nomic_cornstack_python_v1
function __create_at_job self command detail=string begin set started = integer time set logfile = _current_job at string logfile set lines = _current_job at string lines set script = string #:started: %s #:detail: %s #:logfile: %s #:lines: %s #:command: %s /usr/share/univention-updater/disable-apache2-umc %s < /dev/nu...
def __create_at_job(self, command, detail=''): started = int(time()) logfile = self._current_job['logfile'] lines = self._current_job['lines'] script = ''' #:started: %s #:detail: %s #:logfile: %s #:lines: %s #:command: %s /usr/share/univention-updater/disable-apache2-umc %s < /dev/null /usr/share/univention-up...
Python
nomic_cornstack_python_v1
import os import requests from bs4 import BeautifulSoup from svglib.svglib import svg2rlg from reportlab.graphics import renderPDF from PyPDF2 import PdfFileReader , PdfFileWriter import time from PIL import Image import getpass string Скачивание книг с сайта https://urait.ru/ set email = input string Твой логин (email...
import os import requests from bs4 import BeautifulSoup from svglib.svglib import svg2rlg from reportlab.graphics import renderPDF from PyPDF2 import PdfFileReader, PdfFileWriter import time from PIL import Image import getpass ''' Скачивание книг с сайта https://urait.ru/ ''' email = input('Твой логин (email): ') pa...
Python
zaydzuhri_stack_edu_python
function getFilenamesAndGuid thisfile begin set pfn = string call getAttribute string name set filename = base name path pfn end function
def getFilenamesAndGuid(thisfile): pfn = str(thisfile.getElementsByTagName("pfn")[0].getAttribute("name")) filename = os.path.basename(pfn)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 import wx from pathlib import Path import os import fileinput class main_window extends Frame begin function __init__ self *args **kwds begin comment begin wxGlade: main_window.__init__ set kwds at string style = get kwds string style 0 ? DEFAULT_FRAME_STYLE call __init__ self *args keywor...
#!/usr/bin/env python3 import wx from pathlib import Path import os import fileinput class main_window(wx.Frame): def __init__(self, *args, **kwds): # begin wxGlade: main_window.__init__ kwds["style"] = kwds.get("style", 0) | wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) ...
Python
zaydzuhri_stack_edu_python
import pickle set imelda = tuple string More Mayhem string IMelda May string 2011 tuple tuple 1 string Pulling the Rug tuple 2 string Psycho tuple 3 string Mayhem tuple 4 string Kentish Town Waltz comment Write a binary file using pickle comment with open("imelda.pickle", "wb") as pickle_file: comment pickle.dump(imeld...
import pickle imelda = ('More Mayhem', 'IMelda May', '2011', ((1, 'Pulling the Rug'), (2, 'Psycho'), (3, 'Mayhem'), (4, 'Kentish Town Waltz'))) # Write a binary file using pickle # with open("imelda.pickle", "wb") as pickle_file: # pickle.dump(imelda...
Python
zaydzuhri_stack_edu_python
function test_set_data begin from linked_list import Node set test_node = call Node data at 0 call set_data data at 1 assert data == data at 1 end function
def test_set_data(): from linked_list import Node test_node = Node(data[0]) test_node.set_data(data[1]) assert test_node.data == data[1]
Python
nomic_cornstack_python_v1
function _get_sz_info self begin if string None == _state begin return none end set cmd = string show virtual-service detail name guestshell+ set got = call cli cmd set got = got at string TABLE_detail at string ROW_detail set sz_cpu = integer got at string cpu_reservation set sz_disk = integer got at string disk_reser...
def _get_sz_info(self): if 'None' == self._state: return None cmd = 'show virtual-service detail name guestshell+' got = self.cli(cmd) got = got['TABLE_detail']['ROW_detail'] sz_cpu = int(got['cpu_reservation']) sz_disk = int(got['disk_reservation']) ...
Python
nomic_cornstack_python_v1
import pandas as pd from sklearn.linear_model import LogisticRegression comment load the data set data = read csv string data.csv comment create the training and test set set X = data at list string x1 string x2 set y = data at string y comment train the model set model = logistic regression fit model X y comment make ...
import pandas as pd from sklearn.linear_model import LogisticRegression # load the data data = pd.read_csv('data.csv') # create the training and test set X = data[['x1', 'x2']] y = data['y'] # train the model model = LogisticRegression() model.fit(X, y) # make predictions preds = model.predict(X) # check accuracy ...
Python
jtatman_500k
function session_ended_request_handler handler_input begin comment type: (HandlerInput) -> Response info format string Session ended with reason: {} reason return response end function
def session_ended_request_handler(handler_input): # type: (HandlerInput) -> Response logger.info( "Session ended with reason: {}".format( handler_input.request_envelope.request.reason)) return handler_input.response_builder.response
Python
nomic_cornstack_python_v1
function recreate_dataset f name newf callback=none begin if is instance f VersionedHDF5File begin set f = f end set raw_data = f at string _version_data at name at string raw_data set dtype = dtype set chunks = chunks set compression = compression set compression_opts = compression_opts set fillvalue = fillvalue set f...
def recreate_dataset(f, name, newf, callback=None): if isinstance(f, VersionedHDF5File): f = f.f raw_data = f['_version_data'][name]['raw_data'] dtype = raw_data.dtype chunks = raw_data.chunks compression = raw_data.compression compression_opts = raw_data.compression_opts fillvalue...
Python
nomic_cornstack_python_v1
function movePage self pno to=- 1 begin if isClosed begin raise call ValueError string document closed end set pageCount = length self if pno not in range pageCount or to not in range - 1 pageCount begin raise call ValueError string bad page number(s) end set before = 1 set copy = 0 if to == - 1 begin set to = pageCoun...
def movePage(self, pno, to = -1): if self.isClosed: raise ValueError("document closed") pageCount = len(self) if ( pno not in range(pageCount) or to not in range(-1, pageCount) ): raise ValueError("bad page number(s)") before = ...
Python
nomic_cornstack_python_v1
function disable_post sender instance **kwargs begin set post = post if count reports > 2 begin call disable_view end end function
def disable_post(sender, instance, **kwargs): post = instance.post if post.reports.count() > 2: post.disable_view()
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- string 002_display_fps.py Open a Pygame window and display framerate. Program terminates by pressing the ESCAPE-Key. works with python2.7 and python3.4 URL : http://thepythongamebook.com/en:part2:pygame:step002 Author : horst.jens@spielend-programmieren.at Lice...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 002_display_fps.py Open a Pygame window and display framerate. Program terminates by pressing the ESCAPE-Key. works with python2.7 and python3.4 URL : http://thepythongamebook.com/en:part2:pygame:step002 Author : horst.jens@spielend-programmieren.at License: GP...
Python
zaydzuhri_stack_edu_python
from sys import argv comment unpacking of command line arguments set tuple script user_name = argv set prompt = string >
from sys import argv #unpacking of command line arguments script,user_name=argv prompt='>'
Python
zaydzuhri_stack_edu_python
string Your goal in this kata is to create complete the mouth_size method this method take one argument animal which corresponds to the animal encountered by frog. If this one is an alligator (case insensitive) return small otherwise return wide. function mouth_size animal begin return if expression lower animal == str...
"""Your goal in this kata is to create complete the mouth_size method this method take one argument animal which corresponds to the animal encountered by frog. If this one is an alligator (case insensitive) return small otherwise return wide.""" def mouth_size(animal): return "small" if animal.lower() == "alligato...
Python
zaydzuhri_stack_edu_python
from flask.json import jsonify function check result begin comment isalpha() returns True if all characters in the string are alphabets if is alpha result begin return call jsonify dict string result string sanitized end else begin return call jsonify dict string result string unsanitized end end function
from flask.json import jsonify def check(result): if result.isalpha(): #isalpha() returns True if all characters in the string are alphabets return jsonify({'result':'sanitized'}) else: return jsonify({'result':'unsanitized'})
Python
zaydzuhri_stack_edu_python
function frobenius self value begin return sum call hadamard value end function
def frobenius(self, value): return sum(self.hadamard(value))
Python
nomic_cornstack_python_v1
comment print(f.read()) comment for line in f: comment print(line.replace('\n', '')) # Убираем знак переноса строки
# print(f.read()) # for line in f: # print(line.replace('\n', '')) # Убираем знак переноса строки
Python
zaydzuhri_stack_edu_python
import cv2 as cv import numpy as np comment Canny Edge Detector Which Takes An Input Image With Guassian Blur Applied function myCannyEdgeDetectionAlgo image begin set img = call asarray image dtype=float32 set tuple rows cols = shape set edgeGradient = zeros tuple rows - 1 cols - 1 dtype=float32 set angle = zeros tupl...
import cv2 as cv import numpy as np #Canny Edge Detector Which Takes An Input Image With Guassian Blur Applied def myCannyEdgeDetectionAlgo(image): img = np.asarray(image, dtype= np.float32) rows, cols = img.shape edgeGradient = np.zeros((rows-1, cols-1), dtype = np.float32) angle = np.ze...
Python
zaydzuhri_stack_edu_python
function getInstanceData self uid begin set obj = call _getObject uid set inst = list dict string id id ; string uid uid ; string eventClass id ; string eventClassKey eventClassKey ; string rule rule ; string regex regex ; string sequence sequence ; string evaluation explanation ; string example example ; string resolu...
def getInstanceData(self, uid): obj = self._getObject(uid) inst = [{ 'id':obj.id, 'uid':uid, 'eventClass':obj.eventClass().id, 'eventClassKey':obj.eventClassKey, 'rule':obj.rule, 'regex':obj.regex, 'sequence':obj.sequenc...
Python
nomic_cornstack_python_v1
function get_folder self link begin set match = search string /jd(\d{2}) link set directory = call group 1 comment ignore misformated links if directory in allowed begin return directory end else begin return none end end function
def get_folder(self, link): match = re.search("/jd(\d{2})", link) directory = match.group(1) if directory in self.allowed: #ignore misformated links return directory else: return None
Python
nomic_cornstack_python_v1
function __init__ self env mem net args rng name begin debug string Initialize object of type + string __name__ set name = name set env = env set mem = mem set net = net set rng = rng set n_steps_total = 0 set phase = none set callback = none end function
def __init__(self, env, mem, net, args, rng, name): _logger.debug("Initialize object of type " + str(type(self).__name__)) self.name = name self.env = env self.mem = mem self.net = net self.rng = rng self.n_steps_total = 0 self.phase = None self.ca...
Python
nomic_cornstack_python_v1
comment Generating evens using a list comprehension: function generate_evens begin return list comprehension x for x in range 1 50 if x % 2 == 0 end function comment Generating evens using a loop: function generate_evens begin set result = list for x in range 1 50 begin if x % 2 == 0 begin append result x end end retu...
# Generating evens using a list comprehension: def generate_evens(): return [x for x in range(1,50) if x%2 == 0] # Generating evens using a loop: def generate_evens(): result = [] for x in range(1,50): if x % 2 == 0: result.append(x) return result
Python
zaydzuhri_stack_edu_python
function CombineManifests src dest begin comment grab the sequences from the src and append to dest. if src is none begin raise call InternalError string Attempt to combine from a null manifest. end if dest is none begin raise call InternalError string Attempt to combine to a null manifest. end append image_sequences i...
def CombineManifests(src, dest): # grab the sequences from the src and append to dest. if src is None: raise errors.InternalError( "Attempt to combine from a null manifest.") if dest is None: raise errors.InternalError( "Attempt to combine to a null manifest.") dest.image_sequenc...
Python
nomic_cornstack_python_v1