code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment implementation of user based recommnder system import pandas as pd import math comment we have imported few packages which include pandas and math. pandas for reading the data, math for the square root function comment review = pd.read_csv(r"C:\\Users\\Devi Prajwala B S\\Downloads\\recommenders\\recommender_sys...
# implementation of user based recommnder system import pandas as pd import math #we have imported few packages which include pandas and math. pandas for reading the data, math for the square root function #review = pd.read_csv(r"C:\\Users\\Devi Prajwala B S\\Downloads\\recommenders\\recommender_systems\\googl...
Python
zaydzuhri_stack_edu_python
function func3 thing1 thing2 begin print string Life is pain. Anyone who says differently is selling something. print string Oh also, { thing1 } and { thing2 } set a = 1.23423523452345 plot a b label=string { a } set str1 = format string {:.2f} {:.3f} a b end function
def func3(thing1, thing2): print("Life is pain. Anyone who says differently is selling something.") print(f"Oh also, {thing1} and {thing2}") a = 1.23423523452345 plt.plot(a, b, label=f"{a:.2f}") str1 = "{:.2f} {:.3f}".format(a, b)
Python
nomic_cornstack_python_v1
function IsPolyMesh3DSolid begin pass end function
def IsPolyMesh3DSolid(): pass
Python
nomic_cornstack_python_v1
function read_all_nodes_containing value=string begin global _graph if _graph is none begin print string read_all_nodes_containing(): Error: graph has not been initialized or opened. return none end set lvalue = string value if lvalue == string nan begin return none end if lvalue == string begin return none end set no...
def read_all_nodes_containing(value: str = '') -> Union[NodeMatch, None]: global _graph if _graph is None: print('\nread_all_nodes_containing(): Error: graph has not been initialized or opened.\n\n') return None lvalue = str(value) if lvalue == 'nan': return None if lvalue ...
Python
nomic_cornstack_python_v1
function sample_create_tenant project_id external_id begin set client = call TenantServiceClient comment project_id = 'Your Google Cloud Project ID' comment external_id = 'Your Unique Identifier for Tenant' if is instance project_id binary_type begin set project_id = decode project_id string utf-8 end if is instance ex...
def sample_create_tenant(project_id, external_id): client = talent_v4beta1.TenantServiceClient() # project_id = 'Your Google Cloud Project ID' # external_id = 'Your Unique Identifier for Tenant' if isinstance(project_id, six.binary_type): project_id = project_id.decode('utf-8') if isinsta...
Python
nomic_cornstack_python_v1
comment coding : utf8 comment Author : taosenlin comment Time : 2020/3/19 11:56 comment 一、正则表达式的概述 (一套规则,不限于语法或工具) comment 对于复杂、无规则的字符串进行操作(提取) comment 二、正则表达式的作用 comment 1、主要是针对字符串进行操作,可以简化对字符串的复杂操作 comment (1)匹配:检查字符串是否符合正则表达式中的规则 comment (2)切割:按一定的规则将字符串分割成多个子字符串 comment (3)替换:将字符串中符合规则的字符替换成指定字符 comment (4)获取:获取与规格...
#coding : utf8 #Author : taosenlin #Time : 2020/3/19 11:56 # 一、正则表达式的概述 (一套规则,不限于语法或工具) # 对于复杂、无规则的字符串进行操作(提取) # 二、正则表达式的作用 # 1、主要是针对字符串进行操作,可以简化对字符串的复杂操作 ### (1)匹配:检查字符串是否符合正则表达式中的规则 # (2)切割:按一定的规则将字符串分割成多个子字符串 # (3)替换:将字符串中符合规则的字符替换成指定字符 ### (4)获取:获取与规格相符的字符串 # 三、实用语法 # 1、通配符 . # 可以匹配任何除换行符 "\n" 外的字符 # 例: # 待...
Python
zaydzuhri_stack_edu_python
comment 2020.01.06 string acmicpc.net/problem/1924 문제집 : 백준에서 가장 많이 풀린 문제 TOP 100 (입문자 추천) - njw1204 문제: 오늘은 2007년 1월 1일 월요일이다. 그렇다면 2007년 x월 y일은 무슨 요일일까? 이를 알아내는 프로그램을 작성하시오. 입력: 첫째 줄에 빈 칸을 사이에 두고 x(1<=x<=12)와 y(1<=y<=31)이 주어진다. 참고로 2007년에는 1, 3, 5, 7, 8, 10, 12월은 31일까지, 4, 6, 9, 11월은 30일까지, 2월은 28일까지 있다. 출력: 첫째 줄에 x월...
# 2020.01.06 """ acmicpc.net/problem/1924 문제집 : 백준에서 가장 많이 풀린 문제 TOP 100 (입문자 추천) - njw1204 문제: 오늘은 2007년 1월 1일 월요일이다. 그렇다면 2007년 x월 y일은 무슨 요일일까? 이를 알아내는 프로그램을 작성하시오. 입력: 첫째 줄에 빈 칸을 사이에 두고 x(1<=x<=12)와 y(1<=y<=31)이 주어진다. 참고로 2007년에는 1, 3, 5, 7, 8, 10, 12월은 31일까지, 4, 6, 9, 11월은 30일까지, 2월은 28일까지 있다. 출력: 첫째 줄에 x월 ...
Python
zaydzuhri_stack_edu_python
function _rotate_right self node heavy_child begin set parent = parent set left = right update node set parent = parent set right = node update heavy_child comment Update parent pointers (if any) if parent begin call add_child heavy_child end else begin set root = heavy_child end end function
def _rotate_right(self, node, heavy_child): parent = node.parent node.left = heavy_child.right node.update() heavy_child.parent = parent heavy_child.right = node heavy_child.update() # Update parent pointers (if any) if parent: parent.add_ch...
Python
nomic_cornstack_python_v1
function low_threshold_multiplier threshold low begin if threshold == 1 begin return low * 1.5 end if threshold <= 5 begin set factor = 6 set multiplier = 11 - threshold / factor / 10 + 1 set low = low * multiplier end return low end function
def low_threshold_multiplier(threshold, low): if threshold == 1: return low * 1.5 if threshold <= 5: factor = 6 multiplier = (((11 - threshold) / factor) / 10) + 1 low = low * multiplier return low
Python
nomic_cornstack_python_v1
import util import json string This document includes all the methods related in Robert's Coffee. The methods take their information from the pre-written json document roberts_coffee.json. set data = load json open string tests/roberts_coffee.json string Intro guides the user and tells what categories there are to choo...
import util import json """ This document includes all the methods related in Robert's Coffee. The methods take their information from the pre-written json document roberts_coffee.json. """ data = json.load(open('tests/roberts_coffee.json')) """ Intro guides the user and tells what categories there are to choose from...
Python
zaydzuhri_stack_edu_python
function testFilePathMatchAfterFileRename self begin set feature = call TouchCrashedDirectoryBaseFeature options=dict string replace_path dict string old/dir string new/dir assert true match call CrashedDirectory string new/dir/a call FileChangeInfo MODIFY string old/dir/a/FileName.cc string old/dir/a/FileName.cc end f...
def testFilePathMatchAfterFileRename(self): feature = TouchCrashedDirectoryBaseFeature( options={'replace_path': {'old/dir': 'new/dir'}}) self.assertTrue( feature.Match(CrashedDirectory('new/dir/a'), FileChangeInfo(ChangeType.MODIFY, 'old/dir/a/FileName.cc', ...
Python
nomic_cornstack_python_v1
function __eq__ self other begin if not is instance other CsvDataLoadOptions begin return false end return __dict__ == __dict__ end function
def __eq__(self, other): if not isinstance(other, CsvDataLoadOptions): return False return self.__dict__ == other.__dict__
Python
nomic_cornstack_python_v1
function _simple_domain_name_validator value begin set checks = generator expression s in value for s in whitespace if any checks begin raise call ValidationError call _ string The domain name cannot contain any spaces or tabs. code=string invalid end end function
def _simple_domain_name_validator(value): checks = ((s in value) for s in string.whitespace) if any(checks): raise ValidationError( _("The domain name cannot contain any spaces or tabs."), code='invalid', )
Python
nomic_cornstack_python_v1
function test_correct_sheme_host_sent_with_request self begin set req = call get_my_ip dry_run=true assert in client at string host netloc assert in client at string scheme scheme assert in client at string get_my_ip at string path path end function
def test_correct_sheme_host_sent_with_request(self): req = self.httpbin.get_my_ip(dry_run=True) self.assertIn(self.httpbin.client['host'], urlparse(req.prepared_request.url).netloc) self.assertIn(self.httpbin.client['scheme'], urlparse(req.prepared_request.url).scheme) self.assertIn(self...
Python
nomic_cornstack_python_v1
function solve input begin for number in range 1 input + 1 begin if input % number == 0 begin yield number end end end function set user_input = input set solution = call solve integer user_input for i in solution begin print i end=string end
def solve(input: int): for number in range(1, input + 1): if input % number == 0: yield number user_input = input() solution = solve(int(user_input)) for i in solution: print(i, end=" ")
Python
zaydzuhri_stack_edu_python
function msg *args begin if messages_on begin print *args end end function
def msg(*args): if messages_on: print(*args)
Python
nomic_cornstack_python_v1
import os import pickle set train_mfcc = string processed/timit-train-mfcc-nor.pkl set test_mfcc = string processed/timit-test-mfcc-nor.pkl set train_phn = string processed/timit-train-phn.pkl set test_phn = string processed/timit-test-phn.pkl set train_wrd = string processed/timit-train-wrd.pkl set test_wrd = string p...
import os import pickle train_mfcc = 'processed/timit-train-mfcc-nor.pkl' test_mfcc = 'processed/timit-test-mfcc-nor.pkl' train_phn = 'processed/timit-train-phn.pkl' test_phn = 'processed/timit-test-phn.pkl' train_wrd = 'processed/timit-train-wrd.pkl' test_wrd = 'processed/timit-test-wrd.pkl' ''' 1. min/max length...
Python
zaydzuhri_stack_edu_python
for i in aa begin if i == string begin set wordFound = false end else if wordFound == false begin set cnt = cnt + 1 set wordFound = true end end
for i in aa: if i == ' ': wordFound = False elif wordFound == False: cnt += 1 wordFound = True
Python
zaydzuhri_stack_edu_python
function buscarDato d V begin set i = 1 while i <= V at 0 and V at i != d begin set i = i + 1 end if i <= V at 0 begin return i end end function
def buscarDato(d, V): i = 1 while i <= V[0] and V[i] != d: i = i + 1 if i <= V[0]: return i
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 string PeelAlign script Usage: main.py -p <peelPdb> -r <refPdb> [-b <benchMode>] [-c <peelChain>] [-s <refChain>] Options: -h --help help --version version of the script -p --peelPdb = peeled_pdb input pdb file, that will be peeled -r --refPdb = ref_pdb other input pdb file, that will be u...
#!/usr/bin/env python3 """PeelAlign script Usage: main.py -p <peelPdb> -r <refPdb> [-b <benchMode>] [-c <peelChain>] [-s <refChain>] Options: -h --help help --version version of the script -p --peelPdb = peeled_pdb input pdb file, that will be peeled -r --refPdb = ref_pdb ...
Python
zaydzuhri_stack_edu_python
set naam = input string what is your name set age = input string what is your age set age = eval age print naam + string you will be + string age + 1 + string next year
naam = input('what is your name') age = input('what is your age') age = eval(age) print (naam + 'you will be' + str(age +1) + 'next year')
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/nev python3 comment -*- coding:utf-8 -*- string @version: v1.0 @author: pengshp @license: Apache Licence @contact: pengshp3@outlook.com @subject: 直方图 @site: https://pengshp.github.io/ @software: PyCharm Community Edition @file: matplt06.py @time: 16/8/27 上午2:22 import matplotlib.pyplot as plt import n...
#!/usr/bin/nev python3 # -*- coding:utf-8 -*- """ @version: v1.0 @author: pengshp @license: Apache Licence @contact: pengshp3@outlook.com @subject: 直方图 @site: https://pengshp.github.io/ @software: PyCharm Community Edition @file: matplt06.py @time: 16/8/27 上午2:22 """ import matplotlib.pyplot as plt import numpy as np...
Python
zaydzuhri_stack_edu_python
for i in range n begin for j in range i n begin set t = s at slice 0 : i : + s at slice j : : if t == string keyence begin print string YES exit end end end for else begin print string NO end
for i in range(n): for j in range(i, n): t = s[0:i]+s[j:] if t == 'keyence': print('YES') exit() else: print('NO')
Python
zaydzuhri_stack_edu_python
function __remove_signature self text sign begin set sign = right strip sign set ind = reverse find text sign if ind + length sign >= length text - CHAR_ERROR begin return text at slice : ind : end else begin return text end end function
def __remove_signature(self, text, sign): sign = sign.rstrip() ind = text.rfind(sign) if ind + len(sign) >= len(text) - cf.CHAR_ERROR: return text[:ind] else: return text
Python
nomic_cornstack_python_v1
comment 最后两节课为练习课,通过两节课的学习,最终绘制出小猪佩奇的家 comment 第九节课内容:画草坪和蓝天 两朵白云 太阳 from turtle import * call screensize 1154 824 string #8fc3ff call speed 5 comment 先定义一些基础函数 function go_to x y begin string 画笔移动函数 call penup call goto x y call pendown end function function pen_move m n=0 begin string 画笔前后移动函数,默认向前移动 call penup call ...
# 最后两节课为练习课,通过两节课的学习,最终绘制出小猪佩奇的家 # 第九节课内容:画草坪和蓝天 两朵白云 太阳 from turtle import * screensize(1154, 824, "#8fc3ff") speed(5) # 先定义一些基础函数 def go_to(x, y): '''画笔移动函数''' penup() goto(x, y) pendown() def pen_move(m, n=0): '''画笔前后移动函数,默认向前移动''' penup() forward(m) backward(n) ...
Python
zaydzuhri_stack_edu_python
function create_account Name=none begin pass end function
def create_account(Name=None): pass
Python
nomic_cornstack_python_v1
function handle text mic profile begin call say string Starting music mode call handleForever mic call say string Exiting music mode return end function
def handle(text, mic, profile): mic.say("Starting music mode") handleForever(mic) mic.say("Exiting music mode") return
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding: utf-8 comment In[ ]: import numpy as np import pandas as pd import matplotlib as plt import random comment In[ ]: set data_titanic = read csv string ...\train.csv comment data_titanic.head() comment In[ ]: head data_titanic 10 comment In[ ]: set col_del = list string Passeng...
#!/usr/bin/env python # coding: utf-8 # In[ ]: import numpy as np import pandas as pd import matplotlib as plt import random # In[ ]: data_titanic = pd.read_csv("...\\train.csv") #data_titanic.head() # In[ ]: data_titanic.head(10) # In[ ]: col_del = ['PassengerId', 'Name', 'Ticket', 'Cabin'] data_titani...
Python
zaydzuhri_stack_edu_python
function run self begin call serve end function
def run(self): self.server.serve()
Python
nomic_cornstack_python_v1
import numpy from numpy import array from algopy import UTPM , zeros function F x begin set y = zeros 3 dtype=x set y at 0 = x at 0 * x at 1 set y at 1 = x at 1 * x at 2 set y at 2 = x at 2 * x at 0 return y end function set x0 = array list 1 3 5 dtype=float set x1 = array list 1 0 0 dtype=float set D = 2 set P = 1 set...
import numpy; from numpy import array from algopy import UTPM, zeros def F(x): y = zeros(3, dtype=x) y[0] = x[0]*x[1] y[1] = x[1]*x[2] y[2] = x[2]*x[0] return y x0 = array([1,3,5],dtype=float) x1 = array([1,0,0],dtype=float) D = 2; P = 1 x = UTPM(numpy.zeros((D,P,3))) x.data[0,0,:] = x0 x.data[1,...
Python
zaydzuhri_stack_edu_python
function test_retain_query self begin assert true string ?per_page=15 in string content end function
def test_retain_query(self): self.assertTrue('?per_page=15' in str(self.response.content))
Python
nomic_cornstack_python_v1
import pandas as pd import xlrd comment 코로나 엑셀 파일 경로 set xlpath = string ./corona_data.xlsx comment pandas를 활용해 엑셀 파일을 불러와서, xldata라는 변수에 저장한다. set xldata = call read_excel xlpath comment 엑셀 데이터셋에서 필드명이 '확진자'인 데이터만 추출해서 출력한다. set confirmed_cases = xldata at string 확진자 print confirmed_cases print string ================...
import pandas as pd import xlrd # 코로나 엑셀 파일 경로 xlpath = './corona_data.xlsx' # pandas를 활용해 엑셀 파일을 불러와서, xldata라는 변수에 저장한다. xldata = pd.read_excel(xlpath) # 엑셀 데이터셋에서 필드명이 '확진자'인 데이터만 추출해서 출력한다. confirmed_cases = xldata['확진자'] print(confirmed_cases) print('============================================================...
Python
zaydzuhri_stack_edu_python
function reject_outliers data test_value m=5.0 stddev=none debug=false begin if no_numba begin function _reject_outliers data test_value m=5.0 stddev=none debug=false begin if stddev is none begin set stddev = standard deviation np data end set med = median data set d = absolute data - med set mdev = median d if debug ...
def reject_outliers(data, test_value, m=5., stddev=None, debug=False): if no_numba: def _reject_outliers(data, test_value, m=5., stddev=None, debug=False): if stddev is None: stddev = np.std(data) med = np.median(data) d = np.abs(data - med) ...
Python
nomic_cornstack_python_v1
class LinkedNode begin function __init__ self value previous=none following=none begin set value = value set previous = previous set next = following end function end class set players = integer input string Players: comment starts with 0! set marbles = integer input string Marble count: comment number 0 is default set...
class LinkedNode: def __init__(self, value, previous=None, following=None): self.value = value self.previous = previous self.next = following players = int(input("Players: ")) marbles = int(input("Marble count: ")) # starts with 0! marble_count = 1 # number 0 is default current = Linked...
Python
zaydzuhri_stack_edu_python
import urllib3 import requests from urllib import request comment request GET请求 function request36kr begin comment 忽略警告:InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. call disable_warnings comment 一个PoolManager实例来生成请求, 由该实例对象处理与线程池的连接以及线程安全的所有细节 set ...
import urllib3 import requests from urllib import request # request GET请求 def request36kr(): # 忽略警告:InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. requests.packages.urllib3.disable_warnings() # 一个PoolManager实例来生成请求, 由该实例对象处理与线程池的连接以及线程...
Python
zaydzuhri_stack_edu_python
function post self begin set cont = call request_string string continue default=string / call redirect call create_login_url cont end function
def post(self): cont = self.request_string('continue', default="/") self.redirect(users.create_login_url(cont))
Python
nomic_cornstack_python_v1
function run_loop cls symbol begin while true begin try begin call check_buy symbol call check_sell symbol end except Exception as e begin call handle_error e end sleep wait_time end end function
def run_loop(cls, symbol: str): while True: try: cls.check_buy(symbol) cls.check_sell(symbol) except Exception as e: handle_error(e) time.sleep(config.wait_time)
Python
nomic_cornstack_python_v1
function func num begin print num print type num end function comment 0 1 1 2 3 5 8 13 21 34 function get_index_from_fib num begin set prev_index = 0 set curr_index = 1 set count = 2 set sum = prev_index + curr_index print sum while sum < num begin set sum = prev_index + curr_index set prev_index = curr_index set curr_...
def func(num): print(num) print(type(num)) # 0 1 1 2 3 5 8 13 21 34 def get_index_from_fib(num): prev_index = 0 curr_index = 1 count = 2 sum = prev_index + curr_index print(sum) while sum < num: sum = prev_index + curr_index prev_index = curr_index curr_ind...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt function num_leaf tree begin string return number of leaves of given tree using recursive method ---------- Parameters tree: tree_node object decision tree used for prediction ---------- Return cnt: integer the number of leaves of given tree if key == - 1 begin return 1 end else begin se...
import matplotlib.pyplot as plt def num_leaf(tree): """ return number of leaves of given tree using recursive method ---------- Parameters tree: tree_node object decision tree used for prediction ---------- Return cnt: integer ...
Python
zaydzuhri_stack_edu_python
function get_all_movies db_file begin set movies = list set conn = none try begin set conn = call connect db_file set cur = call cursor for row in execute cur string SELECT * FROM Movies begin print row append movies row end for else begin print string Movies is empty end commit conn close conn return movies end excep...
def get_all_movies(db_file): movies = [] conn = None try: conn = sqlite3.connect(db_file) cur = conn.cursor() for row in cur.execute("SELECT * FROM Movies"): print(row) movies.append(row) else: print('Movies is empty') conn.c...
Python
nomic_cornstack_python_v1
import pandas as pd from bs4 import BeautifulSoup as bs import time from splinter import Browser import html5lib from webdriver_manager.chrome import ChromeDriverManager function scrape begin set executable_path = dict string executable_path string chromedriver set browser = call Browser string chrome keyword executabl...
import pandas as pd from bs4 import BeautifulSoup as bs import time from splinter import Browser import html5lib from webdriver_manager.chrome import ChromeDriverManager def scrape(): executable_path = {'executable_path': 'chromedriver'} browser = Browser('chrome', **executable_path, headless=False) url =...
Python
zaydzuhri_stack_edu_python
function comments_for_review context obj css_class=none begin set form = call ThreadedCommentForm context at string request obj if css_class begin set attrs at string class = css_class end set attrs at string placeholder = string Write a comment... set attrs at string rows = 1 set label = string set context at string ...
def comments_for_review(context, obj, css_class=None): form = ThreadedCommentForm(context["request"], obj) if css_class: form.fields['comment'].widget.attrs['class'] = css_class form.fields['comment'].widget.attrs['placeholder'] = 'Write a comment...' form.fields['comment'].widget.attrs['rows'] ...
Python
nomic_cornstack_python_v1
function check_energy fit begin set sampler_params = call get_sampler_params inc_warmup=false set no_warning = true for tuple chain_num s in enumerate sampler_params begin set energies = s at string energy__ set numer = sum generator expression energies at i - energies at i - 1 ^ 2 for i in range 1 length energies / le...
def check_energy(fit): sampler_params = fit.get_sampler_params(inc_warmup=False) no_warning = True for chain_num, s in enumerate(sampler_params): energies = s['energy__'] numer = sum((energies[i] - energies[i - 1])**2 for i in range(1, len(energies))) / len(energies) denom = np.var(e...
Python
nomic_cornstack_python_v1
comment @lc app=leetcode.cn id=476 lang=python3 comment [476] 数字的补数 comment @lc code=start class Solution begin function findComplement self num begin set L = 0 set R = 32 set ans = 32 while L <= R begin set m = L + R // 2 set twom = 1 ? m if num < twom begin set R = m - 1 set ans = m end else begin set L = m + 1 end e...
# # @lc app=leetcode.cn id=476 lang=python3 # # [476] 数字的补数 # # @lc code=start class Solution: def findComplement(self, num: int) -> int: L = 0 R = 32 ans = 32 while L<=R: m = (L+R)//2 twom = (1<<m) if num<twom: R = m-1 ...
Python
zaydzuhri_stack_edu_python
comment - A1- Ejercicio 1: Print y consola (numeros y texto), comentarios. comment Se pueden hacer comentarios que no son ejecutados comment Con gato se hacen comentarios de una línea string #1 Comentarios de múltiples líneas usando triple comillas dobles Antes y después de lo que se quiere comentar comment 2 print mue...
#- A1- Ejercicio 1: Print y consola (numeros y texto), comentarios. # Se pueden hacer comentarios que no son ejecutados # Con gato se hacen comentarios de una línea """ #1 Comentarios de múltiples líneas usando triple comillas dobles Antes y después de lo que se quiere comentar """ #2 print muestra información en la...
Python
zaydzuhri_stack_edu_python
class Solution begin function canJump self nums begin set reach = 0 for tuple i dist in enumerate nums begin if reach < i begin return false end set reach = max reach i + dist end comment if reach >= len(nums) - 1: return True : rebundant return true end function function canJump1 self nums begin set reach = 0 for tupl...
class Solution: def canJump(self, nums: List[int]) -> bool: reach = 0 for i, dist in enumerate(nums): if reach < i: return False reach = max(reach, i + dist) #if reach >= len(nums) - 1: return True : rebundant return True def can...
Python
zaydzuhri_stack_edu_python
function upload_file self dataset dataset_name dataset_type=string pandas *args **kwargs begin set run = call get_context set ws = workspace if dataset_type == string pandas begin comment Load a Tabular Dataset into pandas DataFrame set ds = call from_pandas_dataframe dataframe=dataset end else begin raise exception st...
def upload_file(self, dataset: pd.DataFrame, dataset_name: str, dataset_type: str='pandas', *args, **kwargs): run = Run.get_context() ws = run.experiment.workspace if dataset_type == 'pandas': ds = Dataset.from_pandas_dataframe(dataframe=dataset) # Load a Tabular Dataset into pandas...
Python
nomic_cornstack_python_v1
import socketio import base64 import numpy as np from PIL import Image from io import BytesIO import cv2 import torch from util.loader import load_checkpoint from util.predictor import predict set net = call load_checkpoint string checkpoint.pth set sio = call Client decorator call on string connect function on_connect...
import socketio import base64 import numpy as np from PIL import Image from io import BytesIO import cv2 import torch from util.loader import load_checkpoint from util.predictor import predict net = load_checkpoint('checkpoint.pth') sio = socketio.Client() @sio.on('connect') def on_connect(): print('connection...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- import argparse import os import sys import cv2 function main begin set parser = call ArgumentParser description=string Gabor filter sample script call add_argument help=string image file dest=string img_file set args = call parse_args end function
#-*- coding: utf-8 -*- import argparse import os import sys import cv2 def main(): parser = argparse.ArgumentParser( description='Gabor filter sample script', ) parser.add_argument( help='image file', dest='img_file', ) args = parser.parse_args()
Python
zaydzuhri_stack_edu_python
function get_se_config self begin set se = get params string se none set from_se = query Session Se set from_ops = query Session OperationConfig if se begin set from_se = filter storage == se set from_ops = filter host == se end comment Merge both set response = dictionary for opt in from_se begin set se = storage set ...
def get_se_config(self): se = request.params.get('se', None) from_se = Session.query(Se) from_ops = Session.query(OperationConfig) if se: from_se = from_se.filter(Se.storage == se) from_ops = from_ops.filter(OperationConfig.host == se) # Merge both ...
Python
nomic_cornstack_python_v1
function boot_basic_conf_interval boot_sims orig_sample_estimate significance=0.05 begin set num_boot_params = shape at 1 if length orig_sample_estimate != num_boot_params begin raise exception string num boot columns: + string num_boot_params + string not equal to num orig_sample_estimate: + string length orig_sample_...
def boot_basic_conf_interval(boot_sims, orig_sample_estimate, significance=0.05): num_boot_params = boot_sims.shape[1] if len(orig_sample_estimate) != num_boot_params: raise Exception("num boot columns: " + str(num_boot_params) + ...
Python
nomic_cornstack_python_v1
function check_job_worked plot_name var rgb=false begin if rgb begin if glob plot_name and get size path plot_name > 0 and glob rgb at string layered_rgb_name and get size path rgb at string layered_rgb_name > 0 begin return true end else begin return false end end else if glob plot_name and get size path plot_name > 0...
def check_job_worked(plot_name, var, rgb=False): if rgb: if (glob(plot_name) and os.path.getsize(plot_name) > 0 and glob(rgb["layered_rgb_name"]) and os.path.getsize(rgb["layered_rgb_name"]) > 0): return True else: return False else: if glob(plot_nam...
Python
nomic_cornstack_python_v1
function bind_clicking_widge self widge begin call bind string <Button-1> widge_enlarge_shrink return end function
def bind_clicking_widge(self, widge): widge.bind('<Button-1>', self.widge_enlarge_shrink) return
Python
nomic_cornstack_python_v1
from PIL import Image , ImageDraw from random import randint from colour import Colour from utils import chance import config class Shape begin function __init__ self begin set poly = call __randPoly random integer POLY_MIN_SIDES POLY_MAX_SIDES 0 0 PIC_W PIC_H set colour = call Colour set image = call buildImage end fu...
from PIL import Image, ImageDraw from random import randint from colour import Colour from utils import chance import config class Shape: def __init__(self): self.poly = self.__randPoly(randint(config.POLY_MIN_SIDES, config.POLY_MAX_SIDES), 0, 0, config.PIC_W, config.PIC_H) self.colour = Colour() self.image = ...
Python
zaydzuhri_stack_edu_python
import sys , math from sol import SOL set inputfile = argv at 1 set problem_name = argv at 2 set f = open inputfile set alltext = read f set lines = call splitlines set numrows = 5 set inf = 9999999999999 set table = list comprehension list comprehension list inf * 4 for i in range numrows for j in range 6 comment 4 is...
import sys, math from sol import SOL inputfile = sys.argv[1] problem_name = sys.argv[2] f = open(inputfile) alltext = f.read() lines = alltext.splitlines() numrows = 5 inf = 9999999999999 table = [[[inf]*4 for i in range(numrows)] for j in range(6)] # 4 is number of attributes in a cell a = 0 for line in lines: ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python2.7 string Backend functions for searching and updating the inventory ---------------------------------------------------------------- CS 304 - Databases import sys import MySQLdb from connection import get_conn function countInventoryTotal conn begin string Returns the number of items in invent...
#!/usr/bin/python2.7 """ Backend functions for searching and updating the inventory ---------------------------------------------------------------- CS 304 - Databases """ import sys import MySQLdb from connection import get_conn def countInventoryTotal(conn): """Returns the number of items in inventory""" ...
Python
zaydzuhri_stack_edu_python
function build_delay_message self task_id=none function_name=none args=none kwargs=none begin if task_id is none begin set task_id = hex end if function_name is none begin set function_name = function_name end if args is none begin set args = args end if kwargs is none begin set kwargs = kwargs end return call packb di...
def build_delay_message(self, task_id: str = None, function_name: str = None, args: List[str] = None, kwargs: Dict = None) -> str: if task_id is None: task_id = uuid.uuid4().hex i...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding:utf-8 comment Copyright (C) dirlt import BaseHTTPServer
#!/usr/bin/env python #coding:utf-8 #Copyright (C) dirlt import BaseHTTPServer
Python
zaydzuhri_stack_edu_python
function checkAvailability month year duration lunch_days begin comment Check if duration is valid if duration > 8 or duration <= 0 begin return string Error: Invalid lunch duration end comment Check if lunch days are valid for day in lunch_days begin if day not in list string 1st string 2nd string 3rd string 4th strin...
def checkAvailability(month, year, duration, lunch_days): # Check if duration is valid if duration > 8 or duration <= 0: return "Error: Invalid lunch duration" # Check if lunch days are valid for day in lunch_days: if day not in ['1st', '2nd', '3rd', '4th', 'last']: ...
Python
jtatman_500k
function delete name attributes begin string Make sure the given attributes are deleted from the file/directory name The path to the file/directory attributes The attributes that should be removed from the file/directory, this is accepted as an array. set ret = dict string name name ; string result true ; string commen...
def delete(name, attributes): ''' Make sure the given attributes are deleted from the file/directory name The path to the file/directory attributes The attributes that should be removed from the file/directory, this is accepted as an array. ''' ret = {'name': name, ...
Python
jtatman_500k
function log_sum_exp_accumulate x axis=0 begin set xmax = max axis return log accumulate exp x - xmax axis + xmax end function
def log_sum_exp_accumulate(x, axis=0): xmax = x.max(axis) return log(numpy.add.accumulate(exp(x - xmax), axis)) + xmax
Python
nomic_cornstack_python_v1
function websockets_enabled self begin return get pulumi self string websockets_enabled end function
def websockets_enabled(self) -> bool: return pulumi.get(self, "websockets_enabled")
Python
nomic_cornstack_python_v1
string Given an array of integers, find the length of the longest nondecreasing subsequence in the array import bisect function longest_nondecreasing_subsequence_n2 A begin set max_length = list 1 * length A for i in range length A begin set max_length at i = 1 + max generator expression max_length at j for j in range ...
""" Given an array of integers, find the length of the longest nondecreasing subsequence in the array """ import bisect def longest_nondecreasing_subsequence_n2(A): max_length = [1] * len(A) for i in range(len(A)): max_length[i] = 1 + max( (max_length[j] for j in range(i) if A[i] >= A[j]), default=0) return m...
Python
zaydzuhri_stack_edu_python
comment 1 - CONFUSION MATRIX comment 2 - ROC CURVE comment 3 - CROSS VALIDATION SCORE comment 4 - STRATIFIED K-FOLD CROSS VALIDATION comment 5 - CUMMULATIVE ACCURACY PROFILE (CAP) import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.me...
# 1 - CONFUSION MATRIX # 2 - ROC CURVE # 3 - CROSS VALIDATION SCORE # 4 - STRATIFIED K-FOLD CROSS VALIDATION # 5 - CUMMULATIVE ACCURACY PROFILE (CAP) import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import confusion_matrix...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment =============================================================================== comment Python Numpy/Scipy program for analyzing MMTO WFS seeing data. comment =============================================================================== import numpy as np import matplotlib.cm as c...
#!/usr/bin/env python #=============================================================================== # # Python Numpy/Scipy program for analyzing MMTO WFS seeing data. # #=============================================================================== import numpy as np import matplotlib.cm as cm import matplotlib.py...
Python
zaydzuhri_stack_edu_python
import oseti class Analyzer begin function __init__ self begin set oseti = call Analyzer end function function analyze self text **args begin set all_count = 0 set summary = dict string positive 0 ; string negative 0 for sent_polarity in call count_polarity text begin set summary at string positive = summary at string ...
import oseti class Analyzer: def __init__(self) -> None: self.oseti = oseti.Analyzer() def analyze(self, text, **args): all_count = 0 summary = { 'positive': 0, 'negative': 0, } for sent_polarity in self.oseti.count_polarity(text): su...
Python
zaydzuhri_stack_edu_python
set num1 = decimal input string Enter the first number: set num2 = decimal input string Enter the second number: set num3 = decimal input string Enter the third number: print string The max value is: max num1 num2 num3 input string Press any key to exit
num1 = float( input("Enter the first number: ")) num2 = float( input("Enter the second number: ")) num3 = float( input("Enter the third number: ")) print("The max value is: ", max(num1,num2,num3)) input("Press any key to exit")
Python
zaydzuhri_stack_edu_python
import random comment TODO: Define the Thrower class here. class Dealer begin string Where the dice is thrown function __init__ self begin set card = 0 set right_v_wrong = true end function function draw_card self begin string chooses a random card set card = random integer 1 14 end function function get_points self gu...
import random # TODO: Define the Thrower class here. class Dealer: """Where the dice is thrown""" def __init__(self): self.card = 0 self.right_v_wrong = True def draw_card(self): """chooses a random card""" self.card = random.randint(1, 14) def get_points(self, guess...
Python
zaydzuhri_stack_edu_python
import numpy as np import pandas as pd import seaborn as sb from textblob import TextBlob import csv import string import time import nltk import os import sys from sklearn.preprocessing import normalize from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransfo...
import numpy as np import pandas as pd import seaborn as sb from textblob import TextBlob import csv import string import time import nltk import os import sys from sklearn.preprocessing import normalize from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransfo...
Python
zaydzuhri_stack_edu_python
function fibonacci n begin comment Error handling for non-positive integers if not is instance n int or n <= 0 begin raise call ValueError string Invalid input. Please enter a positive integer. end comment Base cases for 0 and 1 if n == 0 begin return 0 end else if n == 1 begin return 1 end comment Recursive case retur...
def fibonacci(n): # Error handling for non-positive integers if not isinstance(n, int) or n <= 0: raise ValueError("Invalid input. Please enter a positive integer.") # Base cases for 0 and 1 if n == 0: return 0 elif n == 1: return 1 # Recursive case return f...
Python
greatdarklord_python_dataset
function edge_assignment_score edge_index edge_scores n begin comment If there is no edge, do not bother if not length edge_index begin return tuple call empty tuple 0 2 dtype=int64 array range n dtype=int64 0.0 end comment Build an input adjacency matrix to constrain the edge selection to the input graph set adj_mat =...
def edge_assignment_score(edge_index: nb.int64[:,:], edge_scores: nb.float32[:,:], n: nb.int64) -> (nb.int64[:,:], nb.int64[:], nb.float32): # If there is no edge, do not bother if not len(edge_index): return np.empty((0,2), dtype=np.int64), np.arange(...
Python
nomic_cornstack_python_v1
comment !/usr/local/bin/python3 comment coding=utf-8 from MusicUtils import * class DurationValues extends object begin function __init__ self table=none begin call __init__ set _table = dict if table begin set _table = table end set _default = none end function function set_default self value begin set _default = val...
#!/usr/local/bin/python3 # coding=utf-8 from MusicUtils import * class DurationValues (object): def __init__(self, table = None): super().__init__() self._table = {} if table: self._table = table self._default = None def set_default(self, value): self._default = value return self ...
Python
zaydzuhri_stack_edu_python
class DPForWhiteBoxMetodaSzwabe begin function __init__ self optimalBlackBoxClassifier currentBlackBoxAlgorithm normalDP begin set optimalBlackBoxClassifier = optimalBlackBoxClassifier set currentBlackBoxAlgorithm = currentBlackBoxAlgorithm set normalDP = normalDP set myNrows = myNrows set tuple X_train X_test y_train ...
class DPForWhiteBoxMetodaSzwabe: def __init__(self, optimalBlackBoxClassifier, currentBlackBoxAlgorithm, normalDP): self.optimalBlackBoxClassifier = optimalBlackBoxClassifier self.currentBlackBoxAlgorithm = currentBlackBoxAlgorithm self.normalDP = normalDP self.myNrows = normalDP.myN...
Python
zaydzuhri_stack_edu_python
function __call__ self event begin call set_result_if_pending users set timer = timer if timer is not none begin set timer = none call cancel end return true end function
def __call__(self, event): self.waiter.set_result_if_pending(event.users) timer = self.timer if (timer is not None): self.timer = None timer.cancel() return True
Python
nomic_cornstack_python_v1
function process code input_data begin set predicted_class = predict code ementa set input_data at string predicted_class = call Series predicted_class index=index return input_data end function
def process(code, input_data): predicted_class = code.predict(input_data.ementa) input_data['predicted_class'] = pd.Series(predicted_class, index=input_data.index) return input_data
Python
nomic_cornstack_python_v1
function get_object self queryset=none begin comment Use a custom queryset if provided; this is required for subclasses comment like DateDetailView if queryset is none begin set queryset = call get_queryset end comment Next, try looking up by primary key. set pk = get kwargs pk_url_kwarg set slug = get kwargs slug_url_...
def get_object(self, queryset=None): # Use a custom queryset if provided; this is required for subclasses # like DateDetailView if queryset is None: queryset = self.get_queryset() # Next, try looking up by primary key. pk = self.kwargs.get(self.pk_url_kwarg) ...
Python
nomic_cornstack_python_v1
comment Write a Python function to find the Max of three numbers function max a b c begin comment if a <= b >= c: je ekvivalentní zápis s tímto: if b >= a and b >= c begin return b end if c <= a >= b begin return a end if a <= c >= b begin return c end end function assert max 1 2 3 == 3 assert max 10 10 10 == 10 assert...
# Write a Python function to find the Max of three numbers def max(a, b, c): # if a <= b >= c: je ekvivalentní zápis s tímto: if b >= a and b >= c: return b if c <= a >= b: return a if a <= c >= b: return c assert max(1, 2, 3) == 3 assert max(10, 10, 10) == 10 assert max(3, 2, ...
Python
zaydzuhri_stack_edu_python
function ChooseBHNS BH_RATIO df_systems begin set r = random set bh = values set ns = values if r > BH_RATIO begin set choice = random choice ns set kind = 0 end if r < BH_RATIO begin set choice = random choice bh comment kind = 1 is bh set kind = 1 end return list choice kind end function
def ChooseBHNS(BH_RATIO, df_systems): r = np.random.random() bh = df_systems[df_systems['is_bh']==1].index.values ns = df_systems[df_systems['is_bh']==0].index.values if r > BH_RATIO: choice = np.random.choice(ns) kind = 0 if r < BH_RATIO: choice = np.random.choice(bh) ...
Python
nomic_cornstack_python_v1
comment print 1 to 10 print string first : comment i = 1,2,3,4,5,6,7,8,9 for i in range 1 10 begin print i end comment print 1 to 8 with step size= 2 print string second : comment i = 1,3,5,7 for i in range 1 8 2 begin print i end comment print 10 to 1 print string third : comment i = 10,9,8,7,6,5,4,3,2,1 for i in rang...
# print 1 to 10 print("first :") for i in range(1, 10): # i = 1,2,3,4,5,6,7,8,9 print(i) # print 1 to 8 with step size= 2 print("second :") for i in range(1,8,2): # i = 1,3,5,7 print(i) # print 10 to 1 print("third :") for i in range(10,0,-1): # i = 10,9,8,7,6,5,4,3,2,1 print(i) print(4 in range(1,5)...
Python
zaydzuhri_stack_edu_python
function get_feature_locations_from_gff3 gff3_file begin for line in open gff3_file string rU begin set entry = call gff_entry line if valid begin yield call feature_location start end strand seq_id end end end function
def get_feature_locations_from_gff3(gff3_file): for line in open(gff3_file, 'rU'): entry = gff_entry(line) if entry.valid: yield feature_location(entry.start, \ entry.end, \ entry.strand, \ ...
Python
nomic_cornstack_python_v1
import pygame as pg from pygame.locals import * import numpy from Runner import Runner from Strategy import Strategy set BACKGROUND_IMAGE = string grass.jpg set POINT_COLOR = tuple 0 0 0 set POINT_LABEL_COLOR = tuple 255 255 255 set LINE_COLOR = tuple 101 67 33 set RADIUS = 20 class GUI begin function __init__ self wid...
import pygame as pg from pygame.locals import * import numpy from Runner import Runner from Strategy import Strategy BACKGROUND_IMAGE = 'grass.jpg' POINT_COLOR = (0, 0, 0) POINT_LABEL_COLOR = (255, 255, 255) LINE_COLOR = (101, 67, 33) RADIUS = 20 class GUI: def __init__(self, width=600, height=600): pg.i...
Python
zaydzuhri_stack_edu_python
from random import choice from MonteCarloMethods.Blackjack.State import State from MonteCarloMethods.Blackjack.Card import Card from MonteCarloMethods.Blackjack.Dealer import Dealer from MonteCarloMethods.Blackjack.Gambler import Gambler class Blackjack extends object begin set limit = 21 function __init__ self begin s...
from random import choice from MonteCarloMethods.Blackjack.State import State from MonteCarloMethods.Blackjack.Card import Card from MonteCarloMethods.Blackjack.Dealer import Dealer from MonteCarloMethods.Blackjack.Gambler import Gambler class Blackjack(object): limit = 21 def __init__(self): self._...
Python
zaydzuhri_stack_edu_python
function action_configureband4 self model tango_dev=none data_input=none begin call _configureband model data_input 4 end function
def action_configureband4(self, model, tango_dev=None, data_input=None): self._configureband(model, data_input, 4)
Python
nomic_cornstack_python_v1
function search self location=none query=none return_fields=none begin set fts = call _search location=location query=query return_fields=return_fields extra_wfs_fields=list string Type_proef string Proeffiche set interpretaties = call from_wfs fts __wfs_namespace set df = call DataFrame data=call to_df_array interpret...
def search(self, location=None, query=None, return_fields=None): fts = self._search(location=location, query=query, return_fields=return_fields, extra_wfs_fields=['Type_proef', 'Proeffiche']) interpretaties = InformeleStratigrafie.from_wfs( ...
Python
nomic_cornstack_python_v1
function load self filepath begin set model_params = load torch filepath for tuple model_param pretrained_model_param in zip parameters self items model_params begin comment pretrained word embedding if length size pretrained_model_param at 1 > 1 and size pretrained_model_param at 1 at 0 > 5000 begin set pretrained_wor...
def load(self, filepath): model_params = torch.load(filepath) for model_param, pretrained_model_param in zip(self.parameters(), model_params.items()): if len(pretrained_model_param[1].size()) > 1 and pretrained_model_param[1].size()[0] > 5000: # pretrained word embedding pre...
Python
nomic_cornstack_python_v1
string This task makes include guards follow the style stipulated by the Google style guide. import os import regex from enum import Enum from wpiformat.task import Task class State extends Enum begin set FINDING_IFNDEF = 1 set FINDING_ENDIF = 2 set DONE = 3 end class class IncludeGuard extends Task begin function shou...
"""This task makes include guards follow the style stipulated by the Google style guide. """ import os import regex from enum import Enum from wpiformat.task import Task class State(Enum): FINDING_IFNDEF = 1 FINDING_ENDIF = 2 DONE = 3 class IncludeGuard(Task): def should_process_file(self, config...
Python
zaydzuhri_stack_edu_python
comment write to excel import xlsxwriter comment scrape from web import urllib.request comment scrape from web import requests comment scrape from web import io import traceback comment create namedtuple for manipulation from collections import namedtuple comment test source code for email import re set professor = nam...
import xlsxwriter #write to excel import urllib.request #scrape from web import requests #scrape from web import io #scrape from web import traceback from collections import namedtuple #create namedtuple for manipulation import re #test source code for email professor = namedtuple('professor', 'name university')...
Python
zaydzuhri_stack_edu_python
comment queue implementation practice class Queue extends object begin function __init__ self begin set data = list end function function is_empty self begin if length data <= 0 begin return true end else begin return false end end function function checkSize self begin return length data end function function enQ sel...
# queue implementation practice class Queue(object): def __init__(self): self.data=[] def is_empty(self): if len(self.data)<=0: return True else: return False def checkSize(self): return len(self.data) def enQ(self,x): self.data.insert...
Python
zaydzuhri_stack_edu_python
import threading import socket import json from PyQt5.QtCore import pyqtSignal , QObject import time class Core extends QObject begin string Encargado de manejar la info con el servidor set lista_check = call pyqtSignal list set editing_check = call pyqtSignal list function __init__ self begin call __init__ print strin...
import threading import socket import json from PyQt5.QtCore import pyqtSignal, QObject import time class Core(QObject): """ Encargado de manejar la info con el servidor """ lista_check = pyqtSignal(list) editing_check = pyqtSignal(list) def __init__(self): super().__init__() pr...
Python
zaydzuhri_stack_edu_python
import functools import time function timer message=string Duration: precision=3 begin function timer_inner fn begin decorator wraps fn function fn_with_time *args **kwargs begin set start = time set ret = call fn *args keyword kwargs print string { message } { round time - start precision } return ret end function ret...
import functools import time def timer(message="Duration: ", precision=3): def timer_inner(fn): @functools.wraps(fn) def fn_with_time(*args, **kwargs): start = time.time() ret = fn(*args, **kwargs) print(f"{message}{round(time.time() - start, precision)}") ...
Python
zaydzuhri_stack_edu_python
function pluck self key begin set key = string key return call Collection list comprehension call attribute_reader item key none for item in self end function
def pluck(self, key: StrLike) -> Collection[Any]: key = str(key) return Collection([attribute_reader(item, key, None) for item in self])
Python
nomic_cornstack_python_v1
import requests import os import time import argparse class api begin function __init__ self url=string http://localhost:3000/upload begin set url = url set dirs = list end function function upload_images self folder begin set dir = list set dirs = list directory folder set multiple_images = list for d in dirs begin...
import requests import os import time import argparse class api: def __init__(self, url = "http://localhost:3000/upload"): self.url = url self.dirs=[] def upload_images(self,folder): self.dir=[] self.dirs = os.listdir(folder) multiple_images = [] for d in self.dirs: d = os.path.join(folder,d) file...
Python
zaydzuhri_stack_edu_python
function save_players self begin set save_objs = dictionary comprehension key : call SaveObject value for tuple key value in items players call save_object save_objs savepath + string _%s % server end function comment RecourceManager.save_object(self.players, savepath + "_%s" % self.server)
def save_players(self): save_objs = {key: Player.SaveObject(value) for key, value in self.players.items()} RecourceManager.save_object(save_objs, savepath + "_%s" % self.server) # RecourceManager.save_object(self.players, savepath + "_%s" % self.server)
Python
nomic_cornstack_python_v1
function _make_edit_request self state undo=false additional_var=none begin set var = dict string i item_id if undo begin set var at string r = string user/-/state/com.google/ + state end else begin set var at string a = string user/-/state/com.google/ + state end if additional_var begin update var additional_var end r...
def _make_edit_request(self, state, undo=False, additional_var=None): var = { 'i': self.item_id } if undo: var['r'] = 'user/-/state/com.google/' + state else: var['a'] = 'user/-/state/com.google/' + state if additional_var: var.upd...
Python
nomic_cornstack_python_v1
function get_states begin set states = list for state in values all string State begin append states call to_dict end return call jsonify states end function
def get_states(): states = [] for state in strong.all("State").values(): states.append(state.to_dict()) return jsonify(states)
Python
nomic_cornstack_python_v1
function correct_pore_diameter com *params begin set tuple elements coordinates = params return - call pore_diameter elements coordinates com at 0 end function
def correct_pore_diameter(com, *params): elements, coordinates = params return (-pore_diameter(elements, coordinates, com)[0])
Python
nomic_cornstack_python_v1
function test_model_deleting_works_properly self begin set tm = call create count=8 text=string 123456789 set vid = vid delete with assert raises DoesNotExist begin set tm2 = get TestModel vid end end function
def test_model_deleting_works_properly(self): tm = TestModel.create(count=8, text='123456789') vid = tm.vid tm.delete() with self.assertRaises(TestModel.DoesNotExist): tm2 = TestModel.get(vid)
Python
nomic_cornstack_python_v1
function get_nilspod_dataset_corrupted_info dataset file_path begin call _assert_is_dtype dataset Dataset set nilspod_file_pattern = string NilsPodX-\w{4}_(.*?).bin comment ensure pathlib set file_path = call Path file_path set keys = list string name string percent_corrupt string condition set dict_res = call fromkeys...
def get_nilspod_dataset_corrupted_info(dataset: Dataset, file_path: path_t) -> Dict: _assert_is_dtype(dataset, Dataset) nilspod_file_pattern = r"NilsPodX-\w{4}_(.*?).bin" # ensure pathlib file_path = Path(file_path) keys = ["name", "percent_corrupt", "condition"] dict_res = dict.fromkeys(keys) ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python set m = list with open string triangle.txt string r as f begin for line in f begin append m list comprehension integer s for s in split line end end set num_lines = length m
#!/usr/bin/env python m = [] with open('triangle.txt', 'r') as f: for line in f: m.append([int(s) for s in line.split()]) num_lines = len(m)
Python
zaydzuhri_stack_edu_python
function write2dListToCSV list2d fileNameWithDir begin set fullFileName = fileNameWithDir if list2d is not none begin with open fullFileName string w newline=string as csvfile begin set w = writer csvfile write rows w list2d end end end function
def write2dListToCSV(list2d, fileNameWithDir): fullFileName = fileNameWithDir if list2d is not None: with open(fullFileName, 'w', newline='') as csvfile: w = csv.writer(csvfile) w.writerows(list2d)
Python
nomic_cornstack_python_v1