code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment 2020.1.11 dwango#6 A
set N = integer input
set lst = list
for _ in range N
begin
append lst list split input
end
set X = input
set t = 0
for tuple i l in enumerate lst
begin
if l at 0 == X
begin
for j in range i + 1 N
begin
set t = t + integer lst at j at 1
end
end
end
print t | # 2020.1.11 dwango#6 A
N = int(input())
lst = []
for _ in range(N):
lst.append(list(input().split()))
X = input()
t = 0
for i,l in enumerate(lst):
if l[0] == X:
for j in range(i+1,N):
t+=int(lst[j][1])
print(t) | Python | zaydzuhri_stack_edu_python |
function save_shorten_url self
begin
pass
end function | def save_shorten_url(self):
pass | Python | nomic_cornstack_python_v1 |
function find_days a_string
begin
set days = list string Mon string Tue string Wed string Thu string Fri string Sat string Sun
set this_loc_days = list
set a_list = split a_string string
if string Both in a_list
begin
for day in days
begin
if day in a_list
begin
append this_loc_days day
end
end
end
end function | def find_days(a_string):
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
this_loc_days = []
a_list = a_string.split(" ")
if "Both" in a_list:
for day in days:
if day in a_list:
this_loc_days.append(day) | Python | zaydzuhri_stack_edu_python |
function removeOutOfBounds self pieces
begin
set newPieces = set
for tuple i j in pieces
begin
if call withinBounds i j and not call isCorner i j
begin
add newPieces tuple i j
end
end
return newPieces
end function | def removeOutOfBounds(self, pieces):
newPieces = set()
for i, j in pieces:
if self.withinBounds(i, j) and not self.isCorner(i, j):
newPieces.add((i, j))
return newPieces | Python | nomic_cornstack_python_v1 |
function test_literal_chain_replace self
begin
call mktemp string searches.txt content=encode call dedent string search1 search1 search2 search2 search3 search3 search1, search2, search3 string utf-8
set after = call dedent string replace1 replace1 replace2 replace2 search3 search3 replace1, replace2, search3
set searc... | def test_literal_chain_replace(self):
self.mktemp(
'searches.txt',
content=self.dedent(
'''
search1
search1
search2
search2
search3
search3
search1, search2... | Python | nomic_cornstack_python_v1 |
comment coding=utf-8
string leetcode 30. substring with concatenation of all words url: https://leetcode-cn.com/problems/substring-with-concatenation-of-all-words/
import copy
from collections import Counter
function findSubstring s words
begin
string 滑动窗口 640 ms/12.3 MB :type s: str :type words: List[str] :rtype: List... | # coding=utf-8
"""
leetcode 30. substring with concatenation of all words
url: https://leetcode-cn.com/problems/substring-with-concatenation-of-all-words/
"""
import copy
from collections import Counter
def findSubstring(s, words):
"""
滑动窗口
640 ms/12.3 MB
:type s: str
:type words: List[str]
:... | Python | zaydzuhri_stack_edu_python |
function stations
begin
comment Query list of stations and counts
set results = all
comment Convert the query results to a list of stations inside Dicitonary
set all_stations = list
for row in results
begin
set station_dict = dict
set station_dict at string station = row at 0
set station_dict at string count = row at... | def stations():
# Query list of stations and counts
results = session.query(Measurement.station, func.count(Measurement.station)).\
group_by(Measurement.station).\
order_by(func.count(Measurement.station).desc()).all()
# Convert the query results to a list of stations inside... | Python | nomic_cornstack_python_v1 |
from typing import List , Any
function recursive_sum arr
begin
string Рекурсивная функция подсчета суммы элементов списка. Метод решения задачи основан на принципе "Разделяй и влавствуй". :param arr: Входной список элементов :return: Сумма элементов списка
if length arr == 0
begin
return 0
end
return arr at 0 + call re... | from typing import List, Any
def recursive_sum(arr: List[Any]) -> int:
"""
Рекурсивная функция подсчета суммы элементов списка.
Метод решения задачи основан на принципе "Разделяй и влавствуй".
:param arr: Входной список элементов
:return: Сумма элементов списка
"""
if len(arr) == 0:
... | Python | zaydzuhri_stack_edu_python |
string Created on Apr 4, 2012 @author: tambetm
import msgParser
import carState
import carControl
import numpy as np
import random
class Driver extends object
begin
string A driver object for the SCRC
function __init__ self args
begin
string Constructor
set parser = call MsgParser
set state = call CarState
set control ... | '''
Created on Apr 4, 2012
@author: tambetm
'''
import msgParser
import carState
import carControl
import numpy as np
import random
class Driver(object):
'''
A driver object for the SCRC
'''
def __init__(self, args):
'''Constructor'''
self.parser = msgParser.MsgParser()
self.... | Python | zaydzuhri_stack_edu_python |
function unread self include_deleted=false
begin
string Return only unread items in the current queryset
if call is_soft_delete and not include_deleted
begin
return filter unread=true deleted=false
end
comment When SOFT_DELETE=False, developers are supposed NOT to touch 'deleted' field.
comment In this case, to improve... | def unread(self, include_deleted=False):
"""Return only unread items in the current queryset"""
if is_soft_delete() and not include_deleted:
return self.filter(unread=True, deleted=False)
# When SOFT_DELETE=False, developers are supposed NOT to touch 'deleted' field.
# In th... | Python | jtatman_500k |
function _get_data self
begin
set data = call get_data
set required_data = list string open string close string open_date string high string low
if not all
begin
raise call ImplementationError string Data must contain columns: { required_data }
end
set data = sort values data string open_date
set index = open_date
set ... | def _get_data(self):
data = self.get_data()
required_data = ['open','close','open_date','high','low']
if not np.isin(required_data, data.columns).all():
raise ImplementationError(f'''
Data must contain columns: {required_data}
''')
data = data.s... | Python | nomic_cornstack_python_v1 |
function expire_leaderboard_for self leaderboard_name seconds
begin
string Expire the given leaderboard in a set number of seconds. Do not use this with leaderboards that utilize member data as there is no facility to cascade the expiration out to the keys for the member data. @param leaderboard_name [String] Name of t... | def expire_leaderboard_for(self, leaderboard_name, seconds):
'''
Expire the given leaderboard in a set number of seconds. Do not use this with
leaderboards that utilize member data as there is no facility to cascade the
expiration out to the keys for the member data.
@param lead... | Python | jtatman_500k |
import RPi.GPIO as gpio
import time
call setmode BCM
setup gpio 5 OUT
setup gpio 6 OUT
setup gpio 13 OUT
comment fazer um programa para piscar led x vezes
comment in range: numa determinada faixa, no caso,10x
for x in range 1 10
begin
comment configura saida // 2 parametros: a porta e se esta ligada ou desligada
commen... | import RPi.GPIO as gpio
import time
gpio.setmode(gpio.BCM)
gpio.setup(5, gpio.OUT)
gpio.setup(6, gpio.OUT)
gpio.setup(13, gpio.OUT)
#fazer um programa para piscar led x vezes
for x in range (1,10): #in range: numa determinada faixa, no caso,10x
#configura saida // 2 parametros: a porta e se esta ligada ou desli... | Python | zaydzuhri_stack_edu_python |
function section_progress_icon context section
begin
try
begin
set value = call get_progress_info context at string section_progresses at pk string css_glyphicon
end
except KeyError
begin
set value = string
end
return value
end function | def section_progress_icon(context, section):
try:
value = get_progress_info(context['section_progresses'][section.pk], 'css_glyphicon')
except KeyError:
value = ''
return value | Python | nomic_cornstack_python_v1 |
function set_lic_text self doc text
begin
if call has_extr_lic doc
begin
if not extr_text_set
begin
set extr_text_set = true
set text = text
return true
end
else
begin
raise call CardinalityError string ExtractedLicense::text
end
end
else
begin
raise call OrderError string ExtractedLicense::text
end
end function | def set_lic_text(self, doc, text):
if self.has_extr_lic(doc):
if not self.extr_text_set:
self.extr_text_set = True
self.extr_lic(doc).text = text
return True
else:
raise CardinalityError('ExtractedLicense::text')
els... | Python | nomic_cornstack_python_v1 |
from Tkinter import *
import math
set root = call Tk
title root string Calculator
set frame = call Frame root
grid
set a = call Entry frame fg=string black bg=string white
set b = call Button frame fg=string blue bg=string red
grid row=1 column=0
grid row=1 column=1
set k = call Button frame text=string Eval fg=string ... | from Tkinter import *
import math
root=Tk()
root.title("Calculator")
frame=Frame(root)
frame.grid()
a=Entry(frame,fg="black",bg="white")
b=Button(frame,fg="blue",bg="red")
a.grid(row=1,column=0)
b.grid(row=1,column=1)
k=Button(frame,text="Eval",fg="blue",bg="red")
k.grid(row=2,column=0)
j=Button(frame,text="Cos",fg="re... | Python | zaydzuhri_stack_edu_python |
comment ! /usr/bin/env python
comment Ilenia D'Angelo 4404721 Assignment 2
comment it is the server service used as generator of random integer number in the interval [1,6], each one corresponds to a pair of coordinates (x,y)
import rospy
import math
import random
from std_srvs.srv import *
comment service callback
com... | #! /usr/bin/env python
# Ilenia D'Angelo 4404721 Assignment 2
#it is the server service used as generator of random integer number in the interval [1,6], each one corresponds to a pair of coordinates (x,y)
import rospy
import math
import random
from std_srvs.srv import *
#service callback
#This callback is of the ty... | Python | zaydzuhri_stack_edu_python |
function _open args
begin
set directory = directory
if directory is none
begin
set directory = get current directory
end
set files = list
list comprehension extend files glob join path directory infile for infile in infiles
return call _open_files files open_mode
end function | def _open(args):
directory = args.directory
if directory is None:
directory = os.getcwd()
files = []
[files.extend(glob(os.path.join(directory, infile)))
for infile in args.infiles]
return _open_files(files, args.open_mode) | Python | nomic_cornstack_python_v1 |
comment encoding:utf-8
from mc.models import *
class QBase extends object
begin
set _questiontype = none
function __init__ self question=none
begin
pass
end function
function set_question question
begin
set _question = question
end function
function parse_answer self answer
begin
string 验证答案格式是否正确
raise call NotImpleme... | #encoding:utf-8
from mc.models import *
class QBase(object):
_questiontype = None
def __init__(self,question=None):
pass
def set_question(question):
self._question = question
def parse_answer(self, answer):
"""
验证答案格式是否正确
"""
raise NotImpl... | Python | zaydzuhri_stack_edu_python |
comment Get the text
set cleartext = input string Enter text:
comment Get the amount to shift by
set shift = integer input string Enter shift:
comment Split the string into a list
set cleartextList = split cleartext
comment Create a list for the cipher
set cipher = list
comment Loop through each word in the list
for w... | # Get the text
cleartext = input("Enter text: ")
# Get the amount to shift by
shift = int(input("Enter shift: "))
# Split the string into a list
cleartextList = cleartext.split()
# Create a list for the cipher
cipher = []
# Loop through each word in the list
for word in range(len(cleartextList)):
# Split the word int... | Python | zaydzuhri_stack_edu_python |
comment 02/15/2021, Mad Libs Random Stroy Generator
set name = input string what is your name?
print name
set exclamation = input string Enter an exclamation word:
set adverb = input string Enter an adverb:
set noun = input string Enter a noun:
set adjective = input string Enter an adjective:
set nounTwo = input string... | #02/15/2021, Mad Libs Random Stroy Generator
name = input("what is your name?")
print(name)
exclamation = input("Enter an exclamation word:")
adverb = input ("Enter an adverb:")
noun = input("Enter a noun:")
adjective = input("Enter an adjective:")
nounTwo = input("Enter a noun:")
#our story
# f-string... | Python | zaydzuhri_stack_edu_python |
function encode_region_tags self caption
begin
return call encode_region_tags caption tag_to_class_id
end function | def encode_region_tags(self, caption):
return encode_region_tags(caption, self.tag_to_class_id) | Python | nomic_cornstack_python_v1 |
function identify_crossing ticker df
begin
comment only concerned about 1 week's worth of data
comment 5 rows
set tail = copy tail df WEEK deep=true
set tail at string SMA_diff = tail at string SMA_LONG_Close - tail at string SMA_SHORT_Close
set tail at string SMA_diff = apply tail at string SMA_diff abs
set tail = tai... | def identify_crossing(ticker, df):
# only concerned about 1 week's worth of data
# 5 rows
tail = df.tail(WEEK).copy(deep=True)
tail['SMA_diff'] = tail['SMA_LONG_Close'] - tail['SMA_SHORT_Close']
tail['SMA_diff'] = tail['SMA_diff'].apply(abs)
tail = tail[tail['SMA_diff'] < 0.01 * tail['SMA_LONG_C... | Python | nomic_cornstack_python_v1 |
function getTime
begin
return decimal performance counter * 1000
end function | def getTime():
return float(time.perf_counter()*1000) | Python | nomic_cornstack_python_v1 |
function _get_item_from_search_response self response type_
begin
string Returns either a Song or Artist result from search_genius_web
set sections = sorted response at string sections key=lambda sect -> sect at string type == type_ reverse=true
for section in sections
begin
set hits = list comprehension hit for hit in... | def _get_item_from_search_response(self, response, type_):
""" Returns either a Song or Artist result from search_genius_web """
sections = sorted(response['sections'],
key=lambda sect: sect['type'] == type_,
reverse=True)
for section in sectio... | Python | jtatman_500k |
import os
import os.path
import time
class StandardWatcher extends object
begin
function __init__ self entities callback update_freq=10 rescan_freq=20
begin
set update_freq = update_freq
set rescan_freq = rescan_freq
set entities = entities
set callback = callback
set files = dict
for tuple filename entity in call _fi... | import os
import os.path
import time
class StandardWatcher(object):
def __init__(self, entities, callback, update_freq=10, rescan_freq=20):
self.update_freq = update_freq
self.rescan_freq = rescan_freq
self.entities = entities
self.callback = callback
self.files = {}
... | Python | zaydzuhri_stack_edu_python |
string In this doc. we'll see how to handle exceptions in your code. The try block lets you test a block of code for errors. The except block lets you handle the error. The finally block lets you execute code, regardless of the result of the try- and except blocks.
comment we know dividing number on zero will give erro... | """
In this doc. we'll see how to handle exceptions in your code.
The try block lets you test a block of code for errors.
The except block lets you handle the error.
The finally block lets you execute code, regardless of the result of the try- and except blocks.
"""
# we know dividing number on zero will give error
t... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
comment Filename:backup_ver5.py
import os
import time
import sys
set source = list
set target_dir = string /home/ubuntu/python/backup/
append source argv at 1
append source argv at 2
print source
set today = target_dir + string format time time string %Y%m%d
set now = string format time time ... | #!/usr/bin/python3
#Filename:backup_ver5.py
import os
import time
import sys
source = []
target_dir = '/home/ubuntu/python/backup/'
source.append(sys.argv[1])
source.append(sys.argv[2])
print(source)
today = target_dir + time.strftime('%Y%m%d')
now = time.strftime('%H%M%S')
if not os.path.exists(today):
os.mkdi... | Python | zaydzuhri_stack_edu_python |
import gi
import numpy as np
import drawable
call require_version string Gtk string 3.0
call require_foreign string cairo
from enum import auto , Enum
from gi.repository import Gtk , Gdk
from transformations import rotation_matrix , viewport_matrix
from clipping import LineClippingMethod
from drawable import Point , Ve... | import gi
import numpy as np
import drawable
gi.require_version('Gtk', '3.0')
gi.require_foreign("cairo")
from enum import auto, Enum
from gi.repository import Gtk, Gdk
from transformations import rotation_matrix, viewport_matrix
from clipping import LineClippingMethod
from drawable import (
Point,
Vetor2D,
... | Python | zaydzuhri_stack_edu_python |
comment coding:utf-8
function quick_sort NM L R
begin
if L >= R
begin
return
end
set key = NM at L
set tuple low high = tuple L R
while L < R
begin
while L < R and NM at L <= key
begin
set L = L + 1
end
while L < R and NM at R > key
begin
set R = R - 1
end
set tuple NM at L NM at R = tuple NM at R NM at L
end
if NM at ... | # coding:utf-8
def quick_sort(NM,L,R):
if L>=R:return
key = NM[L]
low,high = L,R
while L<R:
while L<R and NM[L]<=key:
L+=1
while L<R and NM[R]>key:
R-=1
NM[L],NM[R] = NM[R],NM[L]
if NM[L-1]<key:
NM[low]=NM[L-1]
NM[L-1] = key | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string @author: Wei, Shuowen https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/ https://labuladong.gitee.io/algo/3/24/78/ https://mp.weixin.qq.com/s/ZhPEchewfc03xWv9VP3msg LC53, LC1143, LC583, LC712, LC72, LC516
class Solution extends object
begin
function minimumDelet... | # -*- coding: utf-8 -*-
"""
@author: Wei, Shuowen
https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/
https://labuladong.gitee.io/algo/3/24/78/
https://mp.weixin.qq.com/s/ZhPEchewfc03xWv9VP3msg
LC53, LC1143, LC583, LC712, LC72, LC516
"""
class Solution(object):
def minimumDeleteSum(self, s1, ... | Python | zaydzuhri_stack_edu_python |
function hello name
begin
print string hello + name
end function
comment hello('lucio')
function plusOne number
begin
return number + 1
end function
print call plusOne 5 | def hello(name):
print('hello '+name)
# hello('lucio')
def plusOne(number):
return number + 1
print(plusOne(5)) | Python | zaydzuhri_stack_edu_python |
function log_user_login_failed sender credentials request **kwargs
begin
set ip_address = call get_client_ip request
warning string Log in failed for credentials "%s" with IP address "%s". % tuple credentials ip_address
end function | def log_user_login_failed(sender, credentials, request, **kwargs):
ip_address = get_client_ip(request)
logger.warning('Log in failed for credentials "%s" with IP address "%s".' % (credentials, ip_address)) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
from collections import Counter
import PyPDF2
import os
set pl = open string 2.5.pdf string rb
set plread = call PdfFileReader pl
set some_text = string
for n in range 10 770
begin
set some_get_page = call getPage n
set some_page = call extractText
set some_text = some_text + some_page
en... | # -*- coding: utf-8 -*-
from collections import Counter
import PyPDF2
import os
pl = open('2.5.pdf', 'rb')
plread = PyPDF2.PdfFileReader(pl)
some_text = ''
for n in range(10, 770):
some_get_page = plread.getPage(n)
some_page = some_get_page.extractText()
some_text = some_text + some_page
with open('c:/... | Python | zaydzuhri_stack_edu_python |
comment pragma: no cover
function get_block_access_path self
begin
comment platform implementation
raise call NotImplementedError
end function | def get_block_access_path(self): # pragma: no cover
# platform implementation
raise NotImplementedError() | Python | nomic_cornstack_python_v1 |
function get_ubuntu_home_user
begin
try
begin
return call getlogin
end
except OSError
begin
comment failed in some ubuntu installations and in systemd services
pass
end
try
begin
set user = environ at string USER
end
except KeyError
begin
comment possibly a systemd service. no sudo was used
return call getuser
end
if u... | def get_ubuntu_home_user():
try:
return os.getlogin()
except OSError:
# failed in some ubuntu installations and in systemd services
pass
try:
user = os.environ['USER']
except KeyError:
# possibly a systemd service. no sudo was used
return getpass.getuser(... | Python | nomic_cornstack_python_v1 |
import dash
import dash_html_components as html
import dash_core_components as dcc
import torch
from transformers import CamembertForSequenceClassification , CamembertTokenizer
function predict reviews model
begin
with no grad
begin
eval
set tuple input_id attention_masks = call preprocess reviews
set input_id = input_... | import dash
import dash_html_components as html
import dash_core_components as dcc
import torch
from transformers import CamembertForSequenceClassification, CamembertTokenizer
def predict(reviews, model):
with torch.no_grad():
model.eval()
input_id, attention_masks = preprocess(reviews)
i... | Python | zaydzuhri_stack_edu_python |
import socket
import threading
import os
set ip = string aaa
set listen_port = 20020
set exitFlag = 0
set default_route = dict string Distance 99999 ; string Next_None none
set Routing_Table = dict
set n_table = dict
set lock = lock
function get_host_ip
begin
try
begin
set s = call socket AF_INET SOCK_DGRAM
call conn... | import socket
import threading
import os
ip = 'aaa'
listen_port = 20020
exitFlag = 0
default_route = {"Distance":99999, "Next_None": None}
Routing_Table = {}
n_table ={}
lock = threading.Lock()
def get_host_ip():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80... | Python | zaydzuhri_stack_edu_python |
comment Write a function that checks whether a passed string is palindrome or not
import pi as pi
function is_palindrome s
begin
if length s == 0
begin
return true
end
else
if s at 0 == s at - 1
begin
return call is_palindrome s at slice 1 : length s - 1 :
end
else
begin
return false
end
end function
set s = string min... | # Write a function that checks whether a passed string is palindrome or not
import pi as pi
def is_palindrome(s):
if len(s) == 0:
return True
else:
if s[0] == s[-1]:
return is_palindrome(s[1:len(s)-1])
else:
return False
s = "minim"
if is_palindrome(s) == 1:
print(s, 'is ... | Python | zaydzuhri_stack_edu_python |
function insert_follow conn data_list
begin
set cursInsert = call cursor
execute cursInsert string insert into follows(flwer,flwee,start_date)values(:1,:2,:3) data_list
close cursInsert
commit conn
end function | def insert_follow(conn, data_list):
cursInsert = conn.cursor()
cursInsert.execute("insert into follows(flwer,flwee,start_date)"
"values(:1,:2,:3)", data_list)
cursInsert.close()
conn.commit() | Python | nomic_cornstack_python_v1 |
import pandas as pd
class DataManager
begin
function __init__ self
begin
print string Clustering data manager initiated
end function
decorator staticmethod
function read_data vectors gold_file column_id=none column_cluster=none
begin
if column_id is none
begin
set column_id = string name
end
if column_cluster is none
b... | import pandas as pd
class DataManager:
def __init__(self):
print("Clustering data manager initiated")
@staticmethod
def read_data(vectors, gold_file, column_id=None, column_cluster=None):
if column_id is None:
column_id = 'name'
if column_cluster is None:
... | Python | zaydzuhri_stack_edu_python |
import os
import random
import jax.numpy as jnp
comment import matplotlib
comment matplotlib.use("tkagg")
comment import seaborn as sns
import matplotlib.pyplot as plt
comment import tensorflow as tf
import numpy as np
comment # Comment this line out to return to matplotlib plot defaults
comment sns.set(rc={ # 'text.us... | import os
import random
import jax.numpy as jnp
# import matplotlib
# matplotlib.use("tkagg")
# import seaborn as sns
import matplotlib.pyplot as plt
# import tensorflow as tf
import numpy as np
# # Comment this line out to return to matplotlib plot defaults
# sns.set(rc={ # 'text.usetex': True,
# 'font... | Python | zaydzuhri_stack_edu_python |
comment ! /usr/bin/env python
comment coding=utf-8
string
import os , shutil , getopt , sys
function cpfile src dst
begin
if not exists path src
begin
raise call FileExistsError string Source file not exists.
end
call copyfile src dst
end function
function deal_cmdline argv
begin
set src = string
set dst = string
tr... | #! /usr/bin/env python
# coding=utf-8
"""
"""
import os,shutil,getopt,sys
def cpfile(src, dst):
if not os.path.exists(src):
raise FileExistsError("Source file not exists.")
shutil.copyfile(src, dst)
def deal_cmdline(argv):
src = ''
dst = ''
try:
opts, args = getopt.getopt(argv,"h... | Python | zaydzuhri_stack_edu_python |
function _calculate_eval_metrics_fn loss logits labels
begin
set loss = mean metrics values=loss
set accuracy = call accuracy labels=argument maximum labels 1 predictions=argument maximum logits 1
set metrics = dict string eval_loss loss ; string eval_accuracy accuracy
return metrics
end function | def _calculate_eval_metrics_fn(loss, logits, labels):
loss = tf.metrics.mean(values=loss)
accuracy = tf.metrics.accuracy(
labels=tf.argmax(labels, 1), predictions=tf.argmax(logits, 1))
metrics = {
"eval_loss": loss,
"eval_accuracy": accuracy,
}
return metrics | Python | nomic_cornstack_python_v1 |
function try_sessions self request **kwargs
begin
set csrf_token = call _sanitize_token get COOKIES CSRF_COOKIE_NAME string
if call is_secure
begin
set referer = get META string HTTP_REFERER
if referer is none
begin
return false
end
set good_referer = string https://%s/ % call get_host
if not call same_origin referer g... | def try_sessions(self, request, **kwargs):
csrf_token = _sanitize_token(request.COOKIES.get(settings.CSRF_COOKIE_NAME, ''))
if request.is_secure():
referer = request.META.get('HTTP_REFERER')
if referer is None:
return False
good_referer = 'https://%... | Python | nomic_cornstack_python_v1 |
function test_worker_failure app
begin
set sentinel = 50
function mocked_deserialise fields
begin
set job = call deserialise fields
if args == list sentinel
begin
raise call Chaos string Found sentinel job
end
return job
end function
with patch string fennel.worker.broker.Job wraps=Job as mocked_job
begin
set side_effe... | def test_worker_failure(app):
sentinel = 50
def mocked_deserialise(fields):
job = Job.deserialise(fields)
if job.args == [sentinel]:
raise Chaos("Found sentinel job")
return job
with mock.patch("fennel.worker.broker.Job", wraps=Job) as mocked_job:
mocked_job.des... | Python | nomic_cornstack_python_v1 |
from __future__ import annotations
from abc import ABC , abstractmethod
from typing import Optional , final
from trouble import Trouble
class Support extends ABC
begin
function __init__ self name
begin
set _name = name
comment type: Optional[Support]
set _next = none
end function
function set_next self next_support
beg... | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Optional, final
from trouble import Trouble
class Support(ABC):
def __init__(self, name: str) -> None:
self._name = name
self._next = None # type: Optional[Support]
def set_next(self, next_support: Suppo... | Python | zaydzuhri_stack_edu_python |
function task_immediate_reminder
begin
set t = call localtime now
set fro = t
set to = t + time delta minutes=45
set period = call Period call exclude appointment__status=CANCELED fro to
set event_objects = call get_occurrences
set event_ids = list set list comprehension id for x in event_objects
call send_period_remin... | def task_immediate_reminder():
t = timezone.localtime(timezone.now())
fro = t
to = t + timedelta(minutes=45)
period = Period(Event.objects.exclude(appointment=None).exclude(
appointment__client=None).exclude(
appointment__status=Appointment.NOTIFIED).exclude(
appointment__status... | Python | nomic_cornstack_python_v1 |
function pixel_to_coord px py gt
begin
if gt at 2 + gt at 4 == 0
begin
set lon = px * gt at 1 + gt at 0
set lat = py * gt at 5 + gt at 3
return tuple lon lat
end
else
begin
raise call ValueError string Cannot convert rotated maps
end
end function | def pixel_to_coord(px: int, py: int, gt: tuple) -> Tuple[float, float]:
if gt[2] + gt[4] == 0:
lon = px * gt[1] + gt[0]
lat = py * gt[5] + gt[3]
return lon, lat
else:
raise ValueError("Cannot convert rotated maps") | Python | nomic_cornstack_python_v1 |
function max_concurrency self
begin
return get pulumi self string max_concurrency
end function | def max_concurrency(self) -> pulumi.Output[Optional[str]]:
return pulumi.get(self, "max_concurrency") | Python | nomic_cornstack_python_v1 |
function test_volatile self
begin
set rft = call RegisterFileTestbench dict string metadata dict string name string test ; string fields list dict string address 0 ; string name string a ; string behavior string volatile-flag ; string bit-overflow-internal string b dict string address 4 ; string bitrange 0 ; string nam... | def test_volatile(self):
rft = RegisterFileTestbench({
'metadata': {'name': 'test'},
'fields': [
{
'address': 0,
'name': 'a',
'behavior': 'volatile-flag',
'bit-overflow-internal': 'b',
... | Python | nomic_cornstack_python_v1 |
function get_all_statistics self
begin
set tuple r response = call send_post_request list_statistics_url entity=entity action=string querySelectedStatistics
if status_code != ok
begin
set msg = format string Failed to list statistics for all ReplicationPair objects. Error: {response} response=response
error msg
raise c... | def get_all_statistics(self):
r, response = self.send_post_request(self.list_statistics_url,
entity=self.entity,
action="querySelectedStatistics")
if r.status_code != requests.codes.ok:
msg = ('Failed t... | Python | nomic_cornstack_python_v1 |
function get_mysql_pool host=none user=none password=none charset=string utf8 db=none size=none isSync=true ioloop=none
begin
string 使用工厂方法返回一个连接池
set factory = call mysql_pool_factory isSync
set kwargs = dict string host host ; string user user ; string password password ; string charset charset ; string db db ; strin... | def get_mysql_pool(host=None, user=None, password=None, charset='utf8',
db=None, size=None, isSync=True, ioloop=None):
"""使用工厂方法返回一个连接池"""
factory = mysql_pool_factory(isSync)
kwargs = {
'host': host,
'user': user,
'password': password,
'charset': charset,
'd... | Python | jtatman_500k |
function merge self imgs
begin
string Merge image channels. Parameters ---------- imgs : `list` of `PIL.Image.Image` Returns ------- `PIL.Image.Image` Raises ------ ValueError If image channel list is empty.
if not imgs
begin
raise call ValueError string empty channel list
end
if length imgs == 1
begin
return imgs at 0... | def merge(self, imgs):
"""Merge image channels.
Parameters
----------
imgs : `list` of `PIL.Image.Image`
Returns
-------
`PIL.Image.Image`
Raises
------
ValueError
If image channel list is empty.
"""
if not im... | Python | jtatman_500k |
comment Create a function that prints a diamond like this:
comment *
comment ***
comment *****
comment *******
comment *********
comment ***********
comment *********
comment *******
comment *****
comment ***
comment *
comment It should take a number as parameter that describes how many lines the diamond has
function d... | # Create a function that prints a diamond like this:
# *
# ***
# *****
# *******
# *********
# ***********
# *********
# *******
# *****
# ***
# *
#
# It should take a number as parameter that describes how many lines the diamond has
def diamond(line):
if line % 2 == 0:
... | Python | zaydzuhri_stack_edu_python |
function test_bufferImage self
begin
set win = win
set gabor = call PatchStim win mask=string gauss ori=- 45 pos=list 0.6 * scaleFactor - 0.6 * scaleFactor sf=2.0 / scaleFactor size=2 * scaleFactor interpolate=true
set bufferImgStim = call BufferImageStim win stim=list gabor interpolate=true
call draw
call compareScree... | def test_bufferImage(self):
win = self.win
gabor = visual.PatchStim(win, mask='gauss', ori=-45,
pos=[0.6*self.scaleFactor, -0.6*self.scaleFactor],
sf=2.0/self.scaleFactor, size=2*self.scaleFactor,
interpolate=True)
bufferImgStim = visual.BufferImageSti... | Python | nomic_cornstack_python_v1 |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
set data = read csv string creditcard.csv sep=string ,
set fraud = data at data at string Class == 1
set genuine = data at data at string Class == 0
comment we look at amounts per transaction for each class
comment amount per transaction for fraud t... | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv('creditcard.csv',sep=',')
fraud = data[data['Class']==1]
genuine = data[data['Class']==0]
#we look at amounts per transaction for each class
#amount per transaction for fraud transactions
plt.hist(fraud.Amount, color="lightcor... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
decorator staticmethod
function convert s num_rows
begin
string :type s: str :type num_rows: int :rtype: str
set length = length s
set result = string
set hash_table = list string * num_rows
if num_rows >= length or num_rows == 1
begin
return s
end
for i in range length
begin
set index = i % 2 * ... | class Solution:
@staticmethod
def convert(s, num_rows):
"""
:type s: str
:type num_rows: int
:rtype: str
"""
length = len(s)
result = ""
hash_table = [""] * num_rows
if num_rows >= length or num_rows == 1:
return s
for... | Python | zaydzuhri_stack_edu_python |
function updateWithThisInstanceOutput self baseInputFilePath targetParaInfo natModifyValues targetOutputInfo globalList globalLock stdModifyValues jobID baseWorkingDir simulatorExeInfo raw_output_process_func
begin
set baseInputFilePath = absolute path path baseInputFilePath
comment Make a new working dir for just this... | def updateWithThisInstanceOutput(self, baseInputFilePath, targetParaInfo, natModifyValues,
targetOutputInfo, globalList, globalLock, stdModifyValues,
jobID, baseWorkingDir, simulatorExeInfo, raw_output_process_func):
baseInputFilePath = os.path.abspath(baseInputFilePath)
# Make a new working dir... | Python | nomic_cornstack_python_v1 |
string 常见数据类型分类 【数字型】: 整型(int)、浮点型(float)、布尔型(Boolean) 复数型(complex了解) 【非数字型】:字符串(str)、列表(list)、元组(tuple)、字典(dict) 集合(了解)
set value = 12.3
set value1 = string a
set value2 = list string hello
set value3 = tuple string aaa 123
set value4 = dict string name string dog
comment 数据类型检测
print type value
comment Python可以进行类型转换... | """
常见数据类型分类
【数字型】: 整型(int)、浮点型(float)、布尔型(Boolean) 复数型(complex了解)
【非数字型】:字符串(str)、列表(list)、元组(tuple)、字典(dict) 集合(了解)
"""
value = 12.3
value1 = "a"
value2 = ["hello"]
value3 = ("aaa", 123)
value4 = {"name": "dog"}
# 数据类型检测
print(type(value))
# Python可以进行类型转换:自动转换、强制转换
# 【列表和元祖可以互转,数字类型的字符串也可以转为整数或者浮点数】
num1... | Python | zaydzuhri_stack_edu_python |
comment Extrai vogais
for i in Risada
begin
if i in vogais
begin
append NovaRisada i
end
end
set NovaRisada = join string NovaRisada
set RisadaInvertida = NovaRisada at slice length NovaRisada : : - 1
if NovaRisada == RisadaInvertida
begin
set Resp = string S
end
else
begin
set Resp = string N
end
print Resp | #Extrai vogais
for i in Risada:
if i in vogais:
NovaRisada.append(i)
NovaRisada = ''.join(NovaRisada)
RisadaInvertida = NovaRisada[len(NovaRisada)::-1]
if NovaRisada == RisadaInvertida:
Resp = "S"
else:
Resp = "N"
print(Resp) | Python | zaydzuhri_stack_edu_python |
function close_db error
begin
if has attribute g string sqlite_db
begin
close sqlite_db
end
end function | def close_db(error):
if hasattr(g, 'sqlite_db'):
g.sqlite_db.close() | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment Copyright (c) 2020 by 정우성, All rights reserved.
comment File : 2020313793.정우성.HW3.py
comment Written on : April. 12, 2020
comment Student ID : 2020313793
comment Author : 정우성 (wsung0011@naver.com)
comment Affiliation: School of Electrical Engineering
comment Sungkyunkwan University... | #!/usr/bin/env python3
#
# Copyright (c) 2020 by 정우성, All rights reserved.
#
# File : 2020313793.정우성.HW3.py
# Written on : April. 12, 2020
#
# Student ID : 2020313793
# Author : 정우성 (wsung0011@naver.com)
# Affiliation: School of Electrical Engineering
# Sungkyunkwan University
# py versi... | Python | zaydzuhri_stack_edu_python |
function debian_name self
begin
return call transform_name python_name *self.requirement.pip_requirement.extras
end function | def debian_name(self):
return self.converter.transform_name(self.python_name, *self.requirement.pip_requirement.extras) | Python | nomic_cornstack_python_v1 |
function add self val
begin
call _add val
end function | def add(self, val):
self._add(val) | Python | nomic_cornstack_python_v1 |
function itoBase nb base
begin
set rit1 = dict 10 string a ; 11 string b ; 12 string c ; 13 string d ; 14 string e ; 15 string f
set rit2 = dict string a 10 ; string b 11 ; string c 12 ; string d 13 ; string e 14 ; string f 15
set dirt = string 0123456789abcdef
for i in range length base
begin
if base at i != dirt at i... | def itoBase(nb, base):
rit1 = {10: 'a', 11: 'b', 12: 'c', 13: 'd', 14: 'e', 15: 'f'}
rit2 = {'a': 10, 'b': 11, 'c': 12, 'd': 13, 'e': 14, 'f': 15}
dirt = "0123456789abcdef"
for i in range(len(base)):
if base[i] != dirt[i]:
return("usage")
if base[-1].isdigit():
isc = int(... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Helper module for pyinotify stuff.
import pyinotify
from jobs import process_jobfile
from import logi , logd
comment pylint: disable-msg=too-few-public-methods
class JobFileHandler extends object
begin
string Wrapper class to set up inotify for incoming jobfiles.
function __init__ ... | # -*- coding: utf-8 -*-
"""Helper module for pyinotify stuff."""
import pyinotify
from .jobs import process_jobfile
from . import logi, logd
class JobFileHandler(object): # pylint: disable-msg=too-few-public-methods
"""Wrapper class to set up inotify for incoming jobfiles."""
def __init__(self, queues, di... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment coding: utf-8
comment In[1]:
comment Importing the libraries
import numpy as np
import pandas as pd
comment In[2]:
comment Importing the dataset
set dataset = read csv string Churn_Modelling.csv
dataset
comment In[3]:
set X = iloc at tuple slice : : slice 3 : 13 :
set y = iloc a... | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# Importing the libraries
import numpy as np
import pandas as pd
# In[2]:
# Importing the dataset
dataset = pd.read_csv('Churn_Modelling.csv')
dataset
# In[3]:
X = dataset.iloc[:, 3:13]
y = dataset.iloc[:, 13]
# In[4]:
#Create dummy variables
geography=pd... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment -*- coding: utf-8 -*-
string Portions lifted from... http://zetcode.com/db/sqlitepythontutorial/ https://www.tutorialspoint.com/sqlite/sqlite_using_joins.htm
import sqlite3 as lite
import sys
import vars
import json
import sys
import pyexiv2
import os
set con = none
string Connect to th... | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Portions lifted from...
http://zetcode.com/db/sqlitepythontutorial/
https://www.tutorialspoint.com/sqlite/sqlite_using_joins.htm
"""
import sqlite3 as lite
import sys
import vars
import json
import sys
import pyexiv2
import os
con = None
"""
Connect to the Photos ... | Python | zaydzuhri_stack_edu_python |
function string_to_float_convert_test string
begin
try
begin
return decimal string
end
except ValueError
begin
return none
end
end function | def string_to_float_convert_test(string):
try:
return float(string)
except ValueError:
return None | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
comment Python midi to color script
import sys
import pygame
import pygame.midi
import pysimpledmx
import lib
comment mydmx = pysimpledmx.DMXConnection('/dev/cu.usbserial-6AYP9O1D') # mac dmx com port
comment mydmx = pysimpledmx.DMXConnection(5) # windows dmx com port
comment linux com port
set... | #!/usr/bin/python
# Python midi to color script
import sys
import pygame
import pygame.midi
import pysimpledmx
import lib
# mydmx = pysimpledmx.DMXConnection('/dev/cu.usbserial-6AYP9O1D') # mac dmx com port
# mydmx = pysimpledmx.DMXConnection(5) # windows dmx com port
mydmx = pysimpledmx.DMXConnection('/dev/ttyUSB... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import numpy as np
import requests
from selenium import webdriver
import time
comment delete this for GITHUB submission
set EMAIL = string EMAIL
set PASSWORD = string PASSWORD
comment Using Selenium to scrape winespectator.com
set driver = call Chrome executable_path=string ./chromedriver
set url = ... | import pandas as pd
import numpy as np
import requests
from selenium import webdriver
import time
# delete this for GITHUB submission
EMAIL = 'EMAIL'
PASSWORD = 'PASSWORD'
# Using Selenium to scrape winespectator.com
driver = webdriver.Chrome(executable_path='./chromedriver')
url = "https://www.winespectator.com/auth... | Python | zaydzuhri_stack_edu_python |
function _check_login self guest_obj distro_name distro_cmd
begin
comment perform login to exercise distro detection
call login
comment validate if instantiating SshClient was correct
call assert_called_with
comment validate usage of SshClient object was correct
call assert_called_with host_name user=user passwd=passwd... | def _check_login(self, guest_obj, distro_name, distro_cmd):
# perform login to exercise distro detection
guest_obj.login()
# validate if instantiating SshClient was correct
self._mock_ssh_client_cls.assert_called_with()
# validate usage of SshClient object was correct
s... | Python | nomic_cornstack_python_v1 |
function _nested_init self key_desc_path src_prio parent
begin
set _key_desc_path = key_desc_path
string Path in the structure of that level of configuration
comment Make a copy to avoid sharing it with the parent
set _src_prio = copy copy src_prio
string List of sources in priority order (1st item is highest prio)
set... | def _nested_init(self, key_desc_path, src_prio, parent):
self._key_desc_path = key_desc_path
"Path in the structure of that level of configuration"
# Make a copy to avoid sharing it with the parent
self._src_prio = copy.copy(src_prio)
"List of sources in priority order (1st item ... | Python | nomic_cornstack_python_v1 |
function delete_all_jobs self phase=none regex=none
begin
call check_all_jobs
if regex
begin
set pattern = compile format string {} regex
set groups = list comprehension call group for i in range length values table_dict
set matching_tables = list comprehension groups at i for i in range length groups if groups at i in... | def delete_all_jobs(self, phase=None, regex=None):
self.check_all_jobs()
if regex:
pattern = re.compile("{}".format(regex))
groups = [pattern.match(self.table_dict.values()[i]).group()
for i in range(len(self.table_dict.values()))]
matching_tab... | Python | nomic_cornstack_python_v1 |
import os , cv2
import xml.etree.ElementTree as ET
comment slight modification of example in visualize.py
comment parameters
comment img=image file path
comment ann=annotation file path
function parse_single img ann
begin
set image = call imread img
set tree = parse ET ann
for elem in iterate
begin
if string object in ... | import os, cv2
import xml.etree.ElementTree as ET
#slight modification of example in visualize.py
#parameters
# img=image file path
# ann=annotation file path
def parse_single(img, ann):
image = cv2.imread(img)
tree = ET.parse(ann)
for elem in tree.iter():
if 'object' in elem.tag or 'part' in el... | Python | zaydzuhri_stack_edu_python |
comment 绘制折线图,来表示商场中,每个月各商品的销售情况!
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
seed 12
comment 男装:30-60
set arr_nan = random integer 30 60 size=tuple 12
comment 女装:20-85
set arr_nv = random integer 20 85 size=tuple 12
comment 餐饮:30-75
set arr_can = random integer 30 75 size=tuple 12
comment 化妆... | # 绘制折线图,来表示商场中,每个月各商品的销售情况!
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
np.random.seed(12)
# 男装:30-60
arr_nan = np.random.randint(30, 60, size=(12,))
# 女装:20-85
arr_nv = np.random.randint(20, 85, size=(12,))
# 餐饮:30-75
arr_can = np.random.randint(30, 75, size=(12,))
# 化妆品:80-140
arr_hua = n... | Python | zaydzuhri_stack_edu_python |
function create_snapshot self volume_id
begin
set response = call create_snapshot url verb headers version volume_id
if response is not none
begin
set res = call CreateSnapshotResponse
call parseString string text res
return res
end
else
begin
return none
end
end function | def create_snapshot(self, volume_id):
response = snapshot.create_snapshot(self.url, self.verb,
self.headers, self.version,
volume_id)
if response is not None :
res = CreateSnapshotResponse.CreateSnapshotResponse... | Python | nomic_cornstack_python_v1 |
function get_tfa_remove_backup_phone self
begin
if not call is_tfa_remove_backup_phone
begin
raise call AttributeError string tag 'tfa_remove_backup_phone' not set
end
return _value
end function | def get_tfa_remove_backup_phone(self):
if not self.is_tfa_remove_backup_phone():
raise AttributeError("tag 'tfa_remove_backup_phone' not set")
return self._value | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
set in_file = string allvectors.in
set out_file = string allvectors.out
set in_fd = open in_file string r
set length = integer strip read line in_fd
close in_fd
set out_fd = open out_file string w
for i in range 0 2 ^ length
begin
write out_fd call zfill length + string
end
close out_fd | #!/usr/bin/env python
in_file = "allvectors.in"
out_file = "allvectors.out"
in_fd = open(in_file, "r")
length = int(in_fd.readline().strip())
in_fd.close()
out_fd = open(out_file, "w")
for i in range(0, 2**length):
out_fd.write(format(i, 'b').zfill(length) + "\n")
out_fd.close() | Python | zaydzuhri_stack_edu_python |
function main self args
begin
comment pylint: disable=protected-access
set force = _force
comment Verbosity level adjusted by -v and -q options
call adjust_verbosity _verbosity - _quietude
comment In python3.3+ we can get here even without a subcommand:
if not _subcommand
begin
error string too few arguments
end
set su... | def main(self, args):
# pylint: disable=protected-access
self.force = args._force
# Verbosity level adjusted by -v and -q options
self.adjust_verbosity(args._verbosity - args._quietude)
# In python3.3+ we can get here even without a subcommand:
if not args._subcommand:
... | Python | nomic_cornstack_python_v1 |
comment [834] Ambiguous Coordinates
comment https://leetcode.com/problems/ambiguous-coordinates/description/
comment algorithms
comment Medium (41.54%)
comment Total Accepted: 1.7K
comment Total Submissions: 4.1K
comment Testcase Example: '"(123)"'
comment We had some 2-dimensional coordinates, like "(1, 3)" or "(2, 0.... | #
# [834] Ambiguous Coordinates
#
# https://leetcode.com/problems/ambiguous-coordinates/description/
#
# algorithms
# Medium (41.54%)
# Total Accepted: 1.7K
# Total Submissions: 4.1K
# Testcase Example: '"(123)"'
#
# We had some 2-dimensional coordinates, like "(1, 3)" or "(2, 0.5)". Then, we
# removed all commas,... | Python | zaydzuhri_stack_edu_python |
import pygame
from core.tools import load_image , render_text
class Figure extends object
begin
function __init__ self row column color filename
begin
set row = row
set column = column
set color = color
set filename = filename
set image = call load_image string { filename } _ { color } .png
set tuple width height = siz... | import pygame
from core.tools import load_image, render_text
class Figure(object):
def __init__(self, row, column, color, filename):
self.row = row
self.column = column
self.color = color
self.filename = filename
self.image = load_image(f'{self.filename}_{se... | Python | zaydzuhri_stack_edu_python |
function get_vertex_prob graph vertex_degree vertex_distribution
begin
if vertex_distribution == string edge_uniform
begin
return vertex_degree * 2 * size graph ^ - 1
end
if vertex_distribution == string node_uniform
begin
return call number_of_nodes ^ - 1
end
else
begin
raise NotImplementedError
end
end function | def get_vertex_prob(graph, vertex_degree, vertex_distribution):
if vertex_distribution == "edge_uniform":
return (vertex_degree *
(2 * graph.size()) ** (-1))
if vertex_distribution == "node_uniform":
return graph.number_of_nodes() ** (-1)
else:
raise NotImplementedErr... | Python | nomic_cornstack_python_v1 |
class Solution extends object
begin
function findMaxConsecutiveOnes self nums
begin
string :type nums: List[int] :rtype: int
set ctr = 0
set maxlist = list
for x in nums
begin
if x == 1
begin
set ctr = ctr + 1
end
else
begin
append maxlist ctr
set ctr = 0
end
end
if ctr > 0
begin
append maxlist ctr
end
if length maxlis... | class Solution(object):
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ctr = 0
maxlist = list()
for x in nums:
if x == 1:
ctr += 1
else:
maxlist.append(ctr)
... | Python | zaydzuhri_stack_edu_python |
function get_facts self
begin
set commands_json = list string show version string show interfaces status
set commands_text = list string show hostname
set result_json = call run_commands commands_json encoding=string json
set result_text = call run_commands commands_text encoding=string text
set version = result_json a... | def get_facts(self):
commands_json = ['show version', 'show interfaces status']
commands_text = ['show hostname']
result_json = self.device.run_commands(commands_json, encoding='json')
result_text = self.device.run_commands(commands_text, encoding='text')
version = result_json[0... | Python | nomic_cornstack_python_v1 |
class MaxHeap
begin
function __init__ self
begin
set heap = list
end function
function insert self value
begin
append heap value
call _sift_up length heap - 1
end function
function deleteMax self
begin
if not heap
begin
raise call IndexError string Priority queue is empty
end
set max_value = heap at 0
set last_value =... | class MaxHeap:
def __init__(self):
self.heap = []
def insert(self, value):
self.heap.append(value)
self._sift_up(len(self.heap) - 1)
def deleteMax(self):
if not self.heap:
raise IndexError("Priority queue is empty")
max_value = self.heap[0]
... | Python | jtatman_500k |
async function add_dashboard_handler request dashboard
begin
set token = token
set user = user
set dashboard_subscriptions = subscriptions
comment Get all user subscriptions
set params = dict string type BUGOUT_RESOURCE_TYPE_SUBSCRIPTION ; string user_id string id
try
begin
set resources : BugoutResources = call list_r... | async def add_dashboard_handler(
request: Request, dashboard: data.DashboardCreate
) -> BugoutResource:
token = request.state.token
user = request.state.user
dashboard_subscriptions = dashboard.subscriptions
# Get all user subscriptions
params = {
"type": BUGOUT_RESOURCE_TYPE_SUBSCRI... | Python | nomic_cornstack_python_v1 |
from heapq import heappush , heappop
function bfs graph start goal
begin
set queue = list list start
set visited = set
set path = list
while length queue > 0
begin
yield 1
set cur = queue at 0
set last = cur at - 1
call display queue last visited
append path last
if last == goal
begin
return tuple cur path call path_l... | from heapq import heappush, heappop
def bfs(graph, start, goal):
queue = [[start]]
visited = set()
path=[]
while len(queue) > 0:
yield 1
cur = queue[0]
last = cur[-1]
graph.display(queue, last, visited)
path.append(last)
if last == goal:
retu... | Python | zaydzuhri_stack_edu_python |
from abc import ABC , abstractmethod
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
import torch
import torch.nn as nn
from torch.functional import F
comment Abstract class simulating and ... | from abc import ABC, abstractmethod
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
import torch
import torch.nn as nn
from torch.functional import F
# Abstract class simulating and inter... | Python | zaydzuhri_stack_edu_python |
function couldReceive self data transmitter txLocation rxLocation context
begin
return call couldReceive data transmitter and call isOrbit and call isOrbit and absolute sector - sector <= 1 or absolute sector - sector >= call getNumSectors - 1
end function | def couldReceive(self, data, transmitter, txLocation, rxLocation, context):
return super(InterSatelliteLink, self).couldReceive(data, transmitter) \
and txLocation.isOrbit() \
and rxLocation.isOrbit() \
and (abs(txLocation.sector - rxLocation.sector) <= 1
... | Python | nomic_cornstack_python_v1 |
function reveal_command_args args
begin
return list comprehension if expression is instance arg HiddenText then secret else arg for arg in args
end function | def reveal_command_args(args: Union[List[str], CommandArgs]) -> List[str]:
return [arg.secret if isinstance(arg, HiddenText) else arg for arg in args] | Python | nomic_cornstack_python_v1 |
import librosa
comment 求一个wav文件的滚降频率
comment 输入:文件名(绝对路径)
comment 输出:滚降频率
function get_Frequency fileName
begin
set tuple y sr = load librosa fileName
comment Approximate maximum frequencies with roll_percent=0.85 (default)
set rolloff = call spectral_rolloff y=y sr=sr
return rolloff
pass
end function
if __name__ == st... | import librosa
# 求一个wav文件的滚降频率
# 输入:文件名(绝对路径)
# 输出:滚降频率
def get_Frequency(fileName):
y, sr = librosa.load(fileName)
# Approximate maximum frequencies with roll_percent=0.85 (default)
rolloff = librosa.feature.spectral_rolloff(y=y, sr=sr)
return rolloff
pass
if __name__ == '__main__':
fileName... | Python | zaydzuhri_stack_edu_python |
function occupied_cells self
begin
for lm in landmarks
begin
if cell_size < 1
begin
comment expand the range the landmark exists
set lm_x_range = array range lm at 0 - R lm at 0 + R cell_size
set lm_y_range = array range lm at 1 - R lm at 1 + R cell_size
comment loop through expanded ranges and compute grid positions
f... | def occupied_cells(self):
for lm in self.landmarks:
if self.cell_size < 1:
# expand the range the landmark exists
lm_x_range = np.arange(lm[0]-self.R, lm[0]+self.R, self.cell_size)
lm_y_range = np.arange(lm[1]-self.R, lm[1]+self.R, self.cell_size)
... | Python | nomic_cornstack_python_v1 |
function __init__ self d_model n_heads use_cos kernel dropout ffn_ratio ln_eps denom_eps bias
begin
call __init__
set ln1 = layer norm d_model eps=ln_eps
set ln2 = layer norm d_model eps=ln_eps
set mha = call MHA d_model n_heads use_cos kernel dropout denom_eps bias
set ffn = call FFN d_model ffn_ratio dropout bias
end... | def __init__(self, d_model, n_heads, use_cos, kernel, dropout,
ffn_ratio, ln_eps, denom_eps, bias):
super(MHA_block, self).__init__()
self.ln1 = nn.LayerNorm(d_model, eps=ln_eps)
self.ln2 = nn.LayerNorm(d_model, eps=ln_eps)
self.mha = MHA(
d_model, n_heads, u... | Python | nomic_cornstack_python_v1 |
function create_brown_noise_regular_ts n_t par=1.0
begin
set uneven = n_t % 2
set X = randn n_t // 2 + 1 + uneven + 1j * randn n_t // 2 + 1 + uneven
set S = array range length X + 1
set y = real
if uneven
begin
set y = y at slice : - 1 :
end
set values = y * square root par / mean absolute y ^ 2.0
set times = array r... | def create_brown_noise_regular_ts(n_t, par=1.0):
uneven = n_t % 2
X = np.random.randn(n_t//2+1+uneven) + 1j*np.random.randn(n_t//2+1+uneven)
S = np.arange(len(X))+1
y = (irfft(X/S)).real
if uneven:
y = y[:-1]
values = y*np.sqrt(par/(np.abs(y)**2.0).mean())
times = np.arange(n_t)
... | Python | nomic_cornstack_python_v1 |
string Convert Excel spreadsheet into python code formatting
function convert_spreadsheet multi_line_string type=float
begin
set str_list = split multi_line_string string
for tuple i item in enumerate str_list
begin
if type == float
begin
set str_list at i = decimal replace item string , string .
end
else
begin
set str... | """Convert Excel spreadsheet into python code formatting"""
def convert_spreadsheet(multi_line_string, type=float):
str_list = multi_line_string.split('\n')
for i, item in enumerate(str_list):
if type == float:
str_list[i] = float(item.replace(',', '.'))
else:
str_list[... | Python | zaydzuhri_stack_edu_python |
string This script handles data after the Joseph fabricates a post. Inputs: - 'Label' files from Stuff share (192.168.1.250\craig\craig\Joseph\Production\Labels) - Each file has meta data about a post, written when post fabrication completes. Outputs: - parse file for traceability about the post - update the LCD screen... | """ This script handles data after the Joseph fabricates a post.
Inputs:
- 'Label' files from Stuff share (192.168.1.250\craig\craig\Joseph\Production\Labels)
- Each file has meta data about a post, written when post fabrication completes.
Outputs:
- parse file for traceability about the post
- updat... | Python | zaydzuhri_stack_edu_python |
function generate_patch_build self domain
begin
comment TODO change name of def
set base_path = paths at string api_doc_dir
call generate_apidoc_patches
from django_swagger_utils.apidoc_gen.generators.patch_generator import PatchGenerator
set patch_generator = call PatchGenerator app_name parser paths base_path
call fi... | def generate_patch_build(self, domain):
# TODO change name of def
base_path = self.paths["api_doc_dir"]
self.generate_apidoc_patches()
from django_swagger_utils.apidoc_gen.generators.patch_generator import PatchGenerator
patch_generator = PatchGenerator(self.app_name, self.parser... | Python | nomic_cornstack_python_v1 |
function test_01_lunch_order self
begin
set tuple cr uid = tuple cr uid
call test_00_lunch_order
comment We receive the order so we confirm the order line so it's state will be 'confirmed'
comment A cashmove will be created and we will test that the cashmove amount equals the order line price
call confirm
set order_one... | def test_01_lunch_order(self):
cr, uid = self.cr, self.uid
self.test_00_lunch_order()
#We receive the order so we confirm the order line so it's state will be 'confirmed'
#A cashmove will be created and we will test that the cashmove amount equals the order line price
self.o... | 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.