code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function minmove board
begin
if call terminal board
begin
return call utility board
end
set value = inf
for action in call actions board
begin
set value = min value call maxmove call result board action
end
return value
end function | def minmove(board):
if terminal(board):
return utility(board)
value = math.inf
for action in actions(board):
value = min(value, maxmove(result(board, action)))
return value | Python | nomic_cornstack_python_v1 |
function factorial num
begin
if num == 1
begin
return 1
end
else
begin
return num * call factorial num - 1
end
end function | def factorial(num):
if num==1:
return 1
else:
return(num*factorial(num-1)) | Python | nomic_cornstack_python_v1 |
function prep_image self
begin
set image = call render text true text_color bg_color
set image_rect = call get_rect
end function | def prep_image(self):
self.image = self.font.render(self.text, True, self.text_color, self.bg_color)
self.image_rect = self.image.get_rect() | Python | nomic_cornstack_python_v1 |
function create_ch_slice self
begin
import gcf.sfa.trust.credential as cred
set slice_cred_string = call wrap_xmlrpc_call CreateSlice list dict TIMEOUT
set slice_credential = call Credential string=slice_cred_string
set slice_gid = call get_gid_object
set slice_urn = call get_urn
comment Set up the array of credentia... | def create_ch_slice(self):
import gcf.sfa.trust.credential as cred
slice_cred_string = wrap_xmlrpc_call(
self.ch_client.CreateSlice, [], {}, settings.TIMEOUT)
slice_credential = cred.Credential(string=slice_cred_string)
slice_gid = slice_credential.get_gid_object()
... | Python | nomic_cornstack_python_v1 |
import pytest
from DependentPropertyValidator import DependentPropertyValidator
from Exceptions import ValidationError , DependencyInputError
comment region Wrappers
function single_dependent_validation A B types_list **options_dict
begin
set DPV = call DependentPropertyValidator A B
call add_property_dependency types_... | import pytest
from DependentPropertyValidator import DependentPropertyValidator
from Exceptions import ValidationError, DependencyInputError
#region Wrappers
def single_dependent_validation(A, B, types_list, **options_dict):
DPV = DependentPropertyValidator(A, B)
DPV.add_property_dependency(types_list, **optio... | Python | zaydzuhri_stack_edu_python |
function merge left right
begin
if length left <= 0
begin
return right
end
if length right <= 0
begin
return left
end
if left at 0 < right at 0
begin
return list left at 0 + merge left at slice 1 : : right
end
else
begin
return list right at 0 + merge left right at slice 1 : :
end
end function
function merge_sort ar... | def merge(left, right):
if len(left) <= 0:
return right
if len(right) <= 0:
return left
if left[0] < right[0]:
return [left[0]] + merge(left[1:], right)
else:
return [right[0]] + merge(left, right[1:])
def merge_sort(array):
if len(array) < 2:
return array
... | Python | zaydzuhri_stack_edu_python |
function cart2sphere x y z
begin
set vector = call asarray list x y z
set tuple x y z = vector / square root sum 1 at tuple slice : : none
set theta = call arccos z
set phi = call arcsin y / sin theta
return tuple theta phi
end function | def cart2sphere(x, y, z):
vector = np.asarray([x, y, z])
x, y, z = vector / np.sqrt((vector*vector).sum(1))[:, None]
theta = np.arccos(z)
phi = np.arcsin(y / np.sin(theta))
return theta, phi | Python | nomic_cornstack_python_v1 |
function kind self
begin
return _job at string _class
end function | def kind(self):
return self._job['_class'] | Python | nomic_cornstack_python_v1 |
function dumpGroups self
begin
try
begin
call sendline string
call expect prompt
call sendline string client_grouptable_dump > groups.txt
call expect prompt
set response = before
comment Write back in the tmp folder - needs to be changed in future
with open tempDirectory + string groups_%s.txt % dpid string w as groups... | def dumpGroups( self ):
try:
self.handle.sendline( "" )
self.handle.expect( self.prompt )
self.handle.sendline( "client_grouptable_dump > groups.txt" )
self.handle.expect( self.prompt )
response = self.handle.before
# Write back in the tmp ... | Python | nomic_cornstack_python_v1 |
comment Game for adults or kids: To be decided at the runtime of application based on the inputs
comment Kid's Game
class Frog
begin
function __init__ self name
begin
set _name = name
end function
function __str__ self
begin
return _name
end function
function interact_with self obstacle
begin
print format string {} the... | # Game for adults or kids: To be decided at the runtime of application based on the inputs
# Kid's Game
class Frog:
def __init__(self, name):
self._name = name
def __str__(self):
return self._name
def interact_with(self, obstacle):
print("{} the frog encounters {} and {}".forma... | Python | zaydzuhri_stack_edu_python |
function lines_groupsize raw_lines sorted_lines
begin
set groupsize = 1
if raw_lines
begin
set groupsize = length raw_lines
end
else
begin
for check in tuple string avg string trend
begin
if any generator expression starts with item at 0 check for item in sorted_lines
begin
set groupsize = length list comprehension ite... | def lines_groupsize(raw_lines, sorted_lines):
groupsize = 1
if raw_lines:
groupsize = len(raw_lines)
else:
for check in ("avg", "trend"):
if any(item[0].startswith(check) for item in sorted_lines):
groupsize = len([item for item in sort... | Python | nomic_cornstack_python_v1 |
function executeAndLogExecution dataDir dataFile prefix
begin
set dateBegin = string now at slice : - 7 :
end function
comment Execute the given command normally | def executeAndLogExecution(dataDir, dataFile, prefix):
dateBegin = str(datetime.datetime.now())[:-7]
# Execute the given command normally | Python | nomic_cornstack_python_v1 |
string This type stub file was generated by pyright.
from abc import ABCMeta , abstractmethod
from _ball_tree import BallTree
from _kd_tree import KDTree
from base import BaseEstimator , MultiOutputMixin
from metrics.pairwise import PAIRWISE_DISTANCE_FUNCTIONS
string Base and mixin classes for nearest neighbors
set VAL... | """
This type stub file was generated by pyright.
"""
from abc import ABCMeta, abstractmethod
from ._ball_tree import BallTree
from ._kd_tree import KDTree
from ..base import BaseEstimator, MultiOutputMixin
from ..metrics.pairwise import PAIRWISE_DISTANCE_FUNCTIONS
"""Base and mixin classes for nearest neighbors"""
V... | Python | zaydzuhri_stack_edu_python |
if __name__ == string __main__
begin
set n = integer input
set lo = n
set hi = n
while lo % 100 != 99 and hi % 100 != 99
begin
set lo = lo - 1
if lo < 0
begin
set lo = 0
end
set hi = hi + 1
end
if hi % 100 == 99
begin
print hi
end
else
begin
print lo
end
end | if __name__ == "__main__":
n = int(input())
lo = n
hi = n
while lo % 100 != 99 and hi % 100 != 99:
lo -= 1
if lo < 0:
lo = 0
hi += 1
if hi % 100 == 99:
print(hi)
else:
print(lo)
| Python | zaydzuhri_stack_edu_python |
class Solution
begin
comment @param A : list of integers
comment @param B : integer
comment @return an integer
function searchInsert self A B
begin
if length A == 0
begin
return 0
end
else
begin
set tuple left right = call binarySearch A B
if left == right
begin
return left
end
else
begin
return right
end
end
end funct... | class Solution:
# @param A : list of integers
# @param B : integer
# @return an integer
def searchInsert(self, A, B):
if len(A) == 0: return 0
else:
left, right = self.binarySearch(A,B)
if left == right:
return left
else: return right
... | Python | zaydzuhri_stack_edu_python |
function __init__ self
begin
pass
end function | def __init__(self):
pass | Python | nomic_cornstack_python_v1 |
from django.test import TestCase
from models import Product , ProductModel , Order
from django.contrib.auth.models import User
class CoreModelTestCase extends TestCase
begin
function setUp self
begin
comment Creating models and products for iPhone
set iphone = call create name=string iPhone
set iphone_4s = call create ... | from django.test import TestCase
from .models import Product, ProductModel, Order
from django.contrib.auth.models import User
class CoreModelTestCase(TestCase):
def setUp(self):
# Creating models and products for iPhone
self.iphone = Product.objects.create(name='iPhone')
self.iphone_4s = ... | Python | zaydzuhri_stack_edu_python |
comment program to find whether person is eligiable to vote or not
comment input a from keyboard
set a = integer input string eenter the age of a:
comment print value of a
print string a:,a
if a >= 18
begin
print a string is eligiable to vote
end | #program to find whether person is eligiable to vote or not
#input a from keyboard
a=int(input("eenter the age of a:"))
#print value of a
print ("a:,a")
if (a>=18):
print(a,"is eligiable to vote") | Python | zaydzuhri_stack_edu_python |
class JSDict
begin
function __init__ self data
begin
for tuple k v in items data
begin
call __setattr__ k v
end
del __class__
end function
end class
class dct
begin
function items self
begin
for k in __keys
begin
yield get attribute self k
end
end function
function keys self
begin
return __keys
end function
function __... | class JSDict():
def __init__(self,data):
for (k,v) in data.items():
self.__setattr__(k,v)
del self.__class__
class dct:
def items(self):
for k in self.__keys:
yield getattr(self,k)
def keys(self):
return self.__keys
def __repr__(self):
... | Python | zaydzuhri_stack_edu_python |
import requests
from bs4 import BeautifulSoup
set headers = dict string user-agent string Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36
comment 爬取的网址虎扑nba新闻
set url = string https://voice.hupu.com/nba
set res = get requests url headers=headers
set so... | import requests
from bs4 import BeautifulSoup
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36'
}
url = 'https://voice.hupu.com/nba' # 爬取的网址虎扑nba新闻
res = requests.get(url, headers=headers)
soup = BeautifulSoup(res.text, '... | Python | zaydzuhri_stack_edu_python |
function getDefaultL3ParserSettings
begin
return call getDefaultL3ParserSettings
end function | def getDefaultL3ParserSettings():
return _libsbml.getDefaultL3ParserSettings() | Python | nomic_cornstack_python_v1 |
function isImperfectVerticalConsonance n1 n2
begin
set ivl = call Interval n1 n2
if simpleName in set literal string m3 string M3 string m6 string M6
begin
return true
end
else
begin
return false
end
end function | def isImperfectVerticalConsonance(n1, n2):
ivl = interval.Interval(n1, n2)
if ivl.simpleName in {'m3', 'M3', 'm6', 'M6'}:
return True
else:
return False | Python | nomic_cornstack_python_v1 |
function repo self
begin
return get pulumi self string repo
end function | def repo(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "repo") | Python | nomic_cornstack_python_v1 |
comment 7-1
set car = input string What kind of rental car do you want?
print string Let me see if I can find you a + title car
comment 7-2
set active = true
while active
begin
set number_in_group = input string How many people are in your dinner group? + string Enter 'quit' to exit.
if number_in_group == string quit
b... | #7-1
car = input("What kind of rental car do you want? ")
print("Let me see if I can find you a " + car.title())
#7-2
active = True
while active:
number_in_group = input("\nHow many people are in your dinner group? " +
"\nEnter 'quit' to exit. ")
if(number_in_group == 'quit'):
active = False
el... | Python | zaydzuhri_stack_edu_python |
class Node extends object
begin
function __init__ self name
begin
set name = name
set adjacency_list = list
set visited = false
set predeccesor = none
end function
end class
class DepthFirstSearch extends object
begin
function dfs self startnode
begin
set visited = true
print string %s % name
for n in adjacency_list
b... | class Node(object):
def __init__(self,name):
self.name = name
self.adjacency_list = []
self.visited = False
self.predeccesor = None
class DepthFirstSearch(object):
def dfs(self,startnode):
startnode.visited = True
print("%s "%startnode.name)
for n in s... | Python | zaydzuhri_stack_edu_python |
from twisted.web import client , error as weberror
from twisted.internet import reactor
import sys , getpass , base64 | from twisted.web import client,error as weberror
from twisted.internet import reactor
import sys,getpass,base64
| Python | zaydzuhri_stack_edu_python |
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfpage import PDFTextExtractionNotAllowed
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfdevice import PDFDevice... | from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfpage import PDFTextExtractionNotAllowed
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfdevice import PDFDevice... | Python | zaydzuhri_stack_edu_python |
from urllib.request import urlopen
from bs4 import BeautifulSoup
from nltk.tokenize import sent_tokenize , word_tokenize
from nltk.corpus import stopwords
from string import punctuation
from nltk.probability import FreqDist
from heapq import nlargest
from collections import defaultdict
set articleURL = string https://w... | from urllib.request import urlopen
from bs4 import BeautifulSoup
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.corpus import stopwords
from string import punctuation
from nltk.probability import FreqDist
from heapq import nlargest
from collections import defaultdict
articleURL = "https://ww... | Python | zaydzuhri_stack_edu_python |
function string_to_array array_string
begin
return loads array_string
end function | def string_to_array(array_string):
return cPickle.loads(array_string) | Python | nomic_cornstack_python_v1 |
set num = integer input string Digite um numero inteiro:
print format string Analisando o numero {} Unidade: {} Dezena: {} Centena: {} Milhar: {} num num // 1 % 10 num // 10 % 10 num // 100 % 10 num // 1000 % 10 | num = int(input('Digite um numero inteiro: '))
print(
'Analisando o numero {}'
'\nUnidade: {}'
'\nDezena: {}'
'\nCentena: {}'
'\nMilhar: {}'
.format(
num,
num // 1 % 10,
num // 10 % 10,
num // 100 % 10,
num // 1000 % 10,
)
) | Python | zaydzuhri_stack_edu_python |
from cryptography.fernet import Fernet
function newkey
begin
set key = call generate_key
return key
end function
function encryptPass Pass key
begin
set cipher_suite = call Fernet key
comment required to be bytes
set ciphered_text = call encrypt bytes Pass string utf-8
return ciphered_text
end function
function decrypt... | from cryptography.fernet import Fernet
def newkey():
key = Fernet.generate_key()
return key
def encryptPass(Pass,key):
cipher_suite= Fernet(key)
ciphered_text=cipher_suite.encrypt(bytes(Pass,"utf-8")) #required to be bytes
return ciphered_text
def decryptPass(Pass,key):
cipher_suite= Fernet(k... | Python | zaydzuhri_stack_edu_python |
function charge self id
begin
return call Charge self id
end function | def charge(self, id):
return Charge(self, id) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python2
comment -*- coding: utf-8 -*-
import sys
import os
from gensim import utils
import shutil
string 数据预处理 filepath 需要做分类数据集路径 filename 需要做分类数据集名称 file_train_pos 需要做分类数据的训练集保存路径 file_test_pos 需要做分类数据的测试集保存路径 file_train_neg 其它类别数据的训练集保存路径 file_teat_neg 其它类别数据的测试集保存路径
comment 清空文件夹
remove tree s... | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
import sys
import os
from gensim import utils
import shutil
"""
数据预处理
filepath 需要做分类数据集路径
filename 需要做分类数据集名称
file_train_pos 需要做分类数据的训练集保存路径
file_test_pos 需要做分类数据的测试集保存路径
file_train_neg 其它类别数据的训练集保存路径
file_teat_neg 其它类别数据的... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
import unittest
import datetime
import geneticalg as genetic
class GuessPasswordTests extends TestCase
begin
set geneset = string abcdeghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!.
function test_Hello_World self
begin
set target = string Hello World!
call guess_password target
end function
... | #!/usr/bin/python3
import unittest
import datetime
import geneticalg as genetic
class GuessPasswordTests(unittest.TestCase):
geneset = " abcdeghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!."
def test_Hello_World(self):
target = "Hello World!"
self.guess_password(target)
def test_benchma... | Python | zaydzuhri_stack_edu_python |
function get_dev_examples self
begin
return call get_dialog_examples string dev
end function | def get_dev_examples(self):
return self.get_dialog_examples("dev") | Python | nomic_cornstack_python_v1 |
comment for loop in python unlike java doesn't have the init;cond;updation syntax.
comment for loop in python refers to the for in loop
comment this program prints all the odd numbers from 11 to 50
for i in range 11 50 2
begin
print i
end | #for loop in python unlike java doesn't have the init;cond;updation syntax.
#for loop in python refers to the for in loop
#this program prints all the odd numbers from 11 to 50
for i in range(11,50,2):
print(i) | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment ==============================================================================
comment \file merge-pic-feature.py
comment \author chenghuige
comment \date 2017-09-02 07:11:31.677005
comment \Description
comment ========================================================================... | #!/usr/bin/env python
# ==============================================================================
# \file merge-pic-feature.py
# \author chenghuige
# \date 2017-09-02 07:11:31.677005
# \Description
# ==============================================================================... | Python | zaydzuhri_stack_edu_python |
comment Author: Mongezi Nene
comment description: Solves equation 2
set a = input string Enter the value of a:
set a = decimal a
set b = input string Enter the value of b:
set b = decimal b
set c = input string Enter the value of c:
set c = decimal c
set d = input string Enter the value of d:
set d = decimal d
set r = ... | # Author: Mongezi Nene
# description: Solves equation 2
a = input("Enter the value of a: ")
a = float(a)
b = input("Enter the value of b: ")
b = float(b)
c = input("Enter the value of c: ")
c = float(c)
d = input("Enter the value of d: ")
d = float(d)
r = input("Enter the value of r: ")
r = float(r)
# First term
... | Python | zaydzuhri_stack_edu_python |
function fit self X_train y_train
begin
if shape at 0 != shape at 0
begin
raise AssertionError
end
set X_train = horizontal stack tuple ones tuple shape at 0 1 X_train
set rows = shape at 0
set cols = shape at 1
set _weight = call normal size=cols
for epoch in range _max_iter
begin
set data = horizontal stack tuple X_t... | def fit(self, X_train, y_train):
if X_train.shape[0] != y_train.shape[0]:
raise AssertionError
X_train = np.hstack((np.ones((X_train.shape[0], 1)), X_train))
rows = X_train.shape[0]
cols = X_train.shape[1]
self._weight = np.random.normal(size=cols)
for epoch ... | Python | nomic_cornstack_python_v1 |
if n > 17
begin
set d = d * 2
print string The difference value is: d
end
else
begin
print string The diff: d
end | if n>17:
d=d*2
print("The difference value is: ",d)
else:
print("The diff:",d) | Python | zaydzuhri_stack_edu_python |
from datetime import datetime , timedelta
set now = timestamp today
print now
comment datetime(year, month, day)
set a = call datetime 2018 11 28 - time delta days=5
print a
comment datetime(year, month, day, hour, minute, second, microsecond)
set b = call datetime 2017 11 28 23 59 59 - time delta days=5
print b
set ti... | from datetime import datetime, timedelta
now = datetime.today().timestamp()
print(now)
#datetime(year, month, day)
a = datetime(2018, 11, 28) - timedelta(days=5)
print(a)
# datetime(year, month, day, hour, minute, second, microsecond)
b = datetime(2017, 11, 28, 23, 59, 59) - timedelta(days=5)
print(b)
timestamp = (... | Python | zaydzuhri_stack_edu_python |
function _convertTZ self
begin
set tz = call get_current_timezone
set dtstart = self at string DTSTART
set dtend = self at string DTEND
if call zone == string UTC
begin
set dt = call astimezone tz
end
if call zone == string UTC
begin
set dt = call astimezone tz
end
end function | def _convertTZ(self):
tz = timezone.get_current_timezone()
dtstart = self['DTSTART']
dtend = self['DTEND']
if dtstart.zone() == "UTC":
dtstart.dt = dtstart.dt.astimezone(tz)
if dtend.zone() == "UTC":
dtend.dt = dtend.dt.astimezone(tz) | Python | nomic_cornstack_python_v1 |
comment ! python3
comment downloadXkcd.py - Downloads every single XKCD comic.
import requests , os , bs4
set url = string http://xkcd.com
comment store comic in folder xkcd, make it if it doesn't exist
make directories string xkcd exist_ok=true
while not ends with url string #
begin
comment TODO: Download the page.
pr... | #! python3
# downloadXkcd.py - Downloads every single XKCD comic.
import requests, os, bs4
url = 'http://xkcd.com'
os.makedirs('xkcd', exist_ok=True) # store comic in folder xkcd, make it if it doesn't exist
while not url.endswith('#'):
# TODO: Download the page.
print('Downloading page %s...' % url)... | Python | zaydzuhri_stack_edu_python |
import time
import multiprocessing
import random
function kuadrat
begin
for i in range 1 11 1
begin
print string Bilangan Asli--: i
sleep 1
print string Bilangan Kuadrat---: i ^ 2
sleep 1.4
end
end function
if __name__ == string __main__
begin
set wk1 = process target=kuadrat
start wk1
join wk1
end | import time
import multiprocessing
import random
def kuadrat():
for i in range (1,11,1):
print('Bilangan Asli--: ',i)
time.sleep(1)
print('Bilangan Kuadrat---: ',i**2)
time.sleep(1.4)
if __name__ == '__main__':
wk1 = multiprocessing.Process(target=kuadrat)
wk1.start();
... | Python | zaydzuhri_stack_edu_python |
function menu chave
begin
set sair = false
set opt = 0
while not sair
begin
print string
print string ------------------------------
print string ---------- CriptaGo ----------
print string ------------------------------
print string ------ 1-Criptografar --------
print string ------ 2-Descriptografar -----
print strin... | def menu(chave):
sair = False
opt = 0
while not sair:
print('\n')
print('------------------------------')
print('---------- CriptaGo ----------')
print('------------------------------')
print('------ 1-Criptografar --------')
print('------ 2-Descriptografar -... | Python | nomic_cornstack_python_v1 |
string aspoň 89% ... 100% = 1 75% ... = 2 50% ... = 3 35% ... = 4 0% ... = 5
function znamka p
begin
if p < 35
begin
return 5
end
else
if p < 50
begin
return 4
end
else
if p < 75
begin
return 3
end
else
if p < 89
begin
return 2
end
else
begin
return 1
end
end function
for i in range 0 100 5
begin
print string { i } % -... | """
aspoň 89% ... 100% = 1
75% ... = 2
50% ... = 3
35% ... = 4
0% ... = 5
"""
def znamka(p):
if p < 35 :
return 5
elif p < 50 :
return 4
elif p < 75 :
return 3
elif p < 89 :
return 2
else :
return 1
for i in range(0, 100, 5):
print(f"{i}% -> {znamka(i)... | Python | zaydzuhri_stack_edu_python |
function project_list_csv event_id event_name
begin
set headers = dict string Content-Disposition string attachment; filename= + event_name + string _projects_dribdat.csv
set csvlist = call gen_csv call request_project_list event_id
return call Response call stream_with_context csvlist mimetype=string text/csv headers=... | def project_list_csv(event_id, event_name):
headers = {
'Content-Disposition': 'attachment; filename='
+ event_name + '_projects_dribdat.csv'
}
csvlist = gen_csv(request_project_list(event_id))
return Response(stream_with_context(csvlist),
mimetype='text/csv',
... | Python | nomic_cornstack_python_v1 |
string [medium] Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8. Example: Given m... | '''
[medium]
Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).
The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.
Example:
Given ... | Python | zaydzuhri_stack_edu_python |
function contact request
begin
print POST
set form = call ContactForm POST or none
if call is_valid
begin
comment cleaning form
set form = call ContactForm
end
return call render request string new_app/form.html dict string title string Contact us ; string form form
end function | def contact(request):
print(request.POST)
form = ContactForm(request.POST or None)
if form.is_valid():
form = ContactForm() # cleaning form
return render(request, 'new_app/form.html', {'title': 'Contact us',
'form': form,
... | Python | nomic_cornstack_python_v1 |
import requests
import json
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from base64 import b64encode
class ApiClient
begin
function __init__ self type
begin
set type = type
end function
function call self image_path
begin
set ENDPOINT_URL = string https://vision.googleapis.com/v1/images:ann... | import requests
import json
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from base64 import b64encode
class ApiClient:
def __init__(self, type):
self.type = type
def call(self, image_path):
ENDPOINT_URL = 'https://vision.googleapis.com/v1/images:annotate'
a... | Python | zaydzuhri_stack_edu_python |
function filter self filters
begin
string Apply filters to the pileup elements, and return a new Pileup with the filtered elements removed. Parameters ---------- filters : list of PileupElement -> bool callables A PileupUp element is retained if all filters return True when called on it.
set new_elements = list compreh... | def filter(self, filters):
'''
Apply filters to the pileup elements, and return a new Pileup with the
filtered elements removed.
Parameters
----------
filters : list of PileupElement -> bool callables
A PileupUp element is retained if all filters return True ... | Python | jtatman_500k |
function compose im y fns
begin
for fn in fns
begin
comment pdb.set_trace()
set tuple im y = call fn im y
end
return if expression y is none then im else tuple im y
end function | def compose(im, y, fns):
for fn in fns:
#pdb.set_trace()
im, y =fn(im, y)
return im if y is None else (im, y) | Python | nomic_cornstack_python_v1 |
function _pool_to_dict self pool
begin
set pool_dict = call to_dict healthmonitor=false listener=false listeners=false loadbalancer=false l7_policies=false members=false session_persistence=false
set pool_dict at string members = list comprehension dict string id id for member in members
set pool_dict at string listene... | def _pool_to_dict(self, pool):
pool_dict = pool.to_dict(healthmonitor=False,
listener=False,
listeners=False,
loadbalancer=False,
l7_policies=False,
... | Python | nomic_cornstack_python_v1 |
class PhoneNumber
begin
function __init__ self number
begin
comment remove standard punctuation
set number = replace replace replace replace replace number string ( string string ) string string - string string . string string string
comment if number isn't 10 characters long it must be 11 characters and start with 1,... | class PhoneNumber:
def __init__(self, number):
# remove standard punctuation
number = number.replace("(", "").replace(")", "").replace("-", "").replace(".", "").replace(" ", "")
# if number isn't 10 characters long it must be 11 characters and start with 1,
# or 12 characters and sta... | Python | zaydzuhri_stack_edu_python |
function import_prestashop_order_states cls channels
begin
set SiteOrderState = get pool string prestashop.site.order_state
if length channels != 1
begin
call raise_user_error string multiple_channels
end
set channel = channels at 0
call validate_prestashop_channel
comment Set this channel to context
with call set_cont... | def import_prestashop_order_states(cls, channels):
SiteOrderState = Pool().get('prestashop.site.order_state')
if len(channels) != 1:
cls.raise_user_error('multiple_channels')
channel = channels[0]
channel.validate_prestashop_channel()
# Set this channel to context
... | Python | nomic_cornstack_python_v1 |
string Scrape eia.gov for annual average gas-prices. Returns both a float and a tuple of floats. The current year's gas prices are averaged from January to the present month. Annual averages starting from 2010 CY to last year are returned in the tuple. Typical usage example: >>> from gasoline_data import GasolineData >... | """Scrape eia.gov for annual average gas-prices.
Returns both a float and a tuple of floats. The current year's
gas prices are averaged from January to the present month. Annual averages
starting from 2010 CY to last year are returned in the tuple.
Typical usage example:
>>> from gasoline_data import Gasoli... | Python | zaydzuhri_stack_edu_python |
comment https://atcoder.jp/contests/abc215/tasks/acc215_c
from itertools import permutations
set tuple S K = split input
set K = integer K
set st = set
for x in permutations S
begin
add st x
end
set ss = sorted list st
print join string ss at K - 1
comment import sys
comment from collections import Counter
comment sys... | # https://atcoder.jp/contests/abc215/tasks/acc215_c
from itertools import permutations
S, K = input().split()
K = int(K)
st = set()
for x in permutations(S):
st.add(x)
ss = sorted(list(st))
print(''.join(ss[K-1]))
# import sys
# from collections import Counter
# sys.setrecursionlimit(10 ** 7)
# def count(s):
#... | Python | zaydzuhri_stack_edu_python |
function _find_parent api project name
begin
set cur_folder = none
for f in list comprehension x for x in split name string / if x
begin
if not cur_folder
begin
set cur_folder = list all at 0
end
else
begin
set cur_folder = list all at 0
end
end
return cur_folder
end function | def _find_parent(api, project, name):
cur_folder = None
for f in [x for x in name.split("/") if x]:
if not cur_folder:
cur_folder = list(api.files.query(project, names=[f]).all())[0]
else:
cur_folder = list(api.files.query(parent=cur_folder.id, names=[f]).all())[0]
re... | Python | nomic_cornstack_python_v1 |
function test_file
begin
set file = call StringIO string Subject ID,Description,Group,VISCODE,VISCODE2,Image ID,Acq Date,RID 101_S_1001,Average,MCI,m12,m12,100001,1/01/2001,1001 101_S_1001,Average,MCI,m24,m24,200001,1/01/2002,1001 102_S_1002,Average,AD,m12,m12,100002,2/02/2002,1002 102_S_1002,Dynamic,AD,m12,m12,200002,... | def test_file():
file = io.StringIO(
"Subject ID,Description,Group,VISCODE,VISCODE2,Image ID,Acq Date,RID\n"
"101_S_1001,Average,MCI,m12,m12,100001,1/01/2001,1001\n"
"101_S_1001,Average,MCI,m24,m24,200001,1/01/2002,1001\n"
"102_S_1002,Average,AD,m12,m12,100002,2/02/2002,1002\n"
... | Python | nomic_cornstack_python_v1 |
comment 列表推导式
set vec = list 2 4 6
set b = list comprehension 3 * x for x in vec
print b
set c = list comprehension list x x ^ 2 for x in vec
print c
set freshfruit = list string banana string loganberry string passion fruit
comment 删除前后空格
set d = list comprehension strip x for x in freshfruit
print d
print list compre... | # 列表推导式
vec = [2, 4, 6]
b = [3 * x for x in vec]
print(b)
c = [[x, x ** 2] for x in vec]
print(c)
freshfruit = [' banana', ' loganberry ', 'passion fruit ']
# 删除前后空格
d = [x.strip() for x in freshfruit]
print(d)
print([3 * x for x in vec if x > 3])
print([3 * x for x in vec if x < 2]) | Python | zaydzuhri_stack_edu_python |
comment 从控制台输入一个整数,判断是否是偶数
set num = integer input
if num % 2 == 0
begin
print string 是偶数
end
else
begin
print string 是奇数
end
string 从控制台输入一个三位数,如果是水仙花数就打印“是水仙花数”,否则打印“不是水仙花数” 153=1^3+5^3+3^3 从控制台输入一个五位数,如果是回文数就打印“是回文数”,否则打印“不是回文数” 11111 12321 12221 #不准使用max min 从控制台输入两个数,输出较大的值 从控制台输入三个数,输出较大的值 | #从控制台输入一个整数,判断是否是偶数
num = int(input())
if num % 2 == 0:
print("是偶数")
else:
print("是奇数")
'''
从控制台输入一个三位数,如果是水仙花数就打印“是水仙花数”,否则打印“不是水仙花数”
153=1^3+5^3+3^3
从控制台输入一个五位数,如果是回文数就打印“是回文数”,否则打印“不是回文数”
11111 12321 12221
#不准使用max min
从控制台输入两个数,输出较大的值
从控制台输入三个数,输出较大的值
'''
| Python | zaydzuhri_stack_edu_python |
function uninstall_rpm_remotely self rpm_filename host rpm_database=RPM_DATABASE
begin
set rpm_package_name = rpm_filename at slice : index rpm_filename string . :
call run_remote_command string rpm -e %s --dbpath %s % tuple rpm_package_name rpm_database host
call check_remote_rpm_uninstall rpm_package_name host
end ... | def uninstall_rpm_remotely(self, rpm_filename, host, rpm_database = RPM_DATABASE):
rpm_package_name = rpm_filename[:rpm_filename.index('.')]
run_remote_command("rpm -e %s --dbpath %s" % (rpm_package_name, rpm_database), host)
self.check_remote_rpm_uninstall(rpm_package_name, host) | Python | nomic_cornstack_python_v1 |
function mouse_pressed buttons mouse_pos
begin
for button in buttons
begin
if call mouse_over mouse_pos
begin
set color = tuple 0 200 200
call click
update button
end
end
end function | def mouse_pressed(buttons, mouse_pos):
for button in buttons:
if button.mouse_over(mouse_pos):
button.color = (0, 200, 200)
button.click()
button.update() | Python | nomic_cornstack_python_v1 |
function delete self
begin
set url = format string https://api.imgur.com/3/account/{0} name
return call _send_request url needs_auth=true method=string DELETE
end function | def delete(self):
url = "https://api.imgur.com/3/account/{0}".format(self.name)
return self._imgur._send_request(url, needs_auth=True, method='DELETE') | Python | nomic_cornstack_python_v1 |
import numpy as np
import pylab as pl
function black_body_Q T
begin
return 5.67 * 10 ^ - 8 * T ^ 4
end function
comment differential ring element to opposed ring element on coaxial disk
comment dF/dR =
function vf_1 r1 r2 h
begin
set R = r2 / r1
set H = h / r1
set Y = call power H 2 + call power R 2 + 1
return 2.0 * R ... | import numpy as np
import pylab as pl
def black_body_Q(T):
return 5.67 * 10**(-8) * T**4
# differential ring element to opposed ring element on coaxial disk
# dF/dR =
def vf_1(r1, r2, h):
R = r2/r1
H = h/r1
Y = np.power(H,2) + np.power(R,2) + 1
return (2. * R * np.power(H,2) * Y) / ((np.power(Y,2... | Python | zaydzuhri_stack_edu_python |
function processEnded self name
begin
comment Cancel the scheduled _forceStopProcess function if the process
comment dies naturally
if name in murder
begin
if call active
begin
call cancel
end
del murder at name
end
call stopped
del protocols at name
if call seconds - timeStarted at name < threshold
begin
comment The p... | def processEnded(self, name):
# Cancel the scheduled _forceStopProcess function if the process
# dies naturally
if name in self.murder:
if self.murder[name].active():
self.murder[name].cancel()
del self.murder[name]
self.processes[name][0].stopped... | Python | nomic_cornstack_python_v1 |
function beta_create_ServerConfig_server servicer pool=none pool_size=none default_timeout=none maximum_timeout=none
begin
set request_deserializers = dict tuple string p4.server.v1.ServerConfig string Get FromString ; tuple string p4.server.v1.ServerConfig string Set FromString
set response_serializers = dict tuple st... | def beta_create_ServerConfig_server(servicer, pool=None, pool_size=None, default_timeout=None, maximum_timeout=None):
request_deserializers = {
('p4.server.v1.ServerConfig', 'Get'): GetRequest.FromString,
('p4.server.v1.ServerConfig', 'Set'): SetRequest.FromString,
}
response_serializers = {
... | Python | nomic_cornstack_python_v1 |
function get_index self
begin
set index_file = index_file
try
begin
set file = open index_file string r
set index = integer load json file
close file
return index
end
except any
begin
print string json file index_file string empty, initializing with index = TABLE.shape[0].
set file = open index_file string w
dump _TABL... | def get_index(self) -> int:
index_file = self.index_file
try:
file = open(index_file, 'r')
index = int(json.load(file))
file.close()
return index
except:
print("json file", index_file, "empty, initializing with index = TABLE.shape[0].... | Python | nomic_cornstack_python_v1 |
comment smoothing='absolute', numsteps=40000):
function build_graph mesh evals nevals nfix step=1.0 params=call OptimizationParams
begin
set list Xori TRIV n m Ik Ih Ik_k Ih_k Tpi Txi Tni iM Windices Ael Bary = mesh
set dtype = string float32
if dtype == string float64
begin
set dtype = string float64
end
if dtype == s... | def build_graph(mesh, evals, nevals,nfix, step=1.0, params=OptimizationParams()): #smoothing='absolute', numsteps=40000):
[Xori,TRIV,n, m, Ik, Ih, Ik_k, Ih_k, Tpi, Txi, Tni, iM, Windices, Ael, Bary] = mesh
dtype='float32'
if(Xori.dtype=='float64'):
dtype='float64'
if(Xori.dt... | Python | nomic_cornstack_python_v1 |
import socket
set s = call socket AF_INET SOCK_DGRAM
call setsockopt SOL_SOCKET SO_BROADCAST 1
set host = call gethostbyname string <broadcast>
comment host = '192.168.0.255'
print string Host is: %s % host
set port = 5000
print string Port is: %s % port
comment s.connect((host, port))
comment data = s.recv(1024)
call ... | import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
host = socket.gethostbyname("<broadcast>")
#host = '192.168.0.255'
print("Host is: %s" % host)
port = 5000
print("Port is: %s" % port)
#s.connect((host, port))
#data = s.recv(1024)
s.sendto("... | Python | zaydzuhri_stack_edu_python |
from socket import *
import threading
import time
global i
set i = 0
class ThreadedServer
begin
function listenToClient self client addr
begin
global i
while true
begin
set string = encode string Welcome to Quiz
comment Send first message to client
call send string
comment Get authentication input
set authentication = ... | from socket import *
import threading
import time
global i
i = 0
class ThreadedServer():
def listenToClient(self, client, addr):
global i
while True:
string="Welcome to Quiz".encode()
client.send(string) #Send first message to client
authentication = client.rec... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function maximumProduct self nums
begin
string :type nums: List[int] :rtype: int
set list max3 max2 max1 = list - 1001 * 3
set list min2 min1 = list 1001 * 2
for num in nums
begin
if num > max3
begin
set max1 = max2
set max2 = max3
set max3 = num
end
else
if num > max2
begin
set max1 = max2
set max... | class Solution:
def maximumProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
[max3, max2, max1] = [-1001] * 3
[min2, min1] = [1001] * 2
for num in nums:
if num > max3:
max1 = max2
max2 = max3
... | Python | zaydzuhri_stack_edu_python |
string Hash which implements separate chaining.
class SequentialSearchArray extends object
begin
function __init__ self
begin
set keys = list
set values = list
end function
function __len__ self
begin
return length keys
end function
function add self key value
begin
append keys key
append values value
end function
fu... | '''
Hash which implements separate chaining.
'''
class SequentialSearchArray(object):
def __init__(self):
self.keys = []
self.values = []
def __len__(self):
return len(self.keys)
def add(self, key, value):
self.keys.append(key)
self.values.append(value)
def ... | Python | zaydzuhri_stack_edu_python |
function create self client_card
begin
set client_card_id = id_client_card
set CNP = CNP
if client_card_id in __storage
begin
raise call KeyError format string There already is a client card with the id {} client_card_id
end
for obj in __storage
begin
if CNP == CNP
begin
raise call KeyError format string There already ... | def create(self, client_card):
client_card_id = client_card.id_client_card
CNP = client_card.CNP
if client_card_id in self.__storage:
raise KeyError("There already is a client card with the id {}".format(client_card_id))
for obj in self.__storage:
if obj.CNP... | Python | nomic_cornstack_python_v1 |
function deserialize_numpy self str numpy
begin
try
begin
set end = 0
set _x = self
set start = end
set end = end + 8
set tuple classid score = call unpack str at slice start : end :
set start = end
set end = end + 4
set tuple length = call unpack str at slice start : end :
set start = end
set end = end + length
if pyt... | def deserialize_numpy(self, str, numpy):
try:
end = 0
_x = self
start = end
end += 8
(_x.classid, _x.score,) = _get_struct_If().unpack(str[start:end])
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if pyth... | Python | nomic_cornstack_python_v1 |
function __init__ __self__ type additional_columns=none disable_metrics_collection=none max_concurrent_connections=none query=none source_retry_count=none source_retry_wait=none
begin
set __self__ string type string CommonDataServiceForAppsSource
if additional_columns is not none
begin
set __self__ string additional_co... | def __init__(__self__, *,
type: str,
additional_columns: Optional[Any] = None,
disable_metrics_collection: Optional[Any] = None,
max_concurrent_connections: Optional[Any] = None,
query: Optional[Any] = None,
source_ret... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
comment graph_coloring_z3.py - Constraint programming exercice: play with the graph coloring problem
comment Copyright (C) 2012 Axel "0vercl0k" Souchet - http://www.twitter.com/0vercl0k
comment This program is free software: you can redistribute it and/or modif... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# graph_coloring_z3.py - Constraint programming exercice: play with the graph coloring problem
# Copyright (C) 2012 Axel "0vercl0k" Souchet - http://www.twitter.com/0vercl0k
#
# This program is free software: you can redistribute it and/or modify
# it under t... | Python | zaydzuhri_stack_edu_python |
function save_headpointer value
begin
with open string settings.txt string w as settings
begin
write settings format string head = {} value
print format string Headpointer was saved as {} value
end
end function | def save_headpointer(value):
with open("settings.txt", 'w') as settings:
settings.write("head = {}".format(value))
print("Headpointer was saved as {}".format(value)) | Python | nomic_cornstack_python_v1 |
import random
function generar_tablero n listaPalabras
begin
comment Sirve para el while
set contador = 0
comment Tablero
set tablero = list
comment Sirve para el random, es un string con números
set contadorRandom = string
while contador < n
begin
comment creo tablero con listas
append tablero list
comment String de... | import random
def generar_tablero(n, listaPalabras):
contador = 0 #Sirve para el while
tablero = [] #Tablero
contadorRandom = "" #Sirve para el random, es un string con números
while(contador < n):
tablero.append([]) #creo tablero con listas
contadorRandom = contadorRandom + str(contado... | Python | zaydzuhri_stack_edu_python |
function _verify_block_against_transaction_stack self transactions
begin
set remaining_txs = dictionary comprehension tx_id : tx for tx in _tx_stack
for tx in transactions
begin
if tx_id in remaining_txs
begin
del remaining_txs at tx_id
end
else
begin
call verify call get_public_key sender_id
end
end
call _reset_transa... | def _verify_block_against_transaction_stack(self, transactions):
remaining_txs = {tx.content.tx_id: tx for tx in self._tx_stack}
for tx in transactions:
if tx.content.tx_id in remaining_txs:
del remaining_txs[tx.content.tx_id]
else:
tx.verify(self.... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
comment @Time : 2018/10/24 20:19
comment @Author : chengz
comment @File : 注意点.py
comment @Software: PyCharm
string 重要警告: 默认参数的值只会被求一次值. 这使得当默认参数的值是可 变对象时会有所不同, 如列表, 字典, 或大多类的对象时。 如果你不想让参数值被后来的调用共享,就li=None,每次都判断下li是否为None 例如, 下面的函式在随后的调用中会累积参数值:
comment 每次都会重置li的值
function lts a=0 li=none
... | # -*- coding: utf-8 -*-
# @Time : 2018/10/24 20:19
# @Author : chengz
# @File : 注意点.py
# @Software: PyCharm
"""重要警告: 默认参数的值只会被求一次值. 这使得当默认参数的值是可
变对象时会有所不同, 如列表, 字典, 或大多类的对象时。
如果你不想让参数值被后来的调用共享,就li=None,每次都判断下li是否为None
例如, 下面的函式在随后的调用中会累积参数值:"""
# 每次都会重置li的值
def lts(a=0, li=None):
if li is None:
l... | Python | zaydzuhri_stack_edu_python |
function test_count self
begin
assert equal 4 call count_drugs
call assertLessEqual 23 call count_articles
end function | def test_count(self):
self.assertEqual(4, self.manager.count_drugs())
self.assertLessEqual(23, self.manager.count_articles()) | Python | nomic_cornstack_python_v1 |
function relative_distance x y
begin
return if expression x == y then 0 else absolute x - y / max x y
end function | def relative_distance(x, y):
return 0 if x == y else abs(x-y)/max(x, y) | Python | nomic_cornstack_python_v1 |
import sys
set numbers = list map int split read line stdin
function swap arr i j
begin
set temp = arr at i
set arr at i = arr at j
set arr at j = temp
end function
function bubbleSort arr
begin
for i in range length arr - 1
begin
for j in range length arr - i - 1
begin
if arr at j > arr at j + 1
begin
call swap arr j ... | import sys
numbers = list(map(int, sys.stdin.readline().split()))
def swap(arr, i, j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
def bubbleSort(arr):
for i in range(len(arr)-1):
for j in range(len(arr)-i-1):
if(arr[j] > arr[j+1]):
swap(arr, j, j+1)
return arr
newlist = bubbleSort(numbe... | Python | zaydzuhri_stack_edu_python |
comment Определение уровня проверяемого узла
function level_Node self Node
begin
set levels = 1
if Parent is none
begin
return levels
end
else
begin
return levels + call level_Node Parent
end
end function
comment Запись в соотв. поле уровня текущего узла и его детей
function level_branch self Node
begin
set Level = cal... | def level_Node(self, Node): # Определение уровня проверяемого узла
levels = 1
if Node.Parent is None:
return levels
else:
return levels + self.level_Node(Node.Parent)
def level_branch(self, Node): # Запись в соотв. поле уровня текущего узла и его детей
Node... | Python | zaydzuhri_stack_edu_python |
function windows_script
begin
with open string buildRenameX86.bat string w as script
begin
write script format string rename dist\arelle-win-x86.exe arelle-win-x86-{}.exe VERSION_STRING
end
with open string buildRenameX64.bat string w as script
begin
write script format string rename dist\arelle-win-x64.exe arelle-win-... | def windows_script():
with open("buildRenameX86.bat", "w") as script:
script.write(
"rename dist\\arelle-win-x86.exe arelle-win-x86-{}.exe\n"
.format(VERSION_STRING)
)
with open("buildRenameX64.bat", "w") as script:
script.write(
"rename dist\\arelle-w... | Python | nomic_cornstack_python_v1 |
function gradientDescent_field_large_workspace x y obs q_start q_goal DSTARGOAL ATTRACT_GAIN REPULSIVE_GAIN Q_STAR
begin
comment Tolerance
set minimaTol = 0.0001
comment max iterations
set num_iterations = 3000000
comment robot = self.robot
set tuple U points = call calc_potential_field_large_workspace q_start q_goal o... | def gradientDescent_field_large_workspace(x, y, obs, q_start, q_goal, DSTARGOAL, ATTRACT_GAIN, REPULSIVE_GAIN, Q_STAR):
# Tolerance
minimaTol = 1e-4
# max iterations
num_iterations = 3000000
# robot = self.robot
U, points = calc_potential_field_large_workspace(q_start, q_goal, obs, 0.25,\
... | Python | nomic_cornstack_python_v1 |
function mask_to_bbox mask
begin
set tuple R H W = shape
set xp = call get_array_module mask
set tuple instance_index ys xs = call nonzero mask
set bbox = zeros tuple R 4 dtype=float32
for i in range R
begin
set ys_i = ys at instance_index == i
set xs_i = xs at instance_index == i
if length ys_i == 0
begin
continue
end... | def mask_to_bbox(mask):
R, H, W = mask.shape
xp = cuda.get_array_module(mask)
instance_index, ys, xs = xp.nonzero(mask)
bbox = xp.zeros((R, 4), dtype=np.float32)
for i in range(R):
ys_i = ys[instance_index == i]
xs_i = xs[instance_index == i]
if len(ys_i) == 0:
c... | Python | nomic_cornstack_python_v1 |
import numpy as np
from scipy.stats import rice
class Rice_model
begin
function __init__ self L c strat_point=0 end_point=5 level=60
begin
comment Sample from a rice distribution using scipy.stats's random number generator
set samples = call rvs c size=L
set bins = linear space strat_point end_point level
set tuple his... | import numpy as np
from scipy.stats import rice
class Rice_model():
def __init__(self, L, c, strat_point = 0, end_point = 5, level = 60):
# Sample from a rice distribution using scipy.stats's random number generator
self.samples = rice.rvs(c, size=L)
self.bins = np.linspace(strat_point, e... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Sun Dec 13 18:11:53 2020 @author: Andres Medina
import numpy as np
from scipy.optimize import minimize
function SetMoneda num simbolo=string US$ n_decimales=2
begin
string Convierte el numero en un string en formato moneda SetMoneda(45924.457, 'RD$', 2) --> 'RD$ 45,924.46... | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 13 18:11:53 2020
@author: Andres Medina
"""
import numpy as np
from scipy.optimize import minimize
def SetMoneda(num, simbolo="US$", n_decimales=2):
"""Convierte el numero en un string en formato moneda
SetMoneda(45924.457, 'RD$', 2) --> 'RD$ 45,924.46'
... | Python | zaydzuhri_stack_edu_python |
function _query_fields self
begin
set c = call cursor
set queryString = string DESCRIBE %s % table
execute c queryString
set fields = list
for f in call fetchall
begin
if f at 0 not in _excludeFields
begin
append fields f at 0
end
end
return fields
end function | def _query_fields(self):
c = self._db.cursor()
queryString = "DESCRIBE %s" % self.table
c.execute(queryString)
fields = []
for f in c.fetchall():
if f[0] not in self._excludeFields:
fields.append(f[0])
return fields | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
import sys
import re
from collections import defaultdict
function getParents child_bag adj_bag_list visited
begin
if child_bag not in adj_bag_list
begin
add visited child_bag
return visited
end
for parent_bag in adj_bag_list at child_bag
begin
add visited parent_bag
call getParents parent_... | #!/usr/bin/env python3
import sys
import re
from collections import defaultdict
def getParents(child_bag, adj_bag_list, visited):
if child_bag not in adj_bag_list:
visited.add(child_bag)
return visited
for parent_bag in adj_bag_list[child_bag]:
visited.add(parent_bag)
... | Python | zaydzuhri_stack_edu_python |
function storage self
begin
return get pulumi self string storage
end function | def storage(self) -> Optional[pulumi.Input['TrinoTelemetryConfigArgs']]:
return pulumi.get(self, "storage") | Python | nomic_cornstack_python_v1 |
function make_create_json summary project_key type_name description assignee priority_name labels due_date
begin
set json_fields = dict string summary summary ; string project dict string key project_key ; string issuetype dict string name type_name
if description
begin
set json_fields at string description = descripti... | def make_create_json(
summary: str,
project_key: str,
type_name: str,
description: Optional[str],
assignee: Optional[str],
priority_name: Optional[str],
labels: Optional[str],
due_date: Optional[str],
) -> Any:
json_fields = {
"summary": summary,
"project": {"key": pr... | Python | nomic_cornstack_python_v1 |
function test_wait_for_page_in self
begin
comment Create test instance
set csdb1 = call CacheStateDB config_data
set csdb2 = call CacheStateDB config_data
comment Create page in channel in the first instance
set ch = call create_page_in_channel
comment Publish a message
call notify_page_in_complete ch string MY_TEST_KE... | def test_wait_for_page_in(self):
# Create test instance
csdb1 = CacheStateDB(self.config_data)
csdb2 = CacheStateDB(self.config_data)
# Create page in channel in the first instance
ch = csdb1.create_page_in_channel()
# Publish a message
csdb2.notify_page_in_comp... | Python | nomic_cornstack_python_v1 |
function query_all_db limit=false
begin
set bb_dict = call read_in_bb_file
set data_set = dict
for tuple key values in items bb_dict
begin
set data = call query_db key values limit
set data_set at key = data
end
return data_set
end function | def query_all_db(limit=False):
bb_dict = read_in_bb_file()
data_set = {}
for key, values in bb_dict.items():
data = query_db(key, values, limit)
data_set[key] = data
return data_set | Python | nomic_cornstack_python_v1 |
comment The input to the program is a line of text. Write a program that counts the number of digits in a given line.
comment Input data format
comment The input to the program is a line of text.
comment Output data format
comment The program should print the number of digits in the given line.
set string = input
set c... | # The input to the program is a line of text. Write a program that counts the number of digits in a given line.
#
# Input data format
# The input to the program is a line of text.
#
# Output data format
# The program should print the number of digits in the given line.
string = input()
count = 0
digits = '1234567890'
f... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment -*- coding: utf-8 -*-
class Solution extends object
begin
function solveSudoku self board
begin
string :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead.
string 使用方法调用栈 深搜
if call solve_sudoku board
begin
pass
end
else
begin
raise exception
... | #!/usr/bin/python
# -*- coding: utf-8 -*-
class Solution(object):
def solveSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
'''
使用方法调用栈 深搜
'''
if self.solve_sudoku(board):
... | Python | zaydzuhri_stack_edu_python |
function run_parser self code_text
begin
set stream = call TextIOWrapper call BytesIO code_text encoding=string utf8
set scanner = call MyScanner stream language
set libraries = list
while 1
begin
info string in parser, starting while
set token = read scanner
info format string in run parser, token {} token
info forma... | def run_parser(self, code_text):
stream = io.TextIOWrapper(io.BytesIO(code_text), encoding="utf8")
self.scanner = MyScanner(stream, self.language)
self.scanner.libraries = []
while 1:
logging.info("in parser, starting while")
token = self.scanner.read()
... | Python | nomic_cornstack_python_v1 |
function _run_lib_checker self args
begin
set file_dir = directory name path __file__
set checker_dir = join path file_dir string lib_checker
set cmd = list string java string -cp checker_dir string LibChecker + args
set process = popen cmd stdout=PIPE
set output = communicate process at 0
set output = right strip outp... | def _run_lib_checker(self, args):
file_dir = os.path.dirname(__file__)
checker_dir = os.path.join(file_dir, 'lib_checker')
cmd = ['java', '-cp', checker_dir, 'LibChecker'] + args
process = subprocess.Popen(cmd, stdout = subprocess.PIPE)
output = process.communicate()[0]
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.