code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment import Python's hash, time, and string modules
import hashlib
import time
import string
comment flag will increment if a password is cracked, if flag=0 at end then the password was not in the list.
comment counter will record the number of passwords attempted
set flag = 0
set counter = 0
comment this function e... | #import Python's hash, time, and string modules
import hashlib
import time
import string
#flag will increment if a password is cracked, if flag=0 at end then the password was not in the list.
#counter will record the number of passwords attempted
flag=0
counter = 0
#this function encodes and hashes character strings fo... | Python | zaydzuhri_stack_edu_python |
for k in range 0 length l1 x
begin
append l2 l1 at slice k : k + x :
end
for k in range length l2
begin
if k % 2 == 0
begin
print *l2[k] sep=string
end
else
begin
print *l2[k][::-1] sep=string
end
end | for k in range(0,len(l1),x):l2.append(l1[k:k+x])
for k in range(len(l2)):
if k%2==0:print(*l2[k],sep=' ')
else:print(*l2[k][::-1],sep=' ') | Python | zaydzuhri_stack_edu_python |
comment World data structures
comment Country class
class Country extends object
begin
function __init__ self
begin
set name = string
set capital = string
set continent = string
end function
end class
class Quiz extends object
begin
comment class responsible for storing questions and stats
pass
end class | #World data structures
#Country class
class Country(object):
def __init__(self):
self.name = ""
self.capital = ""
self.continent = ""
class Quiz(object):
#class responsible for storing questions and stats
pass
| Python | zaydzuhri_stack_edu_python |
import unittest
from collections import deque
comment Definition for a binary tree node.
class TreeNode extends object
begin
function __init__ self x
begin
set val = x
set left = none
set right = none
end function
end class
class Solution
begin
set comma = string ,
set invalid = string NONE
function serialize self root... | import unittest
from collections import deque
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
comma = ","
invalid = "NONE"
def serialize(self, root):
"""Encodes a tree to... | Python | zaydzuhri_stack_edu_python |
function test_observe self
begin
with call create_experiment config base_trial as tuple cfg experiment client
begin
set trial = call Trial keyword trials at 1
assert results == list
call reserve trial
assert objective is none
call observe trial list dictionary name=string objective type=string objective value=101
asse... | def test_observe(self):
with create_experiment(config, base_trial) as (cfg, experiment, client):
trial = Trial(**cfg.trials[1])
assert trial.results == []
client.reserve(trial)
assert setup_storage().get_trial(trial).objective is None
client.observe(tr... | Python | nomic_cornstack_python_v1 |
function is_valid_closing a b
begin
if a == string ( and b == string )
begin
return true
end
if a == string [ and b == string ]
begin
return true
end
if a == string { and b == string }
begin
return true
end
return false
end function
comment def is_balanced(expression):
comment if len(expression) <= 1: return 'NO'
comme... | def is_valid_closing(a, b):
if a == '(' and b == ')': return True
if a == '[' and b == ']': return True
if a == '{' and b == '}': return True
return False
# def is_balanced(expression):
# if len(expression) <= 1: return 'NO'
# if len(expression) % 2 != 0: return 'NO'
# # build list
# b... | Python | zaydzuhri_stack_edu_python |
function __add__ self indent
begin
assert is instance indent int
if _indent + indent < 0
begin
raise call ValueError string Subtracting { absolute indent } positions would give a negative indentation level. Can maximally subtract { _indent } positions.
end
set _indent = _indent + indent
return self
end function | def __add__(self, indent: int):
assert isinstance(indent, int)
if self._indent + indent < 0:
raise ValueError(
f"Subtracting {abs(indent)} positions would give a "
"negative indentation level. Can maximally subtract "
f"{self._indent} positions... | Python | nomic_cornstack_python_v1 |
function calculate_cumulative_gain self search_ranking products_clicked products_added_to_cart products_purchased
begin
set gain = call calculate_gain search_ranking products_clicked products_added_to_cart products_purchased
comment TODO calculate cumulative gain
set cumulative_gain = list comprehension 0.0 for i in ga... | def calculate_cumulative_gain(self, search_ranking, products_clicked, products_added_to_cart, products_purchased):
gain = self.calculate_gain(search_ranking, products_clicked, products_added_to_cart, products_purchased)
cumulative_gain = [0.0 for i in gain] # TODO calculate cumulative gain
retu... | Python | nomic_cornstack_python_v1 |
function fit_transform self epochs
begin
return transform fit self epochs epochs
end function | def fit_transform(self, epochs):
return self.fit(epochs).transform(epochs) | Python | nomic_cornstack_python_v1 |
function test_12_parents_as_minus_1_0_0_1_1_2_3_4_4_5_7_7 self
begin
set parents = list - 1 0 0 1 1 2 3 4 4 5 7 7
call init parents
assert equal 5 call method_under_test
end function | def test_12_parents_as_minus_1_0_0_1_1_2_3_4_4_5_7_7(self):
parents = [ -1, 0, 0, 1, 1, 2, 3, 4, 4, 5, 7, 7 ]
self.init(parents)
self.assertEqual(5, self.method_under_test()) | Python | nomic_cornstack_python_v1 |
function test_mcp_pike_dpdk_install self underlay openstack_deployed config show_step openstack_actions
begin
info string *************** DONE **************
call local tgt=string * fun=string cmd.run args=string service ntp stop; ntpd -gq; service ntp start
if RUN_TEMPEST
begin
call run_tempest pattern=PATTERN
call do... | def test_mcp_pike_dpdk_install(self, underlay, openstack_deployed,
config, show_step, openstack_actions):
LOG.info("*************** DONE **************")
openstack_actions._salt.local(
tgt='*', fun='cmd.run',
args='service ntp stop; ntpd -gq; se... | Python | nomic_cornstack_python_v1 |
from typing import List
class Solution
begin
function twoSum self nums target
begin
set my_dict = dict
for tuple i v in enumerate nums
begin
if v in my_dict
begin
return list my_dict at v i
end
else
begin
set my_dict at target - v = i
end
end
return false
end function
end class
comment find two number's sum equal to t... | from typing import List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
my_dict = {}
for i, v in enumerate(nums):
if v in my_dict:
return [my_dict[v], i]
else:
my_dict[target-v] = i
return False
# find two number's sum equal to target
a = [1, 2,... | Python | zaydzuhri_stack_edu_python |
import requests
import json
from datetime import datetime , timedelta
import os
function get_weather
begin
string Query openweathermap.com's API and to get the weather for Varanasi and then dump the json to the /src/data/ directory with the file name "<today's date>.json"
with open string /c/Users/Admin/airflow/DAGS/sr... | import requests
import json
from datetime import datetime, timedelta
import os
def get_weather():
"""
Query openweathermap.com's API and to get the weather for
Varanasi and then dump the json to the /src/data/ directory
with the file name "<today's date>.json"
"""
with open('/c/Users/Admin/air... | Python | zaydzuhri_stack_edu_python |
function tls_cert self
begin
return get pulumi self string tls_cert
end function | def tls_cert(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "tls_cert") | Python | nomic_cornstack_python_v1 |
string Suite de casos de pruebas para la funcion CalcularPrecio() Creado el 19/04/2015 Equipo:Pytech Autores: Roberto Romero10-10642 Larry Perez 10-10547
import unittest
from datetime import datetime
from tarea2 import Tarifa , calcularPrecio
class Test extends TestCase
begin
function testTarifaCero self
begin
set tari... | '''Suite de casos de pruebas para la funcion CalcularPrecio()
Creado el 19/04/2015
Equipo:Pytech
Autores:
Roberto Romero10-10642
Larry Perez 10-10547
'''
import unittest
from datetime import datetime
from tarea2 import Tarifa, calcularPrecio
class Test(unittest.TestCase):
def testTarifaCero(self):... | Python | zaydzuhri_stack_edu_python |
function dtype self
begin
return _dtype
end function | def dtype(self) -> DataType:
return self._dtype | Python | nomic_cornstack_python_v1 |
function generate_fbs_bibliography methodname
begin
from flowsa.metadata import getMetadata
comment create list of sources in method
set sources = call generate_list_of_sources_in_fbs_method methodname
comment loop through list of sources, load source method
comment yaml, and create bib entry
set bib_list = list
set s... | def generate_fbs_bibliography(methodname):
from flowsa.metadata import getMetadata
# create list of sources in method
sources = generate_list_of_sources_in_fbs_method(methodname)
# loop through list of sources, load source method
# yaml, and create bib entry
bib_list = []
source_set = set... | Python | nomic_cornstack_python_v1 |
comment Hive Classes
import math as m
import pygame as pg
set debug = true
comment Color dict
set c = list
append c dict string black 0 ; string white 15071712 ; string selected 13421772 ; string swapl 3617342 ; string swapd 12565953 ; string u1 15071712 ; string u2 10745781 ; string u3 4245922 ; string u4 3120277 ; s... | # Hive Classes
import math as m
import pygame as pg
debug = True
c = [] # Color dict
c.append({
"black": 0x000000,
"white": 0xe5f9e0,
"selected" : 0xcccccc,
"swapl": 0x37323e,
"swapd": 0xbfbdc1,
"u1" : 0xe5f9e0, # https://coolors.co/e5f9e0-a3f7b5-40c9a2-2f9c95-4b3b47
"u2" : 0xa3f7b5,
... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Mon Nov 4 20:30:57 2019 @author: David
import gym
import numpy as np
comment from sklearn.linear_model import SGDRegressor
from sklearn.pipeline import FeatureUnion
from sklearn.kernel_approximation import RBFSampler
from sklearn.preprocessing import StandardScaler
import... | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 4 20:30:57 2019
@author: David
"""
import gym
import numpy as np
#from sklearn.linear_model import SGDRegressor
from sklearn.pipeline import FeatureUnion
from sklearn.kernel_approximation import RBFSampler
from sklearn.preprocessing import StandardScaler
import tensorfl... | Python | zaydzuhri_stack_edu_python |
comment Write a program to accept a range from user and print all odd numbers in the same. Hint: Don't use any arithmatic operator. #Accept 2 vaules. Use bitwise. Do validation for upper & lower numbers
comment !/usr/bin/python
function printOddNumbers iLower iUpper
begin
for x in range iLower iUpper 1
begin
if x ? 1
b... | #Write a program to accept a range from user and print all odd numbers in the same. Hint: Don't use any arithmatic operator. #Accept 2 vaules. Use bitwise. Do validation for upper & lower numbers
#!/usr/bin/python
def printOddNumbers(iLower,iUpper):
for x in range(iLower,iUpper,1):
if(x & 1):
print(x )
def mai... | Python | zaydzuhri_stack_edu_python |
function show ctx pretty
begin
debug string Started 'show' CLI
comment get all the args for debugging purposes
set command_args = dictionary comprehension arg : value for tuple arg value in items locals if arg is not string ctx
debug string Arguments: { command_args }
debug string Context variables: { obj }
try
begin
d... | def show(ctx, pretty):
logger.debug("Started 'show' CLI")
# get all the args for debugging purposes
command_args = {arg: value for arg,
value in locals().items() if arg is not 'ctx'}
logger.debug(f"Arguments: {command_args}")
logger.debug(f'Context variables: {ctx.obj}')
t... | Python | nomic_cornstack_python_v1 |
function sorted_count self k lb rb
begin
set conn = call get_conn
return call zcount k lb rb
end function | def sorted_count(self, k: str, lb: int, rb: int) -> int:
conn = self.get_conn()
return conn.zcount(k, lb, rb) | Python | nomic_cornstack_python_v1 |
import pytest
from workouts import print_workout_days
function test_print_workout_days capsys
begin
call print_workout_days workout=string upper body
set captured = call readouterr
assert out == string Mon, Thu
call print_workout_days workout=string lower body
set captured = call readouterr
assert out == string Tue, Fr... | import pytest
from workouts import print_workout_days
def test_print_workout_days(capsys):
print_workout_days(workout="upper body")
captured = capsys.readouterr()
assert captured.out == "Mon, Thu\n"
print_workout_days(workout="lower body")
captured = capsys.readouterr()
assert captured.out =... | Python | zaydzuhri_stack_edu_python |
import sys
import random
from PySide2 import QtCore , QtWidgets , QtGui
comment from EcuLog import EcuLog, SwDIDMap, EcuAddressMap
import json
class MyWidget extends QWidget
begin
function __init__ self
begin
call __init__
call setWindowTitle string Read DIDs
set hello = list string Hallo Welt string Hei maailma string... | import sys
import random
from PySide2 import QtCore, QtWidgets, QtGui
# from EcuLog import EcuLog, SwDIDMap, EcuAddressMap
import json
class MyWidget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Read DIDs")
self.hello = ["Hallo Welt", "Hei maailma", "Hol... | Python | zaydzuhri_stack_edu_python |
function xy2RaDec x_array y_array wcs
begin
set pixcrd = T
set world = call wcs_pix2world pixcrd 0
comment print(world)
set tuple ra_array dec_array = T
return tuple ra_array dec_array
end function | def xy2RaDec(x_array, y_array, wcs):
pixcrd = np.array([x_array, y_array], dtype=np.float64).T
world = wcs.wcs_pix2world(pixcrd, 0)
#print(world)
ra_array, dec_array = world.T
return ra_array, dec_array | Python | nomic_cornstack_python_v1 |
string '' CollectGeoInPeriod can collect geospatial weibo data of defined zone that is circular region in period In this class, just need change the period hour after hour to fetch weibo of the defined zone so that collect as much data as possible
import logging
import weibopack
import time
import threading
import date... | '''''
CollectGeoInPeriod can collect geospatial weibo data of defined zone that is circular region in period
In this class, just need change the period hour after hour to fetch weibo of the defined zone
so that collect as much data as possible
'''
import logging
import weibopack
import time
import threading
import date... | Python | zaydzuhri_stack_edu_python |
function addAtHead self val
begin
set new_node = call Node val
set next = head
set head = new_node
end function | def addAtHead(self, val: int) -> None:
new_node = Node(val)
new_node.next = self.head
self.head = new_node | Python | nomic_cornstack_python_v1 |
function get_ad_rep_qr_code self url site_directory=none
begin
if url
begin
set file_path = string ad_rep/%s % lower url
end
return call get_qr_code url site_directory
end function | def get_ad_rep_qr_code(self, url, site_directory=None):
if url:
self.file_path = "ad_rep/%s" % url.lower()
return self.get_qr_code(url, site_directory) | Python | nomic_cornstack_python_v1 |
import numpy as np
import matplotlib.pyplot as plt
from PIL.Image import *
from scipy import ndimage
import cv2
comment Hàm phát hiện góc bằng thuật toán Harris
function Harris img
begin
comment Tính đạo hàm theo trục Ox và Oy
set ix = call sobel img 0
set iy = call sobel img 1
comment Tính các thành phần A, C, B
comme... | import numpy as np
import matplotlib.pyplot as plt
from PIL.Image import *
from scipy import ndimage
import cv2
# Hàm phát hiện góc bằng thuật toán Harris
def Harris(img):
# Tính đạo hàm theo trục Ox và Oy
ix = ndimage.sobel(img, 0)
iy = ndimage.sobel(img, 1)
# Tính các thành phần A, C, B
ix2 = ix * ix #... | Python | zaydzuhri_stack_edu_python |
function parse_manifest self fpath
begin
set directory = directory name path fpath
with open fpath string r as fh
begin
for entry in load json fh
begin
comment Every entry of a manifest file needs to have a "filename"
comment attribute. It is the only requirement so we check for it in a
comment strict fashion.
if strin... | def parse_manifest(self, fpath):
directory = os.path.dirname(fpath)
with open(fpath, 'r') as fh:
for entry in json.load(fh):
# Every entry of a manifest file needs to have a "filename"
# attribute. It is the only requirement so we check for it in a
... | Python | nomic_cornstack_python_v1 |
comment ToDo:
string 111. Minimum Depth of Binary Tree Easy Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Note: A leaf is a node with no children. Example: Given binary tree [3,9,20,null,null,15,7], 3 / 9 2... | # ToDo:
"""
111. Minimum Depth of Binary Tree
Easy
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/... | Python | zaydzuhri_stack_edu_python |
from selenium import webdriver
from time import sleep
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
set driver = call Firefox
comment driver.get('http://www.51zxw.net')
comment sleep(2)
comment driver.find_element_by_link_text("程序开发").click()
comment # element=driver.find_e... | from selenium import webdriver
from time import sleep
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
#
# driver.get('http://www.51zxw.net')
# sleep(2)
# driver.find_element_by_link_text("程序开发").click()
# # element=driver.find_element_by_link_te... | Python | zaydzuhri_stack_edu_python |
comment Metodo de Newton-Raphso
from math import *
function f s x
begin
return eval s
end function
set u = input string funcion?
set v = input string Derivada?
set a = input string Aproximacion?
set n = input string Iteraciones?
set b = 0
for i in range n + 1
begin
if i == 0
begin
set b = a
end
end | #Metodo de Newton-Raphso
from math import *
def f(s,x):
return eval(s)
u=input('funcion? ')
v=input('Derivada? ')
a=input('Aproximacion? ')
n=input('Iteraciones? ')
b=0
for i in range(n+1):
if i==0:
b=a | Python | zaydzuhri_stack_edu_python |
function network_includes self
begin
return get pulumi self string network_includes
end function | def network_includes(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
return pulumi.get(self, "network_includes") | Python | nomic_cornstack_python_v1 |
comment James Galante###
comment 10.22.15###
comment List content comparison##
set list1 = list 1 2 3
set list2 = list 1 2 3
if list1 == list2
begin
print string equal
end
else
begin
print string not equal
end
comment list vs strings##
comment strings can be indexed and sliced
comment 'symbolic'
comment 01234567
commen... | ###James Galante###
###10.22.15###
####List content comparison##
list1 = [1,2,3]
list2 = [1,2,3]
##
if list1 == list2:
print('equal')
else:
print('not equal')
####list vs strings##
###strings can be indexed and sliced
###'symbolic'
### 01234567
###'symbolic'[4] -> symb
###'o'#'symbolic'[0:3] -> 'sym'
##
#... | Python | zaydzuhri_stack_edu_python |
import cv2
import numpy as np
from matplotlib import pyplot as plt
import os
change directory string C:\Users\sachi\.vscode\GitHubRepos\OSCV_Exercises
set exetasknum = 2
comment none of these works as SIFT is not included by default with opencv
comment also included code for Feature Matching + Homography to find Object... | import cv2
import numpy as np
from matplotlib import pyplot as plt
import os
os.chdir('C:\\Users\\sachi\\.vscode\\GitHubRepos\\OSCV_Exercises')
exetasknum = 2
# none of these works as SIFT is not included by default with opencv
# also included code for Feature Matching + Homography to find Objects
if exetasknum==1:
... | Python | zaydzuhri_stack_edu_python |
function test_degrade_map_float_sum self
begin
set nside_coverage = 32
set nside_map = 1024
set nside_new = 512
set full_map = call full call nside_to_npixel nside_map 1.0
comment Generate sparse map
set sparse_map = call HealSparseMap healpix_map=full_map nside_coverage=nside_coverage nside_sparse=nside_map
comment De... | def test_degrade_map_float_sum(self):
nside_coverage = 32
nside_map = 1024
nside_new = 512
full_map = np.full(hpg.nside_to_npixel(nside_map), 1.)
# Generate sparse map
sparse_map = healsparse.HealSparseMap(healpix_map=full_map, nside_coverage=nside_coverage,
... | Python | nomic_cornstack_python_v1 |
function from_bragg_teach cls data_dir=none min_questions=none relations=none conditions=none
begin
if data_dir is none
begin
set data_dir = environ at string BRAGG_TEACH_DIR
end
set df = read csv join path data_dir string data.csv
comment Ignore non-final.
set df = df at finalobservation
set df = rename columns=dict s... | def from_bragg_teach(cls, data_dir=None,
min_questions=None, relations=None, conditions=None):
if data_dir is None:
data_dir = os.environ['BRAGG_TEACH_DIR']
df = pd.read_csv(os.path.join(data_dir, 'data.csv'))
df = df[df.finalobservation] # Ignore non-final... | Python | nomic_cornstack_python_v1 |
function _describe_list self
begin
warn string use graph.summary.list() DeprecationWarning
return list
end function | def _describe_list(self) -> List[Tuple[str, float]]:
warnings.warn("use graph.summary.list()", DeprecationWarning)
return self.summarize.list() | Python | nomic_cornstack_python_v1 |
function set_cached_resource_size self resource_name size
begin
string meterer.set_cached_resource_size(resource_name) Set cached information about the given resource.
set size_data = call json_dumps dict string size size ; string recorded_time time
set string SIZE:%s % resource_name size_data ex=size_cache_timeout
ret... | def set_cached_resource_size(self, resource_name, size):
"""
meterer.set_cached_resource_size(resource_name)
Set cached information about the given resource.
"""
size_data = json_dumps({"size": size, "recorded_time": time()})
self.cache.set(
"SIZE:%s" % resou... | Python | jtatman_500k |
comment -*- coding:utf-8 -*-
import io
import os
set file = open string after.mp4 string w
set fileobj = open string a.txt string rb
set key = string made by hehe
while true
begin
set line = read line fileobj
if key in line
begin
print line
set line = replace line key string
print line
end
if length line == 0
begin
bre... | # -*- coding:utf-8 -*-
import io
import os
file = open('after.mp4','w')
fileobj = open('a.txt','rb')
key = "made by hehe"
while True:
line = fileobj.readline()
if key in line:
print(line)
line = line.replace(key,'')
print(line)
if len(line)==0:
break;
file.write(line)
fileobj.close
file.close
| Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
from nwae.utils.Log import Log
from inspect import currentframe , getframeinfo
from nwae.lang.preprocessing.BasicPreprocessor import BasicPreprocessor
import nltk
from nltk.corpus import comtrans
from nwae.lang.LangFeatures import LangFeatures
from nwae.utils.networking.Ssl import Ssl
clas... | # -*- coding: utf-8 -*-
from nwae.utils.Log import Log
from inspect import currentframe, getframeinfo
from nwae.lang.preprocessing.BasicPreprocessor import BasicPreprocessor
import nltk
from nltk.corpus import comtrans
from nwae.lang.LangFeatures import LangFeatures
from nwae.utils.networking.Ssl import Ssl
class Co... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function reverseParentheses self s
begin
set l = list
set n = length s
set i = 0
print n
while i < n
begin
print string i i string n n
if s at i != string )
begin
append l s at i
set i = i + 1
print string l append後 l string i i
end
else
begin
set a = i - 1
print string a a
while l at a != string ... | class Solution:
def reverseParentheses(self, s: str) -> str:
l=[]
n=len(s)
i=0
print(n)
while i<n:
print('i',i,'n',n)
if s[i]!=')':
l.append(s[i])
i+=1
print('l append後',l,'i',i)
else:
... | Python | zaydzuhri_stack_edu_python |
function detrend_df df period=string MS
begin
comment infer lag from period
if period == string MS
begin
set lag = 12
end
else
begin
raise call ValueError string Periods other than "MS" are not well supported yet!
end
comment new empty df to deal with length mismatches after resampling
set df_out = call DataFrame
comme... | def detrend_df(df, period='MS'):
# infer lag from period
if period == 'MS':
lag = 12
else:
raise ValueError('Periods other than "MS" are not well supported yet!')
# new empty df to deal with length mismatches after resampling
df_out = pd.DataFrame()
# resample time series (in ... | Python | nomic_cornstack_python_v1 |
import unittest
from selenium import webdriver
from selenium.webdriver.support.select import Select
import time
class OnlinerSearch extends TestCase
begin
function setUp self
begin
set driver = call Chrome
end function
function test_vacancy self
begin
set driver = driver
get driver string https://www.onliner.by/
assert... | import unittest
from selenium import webdriver
from selenium.webdriver.support.select import Select
import time
class OnlinerSearch(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
def test_vacancy(self):
driver = self.driver
driver.get("https://www.on... | Python | zaydzuhri_stack_edu_python |
function from_args cls args run_id=none inherit_save_dir=false
begin
if device is not none
begin
set environ at string CUDA_VISIBLE_DEVICES = device
end
set result_dir = none
set resume = none
set ensemble = none
if resume is not none
begin
set resume = call Path resume
set cfg_file = parent / string config.json
if inh... | def from_args(cls, args, run_id=None, inherit_save_dir=False):
if args.device is not None:
os.environ["CUDA_VISIBLE_DEVICES"] = args.device
result_dir = resume = ensemble = None
if args.resume is not None:
resume = Path(args.resume)
cfg_file = resume.parent /... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
class Solution
begin
comment @param {integer[]} nums
comment @return {integer}
function singleNumber self nums
begin
set ones = 0
set twos = 0
for num in nums
begin
set ones = ones ? num ? ? twos
set twos = twos ? num ? ? ones
end
return ones
end function
end class
set x = call Solution
print c... | #!/usr/bin/python
class Solution:
# @param {integer[]} nums
# @return {integer}
def singleNumber(self, nums):
ones = 0
twos = 0
for num in nums:
ones = ones^num & ~twos
twos = twos^num & ~ones
return ones
x = Solution()
print(x.singleNumber([1, 2, 3,... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: UTF-8 -*-
string @File :微博热搜榜.py @Author :叶庭云 @Date :2020/9/18 15:01
import schedule
import pandas as pd
from datetime import datetime
import logging
call basicConfig level=INFO format=string %(asctime)s - %(levelname)s: %(message)s
set count = 0
function get_content
begin
global count
print string ... | # -*- coding: UTF-8 -*-
"""
@File :微博热搜榜.py
@Author :叶庭云
@Date :2020/9/18 15:01
"""
import schedule
import pandas as pd
from datetime import datetime
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s: %(message)s')
count = 0
def get_content():
global count
prin... | Python | zaydzuhri_stack_edu_python |
function _get self
begin
pass
end function | def _get(self):
pass | Python | nomic_cornstack_python_v1 |
function scipy_annotate_eyeblinks raw eye_channel=string EB min_dist=100
begin
set tuple data times = raw at index ch_names eye_channel
comment ie. data: array([[ 7.31836466e-19, -1.67314226e-07, 2.18515609e-07, ...,
comment -1.38256900e-06, -7.66754021e-07, -2.03287907e-19]])
comment peaks is the sample number of each... | def scipy_annotate_eyeblinks(raw, eye_channel='EB', min_dist=100):
data, times = raw[raw.ch_names.index(eye_channel)]
# ie. data: array([[ 7.31836466e-19, -1.67314226e-07, 2.18515609e-07, ...,
# -1.38256900e-06, -7.66754021e-07, -2.03287907e-19]])
# peaks is the sample number of each peak and val... | Python | nomic_cornstack_python_v1 |
comment Formatação de strings com format
comment esse é o método tradicional
set a = format string {}, {} string batata string arroz
print a
comment também tem o método de separar por números os valores:
set b = format string {1}, {0} and {1} string to string lele
print b
comment nesse caso o 1 dentro das {} representa... | #Formatação de strings com format
a = "{}, {}".format("batata", "arroz") # esse é o método tradicional
print(a)
# também tem o método de separar por números os valores:
b = "{1}, {0} and {1}".format("to", "lele")
print(b)
# nesse caso o 1 dentro das {} representa o variável dentro do format que vai pegar, nesse caso o ... | Python | zaydzuhri_stack_edu_python |
function l1 y_true y_pred
begin
if call ndim y_true == 4
begin
return mean K absolute y_pred - y_true axis=list 1 2 3
end
else
if call ndim y_true == 3
begin
return mean K absolute y_pred - y_true axis=list 1 2
end
else
begin
raise call NotImplementedError string Calculating L1 loss on 1D tensors? should not occur for ... | def l1(y_true, y_pred):
if K.ndim(y_true) == 4:
return K.mean(K.abs(y_pred - y_true), axis=[1,2,3])
elif K.ndim(y_true) == 3:
return K.mean(K.abs(y_pred - y_true), axis=[1,2])
else:
raise NotImplementedError("Calculating L1 loss on 1D tensors? should not occur... | Python | nomic_cornstack_python_v1 |
function GetSquaredNorm self
begin
return call itkVectorF2_GetSquaredNorm self
end function | def GetSquaredNorm(self) -> "double":
return _itkVectorPython.itkVectorF2_GetSquaredNorm(self) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python2.6
comment _*_coding:utf8_*_
import numpy as np
import matplotlib
call use string TkAgg
import matplotlib.pyplot as plt
from time import sleep
comment para no presionar enter la pc lo hacecada cierto tiempo
set fig = figure
set ax = call add_subplot 111
plot list list
grid
comment variable... | #!/usr/bin/env python2.6
#_*_coding:utf8_*_
import numpy as np
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
from time import sleep
#para no presionar enter la pc lo hacecada cierto tiempo
fig=plt.figure()
ax=fig.add_subplot(111)
ax.plot([],[])
ax.grid()
#variables
n = range(0,10)
tvec =... | Python | zaydzuhri_stack_edu_python |
function execute self context
begin
comment Connections to Redshift through Airflow PostgresHook
set redshift_hook = call PostgresHook postgres_conn_id=redshift_conn_id
end function
comment Check if there are records or not in the table to make sure that the table is not empty
comment Iterate through all tables to chec... | def execute(self, context):
# Connections to Redshift through Airflow PostgresHook
redshift_hook = PostgresHook(postgres_conn_id=self.redshift_conn_id)
# Check if there are records or not in the table to make sure that the table is not empty
# Iterate through all tables to check emptyne... | Python | nomic_cornstack_python_v1 |
from calendar import Calendar
from django.utils import timezone
from django.shortcuts import render
from trades.models import DerivativeTrade
function list_years request
begin
string List all years available.
set placeholder_years = list comprehension y for y in range 2020 2000 - 1 - 1
set context = dict string years p... | from calendar import Calendar
from django.utils import timezone
from django.shortcuts import render
from trades.models import DerivativeTrade
def list_years(request):
""" List all years available. """
placeholder_years = [y for y in range(2020, 2000 - 1, -1)]
context = {"years": placeholder_years}
re... | Python | zaydzuhri_stack_edu_python |
comment change/update data at particular position number
set dict1 at 2 = string PERFECT
print dict1
comment add data to dictionary
set dict1 at 3 = string BEAUTIFUL
print dict1
comment pop and popitem difference
print pop item dict1
print dict1
print pop dict1 2
print dict1 | # change/update data at particular position number
dict1[2] = 'PERFECT'
print(dict1)
# add data to dictionary
dict1[3] = 'BEAUTIFUL'
print(dict1)
# pop and popitem difference
print(dict1.popitem())
print(dict1)
print(dict1.pop(2))
print(dict1)
| Python | zaydzuhri_stack_edu_python |
function async_get_options_flow config_entry
begin
return call LoxoneOptionsFlowHandler config_entry
end function | def async_get_options_flow(config_entry):
return LoxoneOptionsFlowHandler(config_entry) | Python | nomic_cornstack_python_v1 |
import re
set s = input
set pat = compile string ^A+!+$
if match s
begin
print string Panic!
end
else
begin
print string No panic
end | import re
s = input()
pat = re.compile("^A+!+$")
if pat.match(s):
print("Panic!")
else:
print("No panic")
| Python | zaydzuhri_stack_edu_python |
function extractTagsAndParams self elements text matches
begin
set stripped = string
set taglist = join string | elements
end function | def extractTagsAndParams(self, elements, text, matches):
stripped = u''
taglist = u'|'.join(elements) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
import struct
import math
class Node
begin
function __init__ self data left right
begin
set data = data
set left = left
set right = right
end function
end class
class Liquid
begin
function __init__ self blob
begin
set slots = length blob // 8
set raw_data = call unpack string ! + string LHH... | #!/usr/bin/env python
import struct
import math
class Node:
def __init__(self, data, left, right):
self.data = data
self.left = left
self.right = right
class Liquid:
def __init__(self, blob):
self.slots = len(blob)//8
raw_data = struct.unpack("!" + "LHH"*self.slots, bl... | Python | zaydzuhri_stack_edu_python |
comment import the required libraries
import requests
import time
comment enter the website url
set url = string https://example.com/
comment make the initial request to get the initial html content
set initial_content = text
comment loop for ever
while true
begin
comment every 5 seconds, make a new request
sleep 5
com... | # import the required libraries
import requests
import time
# enter the website url
url = "https://example.com/"
# make the initial request to get the initial html content
initial_content = requests.get(url).text
# loop for ever
while True:
# every 5 seconds, make a new request
time.sleep(5)
# mak... | Python | jtatman_500k |
function existing_file fname
begin
if not is file path fname
begin
raise call ValueError string Invalid file: + string fname
end
return fname
end function | def existing_file(fname):
if not os.path.isfile(fname):
raise ValueError("Invalid file: " + str(fname))
return fname | Python | nomic_cornstack_python_v1 |
import argparse
from simulation import simulate
function main
begin
set parser = call ArgumentParser
call add_argument string seed type=int
call add_argument string --remotemem string -r action=string store_true help=string enable remote memory
call add_argument string --num_servers string -n type=int help=string numbe... | import argparse
from simulation import simulate
def main():
parser = argparse.ArgumentParser()
parser.add_argument('seed', type=int)
parser.add_argument('--remotemem', '-r', action='store_true',
help='enable remote memory')
parser.add_argument('--num_servers','-n', type=int, hel... | Python | zaydzuhri_stack_edu_python |
function _new_progress_logger self *a **k
begin
return call ProgressLogger if expression verbosity >= 1 then logger else none *a keyword k
end function | def _new_progress_logger(self, *a, **k):
return ProgressLogger(logger if self.verbosity >= 1 else None, *a, **k) | Python | nomic_cornstack_python_v1 |
function replay_movement command name nb r p le_n
begin
set move = split command
if string reversed in move or string REVERSED in move
begin
if le_n == 1
begin
set nb = nb - r
set r = 0
call replay_reversed command name nb r p
end
else
begin
call replay_reversed command name nb r p
end
end
else
begin
call replay_forwar... | def replay_movement(command, name, nb, r, p,le_n):
move = command.split()
if "reversed" in move or "REVERSED" in move:
if le_n == 1:
nb = nb - r
r = 0
replay_reversed(command,name, nb, r, p)
else:
replay_reversed(command,name, nb, r, p)
else... | Python | nomic_cornstack_python_v1 |
import json
set person = dict string name string John ; string age 20 ; string girls list string Trixy string Jaine string Lu
set person_json_str = dumps person
set person_from_json = loads person_json_str
print person
print type person
print person_json_str
print type person_json_str
print person_from_json
print type ... | import json
person = {'name': 'John', 'age': 20, 'girls': ['Trixy', 'Jaine', 'Lu']}
person_json_str = json.dumps(person)
person_from_json = json.loads(person_json_str)
print(person)
print(type(person))
print(person_json_str)
print(type(person_json_str))
print(person_from_json)
print(type(person_from_json))
| Python | zaydzuhri_stack_edu_python |
function resume_model self resume_path
begin
if resume_path
begin
set resume_path = string { model_dir } / { resume_path } .pth.tar
if is file path resume_path
begin
print string => loading checkpoint ' { resume_path } '
set checkpoint = load torch resume_path map_location=device
set best_acc = checkpoint at string bes... | def resume_model(self, resume_path):
if resume_path:
resume_path = f'{self.model_dir}/{resume_path}.pth.tar'
if os.path.isfile(resume_path):
print(f"=> loading checkpoint '{resume_path}'")
checkpoint = torch.load(resume_path, map_location=self.device)
... | Python | nomic_cornstack_python_v1 |
function _choose_tau self xs ys taus=array range 0 1 0.1
begin
set negatives = list comprehension x for tuple x y in zip xs ys if not y
set positives = list comprehension x for tuple x y in zip xs ys if y
set prediction = dictionary comprehension x : model x for x in xs
set num_neg = length negatives
set num_pos = leng... | def _choose_tau(self, xs, ys, taus=T.arange(0,1,0.1)):
negatives = [x for x,y in zip(xs,ys) if not y]
positives = [x for x,y in zip(xs,ys) if y]
prediction = {x:self.model(x) for x in xs}
num_neg = len(negatives)
num_pos = len(positives)
def fpr(tau):
"""fpr... | Python | nomic_cornstack_python_v1 |
function create_hit
begin
if call validate_json == string Bad JSON
begin
return call wrong_data string JSON has an error
end
if call title_and_artist_id_provided json is none
begin
return call wrong_data string please provide json data with (title) and (artist_id)
end
if call validate_title json is none
begin
return ca... | def create_hit():
if validate_json() == "Bad JSON":
return wrong_data("JSON has an error")
if title_and_artist_id_provided(request.json) is None:
return wrong_data("please provide json data with (title) and (artist_id)")
if validate_title(request.json) is None:
return wrong_data(
... | Python | nomic_cornstack_python_v1 |
comment ! /usr/bin/env python3
function r8_wrap r rlo rhi
begin
comment *****************************************************************************80
comment R8_WRAP forces an R8 to lie between given limits by wrapping.
comment Discussion:
comment An R8 is a real value.
comment Example:
comment RLO = 4.0, RHI = 8.0
c... | #! /usr/bin/env python3
#
def r8_wrap ( r, rlo, rhi ):
#*****************************************************************************80
#
## R8_WRAP forces an R8 to lie between given limits by wrapping.
#
# Discussion:
#
# An R8 is a real value.
#
# Example:
#
# RLO = 4.0, RHI = 8.0
#
# R Value
#
# -2 ... | Python | zaydzuhri_stack_edu_python |
comment code for mutations goes here
import random
from create_gene import get_replacement , roll4d6
from transcribe_c import writec
from organism import Organism
comment Creates a new randomized gene at the pivot point in the genesequence
function create_gene org pivot file_location
begin
set newgene = call roll4d6
se... | #code for mutations goes here
import random
from create_gene import get_replacement, roll4d6
from transcribe_c import writec
from organism import Organism
# Creates a new randomized gene at the pivot point in the genesequence
def create_gene(org, pivot, file_location):
newgene = roll4d6()
newsequence = org.... | Python | zaydzuhri_stack_edu_python |
function is_pos_safe self addr
begin
for tiger_pos in call get_all_tiger_positions
begin
if call can_capture_pos addr
begin
return false
end
end
return true
end function | def is_pos_safe(self, addr: str) -> bool:
for tiger_pos in self.get_all_tiger_positions():
if tiger_pos.piece.can_capture_pos(addr):
return False
return True | Python | nomic_cornstack_python_v1 |
import math
import cv2
import numpy as np
set x = list
set y = list
set img = zeros tuple 512 512 3 uint8
for i in range 100
begin
append x i
append y i
end
for i in x
begin
for j in y
begin
set r = square root power i - 50 2 + power j - 50 2
comment if r<25:
comment img[i,j]=0
comment if r>25:
comment img[i,j]=0
if ... | import math
import cv2
import numpy as np
x=[]
y=[]
img = np.zeros((512,512,3), np.uint8)
for i in range(100):
x.append(i)
y.append(i)
for i in x:
for j in y:
r=math.sqrt(math.pow(i-50,2)+math.pow(j-50,2))
#if r<25:
# img[i,j]=0
#if r>25:
# ... | Python | zaydzuhri_stack_edu_python |
function Write_uInt16 self Address Register uInt16
begin
call Transaction character Address + character Register + call pack string H uInt16
end function | def Write_uInt16(self,Address,Register,uInt16):
self.Transaction(chr(Address)+chr(Register)+struct.pack('H',uInt16)) | Python | nomic_cornstack_python_v1 |
function main args=argv
begin
set parser = call parser_setup
set poptions = call parse_args
if quiet
begin
call basicConfig level=WARNING format=log_format
end
else
if debug
begin
call basicConfig level=DEBUG format=log_format
end
else
begin
comment Set up the default logging levels
call basicConfig level=INFO format=l... | def main(args = sys.argv):
parser = parser_setup()
poptions = parser.parse_args()
if poptions.quiet:
logging.basicConfig(level=logging.WARNING, format=log_format)
elif poptions.debug:
logging.basicConfig(level=logging.DEBUG, format=log_format)
else:
# Set up the default log... | Python | nomic_cornstack_python_v1 |
class Solution
begin
function hasAlternatingBits self n
begin
set bincon = binary n at slice 2 : :
set counter = 0
for i in range length bincon - 1
begin
if bincon at i != bincon at i + 1
begin
set counter = counter + 1
end
end
if length bincon - 1 == counter
begin
return true
end
else
begin
return false
end
end func... | class Solution:
def hasAlternatingBits(self, n: int) -> bool:
bincon = bin(n)[2:]
counter = 0
for i in range(len(bincon)-1):
if bincon[i] != bincon[i+1]:
counter += 1
if len(bincon)-1 == counter:
return True
else:
... | Python | zaydzuhri_stack_edu_python |
function merging self output_folder
begin
set dict_list_files = call create_list_of_files_to_merge
set nbr_of_files_to_create = length keys dict_list_files
set algorithm = call get_merging_algorithm
set horizontal_layout = call HBox list call Label string Merging Progress layout=call Layout width=string 20% call IntPro... | def merging(self, output_folder):
dict_list_files = self.create_list_of_files_to_merge()
nbr_of_files_to_create = len(dict_list_files.keys())
algorithm = self.get_merging_algorithm()
horizontal_layout = widgets.HBox([widgets.Label("Merging Progress",
... | Python | nomic_cornstack_python_v1 |
function get_class self name
begin
string Return a specific class :param name: the name of the class :rtype: a :class:`ClassDefItem` object
for i in call get_classes
begin
if call get_name == name
begin
return i
end
end
return none
end function | def get_class(self, name):
"""
Return a specific class
:param name: the name of the class
:rtype: a :class:`ClassDefItem` object
"""
for i in self.get_classes():
if i.get_name() == name:
return i
return None | Python | jtatman_500k |
import re
function find path
begin
set numbers = set
with open path + string README.md string r as file
begin
set data = read lines file
set pattern = string \| (\d+).*
for line in data
begin
set match = search pattern line
if match
begin
add numbers integer call group 1
end
end
end
set m = max numbers
for i in range 1... | import re
def find(path):
numbers = set()
with open(path + 'README.md', 'r') as file:
data = file.readlines()
pattern = r'\| (\d+).*'
for line in data:
match = re.search(pattern, line)
if match:
numbers.add(int(match.group(1)))
m = max(numbers)
for i in range(1, m + 1):
if i not in numbers... | Python | zaydzuhri_stack_edu_python |
from menu import menu
function func_a
begin
return string A
end function
function func_b
begin
return string B
end function
set return_value = call menu a=func_a b=func_b
print string Return value is { return_value } | from menu import menu
def func_a():
return 'A'
def func_b():
return 'B'
return_value = menu(a=func_a, b=func_b)
print(f'Return value is {return_value}')
| Python | zaydzuhri_stack_edu_python |
string 풀이: answer = 가격이 떨어진 시점(price_index) - 가격 초기 생성 시점(price_index)를 뺀 수. 가격이 떨어지기 전까지의 price들을 tmp_list에 추가한 후 떨어진 시점 발생 시 tmp_list에 있는 값들을 가져와 비교 후 떨어진 값의 경우 answer 값을 계산하여 추가해준다. 2019.06.14 - 오답(10%): answer 답 삽입 시 insert함수 사용으로 인한 Timeout Error 2019.06.14 - 정답: 찝찝하지만, answer를 price 크기만큼 초기 생성 후 해당 인덱스에 바로 답 삽입으로... | '''
풀이:
answer = 가격이 떨어진 시점(price_index) - 가격 초기 생성 시점(price_index)를 뺀 수.
가격이 떨어지기 전까지의 price들을 tmp_list에 추가한 후 떨어진 시점 발생 시 tmp_list에 있는 값들을 가져와 비교 후
떨어진 값의 경우 answer 값을 계산하여 추가해준다.
2019.06.14 - 오답(10%): answer 답 삽입 시 insert함수 사용으로 인한 Timeout Error
2019.06.14 -
정답: 찝찝하지만, answer를 price 크기만큼 초기 생성 후 해당... | Python | zaydzuhri_stack_edu_python |
function upload_here instance file_name
begin
comment file will be uploaded to MEDIA_ROOT/user_id/file_name
return string { id } / { file_name }
end function | def upload_here(instance, file_name):
return f'{instance.user.id}/{file_name}' # file will be uploaded to MEDIA_ROOT/user_id/file_name | Python | nomic_cornstack_python_v1 |
string valor_verdadeiro = True valor_false = False if valor_verdadeiro != False: print("A variável valor_verdadeiro é verdadeira") # IF E ELSE print ('Menu: 2 = Escreve Talita 2 = Escreve João 3 = Escreve Juliana') opcao = input('Escolha uma opção: ') if opcao == '1': print("Talita") elif opcao == '2': print('João') el... | """valor_verdadeiro = True
valor_false = False
if valor_verdadeiro != False:
print("A variável valor_verdadeiro é verdadeira")
# IF E ELSE
print ('Menu: \n2 = Escreve Talita\n2 = Escreve João\n3 = Escreve Juliana')
opcao = input('Escolha uma opção: ')
if opcao == '1':
print("Talita")
elif opcao == '2':
... | Python | zaydzuhri_stack_edu_python |
function find_radius mass delta_m eta xi mue pp_factor
begin
comment range of radii; reason in detail under step 9 of report
comment MKS
set r_low = 0.01 * Rsun
comment MKS
set r_high = 3 * Rsun
set radius = call brentq lum_difference r_low r_high xtol=0.0001 args=tuple mass delta_m eta xi mue pp_factor
return radius
e... | def find_radius(mass,delta_m,eta,xi,mue,pp_factor):
#range of radii; reason in detail under step 9 of report
r_low = 0.01*Rsun # MKS
r_high = 3*Rsun # MKS
radius = brentq(lum_difference, r_low, r_high, xtol=1.0e-4, args = (mass,delta_m,eta,xi,mue,pp_factor))
return radius | Python | nomic_cornstack_python_v1 |
from django.db import models
from import TimeTracked , TimeTracked
class Person extends TimeTracked
begin
class Meta
begin
set ordering = list string last_name string first_name string middle_name
end class
set first_name = call CharField max_length=40 blank=true null=true
set middle_name = call CharField max_length=4... | from django.db import models
from . import TimeTracked, TimeTracked
class Person(TimeTracked):
class Meta:
ordering = ['last_name', 'first_name', 'middle_name']
first_name = models.CharField(max_length=40, blank=True, null= True)
middle_name = models.CharField(max_length=40, blank=True, nu... | Python | zaydzuhri_stack_edu_python |
comment noqa: D401; irrelevant for properties
function script_name self
begin
if _script_name is not none
begin
return _script_name
end
comment A `_script_name` with a value of None signals that the script name
comment should be pulled from WSGI environ.
return right strip wsgi_environ at string SCRIPT_NAME string /
en... | def script_name(self): # noqa: D401; irrelevant for properties
if self._script_name is not None:
return self._script_name
# A `_script_name` with a value of None signals that the script name
# should be pulled from WSGI environ.
return cherrypy.serving.request.wsgi_environ[... | Python | nomic_cornstack_python_v1 |
for _ in range integer input
begin
print power 2 integer input - 1
end | for _ in range(int(input())):
print(pow(2,int(input())) -1) | Python | zaydzuhri_stack_edu_python |
string This module contains the classes needed to create a form for the GuestInfo model.
from django import forms
from models import GuestInfo
class GuestForm extends ModelForm
begin
string Creates a form for the GuestInfo model.
class Meta
begin
set model = GuestInfo
set fields = string __all__
set labels = dict strin... | '''This module contains the classes needed to
create a form for the GuestInfo model.'''
from django import forms
from .models import GuestInfo
class GuestForm(forms.ModelForm):
'''Creates a form for the GuestInfo model.
'''
class Meta:
model = GuestInfo
fields = '__all__'
labels = ... | Python | zaydzuhri_stack_edu_python |
function prompt_filename
begin
set fileName = input string Enter file:
print format string Opening file '{}' fileName
return fileName
end function
function prompt_word_choice
begin
set users_choice = input string Search the file for the word:
return users_choice
end function
function parse_file fileName users_choice
be... | def prompt_filename():
fileName = input("Enter file: ")
print("\nOpening file '{}' ".format(fileName))
return fileName
def prompt_word_choice():
users_choice = input("\nSearch the file for the word: ")
return users_choice
def parse_file(fileName, users_choice):
with open(fileName, mode = ... | Python | zaydzuhri_stack_edu_python |
function remove_min self
begin
if call is_empty
begin
return none
end
set t = tuple _key _value
set _data = _data at slice 1 : :
return t
end function | def remove_min(self):
if self.is_empty():
return None
t = (self._data[0]._key, self._data[0]._value)
self._data = self._data[1:]
return t | Python | nomic_cornstack_python_v1 |
function combat_tracker_move tracker steps
begin
if steps > 0
begin
while steps
begin
set tracker at string turns = tracker at string turns at slice 1 : : + list tracker at string turns at 0
set steps = steps - 1
end
end
if steps < 0
begin
set steps = absolute steps
while steps
begin
set tracker at string turns = lis... | def combat_tracker_move(tracker, steps):
if steps > 0:
while steps:
tracker['turns'] = tracker['turns'][1:] + [tracker['turns'][0]]
steps -= 1
if steps < 0:
steps = abs(steps)
while steps:
tracker['turns'] = [tracker['turns'][-1]] + tracker['turns'][0:... | Python | nomic_cornstack_python_v1 |
string Faça um programa que leia 5 valores e guarde-os numa lista. No final, Mostre qual foi o maior e qual foi o menor valor digitado e as suas respectivas posições na lista.
set num = list
for i in range 5
begin
append num integer input string Informe o { i + 1 } º número:
end
print string Maior valor: { max num } -... | '''Faça um programa que leia 5 valores e guarde-os numa lista. No final,
Mostre qual foi o maior e qual foi o menor valor digitado e as suas respectivas
posições na lista. '''
num = []
for i in range(5):
num.append(int(input(f'Informe o {i+1}º número: ')))
print(f'Maior valor: {max(num)} -> Posições: ', e... | Python | zaydzuhri_stack_edu_python |
set y = true
set count = 0
while y
begin
set a = string input string Enter the inputs:
set alpha = list string a string b string c string d string e string f string g string h string i string j string k string l string m string n string o string p string q string r string s string t string u string v string w string x ... | y=True
count =0
while(y):
a=str(input("Enter the inputs:"))
alpha = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
b=a.split()
if b[0] in alpha or b[1] in alpha:
print("Error")
count=count+1
else:
c=int(input("1.Addit... | Python | zaydzuhri_stack_edu_python |
import cv2
function showImage img namedWindow=string width=640 height=480
begin
call namedWindow namedWindow WINDOW_NORMAL
call resizeWindow namedWindow width height
image show namedWindow img
end function
set image = call imread string Page_09_Pattern_24.png
comment grayscale
set gray = call cvtColor image COLOR_BGR2... | import cv2
def showImage(
img,
namedWindow="",
width=640, height=480
):
cv2.namedWindow(namedWindow, cv2.WINDOW_NORMAL)
cv2.resizeWindow(namedWindow, width, height)
cv2.imshow(namedWindow, img)
image = cv2.imread("Page_09_Pattern_24.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR... | Python | zaydzuhri_stack_edu_python |
function send_notifications self options
begin
set error = call validate_send_notifications_options options
if error
begin
raise exception error
end
set config = deep copy config
comment execution mode for sending notifications must always be remote
set config at string decisioning_method = value
set target_options = d... | def send_notifications(self, options):
error = validate_send_notifications_options(options)
if error:
raise Exception(error)
config = deepcopy(self.config)
# execution mode for sending notifications must always be remote
config["decisioning_method"] = DecisioningMe... | Python | nomic_cornstack_python_v1 |
comment https://medium.com/@peter.nistrup/full-historical-data-for-every-crypto-on-binance-using-the-python-api-de017de42c2f
comment IMPORTS
import pandas as pd
import math
import os.path
import time
comment import json
import requests
from bitmex import bitmex
from binance.client import Client
from datetime import tim... | # https://medium.com/@peter.nistrup/full-historical-data-for-every-crypto-on-binance-using-the-python-api-de017de42c2f
# IMPORTS
import pandas as pd
import math
import os.path
import time
# import json
import requests
from bitmex import bitmex
from binance.client import Client
from datetime import timedelta, datetime
f... | Python | zaydzuhri_stack_edu_python |
for x in range 5
begin
append book input string Add an entry to the phone book:
end
set names = list
set numbers = list
for line in book
begin
append names join string list comprehension char for char in line if is alpha char
append numbers join string list comprehension char for char in line if call isnumeric or c... | for x in range(5):
book.append(input("Add an entry to the phone book: "))
names = []
numbers = []
for line in book:
names.append(''.join([char for char in line if char.isalpha()]))
numbers.append(''.join([char for char in line if (char.isnumeric() or char == '-')]))
name = input("Who do you want to call?: "... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import zipfile
comment 创建文件夹,需要一个绝对路径作为参数
function create_dir path
begin
set isExists = exists path path
comment 判断结果
if not isExists
begin
comment 如果不存在则创建目录
comment 创建目录操作函数
make directories path
end
end function | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import zipfile
# 创建文件夹,需要一个绝对路径作为参数
def create_dir(path):
isExists = os.path.exists(path)
# 判断结果
if not isExists:
# 如果不存在则创建目录
# 创建目录操作函数
os.makedirs(path)
| Python | zaydzuhri_stack_edu_python |
function get_archive_part_value self part
begin
string Return archive part for today
set parts_dict = dict string year string %Y ; string month month_format ; string week week_format ; string day string %d
if today is none
begin
set today = now
if call is_aware today
begin
set today = call localtime today
end
set today... | def get_archive_part_value(self, part):
"""Return archive part for today"""
parts_dict = {'year': '%Y',
'month': self.month_format,
'week': self.week_format,
'day': '%d'}
if self.today is None:
today = timezone.now()
... | Python | jtatman_500k |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.