code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
string =================================================================================================== This is League of Legends Champion Library The key of the dictionary is the champion name The Value of the key is different skin image file names If more skins updated Enter new champion skins follow by the key (c... | '''
===================================================================================================
This is League of Legends Champion Library
The key of the dictionary is the champion name ... | Python | zaydzuhri_stack_edu_python |
comment --*-- coding=utf-8 --*--
import jieba
import jieba.posseg as psg
import logging
import numpy as np
import codecs
class LAT extends object
begin
string LAT分析:根据语法分析的结果,提取句子中的名词和动词 判断句子相似度时,可根据提取的名词或者动词进行相似度比较
function __init__ self
begin
set interrogative = string 吗 么 呢 什么 多少 多 几 啊 阿
set speech = string i j n nd... | #--*-- coding=utf-8 --*--
import jieba
import jieba.posseg as psg
import logging
import numpy as np
import codecs
class LAT(object):
"""
LAT分析:根据语法分析的结果,提取句子中的名词和动词
判断句子相似度时,可根据提取的名词或者动词进行相似度比较
"""
def __init__(self):
interrogative = u"吗 么 呢 什么 多少 多 几 啊 阿"
speech = u"i j n nd nh ni... | Python | zaydzuhri_stack_edu_python |
function guess_topic lda query features_vec irrelevant verbose=true
begin
set query_doc = list
set doc_topic = list
set topic_most_pr = none
if is instance query str
begin
set query = call clean query
set query = call n_grammize query
for term in query
begin
set weight = call set_weight term irrelevant
if term in fea... | def guess_topic(lda, query, features_vec, irrelevant, verbose=True):
query_doc = []
doc_topic = []
topic_most_pr = None
if isinstance(query,str):
query = clean(query)
query = n_grammize(query)
for term in query:
weight = set_weight(term, irrelevant)
if ter... | Python | nomic_cornstack_python_v1 |
from django.test import SimpleTestCase
from PollingToolApp.models import Response
import pytest
class AnswerTestCase extends SimpleTestCase
begin
function test_model_length self
begin
set test_object = call Response answer=string Very nice web application
assert length answer < 150
end function
function test_model_type... | from django.test import SimpleTestCase
from PollingToolApp.models import Response
import pytest
class AnswerTestCase(SimpleTestCase):
def test_model_length(self):
test_object = Response(answer="Very nice web application")
assert(len(test_object.answer)<150)
def test_model_type(self):
... | Python | zaydzuhri_stack_edu_python |
import random
from string import lowercase , uppercase
import pygame
set SCREEN_SIZE = tuple 550 550
set SCREEN_RADIUS = 5
set RS = character 30
set US = character 31
function get_you_img
begin
set you_tiles = load image string imgs/you.png
comment MAGICAL
set TS = 50
set you_almost = call Surface tuple TS TS SRCALPHA
... | import random
from string import lowercase, uppercase
import pygame
SCREEN_SIZE = (550, 550)
SCREEN_RADIUS = 5
RS = chr(30)
US = chr(31)
def get_you_img():
you_tiles = pygame.image.load("imgs/you.png")
TS = 50 # MAGICAL
you_almost = pygame.Surface((TS, TS), pygame.SRCALPHA)
you_almost.blit(you_tiles... | Python | zaydzuhri_stack_edu_python |
function utilization_queues y_logarithmic=false keys=true
begin
function plot tree plotdef leaf_hook
begin
set gap = call get_gap tree
set gpi = string # utilization set style line 100 lt 1 lc rgb 'black' lw 1.5 dt 3 set arrow 100 from graph 0, first 100 to graph 1, first 100 nohead ls 100 back set ylabel "Utilization ... | def utilization_queues(y_logarithmic=False, keys=True):
def plot(tree, plotdef, leaf_hook):
gap = collectionutil.get_gap(tree)
gpi = """
# utilization
set style line 100 lt 1 lc rgb 'black' lw 1.5 dt 3
set arrow 100 from graph 0, first 100 to graph 1, first 100 ... | Python | nomic_cornstack_python_v1 |
comment 可以用 -1 这个索引来表示最后一个元素:
set L = list string Adam string Lisa string Bart
print L at - 1
comment Bart
comment 类似的,倒数第二用 -2 表示,倒数第三用 -3 表示
comment 使用倒序索引时,也要注意不要越界。会报错。
set L = list 95.5 85 59
print L at - 1
print L at - 2
print L at - 3
comment 59
comment 85
comment 95.5 | #可以用 -1 这个索引来表示最后一个元素:
L = ['Adam', 'Lisa', 'Bart']
print(L[-1])
#Bart
#类似的,倒数第二用 -2 表示,倒数第三用 -3 表示
#使用倒序索引时,也要注意不要越界。会报错。
L = [95.5, 85, 59]
print(L[-1])
print(L[-2])
print(L[-3])
#59
#85
#95.5
| Python | zaydzuhri_stack_edu_python |
function get_all self sort_order=none sort_target=string key
begin
string Get all keys currently stored in etcd. :returns: sequence of (value, metadata) tuples
return get self key=call _encode b'\x00' metadata=true sort_order=sort_order sort_target=sort_target range_end=call _encode b'\x00'
end function | def get_all(self, sort_order=None, sort_target='key'):
"""Get all keys currently stored in etcd.
:returns: sequence of (value, metadata) tuples
"""
return self.get(
key=_encode(b'\0'),
metadata=True,
sort_order=sort_order,
sort_target=sort... | Python | jtatman_500k |
function cli_aggregate **kwargs
begin
set output_keywords_file = pop kwargs string output_keywords_file
set output_format = pop kwargs string output_format
if kwargs at string occurrence_count_filter is none
begin
set kwargs at string occurrence_count_filter = OCCURRENCE_COUNT_FILTER
end
set ret = call aggregate use_pr... | def cli_aggregate(**kwargs):
output_keywords_file = kwargs.pop('output_keywords_file')
output_format = kwargs.pop('output_format')
if kwargs['occurrence_count_filter'] is None:
kwargs['occurrence_count_filter'] = defaults.OCCURRENCE_COUNT_FILTER
ret = aggregate(use_progressbar=True, **kwargs)
... | Python | nomic_cornstack_python_v1 |
function round_to dt hour minute second mode=string round
begin
string Round the given datetime to specified hour, minute and second. :param mode: 'floor' or 'ceiling' .. versionadded:: 0.0.5 message **中文文档** 将给定时间对齐到最近的一个指定了小时, 分钟, 秒的时间上。
set mode = lower mode
if mode not in _round_to_options
begin
raise call ValueErr... | def round_to(dt, hour, minute, second, mode="round"):
"""
Round the given datetime to specified hour, minute and second.
:param mode: 'floor' or 'ceiling'
.. versionadded:: 0.0.5
message
**中文文档**
将给定时间对齐到最近的一个指定了小时, 分钟, 秒的时间上。
"""
mode = mode.lower()
if mode not in _rou... | Python | jtatman_500k |
function verbose_on self
begin
set _verbose = true
return
end function | def verbose_on(self):
self._verbose = True
return | Python | nomic_cornstack_python_v1 |
function from_entries self entries omits=list include_path=false
begin
comment need to make an explicit decision on where to start writing
comment with out that it is completely dependent on where the last
comment seek operation left the pointer in the file
comment could be the beginning, could be the end
comment need... | def from_entries(self, entries, omits=[], include_path=False):
#need to make an explicit decision on where to start writing
#with out that it is completely dependent on where the last
#seek operation left the pointer in the file
#could be the beginning, could be the end
#need to ... | Python | nomic_cornstack_python_v1 |
string memorization O(MN) space O(MN)
class Solution
begin
function minimumDeleteSum self s1 s2
begin
set tuple M N = tuple length s1 length s2
set memo = dict
function helper i j
begin
if i == M and j == N
begin
return 0
end
if tuple i j not in memo
begin
if i == M
begin
set memo at tuple i j = sum generator expressi... | """
memorization
O(MN) space O(MN)
"""
class Solution:
def minimumDeleteSum(self, s1: str, s2: str) -> int:
M,N=len(s1),len(s2)
memo = {}
def helper(i,j):
if i == M and j == N:
return 0
if (i,j) not in memo:
if i == M:
... | Python | zaydzuhri_stack_edu_python |
string Given two linked lists, in reverse order, add them together. 1->2->3 4->5 Equals 5->7->3 321 + 54 ---- 375
from linkedlist import Node , chain_nodes , print_chain
function add l1 l2
begin
string :type l1: ListNode :type l2: ListNode :rtype: ListNode
set carry = 0
set head = l1
while l1 and l2
begin
set tuple pre... | """
Given two linked lists, in reverse order, add them together.
1->2->3
4->5
Equals
5->7->3
321
+ 54
----
375
"""
from linkedlist import Node, chain_nodes, print_chain
def add(l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
carry = 0
head = l1
while l1 and l... | Python | zaydzuhri_stack_edu_python |
comment ATO Script Python 2.7
comment Updated 20191112
import arcpy
import math
comment Define Input Variables
comment Location of TAZ polygons
set TAZ = string Geodatabase\TAZ2017\TAZ.shp
comment Location of Socioeconomic table with job count and household count for each TAZ
set SE = string SE_File_v83_SE23_Net23.dbf
... | #ATO Script Python 2.7
#Updated 20191112
import arcpy
import math
#######################
#Define Input Variables
#Location of TAZ polygons
TAZ = r"Geodatabase\TAZ2017\TAZ.shp"
#Location of Socioeconomic table with job count and household count for each TAZ
SE = "SE_File_v83_SE23_Net23.dbf"
#Location of TAZ to TAZ... | Python | zaydzuhri_stack_edu_python |
function logfile targetfile=string ros.log
begin
string Set the file for Quilt to log to targetfile: Change the file to log to.
set log = call getLogger __name__
call basicConfig filename=string targetfile
end function | def logfile(targetfile="ros.log"):
"""
Set the file for Quilt to log to
targetfile:
Change the file to log to.
"""
log = logging.getLogger(__name__)
log.basicConfig(filename=str(targetfile)) | Python | jtatman_500k |
function get_literal_path path_or_autoloader
begin
try
begin
return path
end
except AttributeError
begin
assert type path_or_autoloader is str msg string beard_path is not a str or an AutoLoader!
return path_or_autoloader
end
end function | def get_literal_path(path_or_autoloader):
try:
return path_or_autoloader.path
except AttributeError:
assert type(path_or_autoloader) is str, "beard_path is not a str or an AutoLoader!"
return path_or_autoloader | Python | nomic_cornstack_python_v1 |
function frequency_from_semitones freq1 interval
begin
return call frequency_from_cents freq1 100.0 * interval
end function | def frequency_from_semitones(freq1, interval):
return frequency_from_cents(freq1, 100.0*interval) | Python | nomic_cornstack_python_v1 |
comment For CS189 at UC Berkeley
comment Training a digit classifier using a soft margin SVM
comment Dan March, Spring 2016
import numpy as np
from scipy import io
from sklearn import svm
from sklearn.metrics import confusion_matrix
import random
from random import shuffle
import matplotlib.pyplot as plot
function prob... | #For CS189 at UC Berkeley
#Training a digit classifier using a soft margin SVM
#Dan March, Spring 2016
import numpy as np
from scipy import io
from sklearn import svm
from sklearn.metrics import confusion_matrix
import random
from random import shuffle
import matplotlib.pyplot as plot
def problem_one(matrix_size=0):
... | Python | zaydzuhri_stack_edu_python |
function factors self
begin
set X = list comprehension variance i 2 for i in range nvar
set factors = list call Factor list exp c
comment TODO: exclude if zero? or exclude if inf/-inf, or if in "assigned", or?
set factors = factors + list comprehension exp for tuple i th in enumerate h if dims at i > 1
set L = call co... | def factors(self):
X = [Var(i,2) for i in range(self.nvar)]
factors = [Factor([],np.exp(self.c))]
# TODO: exclude if zero? or exclude if inf/-inf, or if in "assigned", or?
factors = factors + [Factor([X[i]],[-th,th]).exp() for i,th in enumerate(self.h) if self.dims[i]>1]
L = coo(self.L)
factors... | Python | nomic_cornstack_python_v1 |
import sys , getopt , os , time
comment Color Class
class color
begin
set PURPLE = string [95m
set CYAN = string [96m
set DARKCYAN = string [36m
set BLUE = string [94m
set GREEN = string [92m
set YELLOW = string [93m
set RED = string [91m
set BOLD = string [1m
set UNDERLINE = string [4m
set END = string [0m
e... | import sys, getopt, os, time
# Color Class
class color:
PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
# Global Variables
verbose = False
indir = ""
... | Python | zaydzuhri_stack_edu_python |
function create_run_from_pipeline_func self pipeline_func arguments run_name=none experiment_name=none pipeline_conf=none namespace=none mode=V1_LEGACY launcher_image=none pipeline_root=none enable_caching=none service_account=none
begin
if pipeline_root is not none and mode == V1_LEGACY
begin
raise call ValueError str... | def create_run_from_pipeline_func(
self,
pipeline_func: Callable,
arguments: Mapping[str, str],
run_name: Optional[str] = None,
experiment_name: Optional[str] = None,
pipeline_conf: Optional[dsl.PipelineConf] = None,
namespace: Optional[str] = None,
mode: ... | Python | nomic_cornstack_python_v1 |
function _step self a
begin
set tuple state rew done info = call _step a
set render = call get_render_obs
return tuple render sum rewards boolean done dict
end function | def _step(self, a):
state, rew, done, info = super()._step(a)
render = self.get_render_obs()
return render, sum(self.rewards), bool(done), {} | Python | nomic_cornstack_python_v1 |
function clean_fs fs
begin
set fs = call drop_duplicates
set fs = sort values fs list string Date axis=0
set fs at string Date_m = fs at string Date
set fs at string Date = fs at string Date / 1000
set fs at string Date = as type fs at string Date string datetime64[s]
set rolling_f = dict
set f_col = list
string for ... | def clean_fs(fs):
fs =fs.drop_duplicates()
fs = fs.sort_values(['Date'],axis=0)
fs['Date_m'] = fs['Date']
fs['Date'] = fs['Date']/1000
fs['Date'] = fs['Date'].astype('datetime64[s]')
rolling_f = {}
f_col = []
"""
for i in fs.iterrows():
coin = i[1][1]
if(coin in roll... | Python | nomic_cornstack_python_v1 |
comment Problem No.: 918
comment Solver: Jinmin Goh
comment Date: 20200516
comment URL: https://leetcode.com/problems/maximum-sum-circular-subarray/
import sys
class Solution
begin
function maxSubarraySumCircular self A
begin
if not A
begin
return 0
end
set totalSum = sum A
set curMax = A at 0
set curSumMax = A at 0
se... | # Problem No.: 918
# Solver: Jinmin Goh
# Date: 20200516
# URL: https://leetcode.com/problems/maximum-sum-circular-subarray/
import sys
class Solution:
def maxSubarraySumCircular(self, A: List[int]) -> int:
if not A:
return 0
totalSum = sum(A)
curMax = A[0]
... | Python | zaydzuhri_stack_edu_python |
comment coding=utf-8
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QListWidget , QListWidgetItem , QTreeWidgetItem
from Article import Blog
class ArticleItem
begin
function __init__ self blog *__args
begin
set __blog = blog
end function
function getBlog self
begin
return __blog
end function
end class
class Li... | # coding=utf-8
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QListWidget, QListWidgetItem, QTreeWidgetItem
from Article import Blog
class ArticleItem():
def __init__(self,blog:Blog, *__args):
self.__blog=blog
def getBlog(self):
return self.__blog
class ListWidgetItem(QListWidgetIte... | Python | zaydzuhri_stack_edu_python |
comment pylint: disable=invalid-name
function do_DEBUG *module
begin
if SERVER
begin
return call do_DEBUG *module
end
return false
end function | def do_DEBUG(*module): # pylint: disable=invalid-name
if SERVER:
return SERVER.do_DEBUG(*module)
return False | Python | nomic_cornstack_python_v1 |
function get_voter_parties
begin
return list list string P string G string G string G string G list string G string P string P string P string G list string G string P string G string G string G list string G string G string G string P string P list string P string G string P string G string P
end function | def get_voter_parties():
return [['P', 'G', 'G', 'G', 'G'],
['G', 'P', 'P', 'P', 'G'],
['G', 'P', 'G', 'G', 'G'],
['G', 'G', 'G', 'P', 'P'],
['P', 'G', 'P', 'G', 'P']] | Python | nomic_cornstack_python_v1 |
function make_dndlM_spline self
begin
set bounds = log 10 ^ l10M_bounds
set lM = linear space bounds at 0 bounds at 1 num=100
set dndlM = array list comprehension call dndlM lMi for lMi in lM
set dndlM_spline = call IUS lM dndlM
return tuple lM dndlM
end function | def make_dndlM_spline(self):
bounds = np.log(10**self.l10M_bounds)
lM = np.linspace(bounds[0], bounds[1], num=100)
dndlM = np.array([self.dndlM(lMi) for lMi in lM])
self.dndlM_spline = IUS(lM, dndlM)
return lM, dndlM | Python | nomic_cornstack_python_v1 |
comment ________________ANIMATION TRANSFER SCRIPT__________________
import sys
from PySide2 import QtCore
from PySide2 import QtWidgets
import pymel.core as pm
import itertools
import maya.cmds as cmds
import pymel.core.datatypes as dt
comment LISTS
set sourceList = list
set targetList = list
comment FUNCTIONS
functi... | #________________ANIMATION TRANSFER SCRIPT__________________
import sys
from PySide2 import QtCore
from PySide2 import QtWidgets
import pymel.core as pm
import itertools
import maya.cmds as cmds
import pymel.core.datatypes as dt
#LISTS
sourceList = []
targetList = []
#FUNCTIONS
def getJointList(currentJ... | Python | zaydzuhri_stack_edu_python |
function BaseMode object
begin
function __init__ self **kwargs
begin
string
comment Make a dict of the status objects that the mode requires to
set requiredStatus = dict
end function
function visits_to_observe self observatory_status
begin
pass
end function
end function | def BaseMode(object):
def __init__(self, **kwargs):
"""
"""
# Make a dict of the status objects that the mode requires to
self.requiredStatus = {}
def visits_to_observe(self, observatory_status):
pass | Python | nomic_cornstack_python_v1 |
comment !/bin/python
import re
from lxml.html import fromstring , Element
import argparse
import sys
import numpy as np
from scipy.optimize import linear_sum_assignment
from dataclasses import dataclass , field
from typing import List , Dict
decorator dataclass
class Question
begin
set xml : Element = none
set points :... | #!/bin/python
import re
from lxml.html import fromstring, Element
import argparse
import sys
import numpy as np
from scipy.optimize import linear_sum_assignment
from dataclasses import dataclass, field
from typing import List, Dict
@dataclass
class Question:
xml : Element = None
points : int = 1
answers ... | Python | zaydzuhri_stack_edu_python |
function R n start p
begin
if n == 0
begin
print p at slice : - 1 :
end
else
begin
for j in range start n + 1
begin
call R n - j j p + string j + string +
end
end
end function
call R integer input 1 string | def R(n, start, p):
if n == 0:
print(p[:-1])
else:
for j in range(start, n + 1):
R(n - j, j, p + str(j) + '+')
R(int(input()), 1, '')
| Python | zaydzuhri_stack_edu_python |
import collections
import datetime
comment from calendar import date
from datetime import datetime
from time import strftime
set Cmd = named tuple string Cmd string action text
set Room = named tuple string Room string room_num available reservation
set Reservation = named tuple string Reservation string confirmation r... | import collections
import datetime
##from calendar import date
from datetime import datetime
from time import strftime
Cmd = collections.namedtuple('Cmd', 'action text')
Room = collections.namedtuple('Room', 'room_num available reservation')
Reservation = collections.namedtuple('Reservation', 'confirmation room_num ar... | Python | zaydzuhri_stack_edu_python |
string Processing data type data type 1 (generate by getLocInfo()) type => dict : { dict : int } data [ user ] : { location 1 : # of visit times, location 2 : # of visit times, . . . location n : # of visit times } data type 2 (generate by locVisit()) type => dict : { dict : int } data [ location ] : { user 1 : # of vi... | '''
Processing data type
data type 1 (generate by getLocInfo())
type => dict : { dict : int }
data [ user ] : { location 1 : # of visit times,
location 2 : # of visit times,
.
.
.
location n : # of visit times }
data type 2 (generate by locVisit())
type... | Python | zaydzuhri_stack_edu_python |
function validate_instance self release_meta sync_releases=false enable_terminal_constraint=false
begin
call _validate_declared_tdc_releases release_meta
comment Validate specific versioned instance
for tuple ver versioned_ins in items versioned_instances
begin
print call joinpath ver
call validate_versioned_instance r... | def validate_instance(self, release_meta, sync_releases=False, enable_terminal_constraint=False):
self._validate_declared_tdc_releases(release_meta)
# Validate specific versioned instance
for ver, versioned_ins in self.versioned_instances.items():
print(self.instance_folder.joinpath(... | Python | nomic_cornstack_python_v1 |
function tokenize self string
begin
comment adapt the string to the task
set string = replace string string string
set endToken = string END
if ends with string endToken
begin
set endToken = string ENDS
end
set string = string + endToken
set endToken = left strip endToken string
comment use the external process to tok... | def tokenize(self, string):
# adapt the string to the task
string = string.replace("\n", " ")
endToken = " END"
if string.endswith(endToken):
endToken = " ENDS"
string = string + endToken
endToken = endToken.lstrip(" ")
# use the external process to tokenize the string
res = []
self.__process.stdi... | Python | nomic_cornstack_python_v1 |
function _initialize_parser_keys self
begin
set source_role_marker = SOURCE
set target_role_marker = TARGET
set rack_shape_agg = call get_root_aggregate IRackShape
set filter = none
set allowed_rack_dimensions = list comprehension tuple number_rows number_columns for rs in rack_shape_agg
end function | def _initialize_parser_keys(self):
self.parser.source_role_marker = TRANSFER_ROLES.SOURCE
self.parser.target_role_marker = TRANSFER_ROLES.TARGET
rack_shape_agg = get_root_aggregate(IRackShape)
rack_shape_agg.filter = None
self.parser.allowed_rack_dimensions = [(rs.number_rows,
... | Python | nomic_cornstack_python_v1 |
comment https://www.acmicpc.net/problem/13913
import sys
class Node
begin
function __init__ self value parent
begin
set value = value
set parent = parent
set next_node = none
end function
function chaining self child_node
begin
set next_node = child_node
end function
end class
if __name__ == string __main__
begin
set t... | # https://www.acmicpc.net/problem/13913
import sys
class Node:
def __init__(self, value, parent):
self.value = value
self.parent = parent
self.next_node = None
def chaining(self, child_node):
self.next_node = child_node
if __name__ == '__main__':
me, you = tuple(map(int... | Python | zaydzuhri_stack_edu_python |
comment Import constant from TensorFlow
from tensorflow import constant
string https://campus.datacamp.com/courses/introduction-to-tensorflow-in-python/introduction-to-tensorflow?ex=2
import numpy as np
comment 3D Array
set credit_numpy = array list list list 1 2 3 list 4 5 6 list list 1 2 3 list 4 5 6
print credit_num... | # Import constant from TensorFlow
from tensorflow import constant
"""
https://campus.datacamp.com/courses/introduction-to-tensorflow-in-python/introduction-to-tensorflow?ex=2
"""
import numpy as np
# 3D Array
credit_numpy = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(credit_numpy)
credit_numpy ... | Python | zaydzuhri_stack_edu_python |
class ListNode extends object
begin
function __init__ self val=0 next=none
begin
set val = val
set next = next
end function
end class
class Solution extends object
begin
function reverseBetween self head left right
begin
string :type head: ListNode :type left: int :type right: int :rtype: ListNode
set dummyhead = call ... | class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def reverseBetween(self, head, left, right):
"""
:type head: ListNode
:type left: int
:type right: int
:rtype: ListNode
"""
... | Python | zaydzuhri_stack_edu_python |
string Starter code for CSC108 Assignment 1 Winter 2020
comment Game setting constants
set SECTION_LENGTH = 3
set ANSWER = string CATDOGFOXEMU
comment Move constants
set SWAP = string S
set ROTATE = string R
set CHECK = string C
function get_section_start num
begin
string Return the first index of the section matches t... | """Starter code for CSC108 Assignment 1 Winter 2020"""
# Game setting constants
SECTION_LENGTH = 3
ANSWER = 'CATDOGFOXEMU'
# Move constants
SWAP = 'S'
ROTATE = 'R'
CHECK = 'C'
def get_section_start(num: int) -> int:
""" Return the first index of the section matches to num.
>>> get_section_start(1)
0
... | Python | zaydzuhri_stack_edu_python |
import numpy as np
from PIL import Image
function conv color core arr
begin
set exp_list = zeros tuple shape at 0 + 2 shape at 1 + 2 dtype=int
for i in range 1 shape at 0 + 1
begin
for j in range 1 shape at 1 + 1
begin
set exp_list at i at j = arr at i - 1 at j - 1 at color
end
end
comment expending original list(every... | import numpy as np
from PIL import Image
def conv(color, core, arr):
exp_list = np.zeros((arr.shape[0] + 2, arr.shape[1] + 2), dtype=int)
for i in range(1, arr.shape[0] + 1):
for j in range(1, arr.shape[1] + 1):
exp_list[i][j] = arr[i - 1][j - 1][color]
for i in range(1, arr.shape[0]... | Python | zaydzuhri_stack_edu_python |
function is_uniform self
begin
return boolean __uniform
end function | def is_uniform(self) -> bool:
return bool(self.__uniform) | Python | nomic_cornstack_python_v1 |
function getMatchups soup _cshTeam url
begin
set x = find all soup text=compile _cshTeam
set _csh_wins = 0
set _csh_losses = 0
set _csh_ties = 0
comment sportContent = soup.find_all("div", { "class" : "popover-content" })[0]
comment li = sportContent.find_all("li")[2]
comment _sport = li.find_next("a").get_text()
set t... | def getMatchups(soup, _cshTeam, url):
x = soup.find_all(text=re.compile(_cshTeam))
_csh_wins = 0
_csh_losses = 0
_csh_ties = 0
#sportContent = soup.find_all("div", { "class" : "popover-content" })[0]
#li = sportContent.find_all("li")[2]
#_sport = li.find_next("a").get_text()
title = soup... | Python | nomic_cornstack_python_v1 |
function __file__ self
begin
return __file__
end function | def __file__(self):
return __file__ | Python | nomic_cornstack_python_v1 |
function SetBreakpoint self enable
begin
set callResult = call _Call string SetBreakpoint enable
end function | def SetBreakpoint(self, enable):
callResult = self._Call("SetBreakpoint", enable) | Python | nomic_cornstack_python_v1 |
from typing import Optional
import sqlite3
from fastapi import FastAPI
from fastapi.params import Query , Body
import google_books
set app = call FastAPI
set DATABASE_URL = string ./fastapi_sample.db
decorator get app string /
function read_root
begin
return dict string Hello string World
end function
decorator get app... | from typing import Optional
import sqlite3
from fastapi import FastAPI
from fastapi.params import Query,Body
import google_books
app = FastAPI()
DATABASE_URL="./fastapi_sample.db"
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = Query(Non... | Python | zaydzuhri_stack_edu_python |
comment coding='utf-8'
import datetime
function stamp
begin
set now = now
set StyleTime = string format time now string %Y-%m-%d %H:%M:%S
return StyleTime
end function | # coding='utf-8'
import datetime
def stamp():
now = datetime.datetime.now()
StyleTime = now.strftime("%Y-%m-%d %H:%M:%S")
return StyleTime
| Python | zaydzuhri_stack_edu_python |
import csv
from csv_comparison_package.error_handler import AppErrorHandler
from csv_comparison_package.decorator import call_each
from csv_comparison_package import Compare
decorator call_each
function set_original_header comparable
begin
with open file_name encoding=encoding as csv_file
begin
set reader = dict reader... | import csv
from csv_comparison_package.error_handler import AppErrorHandler
from csv_comparison_package.decorator import call_each
from csv_comparison_package import Compare
@call_each
def set_original_header(comparable: Compare):
with open(comparable.file_name, encoding=comparable.encoding) as csv_file:
... | Python | zaydzuhri_stack_edu_python |
function format_labels y
begin
set n = min y
set yy = zeros tuple shape at 0 max y - n + 1 dtype=float32
for tuple i label in enumerate y
begin
set yy at tuple i label - n = 1
end
return yy
end function | def format_labels(y):
n = np.min(y)
yy = np.zeros((y.shape[0], np.max(y) - n + 1), dtype=np.float32)
for i, label in enumerate(y):
yy[i, label - n] = 1
return yy | Python | nomic_cornstack_python_v1 |
function HandleApply self
begin
set result = call GetData
return true
end function | def HandleApply(self):
self.result = self._diary_entry_text.GetData()
return True | Python | nomic_cornstack_python_v1 |
function get_tweet_map_boundaries tweetLats tweetLons
begin
set tolerance = 5
set minLon = min tweetLons - tolerance
set maxLon = max tweetLons + tolerance
set minLat = min tweetLats - tolerance
set maxLat = max tweetLats + tolerance
return tuple minLon maxLon minLat maxLat
end function | def get_tweet_map_boundaries(tweetLats, tweetLons):
tolerance = 5
minLon = min(tweetLons) - tolerance
maxLon = max(tweetLons) + tolerance
minLat = min(tweetLats) - tolerance
maxLat = max(tweetLats) + tolerance
return(minLon, maxLon, minLat, maxLat) | Python | nomic_cornstack_python_v1 |
function get_and_publish_timeseries data metadata
begin
set metric_type = data at string metric at string type
set metric_kind = data at string metric at string metricKind
set metric_val_type = data at string metric at string valueType
set end_time_str = data at string end_time
set start_time_str = data at string start... | def get_and_publish_timeseries(data, metadata):
metric_type = data["metric"]["type"]
metric_kind = data["metric"]["metricKind"]
metric_val_type = data["metric"]["valueType"]
end_time_str = data["end_time"]
start_time_str = data["start_time"]
project_id = data["project_id"]
logging.debug(
... | Python | nomic_cornstack_python_v1 |
function encrypt self message
begin
set blocks = call string_to_blocks message
return list comprehension call _encrypt_block block for block in blocks
end function | def encrypt(self, message):
blocks = IDEA.string_to_blocks(message)
return [self._encrypt_block(block) for block in blocks] | Python | nomic_cornstack_python_v1 |
function number_of_posts
begin
set posts = all
return call jsonify dict string count length posts
end function | def number_of_posts():
posts = Post.query.order_by(Post.timestamp.desc()).all()
return jsonify({"count": len(posts)}) | Python | nomic_cornstack_python_v1 |
function trade_profitability self direction entry_price exit_price
begin
set tuple quantity entry_comm = call calculate_quantity_and_commission direction entry_price
set exit_comm = call determine_commission quantity exit_price
set total_comm = entry_comm + exit_comm
return exit_price - entry_price * quantity - total_c... | def trade_profitability(self, direction, entry_price, exit_price):
quantity, entry_comm = self.risk.calculate_quantity_and_commission(direction, entry_price)
exit_comm = self.risk.determine_commission(quantity, exit_price)
total_comm = entry_comm + exit_comm
return (exit_price - entry_pr... | Python | nomic_cornstack_python_v1 |
function check_threshold count warn crit logger
begin
set warn = integer warn
set crit = integer crit
if count < warn
begin
set msg = format string Normal: Resource Count={} is less than the warning={} level count warn
info msg
print msg
exit 0
end
else
if count >= warn and count < crit
begin
set msg = format string Wa... | def check_threshold(count, warn, crit, logger):
warn = int(warn)
crit = int(crit)
if count < warn:
msg = ("Normal: Resource Count={} is less than the warning={} level".format(count, warn))
logger.info(msg)
print(msg)
sys.exit(0)
elif count >= warn and count < crit:
... | Python | nomic_cornstack_python_v1 |
function cast *args
begin
return call itkLevelSetFunctionWithRefitTermID3SINBNID33_cast *args
end function | def cast(*args):
return _itkSparseFieldFourthOrderLevelSetImageFilterPython.itkLevelSetFunctionWithRefitTermID3SINBNID33_cast(*args) | Python | nomic_cornstack_python_v1 |
function Pv2T self P v
begin
return P * v / R
end function | def Pv2T(self, P, v):
return P*v/self.R | Python | nomic_cornstack_python_v1 |
function load_data
begin
comment trans_dict is used for changing the given names into standardized names.
set trans_dict = dict string chr1 string 1 ; string chr2 string 2 ; string chr3 string 3 ; string chr4 string 4 ; string chr5 string 5 ; string chr6 string 6 ; string chr7 string 7 ; string chr8 string 8 ; string c... | def load_data() -> list:
# trans_dict is used for changing the given names into standardized names.
trans_dict = {"chr1": "1", "chr2": "2", "chr3": "3", "chr4": "4", "chr5": "5", "chr6": "6", "chr7": "7",
"chr8": "8", "chr9": "9", "chr10": "10", "chr11": "11", "chr12": "12", "chr13": "13", "ch... | Python | nomic_cornstack_python_v1 |
function test_rshift_basic_array_array_none_e2 self
begin
set pydataout = list comprehension call pyshift x y for tuple x y in zip data1 data3
set expected = pydataout at slice 0 : limited : + list data1 at slice limited : :
call rshift data1 data3 maxlen=limited
for tuple dataoutitem expecteditem in zip data1 expec... | def test_rshift_basic_array_array_none_e2(self):
pydataout = [self.pyshift(x, y) for (x, y) in zip(self.data1, self.data3)]
expected = pydataout[0:self.limited] + list(self.data1)[self.limited:]
arrayfunc.rshift(self.data1, self.data3, maxlen=self.limited )
for dataoutitem, expecteditem in zip(self.data1, exp... | Python | nomic_cornstack_python_v1 |
function username self
begin
return get pulumi self string username
end function | def username(self) -> Any:
return pulumi.get(self, "username") | Python | nomic_cornstack_python_v1 |
function guardar4
begin
global h x j i y i2 x2 contgasonvl4 contgasonvl44 contpuntosnvl4 contpuntosnvl44 can4 archivo
set archivo = open string partida4.txt string w
set posix1 = call coords x at 0
set posix11 = call coords x at 1
set posix2 = call coords x2 at 0
set posix22 = call coords x2 at 1
if contgasonvl4 > 0 an... | def guardar4():
global h,x,j,i,y,i2,x2,contgasonvl4,contgasonvl44,contpuntosnvl4,contpuntosnvl44,can4,archivo
archivo = open("partida4.txt", "w")
posix1=can4.coords(x)[0]
posix11=can4.coords(x)[1]
posix2=can4.coords(x2)[0]
posix22=can4.coords(x2)[1]
if(contgasonvl4>0 and contgasonvl44... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Fri Feb 1 10:36:33 2019 Setup database connection, teardown function and CLI function @author: Sam Wan
import sqlite3
import click
comment g stores data for multiple access
from flask import current_app , g
from flask.cli import with_appcontext
comment connection tied to ... | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 1 10:36:33 2019
Setup database connection, teardown function and CLI function
@author: Sam Wan
"""
import sqlite3
import click
from flask import current_app, g #g stores data for multiple access
from flask.cli import with_appcontext
#connection tied to request
def get... | Python | zaydzuhri_stack_edu_python |
function resize_visible_flirone visible_image thermal_image
begin
set tuple h_visible w_visible _ = shape
set tuple h_thermal w_thermal = shape
comment 9.0
set scale = h_visible / h_thermal
set scale = integer scale
set crop_width = w_visible - w_thermal * scale
set visible_image = visible_image at tuple slice : : s... | def resize_visible_flirone(visible_image, thermal_image):
h_visible, w_visible, _ = visible_image.shape
h_thermal, w_thermal = thermal_image.shape
scale = h_visible / h_thermal # 9.0
scale = int(scale)
crop_width = w_visible - w_thermal * scale
visible_image = visible_image[:, crop_width // 2:-... | Python | nomic_cornstack_python_v1 |
function one_hot_encode Y classes
begin
if not is instance Y ndarray or length Y == 0
begin
return none
end
if not is instance classes int or classes < max Y + 1
begin
return none
end
set A = zeros tuple classes shape at 0
for tuple i m in enumerate Y
begin
set A at m at i = 1
end
return A
end function | def one_hot_encode(Y, classes):
if not isinstance(Y, np.ndarray) or len(Y) == 0:
return None
if not isinstance(classes, int) or classes < np.max(Y) + 1:
return None
A = np.zeros((classes, Y.shape[0]))
for i, m in enumerate(Y):
A[m][i] = 1
return A | Python | nomic_cornstack_python_v1 |
import time
import datetime
function cambiar_numeros numero
begin
set cambios = dict string 1 string 9 ; string 2 string 8 ; string 3 string 7 ; string 4 string 6 ; string 5 string 0 ; string 0 string 5 ; string 6 string 4 ; string 7 string 3 ; string 8 string 2 ; string 9 string 1
set a = string
for char in numero
be... | import time
import datetime
def cambiar_numeros(numero):
cambios = {"1": "9", "2": "8", "3": "7", "4": "6", "5": "0", "0": "5",
"6": "4", "7": "3", "8": "2", "9": "1"}
a = ""
for char in numero:
a += cambios[char]
return a[::-1]
def numeros_primos():
i = 2
... | Python | zaydzuhri_stack_edu_python |
function __init__ self coinbase_data coinbase_value wallet_address transactions previous_block_hash difficulty_bits target time
begin
set pubkey = call p2pkh_address_to_pubkey_hash wallet_address
set coinbase = call serialize_coinbase_transaction pubkey coinbase_data coinbase_value
set coinbase_tx = call Transaction co... | def __init__(self, coinbase_data, coinbase_value, wallet_address,
transactions, previous_block_hash, difficulty_bits,
target, time):
pubkey = p2pkh_address_to_pubkey_hash(wallet_address)
coinbase = serialize_coinbase_transaction(pubkey, coinbase_data,
... | Python | nomic_cornstack_python_v1 |
import pygame
from objects import *
from helps import *
from menu import Menu , ButtonType
class Lifes
begin
string Class describes lifes Attribute: lifes number of lifes
function __init__ self lifes
begin
set lifes = lifes
set text = call render string Lifes: + string lifes 1 FONT_COLOR
end function
function decrement... | import pygame
from objects import *
from helps import *
from menu import Menu, ButtonType
class Lifes:
"""
Class describes lifes
Attribute:
lifes number of lifes
"""
def __init__(self, lifes: int):
self.lifes = lifes
self.text = font_renderer.render("Lifes: " + str(self... | Python | zaydzuhri_stack_edu_python |
from typing import *
class Solution
begin
function findRotateSteps self ring key
begin
function l2n a
begin
return ordinal a - ordinal string a
end function
set log = list comprehension list for i in range 26
for i in range length ring
begin
append log at call l2n ring at i i
end
set mem = list comprehension dict for... | from typing import *
class Solution:
def findRotateSteps(self, ring: str, key: str) -> int:
def l2n(a):
return ord(a)-ord('a')
log=[[] for i in range(26)]
for i in range(len(ring)):
log[l2n(ring[i])].append(i)
mem=[{} for j in range(len(key)+1)]
m... | Python | zaydzuhri_stack_edu_python |
import time
import pyautogui
import winsound
sleep 2
set pos = call position
call Beep 750 250
while 1
begin
if call position != pos
begin
exit
end
sleep 0.01
call click
sleep 0.01
call typewrite string you are a cutie
sleep 0.01
call typewrite string
end | import time
import pyautogui
import winsound
time.sleep(2)
pos = pyautogui.position()
winsound.Beep(750, 250)
while 1:
if pyautogui.position() != pos:
exit()
time.sleep(0.01)
pyautogui.click()
time.sleep(0.01)
pyautogui.typewrite("you are a cutie")
time.sleep(0.01)
pyautogui.typewrite("\n") | Python | zaydzuhri_stack_edu_python |
for i in range n
begin
set records at s at i + 100 = records at s at i + 100 + 1
end
for tuple index value in enumerate records
begin
if value != 0
begin
for j in range value
begin
print index - 100 end=string
end
end
end | for i in range(n):
records[s[i] + 100] += 1
for index, value in enumerate(records):
if value != 0:
for j in range(value):
print(index - 100, end=' ')
| Python | zaydzuhri_stack_edu_python |
import os
from flask import Flask , redirect , render_template , request
from werkzeug.utils import secure_filename
from uploadToS3 import s3Helper
comment Basic File Upload Website
set s3helper = call s3Helper
set app = call Flask __name__
function allowed_file filename
begin
return ends with lower filename tuple stri... | import os
from flask import Flask, redirect, render_template, request
from werkzeug.utils import secure_filename
from uploadToS3 import s3Helper
#Basic File Upload Website
s3helper = s3Helper()
app = Flask(__name__)
def allowed_file(filename):
return filename.lower().endswith((".pdf",".txt", ".xml"))
@app.route... | Python | zaydzuhri_stack_edu_python |
function plot_title stellar_mass central_density density_unit step_size polytropic_index mean_molecular_weight title_prefix
begin
set title = string { title_prefix } Solution of Lane-Emden equation, n= { polytropic_index } , M= { stellar_mass } , $\rho_c=$ { value } { density_unit } , h= { step_size } , $\mu=$ { mean_m... | def plot_title(stellar_mass, central_density, density_unit,
step_size, polytropic_index, mean_molecular_weight,
title_prefix):
title = (
f"{title_prefix}"
"Solution of Lane-Emden equation,\n"
f"n={polytropic_index}, "
f"M={stellar_mass:.2G}, "
r... | Python | nomic_cornstack_python_v1 |
import os
import cv2
import cv2.cv as cv
import math
import numpy as np
import numpy.linalg as la
from imgStitcher import stitcher , stitcher_firstFrame
change directory string C:/Users/Mufiz/Desktop/CS4243 Project/videoStitch
comment 7200
set TOTAL_IMAGES = 230
set VIDEO_FORMAT = string mp4
set IMG_FORMAT = string png... | import os
import cv2
import cv2.cv as cv
import math
import numpy as np
import numpy.linalg as la
from imgStitcher import stitcher, stitcher_firstFrame
os.chdir('C:/Users/Mufiz/Desktop/CS4243 Project/videoStitch')
TOTAL_IMAGES = 230 #7200
VIDEO_FORMAT = "mp4"
IMG_FORMAT = "png"
FINAL_IMG = "frame_"
RESIZE_FACTOR... | Python | zaydzuhri_stack_edu_python |
function _report_legacy self **kwargs
begin
if ignore_report
begin
return
end
set kwargs = call _auto_fill_metrics kwargs
set result = call TrainingResult type=REPORT data=kwargs
comment Add result to a thread-safe queue.
put result block=true
comment Acquire lock to stop the training thread until main thread
comment t... | def _report_legacy(self, **kwargs):
if self.ignore_report:
return
kwargs = self._auto_fill_metrics(kwargs)
result = TrainingResult(type=TrainingResultType.REPORT, data=kwargs)
# Add result to a thread-safe queue.
self.result_queue.put(result, block=True)
#... | Python | nomic_cornstack_python_v1 |
comment Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements.
comment For example:
comment unique_in_order('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B']
comme... | #Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements.
#For example:
#unique_in_order('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B']
#unique_in_order('ABBCcA... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Tue May 7 12:32:12 2019 @author: Atiqah
from math import cos , sin , tan , sqrt , pi , e
import matplotlib.pyplot as plt
import numpy as np
comment from All_dic_Parameters import Parameters as par
function flightprofile Aircraft ISA
begin
comment Description: Calculate th... | # -*- coding: utf-8 -*-
"""
Created on Tue May 7 12:32:12 2019
@author: Atiqah
"""
from math import cos, sin, tan, sqrt, pi, e
import matplotlib.pyplot as plt
import numpy as np
#from All_dic_Parameters import Parameters as par
def flightprofile(Aircraft,ISA):
#Description: Calculate the distance for the take-off p... | Python | zaydzuhri_stack_edu_python |
function _parse_args
begin
set parser = call ArgumentParser
call add_argument string out nargs=string * help=string Create a plot for all provided output files
call add_argument string --yscale string -y help=string Y-axis scale default=string linear
call add_argument string --hits help=string Draw hits dest=string hit... | def _parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('out', nargs='*', help='Create a plot for all provided'
' output files')
parser.add_argument('--yscale', '-y', help='Y-axis scale',
default='linear')
parser.add_argument('--hits', he... | Python | nomic_cornstack_python_v1 |
function chromosome_heatmap adata groupby=string cnv_leiden use_rep=string cnv cmap=string bwr figsize=tuple 16 10 show=none save=none **kwargs
begin
if groupby == string cnv_leiden and string cnv_leiden not in columns
begin
raise call ValueError string 'cnv_leiden' is not in `adata.obs`. Did you run `tl.leiden()`?
end... | def chromosome_heatmap(
adata: AnnData,
*,
groupby: str = "cnv_leiden",
use_rep: str = "cnv",
cmap: Union[str, Colormap] = "bwr",
figsize: Tuple[int, int] = (16, 10),
show: Optional[bool] = None,
save: Union[str, bool, None] = None,
**kwargs,
) -> Optional[Dict[str, matplotlib.axes.A... | Python | nomic_cornstack_python_v1 |
function find_median arr
begin
set n = length arr
sort arr
if n % 2 != 0
begin
return arr at n // 2
end
return arr at n - 1 // 2 + arr at n // 2 / 2.0
end function | def find_median(arr):
n = len(arr)
arr.sort()
if n % 2 != 0:
return arr[n//2]
return (arr[(n-1)//2] + arr[n//2]) / 2.0
| Python | flytech_python_25k |
import unittest
import os
import sys
from Array import arr
set path = directory name path absolute path path __file__
insert path 0 path
class ArrayTest extends TestCase
begin
function test_getCapacity self
begin
set array = array 10
assert equal 10 call getCapacity
end function
function test_getSize self
begin
set arr... | import unittest
import os
import sys
from Array import arr
path = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, path)
class ArrayTest(unittest.TestCase):
def test_getCapacity(self):
array = arr.Array(10)
self.assertEqual(10, array.getCapacity())
def test_getSize(self):
... | Python | zaydzuhri_stack_edu_python |
function test_noDrainThenLoseFount self
begin
set drainless = call series call PassthruTube
call flowTo drainless
call receive call object
assert equal flowIsPaused true
set ff2 = call FakeFount
call flowTo drainless
call assertIs drain drainless
assert equal flowIsPaused true
assert equal drain none
assert equal flowI... | def test_noDrainThenLoseFount(self):
drainless = series(PassthruTube())
self.ff.flowTo(drainless)
self.ff.drain.receive(object())
self.assertEqual(self.ff.flowIsPaused, True)
ff2 = FakeFount()
ff2.flowTo(drainless)
self.assertIs(ff2.drain, drainless)
self.... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Fri Oct 26 14:35:38 2018 @author: arthurmaroquenefroissart
comment %%
function linear number lst
begin
for i in range length lst
begin
if number == lst at i
begin
return i
end
end
return none
end function
function hello
begin
set name = input... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 26 14:35:38 2018
@author: arthurmaroquenefroissart
"""
#%%
def linear(number, lst):
for i in range(len(lst)):
if number == lst[i]:
return i
return None
def hello():
name = input("What's your name ? ")
p... | Python | zaydzuhri_stack_edu_python |
function netapi32_NetServerSetInfoCommandLine jitter
begin
set tuple ret_ad args = call func_args_stdcall list string argc string argv
raise call RuntimeError string API not implemented
call func_ret_stdcall ret_ad ret_value
end function | def netapi32_NetServerSetInfoCommandLine(jitter):
ret_ad, args = jitter.func_args_stdcall(["argc", "argv"])
raise RuntimeError('API not implemented')
jitter.func_ret_stdcall(ret_ad, ret_value) | Python | nomic_cornstack_python_v1 |
comment s = 'abcbcd'
set currentString = s at 0
set longestString = string
set i = 0
for i in range 1 length s
begin
if s at i >= s at i - 1
begin
set currentString = currentString + s at i
end
else
begin
if length currentString > length longestString
begin
set longestString = currentString
end
set currentString = s a... | #s = 'abcbcd'
currentString = s[0]
longestString = ''
i = 0
for i in range(1,len(s)):
if s[i] >= s[i-1]:
currentString = currentString + s[i]
else:
if len(currentString) > len(longestString):
longestString = currentString
currentString = s[i] | Python | zaydzuhri_stack_edu_python |
function __delslice__ self *args
begin
return call InstanceVector___delslice__ self *args
end function | def __delslice__(self, *args):
return _fife.InstanceVector___delslice__(self, *args) | Python | nomic_cornstack_python_v1 |
import sqlite3 as sql
function check new_url
begin
set con = call connect string short.db
set cur = call cursor
execute cur string SELECT old from short where new=(url) VALUES (?) new_url
set check = call fetchall
if check != list string
begin
return string This short url has been occupied...
end
end function
function... | import sqlite3 as sql
def check(new_url):
con = sql.connect("short.db")
cur = con.cursor()
cur.execute("SELECT old from short where new=(url) VALUES (?)", (new_url))
check = cur.fetchall()
if check != [('')]:
return "This short url has been occupied..."
def trans(ip, url, new_url):
... | Python | zaydzuhri_stack_edu_python |
function _is_tbr pending
begin
return boolean search string ^TBR=.*$ description MULTILINE
end function | def _is_tbr(pending):
return bool(re.search(r'^TBR=.*$', pending.description, re.MULTILINE)) | Python | nomic_cornstack_python_v1 |
function get_pci_device_by_id id
begin
return call get_pci_device_by_id id
end function | def get_pci_device_by_id(id):
return _get_dbdriver_instance().get_pci_device_by_id(id) | Python | nomic_cornstack_python_v1 |
function get_user_data self access_token *args **kwargs
begin
return call get_json string https://api-oauth2.mendeley.com/oapi/profiles/info/me/ headers=dict string Authorization format string Bearer {0} access_token
end function | def get_user_data(self, access_token, *args, **kwargs):
return self.get_json(
'https://api-oauth2.mendeley.com/oapi/profiles/info/me/',
headers={'Authorization': 'Bearer {0}'.format(access_token)}
) | Python | nomic_cornstack_python_v1 |
from common import *
class PlacementError extends Exception
begin
string Exception raised for errors in the ship placement. Attributes: message -- explanation of the error
function __init__ self message
begin
set message = message
end function
end class
class Ship
begin
set members = list
function __init__ self x=none... | from common import *
class PlacementError(Exception):
"""Exception raised for errors in the ship placement.
Attributes:
message -- explanation of the error
"""
def __init__(self, message):
self.message = message
class Ship ():
members = []
def __init__(self, x=None, y=None,... | Python | zaydzuhri_stack_edu_python |
set filename = input string Enter a file name:
set f = open filename string a
print string File name + filename + string has been opened.
set textinput = input string Enter some text to add to the file:
write f textinput
close f | filename = input("Enter a file name:")
f = open(filename, "a")
print("File name " + filename + " has been opened.")
textinput = input("Enter some text to add to the file:")
f.write(textinput)
f.close()
| Python | zaydzuhri_stack_edu_python |
from typing import List
string 给定一个只包含正整数的非空数组。是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。 注意: 每个数组中的元素不会超过 100 数组的大小不会超过 200 示例 1: 输入: [1, 5, 11, 5] 输出: true 解释: 数组可以分割成 [1, 5, 5] 和 [11].
class Solution
begin
function canPartition self nums
begin
set sums = sum nums
if sums % 2 != 0
begin
return false
end
set mid = sums / 2
sort n... | from typing import List
"""
给定一个只包含正整数的非空数组。是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。
注意:
每个数组中的元素不会超过 100
数组的大小不会超过 200
示例 1:
输入: [1, 5, 11, 5]
输出: true
解释: 数组可以分割成 [1, 5, 5] 和 [11].
"""
class Solution:
def canPartition(self, nums: List[int]) -> bool:
sums = sum(nums)
if sums % 2 != 0:
r... | Python | zaydzuhri_stack_edu_python |
comment {Key1:Value1, Key2:Value2, Key3:Value3 ...}
set dic = dict string name string pey ; string phone string 0119993323 ; string birth string 1118
set dic at string age = 28
print dic
print keys dic values dic
print items dic
print list keys dic
comment 딕셔너리 안에 찾으려는 key 값이 없을 경우 미리 정해 둔 디폴트 값을 대신 가져오게 하고 싶을 때에는
comm... | # {Key1:Value1, Key2:Value2, Key3:Value3 ...}
dic = {'name': 'pey', 'phone': '0119993323', 'birth': '1118'}
dic['age'] = 28
print(dic)
print(dic.keys(), dic.values())
print(dic.items())
print(list(dic.keys()))
# 딕셔너리 안에 찾으려는 key 값이 없을 경우 미리 정해 둔 디폴트 값을 대신 가져오게 하고 싶을 때에는
# get(x, '디폴트 값')을 사용하면 편리하다.
print(dic.get('na... | Python | zaydzuhri_stack_edu_python |
comment WELCOME MESSAGE #
import os
import time
import sys
set money = 0
set DL = 10
set wage = 5
set gender = string Male
function req_name msg
begin
try
begin
return call raw_input msg
end
except NameError
begin
return input msg
end
end function
set name = call req_name string Hello! What's your name?
while true
begi... | ##################################
# WELCOME MESSAGE #
##################################
import os
import time
import sys
money = 0
DL = 10
wage = 5
gender = "Male"
def req_name(msg):
try:
return raw_input(msg)
except NameError:
return input(msg)
name = req_name("""Hello! Wha... | Python | zaydzuhri_stack_edu_python |
function anneal solution
begin
set old_cost = call cost solution
set T = 1.0
set T_min = 1e-05
set ALPHA = 0.9
while T > T_min
begin
set i = 1
while i <= 100
begin
set new_solution = call neighbor solution
set new_cost = call cost new_solution
set ap = call acceptance_probability old_cost new_cost T
if ap > random
begi... | def anneal(solution):
old_cost = cost(solution)
T = 1.0
T_min = 0.00001
ALPHA = 0.9
while T > T_min:
i = 1
while i <= 100:
new_solution = neighbor(solution)
new_cost = cost(new_solution)
ap = acceptance_probability(old_cost, new_cost, T)
... | Python | nomic_cornstack_python_v1 |
import random
import math
function factorial_testcase
begin
set n = call randrange 100
return n
end function
function factorial3 n
begin
set res = 1
for i in range 1 n + 1
begin
set res = res + i
end
return res
end function
function factorial3_test n
begin
set m = call factorial3 n
assert m == call factorial n
end func... | import random
import math
def factorial_testcase():
n = random.randrange(100)
return n
def factorial3(n):
res = 1
for i in range(1, n + 1):
res += i
return res
def factorial3_test(n):
m = factorial3(n)
assert m == math.factorial(n)
def factorial_passing_testcase():
while ... | Python | zaydzuhri_stack_edu_python |
function export_frames self
begin
set result = list
for df in _imported_frames
begin
comment Append `TransformNode`` selecting all the columns (SELECT * FROM frame_id)
set df = df at call tolist
set modin_frame = _modin_frame
comment Forcibly executing plan via HDK.
set mode = _force_execution_mode
set _force_executio... | def export_frames(self):
result = []
for df in self._imported_frames:
# Append `TransformNode`` selecting all the columns (SELECT * FROM frame_id)
df = df[df.columns.tolist()]
modin_frame = df._query_compiler._modin_frame
# Forcibly executing plan via HDK.... | 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.