code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function write_to_file fib_details
begin
comment TODO: Replace with implementation!
pass
end function | def write_to_file(fib_details: dict):
pass # TODO: Replace with implementation! | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
from django.db import models
comment imports regular expressions
import re
import bcrypt
comment Create your models here.
class UserManager extends Manager
begin
function loginVal self postData
begin
set results = dict string errors l... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
from django.db import models
import re #imports regular expressions
import bcrypt
# Create your models here.
class UserManager(models.Manager):
def loginVal(self, postData):
results = {'errors':[], 'status': False, 'user': N... | Python | zaydzuhri_stack_edu_python |
function _raise exception
begin
raise exception
end function | def _raise(exception) -> None:
raise exception | Python | nomic_cornstack_python_v1 |
from aoc_utils import load_input
set f = call load_input string
set c = 0
for pp in f
begin
set tags = list string ecl: string byr: string iyr: string hgt: string hcl: string eyr: string pid:
if all generator expression i in pp for i in tags
begin
set c = c + 1
end
end
print c | from aoc_utils import load_input
f = load_input("\n\n")
c = 0
for pp in f:
tags = ["ecl:", "byr:", "iyr:", "hgt:", "hcl:", "eyr:", "pid:"]
if all(i in pp for i in tags):
c += 1
print(c) | Python | zaydzuhri_stack_edu_python |
import re
function test_name user_name
begin
string user_name:校验用户名是否合法
if match string ^\S{2,10}$ user_name
begin
set a = true
end
else
begin
set a = false
end
return a
end function
function test_pwd user_pwd
begin
string user_name:校验用户密码是否合法,合法True,非法False
if match string ^\s*?$ user_pwd or match string ^[a-z]*?$ use... | import re
def test_name(user_name):
'''
user_name:校验用户名是否合法
'''
if re.match("^\S{2,10}$",user_name):
a = True
else:
a = False
return a
def test_pwd(user_pwd):
'''
user_name:校验用户密码是否合法,合法True,非法False
'''
if re.match("^\s*?$",user_pwd) or re.match("^[a-z]*?$",user_p... | Python | zaydzuhri_stack_edu_python |
function filter_features_by_type feats feat_type
begin
return tuple list comprehension feat for feat in feats if type feat == feat_type
end function | def filter_features_by_type(feats: FeaturesTuple, feat_type: FeatureTypeTypes) -> FeaturesTuple:
return tuple([feat for feat in feats if type(feat) == feat_type]) | Python | nomic_cornstack_python_v1 |
comment Hi Guys, Let's Start Making A Simple Project By Using Numbers
comment First, Let's Make A Code That Counts To Ten:
comment But, You Should Know That Every Code We Write Every Code We Know
for i in range 0 11
begin
print i
end | #Hi Guys, Let's Start Making A Simple Project By Using Numbers
#First, Let's Make A Code That Counts To Ten:
#But, You Should Know That Every Code We Write Every Code We Know
for i in range (0,11):
print (i)
| Python | zaydzuhri_stack_edu_python |
function __init__ self args mode=string train type=string
begin
set train_img_dir = train_img_dir
set eval_img_dir = eval_img_dir
set query_csv = query_csv
set gallery_csv = gallery_csv
set train_csv = train_csv
set mask_dir = mask_dir
set mode = mode
set ids = 0
set images = 0
if mode == string train
begin
with open t... | def __init__(self, args, mode="train", type=""):
self.train_img_dir = args.train_img_dir
self.eval_img_dir = args.eval_img_dir
self.query_csv = args.query_csv
self.gallery_csv = args.gallery_csv
self.train_csv = args.train_csv
self.mask_dir = args.mask_dir
self.mo... | Python | nomic_cornstack_python_v1 |
function play the_game
begin
print string - * 50
print string
set player = player_list at turn
print format string Turn {0} as {1} name name
print string Rolling...
set tuple die1 die2 roll = call roll
print format string {0} + {1} = {2}! die1 die2 roll
if doubles
begin
print string ** D O U B L E S ! **
if in_jail
beg... | def play(the_game):
print('-' * 50)
print('')
player = the_game.player_list[the_game.turn]
print(' Turn {0} as {1}'.format(player.name, player.piece.name))
print(' Rolling...\n')
die1, die2, roll = the_game.roll()
print(' {0} + {1} = {2}!'.format(die1, die2, roll))
if the_game.dice.double... | Python | nomic_cornstack_python_v1 |
function reverse_string s
begin
comment Convert the string into a list of characters
set chars = list s
comment Get the length of the string
set length = length chars
comment Swap characters from the beginning and end of the list
for i in range length // 2
begin
set tuple chars at i chars at length - i - 1 = tuple char... | def reverse_string(s):
# Convert the string into a list of characters
chars = list(s)
# Get the length of the string
length = len(chars)
# Swap characters from the beginning and end of the list
for i in range(length // 2):
chars[i], chars[length - i - 1] = chars[length - i - 1]... | Python | greatdarklord_python_dataset |
function leave event
begin
if event is not none
begin
call after_cancel event
set event = none
end
call hidetip
end function | def leave(event):
if tooltip.event is not None:
widget.after_cancel(tooltip.event)
tooltip.event = None
tooltip.hidetip() | Python | nomic_cornstack_python_v1 |
import json
from typing import Optional
import requests
from fastapi import FastAPI
set app = call FastAPI
function gtallposts idx
begin
set r = get requests string https://jsonplaceholder.typicode.com/posts
set pst = json r
return json r
end function
function getUser aut
begin
comment si el parametro es numérico inten... | import json
from typing import Optional
import requests
from fastapi import FastAPI
app = FastAPI()
def gtallposts(idx: int):
r = requests.get('https://jsonplaceholder.typicode.com/posts')
pst = r.json()
return r.json()
def getUser(aut: str):
# si el parametro es numérico intentará obtener... | Python | zaydzuhri_stack_edu_python |
async function async_setup_platform hass config async_add_entities discovery_info=none
begin
for device_config in config at CONF_DEVICES
begin
set host = device_config at CONF_HOST
set username = device_config at CONF_USERNAME
set password = device_config at CONF_PASSWORD
set interval = get device_config CONF_SCAN_INTE... | async def async_setup_platform(
hass, config, async_add_entities, discovery_info=None):
for device_config in config[CONF_DEVICES]:
host = device_config[CONF_HOST]
username = device_config[CONF_USERNAME]
password = device_config[CONF_PASSWORD]
interval = device_config.get(CON... | Python | nomic_cornstack_python_v1 |
function pipi pkgs
begin
return call pipil split pkgs
end function | def pipi(pkgs:str)->int:
return pipil(pkgs.split()) | Python | nomic_cornstack_python_v1 |
import time
from sys import argv
from insertion_sort import insertion_sort
from merge_sort import merge_sort
from heap import heap_sort
from quick_sort import quick_sort
from counting_sort import counting_sort
function readFromFile fileName
begin
with open fileName as file
begin
set lines = list comprehension integer s... | import time;
from sys import argv;
from insertion_sort import insertion_sort;
from merge_sort import merge_sort;
from heap import heap_sort;
from quick_sort import quick_sort;
from counting_sort import counting_sort;
def readFromFile(fileName):
with open(fileName) as file:
lines = [int(line.strip()) for line in fil... | Python | zaydzuhri_stack_edu_python |
comment Banco de dados
set bd = integer input string Quantidade de BD:
set arquivo = list
set total = 0
for i in range 0 bd
begin
append arquivo integer input string Quantidade de linhas:
set total = total + arquivo at i
end
comment Entrada
set dadosref = 0
set dadosref1 = 0
set dadosref2 = 0
for i in range 0 bd
begin... | ##Banco de dados
bd = int(input("Quantidade de BD: "))
arquivo = []
total = 0
for i in range(0,bd):
arquivo.append(int(input("Quantidade de linhas: ")))
total = total + arquivo[i]
##Entrada
dadosref = 0
dadosref1 = 0
dadosref2 = 0
for i in range(0,bd):
if arquivo[i] <= 4:
dadosref = dadosref + 1
... | Python | zaydzuhri_stack_edu_python |
string Robot in a Grid: Imagine a robot sitting on the upper left corner of grid with r rows and c columns. The robot can only move in two directions, right and down, but certain cells are "off limits"such that the robot cannot step on them. Design an algorithm to find a path for the robot from the top left to the bott... | '''
Robot in a Grid: Imagine a robot sitting on the upper left corner of grid with r rows and c columns.
The robot can only move in two directions, right and down, but certain cells are "off limits"such that
the robot cannot step on them. Design an algorithm to find a path for the robot from the top left to
the bottom ... | Python | zaydzuhri_stack_edu_python |
function Filter_By_Protein_Gap self percentage
begin
if percentage < 0 or percentage > 100
begin
return
end
set token = string QUERY
try
begin
ref_table at token
end
except KeyError
begin
set token = string query
end
set original_sequence = call Get_Seq_Text
set copy_seq = strip original_sequence string -
comment index... | def Filter_By_Protein_Gap( self, percentage ):
if( percentage < 0 or percentage > 100 ):
return
token = 'QUERY'
try:
self.ref_table[token]
except KeyError:
token = 'query'
original_sequence = self.ref_table[token].Get_Seq_... | Python | nomic_cornstack_python_v1 |
function _option_builder self var_dict var_place=string AM
begin
comment Query options line from _temp_options.
if var_place not in _temp_options
begin
set _temp_options at var_place = dict
end
set var_options = get _temp_options var_place dictionary
set dict_id = call id var_dict
if dict_id in var_options
begin
debug... | def _option_builder(self, var_dict, var_place="AM"):
# Query options line from _temp_options.
if var_place not in self._temp_options:
self._temp_options[var_place] = {}
var_options = self._temp_options.get(var_place, dict())
dict_id = id(var_dict)
if dict_id in var_o... | Python | nomic_cornstack_python_v1 |
function __init__ self vault_addr vault_token vault_kv_path
begin
set vcom = call VaultComKV vault_addr vault_token vault_kv_path
set menu_items = dict 1 list string Add/Update secret update_vault_secret ; 2 list string Read secret read_vault_secret ; 3 list string Delete secret delete_vault_secret ; 4 list string List... | def __init__(self, vault_addr: str, vault_token: str, vault_kv_path: str):
self.vcom = VaultComKV(vault_addr,vault_token,vault_kv_path)
self.menu_items = {
1: ["Add/Update secret", self.update_vault_secret],
2: ["Read secret", self.read_vault_secret],
3: ["Delete sec... | Python | nomic_cornstack_python_v1 |
comment -*- coding: UTF-8 -*-
string :Script: testing_script_07.py :Author: Dan.Patterson@carleton.ca :Modified: 2017-08-23 : :Purpose: : :Functions list ......... :...... np functions ..... : num_101() # sum product, einsum by axis : num_102() # Structured to ndarray demo : num_103() # sample plot : num_104() # fancy ... | # -*- coding: UTF-8 -*-
"""
:Script: testing_script_07.py
:Author: Dan.Patterson@carleton.ca
:Modified: 2017-08-23
:
:Purpose:
:
:Functions list .........
:...... np functions .....
: num_101() # sum product, einsum by axis
: num_102() # Structured to ndarray demo
: num_103() # sample plot
... | Python | zaydzuhri_stack_edu_python |
comment Exercise 1: Write a program which repeatedly reads numbers until the user
comment enters “done”. Once “done” is entered, print out the total, count, and average
comment of the numbers. If the user enters anything other than a number, detect their
comment mistake using try and except and print an error message a... | #Exercise 1: Write a program which repeatedly reads numbers until the user
#enters “done”. Once “done” is entered, print out the total, count, and average
#of the numbers. If the user enters anything other than a number, detect their
#mistake using try and except and print an error message and skip to the next
#number.... | Python | zaydzuhri_stack_edu_python |
import os , itertools
from collections import Counter
function file_to_list file_name
begin
string Read a text file and create a list containing lines from the file. Args: file_name: String of name and extension of the file. Returns: List of lines.
set fr = open file_name encoding=string utf-8
set l = list comprehensio... | import os, itertools
from collections import Counter
def file_to_list(file_name):
"""Read a text file and create a list containing lines from the file.
Args:
file_name: String of name and extension of the file.
Returns:
List of lines.
"""
fr = open(file_name, encoding = 'u... | Python | zaydzuhri_stack_edu_python |
function __init__ self
begin
set log = call getLogger
call navigate_to
return
end function | def __init__(self):
self.log = logging.getLogger()
XMLRepollFiles.navigate_to()
return | Python | nomic_cornstack_python_v1 |
async function run_cmd cmd
begin
set process = await call create_subprocess_shell cmd stdout=PIPE stderr=PIPE
set results = await communicate process
return join string generator expression decode x string utf-8 for x in results
end function | async def run_cmd(cmd: str) -> str:
process = await asyncio.create_subprocess_shell(
cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
)
results = await process.communicate()
return "".join(x.decode("utf-8") for x in results) | Python | nomic_cornstack_python_v1 |
function unique_id self
begin
set hash_object = md5 encode unique_id
return hex digest hash_object
end function | def unique_id(self):
hash_object = hashlib.md5(self.__zone.unique_id.encode())
return hash_object.hexdigest() | Python | nomic_cornstack_python_v1 |
from threading import Thread
import struct
from socket import *
function main
begin
function giveFile recv_ipdata
begin
set f = open string ./test.png string rb+
while true
begin
set filedata = read f
set msg = call pack string !H + string %ds % length filedata + string b5sb 3 filedata 0 string octet 0
call sendto msg ... | from threading import Thread
import struct
from socket import *
def main():
def giveFile(recv_ipdata):
f=open("./test.png","rb+")
while True:
filedata=f.read()
msg=struct.pack("!H"+"%ds"%len(filedata)+"b5sb",3,filedata,0,"octet",0)
udpsocket.sendto(msg,recv_ipda... | Python | zaydzuhri_stack_edu_python |
function find_best_answer_for_passage self start_probs end_probs passage_len=none
begin
if passage_len is none
begin
set passage_len = length start_probs
end
else
begin
set passage_len = min length start_probs passage_len
end
set tuple best_start best_end max_prob = tuple - 1 - 1 0
for start_idx in range passage_len
be... | def find_best_answer_for_passage(self, start_probs, end_probs, passage_len=None):
if passage_len is None:
passage_len = len(start_probs)
else:
passage_len = min(len(start_probs), passage_len)
best_start, best_end, max_prob = -1, -1, 0
for start_idx in range(passag... | Python | nomic_cornstack_python_v1 |
comment initialize an integer variable
set var2 = 2 + 56j
comment print the integer variables
print var1
print var2 | #initialize an integer variable
var2 = 2+56j
#print the integer variables
print(var1)
print(var2) | Python | zaydzuhri_stack_edu_python |
function pos_range_search_test
begin
print string Searching position by range:
set test_data = dict string chrom list 4 4 4 ; string start position list 169717822 136953847 154931457 ; string end position list 169717906 136954255 154931577 ; string feature name list string 470_368746_55274(PHF10)_4 string 464_319955_28... | def pos_range_search_test():
print("Searching position by range:")
test_data = {'chrom': [4, 4, 4],
'start position': [169717822, 136953847, 154931457],
'end position': [169717906, 136954255, 154931577],
'feature name': ["470_368746_55274(PHF10)_4", "464_319955... | Python | nomic_cornstack_python_v1 |
function test_anagram word1 word2
begin
if sorted word1 == sorted word2
begin
return true
end
return false
end function
string As we will see in a later chapter, sorting is typically either O(n2) or O(nlogn), so the sorting operations dominate the iteration. In the end, this algorithm will have the same order of magnit... | def test_anagram(word1, word2):
if sorted(word1) == sorted(word2):
return True
return False
"""As we will see in a later chapter, sorting is typically either O(n2) or O(nlogn),
so the sorting operations dominate the iteration. In the end,
this algorithm will have the same order of magnitude as that of the sorti... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Spyder Editor This is a temporary script file.
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
set base = read csv string credit_card_clients.csv header=1
comment somar as dividas
set base at str... | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
base = pd.read_csv('credit_card_clients.csv', header = 1)
#somar as dividas
base['BILL_TOTAL'] = base... | Python | zaydzuhri_stack_edu_python |
for i in range 0 3
begin
print a string | a + 1 string | a + 2
set a = a + 3
if i == 2
begin
break
end
print string --+ string --+ string --
end | #
for i in range(0,3):
print(a,'|',a+1,'|',a+2)
a=a+3
if i==2:
break
print('--+','--+','--')
| Python | zaydzuhri_stack_edu_python |
from tkinter import *
from tkinter import messagebox
import mysql.connector
set mydb = call connect user=string lifechoices password=string @Lifechoices1234 host=string 127.0.0.1 database=string hospital auth_plugin=string mysql_native_password
set root = call Tk
title root string Register
call geometry string 500x300
... | from tkinter import *
from tkinter import messagebox
import mysql.connector
mydb = mysql.connector.connect(user = 'lifechoices', password = '@Lifechoices1234', host = '127.0.0.1', database = 'hospital', auth_plugin='mysql_native_password')
root = Tk()
root.title("Register")
root.geometry("500x300")
userlab = Label(r... | Python | zaydzuhri_stack_edu_python |
function func str
begin
set left = 0
set right = length str - 1
while left < right
begin
if str at left != str at right
begin
return false
end
else
begin
set left = left + 1
set right = right - 1
end
end
return true
end function
if call func input
begin
print string True
end
else
begin
print string False
end | def func(str):
left=0
right=len(str)-1
while left<right:
if str[left]!=str[right]: return False
else:
left+=1
right-=1
return True
if func(input()): print("True")
else: print("False") | Python | zaydzuhri_stack_edu_python |
function joinlines lines newline=string
begin
return join string generator expression string { line } { newline } for line in lines
end function | def joinlines(lines: Iterable[str], newline: str = "\n") -> str:
return "".join(f"{line}{newline}" for line in lines) | Python | nomic_cornstack_python_v1 |
import os
function map_search directory
begin
set map_files = list
for tuple root dirnames filenames in walk directory
begin
for filename in filenames
begin
if ends with filename string .json and not starts with filename string template
begin
append map_files join path root filename
end
end
end
return map_files
end fu... | import os
def map_search(directory):
map_files = []
for root, dirnames, filenames in os.walk(directory):
for filename in filenames:
if filename.endswith('.json') and not filename.startswith('template'):
map_files.append(os.path.join(root, filename))
return map_files
| Python | zaydzuhri_stack_edu_python |
async function ttl self key
begin
return call ttl key
end function | async def ttl(self, key):
return self._redis.ttl(key) | Python | nomic_cornstack_python_v1 |
function load_checkpoint checkpoint model optimizer=none
begin
if not exists path checkpoint
begin
raise call FileNotFoundError ENOENT call strerror ENOENT checkpoint
end
set checkpoint = load torch checkpoint
load state dict model checkpoint at string state_dict
if optimizer
begin
load state dict optimizer checkpoint ... | def load_checkpoint(checkpoint, model, optimizer=None):
if not os.path.exists(checkpoint):
raise FileNotFoundError(errno.ENOENT,
os.strerror(errno.ENOENT),
checkpoint)
checkpoint = torch.load(checkpoint)
model.load_state_dict(checkpoint... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
import random
from Crypto import Random as crandom
from Crypto.Cipher import AES
from hashlib import sha1
function pad text blocksize
begin
set n = blocksize - length text % blocksize
for i in range 0 n
begin
set text = text + encode character n
end
return text
end function
function unpad stri... | #!/usr/bin/python3
import random
from Crypto import Random as crandom
from Crypto.Cipher import AES
from hashlib import sha1
def pad(text, blocksize):
n = blocksize - len(text) % blocksize
for i in range(0, n):
text += chr(n).encode();
return text
def unpad(string):
size = string[-1]
retu... | Python | zaydzuhri_stack_edu_python |
import re
function count_words sentence
begin
set new_sentence = sub string \W+ string sentence
set new_sentence = lower new_sentence
set new_sentence = replace new_sentence string _ string
set words_list = split new_sentence
set words_count = dict
for x in list string t string s string d
begin
while x in words_list
... | import re
def count_words(sentence):
new_sentence = re.sub(r"\W+", ' ', sentence)
new_sentence = new_sentence.lower()
new_sentence = new_sentence.replace('_', ' ')
words_list = new_sentence.split()
words_count = {}
for x in ["t", "s", "d"]:
while x in words_list:
i = words_... | Python | zaydzuhri_stack_edu_python |
function replace_unwanted_value_by_value_grouped tX_grouped unwanted_value value
begin
set tX_grouped_new = list
for i in range length tX_grouped
begin
append tX_grouped_new call replace_unwanted_value_by_value tX_grouped at i unwanted_value value
end
return tX_grouped_new
end function | def replace_unwanted_value_by_value_grouped(tX_grouped, unwanted_value, value):
tX_grouped_new = []
for i in range(len(tX_grouped)):
tX_grouped_new.append(
replace_unwanted_value_by_value(tX_grouped[i], unwanted_value, value)
)
return tX_grouped_new | Python | nomic_cornstack_python_v1 |
import warnings
import pickle
import re
from keras.models import load_model
from keras.preprocessing.sequence import pad_sequences
from numpy import argmax
comment load doc into memory
function load_doc filename
begin
set file = open filename string r
set text = read file
close file
return text
end function
function lo... | import warnings
import pickle
import re
from keras.models import load_model
from keras.preprocessing.sequence import pad_sequences
from numpy import argmax
# load doc into memory
def load_doc(filename):
file = open(filename, 'r')
text = file.read()
file.close()
return text
def load_test_data(filename... | Python | zaydzuhri_stack_edu_python |
function do_imgdata ipath
begin
return call imread ipath mode=string RGB
end function | def do_imgdata(ipath):
return ndimage.imread(ipath, mode='RGB') | Python | nomic_cornstack_python_v1 |
function lincomb_spectrum respath plot_level=0 inlib=false outdir=string ./ num_best=5 suffix=string
begin
set lib = call read_hdf
set sm = call read_hdf respath lib
set name = name
if inlib
begin
set targ_idx = call get_index inlib
set tuple targ_param targ_spec = lib at targ_idx
end
else
begin
set targ_param = none
e... | def lincomb_spectrum(respath, plot_level=0, inlib=False, outdir="./",
num_best=5, suffix=""):
lib = library.read_hdf()
sm = specmatch.SpecMatch.read_hdf(respath, lib)
name = sm.target.name
if inlib:
targ_idx = lib.get_index(inlib)
targ_param, targ_spec = lib[targ_id... | Python | nomic_cornstack_python_v1 |
function test_load_two_sources_incompatible_tags self
begin
comment Make an XML force field with a modified vdW 1-4 scaling factor
set nonstandard_xml_ff = replace xml_ff_w_comments string scale14="0.5" string scale14="1.0"
with raises IncompatibleParameterError match=string handler value: 0.5, incompatible value: 1.0
... | def test_load_two_sources_incompatible_tags(self):
# Make an XML force field with a modified vdW 1-4 scaling factor
nonstandard_xml_ff = xml_ff_w_comments.replace('scale14="0.5"', 'scale14="1.0"')
with pytest.raises(
IncompatibleParameterError,
match="handler value: 0.5, ... | Python | nomic_cornstack_python_v1 |
import pymongo
from common import mongo_config as config
from util import mongo_url
class MongoDB extends object
begin
set __host = none
function __init__ self collection=none
begin
set __collection = collection
set __client = call MongoClient mongo_url
end function
function get_database self database=none
begin
string... | import pymongo
from common import mongo_config as config
from util import mongo_url
class MongoDB(object):
__host = None
def __init__(self, collection=None):
self.__collection = collection
self.__client = pymongo.MongoClient(mongo_url)
def get_database(self, database=None):
"""
... | Python | zaydzuhri_stack_edu_python |
from directed_graph import DirectedGraph
import requests
class User
begin
function __init__ self user_url
begin
set user_details = json get requests user_url
set login = user_details at string login
set url = user_details at string url
set followers_url = format string https://api.github.com/users/{}/followers?client_i... | from directed_graph import DirectedGraph
import requests
class User:
def __init__(self, user_url):
user_details = requests.get(user_url).json()
self.login = user_details['login']
self.url = user_details['url']
self.followers_url = "https://api.github.com/users/{}/followers?client_... | Python | zaydzuhri_stack_edu_python |
function GCD lst
begin
set ans = lst at 0
for x in lst at slice 1 : :
begin
set ans = call gcd ans x
end
return ans
end function
function gcd a b
begin
if b == 0
begin
return a
end
else
begin
return call gcd b a % b
end
end function | def GCD(lst):
ans = lst[0]
for x in lst[1:]:
ans = gcd(ans, x)
return ans
def gcd(a, b):
if(b==0):
return a
else:
return gcd(b, a%b)
| Python | zaydzuhri_stack_edu_python |
function _parse_principal_map_frame self recipe_def compatiblity_mode
begin
comment The hard coded value "Main map" is for legacy reasons (recipe schema v0.2)
set p_map_frame = get recipe_def string principal_map_frame string Main map
if p_map_frame not in list comprehension name for mf in map_frames
begin
set err_msg ... | def _parse_principal_map_frame(self, recipe_def, compatiblity_mode):
# The hard coded value "Main map" is for legacy reasons (recipe schema v0.2)
p_map_frame = recipe_def.get('principal_map_frame', "Main map")
if p_map_frame not in [mf.name for mf in self.map_frames]:
err_msg = (
... | Python | nomic_cornstack_python_v1 |
function find_sync_light_onsets sync_light invert=true fixmissing=false
begin
comment -- Find changes in synch light --
set sync_light_diff = diff np sync_light prepend=0
if invert
begin
set sync_light_diff = - sync_light_diff
end
set sync_light_diff at sync_light_diff < 0 = 0
set sync_light_threshold = 0.2 * max
set s... | def find_sync_light_onsets(sync_light, invert=True, fixmissing=False):
# -- Find changes in synch light --
sync_light_diff = np.diff(sync_light, prepend=0)
if invert:
sync_light_diff = -sync_light_diff
sync_light_diff[sync_light_diff < 0] = 0
sync_light_threshold = 0.2*sync_light_diff.max()
... | Python | nomic_cornstack_python_v1 |
function funcargs funcstr
begin
set ps = find funcstr string (
set argstr = funcstr at slice ps + 1 : - 1 :
set pc = 0
set arglist = list
set argacc = string
for c in argstr
begin
if c == string (
begin
set pc = pc + 1
end
else
if c == string )
begin
set pc = pc - 1
end
if pc == 0 and c == string ,
begin
append argl... | def funcargs(funcstr):
ps = funcstr.find('(')
argstr = funcstr[ps+1:-1]
pc = 0
arglist = []
argacc = ''
for c in argstr:
if c == '(':
pc += 1
elif c == ')':
pc -= 1
if pc == 0 and c == ',':
arglist.append(argacc)
argacc = ''... | Python | nomic_cornstack_python_v1 |
function create_state door_model
begin
comment Create a new instance
set instance = call OpenState door_model
comment Register command for the open intent
function queue_open_intent_commands door
begin
string This method add commands for the open intent to the door command queue.
put call SetIntentCommand IDLE_INTENT
e... | def create_state(door_model):
# Create a new instance
instance = OpenState(door_model)
# Register command for the open intent
def queue_open_intent_commands(door):
"""This method add commands for the open intent to the door command queue."""
door.command_queue.p... | Python | nomic_cornstack_python_v1 |
from unittest import TestCase
from unittest.mock import Mock , patch
from device.led.connection import Connection , BTConnectError
from bluepy.btle import BTLEDisconnectError
decorator patch string device.led.connection.bluepy.btle
class TestConnection extends TestCase
begin
function test_get_device_by_mac self btle_mo... | from unittest import TestCase
from unittest.mock import Mock, patch
from device.led.connection import Connection, BTConnectError
from bluepy.btle import BTLEDisconnectError
@patch("device.led.connection.bluepy.btle")
class TestConnection(TestCase):
def test_get_device_by_mac(self, btle_mock):
btle_mock.P... | Python | zaydzuhri_stack_edu_python |
function backward_p self x
begin
set tuple log_det_jacob z = tuple call new_zeros shape at 0 x
for i in reversed range length t
begin
set z_ = mask at i * z
set s = call z_ * 1 - mask at i
set t = call z_ * 1 - mask at i
set z = 1 - mask at i * z - t * exp - s + z_
set log_det_jacob = log_det_jacob - sum dim=1
end
retu... | def backward_p(self, x):
log_det_jacob, z = x.new_zeros(x.shape[0]), x
for i in reversed(range(len(self.t))):
z_ = self.mask[i] * z
s = self.s[i](z_) * (1 - self.mask[i])
t = self.t[i](z_) * (1 - self.mask[i])
z = (1 - self.mask[i]) * (z - t) * torch.exp(-... | Python | nomic_cornstack_python_v1 |
import numpy as np
import cv2
comment Create a black image
set img = zeros tuple 512 512 3 uint8
comment Draw a diagonal blue lin with a thickness of 5 px
set img = call line img tuple 0 0 tuple 511 511 tuple 255 0 0 5
image show string image img
call waitKey 0 | import numpy as np
import cv2
# Create a black image
img = np.zeros((512, 512, 3), np.uint8)
# Draw a diagonal blue lin with a thickness of 5 px
img = cv2.line(img, (0, 0), (511, 511), (255, 0, 0), 5)
cv2.imshow('image', img)
cv2.waitKey(0) | Python | zaydzuhri_stack_edu_python |
comment How do we make the animation from one year to another "smooth"? We need to add
comment a bunch of points in between.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from vega_datasets import data
comment https://stackoverflow.com/questions/45... | # How do we make the animation from one year to another "smooth"? We need to add
# a bunch of points in between.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from vega_datasets import data
# https://stackoverflow.com/questions/45846765/efficient... | Python | zaydzuhri_stack_edu_python |
import json
import re
from urllib import error , request
class MixcloudTrack
begin
function __init__ self url server_count=30
begin
string :type url: str :param url: link to track at mixcloud.com :type server_count: int :param server_count: maximum server index
set download_url = string
set name = string
set owner = ... | import json
import re
from urllib import error, request
class MixcloudTrack:
def __init__(self, url, server_count=30):
"""
:type url: str
:param url: link to track at mixcloud.com
:type server_count: int
:param server_count: maximum server index
"""
self.dow... | Python | zaydzuhri_stack_edu_python |
function remap_xesmf self dataarray method=string bilinear **kwargs
begin
if has_xesmf
begin
from util import resample
comment check to see if grid is supplied
set target = call _rename_latlon _obj
set source = call _rename_latlon dataarray
set out = call resample_xesmf source target method=method keyword kwargs
return... | def remap_xesmf(self, dataarray, method='bilinear', **kwargs):
if has_xesmf:
from .util import resample
# check to see if grid is supplied
target = _rename_latlon(self._obj)
source = _rename_latlon(dataarray)
out = resample.resample_xesmf(source,
... | Python | nomic_cornstack_python_v1 |
string Make a list or tuple containing a series of 10 numbers and five letters. Randomly select four numbers or letters from the list and print a message saying that any ticket with these four numbers or letters wins prize.
from random import choice
set num_letter = tuple 3 string c 8 string a 1 string z 7 5 string v 8... | """Make a list or tuple containing a series of 10 numbers and five letters.
Randomly select four numbers or letters from the list and print a message
saying that any ticket with these four numbers or letters wins prize."""
from random import choice
num_letter = (3,'c',8,'a',1,'z',7,5,'v',8,'x','p','o','q',0,'h','w',... | Python | zaydzuhri_stack_edu_python |
function release self num_instances=1
begin
string The current process releases instances it has previously taken. It may thus release less than it has taken. These released instances become free. If the total number of free instances then satisfy the request of the top process of the waiting queue, it is popped off th... | def release(self, num_instances: int = 1) -> None:
"""
The current process releases instances it has previously taken. It may thus release less than it has taken.
These released instances become free. If the total number of free instances then satisfy the request of the top
process of th... | Python | jtatman_500k |
import urllib.request , re
set data = 63579
set Url = string http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=
set pattern = compile string (\D+)(\d+).*
print call group 2
while true
begin
set url = Url + string data
print url
set response = url open url
set parsedValue = string decode read response string ... | import urllib.request,re
data=63579;
Url='http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing='
pattern=re.compile(r'(\D+)(\d+).*')
print(pattern.match('and the next nothing is 45439').group(2))
while True:
url=Url+str(data)
print(url)
response = urllib.request.urlopen(url)
parsedValue=str(response.read(... | Python | zaydzuhri_stack_edu_python |
function right_click self event
begin
pass
end function | def right_click(self, event):
pass | Python | nomic_cornstack_python_v1 |
function get_separate_bar
begin
set bar_lenght = 60
set separate_bar = bar_lenght * string -
return separate_bar
end function
function set_heading_for_display
begin
set display = list
set separate_bar = call get_separate_bar
append display separate_bar
set heading = format string {0:{algin}{width}}|{1:{algin}{width}}|... | def get_separate_bar():
bar_lenght = 60
separate_bar = bar_lenght * '-'
return separate_bar
def set_heading_for_display():
display = []
separate_bar = get_separate_bar()
display.append(separate_bar)
heading = '{0:{algin}{width}}|{1:{algin}{width}}|{2:{algin}{width}}'.format('INDEX', 'NAME... | Python | zaydzuhri_stack_edu_python |
async function minidraft self ctx opponent
begin
set challenger = author
if opponent == challenger
begin
await call say string You cant challenge yourself delete_after=autodeletetime
return
end
set l = string
if invoked_subcommand is none
begin
set noleg = false
end
else
begin
set noleg = true
set l = string No legend... | async def minidraft(self, ctx, opponent:discord.Member):
challenger = ctx.message.author
if opponent == challenger:
await self.bot.say("You cant challenge yourself", delete_after=autodeletetime)
return
l = ""
if ctx.invoked_subcommand is None:
noleg = False
else:
noleg = True
l = "\nNo le... | Python | nomic_cornstack_python_v1 |
function __ne__ self other
begin
if not is instance other ShapeResourceAttributes
begin
return true
end
return call to_dict != call to_dict
end function | def __ne__(self, other):
if not isinstance(other, ShapeResourceAttributes):
return True
return self.to_dict() != other.to_dict() | Python | nomic_cornstack_python_v1 |
function do_PUT self
begin
if path at - 1 == string /
begin
call send_error 400 string Can PUT a directory
return none
end
set content_length = call getContentLength
if content_length == none
begin
return none
end
set data = read rfile content_length
set ind = reverse find path string / + 1
set path = path at slice 0 :... | def do_PUT(self):
if self.path[-1] == '/':
self.send_error(400, 'Can PUT a directory')
return None
content_length = self.getContentLength()
if(content_length == None):
return None
data = self.rfile.read(content_length)
ind = self.path.rfind('/') + 1
path = self.p... | Python | nomic_cornstack_python_v1 |
function bfsfilepaths lane starttime rcumode bf_data_dir port0 stnid compress=true
begin
set port = port0 + lane
set tuple pre_bf_dir pst_bf_dir = split bf_data_dir string ?
set outdumpdir = pre_bf_dir + string lane + pst_bf_dir
set outfilepre = string udp_ + stnid
set outarg = join path outdumpdir outfilepre
set dumpl... | def bfsfilepaths(lane, starttime, rcumode, bf_data_dir, port0, stnid,
compress=True):
port = port0 + lane
pre_bf_dir, pst_bf_dir = bf_data_dir.split('?')
outdumpdir = pre_bf_dir + str(lane) + pst_bf_dir
outfilepre = "udp_" + stnid
outarg = os.path.join(outdumpdir, outfilepre)
du... | Python | nomic_cornstack_python_v1 |
for j in range m n + 1
begin
set c = 0
for i in range 2 j
begin
if j % i == 0
begin
set c = c + 1
end
end
if c == 0
begin
if k == n
begin
set k = j
end
else
if k + 2 == j
begin
print string twin number k string , j
set k = j
end
else
if j % 2 != 0
begin
set k = j
end
end
end | for j in range(m,n+1):
c=0;
for i in range(2,j):
if(j%i)==0:
c=c+1
if(c==0):
if(k==n):
k=j
elif(k+2==j):
print("twin number",k,",",j)
k=j
else:
if(j%2!=0)... | Python | zaydzuhri_stack_edu_python |
from lxml import html
import requests
import csv
set url = string https://www.phonecurry.com/best-phones
set resp = get requests url
set tree = call fromstring content
set Product_url = call xpath string //*[@id="page-content-wrapper"]/div[3]/div[3]/div[2]/div/div/ol/li/div[@class="row mobile-list-item"]/div[3]/a[@clas... | from lxml import html
import requests
import csv
url = 'https://www.phonecurry.com/best-phones'
resp = requests.get(url)
tree = html.fromstring(resp.content)
Product_url = tree.xpath('//*[@id="page-content-wrapper"]/div[3]/div[3]/div[2]/div/div/ol/li/div[@class="row mobile-list-item"]/div[3]/a[@class="phone-name"]/@hr... | Python | zaydzuhri_stack_edu_python |
function Xsubmatrix k t standardizeData=true
begin
set tuple K N = tuple length k length t
set X = zeros tuple N K
for i in range N
begin
for j in range K
begin
set X at tuple i j = exp - 1.0 * k at j * t at i
end
end
set Xmean = mean X axis=0
if standardizeData
begin
for j in range K
begin
set X at tuple slice : : ... | def Xsubmatrix(k,t, standardizeData=True):
K, N = len(k), len(t)
X = np.zeros( (N,K) )
for i in range(N):
for j in range(K):
X[i,j] = np.exp(-1.0*k[j]*t[i])
Xmean = X.mean(axis=0)
if standardizeData:
for j in range(K):
X[:,j] = X[:,j] - Xmean[j]
return X, Xmean | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Tue Oct 2 14:53:31 2018 @author: Mithilesh
function ISBN n
begin
set n = list string n
set sum1 = 0
if length n == 10
begin
for i in range 0 10
begin
set sum1 = sum1 + integer n at i * i + 1
end
if sum1 % 11 == 0
begin
print string Legal ISBN
end
end
else
begin
print stri... | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 2 14:53:31 2018
@author: Mithilesh
"""
def ISBN(n):
n=list(str(n))
sum1=0
if len(n)==10:
for i in range(0,10):
sum1+=int(n[i])*(i+1)
if sum1%11==0:
print("Legal ISBN")
else:
print("Illegal ISBN")
n=int(inp... | Python | zaydzuhri_stack_edu_python |
function is_upstream self destination_id
begin
set _difference = destination_id - ram_id
if _difference < 0
begin
set _difference = _difference + num_nodes
end
if _difference <= num_nodes / 2
begin
return false
end
else
begin
return true
end
end function | def is_upstream(self, destination_id):
_difference = destination_id - self.ram_id
if _difference < 0:
_difference += self.model.network.num_nodes
if _difference <= self.model.network.num_nodes / 2:
return False
else:
return True | Python | nomic_cornstack_python_v1 |
function __init__ self wagtail_image *args **kwargs
begin
set wagtail_image = wagtail_image
set file = file
call __init__ instance field name *args keyword kwargs
end function | def __init__(self, wagtail_image, *args, **kwargs):
self.wagtail_image = wagtail_image
file = wagtail_image.file
super(WagtailThumbnailerImageFieldFile, self).__init__(file.instance, file.field, file.name, *args, **kwargs) | Python | nomic_cornstack_python_v1 |
import player as p
set numPlayers = - 1 | import player as p
numPlayers = -1 | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
string increments lines for play
import rospy
from std_msgs.msg import Int32
function incrementCallback data
begin
set increment = data
set increment = increment + 1
call publish increment
return
end function
call init_node string Counter
set line_num = call Publisher string /lines Int32 qu... | #!/usr/bin/env python
'''
increments lines for play
'''
import rospy
from std_msgs.msg import Int32
def incrementCallback(data):
increment = data.data
increment = increment + 1
line_num.publish(increment)
return
rospy.init_node("Counter")
line_num = rospy.Publisher('/lines', Int32, queue_size=1)
rospy.Subscr... | Python | zaydzuhri_stack_edu_python |
comment print (a)
comment вывод перевернуттого числа после расчета
print integer outres
comment вывод числа якобы перевернутым при помощи slice
print string integer a at slice : : - 1 | #print (a)
print(int(outres)) #вывод перевернуттого числа после расчета
print(str(int(a))[::-1]) #вывод числа якобы перевернутым при помощи slice | Python | zaydzuhri_stack_edu_python |
function read file
begin
set f = open file
comment skipping first line
next f
set x = list
for line in f
begin
set y = list comprehension decimal value for value in split line
append x y
end
close f
set x2 = filter none x
return x2
end function | def read(file):
f = open(file)
next(f) #skipping first line
x = []
for line in f:
y = [float(value) for value in line.split()]
x.append( y )
f.close()
x2 = filter(None, x)
return x2 | Python | nomic_cornstack_python_v1 |
function update_terminal_regions self tree X y residual y_pred sample_weight sample_mask learning_rate=1.0 k=0
begin
comment compute leaf for each sample in ``X``.
set terminal_regions = apply tree X
comment mask all which are not in sample mask.
set masked_terminal_regions = copy terminal_regions
set masked_terminal_r... | def update_terminal_regions(self, tree, X, y, residual, y_pred,
sample_weight, sample_mask,
learning_rate=1.0, k=0):
# compute leaf for each sample in ``X``.
terminal_regions = tree.apply(X)
# mask all which are not in sample mask.... | Python | nomic_cornstack_python_v1 |
async function async_setup_entry hass config_entry async_add_entities
begin
call async_add_entities list call DemoSensor string statistics_issue_1 string Statistics issue 1 100 none MEASUREMENT WATT call DemoSensor string statistics_issue_2 string Statistics issue 2 100 none MEASUREMENT string dogs call DemoSensor stri... | async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
async_add_entities(
[
DemoSensor(
"statistics_issue_1",
"Statistics issue 1",
100,
None,
... | Python | nomic_cornstack_python_v1 |
function rpc_database_get_row_by_id self row_id
begin
set table_name = split path string / at - 2
set table = get DATABASE_TABLE_OBJECTS table_name
assert table
set columns = DATABASE_TABLES at table_name
set session = call Session
set row = call get_row_by_id session table row_id
if row
begin
set row = dictionary zip ... | def rpc_database_get_row_by_id(self, row_id):
table_name = self.path.split('/')[-2]
table = DATABASE_TABLE_OBJECTS.get(table_name)
assert table
columns = DATABASE_TABLES[table_name]
session = db_manager.Session()
row = db_manager.get_row_by_id(session, table, row_id)
if row:
row = dict(zip(columns, (ge... | Python | nomic_cornstack_python_v1 |
function _read_length self
begin
set byte = call _read_byte
if byte ? 128
begin
set count = byte ? 127
if count == 127
begin
raise error string ASN1 syntax error
end
set bytes = call _read_bytes count
set bytes = list comprehension b for b in bytes
set length = 0
for byte in bytes
begin
if is instance byte str
begin
se... | def _read_length(self):
byte = self._read_byte()
if byte & 0x80:
count = byte & 0x7f
if count == 0x7f:
raise Error('ASN1 syntax error')
bytes = self._read_bytes(count)
bytes = [ b for b in bytes ]
length = 0
for byte... | Python | nomic_cornstack_python_v1 |
function upstream self
begin
comment this is jus syntactic sugar, upstream relations are tracked by the
comment DAG object
comment this always return a copy to prevent global state if contents
comment are modified (e.g. by using pop)
return call _get_upstream name
end function | def upstream(self):
# this is jus syntactic sugar, upstream relations are tracked by the
# DAG object
# this always return a copy to prevent global state if contents
# are modified (e.g. by using pop)
return self.dag._get_upstream(self.name) | Python | nomic_cornstack_python_v1 |
import scipy.optimize
comment Execute optimization
set mini = call minimize_scalar func=func bounds=interval
comment Print optimal value x_opt
print format string {0:5.5f} x | import scipy.optimize
# Execute optimization
mini = scipy.optimize.minimize_scalar(func = func,
bounds = interval)
# Print optimal value x_opt
print('{0:5.5f}'.format(mini.x))
| Python | flytech_python_25k |
comment Separate the indoorCVPR_09 dataset into train and eval subsets according the given TestImage labels
import os
from shutil import copyfile , move
set dataset_dir = string /home/data/indoorCVPR_09/
set image_folder = string Images
set testImageLabel_file = string TestImages.txt
comment Create the train and eval f... | # Separate the indoorCVPR_09 dataset into train and eval subsets according the given TestImage labels
import os
from shutil import copyfile, move
dataset_dir = "/home/data/indoorCVPR_09/"
image_folder = "Images"
testImageLabel_file = "TestImages.txt"
# Create the train and eval folder
train_dir = os.path.join(datase... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import string , random
from collections import Counter
import getopt , sys
import pickle
import datetime
function train
begin
with open string train.tagged string r as f
begin
set lines = list comprehension line for line in f
comment initialize
set word_tag_counts = counter
set word_counts = counter
... | import numpy as np
import string, random
from collections import Counter
import getopt, sys
import pickle
import datetime
def train():
with open('train.tagged', 'r') as f:
lines = [line for line in f]
word_tag_counts = Counter() #initialize
word_counts = Counter()
... | Python | zaydzuhri_stack_edu_python |
import arithmetic
import itertools
function interpret expression
begin
set elementList = list
for i in expression
begin
comment List of all elements in the expression
append elementList i
end
set isNumber = false
comment List of symbol indexes in the string
set symbolList = list
set allowedNums = list string 0 string... | import arithmetic
import itertools
def interpret(expression):
elementList = []
for i in expression:
elementList.append(i) #List of all elements in the expression
isNumber = False
symbolList = [] #List of symbol indexes in the string
allowedNums = ["0", "1", "2", "3", "4", "5", "6", "7", "8",... | Python | zaydzuhri_stack_edu_python |
function remove_sample self i
begin
set indices = get attribute format string {}.sample name mi=true or list
if i not in indices
begin
raise call RuntimeError format string Sample {} does not exist. i
end
call removeMultiInstance format string {}.sample[{}] name i all=true b=true
end function | def remove_sample(self, i):
indices = cmds.getAttr("{}.sample".format(self.name), mi=True) or []
if i not in indices:
raise RuntimeError("Sample {} does not exist.".format(i))
cmds.removeMultiInstance("{}.sample[{}]".format(self.name, i), all=True, b=True) | Python | nomic_cornstack_python_v1 |
comment given list of numbers
set nums = list 1 2 3 4 5 6 7 8 9 10
comment empty list for even numbers
set even_list = list
comment iterate over the list
for num in nums
begin
comment check if number is even
if num % 2 == 0
begin
comment append number to even list
append even_list num
end
end
comment print even number... | # given list of numbers
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# empty list for even numbers
even_list = []
# iterate over the list
for num in nums:
# check if number is even
if num % 2 == 0:
# append number to even list
even_list.append(num)
# print even numbers
print(even_list) | Python | iamtarun_python_18k_alpaca |
comment test
from ROOT import TTree , TFile
from array import array
from random import gauss
set output_file = open string output.root string recreate
set some_float = array string f list 0.0
set some_int = array string i list 0
set tree = call TTree string mytree string
call Branch string some_float some_float string ... | # test
from ROOT import TTree, TFile
from array import array
from random import gauss
output_file = TFile.Open('output.root', 'recreate')
some_float = array('f', [0.])
some_int = array('i', [0])
tree = TTree('mytree', '')
tree.Branch('some_float', some_float, 'some_float/F')
tree.Branch('some_int', some_int, 'some_int... | Python | zaydzuhri_stack_edu_python |
function integrate self dt
begin
set f = lambda t y -> Cm * dot phi call activation y + dot phi_input call activation input - Gm * y
set Vm = call rk4 t Vm t + dt f
end function | def integrate(self, dt):
f = lambda t, y: self.Cm * (np.dot(self.phi, self.activation(y)) + np.dot(self.phi_input, self.activation(self.input)) - self.Gm * y)
self.Vm = rk4(self.t, self.Vm, self.t + dt, f) | Python | nomic_cornstack_python_v1 |
function copy_dir_js dst
begin
import shutil
import os
import glob
comment ./js/*
set pattern = directory name path absolute path path __file__ + string /js/*
set li_files = glob glob pattern
for f in li_files
begin
copy shutil f dst
end
end function | def copy_dir_js(dst):
import shutil
import os
import glob
pattern = os.path.dirname(os.path.abspath(__file__)) + "/js/*" # ./js/*
li_files = glob.glob(pattern)
for f in li_files:
shutil.copy(f, dst) | Python | nomic_cornstack_python_v1 |
function append_response self response
begin
append generated_responses response
end function | def append_response(self, response: str):
self.generated_responses.append(response) | Python | nomic_cornstack_python_v1 |
function importAsNumPyArray self
begin
try
begin
print call to_numpy
return call to_numpy
end
except ValueError as value_error
begin
raise call ValueError value_error
end
end function | def importAsNumPyArray(self):
try:
print(self.main_dataframe.to_numpy())
return self.main_dataframe.to_numpy()
except ValueError as value_error:
raise ValueError(value_error) | Python | nomic_cornstack_python_v1 |
comment You are given a string S.
comment contains alphanumeric characters only.
comment Your task is to sort the string S in the following manner:
comment All sorted lowercase letters are ahead of uppercase letters.
comment All sorted uppercase letters are ahead of digits.
comment All sorted odd digits are ahead of so... | # You are given a string S.
# contains alphanumeric characters only.
# Your task is to sort the string S in the following manner:
# All sorted lowercase letters are ahead of uppercase letters.
# All sorted uppercase letters are ahead of digits.
# All sorted odd digits are ahead of sorted even digits.
# Input Format
# ... | Python | zaydzuhri_stack_edu_python |
for tuple a b c in mapped
begin
print string roll number: a string name: b string marks: c
end | for a,b,c in mapped:
print("roll number:",a,"name:",b,"marks:",c)
| Python | zaydzuhri_stack_edu_python |
function __init__ __self__ resource_name args opts=none
begin
Ellipsis
end function | def __init__(__self__,
resource_name: str,
args: MetaTagArgs,
opts: Optional[pulumi.ResourceOptions] = None):
... | Python | nomic_cornstack_python_v1 |
function is_sorted arr
begin
comment Base case: an empty list or a list with a single element is always considered sorted
if length arr <= 1
begin
return true
end
comment Recursive case: check if the first two elements are in non-decreasing order,
comment and recursively check the rest of the list
return arr at 0 <= ar... | def is_sorted(arr):
# Base case: an empty list or a list with a single element is always considered sorted
if len(arr) <= 1:
return True
# Recursive case: check if the first two elements are in non-decreasing order,
# and recursively check the rest of the list
return arr[0] <= arr[1] an... | Python | jtatman_500k |
import numpy as np
import stellargraph as sg
from keras import Sequential
from keras.layers import Dense , Dropout
from keras.models import Model
from sklearn.metrics import accuracy_score
from tensorflow.keras import losses
from sklearn import model_selection
from stellar_graph_demo.visualisation import tsne_plot_embe... | import numpy as np
import stellargraph as sg
from keras import Sequential
from keras.layers import Dense, Dropout
from keras.models import Model
from sklearn.metrics import accuracy_score
from tensorflow.keras import losses
from sklearn import model_selection
from stellar_graph_demo.visualisation import tsne_plot_emb... | Python | zaydzuhri_stack_edu_python |
function make_sparkunion *transformers
begin
return call SparkFeatureUnion call _name_estimators transformers
end function | def make_sparkunion(*transformers):
return SparkFeatureUnion(_name_estimators(transformers)) | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.