code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function is_default self
begin
return get pulumi self string is_default
end function | def is_default(self) -> bool:
return pulumi.get(self, "is_default") | Python | nomic_cornstack_python_v1 |
function _get_interval_from_string self value variable
begin
set return_list = list
for item in split value string -
begin
set item = call _convert strip item variable
append return_list item
end
return tuple return_list
end function | def _get_interval_from_string(self, value, variable):
return_list = []
for item in value.split('-'):
item = self._convert(item.strip(), variable)
return_list.append(item)
return tuple(return_list) | Python | nomic_cornstack_python_v1 |
import numpy as np
from addlinetolevels_python_temp import addlinetolevels
function addlevels s
begin
comment strings together transitions to find levels[' not particularly fast. by
comment the end, levels['maxe and levels['mine should reflect the spread of
comment calculated values[' overcontraints simply ignored - wo... | import numpy as np
from addlinetolevels_python_temp import addlinetolevels
def addlevels(s):
#strings together transitions to find levels[' not particularly fast. by
#the end, levels['maxe and levels['mine should reflect the spread of
#calculated values[' overcontraints simply ignored - work it out later
#... | Python | zaydzuhri_stack_edu_python |
function list_versions_from_array docfiles
begin
set versions = list
for docfile in docfiles
begin
if not call get_version in versions
begin
append versions call get_version
end
end
sort versions
reverse versions
return versions
end function | def list_versions_from_array(docfiles):
versions = []
for docfile in docfiles:
if not docfile.get_version() in versions:
versions.append(docfile.get_version())
versions.sort()
versions.reverse()
return versions | Python | nomic_cornstack_python_v1 |
function RegisterCallbacksForTopLayoutControls self
begin
call AddCallback string Changed OnPriceSemanticSelected self
call AddCallback string Changed OnProviderTypeChanged self
call AddCallback string Changed OnSemanticCommentChanged self
call AddCallback string SelectionChanged OnSemanticListSelectionChanged self
cal... | def RegisterCallbacksForTopLayoutControls(self):
self.price_semantic.AddCallback ('Changed', OnPriceSemanticSelected, self)
self.provider_type.AddCallback ('Changed', OnProviderTypeChanged, self)
self.semantic_comment.AddCallback ('Changed', OnSemanticCommentChanged, self)... | Python | nomic_cornstack_python_v1 |
function get self key_path
begin
set config = data
for k in split key_path string /
begin
if config
begin
set config = get config k
end
end
if config or config == 0
begin
return config
end
return none
end function | def get(self, key_path):
config = self.data
for k in key_path.split('/'):
if config:
config = config.get(k)
if config or config == 0:
return config
return None | Python | nomic_cornstack_python_v1 |
comment 利用map()函数,将输入的名字首字母变为大写其余字母小写
from functools import reduce
set names = list string jims string john string tom string LISA
set change_name = list
for name in names
begin
append change_name title name
end
print change_name
comment 用map()函数来写这个小程序
function useTitle str
begin
return title str
end function
set cha... | #利用map()函数,将输入的名字首字母变为大写其余字母小写
from functools import reduce
names = ['jims','john','tom','LISA']
change_name=[]
for name in names:
change_name.append(name.title())
print(change_name)
#用map()函数来写这个小程序
def useTitle(str):
return str.title()
change_names = list(map(useTitle, names))
print(change_names)
| Python | zaydzuhri_stack_edu_python |
comment real signature unknown; restored from __doc__
function __init__ self *more
begin
pass
end function | def __init__(self, *more): # real signature unknown; restored from __doc__
pass | Python | nomic_cornstack_python_v1 |
class Solution extends object
begin
function firstUniqChar self s
begin
string :type s: str :rtype: int
set a = set
comment 侯选
set b = list
set c = dictionary
for tuple num i in enumerate s
begin
if i not in a
begin
add a i
append b i
set c at i = num
end
else
begin
try
begin
remove b i
end
except ValueError
begin
pass... | class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
a = set()
b = list() # 侯选
c = dict()
for num, i in enumerate(s):
if i not in a:
a.add(i)
b.append(i)
c[i] ... | Python | zaydzuhri_stack_edu_python |
from platform import system , uname
from subprocess import check_output
function get_max_descriptors
begin
try
begin
return integer check output string ulimit -n shell=true
end
except ValueError
begin
comment failed by some reason
return none
end
end function
function set_max_descriptors value=none
begin
string Trying ... | from platform import system, uname
from subprocess import check_output
def get_max_descriptors():
try:
return int(check_output('ulimit -n', shell=True))
except ValueError:
# failed by some reason
return None
def set_max_descriptors(value=None):
"""
Trying to set max descripto... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
string python aliases-lpm.py -a [aliasedprefix.txt] -i [input filename] --non-aliased-result=[non-aliased.txt] --aliased-result=[aliased.txt]
from __future__ import print_function
import argparse
import sys
try
begin
import SubnetTree
end
except Exception as e
begin
print e file=stderr
prin... | #!/usr/bin/env python
'''
python aliases-lpm.py -a [aliasedprefix.txt] -i [input filename] --non-aliased-result=[non-aliased.txt] --aliased-result=[aliased.txt]
'''
from __future__ import print_function
import argparse
import sys
try:
import SubnetTree
except Exception as e:
print(e, file=sys.stderr)
prin... | Python | zaydzuhri_stack_edu_python |
from lxml import etree
from Funciones import listar , contar , buscar , informacion , libre
set datos = parse etree string archivoxml.xml
print string MENU 1.Listar información: Mostrar el nombre de las canales de los que tenemos información. 2.Contar información: Mostrar la cantidad de canales que son de deportes. 3.B... | from lxml import etree
from Funciones import listar, contar, buscar, informacion, libre
datos=etree.parse("archivoxml.xml")
print(''' MENU
1.Listar información: Mostrar el nombre de las canales de los que tenemos información.
2.Contar información: Mostrar la cantidad de canales que son de deportes.
3.Buscar o filtr... | Python | zaydzuhri_stack_edu_python |
import heapq
function min_groups intervals
begin
sort intervals
set pq = list
for interval in intervals
begin
if pq and pq at 0 < interval at 0
begin
call heappop pq
end
call heappush pq interval at 1
end
return length pq
end function | import heapq
def min_groups(intervals):
intervals.sort()
pq = []
for interval in intervals:
if pq and pq[0] < interval[0]:
heapq.heappop(pq)
heapq.heappush(pq, interval[1])
return len(pq)
| Python | jtatman_500k |
function count_occurrences lst num
begin
set count = 0
for item in lst
begin
if item == num
begin
set count = count + 1
end
end
return count
end function | def count_occurrences(lst, num):
count = 0
for item in lst:
if item == num:
count += 1
return count
| Python | flytech_python_25k |
function process_counts id
begin
set id_df = call DataFrame
set start_date = call date 2019 8 25
set end_date = call date 2019 8 27
set cur_date = start_date
while cur_date <= end_date
begin
set start_str = string format time cur_date string %Y-%m-%d
set end_str = string format time cur_date + time delta days=1 string ... | def process_counts(id):
id_df = pd.DataFrame()
start_date = date(2019, 8, 25)
end_date = date(2019, 8, 27)
cur_date = start_date
while cur_date <= end_date:
start_str = cur_date.strftime("%Y-%m-%d")
end_str = (cur_date + timedelta(days=1)).strftime("%Y-%m-%d")
d = get_data_c... | Python | nomic_cornstack_python_v1 |
function collision self player distance=none
begin
if distance == none
begin
set distance = 2 * radius
end
return distance pos < distance
end function | def collision(self, player, distance=None):
if distance == None:
distance = 2 * self.radius
return self.pos.distance(player.pos) < distance | Python | nomic_cornstack_python_v1 |
class Solution
begin
function canFinish self numCourses prerequisites
begin
set course = default dictionary list
for tuple c p in prerequisites
begin
append course at p c
end
set visited = list 0 * numCourses
for i in range numCourses
begin
if not call dfs course visited i
begin
return false
end
end
return true
end fun... | class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
course = collections.defaultdict(list)
for c, p in prerequisites:
course[p].append(c)
visited = [0] * numCourses
for i in range(numCourses):
if not self.dfs(course, v... | Python | zaydzuhri_stack_edu_python |
comment step1. import pygame
import pygame
comment step2. define screen size
comment step3. create screen
set screen_size = list 360 600
set screen = call set_mode screen_size
comment step4. load a image
set background = load image string ./background.jpg
comment ste5. display image on the game screen
comment step6. cr... | #step1. import pygame
import pygame
#step2. define screen size
#step3. create screen
screen_size = [360, 600]
screen = pygame.display.set_mode(screen_size)
#step4. load a image
background = pygame.image.load("./background.jpg")
#ste5. display image on the game screen
#step6. create game loop => loop displaying image... | Python | zaydzuhri_stack_edu_python |
from functools import wraps
function memo func
begin
string A function that stores cached values from other functions. Can be used as a decorator to avoid rewriting a function as a generator. From Python Algorithms by Magnus Lie Hetland.
comment Stored subproblem solutions
set cache = dict
decorator wraps func
comment... | from functools import wraps
def memo(func):
"""A function that stores cached values from other functions.
Can be used as a decorator to avoid rewriting a function as a generator.
From Python Algorithms by Magnus Lie Hetland.
"""
cache = {} # Stored subproblem solutions
... | Python | zaydzuhri_stack_edu_python |
function datetime_utc_now
begin
return now utc
end function | def datetime_utc_now() -> datetime:
return datetime.now(timezone.utc) | Python | nomic_cornstack_python_v1 |
function on_upstream_connection_close self
begin
pass
end function | def on_upstream_connection_close(self) -> None:
pass | Python | nomic_cornstack_python_v1 |
function test_transform_album_artist_based_on_artist_album_no_match_album self
begin
set album = call Album artist=string Artist album=string Album 2 totaltracks=1 totalseconds=60
set transform = transform 1 cond_artist=true pattern_artist=string Artist cond_album=true pattern_album=string Album change_artist=true to_a... | def test_transform_album_artist_based_on_artist_album_no_match_album(self):
album = Album(artist='Artist', album='Album 2',
totaltracks=1, totalseconds=60)
transform = Transform(1,
cond_artist=True, pattern_artist = 'Artist',
cond_album=True, pattern_album='Album',
... | Python | nomic_cornstack_python_v1 |
import feedparser
import json
import requests
from bs4 import BeautifulSoup
function get_all_feed_urls file_path
begin
string Get rss feed(list of json objects with title, url, text and published fields) of all the urls present in the given file_path
set all_news_articles = list
with open file_path string r as in_file... | import feedparser
import json
import requests
from bs4 import BeautifulSoup
def get_all_feed_urls(file_path):
"""
Get rss feed(list of json objects with title, url, text and published fields)
of all the urls present in the given file_path
"""
all_news_articles = []
with open(file_path, 'r') as... | Python | zaydzuhri_stack_edu_python |
from pathlib import Path
import re
function go_deep node depth
begin
set output = string
if depth < 32
begin
for item in list comprehension i for i in split get rules node string
begin
if item in string ab|
begin
set output = output + item
end
else
begin
set output = output + string ( + call go_deep integer item depth... | from pathlib import Path
import re
def go_deep(node, depth):
output = ''
if depth < 32:
for item in [i for i in rules.get(node).split(' ')]:
if item in 'ab|':
output += item
else:
output += '(' + go_deep(int(item), depth + 1) + ')'
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding:utf-8 -*-
string 1、collections 是python内建的一个集合模块,提供了很多有用的集合类 2、namedtuple('名称',[属性list]) 用来创建一个tuple对象,并规定tuple元素的个数
comment 内建函数1:namedtuple()
comment 引进原因:可以实现类似 类的部分功能,但是代码量少。
from collections import namedtuple
comment 通过 namedtuple()创建一个名字为 Ponit的元祖
set Point = named ... | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
'''
1、collections 是python内建的一个集合模块,提供了很多有用的集合类
2、namedtuple('名称',[属性list]) 用来创建一个tuple对象,并规定tuple元素的个数
'''
#内建函数1:namedtuple()
#引进原因:可以实现类似 类的部分功能,但是代码量少。
from collections import namedtuple
Point = namedtuple('Point',['x','y']) #通过 namedtuple()创建一个名字为 Ponit的元祖
p = Po... | Python | zaydzuhri_stack_edu_python |
function copy_remote_files self
begin
if not get target string path
begin
call print_path_not_found_error
end
else
begin
set src_path = get source string path
set tgt_path = get target string path
set dirs = call getPendingDirs
for directory in dirs
begin
set new_dir = replace directory at string path src_path tgt_path... | def copy_remote_files(self):
if not self.target.get("path"):
self.print_path_not_found_error()
else:
src_path = self.source.get('path')
tgt_path = self.target.get('path')
dirs = self.database.getPendingDirs()
for directory in dirs:
... | Python | nomic_cornstack_python_v1 |
function sort_nicely l
begin
sort l key=alphanum_key
return l
end function | def sort_nicely(l):
l.sort(key=alphanum_key)
return l | Python | nomic_cornstack_python_v1 |
function mask tensor mask=none length=none value=0 debug=false
begin
if length list comprehension x for x in tuple mask length if x is not none != 1
begin
raise call KeyError string Exactly one of mask and length must be provided.
end
with call name_scope string mask
begin
if mask is none
begin
set range_ = range value... | def mask(tensor, mask=None, length=None, value=0, debug=False):
if len([x for x in (mask, length) if x is not None]) != 1:
raise KeyError('Exactly one of mask and length must be provided.')
with tf.name_scope('mask'):
if mask is None:
range_ = tf.range(tensor.shape[1].value)
mask = range_[None, ... | Python | nomic_cornstack_python_v1 |
function get_dataset data_name data_path
begin
set tuple transform_train transform_test = call data_transform data_name
if lower data_name == string cifar100
begin
set train_dataset = call CIFAR100 data_path train=true download=true transform=transform_train
set test_dataset = call CIFAR100 data_path train=false downlo... | def get_dataset(data_name, data_path):
transform_train, transform_test = data_transform(data_name)
if data_name.lower() == 'cifar100':
train_dataset = datasets.CIFAR100(data_path, train=True, download=True, transform=transform_train)
test_dataset = datasets.CIFAR100(data_path, train=False, downl... | Python | nomic_cornstack_python_v1 |
function login_validation self
begin
comment Extract Username form the Field
set username = call text
comment Extract Password form the Field
set password = call text
comment If Either of Fields are Blank
if username == string or password == string
begin
comment Display Error Message
call Message self string Error st... | def login_validation(self):
username = self.username_field.text() # Extract Username form the Field
password = self.password_field.text() # Extract Password form the Field
if username == '' or password == '': ... | Python | nomic_cornstack_python_v1 |
function GetBoxLineCharacters self
begin
return _box_line_characters
end function | def GetBoxLineCharacters(self):
return self._box_line_characters | Python | nomic_cornstack_python_v1 |
function __init__ self report_name app_id source_type report_source_id existing_report=none *args **kwargs
begin
call __init__ *args keyword kwargs
set existing_report = existing_report
if existing_report
begin
call _bootstrap existing_report
set button_text = call _ string Update Report
end
else
begin
set report_name ... | def __init__(self, report_name, app_id, source_type, report_source_id, existing_report=None, *args, **kwargs):
super(ConfigureNewReportBase, self).__init__(*args, **kwargs)
self.existing_report = existing_report
if self.existing_report:
self._bootstrap(self.existing_report)
... | Python | nomic_cornstack_python_v1 |
function makeModel **kwargs
begin
set params = get kwargs string params
set plot = get kwargs string plot false
set res = get kwargs string res string 300k
set grid = lower get kwargs string grid string phoenix
set bands = get kwargs string bands list list 15200 15800 list 15860 16425 list 16475 16935
set method = get ... | def makeModel(**kwargs):
params = kwargs.get('params')
plot = kwargs.get('plot', False)
res = kwargs.get('res', '300k')
grid = kwargs.get('grid', 'phoenix').lower()
bands = kwargs.get('bands', [[15200,15800],[15860,16425],[16475,16935]])
method = kwargs.get('method', 'fast')
# mdl_name = r'Teff = {}, l... | Python | nomic_cornstack_python_v1 |
function checkio array
begin
string sums even-indexes elements and multiply at the last
if length array == 0
begin
return false
end
set b = 0
for index in range length array
begin
if index % 2 == 0 and index <= 20
begin
set b = b + array at index
end
end
return b * array at index
end function
string Дан массив целых чи... | def checkio(array):
"""
sums even-indexes elements and multiply at the last
"""
if len(array) == 0:
return False
b = 0
for index in range(len(array)):
if index % 2 == 0 and index <= 20:
b = b + array[index]
return b * array[index]
"""
Дан массив целых чисел.... | Python | zaydzuhri_stack_edu_python |
import collections
with open string input.txt string r encoding=string utf8 as d
begin
comment считали текст в список по словам
set k = list split read d
end
set g = call most_common
sort g key=lambda x -> tuple - x at 1 x at 0
for element in g
begin
print element at 0
end | import collections
with open('input.txt', 'r', encoding='utf8') as d:
k = list(d.read().split()) # считали текст в список по словам
g = (collections.Counter(k)).most_common()
g.sort(key=lambda x: (-x[1], x[0]))
for element in g:
print(element[0]) | Python | zaydzuhri_stack_edu_python |
function _get_probability df prob_mod
begin
call _persist_if_unpersisted df
set scored_df = transform prob_mod df
set prob_col = call getOrDefault string probabilityCol
set prob_1_col = prob_col + string _1
set scored_df = call withColumn prob_1_col call call udf lambda x -> decimal x at 1 call FloatType call col prob_... | def _get_probability(df: DataFrame,
prob_mod: pyspark.ml.Model) -> Tuple[DataFrame, str]:
_persist_if_unpersisted(df)
scored_df = prob_mod.transform(df)
prob_col = prob_mod.getOrDefault('probabilityCol')
prob_1_col = prob_col + "_1"
scored_df = scored_df.withColumn(prob_... | Python | nomic_cornstack_python_v1 |
from unittest import TestCase
from p777.Solution import Solution
class TestSolution extends TestCase
begin
function test_canTransform self
begin
set sol = call Solution
assert equal false call canTransform string L string R
assert equal true call canTransform string LXRX string LXXR
assert equal false call canTransform... | from unittest import TestCase
from p777.Solution import Solution
class TestSolution(TestCase):
def test_canTransform(self):
sol = Solution()
self.assertEqual(False, sol.canTransform("L", "R"))
self.assertEqual(True, sol.canTransform("LXRX", "LXXR"))
self.assertEqual(False, sol.can... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
import glob
import os
import sys
from collections import deque
import math
import numpy as np
try
begin
append path glob glob string **/*%d.%d-%s.egg % tuple major minor if expression name == string nt then string win-amd64 else string linux-x86_64 at 0
end
except IndexError
begin
pass
end
... | #!/usr/bin/env python
import glob
import os
import sys
from collections import deque
import math
import numpy as np
try:
sys.path.append(glob.glob('**/*%d.%d-%s.egg' % (
sys.version_info.major,
sys.version_info.minor,
'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0])
except IndexErr... | Python | zaydzuhri_stack_edu_python |
async function test_ssdp_discovery_failed hass mock_ssdp_no_yamaha mock_get_source_ip
begin
set result = await call async_init DOMAIN context=dict string source SOURCE_SSDP data=call SsdpServiceInfo ssdp_usn=string mock_usn ssdp_st=string mock_st ssdp_location=string http://127.0.0.1/desc.xml upnp=dict ATTR_UPNP_MODEL_... | async def test_ssdp_discovery_failed(
hass: HomeAssistant, mock_ssdp_no_yamaha, mock_get_source_ip
) -> None:
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_SSDP},
data=ssdp.SsdpServiceInfo(
ssdp_usn="mock_usn",
... | Python | nomic_cornstack_python_v1 |
from twilio.rest import Client
from urllib.parse import urlencode
comment Your Account Sid and Auth Token from twilio.com/console
set account_sid = string ACa7895c59a8482877ce1777ca90057d50
set auth_token = string 1eba21cccd071e621ab1eb2413409982
comment To do: Check behavior on moving message body to the constructor o... | from twilio.rest import Client
from urllib.parse import urlencode
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACa7895c59a8482877ce1777ca90057d50'
auth_token = '1eba21cccd071e621ab1eb2413409982'
# To do: Check behavior on moving message body to the constructor of the function.
'''def sendM... | Python | zaydzuhri_stack_edu_python |
function isOpen self
begin
set what = read call checkapf string WHATSOPN
if string DomeShutter in what or string MirrorCover in what or string Vents in what
begin
return tuple true what
end
else
begin
return tuple false string
end
end function | def isOpen(self):
what = self.checkapf("WHATSOPN").read()
if "DomeShutter" in what or "MirrorCover" in what or "Vents" in what:
return True, what
else:
return False, '' | Python | nomic_cornstack_python_v1 |
function readStudentNames
begin
set studentScores = dictionary
set file = open string student-grade-math.csv
for line in file
begin
set tokens = split line string ,
set studentName = pop tokens 0
set scores = list map int tokens
set studentScores at studentName = scores
end
close file
return studentScores
end function
... | def readStudentNames():
studentScores = dict()
file = open("student-grade-math.csv")
for line in file:
tokens = line.split(",")
studentName = tokens.pop(0)
scores = list(map(int,tokens ))
studentScores[studentName] = scores
file.close()
return studentScores
#This... | Python | zaydzuhri_stack_edu_python |
function elimate_leading_whitespace source target=none
begin
if not source
begin
return 0
end
set tuple i length = tuple 0 length source
while i < length
begin
if source at i not in string
begin
if target and source at i == target or target is none
begin
return i
end
return 0
end
set i = i + 1
end
return 0
end functio... | def elimate_leading_whitespace(source, target=None):
if not source:
return 0
i, length = 0, len(source)
while i < length:
if source[i] not in ' \t':
if (target and source[i] == target) or target is None:
return i
return 0
i += 1
return 0 | Python | nomic_cornstack_python_v1 |
function get_data
begin
set X = load np string aggregate_data/X.npy
set y = load np string aggregate_data/y.npy
return tuple X y
end function | def get_data():
X = np.load('aggregate_data/X.npy')
y = np.load('aggregate_data/y.npy')
return X, y | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Formatting Argentina data
import pandas as pd
import platform
import numpy as np
import sys
comment load our functions
set USERNAME_path = string FILEPATH/Functions
set USERNAME_path = string FILEPATH/Functions
append path USERNAME_path
append path USERNAME_path
from hosp_prep impor... | # -*- coding: utf-8 -*-
"""
Formatting Argentina data
"""
import pandas as pd
import platform
import numpy as np
import sys
# load our functions
USERNAME_path = r"FILEPATH/Functions"
USERNAME_path = r"FILEPATH/Functions"
sys.path.append(USERNAME_path)
sys.path.append(USERNAME_path)
from hosp_prep import *
# Environm... | Python | zaydzuhri_stack_edu_python |
import re
function remove_vowels text
begin
set pattern = compile string [aeiouAEIOU]
return sub pattern string text
end function
set text = string Hello, World!
set result = call remove_vowels text
comment Output: "Hll, Wrld!"
print result | import re
def remove_vowels(text):
pattern = re.compile('[aeiouAEIOU]')
return re.sub(pattern, '', text)
text = "Hello, World!"
result = remove_vowels(text)
print(result) # Output: "Hll, Wrld!"
| Python | jtatman_500k |
from keras.applications.resnet50 import ResNet50
from keras.models import Sequential
from keras.layers import Dense , Dropout , GlobalAveragePooling2D
from keras.preprocessing.image import ImageDataGenerator
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint , ReduceLROnPlateau
import os
impo... | from keras.applications.resnet50 import ResNet50
from keras.models import Sequential
from keras.layers import Dense,Dropout,GlobalAveragePooling2D
from keras.preprocessing.image import ImageDataGenerator
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint,ReduceLROnPlateau
import os
import mat... | Python | zaydzuhri_stack_edu_python |
from player import *
from mobile import *
from room import *
import random
class Butterfly extends MobileThing
begin
function __init__ self name loc restlessness description
begin
call __init__ self name loc description
set _countdown = random integer 4 10
set _changeState = random integer 5 9
set _state = string cater... | from player import *
from mobile import *
from room import *
import random
class Butterfly (MobileThing):
def __init__ (self,name,loc,restlessness,description):
MobileThing.__init__(self,name,loc,description)
self._countdown = random.randint(4,10)
self._changeState = random.randint(5,9)
self._state = "caterp... | Python | zaydzuhri_stack_edu_python |
import requests
set headers = dict string Authorization string Token 775541e1a93f7d1f40f24fa4f29adece2f5e2ee7
set url_base_cursos = string http://localhost:8000/api/v2/cursos/
set url_base_avaliacoes = string http://localhost:8000/api/v2/avaliacoes/
comment Testes método DELETE
comment # Verificando se curso existe com... | import requests
headers = {'Authorization': 'Token 775541e1a93f7d1f40f24fa4f29adece2f5e2ee7'}
url_base_cursos = 'http://localhost:8000/api/v2/cursos/'
url_base_avaliacoes = 'http://localhost:8000/api/v2/avaliacoes/'
## Testes método DELETE
# # Verificando se curso existe com id = 3
# curso = request.get(url=f'{url_... | Python | zaydzuhri_stack_edu_python |
function std nums n_mean=none
begin
if not n_mean
begin
set n_mean = mean nums
end
set n = length nums
if n == 1
begin
return 0.0
end
set variance = 0.0
for i in call xrange n
begin
set tmp = nums at i - n_mean
set variance = variance + tmp * tmp
end
set variance = variance / n - 1
return square root variance
end funct... | def std (nums,n_mean=None):
if not n_mean:
n_mean = mean(nums)
n = len(nums)
if n == 1:
return 0.0
variance = 0.0
for i in xrange(n):
tmp = (nums[i]-n_mean)
variance += (tmp*tmp)
variance /= n-1
return sqrt(variance) | Python | nomic_cornstack_python_v1 |
string ------------------------------------------------------------------------------- Name: f_to_c.py Purpose: To change fahrenheit to celcius Author: Lue.Kyle Created: 08/02/2021 ------------------------------------------------------------------------------
print string *****Farenheit to Celcius*****
comment Input Fa... | """
-------------------------------------------------------------------------------
Name: f_to_c.py
Purpose: To change fahrenheit to celcius
Author: Lue.Kyle
Created: 08/02/2021
------------------------------------------------------------------------------
"""
print ("*****Farenheit to Celcius*****")
# Input Fa... | Python | zaydzuhri_stack_edu_python |
function cosine_similarity a b
begin
return dot a b / call euclidean_norm a / call euclidean_norm b
end function | def cosine_similarity(a: Iterable[Computable], b: Iterable[Computable]) -> Computable:
return dot(a, b) / euclidean_norm(a) / euclidean_norm(b) | Python | nomic_cornstack_python_v1 |
for a in numbers at slice : :
begin
for b in numbers at slice : :
begin
if a >= b
begin
print a string * b string = a * b end=string
end
end
print string
end
print string 开始打印去除偶数行的九九乘法表
for c in numbers at slice : :
begin
set d = 1
if c % 2 == 1
begin
while c >= d
begin
print c string * d string = c * d end=s... | for a in numbers[:]:
for b in numbers[:]:
if a >= b:
print(a, "*", b, "=", a * b,end=" ")
print('\n')
print('开始打印去除偶数行的九九乘法表')
for c in numbers[:]:
d = 1
if c % 2 ==1:
while c >= d:
print(c, "*", d, "=", c * d,end=" ")
d += 1
print('\n')
... | Python | zaydzuhri_stack_edu_python |
comment coding=utf-8
import nltk
from nltk.corpus import wordnet as wn
comment from nltk.corpus.wordnet import WordNetCorpusReader
comment nltk.app.wordnet()
comment 同义词
comment motorcar 只有一个可能的含义,它被定义为 car.n.01,car的第一个名词意义
comment print wn.synsets('motorcar')
comment car.n.01被称为synset或“同义词集”,意义相同的词(或“词条”)的集合
comment p... | # coding=utf-8
import nltk
from nltk.corpus import wordnet as wn
##from nltk.corpus.wordnet import WordNetCorpusReader
##nltk.app.wordnet()
####同义词
####motorcar 只有一个可能的含义,它被定义为 car.n.01,car的第一个名词意义
##print wn.synsets('motorcar')
####car.n.01被称为synset或“同义词集”,意义相同的词(或“词条”)的集合
##print wn.synset('car.n.01').lemma_names... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Mon Jun 14 22:40:20 2021 @author: nikhil.barua
comment Data visualisation
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
set iris = call load_dataset string iris
call pairplot iris hue=string species palette=string Dark2
set s... | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 14 22:40:20 2021
@author: nikhil.barua
"""
#Data visualisation
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
iris = sns.load_dataset('iris')
sns.pairplot(iris, hue = 'species', palette='Dark2')
setosa... | Python | zaydzuhri_stack_edu_python |
function positive self
begin
return get json string positive none
end function | def positive(self):
return self.json.get('positive', None) | Python | nomic_cornstack_python_v1 |
function do_zremoteinstall self args
begin
set arglist = split args
comment Expect 3 argument
if not arglist or length arglist != 4
begin
call perror string zremoteinstall requires exactly 4 argument: traceback_war=false
call do_help string zremoteinstall
set _last_result = call CommandResult string string Bad argumen... | def do_zremoteinstall(self, args):
arglist = args.split()
# Expect 3 argument
if not arglist or len(arglist) != 4:
self.perror('zremoteinstall requires exactly 4 argument:', traceback_war=False)
self.do_help('zremoteinstall')
self._last_result = cmd2.Command... | Python | nomic_cornstack_python_v1 |
comment problem 1 : 34. Find First and Last Position of Element in Sorted Array
comment Time Complexity : O(log n)
comment Space Complexity : O(1)
comment Did this code successfully run on Leetcode : Yes
comment Any problem you faced while coding this : None
comment Your code here along with comments explaining your ap... | # problem 1 : 34. Find First and Last Position of Element in Sorted Array
# Time Complexity : O(log n)
# Space Complexity : O(1)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : None
# Your code here along with comments explaining your approach
## modifies binary search ... | Python | zaydzuhri_stack_edu_python |
function __getitem__ self roi stranded=true
begin
return call get_overlapping_features roi stranded=stranded
end function | def __getitem__(self, roi, stranded=True):
return self.get_overlapping_features(roi, stranded=stranded) | Python | nomic_cornstack_python_v1 |
function right_mouse_down
begin
return call get_pos
end function | def right_mouse_down():
return pygame.mouse.get_pos() | Python | nomic_cornstack_python_v1 |
function getEmployeeDetails uid
begin
set urlTodo = string https://jsonplaceholder.typicode.com/todos
set urlUsers = string https://jsonplaceholder.typicode.com/users
set reqTodo = get requests urlTodo
set reqUsers = get requests urlUsers
set doneTaskList = list
for task in json reqTodo
begin
if get task string userId... | def getEmployeeDetails(uid):
urlTodo = "https://jsonplaceholder.typicode.com/todos"
urlUsers = "https://jsonplaceholder.typicode.com/users"
reqTodo = requests.get(urlTodo)
reqUsers = requests.get(urlUsers)
doneTaskList = []
for task in reqTodo.json():
if task.get('userId') == uid:
... | Python | nomic_cornstack_python_v1 |
function quantize matrix quantiles
begin
comment Make sure quantiles is a numpy arra
set quantiles = array quantiles
comment Create output matrix
set quantizedMatrix = zeros shape dtype=int
comment Convert to int values...
for quantile in quantiles
begin
set quantizedMatrix = quantizedMatrix + matrix > quantile
end
com... | def quantize( matrix, quantiles ):
# Make sure quantiles is a numpy arra
quantiles = np.array( quantiles )
# Create output matrix
quantizedMatrix = np.zeros( matrix.shape, dtype=np.int )
# Convert to int values...
for quantile in quantiles:
quantizedMatrix += matrix > quantile
# Make... | Python | nomic_cornstack_python_v1 |
function event_m10_29_x25 z38=_ z39=_
begin
string State 0,2: [Reproduction] Door that opens in conjunction with the gimmick door_SubState
assert call event_m10_29_x27
string State 3: [Condition] Door that opens in conjunction with the gimmick door_SubState
set call = call event_m10_29_x26 z38=z38 z39=z39
if get call =... | def event_m10_29_x25(z38=_, z39=_):
"""State 0,2: [Reproduction] Door that opens in conjunction with the gimmick door_SubState"""
assert event_m10_29_x27()
"""State 3: [Condition] Door that opens in conjunction with the gimmick door_SubState"""
call = event_m10_29_x26(z38=z38, z39=z39)
if call.... | Python | nomic_cornstack_python_v1 |
import csv
import html
import requests
import time
from bs4 import BeautifulSoup
class LanguagePokemonScraper
begin
string
function __init__ self url lang **kwargs
begin
string
set url = url
set lang = lang
set kwargs = kwargs
set soup = call get_soup url
set lang_tuples = call get_lang_tuples
end function
decorator ... | import csv
import html
import requests
import time
from bs4 import BeautifulSoup
class LanguagePokemonScraper:
"""
"""
def __init__(self, url, lang, **kwargs):
"""
"""
self.url = url
self.lang = lang
self.kwargs = kwargs
self.soup = self.get... | Python | zaydzuhri_stack_edu_python |
from alpha_vantage.timeseries import TimeSeries
from alpha_vantage.techindicators import TechIndicators
from matplotlib.pyplot import figure
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from datetime import date , datetime
set key = string I60U01EBQ8EXL7J8
set start_date = today
comment Choose... | from alpha_vantage.timeseries import TimeSeries
from alpha_vantage.techindicators import TechIndicators
from matplotlib.pyplot import figure
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from datetime import date, datetime
key = 'I60U01EBQ8EXL7J8'
start_date = date.today()
# Choose... | Python | zaydzuhri_stack_edu_python |
from typing import Any
from stemmaweb_middleware.permissions.models import PermissionArguments
function public_resources_only response
begin
string Response transformer that filters out all resources that are not public. We determine whether a resource is public by checking the `is_public` field. :param response: The r... | from typing import Any
from stemmaweb_middleware.permissions.models import PermissionArguments
def public_resources_only(response: Any) -> list[dict]:
"""
Response transformer that filters out all resources that are not public.
We determine whether a resource is public by checking the `is_public` field.
... | Python | zaydzuhri_stack_edu_python |
function __getitem__ self key
begin
return _data at key
end function | def __getitem__(self, key: str) -> ntyping.ArrayLike:
return self._data[key] | Python | nomic_cornstack_python_v1 |
function agent_start self state
begin
comment select action given state (using self.agent_policy()), and save current state and action
comment self.last_state = ?
comment self.last_action = ?
comment ----------------
comment your code here
set last_state = state
set last_action = call agent_policy state
comment -------... | def agent_start(self, state):
### select action given state (using self.agent_policy()), and save current state and action
# self.last_state = ?
# self.last_action = ?
# ----------------
# your code here
self.last_state = state
self.last_action = self.agent_polic... | Python | nomic_cornstack_python_v1 |
string count the number of unique words in a text file
from re import compile as _compile
from collections import Counter
import os
function word_count _file
begin
string Count the number of unique words in the file use the regex '\w+' and Counter to detect words and count unique ones respectively A list of tuples with... | """count the number of unique words in a text file"""
from re import compile as _compile
from collections import Counter
import os
def word_count(_file):
"""Count the number of unique words in the file
use the regex '\w+' and Counter to detect words and count unique ones respectively
A list of tuples with each t... | Python | zaydzuhri_stack_edu_python |
function test_leftoverSockets self
begin
set suite = call loadByName string twisted.trial.test.erroneous.SocketOpenTest.test_socketsLeftOpen
run result
assert false call wasSuccessful
comment socket cleanup happens at end of class's tests.
comment all the tests in the class are successful, even if the suite
comment fai... | def test_leftoverSockets(self):
suite = self.loader.loadByName(
"twisted.trial.test.erroneous.SocketOpenTest.test_socketsLeftOpen"
)
suite.run(self.result)
self.assertFalse(self.result.wasSuccessful())
# socket cleanup happens at end of class's tests.
# all th... | Python | nomic_cornstack_python_v1 |
import sys
import math
set T = integer input
for i in range T
begin
set li = list
set r_li = list
set tuple x1 y1 r1 x2 y2 r2 = map int split read line stdin
set dis = x1 - x2 ^ 2 + y1 - y2 ^ 2
set sub1 = r2 + r1
set sub2 = r2 - r1
set sub1 = sub1 ^ 2
set sub2 = sub2 ^ 2
if absolute dis < sub1 and absolute dis > sub2... | import sys
import math
T = int(input())
for i in range(T):
li = []
r_li = []
x1,y1,r1,x2,y2,r2 = map(int, sys.stdin.readline().split())
dis = (x1-x2)**2 + (y1-y2)**2
sub1 = r2 + r1
sub2 = r2 - r1
sub1 **= 2
sub2 **= 2
if abs(dis) < sub1 and abs(dis) >sub2:
print(2)
elif a... | Python | zaydzuhri_stack_edu_python |
function test_zarr_driver create_test_group array_shape max_workers
begin
set dl = call ZarrDriver url=url max_workers=max_workers
set it = call get_iter
for arr in it
begin
assert shape == array_shape
end
set root = call get_root_group
assert difference set keys root set literal string 4 string 2 string 1 string 3 == ... | def test_zarr_driver(create_test_group: SquirrelGroup, array_shape: SHAPE, max_workers: int) -> None:
dl = ZarrDriver(url=create_test_group.store.url, max_workers=max_workers)
it = dl.get_iter()
for arr in it:
assert arr.shape == array_shape
root = dl.get_root_group()
assert set(root.keys())... | Python | nomic_cornstack_python_v1 |
function after_init self
begin
set _lexer = call PythonLexer
set _formatter = call TerminalFormatter
comment Logic:
set _processed_filenames : List at str = list
set _error_count = 0
end function | def after_init(self):
self._lexer = PythonLexer()
self._formatter = TerminalFormatter()
# Logic:
self._processed_filenames: List[str] = []
self._error_count = 0 | Python | nomic_cornstack_python_v1 |
function lusid_response_to_data_frame lusid_response rename_properties=false column_name_mapping=none
begin
comment Check if lusid_response is a list of the same objects which all have to_dict() method
if type lusid_response == list and length lusid_response == 0
begin
return call DataFrame
end
else
if type lusid_respo... | def lusid_response_to_data_frame(
lusid_response, rename_properties: bool = False, column_name_mapping: dict = None
):
# Check if lusid_response is a list of the same objects which all have to_dict() method
if type(lusid_response) == list and len(lusid_response) == 0:
return pd.DataFrame()
el... | Python | nomic_cornstack_python_v1 |
string provides gcp database utility for master application on google cloud
import json
import MySQLdb
from datetime import date
comment noinspection SqlDialectInspection
class GcpDatabase
begin
string provides gcp database utility for master application on google cloud
function __init__ self
begin
set tuple host datab... | """
provides gcp database utility for master application on google cloud
"""
import json
import MySQLdb
from datetime import date
# noinspection SqlDialectInspection
class GcpDatabase:
"""
provides gcp database utility for master application on google cloud
"""
def __init__(self):
host, data... | Python | zaydzuhri_stack_edu_python |
function overlap interval1 interval2
begin
comment Assumption: interval1[0] <= interval2[0]
if interval1 at 0 > interval2 at 0
begin
set tuple interval1 interval2 = tuple interval2 interval1
end
if interval1 at 0 <= interval2 at 0 <= interval1 at 1
begin
return tuple interval1 at 0 max interval1 at 1 interval2 at 1
end... | def overlap(interval1, interval2):
# Assumption: interval1[0] <= interval2[0]
if interval1[0] > interval2[0]:
interval1, interval2 = interval2, interval1
if interval1[0] <= interval2[0] <= interval1[1]:
return interval1[0], max(interval1[1], interval2[1])
else:
... | Python | nomic_cornstack_python_v1 |
function move_ball self
begin
set x = x + ball_vel at 0 * speed_multiplyer
comment pygame treats "up" as decreasing y axis
set y = y - ball_vel at 1 * speed_multiplyer
if left <= 0
begin
set left = 0
set ball_vel at 0 = - ball_vel at 0
end
else
if left >= MAX_BALL_X
begin
set left = MAX_BALL_X
set ball_vel at 0 = - bal... | def move_ball(self):
self.ball.x += self.ball_vel[0] * self.speed_multiplyer
self.ball.y -= self.ball_vel[1] * self.speed_multiplyer # pygame treats "up" as decreasing y axis
if self.ball.left <= 0:
self.ball.left = 0
self.ball_vel[0] = -self.ball_vel[0]
... | Python | nomic_cornstack_python_v1 |
function test_contains
begin
set bounds = call CategoricalBounds categories=set literal string spam string eggs
assert call contains call CategoricalBounds categories=set literal string spam
assert not call contains call CategoricalBounds categories=set literal string spam string foo
assert not call contains call RealB... | def test_contains():
bounds = CategoricalBounds(categories={"spam", "eggs"})
assert bounds.contains(CategoricalBounds(categories={"spam"}))
assert not bounds.contains(CategoricalBounds(categories={"spam", "foo"}))
assert not bounds.contains(RealBounds(0.0, 2.0, ''))
assert not bounds.contains(None)
... | Python | nomic_cornstack_python_v1 |
function pvExistTest self context addr fullname
begin
try
begin
set pv = call _strip_prefix fullname
if pv is not none and pv in _pvs
begin
return pverExistsHere
end
else
begin
return call pvExistTest self context addr fullname
end
end
except any
begin
return pverDoesNotExistHere
end
end function | def pvExistTest(self, context, addr, fullname):
try:
pv = self._strip_prefix(fullname)
if pv is not None and pv in self._pvs:
return cas.pverExistsHere
else:
return SimpleServer.pvExistTest(self, context, addr, fullname)
except:
... | Python | nomic_cornstack_python_v1 |
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import math
class Training
begin
function __init__ self data_handler
begin
set rho_up = 0.95
set activation = string relu
set loss_function = string mse
set target_batches_amount = 10
set neuron_amount = 200
set shuffle = true
set patience = 10
... | import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import math
class Training():
def __init__(self,data_handler):
self.rho_up = 0.95
self.activation = "relu"
self.loss_function = 'mse'
self.target_batches_amount = 10
self.neuron_amount = 200
self.shuffle = True
se... | Python | zaydzuhri_stack_edu_python |
function test_zernike_indexing self
begin
set basis = call ZernikePolynomial L=8 M=4 spectral_indexing=string ansi
assert any
assert not any
set basis = call ZernikePolynomial L=10 M=4 spectral_indexing=string fringe
assert any
assert not any
set basis = call FourierZernikeBasis L=8 M=4 N=0 spectral_indexing=string ans... | def test_zernike_indexing(self):
basis = ZernikePolynomial(L=8, M=4, spectral_indexing="ansi")
assert (basis.modes == [8, 4, 0]).all(axis=1).any()
assert not (basis.modes == [8, 8, 0]).all(axis=1).any()
basis = ZernikePolynomial(L=10, M=4, spectral_indexing="fringe")
assert (bas... | Python | nomic_cornstack_python_v1 |
function test_decoding_2 self
begin
assert equal call decodemorse string ... ----/..- ...- string S<CNF> UV string decoding not correct
end function | def test_decoding_2(self):
self.assertEqual(decodemorse("... ----/..- ...-"), ("S<CNF> UV"),
'decoding not correct') | Python | nomic_cornstack_python_v1 |
function is_legitimate mtrx
begin
set inv_mtrx = list comprehension list row for row in zip *mtrx
return 1 not in mtrx at 0 + mtrx at length mtrx - 1 + inv_mtrx at 0 + inv_mtrx at length inv_mtrx - 1
end function | def is_legitimate(mtrx):
inv_mtrx = [list(row) for row in zip(*mtrx)]
return 1 not in mtrx[0]+mtrx[len(mtrx)-1]+inv_mtrx[0]+inv_mtrx[len(inv_mtrx)-1]
| Python | zaydzuhri_stack_edu_python |
class Node
begin
function __init__ self n
begin
set value = n
set left = none
set right = none
end function
end class
class BTree
begin
function __init__ self n
begin
set root = call Node n
end function
function addNode self n
begin
function addNodeHelper cur_root n
begin
if cur_root == none
begin
set cur_root = call N... | class Node:
def __init__(self,n):
self.value = n
self.left = None
self.right = None
class BTree:
def __init__(self,n):
self.root = Node(n)
def addNode(self,n):
def addNodeHelper(cur_root,n):
if cur_root == None:
cur_root = Node(n)
... | Python | zaydzuhri_stack_edu_python |
function collect_results result
begin
extend results result
end function | def collect_results(result):
results.extend(result) | Python | nomic_cornstack_python_v1 |
function get_top_k cfg
begin
set score = call get_score cfg
set oc = call get_oc cfg
set top_k_open = list
set top_k_close = list
set top_k_global = list
for score_tup in score
begin
set coord_id = score_tup at IX_SCORE_COORD_NAME
set oc_status = oc at coord_id
if length top_k_global < K
begin
append top_k_global co... | def get_top_k(cfg):
score = get_score(cfg)
oc = get_oc(cfg)
top_k_open = []
top_k_close = []
top_k_global = []
for score_tup in score:
coord_id = score_tup[IX_SCORE_COORD_NAME]
oc_status = oc[coord_id]
if (len(top_k_global) < K):
top_k_global.append(coord_id)
... | Python | nomic_cornstack_python_v1 |
for j in range length list
begin
if list at j % 2 == 0
begin
set even = even + 1
end
end
print format string {} valores pares even | for j in range(len(list)):
if list[j]%2 == 0:
even+=1
print('{} valores pares'.format(even))
| Python | zaydzuhri_stack_edu_python |
function sleep_ms milliseconds
begin
Ellipsis
end function | def sleep_ms(milliseconds: int) -> None:
... | Python | nomic_cornstack_python_v1 |
function create_otsu_mask_from_slide slide level
begin
set image = call asarray call get_full_slide level
set image = call remove_alpha_channel image
return call _create_otsu_mask_by_image image
end function | def create_otsu_mask_from_slide(slide: Slide, level) -> np.ndarray:
image = np.asarray(slide.get_full_slide(level))
image = remove_alpha_channel(image)
return _create_otsu_mask_by_image(image) | Python | nomic_cornstack_python_v1 |
comment The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
comment P A H N
comment A P L S I I G
comment Y I R
comment And then read line by line: "PAHNAPLSIIGYIR"
comment Write the code that will t... | # The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
#
# P A H N
# A P L S I I G
# Y I R
# And then read line by line: "PAHNAPLSIIGYIR"
#
# Write the code that will take a string and mak... | Python | zaydzuhri_stack_edu_python |
string Created on Jul 2, 2014 @author: Bert
import sys
set test_cases = open argv at 1 string r
for test in test_cases
begin
if test == string
begin
break
end
set line = split strip test string ,
set word = line at 0
try
begin
set idx = index list word line at 1
end
except ValueError
begin
set idx = - 1
end
end | '''
Created on Jul 2, 2014
@author: Bert
'''
import sys
test_cases = open(sys.argv[1], 'r')
for test in test_cases:
if test == "": break
line = test.strip().split(",")
word = line[0]
try:
idx = list(word).index(line[1])
except ValueError:
idx = -1 | Python | zaydzuhri_stack_edu_python |
from scrapy import Spider , Request
from powell.items import PowellItem
import re
class PowellSpider extends Spider
begin
set name = string powell_spider
set allowed_domains = list string www.powells.com
set start_urls = list string https://www.powells.com/used
function parse self response
begin
comment Find the total ... | from scrapy import Spider, Request
from powell.items import PowellItem
import re
class PowellSpider(Spider):
name = 'powell_spider'
allowed_domains = ['www.powells.com']
start_urls = ['https://www.powells.com/used']
def parse(self, response):
# Find the total number of pages in the result so t... | Python | zaydzuhri_stack_edu_python |
import sys
from PIL import Image
set im = open argv at 1
set rgb_im = call convert string RGB
set tuple width height = size
set outputIm = call new string RGB tuple width height
set pixels = load outputIm
for i in range width
begin
for j in range height
begin
set dividedByTwo = tuple generator expression element // 2 f... | import sys
from PIL import Image
im = Image.open(sys.argv[1])
rgb_im = im.convert('RGB')
width, height = im.size
outputIm = Image.new('RGB',(width,height))
pixels = outputIm.load()
for i in range(width):
for j in range(height):
dividedByTwo = tuple(element//2 for element in rgb_im.getpixel((i,j)))
pixels[i,j] = ... | Python | zaydzuhri_stack_edu_python |
function test_simple_model
begin
comment Train the simple copy task.
set V = 11
set criterion = call LabelSmoothing size=V padding_idx=0 smoothing=0.0
set model = call make_model V V N=2 d_model=512 d_ff=1024
set model_opt = call NoamOpt d_model 1 400 adam parameters model lr=0 betas=tuple 0.9 0.98 eps=1e-09
for epoch ... | def test_simple_model():
# Train the simple copy task.
V = 11
criterion = LabelSmoothing(size=V, padding_idx=0, smoothing=0.0)
model = Transformer.make_model(V, V, N=2, d_model=512, d_ff=1024)
model_opt = NoamOpt(model.src_embed[0].d_model, 1, 400,
torch.optim.Adam(model.para... | Python | nomic_cornstack_python_v1 |
function load_ini_into_dict ini_file json_dict replace_suffix
begin
set config = config parser
comment Enable case-sensitive keys.
set optionxform = str
read config ini_file
for key in config at string Default
begin
set value = config at string Default at key
set key = sub string (.*?)[0-9]+ string \1 key + replace_suf... | def load_ini_into_dict(ini_file: str, json_dict: typing.Dict, replace_suffix: str):
config = ConfigParser()
# Enable case-sensitive keys.
config.optionxform = str
config.read(ini_file)
for key in config['Default']:
value = config['Default'][key]
key = re.sub(r'(.*?)[0-9]+', r'\1',... | Python | nomic_cornstack_python_v1 |
function _move_receptor_to_grid_center self
begin
set lower_receptor_corner = array list comprehension min for i in range 3 dtype=float
set upper_receptor_corner = array list comprehension max for i in range 3 dtype=float
set receptor_box_center = upper_receptor_corner + lower_receptor_corner / 2.0
set grid_center = _o... | def _move_receptor_to_grid_center(self):
lower_receptor_corner = np.array([self._crd[:,i].min() for i in range(3)], dtype=float)
upper_receptor_corner = np.array([self._crd[:,i].max() for i in range(3)], dtype=float)
receptor_box_center = (upper_receptor_corner + lower_receptor_corner) ... | Python | nomic_cornstack_python_v1 |
function timerStart self event
begin
global CONST_CLOCK_SPEED
start logFileTimer CONST_CLOCK_SPEED
end function | def timerStart(self, event):
global CONST_CLOCK_SPEED
self.logFileTimer.start(CONST_CLOCK_SPEED) | Python | nomic_cornstack_python_v1 |
function to_long_int val
begin
return if expression PY2 then call long val else integer val
end function | def to_long_int(val):
return long(val) if six.PY2 else int(val) | Python | nomic_cornstack_python_v1 |
for n in range 10
begin
set s = s + n
end
print s
set n = 10
while n <= 10
begin
print string Prueba
break
end | for n in range(10):
s += n
print(s)
n = 10
while n <= 10:
print("Prueba")
break
| Python | zaydzuhri_stack_edu_python |
function home_page
begin
return call redirect string /register
end function | def home_page():
return redirect('/register') | 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.