code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function pkill procname
begin
set tuple _ pids = call run_shell_command format string adb shell ps | grep "{}" | awk '{{print $2;}}' procname
for pid in split pids string
begin
set pid = strip pid
if pid
begin
set tuple passed _ = call run_adb_shell_command format string kill {} pid
sleep 1
end
end
end function | def pkill(procname: str):
_, pids = cmd_utils.run_shell_command('adb shell ps | grep "{}" | '
'awk \'{{print $2;}}\''.
format(procname))
for pid in pids.split('\n'):
pid = pid.strip()
if pid:
passed,_ = cmd_utils.run_ad... | Python | nomic_cornstack_python_v1 |
function testSignalAbort self
begin
set session = call Session
set storage_writer = call FakeStorageWriter session
set knowledge_base = call _SetUpKnowledgeBase
set analysis_mediator = call AnalysisMediator storage_writer knowledge_base
call SignalAbort
end function | def testSignalAbort(self):
session = sessions.Session()
storage_writer = fake_writer.FakeStorageWriter(session)
knowledge_base = self._SetUpKnowledgeBase()
analysis_mediator = mediator.AnalysisMediator(
storage_writer, knowledge_base)
analysis_mediator.SignalAbort() | Python | nomic_cornstack_python_v1 |
function get_similarities_common_neighbours neighbours
begin
set p_dictionary = dict
for node_i in neighbours
begin
set prob = list
set neighbours_i = set neighbours at node_i
for node_j in neighbours at node_i
begin
set neighbours_j = set neighbours at node_j
set similarity = length intersection neighbours_i neighbo... | def get_similarities_common_neighbours(neighbours):
p_dictionary = {}
for node_i in neighbours:
prob = []
neighbours_i = set(neighbours[node_i])
for node_j in neighbours[node_i]:
neighbours_j = set(neighbours[node_j])
similarity = len(neighbours_i.intersection(nei... | Python | nomic_cornstack_python_v1 |
function lca self low_key high_key
begin
return root and call lca low_key high_key
end function | def lca(self, low_key, high_key):
return self.root and self.root.lca(low_key, high_key) | Python | nomic_cornstack_python_v1 |
function tiling n
begin
set memo = list comprehension - 1 for i in range n + 1
set memo at 0 = 0
set memo at 1 = 1
set memo at 2 = 3
set memo at 3 = 6
for i in range 4 n + 1
begin
set memo at i = memo at i - 1 + memo at i - 2 * 2 + memo at i - 3
end
return memo at n
end function
print call tiling 5
print call tiling 8
... | def tiling(n):
memo = [-1 for i in range(n+1)]
memo[0] = 0
memo[1] = 1
memo[2] = 3
memo[3] = 6
for i in range(4, n+1):
memo[i] = memo[i-1] + memo[i-2]*2 + memo[i-3]
return memo[n]
print(tiling(5))
print(tiling(8))
print(tiling(10)) | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding:utf-8 -*-
from QU_path_compression import QU_Path_Compression
from Quick_Find import Quick_Find
from Quick_Union import Quick_Union
from Weighted_QU import Weighted_QU
from Weighted_QU_Path_Compression import Weighted_QU_Path_Compression
import time
import random
class UF... | #!/usr/bin/env python
# -*- coding:utf-8 -*-
from QU_path_compression import QU_Path_Compression
from Quick_Find import Quick_Find
from Quick_Union import Quick_Union
from Weighted_QU import Weighted_QU
from Weighted_QU_Path_Compression import Weighted_QU_Path_Compression
import time
import random
class UF_time_test(... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment coding: utf-8
comment # COURSE: Master statistics and machine learning: Intuition, Math, code
comment ##### COURSE URL: udemy.com/course/statsml_x/?couponCode=202006
comment ## SECTION: Descriptive statistics
comment ### VIDEO: Inter-quartile range (IQR)
comment #### TEACHER: Mike X... | #!/usr/bin/env python
# coding: utf-8
# # COURSE: Master statistics and machine learning: Intuition, Math, code
# ##### COURSE URL: udemy.com/course/statsml_x/?couponCode=202006
# ## SECTION: Descriptive statistics
# ### VIDEO: Inter-quartile range (IQR)
# #### TEACHER: Mike X Cohen, sincxpress.com
# In[ ]:
# impo... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Wed Jan 6 15:44:47 2021 @author: deesaw
function reverse s
begin
comment Base Case
if length s <= 1
begin
return s
end
comment Recursion
print 1
return reverse s at slice 1 : : + s at 0
end function
print reverse string hello worlddddddddddddddddddddddddddddddddddddddddd... | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 6 15:44:47 2021
@author: deesaw
"""
def reverse(s):
# Base Case
if len(s) <= 1:
return s
# Recursion
print(1)
return reverse(s[1:]) + s[0]
print(reverse('hello worldddddddddddddddddddddddddddddddddddddddddd')) | Python | zaydzuhri_stack_edu_python |
function init_hidden self mini_batch_size
begin
comment BEGIN YOUR CODE HERE
set hidden = call Variable zeros 2 mini_batch_size hidden_size
if call is_available
begin
set hidden = cuda hidden
end
end function
comment END OF YOUR CODE | def init_hidden(self, mini_batch_size):
#######################################
### BEGIN YOUR CODE HERE
#######################################
self.hidden = Variable(torch.zeros(2,mini_batch_size, self.hidden_size))
if torch.cuda.is_available():
self.hidden = ... | Python | nomic_cornstack_python_v1 |
function run queue data_dir
begin
function handle_error
begin
put none
end function
set file_map = call get_file_dates data_dir
if length file_map != 1
begin
error string File map had length ' { length file_map } ' for dir: { data_dir } .
return call handle_error
end
set tuple date date_files = next iterate items file_... | def run(queue, data_dir):
def handle_error():
queue.put(None)
file_map = get_file_dates(data_dir)
if len(file_map) != 1:
logger.error(f"File map had length '{len(file_map)}' for dir: {data_dir}.")
return handle_error()
date, date_files = next(iter(file_map.items()))
erro... | Python | nomic_cornstack_python_v1 |
import pandas as pd
comment Eating, exercise habbit and their body shape
set df = call DataFrame columns=list string calory string breakfast string lunch string dinner string exercise string body_shape
set loc at 0 = list 1200 1 0 0 2 string Skinny
set loc at 1 = list 2800 1 1 1 1 string Normal
set loc at 2 = list 3500... | import pandas as pd
# Eating, exercise habbit and their body shape
df = pd.DataFrame(columns=['calory', 'breakfast', 'lunch', 'dinner', 'exercise', 'body_shape'])
df.loc[0] = [1200, 1, 0, 0, 2, 'Skinny']
df.loc[1] = [2800, 1, 1, 1, 1, 'Normal']
df.loc[2] = [3500, 2, 2, 1, 0, 'Fat']
df.loc[3] = [1400, 0, 1, 0, 3, 'Ski... | Python | zaydzuhri_stack_edu_python |
for num in nums
begin
if num == 4
begin
print string Found 4
break
end
if num == 2
begin
print string Found 2
continue
end
print num
end
for num in range 7 10
begin
for letter in string abc
begin
print num letter
end
end
set x = 0
while true
begin
if x == 5
begin
break
end
print x
set x = x + 1
end | for num in nums:
if num == 4:
print('Found 4')
break
if num == 2:
print('Found 2')
continue
print(num)
for num in range(7, 10):
for letter in 'abc':
print(num, letter)
x = 0
while True:
if x==5:
break
print(x)
x+=1 | Python | zaydzuhri_stack_edu_python |
function train network_def target_params optimizer states actions next_states rewards terminals loss_weights target_opt num_tau_samples num_tau_prime_samples num_quantile_samples cumulative_gamma double_dqn kappa tau alpha clip_value_min num_actions rng
begin
set online_params = target
function loss_fn params rng_input... | def train(network_def, target_params, optimizer, states, actions, next_states, rewards,
terminals, loss_weights, target_opt, num_tau_samples, num_tau_prime_samples,
num_quantile_samples, cumulative_gamma, double_dqn, kappa, tau,alpha,clip_value_min, num_actions,rng):
online_params = optimizer.targ... | Python | nomic_cornstack_python_v1 |
function inject_shared_files disk_image shared_dir dev
begin
set gfs = call GuestFS python_return_dict=true
call add_drive_opts disk_image
call launch
call mount dev string /
set shared_files = list
for tuple root dirs files in walk shared_dir
begin
for file_name in files
begin
append shared_files join path root file_... | def inject_shared_files(disk_image, shared_dir, dev):
gfs = guestfs.GuestFS(python_return_dict=True)
gfs.add_drive_opts(disk_image)
gfs.launch()
gfs.mount(dev, '/')
shared_files = []
for root, dirs, files in os.walk(shared_dir):
for file_name in files:
shared_files.append(os.... | Python | nomic_cornstack_python_v1 |
import re
comment ************************************************************************
comment *** VERIFY METHOD - Takes in address and returns boolean (validated) ***
comment ************************************************************************
function verify address
begin
set pattern = compile string ^[^@.0-9... | import re
# ************************************************************************
# *** VERIFY METHOD - Takes in address and returns boolean (validated) ***
# ************************************************************************
def verify(address):
pattern = re.compile(r'^[^@.0-9\"(),:;<>[\\\]\'](?!.... | Python | zaydzuhri_stack_edu_python |
function search self query k=none
begin
set query_as_list = call parse_sentence query
set tuple relevant_docs query_vec = call _relevant_docs_from_posting query_as_list
set n_relevant = length relevant_docs
set ranked_doc_ids = call rank_relevant_docs relevant_docs query_vec
return tuple n_relevant ranked_doc_ids
end f... | def search(self, query, k=None):
query_as_list = self._parser.parse_sentence(query)
relevant_docs, query_vec = self._relevant_docs_from_posting(query_as_list)
n_relevant = len(relevant_docs)
ranked_doc_ids = Ranker.rank_relevant_docs(relevant_docs, query_vec)
return n_relevant,... | Python | nomic_cornstack_python_v1 |
function foo i x=list
begin
append x append x i
return x
end function
for i in range 3
begin
set y = call foo i
print y
end
print y | def foo(i, x=[]):
x.append(x.append(i))
return x
for i in range(3):
y = foo(i)
print(y)
print(y) | Python | zaydzuhri_stack_edu_python |
comment noqa: E501
function getorder OrderId
begin
set merchant_id = split call username string _ at 0
return call find_one dict string id OrderId ; string merchant_id merchant_id dict string _id 0 ; string merchant_id 0
end function | def getorder(OrderId): # noqa: E501
merchant_id=auth.username().split('_')[0]
return db.orders.find_one({'id':OrderId,'merchant_id':merchant_id},{'_id':0,'merchant_id':0}) | Python | nomic_cornstack_python_v1 |
import cv2
import numpy as np
set img = call imread string C:\Users\Admin\Desktop\projects_vartika_saumya\cartoonification_of_image\sample images\sample 1\1.jpg
comment 1) Edges
set gray = call cvtColor img COLOR_BGR2GRAY
set gray = call medianBlur gray 5
set edges = call adaptiveThreshold gray 255 ADAPTIVE_THRESH_MEAN... | import cv2
import numpy as np
img = cv2.imread(r"C:\Users\Admin\Desktop\projects_vartika_saumya\cartoonification_of_image\sample images\sample 1\1.jpg")
# 1) Edges
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = cv2.medianBlur(gray,5)
edges = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH... | Python | zaydzuhri_stack_edu_python |
import datetime
import times
from sqlalchemy_utils import PhoneNumber , PhoneNumberType , Choice , ChoiceType
class JSONDateTimeMixin extends object
begin
string A mixin for JSONEncoders, encoding :class:`datetime.datetime` and :class:`datetime.date` objects by converting them to strings that can be parsed by all moder... | import datetime
import times
from sqlalchemy_utils import PhoneNumber, PhoneNumberType, Choice, ChoiceType
class JSONDateTimeMixin(object):
"""A mixin for JSONEncoders, encoding :class:`datetime.datetime` and
:class:`datetime.date` objects by converting them to strings that can be
parsed by all modern br... | Python | zaydzuhri_stack_edu_python |
function date_handler end
begin
set calc_date = string parse time string end string %Y-%m-%d
set shift = time delta 8
set new_date = calc_date + shift
return call date
end function | def date_handler(end):
calc_date = datetime.strptime(str(end), "%Y-%m-%d")
shift = timedelta(8)
new_date = calc_date + shift
return new_date.date() | Python | nomic_cornstack_python_v1 |
from nltk.parse.malt import MaltParser
from PersianPOSTagger import *
from nltk.data import ZipFilePathPointer
from hazm.PersianTokenizer import *
from hazm.PersianTextNormalizer import *
import os
class PersianDependencyParser extends MaltParser
begin
function __init__ self tagger=none mco=none working_dir=string data... | from nltk.parse.malt import MaltParser
from PersianPOSTagger import *
from nltk.data import ZipFilePathPointer
from hazm.PersianTokenizer import *
from hazm.PersianTextNormalizer import *
import os
class PersianDependencyParser(MaltParser):
def __init__(self, tagger=None, mco=None, working_dir="data/parse", path_to_... | Python | zaydzuhri_stack_edu_python |
function define_nav_elements self
begin
return list call TabTip app=app call TabIris app=app call InstructionsTab app=app
end function | def define_nav_elements(self):
return [
TabTip(app=self.app),
TabIris(app=self.app),
InstructionsTab(app=self.app),
] | Python | nomic_cornstack_python_v1 |
class Bank
begin
function __init__ self accno name balance bankname
begin
set accno = accno
set name = name
set balance = balance
set bankname = bankname
end function
function withdraw self amount
begin
if balance < amount
begin
print string Insufficient Balance
end
else
begin
set balance = balance - amount
print strin... | class Bank:
def __init__(self,accno,name,balance,bankname):
self.accno=accno
self.name=name
self.balance=balance
self.bankname=bankname
def withdraw(self,amount):
if(self.balance<amount):
print("Insufficient Balance")
else:
self.balance-=am... | Python | zaydzuhri_stack_edu_python |
import csv
from bs4 import BeautifulSoup
import requests
from DataCollection.User import User
from datetime import datetime
set __author__ = string lizzybradley
class AddAfDStats
begin
set user_list = list
function __init__ self filename
begin
with open filename as csvfile
begin
set reader = dict reader csvfile
for ro... | import csv
from bs4 import BeautifulSoup
import requests
from DataCollection.User import User
from datetime import datetime
__author__ = 'lizzybradley'
class AddAfDStats:
user_list = []
def __init__(self, filename):
with open(filename) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
se... | Python | zaydzuhri_stack_edu_python |
class home
begin
function __init__ self
begin
comment 家的大小
set area = 180
comment 家具的列表
set furniture = list
comment 家里的光照亮度
set lighting = string off
end function
function __str__ self
begin
set msg = string 这是我的家 + string + string 家里有
for temp in furniture
begin
set msg = msg + temp + string ,
end
set msg = strip m... | class home:
def __init__(self):
self.area = 180 #家的大小
self.furniture = [] #家具的列表
self.lighting = 'off' #家里的光照亮度
def __str__(self):
msg = '这是我的家'+'\n'+'家里有'
for temp in self.furniture:
msg = msg + temp +','
msg=msg.strip(',')
msg+=... | Python | zaydzuhri_stack_edu_python |
comment loop to print data for every month
while new_balance > 0
begin
set new_balance = balance
set minMonthlyPayment = minMonthlyPayment + 10
set month = 1
while month <= 12 and new_balance > 0
begin
comment compute the balance after payment
set new_balance = new_balance - minMonthlyPayment
comment compute monthly in... | # loop to print data for every month
while (new_balance > 0):
new_balance = balance
minMonthlyPayment += 10
month = 1
while (month <= 12 and new_balance > 0):
# compute the balance after payment
new_balance -= minMonthlyPayment
# compute monthly interest rate
... | Python | zaydzuhri_stack_edu_python |
import sys
set file = open argv at 1 string r
set text = read lines file
close file
set pairs = dict
for line in text
begin
set position = split line string v at 0
set velocity = split line string v at 1
set position = position at slice 10 : - 2 :
set tuple positionX positionY = split position string ,
set velocity =... | import sys
file = open(sys.argv[1],'r')
text = file.readlines()
file.close()
pairs = {}
for line in text:
position = line.split("v")[0]
velocity = line.split("v")[1]
position = position[10:-2]
positionX, positionY = position.split(",")
velocity = velocity[9:-2]
velocityX, velocityY = velocity.split(",")
p... | Python | zaydzuhri_stack_edu_python |
function easts self
begin
return call get_property_infos string best_east
end function | def easts(self):
return self.get_property_infos('best_east') | Python | nomic_cornstack_python_v1 |
function main
begin
set feet = decimal input string enter # of feet:
set inches = call feet_to_inches feet
print format string {} feet are equal to {} inches feet inches
end function
function feet_to_inches f
begin
set inches = f * 12
return inches
end function
call main | def main():
feet = float(input("enter # of feet: "))
inches = feet_to_inches(feet)
print("{} feet are equal to {} inches".format(feet,inches))
def feet_to_inches(f):
inches = f * 12
return inches
main()
| Python | zaydzuhri_stack_edu_python |
function surfpt self u v
begin
comment Check all parameters are set before the surface evaluation
call _check_variables
comment Check u and v parameters are correct
call check_uv u v
comment Evaluate the surface
set spt = call evaluate_single knot_u=u knot_v=v degree_u=degree_u degree_v=degree_v knotvector_u=knotvector... | def surfpt(self, u, v):
# Check all parameters are set before the surface evaluation
self._check_variables()
# Check u and v parameters are correct
utilities.check_uv(u, v)
# Evaluate the surface
spt = self._evaluator.evaluate_single(knot_u=u, knot_v=v,
... | Python | nomic_cornstack_python_v1 |
function panes_for_command self command
begin
for tuple i c in call iteritems
begin
if c == command
begin
yield panes at i
end
end
end function | def panes_for_command(self, command):
for i, c in self.pane_map.iteritems():
if c == command:
yield self.panes[i] | Python | nomic_cornstack_python_v1 |
comment 导入
import pymysql
comment 连接数据库
set con = call connect host=string localhost user=string 3118004702 password=string 990225Zhxb. database=string py_database
comment 创建游标
set cur = call cursor
comment sql语句
set sql = string delete from t_student where sname = %s
comment 执行sql语句
try
begin
execute cur sql tuple str... | # 导入
import pymysql
# 连接数据库
con = pymysql.connect(host="localhost",user="3118004702",password="990225Zhxb.",database="py_database")
# 创建游标
cur = con.cursor()
# sql语句
sql = "delete from t_student where sname = %s"
# 执行sql语句
try:
cur.execute(sql,("张三丰",))
con.commit()
print("删除成功")
# 执行失败
except Exception... | Python | zaydzuhri_stack_edu_python |
function visit_dotted_filter self _ children
begin
return children at 1
end function | def visit_dotted_filter(self, _, children):
return children[1] | Python | nomic_cornstack_python_v1 |
comment Problem statement - https://leetcode.com/problems/maximum-sum-circular-subarray/
string Complexity analysis: 1) Time complexity: 2) Space complexity:
string Analysis and Tricks:
class Solution
begin
function maxSubarraySumCircular self A
begin
set tuple total maxSum curMax minSum curMin = tuple 0 - decimal stri... | # Problem statement - https://leetcode.com/problems/maximum-sum-circular-subarray/
"""
Complexity analysis:
1) Time complexity:
2) Space complexity:
"""
"""
Analysis and Tricks:
"""
class Solution:
def maxSubarraySumCircular(self, A) -> int:
total, maxSum, curMax, minSum, curMin = 0, -float('inf')... | Python | zaydzuhri_stack_edu_python |
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import numpy as np
import pandas as pd
import light_sense as ls
import utils as u
from datetime import datetime , timedelta
set TOTAL_TIME = 1440
comment load data
comment add features
class NoModel extends Exception
begin
pass
end... | import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import numpy as np
import pandas as pd
import light_sense as ls
import utils as u
from datetime import datetime, timedelta
TOTAL_TIME = 1440
##load data
##add features
class NoModel(Exception):
pass
def batch_complete_data(... | Python | zaydzuhri_stack_edu_python |
function test_less_or_equal_to_zero self
begin
set tuple course_run user = call create_purchasable_course_run
set price_obj = get courseprice_set is_valid=true
for invalid_price in tuple 0 - 1.23
begin
set price = invalid_price
save
with patch string ecommerce.api.get_purchasable_course_run autospec=true return_value=c... | def test_less_or_equal_to_zero(self):
course_run, user = create_purchasable_course_run()
price_obj = course_run.courseprice_set.get(is_valid=True)
for invalid_price in (0, -1.23,):
price_obj.price = invalid_price
price_obj.save()
with patch('ecommerce.api.ge... | Python | nomic_cornstack_python_v1 |
function cublasDtpsv handle uplo trans diag n AP x incx
begin
string Solve real triangular-packed system with one right-hand side.
set status = call cublasDtpsv_v2 handle _CUBLAS_FILL_MODE at uplo _CUBLAS_OP at trans _CUBLAS_DIAG at diag n integer AP integer x incx
call cublasCheckStatus status
end function | def cublasDtpsv(handle, uplo, trans, diag, n, AP, x, incx):
"""
Solve real triangular-packed system with one right-hand side.
"""
status = _libcublas.cublasDtpsv_v2(handle,
_CUBLAS_FILL_MODE[uplo],
_CUBLAS_OP[trans],
... | Python | jtatman_500k |
comment !/usr/bin/env python
import pprint
from asciimatics.screen import Screen
import time
import pdb
set input_file = string input.txt
comment v : facing down
comment ^ : facing up
comment > : move right
comment < : move left
class cart
begin
function __init__ self x y d id=none
begin
set x = x
set y = y
set d = d
s... | #!/usr/bin/env python
import pprint
from asciimatics.screen import Screen
import time
import pdb
input_file = "input.txt"
# v : facing down
# ^ : facing up
# > : move right
# < : move left
class cart:
def __init__(self, x,y,d, id=None):
self.x = x
self.y = y
self.d = d
self.id =... | Python | zaydzuhri_stack_edu_python |
function get_material_features self
begin
return material_features
end function | def get_material_features(self):
return self.material_features | Python | nomic_cornstack_python_v1 |
function Translate data _to_lang _from_lang
begin
set translator = call Translator to_lang=_to_lang from_lang=_from_lang
set translation = call translate data
return translation
end function | def Translate(data, _to_lang, _from_lang):
translator = Translator(to_lang=_to_lang, from_lang=_from_lang)
translation = translator.translate(data)
return translation | Python | nomic_cornstack_python_v1 |
comment Using CLASS
class Fibonacci
begin
function __init__ self N
begin
set __N = N
set __index = 0
set __F1 = 1
set __F2 = 1
end function
comment Obligatorio (Se ejecuta una sola vez)
function __iter__ self
begin
return self
end function
comment Obligatorio (Se ejecuta en cada iteración)
function __next__ self
begin
... | # Using CLASS
class Fibonacci:
def __init__(self, N):
self.__N = N
self.__index = 0
self.__F1 = self.__F2 = 1
# Obligatorio (Se ejecuta una sola vez)
def __iter__(self):
return self
# Obligatorio (Se ejecuta en cada iteración)
def __next__(self):
self.__inde... | Python | zaydzuhri_stack_edu_python |
function initContext self c
begin
add listeners ID
end function | def initContext(self, c):
self.listeners.add(c.ID) | Python | nomic_cornstack_python_v1 |
import json
function lambda_handler event context
begin
comment Get the operation and operands from the event
set operation = event at string operation
set operands = event at string operands
end function
comment Perform the operation | import json
def lambda_handler(event, context):
# Get the operation and operands from the event
operation = event['operation']
operands = event['operands']
# Perform the operation | Python | flytech_python_25k |
string Write a program that takes a number n and checks if the number is an odd multiple of 3. Example n = 24 Not odd multiple of 3. n = 21 Odd multiple of 3
set n = integer input string Enter your number: -
if n % 3 == 0 and n % 2 != 0
begin
print string This is the odd multiple of 3 n
end
else
begin
print string This... | '''Write a program that takes a number n and checks if the number is an odd multiple of 3.
Example
n = 24
Not odd multiple of 3.
n = 21
Odd multiple of 3
'''
n = int(input("Enter your number: - "))
if n%3==0 and n%2!=0:
print("This is the odd multiple of 3 ",n)
else:
print("This is not the od... | Python | zaydzuhri_stack_edu_python |
comment Extracting data from Archive API
import os
import argparse
import requests
import os
import json
import datetime
comment Function to ensure if a directory exists in the path or not;if not create one
function ensure_dir file_path directory_name
begin
if not exists path file_path + string / + directory_name
begin... | #Extracting data from Archive API
import os
import argparse
import requests
import os
import json
import datetime
#Function to ensure if a directory exists in the path or not;if not create one
def ensure_dir(file_path,directory_name):
if not os.path.exists(file_path+"/"+directory_name):
os.mkdir(file_path... | Python | zaydzuhri_stack_edu_python |
comment identity operator : is
set x = list 1 2 3
set y = list 1 2 3
set z = list 1 2 3
string print(x==y) print(x==z) print(x is y) # x ile y aynı adreste mi diye sorgular print(x is z)
comment membership operator : in
set x = list string apple string banana
comment dizisinin içinde banana bilgisi var mı ?
print strin... | #identity operator : is
x=y=[1,2,3]
z=[1,2,3]
'''
print(x==y)
print(x==z)
print(x is y) # x ile y aynı adreste mi diye sorgular
print(x is z)
'''
# membership operator : in
x=['apple', 'banana']
print('banana' in x) #dizisinin içinde banana bilgisi var mı ? | Python | zaydzuhri_stack_edu_python |
function countries_display countries
begin
return list comprehension dict string display_name v ; string value k for tuple k v in countries
end function | def countries_display(countries):
return [{"display_name": v, "value": k} for (k, v) in countries] | Python | nomic_cornstack_python_v1 |
function nmf_space_transitions self phenotype_transitions=string all data_type=string splicing n=20
begin
if phenotype_transitions == string all
begin
set phenotype_transitions = phenotype_transitions
end
if data_type == string splicing
begin
return call nmf_space_transitions sample_id_to_phenotype phenotype_transition... | def nmf_space_transitions(self, phenotype_transitions='all',
data_type='splicing', n=20):
if phenotype_transitions == 'all':
phenotype_transitions = self.phenotype_transitions
if data_type == 'splicing':
return self.splicing.nmf_space_transitions(
... | Python | nomic_cornstack_python_v1 |
function _search self
begin
call _build_query
if DO_CACHING
begin
set html = call get_cached _SEARCH_PARAMS
set SEARCH_RESULTS at string cache_file = join path CACHEDIR call cached_file_name _SEARCH_PARAMS
end
else
begin
set html = false
end
if not html
begin
try
begin
set r = get requests _SEARCH_URL headers=_HEADERS ... | def _search(self):
self._build_query()
if DO_CACHING:
html = get_cached(self._SEARCH_PARAMS)
self.SEARCH_RESULTS['cache_file'] = os.path.join(CACHEDIR, cached_file_name(self._SEARCH_PARAMS))
else:
html = False
if not html:
try:
... | Python | nomic_cornstack_python_v1 |
function PrintPostDeployHints new_versions
begin
if not new_versions
begin
return
end
else
if length new_versions > 1
begin
set service_hint = string -s <service>
end
else
if service == string default
begin
set service_hint = string
end
else
begin
set service = service
set service_hint = format string -s {svc} svc=ser... | def PrintPostDeployHints(new_versions):
if not new_versions:
return
elif len(new_versions) > 1:
service_hint = ' -s <service>'
elif new_versions[0].service == 'default':
service_hint = ''
else:
service = new_versions[0].service
service_hint = ' -s {svc}'.format(svc=service)
log.status.Prin... | Python | nomic_cornstack_python_v1 |
function get_parameters fn handle weight_buf
begin
set cudnn_methods = list cudnnGetRNNLinLayerMatrixParams cudnnGetRNNLinLayerBiasParams
set params = list
set num_linear_layers = call _num_linear_layers fn
set num_layers = num_directions * num_layers
for layer in range num_layers
begin
set layer_params = list
for cu... | def get_parameters(fn, handle, weight_buf):
cudnn_methods = [
cudnn.lib.cudnnGetRNNLinLayerMatrixParams,
cudnn.lib.cudnnGetRNNLinLayerBiasParams
]
params = []
num_linear_layers = _num_linear_layers(fn)
num_layers = fn.num_directions * fn.num_layers
for layer in range(num_layers... | Python | nomic_cornstack_python_v1 |
function lcm x y
begin
if x <= 0 or y <= 0
begin
return - 1
end
if x > y
begin
set greater_number = x
end
else
begin
set greater_number = y
end
while true
begin
if greater_number % x == 0 and greater_number % y == 0
begin
set lcm = greater_number
break
end
set greater_number = greater_number + 1
end
return lcm
end func... | def lcm(x, y):
if x <= 0 or y <= 0:
return -1
if x > y:
greater_number = x
else:
greater_number = y
while True:
if (greater_number % x == 0) and (greater_number % y == 0):
lcm = greater_number
break
greater_number += 1
return lcm | Python | nomic_cornstack_python_v1 |
import torch
from torch.utils.data import DataLoader
from metrics import get_metrics , VALUE_KEY , MODE_KEY
function create config
begin
return call Evaluator keyword config
end function
class Evaluator
begin
string Basic evaluator class Args: model (nn.Module, CallableWrapper): The model to be evaluated. dataset (Data... | import torch
from torch.utils.data import DataLoader
from ..metrics import get_metrics, VALUE_KEY, MODE_KEY
def create(config):
return Evaluator(**config)
class Evaluator:
"""Basic evaluator class
Args:
model (nn.Module, CallableWrapper): The model to be evaluated.
dataset (Dataset, Da... | Python | zaydzuhri_stack_edu_python |
from selenium import webdriver
set query = input string 입력 :
set driver = call Chrome string chromedriver.exe
get driver string https://www.naver.com/
call implicitly_wait 3
set xpath = string //*[@id="query"]
call send_keys query
set button_xpath = string //*[@id="search_btn"]
call click
set html = page_source
close d... | from selenium import webdriver
query = input("입력 : ")
driver = webdriver.Chrome("chromedriver.exe")
driver.get("https://www.naver.com/")
driver.implicitly_wait(3)
xpath = '//*[@id="query"]'
driver.find_element_by_xpath(xpath).send_keys(query)
button_xpath = '//*[@id="search_btn"]'
driver.find_element_by_xpath(butt... | Python | zaydzuhri_stack_edu_python |
function test_custom_examinator testdir monkeypatch
begin
for examinator in EXAMINATORS
begin
call delenv examinator raising=false
end
call setenv string GOVERNMENT_TEST_TOOL string 1
call makeini string [pytest] vw_examinators = GOVERNMENT_TEST_TOOL SOME_OTHER_CI
call makepyfile string def test_environmental_impact_co... | def test_custom_examinator(testdir, monkeypatch):
for examinator in pytest_vw.EXAMINATORS:
monkeypatch.delenv(examinator, raising=False)
monkeypatch.setenv('GOVERNMENT_TEST_TOOL', '1')
testdir.makeini("""
[pytest]
vw_examinators =
GOVERNMENT_TEST_TOOL
SOME_OTH... | Python | nomic_cornstack_python_v1 |
function info self
begin
return nfo
end function | def info(self):
return self.nfo | Python | nomic_cornstack_python_v1 |
import validictory
from common_validation import VALIDATION_MAP
class SubmissionEntity
begin
function __init__ self
begin
set __submission_id = none
set __hackathon_group_id = none
set __score = none
end function
decorator property
function submission_id self
begin
return __submission_id
end function
decorator setter
f... | import validictory
from common_validation import VALIDATION_MAP
class SubmissionEntity:
def __init__(self):
self.__submission_id = None
self.__hackathon_group_id = None
self.__score = None
@property
def submission_id(self):
return self.__submission_id
@submission_id.... | Python | zaydzuhri_stack_edu_python |
function send_chat_action self peer action on_success=none
begin
string Send status to peer. :param peer: Peer to send status to. :param action: Type of action to send to peer. :param on_success: Callback to call when call is complete.
run
end function | def send_chat_action(self, peer: Peer, action: botapi.ChatAction, on_success: callable=None):
"""
Send status to peer.
:param peer: Peer to send status to.
:param action: Type of action to send to peer.
:param on_success: Callback to call when call is complete.
"""
... | Python | jtatman_500k |
from scrapydemo.items import ScrapydemoItem
from scrapydemo.utils.datetime_helper import DatetimeHelper
class ItemHelper
begin
set _datetime_helper = call DatetimeHelper
function build_question self title create_time author from_url content domain
begin
set item = call ScrapydemoItem
set item at string title = call _en... | from scrapydemo.items import ScrapydemoItem
from scrapydemo.utils.datetime_helper import DatetimeHelper
class ItemHelper():
_datetime_helper = DatetimeHelper()
def build_question(self, title, create_time, author, from_url, content, domain):
item = ScrapydemoItem()
item['title'] = self._encode... | Python | zaydzuhri_stack_edu_python |
function create_inventory self
begin
call create_device_connection_object
call create_device_object
end function | def create_inventory(self):
self.create_device_connection_object()
self.create_device_object() | Python | nomic_cornstack_python_v1 |
function testGetNormalizedTimestamp self
begin
set fake_time_object = call FakeTime
call CopyFromDateTimeString string 2010-08-12 21:06:31.546875
set normalized_timestamp = call _GetNormalizedTimestamp
assert equal normalized_timestamp call Decimal string 1281647191.546875
set fake_time_object = call FakeTime
call Copy... | def testGetNormalizedTimestamp(self):
fake_time_object = fake_time.FakeTime()
fake_time_object.CopyFromDateTimeString('2010-08-12 21:06:31.546875')
normalized_timestamp = fake_time_object._GetNormalizedTimestamp()
self.assertEqual(normalized_timestamp, decimal.Decimal('1281647191.546875'))
fake_ti... | Python | nomic_cornstack_python_v1 |
function EvaluateFunction self p_float=Ellipsis p_float=Ellipsis p_float=Ellipsis
begin
Ellipsis
end function | def EvaluateFunction(self, p_float=..., p_float=..., p_float=...):
... | Python | nomic_cornstack_python_v1 |
function plot_roc roc_data savepath=string roc.png names=list
begin
from pylab import rcParams
set rcParams at string figure.figsize = tuple 4 4
for tuple i item in enumerate roc_data
begin
set tuple fpr tpr = item
set name = if expression length names > i then names at i else string Model%d % i
plot fpr tpr label=stri... | def plot_roc(roc_data, savepath='roc.png', names=[]):
from pylab import rcParams
rcParams['figure.figsize'] = 4, 4
for i, item in enumerate(roc_data):
fpr, tpr = item
name = names[i] if len(names) > i else "Model%d" % i
plt.plot(fpr, tpr, label='%s (area = %0.2f)' %
... | Python | nomic_cornstack_python_v1 |
function get_omega self df_irregular
begin
comment collect RVdense estimates
set tuple RVdenses Ns = call RV_dense df_irregular at list string logprice
set omega2hat_i = RVdenses / 2 * Ns
set omega2hat = mean np omega2hat_i
return omega2hat
end function | def get_omega(self,df_irregular):
# collect RVdense estimates
RVdenses,Ns = self.RV_dense(df_irregular[['logprice']])
omega2hat_i = RVdenses / (2*Ns)
omega2hat = np.mean(omega2hat_i)
return omega2hat | Python | nomic_cornstack_python_v1 |
function _update_model_params self params model_ID model param_grid
begin
set params = copy params
set param_grid = copy param_grid
set params_transform = dict
for key in keys params
begin
if string log10. in key
begin
set log10_transform = true
end
else
begin
set log10_transform = false
end
set key = replace key stri... | def _update_model_params(self, params, model_ID, model, param_grid):
params = params.copy()
param_grid = param_grid.copy()
params_transform = {}
for key in params.keys():
if 'log10.' in key:
log10_transform = True
... | Python | nomic_cornstack_python_v1 |
function convert_to_shell_response request response
begin
comment If the response is HTML and isn't the login view then return a "render HTML
comment response that wraps the response in an iframe on the frontend
comment FIXME: Find a proper mime type parser
set is_html = starts with get response string Content-Type str... | def convert_to_shell_response(request, response):
# If the response is HTML and isn't the login view then return a "render HTML
# response that wraps the response in an iframe on the frontend
# FIXME: Find a proper mime type parser
is_html = response.get('Content-Type').startswith('text/html')
if i... | Python | nomic_cornstack_python_v1 |
comment Import a library of functions called 'pygame'
import pygame
from math import pi
import math
comment Our logic code is here
set level = 2
set Fheight = 650
set Fwidth = 650
set vsplits = 2 ^ level + 1
set vwidth = Fheight / vsplits
set vy = list
set vx = list
append vy vwidth
comment our x coordinate center fo... | # Import a library of functions called 'pygame'
import pygame
from math import pi
import math
# Our logic code is here
level=2
Fheight=Fwidth=650
vsplits=2**(level+1)
vwidth=Fheight/vsplits
vy=[]
vx=[]
vy.append(vwidth)
#our x coordinate center for all diagrams will be 300
vx.append(Fwidth/2)
for i in range(0,(vspl... | Python | zaydzuhri_stack_edu_python |
function load_codebook self filename
begin
string Load the codebook from a file to the Somoclu object. :param filename: The name of the file. :type filename: str.
set codebook = call loadtxt filename comments=string %
if n_dim == 0
begin
set n_dim = shape at 1
end
if shape != tuple _n_rows * _n_columns n_dim
begin
rais... | def load_codebook(self, filename):
"""Load the codebook from a file to the Somoclu object.
:param filename: The name of the file.
:type filename: str.
"""
self.codebook = np.loadtxt(filename, comments='%')
if self.n_dim == 0:
self.n_dim = self.codebook.shape[... | Python | jtatman_500k |
function photo_links self photo_links
begin
set _photo_links = photo_links
end function | def photo_links(self, photo_links):
self._photo_links = photo_links | Python | nomic_cornstack_python_v1 |
comment Link - https://www.hackerrank.com/challenges/the-power-sum/problem
comment !/bin/python3
import math
import os
import random
import re
import sys
set X = integer input
set N = integer input
function rec X N start
begin
set count = 0
for i in range start X
begin
set ans = X - i ^ N
if ans == 0
begin
set count = ... | # Link - https://www.hackerrank.com/challenges/the-power-sum/problem
#!/bin/python3
import math
import os
import random
import re
import sys
X = int(input())
N = int(input())
def rec(X,N,start):
count = 0
for i in range(start,X):
ans = X-i**N
if ans == 0:
count +=... | Python | zaydzuhri_stack_edu_python |
function do_create self line
begin
if not call valid_line line
begin
return
end
try
begin
set class_to_intance = eval line
if is subclass class_to_intance BaseModel
begin
set instance = call class_to_intance
call new instance
save
print id
end
else
begin
raise NameError
end
end
except NameError
begin
print string ** cl... | def do_create(self, line):
if not valid_line(line):
return
try:
class_to_intance = eval(line)
if issubclass(class_to_intance, BaseModel):
instance = class_to_intance()
storage.new(instance)
storage.save()
... | Python | nomic_cornstack_python_v1 |
function __init__ self *args
begin
set this = call new_IdList *args
try
begin
append this this
end
except any
begin
set this = this
end
end function | def __init__(self, *args):
this = _libsbml.new_IdList(*args)
try: self.this.append(this)
except: self.this = this | Python | nomic_cornstack_python_v1 |
function close_fd self i
begin
return call russ_cconn_close_fd _ptr i
end function | def close_fd(self, i):
return libruss.russ_cconn_close_fd(self._ptr, i) | Python | nomic_cornstack_python_v1 |
function beta_create_DoctorService_stub channel host=none metadata_transformer=none pool=none pool_size=none
begin
set request_serializers = dict tuple string hospital.DoctorService string createPatient SerializeToString ; tuple string hospital.DoctorService string findExaminations SerializeToString ; tuple string hosp... | def beta_create_DoctorService_stub(channel, host=None, metadata_transformer=None, pool=None, pool_size=None):
request_serializers = {
('hospital.DoctorService', 'createPatient'): Patient.SerializeToString,
('hospital.DoctorService', 'findExaminations'): PatientPESEL.SerializeToString,
('hospital.D... | Python | nomic_cornstack_python_v1 |
comment Enter your code here. Read input from STDIN. Print output to STDOUT
import fileinput
import sys
function getFileInformation
begin
set all_lines = input
set list_of_lines = list
for line in all_lines
begin
if line == string
begin
continue
end
set line = line at slice : - 1 :
append list_of_lines line
end
ret... | # Enter your code here. Read input from STDIN. Print output to STDOUT
import fileinput
import sys
def getFileInformation():
all_lines = fileinput.input()
list_of_lines = []
for line in all_lines:
if(line == '\n'):
continue
line = line[:-1]
list_of_lines.append(line)
... | Python | zaydzuhri_stack_edu_python |
comment Definition for a binary tree node.
import heapq
import unittest
comment Read about enumerate in python
from collections import defaultdict
from typing import List , Tuple
class EvaluateDivision extends TestCase
begin
function calcEquation self equations values queries
begin
comment TODO: Type hint for dictionar... | # Definition for a binary tree node.
import heapq
import unittest
# Read about enumerate in python
from collections import defaultdict
from typing import List, Tuple
class EvaluateDivision(unittest.TestCase):
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> Lis... | Python | zaydzuhri_stack_edu_python |
function signal self nu=list 148.0 fwhm_arcmin=none output_units=string uK_RJ **kwargs
begin
try
begin
set nnu = length nu
end
except TypeError
begin
set nnu = 1
set nu = array list nu
end
try
begin
set output_map = output_map
end
except AttributeError
begin
if fwhm_arcmin is none
begin
set alm = alm
end
else
begin
set... | def signal(self, nu=[148.], fwhm_arcmin=None, output_units="uK_RJ", **kwargs):
try:
nnu = len(nu)
except TypeError:
nnu = 1
nu = np.array([nu])
try:
output_map = self.output_map
except AttributeError:
if fwhm_arcmin is None:
... | Python | nomic_cornstack_python_v1 |
function _convert_display_size size
begin
set unit_gigabyte = 1024 * 1024 * 1024.0
set unit_megabyte = 1024 * 1024.0
set unit_kilobyte = 1024.0
if size > unit_gigabyte
begin
return format string {:.2f} GB size / unit_gigabyte
end
else
if size > unit_megabyte
begin
return format string {:.2f} MB size / unit_megabyte
end... | def _convert_display_size(size):
unit_gigabyte = 1024 * 1024 * 1024.0
unit_megabyte = 1024 * 1024.0
unit_kilobyte = 1024.0
if size > unit_gigabyte:
return "{:.2f} GB".format(
size / unit_gigabyte)
elif size > unit_megabyte:
return "{:.2f} MB".format(
size / u... | Python | nomic_cornstack_python_v1 |
if player_1 == string rock and player_2 == string scissors
begin
print string Player 1 wins!
end
else
if player_1 == string rock and player_2 == string paper
begin
print string Player 2 wins!
end
else
if player_1 == string rock and player_2 == string rock
begin
print string Tie! Shoot again!
end
else
if player_1 == str... | if player_1 == 'rock' and player_2 == 'scissors':
print('Player 1 wins!')
elif player_1 == 'rock' and player_2 == 'paper':
print('Player 2 wins!')
elif player_1 == 'rock' and player_2 == 'rock':
print('Tie! Shoot again!')
elif player_1 == 'paper' and player_2 == 'scissors':
print('Player... | Python | zaydzuhri_stack_edu_python |
function fit_data self data
begin
set d = log - log data
return dot d T
end function | def fit_data(self, data):
d = log(-log(data))
return dot(d, self._fit_matrix.T) | Python | nomic_cornstack_python_v1 |
from itertools import combinations
with open string day1_input.txt string r encoding=string utf-8 as expenses
begin
set numbers = read lines expenses
end
set numbers = set generator expression integer strip number string for number in numbers
function generator1 value
begin
set combi = call combinations value 3
yield f... | from itertools import combinations
with open('day1_input.txt', 'r', encoding='utf-8') as expenses:
numbers = expenses.readlines()
numbers = set(int(number.strip('\n')) for number in numbers)
def generator1(value):
combi = combinations(value, 3)
yield from combi
gen1 = generator1(numbers)
while True:
... | Python | zaydzuhri_stack_edu_python |
function result self
begin
string The result from realising the future If the result is not available, block until done. :return: result of the future :raises: any exception encountered during realising the future
if _result is none
begin
call await_result
end
set tuple chunks exception = _result
if exception is none
b... | def result(self):
"""
The result from realising the future
If the result is not available, block until done.
:return: result of the future
:raises: any exception encountered during realising the future
"""
if self._result is None:
self.await_result()... | Python | jtatman_500k |
for x in range 0 length num
begin
print x
end | for x in range(0,len(num)):
print(x) | Python | zaydzuhri_stack_edu_python |
function __init__ __self__ max_surge=none max_unavailable=none
begin
if max_surge is not none
begin
set __self__ string max_surge max_surge
end
if max_unavailable is not none
begin
set __self__ string max_unavailable max_unavailable
end
end function | def __init__(__self__, *,
max_surge: Optional[pulumi.Input[Union[int, str]]] = None,
max_unavailable: Optional[pulumi.Input[Union[int, str]]] = None):
if max_surge is not None:
pulumi.set(__self__, "max_surge", max_surge)
if max_unavailable is not None:
... | Python | nomic_cornstack_python_v1 |
function get_image self
begin
return call get_slice 0 n_windows
end function | def get_image(self):
return self.get_slice(0, self.n_windows) | Python | nomic_cornstack_python_v1 |
import argparse
from datetime import datetime
import signal
import sys
from timeout_utils import TimeoutException
from timeout_utils import handler
import requests
set DEBUG = false
function write_time_to_file data_file response
begin
comment Write to data file
with open data_file string a+ as data
begin
set now_time =... | import argparse
from datetime import datetime
import signal
import sys
from timeout_utils import TimeoutException
from timeout_utils import handler
import requests
DEBUG = False
def write_time_to_file(data_file, response):
# Write to data file
with open(data_file, "a+") as data:
now_time = datetime... | Python | zaydzuhri_stack_edu_python |
function setDuration self duration
begin
if duration == none
begin
return false
end
set dur = call _float duration
if dur == none
begin
raise call Error_Float format string Cannot interpret duration {} duration
return false
end
else
begin
set duration = dur
set durationMs = call durationToMs dur
return true
end
end fun... | def setDuration(self, duration):
if duration == None:
return False
dur = _float(duration)
if dur == None:
raise Error_Float("Cannot interpret duration {}".format(duration))
return False
else:
self.duration = dur
self.durationMs ... | Python | nomic_cornstack_python_v1 |
string Original Code Written By Robert Becker Created on July 19, 2019 Last Modified on July 19, 2019 Program was designed to calculate steps per month during a normal year. (365 Days) Project7 Part2
with open string steps.txt as f
begin
set variable = list
for line in f
begin
set items = split line
set steps = intege... | """
Original Code Written By Robert Becker
Created on July 19, 2019
Last Modified on July 19, 2019
Program was designed to calculate steps per month during a normal year. (365 Days)
Project7 Part2
"""
with open("steps.txt") as f:
variable = []
for line in f:
items = line.split()
steps... | Python | zaydzuhri_stack_edu_python |
if m == 0
begin
print ones at h + string o' clock
end
else
if m % 10 == 0 and m < 30
begin
print tens at integer m / 10 - 1 + string minutes past + ones at h
end
else
if m == 1
begin
print string one minute past + ones at h
end
else
if m < 15
begin
print ones at m - 1 + string minutes past + ones at h
end
else
if m == ... | if m == 0:
print(ones[h]+" o' clock")
elif m % 10 == 0 and m < 30:
print(tens[int(m/10)-1]+" minutes past "+ones[h])
elif m == 1:
print("one minute past "+ones[h])
elif m < 15:
print(ones[m-1]+" minutes past "+ones[h])
elif m == 15:
print("quarter past "+ones[h])
elif 15 < m < 30:
if 15 < m < 20... | Python | zaydzuhri_stack_edu_python |
import cv2
set count = 0
set face_cascade = call CascadeClassifier string E:\A\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml
comment For the access of camera 0-for same device 1-for other device
set cap = call VideoCapture 0
while true
begin
set count = count + 1
comment For capturing frame-by-frame
se... | import cv2
count = 0
face_cascade = cv2.CascadeClassifier('E:\\A\\Lib\\site-packages\\cv2\\data\\haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0) # For the access of camera 0-for same device 1-for other device
while True:
count = count+1
ret, frame = cap.read() ... | Python | zaydzuhri_stack_edu_python |
while numberofitems < 0
begin
print string ERROR: Please enter a positive interger
set numberofitems = integer input string Number of items:
end
for a in range numberofitems
begin
set price = decimal input string Price of item: $
set total = total + price
end
if total > 100
begin
set total = total * 0.9
end
print strin... | while numberofitems < 0:
print("ERROR: Please enter a positive interger")
numberofitems = int(input("Number of items: "))
for a in range(numberofitems):
price = float(input("Price of item: $"))
total += price
if total > 100:
total = total * 0.9
print("Total price for your", numberofitems, " items ... | Python | zaydzuhri_stack_edu_python |
function identify_repo repo
begin
set repo_root = call config string mozilla string repo_root string /repo/hg/mozilla
if not ends with repo_root string /
begin
set repo_root = repo_root + string /
end
set d = dict string firefox call is_firefox_repo repo ; string thunderbird call is_thunderbird_repo repo ; string publi... | def identify_repo(repo):
repo_root = repo.ui.config('mozilla', 'repo_root', '/repo/hg/mozilla')
if not repo_root.endswith('/'):
repo_root += '/'
d = {
'firefox': is_firefox_repo(repo),
'thunderbird': is_thunderbird_repo(repo),
'publishing': repo.ui.configbool('phases', 'publ... | Python | nomic_cornstack_python_v1 |
function begin self
begin
call begin
set _current_loop_count = 0
end function | def begin(self):
self._inner.begin()
self._current_loop_count = 0 | Python | nomic_cornstack_python_v1 |
comment exercise 11.7
import sys
function test did_pass
begin
string Print the result of the test
set linenum = f_lineno
if did_pass
begin
set msg = format string Test at line {0} ok. linenum
end
else
begin
set msg = format string Test at line {0} FAILED. linenum
end
print msg
end function
function dot_product u v
begi... | # exercise 11.7
import sys
def test(did_pass):
""" Print the result of the test """
linenum = sys._getframe(1).f_lineno
if did_pass:
msg = "Test at line {0} ok.".format(linenum)
else:
msg = "Test at line {0} FAILED.".format(linenum)
print(msg)
def dot_product(u, v):
result = ... | Python | zaydzuhri_stack_edu_python |
comment -*- coding:utf-8 -*-
comment 递归函数,查找下一级目录中的文件
import os
function search dir text
begin
for x in list directory dir
begin
if is file path x
begin
if text in call splitext string . at 0
begin
print string %s, %s % string x
end
end
if is directory path x
begin
search join path dir x text
end
end
end function
comme... | #-*- coding:utf-8 -*-
#递归函数,查找下一级目录中的文件
import os
def search(dir,text):
for x in os.listdir(dir):
if os.path.isfile(x):
if text in x.splitext(".")[0]:
print("%s, %s" %str(x))
if os.path.isdir(x):
search(os.path.join(dir,x),text)
#寻找目录中的有指定字符串的文件,并将工作目录变为该文件夹
... | Python | zaydzuhri_stack_edu_python |
function _convert_labelled_numeric_items table exploded_df row_header_cols col_header_cols decimal_pt=string . cast_type=float
begin
function convert_val val
begin
return call _convert_val_to_numeric val cast_type string [^0-9 { decimal_pt } ()-]
end function
set numeric_cells = call _generate_is_numeric_table exploded... | def _convert_labelled_numeric_items(table, exploded_df, row_header_cols, col_header_cols, decimal_pt='.',
cast_type=float):
def convert_val(val):
return _convert_val_to_numeric(val, cast_type, f'[^0-9{decimal_pt}()-]')
numeric_cells = _generate_is_numeric_table(expl... | Python | nomic_cornstack_python_v1 |
comment test FrameLayout
try
begin
import PySide2.QtCore as QtCore
import PySide2.QtWidgets as QtWidgets
import PySide2.QtGui as QtGui
end
except any
begin
print string Fail to import PySide2
import PySide.QtCore as QtCore
import PySide.QtGui as QtWidgets
import PySide.QtGui as QtGui
end
class frameLayout extends QFram... | # test FrameLayout
try:
import PySide2.QtCore as QtCore
import PySide2.QtWidgets as QtWidgets
import PySide2.QtGui as QtGui
except:
print('Fail to import PySide2')
import PySide.QtCore as QtCore
import PySide.QtGui as QtWidgets
import PySide.QtGui as QtGui
class frameLayout(QtWidgets.QFrame,):
def __init__(... | Python | zaydzuhri_stack_edu_python |
function metadata_json self
begin
return dict string flavor_classes string *,!onmetal ; string image_type string base ; string os_type string linux ; string org.openstack__1__os_distro string org.freebsd ; string vm_mode string hvm ; string auto_disk_config string disabled
end function | def metadata_json(self):
return {
"flavor_classes": "*,!onmetal",
"image_type": "base",
"os_type": "linux",
"org.openstack__1__os_distro": "org.freebsd",
"vm_mode": "hvm",
"auto_disk_config": "disabled"
} | Python | nomic_cornstack_python_v1 |
function init self userdata conn
begin
pass
end function | def init(self, userdata, conn):
pass | 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.