code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function read_bank_1
begin
return call _pigpio_command _control _PI_CMD_BR1 0 0
end function | def read_bank_1():
return _pigpio_command(_control, _PI_CMD_BR1, 0, 0) | Python | nomic_cornstack_python_v1 |
comment print(data)
set datalist = list
for i in range length data
begin
set a = split data at i string ]
comment print(a)
for j in range length a - 1
begin
set datatimestr = a at j at slice 1 : :
comment print(datatimestr)
set datatimelist = split datatimestr string :
set datatime = decimal datatimelist at 0 * 60 +... | # print(data)
datalist = []
for i in range(len(data)):
a = data[i].split("]")
# print(a)
for j in range(len(a)-1):
datatimestr = a[j][1:]
# print(datatimestr)
datatimelist = datatimestr.split(":")
datatime = float(datatimelist[0]) * 60 + float(datatimelist[1])
... | Python | zaydzuhri_stack_edu_python |
function __init__ self resize=tuple 96 96
begin
set device = device if expression call is_available then string cuda:0 else string cpu
set detector = call MTCNN keep_all=true device=device
set resize = resize
end function | def __init__(self,
resize:tuple = (96, 96)):
device = torch.device(
'cuda:0' if torch.cuda.is_available() else 'cpu')
self.detector = MTCNN(keep_all=True, device=device)
self.resize = resize | Python | nomic_cornstack_python_v1 |
from typing import Optional
from src.ioc_extraction.indicators.ip_indicator import IPv4Indicator
class IPv4RangeIndicator extends IPv4Indicator
begin
function get_sigma_value self
begin
set tuple ip_address1 ip_address2 = list comprehension split value string . for value in list comprehension strip value for value in s... | from typing import Optional
from src.ioc_extraction.indicators.ip_indicator import IPv4Indicator
class IPv4RangeIndicator(IPv4Indicator):
def get_sigma_value(self) -> Optional[str]:
ip_address1, ip_address2 = [value.split('.') for value in [value.strip() for value in self.value.split('-')]]
# f... | Python | zaydzuhri_stack_edu_python |
function url_for *args **kwargs
begin
if string _external not in kwargs
begin
set kwargs at string _external = false
end
set reqctx = top
if reqctx is none
begin
if kwargs at string _external
begin
raise call RuntimeError string Cannot generate external URLs without a request context.
end
with call test_request_context... | def url_for(*args, **kwargs):
if '_external' not in kwargs:
kwargs['_external'] = False
reqctx = _request_ctx_stack.top
if reqctx is None:
if kwargs['_external']:
raise RuntimeError('Cannot generate external URLs without a '
'request context.')
... | Python | nomic_cornstack_python_v1 |
function sort_strings strings alphabetical_order
begin
function get_key s
begin
set sum_val = sum generator expression get alphabetical_order c 0 for c in s
return tuple sum_val - length s s
end function
return sorted strings key=get_key
end function
set alphabetical_order = dict string a 1 ; string b 2 ; string c 3
co... | def sort_strings(strings, alphabetical_order):
def get_key(s):
sum_val = sum(alphabetical_order.get(c, 0) for c in s)
return (sum_val, -len(s), s)
return sorted(strings, key=get_key)
alphabetical_order = {
'a': 1,
'b': 2,
'c': 3,
# add more letters and their integer values her... | Python | jtatman_500k |
comment import datetime
import datetime
set time = now
print string Hour: hour
print string Minute: minute
print string Second: second
comment 10^6 = 1s
print string Microsecond: microsecond | # import datetime
import datetime
time = datetime.datetime.now()
print("Hour: ",time.hour)
print("Minute: ",time.minute)
print("Second: ",time.second)
print("Microsecond: ",time.microsecond)#10^6 = 1s
| Python | zaydzuhri_stack_edu_python |
import numpy as np
import pandas as pd
from pandas import *
from operator import itemgetter
import logging
import math
class Categorical_DataFrame
begin
function __init__ self df
begin
set df = df
set cat_list_dict = dict
end function
function cat_list_dict_create self inlist
begin
for i in inlist
begin
comment key fo... | import numpy as np
import pandas as pd
from pandas import *
from operator import itemgetter
import logging
import math
class Categorical_DataFrame:
def __init__(self, df):
self.df = df
self.cat_list_dict = {}
def cat_list_dict_create(self, inlist):
for i in inlist:
self.df[i] = self.df[i].astype(object).re... | Python | zaydzuhri_stack_edu_python |
import pandas
import numpy as np
import datetime
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.model_selection import KFold , cross_val_score
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import StandardScaler
function main
begin
set start = now
set data = read csv ... | import pandas
import numpy as np
import datetime
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.model_selection import KFold, cross_val_score
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import StandardScaler
def main():
start = datetime.datetime.now()
... | Python | zaydzuhri_stack_edu_python |
function parse_weights d weights axis=none
begin
if weights is none
begin
comment No weights
return
end
if not is instance weights dict
begin
comment Weights is data_like. Don't check broadcastability to d,
comment leave that to whatever uses the weights.
return call asdata weights
end
if not weights
begin
comment No w... | def parse_weights(d, weights, axis=None):
if weights is None:
# No weights
return
if not isinstance(weights, dict):
# Weights is data_like. Don't check broadcastability to d,
# leave that to whatever uses the weights.
return type(d).asdata(weights)
if not weights:
... | Python | nomic_cornstack_python_v1 |
string import mysql.connector db_connection = mysql.connector.connect( host= "localhost", user= "root", passwd= "Abc@1234" ) # creating database_cursor to perform SQL operation db_cursor = db_connection.cursor() print(db_cursor) # executing cursor with execute method and pass SQL query db_cursor.execute("CREATE DATABAS... | '''
import mysql.connector
db_connection = mysql.connector.connect(
host= "localhost",
user= "root",
passwd= "Abc@1234"
)
# creating database_cursor to perform SQL operation
db_cursor = db_connection.cursor()
print(db_cursor)
# executing cursor with execute method and pass SQL query
db_cursor.execute("CREATE DATABASE... | Python | zaydzuhri_stack_edu_python |
function updated self
begin
return _updated
end function | def updated(self) -> str:
return self._updated | Python | nomic_cornstack_python_v1 |
function hasUniqueName self
begin
pass
end function | def hasUniqueName(self):
pass | Python | nomic_cornstack_python_v1 |
function run_coro coro error=string Event Loop Running
begin
set loop = call get_event_loop
if call is_running
begin
raise call RuntimeError error
end
return call run_until_complete coro
end function | def run_coro(coro: Coroutine[None, None, T],
error: str = "Event Loop Running") -> T:
loop = asyncio.get_event_loop()
if loop.is_running():
raise RuntimeError(error)
return loop.run_until_complete(coro) | Python | nomic_cornstack_python_v1 |
from book_api.api.BookApi import BookApi
from book_api.books.models import Book
from book_api.dto.BookDto import BookDto
from book_api.repository.AuthorRepository import AuthorRepository
from book_api.repository.BookRepository import BookRepository
from book_api.repository.CategoryRepository import CategoryRepository
f... | from book_api.api.BookApi import BookApi
from book_api.books.models import Book
from book_api.dto.BookDto import BookDto
from book_api.repository.AuthorRepository import AuthorRepository
from book_api.repository.BookRepository import BookRepository
from book_api.repository.CategoryRepository import CategoryRepository
f... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
import scrapy
import re
import csv
from scrapyToJianshu.items import TaobaoItem
class TaobaoSpider extends Spider
begin
set name = string TbCpuI38100
set start_url = string https://s.taobao.com/search?q=cpu+I3+8100&ie=utf-8
set detail_urls = list
set data = list
function start_requests s... | # -*- coding: utf-8 -*-
import scrapy
import re
import csv
from scrapyToJianshu.items import TaobaoItem
class TaobaoSpider(scrapy.Spider):
name = 'TbCpuI38100'
start_url = 'https://s.taobao.com/search?q=cpu+I3+8100&ie=utf-8'
detail_urls = []
data = []
def start_requests(self):
for i in ra... | Python | zaydzuhri_stack_edu_python |
function quaternion_algebra self
begin
try
begin
return __quaternion_algebra
end
except AttributeError
begin
pass
end
set A = call parent
set __quaternion_algebra = A
return A
end function | def quaternion_algebra(self):
try: return self.__quaternion_algebra
except AttributeError: pass
A = self.__basis[0].parent()
self.__quaternion_algebra = A
return A | Python | nomic_cornstack_python_v1 |
function SketchConstraintsDelAll self
begin
return call InvokeTypes 65578 LCID 1 tuple 24 0 tuple
end function | def SketchConstraintsDelAll(self):
return self._oleobj_.InvokeTypes(65578, LCID, 1, (24, 0), (),) | Python | nomic_cornstack_python_v1 |
function set_max_noutput_items self m
begin
return call send_nanolink_sptr_set_max_noutput_items self m
end function | def set_max_noutput_items(self, m):
return _ccsds_swig.send_nanolink_sptr_set_max_noutput_items(self, m) | Python | nomic_cornstack_python_v1 |
import logging
import time
import threading
function threadFunction id
begin
info string thread function: %d started id
sleep 2
info string thread function %d ended id
end function
if __name__ == string __main__
begin
call basicConfig format=string %(asctime)s:%(message)s level=INFO datefmt=string %H:%M:%S
set thread =... | import logging
import time
import threading
def threadFunction(id):
logging.info("thread function: %d started", id)
time.sleep(2)
logging.info("thread function %d ended", id)
if __name__ == "__main__":
logging.basicConfig(format="%(asctime)s:%(message)s",level=logging.INFO,datefmt="%H:%M:%S")
... | Python | zaydzuhri_stack_edu_python |
from time import *
from math import *
set start = time
set n = 64000000
set summation = 7966336 | from time import *
from math import *
start = time()
n = 64000000
summation = 7966336 | Python | zaydzuhri_stack_edu_python |
from unidecode import unidecode
import re
class TextCleaner extends object
begin
string The module includes cleaning functions for different scenario.
function __init__ self
begin
set CURRENCIES = dict string $ string USD ; string € string EUR ; string £ string GBP ; string ¥ string JPY
set REDUNDANT_TERMS = set litera... | from unidecode import unidecode
import re
class TextCleaner(object):
"""The module includes cleaning functions for different scenario.
"""
def __init__(self):
self.CURRENCIES = {'$': 'USD', '€': 'EUR', '£': 'GBP', '¥': 'JPY'}
self.REDUNDANT_TERMS = {"Apply Save Share", "Apply Now", "About u... | Python | zaydzuhri_stack_edu_python |
import sqlalchemy
from flask_sqlalchemy import SQLAlchemy
from werkzeug import generate_password_hash , check_password_hash
from sqlalchemy.orm import class_mapper , ColumnProperty
set db = call SQLAlchemy
class User extends Model
begin
set id = call Column Integer primary_key=true
set username = call Column call Strin... | import sqlalchemy
from flask_sqlalchemy import SQLAlchemy
from werkzeug import generate_password_hash, check_password_hash
from sqlalchemy.orm import class_mapper, ColumnProperty
db = SQLAlchemy()
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=Tr... | Python | zaydzuhri_stack_edu_python |
function dayOfProgrammer year
begin
if year == 1918
begin
return string 26.09.1918
end
else
if year < 1917 and year % 4 == 0 or year > 1918 and year % 400 == 0 or year % 4 == 0 and year % 100 != 0
begin
return string 12.09.%s % year
end
else
begin
return string 13.09.%s % year
end
end function
if __name__ == string __m... | def dayOfProgrammer(year):
if year==1918:
return '26.09.1918'
elif (year < 1917 and year%4==0)or(year>1918 and (year%400==0 or (year%4==0 and year%100!=0))):
return '12.09.%s' % year
else:
return '13.09.%s' % year
if __name__ == '__main__':
#fptr = open(os.environ['OUTPUT_PATH']... | Python | zaydzuhri_stack_edu_python |
function timeimage self cmd=string
begin
comment check arguments
set p = url parse cmd
set q = call parse_qs query
try
begin
set color = string # + lower strip q at string color at 0
end
except KeyError
begin
set color = string #330
end
comment make a generally transparent image,
set imageWidth = 128
set imageHeight = ... | def timeimage(self,cmd=''):
# check arguments
p = urlparse.urlparse(cmd)
q = urlparse.parse_qs(p.query)
try:
color = "#" + q['color'][0].strip().lower()
except KeyError:
color = "#330"
#
# make a generally transparent image,
#
imageWidth = 128
imageHeight = 32
t... | Python | nomic_cornstack_python_v1 |
string Original implementation of the code was done by McDickenson available here - https://github.com/mcdickenson/em-gaussian considering two gaussian mixture model. This code modified the original work by extending to three gaussian mixture and shows a way of how to use the same code for n number of gaussian mixtures... | ''' Original implementation of the code was done by McDickenson available here - https://github.com/mcdickenson/em-gaussian
considering two gaussian mixture model. This code modified the original work by
extending to three gaussian mixture and shows a way of how to use the same code for n number of
gaussian mixtures '... | Python | zaydzuhri_stack_edu_python |
comment 卷积神经网络
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tensorflow.python.keras.backend_config import epsilon
if __name__ == string __main__
begin
set tuple tuple train_x train_y tuple test_x test_y = call load_data
set model = sequential list conv 2d 64 tuple 3 3 activation=relu ... | # 卷积神经网络
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tensorflow.python.keras.backend_config import epsilon
if __name__ == "__main__":
(train_x,train_y),(test_x,test_y)=tf.keras.datasets.fashion_mnist.load_data()
model=tf.keras.models.Sequential([
tf.keras.layers.Conv... | Python | zaydzuhri_stack_edu_python |
function modules_to_freeze self
begin
return get attribute self string backbone none
end function | def modules_to_freeze(self) -> Optional[nn.Module]:
return getattr(self, "backbone", None) | Python | nomic_cornstack_python_v1 |
function saveJSON self file
begin
set conflictData = call export_rep
set nodes = list
for tuple stateIdx stateDec in enumerate decimal
begin
set stateYN = yn at stateIdx
set stateOrd = ordered at stateIdx
set reachable = list
for tuple coInd dm in enumerate effectiveDMs
begin
for rchSt in call reachable dm stateIdx
b... | def saveJSON(self,file):
conflictData = self.conflict.export_rep()
nodes = []
for stateIdx,stateDec in enumerate(self.conflict.feasibles.decimal):
stateYN = self.conflict.feasibles.yn[stateIdx]
stateOrd = self.conflict.feasibles.ordered[stateIdx]
rea... | Python | nomic_cornstack_python_v1 |
function copy_project self new_name switch=true
begin
if new_name in self
begin
raise call ValueError format string Project {} already exists new_name
end
set fp = _base_data_dir / call safe_filename new_name full=full_hash
if exists fp
begin
raise call ValueError string Project directory already exists
end
set project... | def copy_project(self, new_name, switch=True):
if new_name in self:
raise ValueError("Project {} already exists".format(new_name))
fp = self._base_data_dir / safe_filename(new_name, full=self.dataset.full_hash)
if fp.exists():
raise ValueError("Project directory already e... | Python | nomic_cornstack_python_v1 |
function query_api endpoint log
begin
string Query the AppVeyor API. :raise HandledError: On non HTTP200 responses or invalid JSON response. :param str endpoint: API endpoint to query (e.g. '/projects/Robpol86/appveyor-artifacts'). :param logging.Logger log: Logger for this function. Populated by with_log() decorator. ... | def query_api(endpoint, log):
"""Query the AppVeyor API.
:raise HandledError: On non HTTP200 responses or invalid JSON response.
:param str endpoint: API endpoint to query (e.g. '/projects/Robpol86/appveyor-artifacts').
:param logging.Logger log: Logger for this function. Populated by with_log() decor... | Python | jtatman_500k |
function spot1d_psi infile sequence
begin
return reshape call loadtxt infile usecols=11 skiprows=1 tuple 1 - 1 1
end function | def spot1d_psi(infile, sequence):
return np.loadtxt(infile, usecols=11, skiprows=1).reshape((1, -1, 1)) | Python | nomic_cornstack_python_v1 |
class Solution
begin
function oddCells self m n indices
begin
comment result = [[0] * n for i in range(m)]
set rowIncrements = dict
set colIncrements = dict
for tuple rowToIncrement colToIncrement in indices
begin
if rowToIncrement not in rowIncrements
begin
set rowIncrements at rowToIncrement = 0
end
if colToIncreme... | class Solution:
def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int:
# result = [[0] * n for i in range(m)]
rowIncrements = {}
colIncrements = {}
for rowToIncrement, colToIncrement in indices:
if rowToIncrement not in rowIncrements:
rowIncr... | Python | zaydzuhri_stack_edu_python |
import json
import tkinter as tk
from tkinter import font as tkfont
from tkinter import messagebox
from tkinter import ttk
from Gui import *
import Config
class AdminCommands
begin
pass
end class
class AdminCommandsAdmin extends Frame AdminCommands
begin
string Methods: __init__ Variables: controller Title - Title Labe... | import json
import tkinter as tk
from tkinter import font as tkfont
from tkinter import messagebox
from tkinter import ttk
from Gui import *
import Config
class AdminCommands:
pass
class AdminCommandsAdmin(tk.Frame,AdminCommands):
"""
Methods:
__init__
Variables:
con... | Python | zaydzuhri_stack_edu_python |
function _GetCookieName self
begin
return __name__ + string _last_key
end function | def _GetCookieName(self):
return type(self).__name__ + '_last_key' | Python | nomic_cornstack_python_v1 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import cvxpy as cvx
from scipy.optimize import minimize , differential_evolution
class ControlSolver extends object
begin
function __init__ self dataset outcome_var id_var time_var treatment_period treated_unit treatment_effect=none w=none
begin
str... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import cvxpy as cvx
from scipy.optimize import minimize, differential_evolution
class ControlSolver(object):
def __init__(self, dataset, outcome_var, id_var, time_var, treatment_period, treated_unit, treatment_effect=None, w=None):
... | Python | zaydzuhri_stack_edu_python |
import random
comment This is an out-of-the-box ghost AI implementation. In theory this is
comment pluggable from a front-end, but that isn't necessary. Note that the ghost is
comment assumed to be outside of the ghost box for ghost logic functions.
function simple_logic board location state
begin
set directions = call... | import random
# This is an out-of-the-box ghost AI implementation. In theory this is
# pluggable from a front-end, but that isn't necessary. Note that the ghost is
# assumed to be outside of the ghost box for ghost logic functions.
def simple_logic(board, location, state):
directions = board.allowable_directio... | Python | zaydzuhri_stack_edu_python |
comment Created by Holden on 7/8/2016
comment COMPLETED on 6/24/2017
comment Problem 53 - Prime Digit Replacements
import math
function prime_digit_replacements n
begin
set start = 3
while true
begin
if string start at - 1 == string 5
begin
set start = start + 2
continue
end
if string 1 in string start at slice : - 1 ... | ###
#
# Created by Holden on 7/8/2016
#
# COMPLETED on 6/24/2017
#
# Problem 53 - Prime Digit Replacements
#
###
import math
def prime_digit_replacements(n):
start = 3
while True:
if str(start)[-1] == "5":
start += 2
continue
if "1" in str(start)[:-1]:
str... | Python | zaydzuhri_stack_edu_python |
function calculate_rate_discrimination_accuracy spikeTimes eventOnsetTimes baseRange responseRange currentFreq shuffle=false
begin
comment From case==2 of am_preceptron.py of Nick's 2018thstr
comment Set to true to shuffle AM rates, giving an estimate of the chance level.
set SHUFFLE = shuffle
comment if pVal > 0.05: #... | def calculate_rate_discrimination_accuracy(spikeTimes, eventOnsetTimes, baseRange, responseRange, currentFreq,
shuffle=False): # From case==2 of am_preceptron.py of Nick's 2018thstr
SHUFFLE = shuffle # Set to true to shuffle AM rates, giving an estimate of the chance lev... | Python | nomic_cornstack_python_v1 |
function _bcrypt_encrypt certificate_or_public_key data rsa_oaep_padding=false
begin
set flags = BCRYPT_PAD_PKCS1
if rsa_oaep_padding is true
begin
set flags = BCRYPT_PAD_OAEP
set padding_info_struct_pointer = call struct bcrypt string BCRYPT_OAEP_PADDING_INFO
set padding_info_struct = call unwrap padding_info_struct_p... | def _bcrypt_encrypt(certificate_or_public_key, data, rsa_oaep_padding=False):
flags = BcryptConst.BCRYPT_PAD_PKCS1
if rsa_oaep_padding is True:
flags = BcryptConst.BCRYPT_PAD_OAEP
padding_info_struct_pointer = struct(bcrypt, 'BCRYPT_OAEP_PADDING_INFO')
padding_info_struct = unwrap(padd... | Python | nomic_cornstack_python_v1 |
comment from collections import *
comment from itertools import *
comment from bisect import *
from heapq import *
comment import copy
comment N=int(input())
comment X,Y=map(int,input().split())
comment S=list(map(int,input().split()))
comment S=[list(map(int,input().split())) for i in range(N)]
set tuple N C = map int... | #from collections import *
#from itertools import *
#from bisect import *
from heapq import *
#import copy
#N=int(input())
#X,Y=map(int,input().split())
#S=list(map(int,input().split()))
#S=[list(map(int,input().split())) for i in range(N)]
N,C=map(int,input().split())
XV=[list(map(int,input().split())) for i in range... | Python | zaydzuhri_stack_edu_python |
import os , shutil , numpy as np
from wordSeg import getLabels
function letterCounter
begin
set your_path_here = string /Users/ovoowo/Desktop/fraktur
comment your_path_here = '/Users/Christine/cs/fraktur'
set path = your_path_here + string /segmentation
comment list of book folders in 'data'
change directory your_path_... | import os, shutil, numpy as np
from wordSeg import getLabels
def letterCounter():
your_path_here = '/Users/ovoowo/Desktop/fraktur'
# your_path_here = '/Users/Christine/cs/fraktur'
path = your_path_here + '/segmentation'
# list of book folders in 'data'
os.chdir(your_path_here + '/data')
folders... | Python | zaydzuhri_stack_edu_python |
function addEdge self u v
begin
append graph at u v
end function | def addEdge(self,u,v):
self.graph[u].append(v) | Python | nomic_cornstack_python_v1 |
function peek self word_list
begin
if word_list
begin
set word = word_list at 0
return word at 0
end
else
begin
return none
end
end function | def peek(self, word_list):
if word_list:
word = word_list[0]
return word[0]
else:
return None | Python | nomic_cornstack_python_v1 |
function verify_post self username title
begin
call wait_and_click locator_type=XPATH locator=format MY_PROFILE_BUTTON_XPATH lower_username=username
call verify_message xpath=POST_NAMES_XPATH text=title
set text = call find_elements_by_xpath POST_NAMES_XPATH
assert length text == 1
assert text == title
end function | def verify_post(self, username, title):
self.wait_and_click(locator_type=By.XPATH,
locator=ProfilePageConstants.MY_PROFILE_BUTTON_XPATH.format(lower_username=username))
self.verify_message(xpath=ProfilePageConstants.POST_NAMES_XPATH, text=title)
text = self.driver.fin... | Python | nomic_cornstack_python_v1 |
from collections import deque
function maxSequence arr
begin
comment convert the incoming list to a deque
set d = deque arr
comment get rid of all values < 1 that are on left & right edges
while d
begin
if d at 0 < 1
begin
call popleft
end
else
if d at - 1 < 1
begin
pop d
end
else
begin
break
end
end
comment covers cas... | from collections import deque
def maxSequence(arr):
d = deque(arr) # convert the incoming list to a deque
while d: # get rid of all values < 1 that are on left & right edges
if d[0] < 1:
d.popleft()
elif d[-1] < 1:
d.pop()
els... | Python | zaydzuhri_stack_edu_python |
function trusted_cert_path self
begin
return get pulumi self string trusted_cert_path
end function | def trusted_cert_path(self) -> Optional[Any]:
return pulumi.get(self, "trusted_cert_path") | Python | nomic_cornstack_python_v1 |
function OnImportarDesdeBin self event
begin
call OnNuevoPrograma event
if cancel
begin
pass
end
set dlg = call FileDialog self message=string Abrir archivo ... defaultDir=DIRACTUAL defaultFile=string wildcard=wildcardbin style=OPEN
call SetFilterIndex 2
if call ShowModal == ID_OK
begin
set path = call GetPath
import ... | def OnImportarDesdeBin(self, event):
self.OnNuevoPrograma(event)
if self.cancel:
pass
dlg = wx.FileDialog(
self, message="Abrir archivo ...", defaultDir=DIRACTUAL,
defaultFile="", wildcard=wildcardbin, style=wx.OPEN
)
dlg.... | Python | nomic_cornstack_python_v1 |
function asteriscos n
begin
print n * string *
end function
call asteriscos n | def asteriscos(n):
print(n*'*')
asteriscos(n) | Python | zaydzuhri_stack_edu_python |
for i in range 1796
begin
try
begin
if sa == string a
begin
set sa = a at 0
set a = a at slice 1 : :
end
else
if sa == string b
begin
set sa = b at 0
set b = b at slice 1 : :
end
else
if sa == string c
begin
set sa = c at 0
set c = c at slice 1 : :
end
end
except any
begin
print upper sa
break
end
end | for i in range(1796):
try:
if sa == 'a':
sa = a[0]
a = a[1:]
elif sa == 'b':
sa = b[0]
b = b[1:]
elif sa == 'c':
sa = c[0]
c = c[1:]
except:
print(sa.upper())
break | Python | zaydzuhri_stack_edu_python |
string 函数参数 实际参数 位置实参 关键字实参
function func01 p1 p2 p3
begin
print p1
print p2
print p3
end function
comment 位置实参:按顺序与形参进行对应
call func01 1 2 3
comment func01(1, 2, 3, 4)
comment func01(1, 2)
comment 关键字实参:按名字与形参进行对应
call func01 p2=2 p1=1 p3=3 | """
函数参数
实际参数
位置实参
关键字实参
"""
def func01(p1, p2, p3):
print(p1)
print(p2)
print(p3)
# 位置实参:按顺序与形参进行对应
func01(1, 2, 3)
# func01(1, 2, 3, 4)
# func01(1, 2)
# 关键字实参:按名字与形参进行对应
func01(p2=2, p1=1, p3=3)
| Python | zaydzuhri_stack_edu_python |
import sqlite3
from pathlib import Path
from copy import copy
class DB
begin
function __init__ self caminhoDoArquivo tableName dataNameList connection=none
begin
string caminhoDoArquivo: String com o caminho do arquivo tableName: String com o nome da tabela dataNameList: Lista de strings com os nomes de cada atributo
s... | import sqlite3
from pathlib import Path
from copy import copy
class DB():
def __init__(self, caminhoDoArquivo, tableName, dataNameList, connection=None):
'''caminhoDoArquivo: String com o caminho do arquivo
tableName: String com o nome da tabela
dataNameList: L... | Python | zaydzuhri_stack_edu_python |
function on_comment_posted sender comment request **kwargs
begin
string Send email notification of a new comment to site staff when email notifications have been requested.
set content_object = content_object
set moderator = call get_model_moderator __class__
if moderator is none or __class__ is not CommentModel
begin
... | def on_comment_posted(sender, comment, request, **kwargs):
"""
Send email notification of a new comment to site staff when email notifications have been requested.
"""
content_object = comment.content_object
moderator = moderation.get_model_moderator(content_object.__class__)
if moderator is No... | Python | jtatman_500k |
function onOK self e
begin
if call GetValue == string
begin
set trg_warning = call MessageDialog none message=string No target parameters specified! Generate defaults? caption=string No Target Parameters style=YES_NO ? ICON_EXCLAMATION
if call ShowModal == ID_YES
begin
call write_default_phil
end
call Destroy
return
e... | def onOK(self, e):
if self.phil.ctr.GetValue() == '':
trg_warning = wx.MessageDialog(None,
message='No target parameters specified! Generate defaults?',
caption='No Target Parameters',
style=wx.YES_... | Python | nomic_cornstack_python_v1 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from module import clones , LayerNorm , subsequent_mask
class Generator extends Module
begin
string Define standard linear + softmax generation step.
function __init__ self d_model vocab
begin
call __init__
set proj =... | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from module import clones,LayerNorm,subsequent_mask
class Generator(nn.Module):
"Define standard linear + softmax generation step."
def __init__(self, d_model, vocab):
super(Generator, self).__init__(... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
string Size of a matrix
function matrix_shape matrix
begin
string Function that calculates the shape of a matrix
set size = list
append size length matrix
if type matrix at 0 == list
begin
while type matrix at 0 != int
begin
append size length matrix at 0
set matrix = matrix at 0
end
end
... | #!/usr/bin/env python3
"""Size of a matrix"""
def matrix_shape(matrix):
"""Function that calculates the shape of a matrix"""
size = []
size.append(len(matrix))
if type(matrix[0]) == list:
while type(matrix[0]) != int:
size.append(len(matrix[0]))
matrix = matrix[0]
r... | Python | zaydzuhri_stack_edu_python |
comment Python3 code to demonstrate working of
comment Convert string list into multiple cases
comment Using inbuilt functions + list comprehension
comment Initializing list
set test_list = list string bLue string ReD string yeLLoW
comment printing original list
print string The original list is : + string test_list
co... | # Python3 code to demonstrate working of
# Convert string list into multiple cases
# Using inbuilt functions + list comprehension
# Initializing list
test_list = ['bLue', 'ReD', 'yeLLoW']
# printing original list
print("The original list is : " + str(test_list))
# Convert string list into multiple cases... | Python | zaydzuhri_stack_edu_python |
function pretty_print_poas_result probability rerolls num_objects
begin
set result = call probability_of_all_successes probability rerolls num_objects
print string Given { num_objects } dice with a probability of success of { probability } and { rerolls } rolls
print string The probability of achieving all successes is... | def pretty_print_poas_result(probability: float, rerolls: int, num_objects: int):
result = probability_of_all_successes(probability, rerolls, num_objects)
print(f"Given {num_objects} dice with a probability of success of {probability} and {rerolls} rolls")
print(f"The probability of achieving all successes... | Python | nomic_cornstack_python_v1 |
function count_digits n
begin
set count = 0
set n = absolute n
while n != 0
begin
set count = count + 1
set n = n // 10
end
return count
end function | def count_digits(n):
count = 0
n=abs(n)
while n!=0:
count += 1
n = n // 10
return count | Python | nomic_cornstack_python_v1 |
comment pragma no cover
function _best_case
begin
set setup_code = string from __main__ import _best_case from bst import BinarySearchTree from bst import Node
set test_code = string new_tree = BinarySearchTree([4,2,3,1,6,5,7]) new_tree.search(7)
return repeat setup=setup_code stmt=test_code number=100000
end function | def _best_case(): # pragma no cover
setup_code = """
from __main__ import _best_case
from bst import BinarySearchTree
from bst import Node
"""
test_code = """
new_tree = BinarySearchTree([4,2,3,1,6,5,7])
new_tree.search(7)
"""
return(timeit.repeat(setup=setup_code, stmt=test_code, number=100000)) | Python | nomic_cornstack_python_v1 |
function max_size self
begin
return get pulumi self string max_size
end function | def max_size(self) -> Optional[str]:
return pulumi.get(self, "max_size") | Python | nomic_cornstack_python_v1 |
comment This challenge asks to split an input string
comment by its even and odd characters, separated
comment by a space on the same line.
comment take an input
comment word = int(input())
function eo_split word
begin
comment Separate each character
set split_word = list word
comment Begin with empty even and odd list... | # This challenge asks to split an input string
# by its even and odd characters, separated
# by a space on the same line.
# take an input
# word = int(input())
def eo_split(word):
# Separate each character
split_word = list(word)
# Begin with empty even and odd lists
evens = []
odds = []
# ... | Python | zaydzuhri_stack_edu_python |
function test_lazy_tensor_flops self
begin
set model = call LazyLinear 10
set ms = call get_module_summary model module_args=tuple randn 1 10
with call assertWarns Warning
begin
num_parameters
end
with call assertWarns Warning
begin
num_trainable_parameters
end
assert true has_uninitialized_param
assert equal flops_bac... | def test_lazy_tensor_flops(self) -> None:
model = torch.nn.LazyLinear(10)
ms = get_module_summary(model, module_args=(torch.randn(1, 10),))
with self.assertWarns(Warning):
ms.num_parameters
with self.assertWarns(Warning):
ms.num_trainable_parameters
self.a... | Python | nomic_cornstack_python_v1 |
function _do_if_tags_check_fails self info file name description tag tag_check_output **kwargs
begin
raise call ValueError string Tag Check on file named " { name } " has failed: { tag_check_output }
end function | def _do_if_tags_check_fails(self, info, file: InMemoryUploadedFile, name: str, description: str, tag: str, tag_check_output, **kwargs):
raise ValueError(f"Tag Check on file named \"{name}\" has failed: {tag_check_output}") | Python | nomic_cornstack_python_v1 |
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup_ import Base , User
import helper_functions_
import config_ , uuid
comment Connects to the database
set engine = call create_engine call path_to_db
set bind = engine
set DBSession = call sessionmaker bind=engine
set session... | from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup_ import Base, User
import helper_functions_
import config_, uuid
# Connects to the database
engine = create_engine(config_.path_to_db())
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession... | Python | zaydzuhri_stack_edu_python |
function initialize_children self
begin
set j = 0
comment Go through all the bibliography files
for bib in bibs
begin
set j = j + 1
with open bib errors=string backslashreplace as input
begin
comment Fetch or add the parent paper
set splits = split re string \[[0-9]+\] strip read line input
set parent_citation = call c... | def initialize_children(self):
j = 0
# Go through all the bibliography files
for bib in self.bibs:
j += 1
with open(bib, errors="backslashreplace") as input:
# Fetch or add the parent paper
splits = re.split('\[[0-9]+\]', input.readline().strip())
parent_citation = clean_citation(splits... | Python | nomic_cornstack_python_v1 |
function test_ensured_block_ranges
begin
set h = call Hived
assert list call pluck string block_num call get_blocks_range 1000 2000 == list range 1000 2000
end function
comment for fuzzing in h.get_block_range_ensured() use:
comment degraded_results = [x for x in results if x['block_num'] %
comment random.choice(range(... | def test_ensured_block_ranges():
h = Hived()
assert list(pluck('block_num', h.get_blocks_range(1000, 2000))) == list(
range(1000, 2000))
# for fuzzing in h.get_block_range_ensured() use:
# degraded_results = [x for x in results if x['block_num'] %
# random.choice(range(1, 10)) != 0] | Python | nomic_cornstack_python_v1 |
import scrapy
from scrapy.selector import Selector
from pandas import DataFrame , Series
from items import DoubanItem
class DoubanbookSpider extends Spider
begin
set name = string doubanbook
set allowed_domains = list string book.douban.com
set start_urls = list string https://book.douban.com/top250
function parse self... | import scrapy
from scrapy.selector import Selector
from pandas import DataFrame,Series
from ..items import DoubanItem
class DoubanbookSpider(scrapy.Spider):
name = 'doubanbook'
allowed_domains = ['book.douban.com']
start_urls = ['https://book.douban.com/top250']
def parse(self, response):
# ... | Python | zaydzuhri_stack_edu_python |
import pylab
set PATH_TO_FILE = string julyTemps.txt
function load_words
begin
try
begin
set inFile = open PATH_TO_FILE string r
end
except IOError
begin
print string No file for July Temperature.
end
set high = list
set low = list
set line = read line inFile
while line
begin
set fields = split line string
if length ... | import pylab
PATH_TO_FILE = 'julyTemps.txt'
def load_words():
try:
inFile = open(PATH_TO_FILE, 'r')
except IOError:
print("No file for July Temperature.")
high = []
low = []
line = inFile.readline()
while line:
fields = line.split(' ')
if len(fields) == 3 and f... | Python | zaydzuhri_stack_edu_python |
function frequency_sort items
begin
comment your code here
return sorted items key=lambda i -> tuple count items i - 1 * index items i reverse=true
end function
string Chekio Mission Link: https://py.checkio.org/en/mission/sort-array-by-element-frequency/ Chekio Solution Link: https://py.checkio.org/mission/sort-array-... | def frequency_sort(items):
# your code here
return sorted(items, key=lambda i: (items.count(i), -1 * items.index(i)), reverse=True)
'''
Chekio Mission Link:
https://py.checkio.org/en/mission/sort-array-by-element-frequency/
Chekio Solution Link:
https://py.checkio.org/mission/sort-array-by-element-frequency/p... | Python | zaydzuhri_stack_edu_python |
class Plane
begin
function __init__ self source busy_time id
begin
set source = source
set busy_time = busy_time
set id = id
end function
function is_busy self time
begin
if busy_time > time
begin
return 1
end
else
begin
return 0
end
end function
function setSource self source
begin
set source = source
end function
fun... | class Plane:
def __init__(self, source, busy_time, id):
self.source = source
self.busy_time = busy_time
self.id = id
def is_busy(self, time):
if ( self.busy_time > time ):
return 1
else:
return 0
def setSource(self, source):
self.sour... | Python | zaydzuhri_stack_edu_python |
import os
import serial
import sys
import json
import time
function get_usb_device name default=string /dev/ttyUSB0 device_id=none
begin
try
begin
set results = split read popen string dmesg |grep -i "ttyUSB"| grep -i "now attached" string
for line in reversed results
begin
print string line: %s % line
if name in line
... | import os
import serial
import sys
import json
import time
def get_usb_device(name, default='/dev/ttyUSB0', device_id=None):
try:
results = os.popen('dmesg |grep -i "ttyUSB"| grep -i "now attached"').read().split('\n')
for line in reversed(results):
print('line: %s' % line)
... | Python | zaydzuhri_stack_edu_python |
function add_set self set_name
begin
try
begin
set new_set = set name=set_name key_name=set_name
put
return true
end
except any
begin
return false
end
end function | def add_set(self, set_name):
try:
new_set = Set(name = set_name,
key_name = set_name
)
new_set.put()
return True
except:
return False | Python | nomic_cornstack_python_v1 |
from collections import deque
import time
import random
comment inputs -> N: num_row, M: num_col
set tuple M N = map int split input string string
set box = list comprehension list *map(int, input('').split(' ')) for _ in range N
comment # test inputs
comment M, N = 500, 500
comment box = [[random.randint(0, 1)] * M fo... | from collections import deque
import time
import random
# inputs -> N: num_row, M: num_col
M, N = map(int, input('').split(' '))
box = [[*map(int, input('').split(' '))] for _ in range(N)]
# # test inputs
# M, N = 500, 500
# box = [[random.randint(0, 1)] * M for _ in range(N)]
# start_time = time.time()
#############... | Python | zaydzuhri_stack_edu_python |
from tkinter import *
set root = call Tk
set pane = call Frame root height=150 width=150 bg=string green relief=RAISED bd=10.0
call place relx=0.5 rely=0.5 anchor=CENTER
function helloCallBack
begin
print string Hello Python
end function
set B = call Button pane height=2 width=10 text=string Hello command=helloCallBack... | from tkinter import *
root = Tk()
pane=Frame(root, height=150, width=150, bg = "green", relief = RAISED, bd = 10.)
pane.place( relx=0.5, rely=0.5,anchor=CENTER )
def helloCallBack():
print( "Hello Python")
B = Button(pane, height=2, width=10, text ="Hello", command = helloCallBack)
L = Label(pane, text= "Welc... | Python | zaydzuhri_stack_edu_python |
function fiona_open path mode=string r **kwargs
begin
set path = call from_inp path
if string w in mode
begin
with call fiona_write path mode=mode keyword kwargs as dst
begin
yield dst
end
end
else
begin
with call fiona_read path mode=mode keyword kwargs as src
begin
yield src
end
end
end function | def fiona_open(path, mode="r", **kwargs):
path = MPath.from_inp(path)
if "w" in mode:
with fiona_write(path, mode=mode, **kwargs) as dst:
yield dst
else:
with fiona_read(path, mode=mode, **kwargs) as src:
yield src | Python | nomic_cornstack_python_v1 |
function delaunay R
begin
set vol = 0.0
set delaunay = call Delaunay R
set root = call Tree call NodeData vertices=R
comment This is a temporary "pointer" that goes down the tree
set cursor = root
comment Number of simplices
set Nsx = shape at 0
if Nsx == 1
begin
set vol = vol + call simplex_volume R
end
for i in range... | def delaunay(R):
vol = 0.
delaunay = scs.Delaunay(R)
root = Tree(NodeData(vertices=R))
cursor = root # This is a temporary "pointer" that goes down the tree
Nsx = delaunay.simplices.shape[0] # Number of simplices
if Nsx==1:
vol += simplex_volume(R)
for i in range(Nsx-1):
left... | Python | nomic_cornstack_python_v1 |
function test_create_firewall_policy_with_all_params self
begin
set resource = string firewall_policy
set cmd = call CreateFirewallPolicy call MyApp stdout none
set name = string my-name
set description = string my-desc
set firewall_rules_arg = string rule_id1 rule_id2
set firewall_rules_res = list string rule_id1 stri... | def test_create_firewall_policy_with_all_params(self):
resource = 'firewall_policy'
cmd = firewallpolicy.CreateFirewallPolicy(test_cli20.MyApp(sys.stdout),
None)
name = 'my-name'
description = 'my-desc'
firewall_rules_arg = ... | Python | nomic_cornstack_python_v1 |
for i in range 2 s + 1
begin
if s % i == 0
begin
break
end
end
if s == i
begin
print string yes
end
else
begin
print string no
end | for i in range(2,s+1):
if(s%i==0):
break;
if(s==i):
print("yes")
else:
print("no")
| Python | zaydzuhri_stack_edu_python |
class RawEvent extends object
begin
function __init__ self time
begin
set time = time
return
end function
function __del__ self
begin
print string RawEvent is destroyed: + string time
return
end function
function getTime self
begin
return time
end function
end class
set evt = call RawEvent 33
set eventsIn = dict 1 list... | class RawEvent(object):
def __init__(self, time):
self.time = time
return
def __del__(self):
print("RawEvent is destroyed: " + str(self.time))
return
def getTime(self) :
return self.time
evt = RawEvent(33)
eventsIn = {1 : [evt, RawEvent(35), RawEvent(36)], 3:[RawE... | Python | zaydzuhri_stack_edu_python |
import pytest
from polar.lang import OutMessageEvent , UserMessage
from polar.lang.all import SimpleResponse , Flow
from polar.lang.eval import Bot , Rule
from polar.lang.regex_rule import RegexRule
from tests.logic import execute_event
function test_trivial_logic
begin
set bot = call Bot
set rule_mind = call Rule name... | import pytest
from polar.lang import OutMessageEvent, UserMessage
from polar.lang.all import SimpleResponse, Flow
from polar.lang.eval import Bot, Rule
from polar.lang.regex_rule import RegexRule
from tests.logic import execute_event
def test_trivial_logic():
bot = Bot()
rule_mind = Rule(name="name")
ru... | Python | zaydzuhri_stack_edu_python |
comment Adriana Avalos Vargas
comment Lets call de modules
comment Module for paths
import os
comment Module for reading CSV files
import csv
comment - - - - - - - - - - - - - -- - - - - -- - - - - - - -
comment Lets fix the path
set csvpath = join path string Resources string budget_data.csv
comment - - - - - - - - - ... | #Adriana Avalos Vargas
#Lets call de modules
#Module for paths
import os
# Module for reading CSV files
import csv
#- - - - - - - - - - - - - -- - - - - -- - - - - - - -
#Lets fix the path
csvpath = os.path.join('Resources', 'budget_data.csv')
#- - - - - - - - - - - - - - - - - - - - - - - - - --
#A counter to coun... | Python | zaydzuhri_stack_edu_python |
import sys
comment G is the gamma matrix
comment par is the parent array
comment n is the number of nodes
function writeGammaMatrix gammaFile G par n
begin
for i in range n
begin
for j in range n
begin
set G at i at j = 0
end
end
for i in range n
begin
set G at i at i = 1
set j = par at i - 1
while j > - 1
begin
set G ... | import sys
# G is the gamma matrix
# par is the parent array
# n is the number of nodes
def writeGammaMatrix(gammaFile, G, par, n):
for i in range(n):
for j in range(n):
G[i][j] = 0
for i in range(n):
G[i][i] = 1
j = par[i]-1
while j > -1:
G[j][i] = 1
j = par[j]-1
for i in range(n):
for j in ra... | Python | jtatman_500k |
comment !/usr/bin/env python
comment ! -*- coding: utf-8 -*-
comment CheaterPress (LetterPress Cheat) is dedicated to the new word game LetterPress.
comment Enter all 25 letters from the 5 by 5 game board and you'll get a list of all the words that you can spell.
comment Boubakr NOUR <n.boubakr@gmail.com>
import sys
fu... | #!/usr/bin/env python
#! -*- coding: utf-8 -*-
#
# CheaterPress (LetterPress Cheat) is dedicated to the new word game LetterPress.
# Enter all 25 letters from the 5 by 5 game board and you'll get a list of all the words that you can spell.
#
# Boubakr NOUR <n.boubakr@gmail.com>
import sys
def loadWords(dictionary_... | Python | zaydzuhri_stack_edu_python |
function post_mock_response status_code content
begin
set test_mock = call Mock
set status_code = status_code
set content = content
function mock_response api_url headers timeout proxies
begin
return test_mock
end function
return mock_response
end function | def post_mock_response(status_code, content):
test_mock = mock.Mock()
test_mock.status_code = status_code
test_mock.content = content
def mock_response(api_url, headers, timeout, proxies):
return test_mock
return mock_response | Python | nomic_cornstack_python_v1 |
function binary_search_recursive a_list item
begin
if length a_list == 0
begin
return false
end
else
begin
set midpoint = length a_list // 2
if a_list at midpoint == item
begin
return true
end
else
if item < a_list at midpoint
begin
return call binary_search_recursive a_list at slice : midpoint : item
end
else
begin
... | def binary_search_recursive(a_list, item):
if len(a_list) == 0:
return False
else:
midpoint = len(a_list) // 2
if a_list[midpoint] == item:
return True
else:
if item < a_list[midpoint]:
return binary_search_recursive(a_list[:midpoint], item... | Python | nomic_cornstack_python_v1 |
function invoke_sanity_checks self *args **kwargs
begin
set ID_IS_DONE = 0
if call am_i_done
begin
return list tuple true true string ID_IS_DONE none
end
else
begin
set msg = string Please finish annotating all ballot attributes. If you are on the last ballot, please click the 'Next' button one more time.
return list ... | def invoke_sanity_checks(self, *args, **kwargs):
ID_IS_DONE = 0
if self.attr_panel.am_i_done():
return [(True, True, "", ID_IS_DONE, None)]
else:
msg = "Please finish annotating all ballot attributes. If \
you are on the last ballot, please click the 'Next' button one mor... | Python | nomic_cornstack_python_v1 |
function __day_time self kwargs
begin
del kwargs
log string Day timer triggered
if scene == string Morning
begin
set scene = string Day
end
else
begin
log string Scene not changed to Day from Morning (scene is { scene } )
end
end function | def __day_time(self, kwargs: dict):
del kwargs
self.log("Day timer triggered")
if self.scene == "Morning":
self.scene = "Day"
else:
self.log(f"Scene not changed to Day from Morning (scene is {self.scene})") | Python | nomic_cornstack_python_v1 |
function start self
begin
comment register self to the sigchld_handler
call sigchld_handler process=self
comment register the sigchld_handler
set sig_handler = call signal SIGCHLD sigchld_handler
try
begin
if string CLEWN_PIPES in environ or string CLEWN_POPEN in environ
begin
popen
end
else
begin
call ptyopen
end
end
... | def start(self):
# register self to the sigchld_handler
sigchld_handler(process=self)
# register the sigchld_handler
self.sig_handler = signal.signal(signal.SIGCHLD, sigchld_handler)
try:
if 'CLEWN_PIPES' in os.environ or 'CLEWN_POPEN' in os.environ:
... | Python | nomic_cornstack_python_v1 |
class Polygon2D
begin
string (Regular) Polygon class for a layer
decorator staticmethod
function regular_polygon layer x y r n c antialias=false
begin
string Draw a regular polygon with center (x, y), radius r, division n, color c
for i in range n
begin
call line layer round x + r * cos 2 * pi * i / n round y + r * sin... | class Polygon2D:
"""(Regular) Polygon class for a layer"""
@staticmethod
def regular_polygon(layer:Layer, x, y, r, n, c, antialias=False):
"""Draw a regular polygon with center (x, y), radius r, division n, color c"""
for i in range(n):
Line2D.line(layer, round(x + r * np.cos(2 ... | Python | zaydzuhri_stack_edu_python |
function rnd x
begin
set digits = 6
if x == 0 or not call isfinite x
begin
return x
end
set digits = digits - ceil call log10 absolute x
return round x digits
end function | def rnd(x):
digits = 6
if x == 0 or not math.isfinite(x):
return x
digits -= math.ceil(math.log10(abs(x)))
return round(x, digits) | Python | nomic_cornstack_python_v1 |
import itertools
set n = integer input
set A = list comprehension 0 for i in range n
set A = split input
for i in range n
begin
set A at i = integer A at i
end
set q = integer input
set B = list comprehension 0 for i in range q
set B = split input
set C = list
for i in range q
begin
set B at i = integer B at i
end
set... | import itertools
n=int(input())
A=[0 for i in range(n)]
A=input().split()
for i in range(n):
A[i]=int(A[i])
q=int(input())
B=[0 for i in range(q)]
B=input().split()
C=[]
for i in range(q):
B[i]=int(B[i])
l=[0,1]
p=[]
k=0
D=[]
for v in itertools.product(l,repeat=n):
sum=0
for i in range(n):
if v[... | Python | zaydzuhri_stack_edu_python |
comment noqa
function test_default_domain_given_same_file create_temp_yaml
begin
set conf_file1 = call create_temp_yaml dict
set domain1 = call default_domain conf_file1
set domain2 = call default_domain conf_file1
assert domain1 is domain2
end function | def test_default_domain_given_same_file(create_temp_yaml): # noqa
conf_file1 = create_temp_yaml({})
domain1 = domain.default_domain(conf_file1)
domain2 = domain.default_domain(conf_file1)
assert domain1 is domain2 | Python | nomic_cornstack_python_v1 |
function gibbs_reduce graph_h structure exponent num_samples
begin
comment Construct an isomorphism CSP from the given graph_h and structure
set formula = call IsomorphismCSP graph_h structure
set old_percent_nailed = 0.0
set unnailed = set comprehension n for n in call nodes if not call nailed
comment Loop forever
whi... | def gibbs_reduce(graph_h, structure, exponent, num_samples):
# Construct an isomorphism CSP from the given graph_h and structure
formula = IsomorphismCSP(graph_h, structure)
old_percent_nailed = 0.
unnailed = {n for n in graph_h.nodes() if not n.nailed()}
# Loop forever
while True:
... | Python | nomic_cornstack_python_v1 |
print string # to display 'hello' equivalent to the number of letters in your name.
set b = input string enter your name.
set c = length b
set n = 1
while n <= c
begin
print string hello, b string you've got a nice name. :)
set n = n + 1
end | print("# to display 'hello' equivalent to the number of letters in your name. ")
b=(input("enter your name. "))
c=len(b)
n=1
while(n<=c):
print(" hello, ",b," you've got a nice name. :)")
n=n+1 | Python | zaydzuhri_stack_edu_python |
function gain_bias self max_rates intercepts
begin
set gain = max_rates / 1 - intercepts
set bias = - intercepts * gain
return tuple gain bias
end function | def gain_bias(self, max_rates, intercepts):
gain = max_rates / (1 - intercepts)
bias = -intercepts * gain
return gain, bias | Python | nomic_cornstack_python_v1 |
import sys
import subprocess
set query = argv at 1
function write_to_clipboard output
begin
set process = popen string pbcopy env=dict string LANG string en_US.UTF-8 stdin=PIPE
communicate process encode output string utf-8
end function
set out = string
set glue = string ::scrabble
if query at 0 == string +
begin
set ... | import sys
import subprocess
query = sys.argv[1]
def write_to_clipboard(output):
process = subprocess.Popen(
'pbcopy', env={'LANG': 'en_US.UTF-8'}, stdin=subprocess.PIPE)
process.communicate(output.encode('utf-8'))
out = ''
glue = '::scrabble'
if query[0] == '+':
glue = ': +:scrabble'
quer... | Python | zaydzuhri_stack_edu_python |
function load_listings_to_api self *args
begin
comment Unpackinig tuple:
set job_listings = args at 0
comment If the list of posts contains no entries end w/o making POST request:
if length job_listings < 1
begin
warning string No Data Recieved from recursive extraction method. Exiting w/o making POST request. string i... | def load_listings_to_api(self, *args):
# Unpackinig tuple:
job_listings = args[0]
# If the list of posts contains no entries end w/o making POST request:
if len(job_listings) < 1:
self.logger.warning(f"No Data Recieved from recursive extraction method. Exiting w... | Python | nomic_cornstack_python_v1 |
function calcVecProjection a b
begin
return dot a call normalize b
end function | def calcVecProjection(a, b):
return dot(a, normalize(b)) | Python | nomic_cornstack_python_v1 |
function GetReferencedPackage self
begin
set callResult = call _Call string GetReferencedPackage
if callResult is none
begin
return none
end
set objId = callResult
set classInstance = Package
return call classInstance _xmlRpc objId
end function | def GetReferencedPackage(self):
callResult = self._Call("GetReferencedPackage", )
if callResult is None:
return None
objId = callResult
classInstance = Package
return classInstance(self._xmlRpc, objId) | 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.