code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function is_public self begin if storage_class == STATIC begin return false end return true end function
def is_public(self) -> bool: if self.node.storage_class == StorageClass.STATIC: return False return True
Python
nomic_cornstack_python_v1
comment coding: utf-8 comment In[5]: comment Merge Sort by Using For loops from time import time from random import random function merge m1 m2 begin set m = list while length m1 != 0 and length m2 != 0 begin if m1 at 0 == min m1 at 0 m2 at 0 begin append m m1 at 0 del m1 at 0 end else begin append m m2 at 0 del m2 at...
# coding: utf-8 # In[5]: #Merge Sort by Using For loops from time import time from random import random def merge(m1,m2): m=[] while len(m1)!=0 and len(m2)!=0: if m1[0]==min(m1[0],m2[0]): m.append(m1[0]) del(m1[0]) else: m.append(m2[0]) del(m2...
Python
zaydzuhri_stack_edu_python
function match_lookup_by_node_name self node_name attribute_name begin set lookup_query = format string MATCH(n:{}) RETURN n.{} node_name attribute_name set key = string n. + attribute_name set driver = call access_db set session = call session with call begin_transaction as _tx begin set result = run lookup_query end ...
def match_lookup_by_node_name(self, node_name, attribute_name): lookup_query = "MATCH(n:{}) RETURN n.{}".format(node_name, attribute_name) key = "n." + attribute_name driver = self.access_db() session = driver.session() with session.begin_transaction() as _tx: result...
Python
nomic_cornstack_python_v1
class calculator begin decorator classmethod function add cls a b begin return a + b end function decorator classmethod function times cls a b begin return a * b end function end class
class calculator: @classmethod def add (cls, a, b): return a + b @classmethod def times (cls, a, b): return a * b
Python
zaydzuhri_stack_edu_python
comment -*- coding:utf-8 -*- import sys from pylab import * import matplotlib.pyplot as plt call reload sys call setdefaultencoding string utf-8 set rcParams at string font.sans-serif = list string SimHei set labels = tuple string C语言 string 数据库 string 嵌入式 string Linux string Python string Windows string Java set fracs...
# -*- coding:utf-8 -*- import sys from pylab import * import matplotlib.pyplot as plt reload(sys) sys.setdefaultencoding('utf-8') mpl.rcParams['font.sans-serif'] = ['SimHei'] labels = u'C语言', u'数据库', u'嵌入式', u'Linux', u'Python', u'Windows', u'Java' fracs = [25, 23, 22, 15, 5, 5, 5] explode = [0.1, 0, 0, 0, 0, 0, 0] pa...
Python
zaydzuhri_stack_edu_python
comment Conditions set number = integer input string Enter a number: comment if == equal if number == 6 begin print number * 2 end else comment elif <= smaller or equal if number <= 3 begin print number + 3 end else begin print number - 1 end
#Conditions number=int(input("Enter a number: \n")) #if == equal if (number==6): print(number*2) #elif <= smaller or equal elif (number<=3): print(number+3) else: print(number-1)
Python
zaydzuhri_stack_edu_python
function get_db request begin return db end function
def get_db(request: Request) -> Session: return request.state.db
Python
nomic_cornstack_python_v1
comment Kevin Nguyen comment Python program that determines whether a given character sequence is a palindrome or not. comment How to run (linux): comment 1.) open command line and cd into directory folder of where this code is comment 2.) type in "python Python-Shell.py" comment import statements import sys import arr...
#Kevin Nguyen #Python program that determines whether a given character sequence is a palindrome or not. # #How to run (linux): # 1.) open command line and cd into directory folder of where this code is # 2.) type in "python Python-Shell.py" #import statements import sys; import array; #function implementation/defini...
Python
zaydzuhri_stack_edu_python
function sortArray arr begin sort arr return arr end function comment Driver code set arr = list 9 5 1 10 print call sortArray arr comment Output: [1, 5, 9, 10]
def sortArray(arr): arr.sort() return arr # Driver code arr = [9, 5, 1, 10] print(sortArray(arr)) # Output: [1, 5, 9, 10]
Python
jtatman_500k
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment @Time : 19-4-29 上午8:34 comment @Author : ho-ho comment @Site : comment @File : gui.py comment @Description: comment ------------------------------------------------------------------------------------- from tkinter import * import tkinter.filedialog fro...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 19-4-29 上午8:34 # @Author : ho-ho # @Site : # @File : gui.py # @Description: # ------------------------------------------------------------------------------------- from tkinter import * import tkinter.filedialog from tkinter import messagebox """ top = Tk...
Python
zaydzuhri_stack_edu_python
string Stage to populate the units.info table. This module contains a loader to load all unit level information into the database. import itertools as it import pymotifs.core as core from pymotifs import models as mod from pymotifs.utils import units from pymotifs.download import Downloader from pymotifs.pdbs.info impo...
"""Stage to populate the units.info table. This module contains a loader to load all unit level information into the database. """ import itertools as it import pymotifs.core as core from pymotifs import models as mod from pymotifs.utils import units from pymotifs.download import Downloader from pymotifs.pdbs.info ...
Python
zaydzuhri_stack_edu_python
set pythonList = list string int string str string bool string if string else string elif string loop string tuple string list string None true false print pythonList at slice 1 : 3 :
pythonList = ["int", "str", "bool", "if", "else", "elif", "loop", "tuple", "list", "None", True, False] print (pythonList[1:3])
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment @Time : 2020/8/1 13:49 comment @Author : AsiHacker comment @Site : comment @File : 主要看这个.py comment @Software: PyCharm import logging from logging.handlers import TimedRotatingFileHandler comment 级别排序:CRITICAL > ERROR > WARNING > INFO > DEBUG comment de...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/8/1 13:49 # @Author : AsiHacker # @Site : # @File : 主要看这个.py # @Software: PyCharm import logging from logging.handlers import TimedRotatingFileHandler # 级别排序:CRITICAL > ERROR > WARNING > INFO > DEBUG # debug : 打印全部的日志,详细的信息,通常只出现在诊断问题上 # info : 打...
Python
zaydzuhri_stack_edu_python
function hostname self hostname begin set _hostname = hostname end function
def hostname(self, hostname): self._hostname = hostname
Python
nomic_cornstack_python_v1
function _dispatch_events self begin for event in get event begin if type == QUIT begin if _on_quit_cb is none or call _on_quit_cb begin call quit end end if type == EVENT_ANIM_HEARTBEAT begin set _anim_timer = _anim_timer + 1 continue end if type in _unsettling_events begin set _idle_ticks = 0 end if type == MOUSEBUTT...
def _dispatch_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: if self._on_quit_cb is None or self._on_quit_cb(): self.quit() if event.type==self.EVENT_ANIM_HEARTBEAT: ...
Python
nomic_cornstack_python_v1
import json from collections import OrderedDict from enum import Enum from SimpleJSONEncoder import SimpleJSONEncoder from utils import is_elemental , is_collection , is_customized_class , hashable class RefJSONEncoder extends SimpleJSONEncoder begin function _count_ref self obj begin if call is_elemental obj begin ret...
import json from collections import OrderedDict from enum import Enum from .SimpleJSONEncoder import SimpleJSONEncoder from .utils import (is_elemental, is_collection, is_customized_class, hashable) class RefJSONEncoder(SimpleJSONEncoder): def _count_ref(self, obj): if is_elemental(obj...
Python
zaydzuhri_stack_edu_python
import numpy as np import random import os.path import matplotlib.pyplot as plt class NNmodel begin function __init__ self input_size hidden_size output_size batch_size begin set W1 = 0.1 * randn input_size hidden_size set b1 = zeros hidden_size set W2 = 0.1 * randn hidden_size output_size set b2 = zeros output_size se...
import numpy as np import random import os.path import matplotlib.pyplot as plt class NNmodel: def __init__(self, input_size, hidden_size, output_size, batch_size): self.W1 = .1 * np.random.randn(input_size, hidden_size) self.b1 = np.zeros(hidden_size) self.W2 = .1 * np.random.randn(hidden_...
Python
zaydzuhri_stack_edu_python
import hashlib import os set file_path = join string / split __file__ string / at slice : - 1 : change directory file_path import bash comment usr_dic = {} comment with open(r'/mnt/d/个人目标/my_git_hub/DATA-SCIENTIST-/python_full_stack/project/FTP/server/DB/user', 'r', encoding='utf-8') as f: comment for line in f.readli...
import hashlib import os file_path = '/'.join(__file__.split('/')[:-1]) os.chdir(file_path) import bash # usr_dic = {} # with open(r'/mnt/d/个人目标/my_git_hub/DATA-SCIENTIST-/python_full_stack/project/FTP/server/DB/user', 'r', encoding='utf-8') as f: # for line in f.readlines(): # usr_id, usr_pwd = line.split...
Python
zaydzuhri_stack_edu_python
from io import StringIO import pandas as pd import pyperclip import sys comment pdb.set_trace() ;;; 'continue' proceeds, 'next' steps import pdb import re import numpy as np comment fuzz is used to compare TWO strings from fuzzywuzzy import fuzz comment process is used to compare a string to MULTIPLE other strings from...
from io import StringIO import pandas as pd import pyperclip; import sys import pdb # pdb.set_trace() ;;; 'continue' proceeds, 'next' steps import re import numpy as np # fuzz is used to compare TWO strings from fuzzywuzzy import fuzz # process is used to compare a string to MULTIPLE other strings from fuzzywuzzy impo...
Python
zaydzuhri_stack_edu_python
from flask import Flask , request set app = call Flask __name__ function layout body begin return string <!DOCTYPE html> <html lang="en"> <head> <title>Raspberry Pi Sound Recognizer</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="styleshee...
from flask import Flask, request app = Flask(__name__) def layout(body): return f""" <!DOCTYPE html> <html lang="en"> <head> <title>Raspberry Pi Sound Recognizer</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" hre...
Python
zaydzuhri_stack_edu_python
function add_spgwc_init_containers self begin return list call V1Container name=string spgwc-dep-check image=string quay.io/stackanetes/kubernetes-entrypoint:v0.3.1 image_pull_policy=string IfNotPresent security_context=call V1SecurityContext allow_privilege_escalation=false read_only_root_filesystem=false run_as_user=...
def add_spgwc_init_containers(self) -> dict: return [ kubernetes.client.V1Container( name = "spgwc-dep-check", image = "quay.io/stackanetes/kubernetes-entrypoint:v0.3.1", image_pull_policy = "IfNotPresent", security_context = kubernete...
Python
nomic_cornstack_python_v1
function test_delete_many_documents_by_query_inline_commit self what=string commit begin set doc_count = 10 comment Same user ID will be used for all documents. set user_id = call get_rand_string set documents = list comprehension call get_rand_userdoc user_id=user_id for i in range doc_count call add_many documents co...
def test_delete_many_documents_by_query_inline_commit(self, what="commit"): doc_count = 10 # Same user ID will be used for all documents. user_id = get_rand_string() documents = [get_rand_userdoc(user_id=user_id) for i in range(doc_count)] self.conn.add_many(...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment Copyright 2007 Google Inc. comment Licensed under the Apache License, Version 2.0 (the "License"); comment you may not use this file except in compliance with the License. comment You may obtain a copy of the License at comment http://www.apache.org/licenses/LICENSE-2.0 comment Unle...
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
Python
zaydzuhri_stack_edu_python
function print_bq_insert_errors rows errors begin error string The following errors have been detected: set stopped_rows = 0 for item in errors begin set index = item at string index set row_errors = item at string errors for error in row_errors begin if error at string reason != string stopped begin error string Row n...
def print_bq_insert_errors(rows, errors): logger.error("The following errors have been detected:") stopped_rows = 0 for item in errors: index = item["index"] row_errors = item["errors"] for error in row_errors: if error["reason"] != "stopped": logger.error...
Python
nomic_cornstack_python_v1
string Created on 21 oct. 2018 @author: marlorebazaloyola from builtins import sorted import string import builtins from _functools import reduce import numpy from matplotlib.pyplot import step from pygments.lexers._vim_builtins import command string Sobre la condicional: "__name__" es un atributo especial de python qu...
''' Created on 21 oct. 2018 @author: marlorebazaloyola ''' from builtins import sorted import string import builtins from _functools import reduce import numpy from matplotlib.pyplot import step from pygments.lexers._vim_builtins import command ''' Sobre la condicional: "__name__" es un atributo especial de p...
Python
zaydzuhri_stack_edu_python
function sistema self sistema begin set _sistema = sistema end function
def sistema(self, sistema: Sistema): self._sistema = sistema
Python
nomic_cornstack_python_v1
import pandas as pd class model begin function __init__ self begin pass end function function load_img self img begin set image = img end function function load_data self df_data begin set df = df_data comment self.ordering_data() comment self.optimize_data() set current_df = df set df_for_filter_Square = call DataFram...
import pandas as pd class model: def __init__(self): pass def load_img(self, img): self.image = img def load_data(self, df_data): self.df = df_data # self.ordering_data() # self.optimize_data() self.current_df = self.df self.df_for_filter_Square ...
Python
zaydzuhri_stack_edu_python
from django.core.management.base import BaseCommand , CommandError from lines import models class Command extends BaseCommand begin set help = string Manage daily schedule function add_arguments self parser begin call add_argument string station-id call add_argument string --days string -d nargs=string + help=string Li...
from django.core.management.base import BaseCommand, CommandError from lines import models class Command(BaseCommand): help = 'Manage daily schedule' def add_arguments(self, parser): parser.add_argument('station-id') parser.add_argument('--days', '-d', nargs='+', h...
Python
zaydzuhri_stack_edu_python
from functools import lru_cache import bisect class P1 begin function threeConsecutiveOdds self arr begin set cur = 0 for x in arr begin set cur = x ? 1 * cur + x ? 1 if cur == 3 begin return true end end return false end function end class class P2 begin function minOperations_2 self n begin set m = n ? 1 ? 1 return n...
from functools import lru_cache import bisect class P1: def threeConsecutiveOdds(self, arr: [int]) -> bool: cur = 0 for x in arr: cur = (x & 1) * (cur + (x & 1)) if cur == 3: return True return False class P2: def minOperations_2(self, n: int) ->...
Python
zaydzuhri_stack_edu_python
function cloudwatch_destinations self begin return get pulumi self string cloudwatch_destinations end function
def cloudwatch_destinations(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['EventDestinationCloudwatchDestinationArgs']]]]: return pulumi.get(self, "cloudwatch_destinations")
Python
nomic_cornstack_python_v1
string 217. Contains Duplicate src: https://leetcode.com/problems/contains-duplicate/ Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. function contains_duplicate nums begin set seen = set list for num in nums begin if num in seen ...
""" 217. Contains Duplicate src: https://leetcode.com/problems/contains-duplicate/ Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. """ def contains_duplicate(nums: list[int]) -> bool: seen = set([]) for num in nums: ...
Python
zaydzuhri_stack_edu_python
function top_dimensionality self begin return sum _vocab_size end function
def top_dimensionality(self): return sum(self._vocab_size)
Python
nomic_cornstack_python_v1
function test_checksum begin call cashdec string prefix:x64nx6hz call cashdec string p:gpf8m4h7 call cashdec string bitcoincash:qpzry9x8gf2tvdw0s3jn54khce6mua7lcw20ayyn call cashdec string bchreg:555555555555555555555555555555555555555555555udxmlmrz with raises AssertionError match=string Bad checksum begin call cashde...
def test_checksum(): cashdec("prefix:x64nx6hz") cashdec("p:gpf8m4h7") cashdec("bitcoincash:qpzry9x8gf2tvdw0s3jn54khce6mua7lcw20ayyn") cashdec("bchreg:555555555555555555555555555555555555555555555udxmlmrz") with pytest.raises(AssertionError, match="Bad checksum"): cashdec("bchreg:555555555555...
Python
nomic_cornstack_python_v1
function ans k a begin sort a if k > length a begin return string -1 end else if k != 0 begin return a at length a - k end end function set tuple n k = map int split input string set arr = list map int split input string if call ans k arr == string -1 begin print string -1 end else begin print call ans k arr string ca...
def ans(k,a): a.sort() if(k>len(a)): return "-1" else: if(k!=0): return a[len(a)-k] n,k=map(int,input().split(" ")) arr=list(map(int,input().split(" "))) if (ans(k,arr)=="-1"): print("-1") else: print(ans(k,arr)," ",ans(k,arr))
Python
jtatman_500k
function run_test_on_model test model begin comment execute test set run_time = call execute_test_on_model test model with call in_dir ; open STDOUT_FILE as stdout_file begin set stdout = read stdout_file end comment look backwards in the stdout for the first non whitespaced line comment try: comment data_string = next...
def run_test_on_model(test,model): # execute test run_time = execute_test_on_model(test,model) with test.in_dir(), open(STDOUT_FILE) as stdout_file: stdout = stdout_file.read() #look backwards in the stdout for the first non whitespaced line #try: # data_string = next(itertools.ifi...
Python
nomic_cornstack_python_v1
comment Result: Time Limit Exceeded comment url: https://codeforces.com/contest/1118/problem/B function is_good ls begin set even = 0 set odd = 0 for i in range length ls begin if i % 2 == 0 begin set even = even + ls at i end else begin set odd = odd + ls at i end end return even == odd end function set n_candies = in...
# Result: Time Limit Exceeded # url: https://codeforces.com/contest/1118/problem/B def is_good(ls): even = 0 odd = 0 for i in range(len(ls)): if i % 2 == 0: even += ls[i] else: odd += ls[i] return even == odd n_candies = int(input()) weights = list(map(int, in...
Python
zaydzuhri_stack_edu_python
function default_init cls begin return call __call__ - 1 - 1 end function
def default_init(cls): return cls.__call__(-1, -1)
Python
nomic_cornstack_python_v1
function check_connection begin import subprocess set retcode = call string dhclient -1 wlan0 shell=true if retcode == 0 begin return true end else begin return false end end function
def check_connection(): import subprocess retcode = subprocess.call("dhclient -1 wlan0", shell=True) if retcode == 0: return True else: return False
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Sat Sep 7 23:09:19 2019 @author: yujzhang comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Sat Sep 7 16:38:24 2019 @author: yujzhang import pandas as pd import glob import sklearn.utils as su import sklearn.ensemb...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Sep 7 23:09:19 2019 @author: yujzhang """ #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Sep 7 16:38:24 2019 @author: yujzhang """ import pandas as pd import glob import sklearn.utils as su import sklearn.ensemble as se import sk...
Python
zaydzuhri_stack_edu_python
function addAdminResource self pluginSubPath resource begin string Add Site Resource Add a cusotom implementation of a served http resource. :param pluginSubPath: The resource path where you want to serve this resource. :param resource: The resource to serve. :return: None set pluginSubPath = strip pluginSubPath b'/' c...
def addAdminResource(self, pluginSubPath: bytes, resource: BasicResource) -> None: """ Add Site Resource Add a cusotom implementation of a served http resource. :param pluginSubPath: The resource path where you want to serve this resource. :param resource: The resource to serve. ...
Python
jtatman_500k
comment returns the mobile numbers import re set file = string input.txt set f = open file string r set pattern = string \b(0|(\+)|(91))?[6-9]\d{9}\b for tuple lineno line in enumerate f begin if search pattern line begin print lineno + 1 right strip line end end close f
#returns the mobile numbers import re file = "input.txt" f=open(file,'r') pattern=r"\b(0|(\+)|(91))?[6-9]\d{9}\b" for lineno,line in enumerate(f): if re.search(pattern,line): print(lineno + 1,line.rstrip()) f.close()
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python function getTokTweetsList filename begin set infile = open filename string r return list comprehension strip tweet for tweet in infile end function function addTokTweets tokTweets filename begin set infile = open filename string r set index = 0 for line in infile begin set line = split strip li...
#!/usr/bin/python def getTokTweetsList(filename): infile = open(filename,'r') return [tweet.strip() for tweet in infile] def addTokTweets(tokTweets,filename): infile = open(filename,'r') index = 0 for line in infile: line = line.strip().split('\t') line[4] = tokTweets[index]
Python
zaydzuhri_stack_edu_python
from itertools import groupby , chain import os , time , re function diagonalPos board columns rows begin for diag in generator expression list comprehension tuple j i - j for j in range columns for i in range columns + rows - 1 begin yield list comprehension board at i at j for tuple i j in diag if i >= 0 and j >= 0 a...
from itertools import groupby, chain import os,time,re def diagonalPos(board,columns,rows): for diag in ([(j, i - j) for j in range(columns)] for i in range(columns + rows -1)): yield [board[i][j] for i, j in diag if i >= 0 and j >= 0 and i < columns and j < rows] def diagonalNeg(board,columns,rows): ...
Python
zaydzuhri_stack_edu_python
function credential self begin return get pulumi self string credential end function
def credential(self) -> Optional['outputs.CredentialReferenceResponse']: return pulumi.get(self, "credential")
Python
nomic_cornstack_python_v1
comment Importing the libraries import pandas as pd from sklearn.neural_network import MLPClassifier from sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_score , f1_score , precision_score , recall_score import time from sklearn.ensemble import RandomForestClassifier from sklearn.neighbors ...
# Importing the libraries import pandas as pd from sklearn.neural_network import MLPClassifier from sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score import time from sklearn.ensemble import RandomForestClassifier from sklearn.neighbors import ...
Python
zaydzuhri_stack_edu_python
function ipconfig *args begin set tuple command args = call get_command_args args set proc = decode check output string ipconfig string utf-8 append return_value proc end function
def ipconfig(*args): command, args = get_command_args(args) proc = subprocess.check_output("ipconfig").decode('utf-8') return_value.append(proc)
Python
nomic_cornstack_python_v1
import pycedar set d = dictionary print length d print boolean d print list d set d at string nineteen = 19 set string twenty 20 set d at string twenty one = 21 set d at string twenty two = 22 set d at string twenty three = 23 set d at string twenty four = 24 print length d print boolean d print list d print list keys ...
import pycedar d = pycedar.dict() print(len(d)) print(bool(d)) print(list(d)) d['nineteen'] = 19 d.set('twenty', 20) d['twenty one'] = 21 d['twenty two'] = 22 d['twenty three'] = 23 d['twenty four'] = 24 print(len(d)) print(bool(d)) print(list(d)) print(list(d.keys())) print(list(d.values())) print(list(d.items()))...
Python
zaydzuhri_stack_edu_python
import random function generate_unique_url store_name product_category begin if not store_name or not product_category begin raise exception string Missing store name or product category end set url = replace lower store_name string string + string _ + replace lower product_category string string + string _ + call ge...
import random def generate_unique_url(store_name, product_category): if not store_name or not product_category: raise Exception("Missing store name or product category") url = store_name.lower().replace(" ", "") + "_" + product_category.lower().replace(" ", "") + "_" + generate_random_string(15) r...
Python
jtatman_500k
string Your task is to construct a building which will be a pile of n cubes. The cube at the bottom will have a volume of n ^ 3, the cube above will have volume of(n-1) ^ 3 and so on until the top which will have a volume of 1 ^ 3. You are given the total volume m of the building. Being given m can you find the number ...
'''Your task is to construct a building which will be a pile of n cubes. The cube at the bottom will have a volume of n ^ 3, the cube above will have volume of(n-1) ^ 3 and so on until the top which will have a volume of 1 ^ 3. You are given the total volume m of the building. Being given m can you find the number ...
Python
zaydzuhri_stack_edu_python
function deploy_cloud_console_proxy self begin return get pulumi self string deploy_cloud_console_proxy end function
def deploy_cloud_console_proxy(self) -> bool: return pulumi.get(self, "deploy_cloud_console_proxy")
Python
nomic_cornstack_python_v1
import boto3 import json function lambda_handler event context begin comment Create an SES client set ses = call client string ses comment Get the email address from the input set email = event at string email end function comment Construct the email set response = call send_email Destination=dict string ToAddresses li...
import boto3 import json def lambda_handler(event, context): # Create an SES client ses = boto3.client('ses') # Get the email address from the input email = event['email'] # Construct the email response = ses.send_email( Destination={ 'ToAddresses': [ email ] }, Message={ 'Body': { 'Text': { 'Charset': ...
Python
jtatman_500k
comment -*- coding: utf-8 -*- string Created on Thu Sep 26 15:50:32 2019 @author: Nicolas Pfeuffer comment Import libraries for our data analysis. import os import pandas as pd import numpy as np import csv comment Data Import and Pandas Intro #### comment Import our data set. comment Check your working directory first...
# -*- coding: utf-8 -*- """ Created on Thu Sep 26 15:50:32 2019 @author: Nicolas Pfeuffer """ # Import libraries for our data analysis. import os import pandas as pd import numpy as np import csv ###################################### ### Data Import and Pandas Intro #### ###################################### ...
Python
zaydzuhri_stack_edu_python
function wldap32_ldap_count_entries jitter begin set tuple ret_ad args = call func_args_stdcall list string ld string res raise call RuntimeError string API not implemented call func_ret_stdcall ret_ad ret_value end function
def wldap32_ldap_count_entries(jitter): ret_ad, args = jitter.func_args_stdcall(["ld", "res"]) raise RuntimeError('API not implemented') jitter.func_ret_stdcall(ret_ad, ret_value)
Python
nomic_cornstack_python_v1
string http://www.geeksforgeeks.org/find-a-tour-that-visits-all-stations/ import os import sys import operator import csv import itertools import math import collections import gc from itertools import groupby from sys import argv from operator import itemgetter , attrgetter , methodcaller from sys import maxsize class...
''' http://www.geeksforgeeks.org/find-a-tour-that-visits-all-stations/ ''' import os import sys import operator import csv import itertools import math import collections import gc from itertools import groupby from sys import argv from operator import itemgetter, attrgetter, methodcaller from sys import maxsize clas...
Python
zaydzuhri_stack_edu_python
function backtrack k begin global my_min if sum visit > my_min begin return end if k >= n begin set temp = sum visit if temp < my_min begin set my_min = temp end return end for i in range n begin if not visit at i begin set visit at i = data at k at i call backtrack k + 1 set visit at i = 0 end end end function for tc ...
def backtrack(k) : global my_min if sum(visit) > my_min : return if k >= n : temp = sum(visit) if temp < my_min : my_min = temp return for i in range(n) : if not visit[i] : visit[i] = data[k][i] backtrack(k+1) visit[...
Python
zaydzuhri_stack_edu_python
function cleanupAssociations self begin try begin set mist_associations = call objects end except DoesNotExist begin set mist_associations = list end set counter = 0 for assoc in mist_associations begin if call is_expired begin delete set counter = counter + 1 end end return counter end function
def cleanupAssociations(self): try: mist_associations = MistAssociation.objects() except me.DoesNotExist: mist_associations = [] counter = 0 for assoc in mist_associations: if assoc.is_expired(): assoc.delete() counter ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment part of the speech recognition nodes of chippu comment reads a string from stdin( provided by speechrecog_init.py), strips it out of unwanted characters and informations, comment and publishes the recognised speech as a message named 'speech' comment wr...
#!/usr/bin/env python # -*- coding: utf-8 -*- #part of the speech recognition nodes of chippu #reads a string from stdin( provided by speechrecog_init.py), strips it out of unwanted characters and informations, #and publishes the recognised speech as a message named 'speech' # #written by achuwilson #achu_wilson@redif...
Python
zaydzuhri_stack_edu_python
import smtplib , ssl from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText function send_email_mod sender_email=string sender_password=string receiver_emails=list email_type=string subject=string body=string attachment=none begin string Function: Sends an email as requested by user P...
import smtplib, ssl from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText def send_email_mod(sender_email='', sender_password='', receiver_emails=[], email_type='', subject='', body='', attachment=None): """ Function: Sends an email as requested by user Parameters: 1....
Python
zaydzuhri_stack_edu_python
function download_historical tickers_list output_folder begin string Download historical data from Yahoo Finance. Downloads full historical data from Yahoo Finance as CSV. The following fields are available: Adj Close, Close, High, Low, Open and Volume. Files will be saved to output_folder as <ticker>.csv. :param ticke...
def download_historical(tickers_list, output_folder): """Download historical data from Yahoo Finance. Downloads full historical data from Yahoo Finance as CSV. The following fields are available: Adj Close, Close, High, Low, Open and Volume. Files will be saved to output_folder as <ticker>.csv. :p...
Python
jtatman_500k
comment !/usr/bin/env python3 import json import pandas as pd class OwnerExtraction begin function __init__ self owner_id player_ids begin set owner_id = owner_id set player_ids = player_ids end function function __repr__ self begin return string Owner: { owner_id } Players: { player_ids } end function function __str__...
#!/usr/bin/env python3 import json import pandas as pd class OwnerExtraction: def __init__(self, owner_id, player_ids): self.owner_id = owner_id self.player_ids = player_ids def __repr__(self): return f'Owner: {self.owner_id}\nPlayers: {self.player_ids}' def __str__(self): ...
Python
zaydzuhri_stack_edu_python
string Returneaza true daca n este prim si false daca nu. function is_prime n begin comment codul vostru aici if n < 2 begin return false end for i in range 2 n // 2 + 1 begin if n % i == 0 begin return false end end return true end function string Returneaza produsul numerelor din lista lst. function get_product lst b...
''' Returneaza true daca n este prim si false daca nu. ''' def is_prime(n): # codul vostru aici if n<2: return False for i in range(2, n//2+1): if n % i == 0: return False return True ''' Returneaza produsul numerelor din lista lst. ''' def get_product(lst): # codul vostru aici p=1 ...
Python
zaydzuhri_stack_edu_python
function build_optimizer model optimizer_cfg begin if has attribute model string module begin set model = module end set optimizer_cfg = copy optimizer_cfg set paramwise_options = pop optimizer_cfg string paramwise_options none comment if no paramwise option is specified, just use the global setting if paramwise_option...
def build_optimizer(model, optimizer_cfg): if hasattr(model, 'module'): model = model.module optimizer_cfg = optimizer_cfg.copy() paramwise_options = optimizer_cfg.pop('paramwise_options', None) # if no paramwise option is specified, just use the global setting if paramwise_options is None:...
Python
nomic_cornstack_python_v1
function get_module_list self c begin if device_detected == true begin set resp = yield check output string cacli modlist end else begin set resp = string Device not connected. end end function
def get_module_list(self, c): if self.device_detected == True: resp = yield subprocess.check_output("cacli modlist") else: resp = "Device not connected."
Python
nomic_cornstack_python_v1
comment noqa: E501 # noqa: E501 function __init__ self intermission_time_remaining=none intermission_time_elapsed=none in_intermission=none begin set _intermission_time_remaining = none set _intermission_time_elapsed = none set _in_intermission = none set discriminator = none if intermission_time_remaining is not none ...
def __init__(self, intermission_time_remaining=None, intermission_time_elapsed=None, in_intermission=None): # noqa: E501 # noqa: E501 self._intermission_time_remaining = None self._intermission_time_elapsed = None self._in_intermission = None self.discriminator = None if interm...
Python
nomic_cornstack_python_v1
class Solution begin function fourSum self nums target begin comment nums 정렬 sort nums comment 정답 저장 set set ans = set comment 처음에는 nums 첫번째 index부터 세번째 index까지는 순서대로 숫자를 더함 comment 네번째 index는 처음에는 맨 마지막 index에 있는 값을 사용 comment 더하다가 target과 일치하면 그 숫자 조합을 ans에 저장하면서 comment 세번째 index는 하나씩 올리고 네번째 index는 하나씩 떨어트림 comment...
class Solution: def fourSum(self, nums: List[int], target: int) -> List[List[int]]: nums.sort() # nums 정렬 ans = set() # 정답 저장 set # 처음에는 nums 첫번째 index부터 세번째 index까지는 순서대로 숫자를 더함 # 네번째 index는 처음에는 맨 마지막 index에 있는 값을 사용 # 더하다가 target과 일치하면 그 숫자 조합을 ans에 저장하면서 ...
Python
zaydzuhri_stack_edu_python
async function getFavoriteMids self begin return await call string getFavoriteMids end function
async def getFavoriteMids(self) -> list: return await self.auth.call("getFavoriteMids")
Python
nomic_cornstack_python_v1
function detect_model_name string begin set match = match MODEL_NAME_REGEX string if match begin return call group end else begin return none end end function
def detect_model_name(string): match = re.match(MODEL_NAME_REGEX, string) if match: return match.group() else: return None
Python
nomic_cornstack_python_v1
comment importing required modules import PyPDF2 import re comment creating a pdf file object set pdfFileObj = open string 2.pdf string rb comment creating a pdf reader object set pdfReader = call PdfFileReader pdfFileObj comment printing number of pages in pdf file comment print(pdfReader.numPages) comment creating a ...
# importing required modules import PyPDF2 import re # creating a pdf file object pdfFileObj = open('2.pdf', 'rb') # creating a pdf reader object pdfReader = PyPDF2.PdfFileReader(pdfFileObj) # printing number of pages in pdf file #print(pdfReader.numPages) # creating a page object pageObj = pdf...
Python
zaydzuhri_stack_edu_python
comment coding: utf-8 comment author: ismdeep comment dateime: 2019-03-18 16:07:03 comment filename: 1307.py comment blog: https://ismdeep.com from queue import Queue function convert_nfa_to_dfa _trans_ _start_state_ _terminals_ begin set link_set = list for tuple _from_ _link_ _to_ in _trans_ begin if _link_ not in l...
# coding: utf-8 # author: ismdeep # dateime: 2019-03-18 16:07:03 # filename: 1307.py # blog: https://ismdeep.com from queue import Queue def convert_nfa_to_dfa(_trans_, _start_state_, _terminals_): link_set = [] for _from_, _link_, _to_ in _trans_: if _link_ not in link_set: link_set.appe...
Python
zaydzuhri_stack_edu_python
comment This function differentiates between a (generic) greeting and another message or question function greeting_differentiator message begin comment array with generic or common greetings created set potential_greetings = list string hello string hey string hi string greetings string hiya string good morning string...
#This function differentiates between a (generic) greeting and another message or question def greeting_differentiator (message): #array with generic or common greetings created potential_greetings = ["hello", "hey", "hi", "greetings", "hiya", "good morning", "good evening", "g'day", "howdy"] def split_lin...
Python
zaydzuhri_stack_edu_python
function get_moments_estimates_2 ordered_data begin set logs_1 = log ordered_data set logs_2 = log ordered_data ^ 2 set logs_1_cumsum = cumulative sum np logs_1 at slice : - 1 : set logs_2_cumsum = cumulative sum np logs_2 at slice : - 1 : set k_vector = array range 1 length ordered_data set M1 = 1.0 / k_vector * log...
def get_moments_estimates_2(ordered_data): logs_1 = np.log(ordered_data) logs_2 = (np.log(ordered_data))**2 logs_1_cumsum = np.cumsum(logs_1[:-1]) logs_2_cumsum = np.cumsum(logs_2[:-1]) k_vector = np.arange(1, len(ordered_data)) M1 = (1./k_vector)*logs_1_cumsum - logs_1[1:] M2 = (1./k_vector...
Python
nomic_cornstack_python_v1
import os import matplotlib.pyplot as plt import numpy as np import pandas as pd import pymc3 as pm from scipy.stats import norm , uniform import seaborn as sns comment Config change directory string /home/jovyan/work
import os import matplotlib.pyplot as plt import numpy as np import pandas as pd import pymc3 as pm from scipy.stats import norm, uniform import seaborn as sns # Config os.chdir("/home/jovyan/work")
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Tue Sep 4 14:18:50 2018 @author: khalednakhleh Copying this work is prohibited under all circumstances. import pandas as pd set df = read csv string /Users/khalednakhleh/Documents/ecen_689/ECEN689-Fall2018/Challenges/1Files/1challenge1activit...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 4 14:18:50 2018 @author: khalednakhleh Copying this work is prohibited under all circumstances. """ import pandas as pd df = pd.read_csv("/Users/khalednakhleh/Documents/ecen_689/ECEN689-Fall2018" \ "/Challenges/1Files/1challenge...
Python
zaydzuhri_stack_edu_python
comment suma macierzy o wymiarach 128x128 wygenerowanych losowo import random comment import numpy as np function random_tab n begin return list comprehension list comprehension random integer - 9 9 for x in range n for y in range n end function print call random_tab 3 function random_tab2 n begin return list comprehen...
#suma macierzy o wymiarach 128x128 wygenerowanych losowo import random #import numpy as np def random_tab(n: int): return [[random.randint(-9, 9) for x in range(n)] for y in range(n)] print(random_tab(3)) def random_tab2(n: int): return [[random.randint(-9, 9) for x in range(n)] for y in range(n)] print(r...
Python
zaydzuhri_stack_edu_python
function truncate self length begin if file == none begin raise string LuksFile has not been initialized end if length % SECTOR_SIZE != 0 begin raise string length must be a multiple of %s % SECTOR_SIZE end if length < 0 begin raise string length must be positive end call truncate integer payloadOffset * SECTOR_SIZE + ...
def truncate(self, length): if self.file == None: raise "LuksFile has not been initialized" if length % self.SECTOR_SIZE != 0: raise "length must be a multiple of %s" % self.SECTOR_SIZE if length < 0: raise "length must be positive" self.file.truncate(int(self.payloadOffset * self.SECTOR_SIZE) + le...
Python
nomic_cornstack_python_v1
function update_totals self begin set input_total = sum list comprehension value for i in inputs if value set output_total = sum list comprehension value for o in outputs if value comment self.fee = 0 if input_total begin set fee = input_total - output_total end end function
def update_totals(self): self.input_total = sum([i.value for i in self.inputs if i.value]) self.output_total = sum([o.value for o in self.outputs if o.value]) # self.fee = 0 if self.input_total: self.fee = self.input_total - self.output_total
Python
nomic_cornstack_python_v1
function filterBySpeaker self df speaker colNames lineByLevels begin if speaker == none begin return df end else begin comment print df[colNames['lineBy']].unique() set df = ix at tuple df at colNames at string lineBy == lineByLevels at speaker slice : : end end function
def filterBySpeaker(self,df,speaker, colNames, lineByLevels): if speaker == None: return df else: #print df[colNames['lineBy']].unique() df = df.ix[df[colNames['lineBy']]== lineByLevels[speaker],:]
Python
nomic_cornstack_python_v1
comment Update is useful for updating multiple key values at a time update student dict string name string Jane ; string age 26 ; string phone string 555-5555 print student del student at string age print student update student dict string age 25 print get student string age print student set age = pop student string a...
# Update is useful for updating multiple key values at a time student.update({'name': 'Jane', 'age': 26, 'phone': '555-5555'}) print(student) del student['age'] print(student) student.update({'age': 25}) print(student.get('age')) print(student) age = student.pop('age') print(student) print(age) student['age']...
Python
zaydzuhri_stack_edu_python
import os import csv from collections import Counter , defaultdict from pathlib import Path from sklearn.model_selection import train_test_split import torch import pickle from torch.utils.data import TensorDataset , random_split from torch.utils.data import DataLoader , RandomSampler , SequentialSampler import numpy a...
import os import csv from collections import Counter, defaultdict from pathlib import Path from sklearn.model_selection import train_test_split import torch import pickle from torch.utils.data import TensorDataset, random_split from torch.utils.data import DataLoader, RandomSampler, SequentialSampler import numpy as np...
Python
zaydzuhri_stack_edu_python
function build_all_reduce_device_prefixes job_name num_tasks begin string Build list of device prefix names for all_reduce. Args: job_name: "worker", "ps" or "localhost". num_tasks: number of jobs across which device names should be generated. Returns: A list of device name prefix strings. Each element spells out the f...
def build_all_reduce_device_prefixes(job_name, num_tasks): """Build list of device prefix names for all_reduce. Args: job_name: "worker", "ps" or "localhost". num_tasks: number of jobs across which device names should be generated. Returns: A list of device name prefix strings. Each element spell...
Python
jtatman_500k
function ups_account_number self begin return _ups_account_number end function
def ups_account_number(self): return self._ups_account_number
Python
nomic_cornstack_python_v1
import csv import RPi.GPIO as GPIO import time import csv import time import pandas as pd from itertools import chain import numpy as np call setmode BCM call setwarnings false set R1 = 14 comment Right side motor's 2 GPIO set R2 = 15 set L1 = 18 comment Left side motor's 2 GPIO set L2 = 23 comment left set IR1 = 19 co...
import csv import RPi.GPIO as GPIO import time import csv import time import pandas as pd from itertools import chain import numpy as np GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) R1 = 14 R2 = 15 #Right side motor's 2 GPIO L1 = 18 L2 = 23 #Left side motor's 2 GPIO IR1 = 19 #left IR2 = 1...
Python
zaydzuhri_stack_edu_python
function get_neighbors self vertex_id begin comment TODO return vertices at vertex_id end function
def get_neighbors(self, vertex_id): # TODO return self.vertices[vertex_id]
Python
nomic_cornstack_python_v1
function description self begin return get pulumi self string description end function
def description(self) -> pulumi.Output[str]: return pulumi.get(self, "description")
Python
nomic_cornstack_python_v1
for i in range n begin set p = 0 for j in a begin if j > a at i begin set p = p + 1 end end append l p end for i in range n begin set p = 0 for j in range i begin if a at j > a at i begin set p = p + 1 end end append l1 p end set ans = 0 set mod = 10 ^ 9 + 7 for i in range n begin set ans = ans + k * 2 * l1 at i + k - ...
for i in range(n): p=0 for j in a: if j>a[i]: p+=1 l.append(p) for i in range(n): p=0 for j in range(i): if a[j]>a[i]: p+=1 l1.append(p) ans=0 mod=10**9+7 for i in range(n): ans+=k*(2*l1[i]+(k-1)*(l[i]))//2 ans=ans%mod print(ans)
Python
zaydzuhri_stack_edu_python
function _aget_user_resp self response begin if error is not none begin raise call UserNotFoundError string Exception happened: %s for request %s % tuple error request end else if status != OK begin raise call UserNotFoundError string request: %s status: %s body: %s % tuple request status body end comment convert json ...
def _aget_user_resp(self, response): if response.error is not None: raise UserNotFoundError("Exception happened: %s for request %s" % (response.error, response.request)) elif response.status != httplib.OK: raise UserNotFoundError("request: %s status: %s body: %s" % ...
Python
nomic_cornstack_python_v1
function calculate_salary self begin if department == string management begin set monthly_salary = hourly_wage * hours_worked set monthly_salary = monthly_salary + monthly_salary * 0.1 end else if department == string sales begin set monthly_salary = hourly_wage * hours_worked set monthly_salary = monthly_salary + mont...
def calculate_salary(self): if self.department == "management": monthly_salary = self.hourly_wage * self.hours_worked monthly_salary += monthly_salary * 0.1 elif self.department == "sales": monthly_salary = self.hourly_wage * self.hours_worked monthly_salary += monthly_salary * 0...
Python
greatdarklord_python_dataset
function within a b **kwargs begin return call within a b keyword kwargs end function
def within(a, b, **kwargs): return lib.within(a, b, **kwargs)
Python
nomic_cornstack_python_v1
import requests import json import os string # files = ['file1.json', 'file2.json'] id = 0 for filename in os.listdir(os.getcwd()+"/products"): headers = {'Content-type': 'application/json'} req = requests.post('http://localhost:9200/test/_doc/'+str(id), data = open("./products/"+filename,'rb').read(), headers = header...
import requests import json import os """ # files = ['file1.json', 'file2.json'] id = 0 for filename in os.listdir(os.getcwd()+"/products"): headers = {'Content-type': 'application/json'} req = requests.post('http://localhost:9200/test/_doc/'+str(id), data = open("./products/"+filename,'rb').read(), headers = ...
Python
zaydzuhri_stack_edu_python
function get_items_at r s begin try begin return call get_items_at r at slice : - 2 : s + list r at - 1 + s < string o end except any begin return list end end function
def get_items_at(r,s): try:return get_items_at(r[:-2],s)+[r[-(1+(s<'o'))]] except:return[]
Python
zaydzuhri_stack_edu_python
function comp_angle_opening_magnet self begin if W0_is_rad begin return W0 end else begin comment Convert W0 from m to rad set Rbo = call get_Rbo return decimal 2 * call arcsin W0 / 2 * Rbo end end function
def comp_angle_opening_magnet(self): if self.W0_is_rad: return self.W0 else: # Convert W0 from m to rad Rbo = self.get_Rbo() return float(2 * arcsin(self.W0 / (2 * Rbo)))
Python
nomic_cornstack_python_v1
import os import gender_guesser.detector as gender from string import digits set d = call Detector case_sensitive=false set FEMALE = 0 set MALE = 1 set UNKNOWN = 2 function guessGender fullname begin set fullname = replace fullname string " string set fullname = call translate none digits set name = split fullname comm...
import os import gender_guesser.detector as gender from string import digits d = gender.Detector(case_sensitive=False) FEMALE = 0; MALE = 1; UNKNOWN = 2; def guessGender(fullname): fullname = fullname.replace('"', ' ') fullname = fullname.translate(None, digits) name = fullname.split() # if the len ...
Python
zaydzuhri_stack_edu_python
import numpy as np set a = array input string enter array set b = array input string enter array set c = a + b
import numpy as np a=np.array(input("enter array")) b=np.array(input("enter array")) c=a+b
Python
zaydzuhri_stack_edu_python
function factorial num begin if num == 1 begin return 1 end else begin return num * call factorial num - 1 end end function set ans = call factorial 5 print ans
def factorial(num): if num == 1: return 1 else: return num * factorial(num-1) ans = factorial(5) print(ans)
Python
flytech_python_25k
function update_auth self method rate_limit registration_link_timeout begin call update_auth method rate_limit registration_link_timeout end function
def update_auth(self, method, rate_limit, registration_link_timeout): self.config_manager.update_auth(method, rate_limit, registration_link_timeout)
Python
nomic_cornstack_python_v1
function __handle_include self node current_file begin if length children == 1 begin set root = children at 0 if is instance root Root begin call __handle_chapters root current_file end end end function
def __handle_include(self, node: n.Directive, current_file: FileId) -> None: if len(node.children) == 1: root = node.children[0] if isinstance(root, n.Root): self.__handle_chapters(root, current_file)
Python
nomic_cornstack_python_v1
function plot_compare_train_test decisions bins classifier ws=none begin set low = min generator expression min d for d in decisions set high = max generator expression max d for d in decisions set low_high = tuple low high comment Plot with python. figure histogram decisions at 0 color=string b alpha=0.5 range=low_hig...
def plot_compare_train_test(decisions,bins,classifier, ws=None): low = min(np.min(d) for d in decisions) high = max(np.max(d) for d in decisions) low_high = (low,high) # Plot with python. plt.figure() plt.hist(decisions[0], color='b', alpha=0.5, range=low_high, bins=bins, histtype='stepfilled',...
Python
nomic_cornstack_python_v1
comment python_deepDive part 2 , Module 2 comment python version: 3.7.3 string This module contains the following: Iterable : It is a container type of object and we can list out the elements one by one. But the order in which they come is not guranteed. for example: sets are iterable but their order is not guranteed. ...
# python_deepDive part 2 , Module 2 # python version: 3.7.3 """ This module contains the following: Iterable : It is a container type of object and we can list out the elements one by one. But the order in which they come is not guranteed. for example: sets are iterable but their order is not guranteed. ...
Python
zaydzuhri_stack_edu_python
import torch import torch.nn as nn comment noinspection PyPep8Naming import torch.nn.functional as F from torch.utils.data import DataLoader import numpy as np function train model device train_loader optimizer epoch log_interval writer=none logger=none begin string Performs one epoch of training on model :param logger...
import torch import torch.nn as nn # noinspection PyPep8Naming import torch.nn.functional as F from torch.utils.data import DataLoader import numpy as np def train(model: nn.Module, device, train_loader: torch.utils.data.DataLoader, optimizer: torch.optim.SGD, epoch, log_inter...
Python
zaydzuhri_stack_edu_python
function compute_responsibilities hdf5_file N_columns damping N_processes begin set slice_queue = call JoinableQueue set pid_list = list for i in range N_processes begin set worker = call Responsibilities_worker hdf5_file string /aff_prop_group N_columns damping slice_queue set daemon = true start worker append pid_li...
def compute_responsibilities(hdf5_file, N_columns, damping, N_processes): slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Responsibilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue) worker.d...
Python
nomic_cornstack_python_v1