code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function _load_and_process_metadata annotations_file
begin
with call FastGFile annotations_file string r as f
begin
set json_data = load json f
end
print string Processing json annotation file.
set image_metadata = list
for data in json_data
begin
set filename = data at string image
set annotation = data at string ann... | def _load_and_process_metadata(annotations_file):
with tf.gfile.FastGFile(annotations_file, "r") as f:
json_data = json.load(f)
print("Processing json annotation file.")
image_metadata = []
for data in json_data:
filename = data['image']
annotation = data['annotation']
i... | Python | nomic_cornstack_python_v1 |
function excel_column_number_to_name column_number
begin
set results = string
while column_number > 0
begin
set results = character ordinal string A + column_number - 1 % 26 + results
set column_number = column_number - 1 // 26
end
return results
end function
print call excel_column_number_to_name 1
print call excel_c... | def excel_column_number_to_name(column_number):
results = ""
while column_number > 0:
results = chr(ord('A') + (column_number - 1) % 26) + results
column_number = (column_number - 1) // 26
return results
print(excel_column_number_to_name(1))
print(excel_column_number_to_name(2... | Python | zaydzuhri_stack_edu_python |
import unittest
from solutions import abs_sort
class AbsoluteValueSort extends TestCase
begin
function test_case_1 self
begin
set arr = list 2 - 7 - 2 - 2 0
set expected = list 0 - 2 - 2 2 - 7
set actual = call abs_sort arr
assert equal expected actual
end function
function test_case_2 self
begin
set arr = list - 2 1
s... | import unittest
from solutions import abs_sort
class AbsoluteValueSort(unittest.TestCase):
def test_case_1(self):
arr = [2,-7,-2,-2,0]
expected = [0,-2,-2,2,-7]
actual = abs_sort(arr)
self.assertEqual(expected, actual)
def test_case_2(self):
arr = [-2,1]
... | Python | zaydzuhri_stack_edu_python |
import copy
from sys import stdin
class MatrixError extends BaseException
begin
function __init__ self Matrix other
begin
set matrix1 = Matrix
set matrix2 = other
end function
end class
class Matrix
begin
function __init__ self lst
begin
set lst = deep copy lst
end function
function __str__ self
begin
set rows = list
... | import copy
from sys import stdin
class MatrixError(BaseException):
def __init__(self, Matrix, other):
self.matrix1 = Matrix
self.matrix2 = other
class Matrix:
def __init__(self, lst):
self.lst = copy.deepcopy(lst)
def __str__(self):
rows = []
for row in self.lst... | Python | zaydzuhri_stack_edu_python |
from wordcloud import WordCloud
import os
from os import path
import matplotlib.pyplot as plt
import jieba
from scipy.misc import imread
comment 读取图片
set bg_pic = call imread string H:\数据挖掘mode\QQ图片20180523170041.png
set comment_text = read open string 背影.txt string r
set cut_text = call lcut comment_text
print cut_tex... | from wordcloud import WordCloud
import os
from os import path
import matplotlib.pyplot as plt
import jieba
from scipy.misc import imread
#读取图片
bg_pic = imread('H:\\数据挖掘mode\\QQ图片20180523170041.png')
comment_text=open('背影.txt','r').read()
cut_text=jieba.lcut(comment_text)
print(cut_text)
cut_text=filter(lambda x:len(x... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import os , sys
import random
from copy import deepcopy
import bisect
function gcd a b recursion=true
begin
string Returns the greatest common divider of a and b.
comment one way to solve it is by recursion
if recursion
begin
if a == b
begin
return a
end
else
if a > b
begin
return call gcd a - b b tr... | import numpy as np
import os, sys
import random
from copy import deepcopy
import bisect
def gcd(a, b, recursion = True):
"""
Returns the greatest common divider of a and b.
"""
if recursion: # one way to solve it is by recursion
if a == b:
return a
elif a > b:
... | Python | zaydzuhri_stack_edu_python |
function _init_all_settings self
begin
if cuda
begin
call _init_cuda_setting
end
call _init_hps hps
if model is none
begin
set model = call _init_model
end
if model is not none and cuda
begin
set model = cuda model
end
if _flag_load_checkpoint
begin
call load_checkpoint
end
else
begin
call _load_pretrained_model
end
se... | def _init_all_settings(self):
if self.cfg.cuda:
self._init_cuda_setting()
self._init_hps(self.hps)
if self.model is None:
self.model = self._init_model()
if self.model is not None and self.cfg.cuda:
self.model = self.model.cuda()
if self._flag_... | Python | nomic_cornstack_python_v1 |
function mine_itemsets self X
begin
set itemsets = call apriori X min_support=min_support use_colnames=true
comment apriori returns the support for each item. just take itemsets
return itemsets
end function | def mine_itemsets(self, X):
itemsets = apriori(X, min_support=self.min_support, use_colnames=True)
return itemsets.itemsets # apriori returns the support for each item. just take itemsets | Python | nomic_cornstack_python_v1 |
function test_spaces self
begin
assert equal call escape_cmd list string scp string source string a space string scp source "a space"
end function | def test_spaces(self):
self.assertEqual(escape_cmd(["scp", "source", "a space"]), 'scp source "a space"') | Python | nomic_cornstack_python_v1 |
comment https://www.hackerrank.com/challenges/ctci-ransom-note/problem
comment Sample Input:
comment 6 4
comment give me one grand today night
comment give one grand today
comment Sample Output: Yes
comment Slow answer (times out sometimes)
function ransom_note magazine ransom
begin
for word in magazine
begin
if word i... | #https://www.hackerrank.com/challenges/ctci-ransom-note/problem
# Sample Input:
# 6 4
# give me one grand today night
# give one grand today
#Sample Output: Yes
#Slow answer (times out sometimes)
def ransom_note(magazine, ransom):
for word in magazine:
if word in ransom:
ransom.remove(word) | Python | zaydzuhri_stack_edu_python |
function get_percent_height y
begin
comment For tall bars, the % sign is inside the bar
if y < 20
begin
return y + 10
end
comment For most bars, the % sign is above the bar
return y - 7
end function | def get_percent_height(y):
if y < 20: #For tall bars, the % sign is inside the bar
return y + 10
return y - 7 #For most bars, the % sign is above the bar | Python | nomic_cornstack_python_v1 |
comment converts structure files into genepop format
comment the expected structure format are 2 lines per individual, first two columns separated by tabs, genotype data separated by spaces).
comment first line is the individual identifier and the second the pop indentifier
comment it converts batches of files or indiv... | #converts structure files into genepop format
#the expected structure format are 2 lines per individual, first two columns separated by tabs, genotype data separated by spaces).
#first line is the individual identifier and the second the pop indentifier
#it converts batches of files or individual files. In the latte... | Python | zaydzuhri_stack_edu_python |
import copy
import random
class Memento
begin
function __init__ self money
begin
set money = money
set fruits = list
end function
function getMoney self
begin
return money
end function
function addFruit self fruit
begin
append fruits fruit
end function
function getFruits self
begin
return copy copy fruits
end function... | import copy
import random
class Memento:
def __init__(self, money):
self.money = money
self.fruits = []
def getMoney(self):
return self.money
def addFruit(self, fruit):
self.fruits.append(fruit)
def getFruits(self):
return copy.copy(self.fruits)
class Gamer... | Python | zaydzuhri_stack_edu_python |
string 作者:文文 主要介绍正则表达式中的分组概念 python版本:python3.5
import re
string python正则表达式提供了一个机制将表达式分组,当使用分组时,除了获得整个匹配,还可以在匹配中选择每一个单独组 可以在正则表达式中使用圆括号指定分组
set match = search string ([\d]{3})-([\d]{4}) string 867-5309 / Jenny
comment 返回整个匹配,即867-5309
print call group
comment 返回一个对应每一个单个分组的元组
comment output : ('867', '5309')
print cal... | """
作者:文文
主要介绍正则表达式中的分组概念
python版本:python3.5
"""
import re
"""
python正则表达式提供了一个机制将表达式分组,当使用分组时,除了获得整个匹配,还可以在匹配中选择每一个单独组
可以在正则表达式中使用圆括号指定分组
"""
match = re.search(r'([\d]{3})-([\d]{4})','867-5309 / Jenny')
#返回整个匹配,即867-5309
print (match.group())
#返回一个对应每一个单个分组的元组
#output : ('867', '5309')
print (match.groups())
#获取单... | Python | zaydzuhri_stack_edu_python |
while n != 1
begin
set n = n / 2
set sum = sum + n
end
set sum = sum - 1
print sum | while n!=1:
n = n/2
sum +=n
sum -= 1
print(sum) | Python | zaydzuhri_stack_edu_python |
comment Write a function that will shift an array by an arbitrary amount
comment using a convolution (yes, I know there are easier ways to do this).
comment The function should take 2 arguments - an array, and an amount by
comment which to shift the array. Plot a gaussian that started in the centre
comment of the array... | #Write a function that will shift an array by an arbitrary amount
#using a convolution (yes, I know there are easier ways to do this).
#The function should take 2 arguments - an array, and an amount by
#which to shift the array. Plot a gaussian that started in the centre
#of the array shifted by half the array length ... | Python | zaydzuhri_stack_edu_python |
function plot_pointings self ax=none projection=string polar add_grid3d=false train_kwargs=none test_kwargs=none
begin
set train_kwargs = if expression train_kwargs is none then dict else train_kwargs
set test_kwargs = if expression test_kwargs is none then dict else test_kwargs
set default test_kwargs string color s... | def plot_pointings(self, ax=None, projection='polar', add_grid3d=False, train_kwargs=None, test_kwargs=None):
train_kwargs = {} if train_kwargs is None else train_kwargs
test_kwargs = {} if test_kwargs is None else test_kwargs
test_kwargs.setdefault('color', 'black')
test_kwargs.setdefau... | Python | nomic_cornstack_python_v1 |
from flask_wtf import FlaskForm
from wtforms import StringField , SubmitField , PasswordField , BooleanField , ValidationError , validators , RadioField , IntegerField
from wtforms.validators import DataRequired , Regexp
from wtforms.fields.html5 import EmailField
from flask_wtf import Form
from flask_wtf.file import F... | from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, PasswordField, BooleanField, ValidationError, validators,RadioField,IntegerField
from wtforms.validators import DataRequired, Regexp
from wtforms.fields.html5 import EmailField
from flask_wtf import Form
from flask_wtf.file import FileField,... | Python | zaydzuhri_stack_edu_python |
import tweepy
import time
set auth = call OAuthHandler string YOURAUTHKEY
call set_access_token string ACCESS_TOKEN string TOKENISER2
set api = call API auth
comment public_tweets = api.home_timeline()
comment for tweet in public_tweets:
comment print(tweet.text)
set user = call me
comment print(user.name)
comment prin... | import tweepy
import time
auth = tweepy.OAuthHandler('YOURAUTHKEY')
auth.set_access_token('ACCESS_TOKEN',
'TOKENISER2')
api = tweepy.API(auth)
# public_tweets = api.home_timeline()
# for tweet in public_tweets:
# print(tweet.text)
user = api.me()
# print(user.name)
# print(user.screen_na... | Python | zaydzuhri_stack_edu_python |
string Drive Functions
import wpilib
import navx
from ctre import *
from wpilib.drive import DifferentialDrive
from wpilib.controller import PIDController
class Drive
begin
function __init__ self
begin
string Drive Train
comment drive train motors
set frontLeftMotor = call WPI_VictorSPX 1
set frontRightMotor = call WPI... | """ Drive Functions """
import wpilib
import navx
from ctre import *
from wpilib.drive import DifferentialDrive
from wpilib.controller import PIDController
class Drive:
def __init__(self):
""" Drive Train """
# drive train motors
self.frontLeftMotor = WPI_VictorSPX(1)
self.frontRig... | Python | zaydzuhri_stack_edu_python |
function prepare_data input_data
begin
set the_data = list
for line in input_data
begin
set splitted_line = split line string bags contain
set new_bag = dict string color splitted_line at 0
set new_bag at string children = list
set children = split re string bag[s,. ]* strip splitted_line at 1
for child in children
b... | def prepare_data(input_data):
the_data = []
for line in input_data:
splitted_line = line.split(' bags contain ')
new_bag = {'color':splitted_line[0]}
new_bag['children'] = []
children = re.split(r" bag[s,. ]*", splitted_line[1].strip())
for child in children:
... | Python | nomic_cornstack_python_v1 |
function remove self *args
begin
return call ListOfLineSegments_remove self *args
end function | def remove(self, *args):
return _libsbml.ListOfLineSegments_remove(self, *args) | Python | nomic_cornstack_python_v1 |
function __init__ self id value editable modified_on
begin
set id = id
set value = value
set editable = editable
set modified_on = modified_on
end function | def __init__(self,
id: str,
value: 'MobileRedirectRespResultValue',
editable: bool,
modified_on: datetime) -> None:
self.id = id
self.value = value
self.editable = editable
self.modified_on = modified_on | Python | nomic_cornstack_python_v1 |
function distinct_chars s l r
begin
string Returns the number of distinct characters in the substring of s starting at index l and ending at index r, inclusive.
return length set s at slice l : r + 1 :
end function
function replace_chars s l r c
begin
string Replaces all occurrences of the character at index c in the s... | def distinct_chars(s, l, r):
"""
Returns the number of distinct characters in the substring of s
starting at index l and ending at index r, inclusive.
"""
return len(set(s[l:r+1]))
def replace_chars(s, l, r, c):
"""
Replaces all occurrences of the character at index c in the substring
of s starting at index l a... | Python | jtatman_500k |
function create_compound_load **kwargs
begin
return call CompoundLoad keyword kwargs
end function | def create_compound_load(**kwargs):
return CompoundLoad(**kwargs) | Python | nomic_cornstack_python_v1 |
function equal nm A B
begin
comment check type
if not __class__ == __class__
begin
call pr format string {}, different types: {} vs {} nm __class__ __class__
return false
end
comment dictionary, check each key
if __class__ == dict
begin
set keyAs = keys A
set keyBs = keys A
sort keyAs
sort keyBs
if not call equal nm ke... | def equal(nm, A, B):
# check type
if not A.__class__ == B.__class__:
pri.pr('{}, different types: {} vs {}'.format(nm, A.__class__, B.__class__))
return False
# dictionary, check each key
if A.__class__ == dict:
keyAs = A.keys()
keyBs = A.keys()
keyAs.sort()
... | Python | nomic_cornstack_python_v1 |
from discord.ext import commands
import logging
import asyncio
from trigger import Trigger
import settings
import sys
class ReminderController
begin
set reminderContexts = list
decorator staticmethod
function addReminderContext uid ctx tr
begin
for rs in reminderContexts
begin
if _uqID == uid
begin
call addTrigger tr
... | from discord.ext import commands
import logging
import asyncio
from trigger import Trigger
import settings
import sys
class ReminderController:
reminderContexts = []
@staticmethod
def addReminderContext(uid, ctx,tr:Trigger):
for rs in ReminderController.reminderContexts:
if rs._uqID == ... | Python | zaydzuhri_stack_edu_python |
string @Author: your name @Date: 2020-02-06 09:26:11 @LastEditTime : 2020-02-06 15:53:54 @LastEditors : Please set LastEditors @Description: In User Settings Edit @FilePath: scode_code scode_python_test\练习\json测试nother.py
import requests
import json
import pygal
comment json_url = 'https://raw.githubusercontent.com/mu... | '''
@Author: your name
@Date: 2020-02-06 09:26:11
@LastEditTime : 2020-02-06 15:53:54
@LastEditors : Please set LastEditors
@Description: In User Settings Edit
@FilePath: \vscode_code\vscode_python_test\练习\json测试\another.py
'''
import requests
import json
import pygal
#json_url = 'https://raw.githubusercontent.com/mu... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Wed Dec 20 12:46:25 2017 @author: a_santos Module to generate an especific waveform from the Georgia Tech waveform catalog. This module was prefixed to get only the l:2 and m:2 radiated mode. The entire catalog has to be stored in the compute... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 20 12:46:25 2017
@author: a_santos
Module to generate an especific waveform from the Georgia Tech waveform catalog.
This module was prefixed to get only the l:2 and m:2 radiated mode.
The entire catalog has to be stored in the computer
The way to ... | Python | zaydzuhri_stack_edu_python |
function __init__ self path
begin
set libdaos = call CDLL path + string libdaos.so.0.0.2 mode=DEFAULT_MODE
call CDLL path + string libdaos_common.so mode=RTLD_GLOBAL
set libtest = call CDLL path + string libdaos_tests.so mode=DEFAULT_MODE
call daos_init
comment Note: action-subject format
set ftable = dict string add-t... | def __init__(self, path):
self.libdaos = ctypes.CDLL(path+"libdaos.so.0.0.2",
mode=ctypes.DEFAULT_MODE)
ctypes.CDLL(path+"libdaos_common.so",
mode=ctypes.RTLD_GLOBAL)
self.libtest = ctypes.CDLL(path+"libdaos_tests.so",
... | Python | nomic_cornstack_python_v1 |
function within_boundary_area lat lng min_lat max_lat min_lng max_lng
begin
if lat > max_lat or lat < min_lat
begin
return false
end
if lng > max_lng or lng < min_lng
begin
return false
end
return true
end function | def within_boundary_area(lat, lng, min_lat, max_lat, min_lng, max_lng):
if lat > max_lat or lat < min_lat:
return False
if lng > max_lng or lng < min_lng:
return False
return True | Python | nomic_cornstack_python_v1 |
function rocketlab_page
begin
return call render_template string rocketlab.html
end function | def rocketlab_page():
return render_template('rocketlab.html') | Python | nomic_cornstack_python_v1 |
async function on_player_unready self user
begin
set game = game
comment Player not at the table
set player = call get_player id
if not player
begin
return
end
comment SUCCESS
set ready = false
call global_log string dbg format string [{}] Player {} is unready. table_id name
call check_game_start
await call notify_view... | async def on_player_unready(self, user):
game = self.game
# Player not at the table
player = self.game.get_player(user.id)
if not player:
return
# SUCCESS
player.ready = False
global_log("dbg", "[{}] Player {} is unready.".format(game.table_id, user... | Python | nomic_cornstack_python_v1 |
import mymaths
set MAX = 1000000
set totient = call generate_totient MAX
print max generator expression tuple 1.0 * n / totient at n n for n in range 2 MAX | import mymaths
MAX = 1000000
totient = mymaths.generate_totient(MAX)
print(max((1.0*n/totient[n] , n)for n in range(2, MAX))) | Python | zaydzuhri_stack_edu_python |
function lstm_cell i o state
begin
set input_gate = sigmoid matrix multiply i ix + matrix multiply o im + ib
set forget_gate = sigmoid matrix multiply i fx + matrix multiply o fm + fb
set update = matrix multiply i cx + matrix multiply o cm + cb
set state = forget_gate * state + input_gate * tanh update
set output_gate... | def lstm_cell(i, o, state):
input_gate = tf.sigmoid(tf.matmul(i, ix) + tf.matmul(o, im) + ib)
forget_gate = tf.sigmoid(tf.matmul(i, fx) + tf.matmul(o, fm) + fb)
update = tf.matmul(i, cx) + tf.matmul(o, cm) + cb
state = forget_gate * state + input_gate * tf.tanh(update)
output_gate = tf.sigmoid(tf.ma... | Python | nomic_cornstack_python_v1 |
function binaryWatch n
begin
return list comprehension string %d:%02d % tuple h m for h in range 12 for m in range 60 if count binary h + binary m string 1 == n
end function | def binaryWatch(n):
return ['%d:%02d' % (h,m) for h in range(12) for m in range(60)
if (bin(h) + bin(m)).count('1') == n] | Python | nomic_cornstack_python_v1 |
import pygame
import os
import time
import random
import assets
import classes
import gamescreens
comment setting up pygamae window and variables
call init
call init
call set_caption string HIT OR RUN
set tuple width height = tuple 700 800
set window = call set_mode tuple width height
set click = false
set FPS = 60
set... | import pygame
import os
import time
import random
import assets
import classes
import gamescreens
#setting up pygamae window and variables
pygame.init()
pygame.font.init()
pygame.display.set_caption("HIT OR RUN")
width,height = 700,800
window = pygame.display.set_mode((width, height))
click = False
FPS ... | Python | zaydzuhri_stack_edu_python |
comment -*- coding:utf-8 _*-
string @version: 1.0.0 author: 孔维一 @time: 2020/09/05 @file: 04-输出json字符串到json文件当中.py @function: @modify:
import json
set data_en = list dict string name string bob ; string age 21 ; string gender string male dict string name string Lily ; string age 18 ; string gender string female
set data... | # -*- coding:utf-8 _*-
"""
@version: 1.0.0
author: 孔维一
@time: 2020/09/05
@file: 04-输出json字符串到json文件当中.py
@function:
@modify:
"""
import json
data_en = [
{
"name": "bob",
"age": 21,
"gender": "male"
},
{
"name": "Lily",
"age": 18,
"gender": "female"
}
]
d... | Python | zaydzuhri_stack_edu_python |
from typing import List
class Solution
begin
function removeElement self nums val
begin
set result = list
for i in nums
begin
if i != val
begin
append result i
end
end
clear nums
for i in result
begin
append nums i
end
return length result
end function
end class
if __name__ == string __main__
begin
set r = list 3 2 2 ... | from typing import List
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
result = []
for i in nums:
if i != val:
result.append(i)
nums.clear()
for i in result:
nums.append(i)
return len(result)
if __name__ =... | Python | zaydzuhri_stack_edu_python |
function __write_playlist_status self
begin
debug string writing playlist
set plfile = open basedir + string /playlist string w
write plfile playlist + string
close plfile
end function | def __write_playlist_status(self):
log.debug("writing playlist")
plfile = open(self.basedir + "/playlist", 'w')
plfile.write(self.playlist + "\n")
plfile.close() | Python | nomic_cornstack_python_v1 |
import os
import csv
set election_csv = join path string .. string Resources string election_data.csv
set data = list
with open election_csv newline=string as csvfile
begin
set csvreader = reader csvfile delimiter=string ,
for line in csvreader
begin
append data line
end
end
pop data 0
set total = 0
for line in data
b... | import os
import csv
election_csv = os.path.join("..", "Resources", "election_data.csv")
data = []
with open(election_csv, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
for line in csvreader:
data.append(line)
data.pop(0)
total = 0
for line in data:
total += 1 | Python | zaydzuhri_stack_edu_python |
function __init__ self **kwargs
begin
comment Basic stuff
set active = get kwargs string active true
set render = get kwargs string render true
set debug = get kwargs string debug false
set x = get kwargs string x 0.0
set y = get kwargs string y 0.0
set width = get kwargs string width 0
set height = get kwargs string h... | def __init__(self, **kwargs):
# Basic stuff
self.active = kwargs.get('active', True)
self.render = kwargs.get('render', True)
self.debug = kwargs.get('debug', False)
self.x = kwargs.get('x', 0.0)
self.y = kwargs.get('y', 0.0)
self.width = kwargs.get('width', 0)
... | Python | nomic_cornstack_python_v1 |
function is_in_studio self
begin
return get attribute xmodule_runtime string is_author_mode false
end function | def is_in_studio(self):
return getattr(self.xmodule_runtime, 'is_author_mode', False) | Python | nomic_cornstack_python_v1 |
function main
begin
comment Calling folder selection and choice selection boxes
set obj = call Gui
set tuple input_folder choice stag = call folder_choice
global err
set err = 0
if choice == 1
begin
set tag = lower stag
set mp3fm = call PackSongs input_folder tag
call put_songs
call generate_log
end
else
if choice == 2... | def main():
# Calling folder selection and choice selection boxes
obj = gui.Gui()
input_folder, choice, stag = obj.folder_choice()
global err
err = 0
if choice == 1:
tag = stag.lower()
mp3fm = pack.PackSongs(input_folder, tag)
mp3fm.put_songs()
mp3fm.generate_log... | Python | nomic_cornstack_python_v1 |
import random , string
set f = open string action_code.txt string w
set num = 200
set chars = ascii_letters + digits
set length = 7
for i in range num
begin
set s = list comprehension random choice chars for i in range 10
write f join string s + string
end
close f | import random, string
f = open('action_code.txt', 'w')
num = 200
chars = string.ascii_letters + string.digits
length = 7
for i in range(num):
s = [random.choice(chars) for i in range(10)]
f.write(' '.join(s) + '\n')
f.close() | Python | zaydzuhri_stack_edu_python |
function LoadYaml path
begin
comment NOTE(g): Import is done here, instead of the top of the file, to not require this module if it is not used
import yaml
set fp = none
try
begin
set fp = open path
set data = load yaml fp
end
finally
begin
if fp
begin
close fp
end
end
return data
end function | def LoadYaml(path):
#NOTE(g): Import is done here, instead of the top of the file, to not require this module if it is not used
import yaml
fp = None
try:
fp = open(path)
data = yaml.load(fp)
finally:
if fp:
fp.close()
return data | Python | nomic_cornstack_python_v1 |
function get_known_sRNAs knownbs
begin
set srs = set
with open knownbs as sin
begin
for line in sin
begin
set sn = split line at 10
add srs lower sn at 0 + sn at slice 1 : :
end
end
return srs
end function | def get_known_sRNAs(knownbs):
srs = set()
with open(knownbs) as sin:
for line in sin:
sn = line.split()[10]
srs.add(sn[0].lower()+sn[1:])
return srs | Python | nomic_cornstack_python_v1 |
for k in range 1 2 * n + 1
begin
set num = 2 * n + k
if num <= m
begin
print num end=string
end
set num = k
if num <= m
begin
print num end=string
end
end | for k in range(1,2*n +1):
num = 2 *n +k
if num <= m:
print(num, end=" ")
num = k
if num <= m:
print(num, end=" ")
| Python | jtatman_500k |
comment Требуется написать программу, осуществляющую преобразование из одних единиц измерения длины в другие.
comment Должны поддерживаться
comment мили (1 mile = 1609 m),
comment ярды (1 yard = 0.9144 m),
comment футы (1 foot = 30.48 cm),
comment дюймы (1 inch = 2.54 cm),
comment километры (1 km = 1000 m),
comment мет... | # Требуется написать программу, осуществляющую преобразование из одних единиц измерения длины в другие.
# Должны поддерживаться
# мили (1 mile = 1609 m),
# ярды (1 yard = 0.9144 m),
# футы (1 foot = 30.48 cm),
# дюймы (1 inch = 2.54 cm),
# километры (1 km = 1000 m),
# метры (m),
# сантиметры (1 cm = 0.01 m)
# миллиметр... | Python | zaydzuhri_stack_edu_python |
function get_rope_length head_pos tail_pos
begin
set x_dist = head_pos at 0 - tail_pos at 0
set y_dist = head_pos at 1 - tail_pos at 1
set length = max absolute x_dist absolute y_dist
if x_dist > 0
begin
set change_x = 1
end
else
if x_dist < 0
begin
set change_x = - 1
end
else
begin
set change_x = 0
end
if y_dist > 0
b... | def get_rope_length(head_pos: tuple, tail_pos: tuple):
x_dist = head_pos[0] - tail_pos[0]
y_dist = head_pos[1] - tail_pos[1]
length = max(abs(x_dist), abs(y_dist))
if x_dist > 0:
change_x = 1
elif x_dist < 0:
change_x = -1
else:
change_x = 0
if y_dist > 0:
change_y = 1
elif y_dist < 0:
... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: UTF-8 -*-
import configparser
import json
import os
import sys
import time
import traceback
import xml.etree.ElementTree as ET
import zipfile
import pandas as pd
from openpyxl import load_workbook
from pandas import DataFrame
import shutil
import logging
from logging import handlers
from openpyxl.ut... | # -*- coding: UTF-8 -*-
import configparser
import json
import os
import sys
import time
import traceback
import xml.etree.ElementTree as ET
import zipfile
import pandas as pd
from openpyxl import load_workbook
from pandas import DataFrame
import shutil
import logging
from logging import handlers
from openpyxl.utils im... | Python | zaydzuhri_stack_edu_python |
function test_get_router_api self
begin
set r = json get requests router_url + string /user/ + string unit_testing%40test.com
assert equal r at string status 200
end function | def test_get_router_api(self):
r = requests.get(router_url + '/user/' +
'unit_testing%40test.com').json()
self.assertEqual(r['status'], 200) | Python | nomic_cornstack_python_v1 |
function reshape width height
begin
global config
set windowWidth = width
set windowHeight = height
call viewMatrix
end function | def reshape(width, height):
global config
config.windowWidth = width
config.windowHeight = height
viewMatrix() | Python | nomic_cornstack_python_v1 |
function extract_one num
begin
set oneNum = 0
while num > 0
begin
if num % 2 == 1
begin
set oneNum = oneNum + 1
end
set num = num // 2
end
return oneNum
end function
function solution n
begin
set answer = n + 1
set nOne = call extract_one n
while nOne != call extract_one answer
begin
set answer = answer + 1
end
return ... | def extract_one(num):
oneNum = 0
while num>0:
if num % 2 == 1:
oneNum += 1
num = num // 2
return oneNum
def solution(n):
answer = n+1
nOne = extract_one(n)
while nOne != extract_one(answer):
answer += 1
return answer
if __name__ == '__main__':
n = 7... | Python | zaydzuhri_stack_edu_python |
import logging
import postgresql
import time
import checker
from telegram.ext import Updater , CommandHandler , MessageHandler , Filters , ConversationHandler
call basicConfig filename=string logs.txt filemode=string w format=string %(asctime)s - %(name)s - %(levelname)s - %(message)s level=INFO
set logger = call getLo... | import logging
import postgresql
import time
import checker
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters, ConversationHandler)
logging.basicConfig(filename='logs.txt', filemode='w', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
... | Python | zaydzuhri_stack_edu_python |
function __AI_next_position self game_board
begin
set position = position
set player_label = call player_label position
set empty = filter lambda pair -> pair at 1 == string enumerate position
set empty_indexes = map lambda pair -> pair at 0 empty
if length empty_indexes > 12
begin
set i = empty_indexes at random inte... | def __AI_next_position(self, game_board):
position = game_board.position
player_label = game_board.player_label(position)
empty = filter(lambda pair : pair[1] == ' ', enumerate(position))
empty_indexes = map(lambda pair : pair[0], empty)
if len(empty_indexes) > 12:
... | Python | nomic_cornstack_python_v1 |
for i in range length H
begin
if cur_max_h <= H at i
begin
set ans = ans + 1
set cur_max_h = H at i
end
end
print ans | for i in range(len(H)):
if cur_max_h <= H[i]:
ans += 1
cur_max_h = H[i]
print(ans)
| Python | zaydzuhri_stack_edu_python |
string Bot provides some information about current state of International Space Station
import logging
import time
from collections import defaultdict
from datetime import datetime
import requests
import telebot
from environs import Env
from telebot import apihelper , types
from telebot.types import Message
set URL_ISS... | """
Bot provides some information about current state of International Space Station
"""
import logging
import time
from collections import defaultdict
from datetime import datetime
import requests
import telebot
from environs import Env
from telebot import apihelper, types
from telebot.types import Message
URL_ISS_... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
string Run regression on apartment data.
from __future__ import print_function
import argparse
import pandas as pd
import numpy as np
import itertools
import matplotlib.pyplot as plt
import getpass
function parse_args *argument_array
begin
set parser = call ArgumentParser
call set_defaults... | #!/usr/bin/env python3
"""
Run regression on apartment data.
"""
from __future__ import print_function
import argparse
import pandas as pd
import numpy as np
import itertools
import matplotlib.pyplot as plt
import getpass
def parse_args(*argument_array):
parser = argparse.ArgumentParser()
parser.set_defaults(... | Python | zaydzuhri_stack_edu_python |
class Solution extends object
begin
function generate self numRows
begin
string :type numRows: int :rtype: List[List[int]]
if numRows == 0
begin
return list
end
if numRows == 1
begin
return list list 1
end
if numRows == 2
begin
return list list 1 list 1 1
end
set res = list list 1 list 1 1
for i in range 2 numRows
beg... | class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if numRows == 0:
return []
if numRows == 1 :
return [[1]]
if numRows == 2:
return [[1],[1,1]]
res = [[1],[1,1]]
for i in range(2,numRows):
temp = [1]
for j in range(len(res[-1])-1):
... | Python | zaydzuhri_stack_edu_python |
import pytest
from contextlib import closing
from unittest.mock import call
comment NOQA - fixtures
from tests.lib import *
decorator fixture
function invbot fakebot
begin
string Provide a bot loaded with the Calc module. Clear the database.
set botconfig at string module_configs at string Inventory = dict string limit... | import pytest
from contextlib import closing
from unittest.mock import call
from tests.lib import * # NOQA - fixtures
@pytest.fixture
def invbot(fakebot):
"""
Provide a bot loaded with the Calc module. Clear the database.
"""
fakebot.botconfig["module_configs"]["Inventory"] = {
"limit": 2,
... | Python | zaydzuhri_stack_edu_python |
function get_button_status self button
begin
return call get_mouse_button glfw_window button
end function | def get_button_status(self, button):
return glfw.get_mouse_button(self.window.context.glfw_window, button) | Python | nomic_cornstack_python_v1 |
comment start Menu #
from pygame import *
call init
from math import cos , radians
import webbrowser
import singleplayer , snake
function menu menu pos=string center font1=none font2=none color1=tuple 128 128 128 color2=none interline=5 justify=true light=5 speed=300 lag=30
begin
class Item extends Rect
begin
function ... | # start Menu #
from pygame import *
font.init()
from math import cos,radians
import webbrowser
import singleplayer, snake
def menu(menu,pos='center',font1=None,font2=None,color1=(128,128,128),color2=None,interline=5,justify=True,light=5,speed=300,lag=30):
class Item(Rect):
def __init__(self,menu... | Python | zaydzuhri_stack_edu_python |
function test_7 self
begin
set input = string procedure foo(); var a: real; begin end
set expect = string successful
assert true call test input expect 207
end function | def test_7(self):
input = """
procedure foo();
var a: real;
begin
end
"""
expect = "successful"
self.assertTrue(TestParser.test(input, expect, 207)) | Python | nomic_cornstack_python_v1 |
function resort iterations md_module INITIAL_TARGET_NUMBER_OF_SEGMENTS
begin
set parent_iteration = iterations at - 2
set current_iteration = iterations at - 1
comment Sanity check for RMSD matrix
comment if rama_ids.min() == 0.0:
comment print("\x1b[31m Warning!\x1b[0m SegmentsToBins RMSD Matrix has entries 0.00000!"\... | def resort(iterations, md_module, INITIAL_TARGET_NUMBER_OF_SEGMENTS):
parent_iteration = iterations[-2]
current_iteration = iterations[-1]
# Sanity check for RMSD matrix
# if rama_ids.min() == 0.0:
# print("\x1b[31m Warning!\x1b[0m SegmentsToBins RMSD Matrix has entries 0.00000... | Python | nomic_cornstack_python_v1 |
function factorial n
begin
if n == 0
begin
return 1
end
else
begin
return n * call factorial n - 1
end
end function | def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1) | Python | iamtarun_python_18k_alpaca |
comment Good morning! Here's your coding interview problem for today.
comment This problem was asked by Uber.
comment Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
comment For example, if our... | # Good morning! Here's your coding interview problem for today.
#
# This problem was asked by Uber.
#
# Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
#
# For example, if our input was [1, ... | Python | zaydzuhri_stack_edu_python |
function anagram s1 s2
begin
set h1 = dictionary
for i in s1
begin
set h1 at i = get h1 i 0 + 1
end
for i in s2
begin
if i in h1
begin
set h1 at i = h1 at i - 1
end
else
begin
set h1 at i = 1
end
end
for i in h1
begin
if h1 at i != 0
begin
return false
end
end
return true
end function
if __name__ == string __main__
beg... | def anagram(s1,s2):
h1=dict()
for i in s1:
h1[i]=h1.get(i,0)+1
for i in s2:
if(i in h1):
h1[i]=h1[i]-1
else:
h1[i]=1
for i in h1:
if(h1[i]!=0):
return False
return True
if __name__=='__main__':
s1=input()
s2... | Python | zaydzuhri_stack_edu_python |
function form_valid self form
begin
set kwargs = call get_form_kwargs
set request = kwargs at string request
set notification_medium = cleaned_data at string notification_medium
try
begin
set form_valid = call form_valid form
call success request string New notification channel added
return form_valid
end
except Integr... | def form_valid(self, form):
kwargs = self.get_form_kwargs()
request = kwargs["request"]
notification_medium = form.cleaned_data["notification_medium"]
try:
form_valid = super().form_valid(form)
messages.success(request, "New notification channel added")
... | Python | nomic_cornstack_python_v1 |
comment Section05-2
comment 반복문 / 흐름제어 (제어문)
comment for, while basics
comment difference:
comment while loop will do sth as long as the condition is met.
comment for loop will do soth to everything which i wish to iterate through.
set c1 = 1
comment while
while c1 < 11
begin
print string c1 is : c1
set c1 = c1 + 1
end... | # Section05-2
# 반복문 / 흐름제어 (제어문)
# for, while basics
# difference:
# while loop will do sth as long as the condition is met.
# for loop will do soth to everything which i wish to iterate through.
c1 = 1
# while
while c1 < 11:
print("c1 is : ", c1)
c1 += 1
print()
# for
for c2 in ran... | Python | zaydzuhri_stack_edu_python |
function showBill
begin
set totalPrice = 0
print string -----My Food ----
for number in range length menuList
begin
print menuList at number at 0 menuList at number at 1
set totalPrice = totalPrice + integer menuList at number at 1
end
print string Total totalPrice string THB
end function
while true
begin
set nameMenu ... | def showBill():
totalPrice = 0
print("-----My Food ----")
for number in range(len(menuList)):
print(menuList[number][0],menuList[number][1])
totalPrice += int(menuList[number][1])
print("Total",totalPrice,"THB")
while True:
nameMenu = input("Please Enter Menu : ")
if (nameMe... | Python | zaydzuhri_stack_edu_python |
function plot_example_images output_dir epoch generator label_imgs test_imgs imgs_count examples=4
begin
set random_ints = random integer 0 imgs_count examples
set image_batch_hr = call denormalize label_imgs at random_ints
set image_batch_lr = test_imgs at random_ints
set gen_img = predict generator image_batch_lr
set... | def plot_example_images(
output_dir, epoch, generator, label_imgs, test_imgs, imgs_count,
examples=4):
random_ints = np.random.randint(0, imgs_count, examples)
image_batch_hr = denormalize(label_imgs[random_ints])
image_batch_lr = test_imgs[random_ints]
gen_img = generator.predict(image_... | Python | nomic_cornstack_python_v1 |
function plot_confusion_matrix cm classes normalize=false title=string Confusion matrix cmap=Blues
begin
image show cm interpolation=string nearest cmap=cmap
title plt title
call colorbar
set tick_marks = array range length classes
call xticks tick_marks classes rotation=45
call yticks tick_marks classes
if normalize
b... | def plot_confusion_matrix(cm, classes, normalize=False,
title='Confusion matrix', cmap=plt.cm.Blues):
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
... | Python | nomic_cornstack_python_v1 |
function delete_by_template self template
begin
set w = call _template_to_where_clause template
set q = string delete from + _table_name + string + w at 0
comment print(q)
return call _run_q q args=w at 1 fetch=false
end function | def delete_by_template(self, template):
w = self._template_to_where_clause(template)
q = 'delete from ' + self._table_name + ' ' + w[0]
# print(q)
return self._run_q(q, args=w[1], fetch=False) | Python | nomic_cornstack_python_v1 |
import string
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer , TfidfTransformer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import confusion_matrix , classification_report
from nltk.corpus import stopwords
from ... | import string
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import confusion_matrix, classification_report
from nltk.corpus import stopwords
from s... | Python | zaydzuhri_stack_edu_python |
function run self
begin
while keep_running
begin
try
begin
call method
end
except Exception as error
begin
set exception = error
set keep_running = false
print string Service name string stopped at string call utcnow string by the following error: string error
error string Service + name + string error: + string error
... | def run(self):
while self.keep_running:
try:
self.method()
except Exception as error:
self.exception = error
self.keep_running = False
print('Service', self.name, 'stopped at ', str(datetime.utcnow()),
... | Python | nomic_cornstack_python_v1 |
function buildTable totalFuel totalCars capacity
begin
set L = dict
set p = dict
comment from totalCars to 1
for K in range totalCars 0 - 1
begin
set L at K = dict
comment from totalFuel to 0
for F in range totalFuel - 1 - 1
begin
set move = 0
set sendBack = 0
if F + 2 * K <= totalFuel
begin
if F + 2 * K + K * L at ... | def buildTable(totalFuel, totalCars, capacity):
L = {}
p = {}
for K in range(totalCars,0,-1): #from totalCars to 1
L[K] = {}
for F in range(totalFuel,-1,-1): #from totalFuel to 0
move = 0
sendBack = 0
if (F+2*K) <= totalFuel:
if F + 2*K + K*L[K][F+2*K] <= K*ca... | Python | zaydzuhri_stack_edu_python |
function call_api query_dict
begin
set actual_query_dict = dict string format string xml ; string action string query
update actual_query_dict query_dict
set query = url encode actual_query_dict
with url open API_BASE_URL + query as xml
begin
return call BeautifulSoup decode read xml string xml
end
end function | def call_api(query_dict):
actual_query_dict = {'format': 'xml', 'action': 'query'}
actual_query_dict.update(query_dict)
query = urllib.parse.urlencode(actual_query_dict)
with urlopen(API_BASE_URL + query) as xml:
return BeautifulSoup(xml.read().decode(), 'xml') | Python | nomic_cornstack_python_v1 |
function snail snail_map
begin
if snail_map == list list
begin
return list
end
if length snail_map == 1
begin
return pop snail_map
end
set array = list
return call snail_recursive snail_map array
end function
function snail_recursive snail_map array
begin
if length snail_map == 1
begin
extend array pop snail_map
ret... | def snail(snail_map: list) -> list:
if snail_map == [[]]: return []
if len(snail_map) == 1: return snail_map.pop()
array = []
return snail_recursive(snail_map, array)
def snail_recursive(snail_map: list, array: list) -> list:
if len(snail_map) == 1:
array.extend(snail_map.pop())
... | Python | zaydzuhri_stack_edu_python |
function translate_roll_axis roll_axis
begin
set translator = dict 1 string x ; 0 string y ; 2 string z
return translator at roll_axis
end function | def translate_roll_axis(roll_axis):
translator = {1: 'x', 0: 'y', 2: 'z'}
return translator[roll_axis] | Python | nomic_cornstack_python_v1 |
function countdown n
begin
if n <= 0
begin
print string Blastoff!!
end
else
begin
print n
call countdown n - 1
end
end function
print string Enter a number:
set n = input
if not is instance integer n int
begin
print string Only enter integer!
end
call countdown integer n | def countdown(n):
if n <= 0:
print("Blastoff!!")
else:
print(n)
countdown(n - 1)
print("Enter a number:")
n = input()
if not isinstance(int(n), int):
print("Only enter integer!")
countdown(int(n))
| Python | zaydzuhri_stack_edu_python |
function replaceInfrequentWords_UNK self
begin
set newList = list
comment iterate both word list and tag list to find and replace the infrequent words with suitable UNK tag
for tuple w t in zip words tags
begin
set word = w
if occurrenceMap_w at w <= infrequent
begin
if lang == string en
begin
set word = call convertW... | def replaceInfrequentWords_UNK(self):
newList = []
# iterate both word list and tag list to find and replace the infrequent words with suitable UNK tag
for w, t in zip(self.words, self.tags):
word = w
if self.occurrenceMap_w[w] <= self.infrequent:
if self.... | Python | nomic_cornstack_python_v1 |
from typing import List
comment Definition for a binary tree node.
class TreeNode
begin
function __init__ self val=0 left=none right=none
begin
set val = val
set left = left
set right = right
end function
end class
class Solution
begin
function buildTree self inorder postorder
begin
set n = length inorder
set map_inord... | from typing import List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
n = len... | Python | zaydzuhri_stack_edu_python |
function _clear_meta_info self
begin
set _meta_info = dict cluster dict ; node dict
end function | def _clear_meta_info(self):
self._meta_info = {MetaInfoScope.cluster: {}, MetaInfoScope.node: {}} | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
import numpy as np
with open string lcd_out.csv encoding=string utf-8 as f
begin
set csv = read f
end
set lines = split csv string
set data = zeros tuple 128 128
for line in lines
begin
if not strip line
begin
continue
end
set tuple x y color = list comprehension decimal x for x in split... | import matplotlib.pyplot as plt
import numpy as np
with open('lcd_out.csv', encoding='utf-8') as f:
csv = f.read()
lines = csv.split("\n")
data = np.zeros((128, 128))
for line in lines:
if not line.strip():
continue
x, y, color = [float(x) for x in line.split(",")]
if color == 0:
colo... | Python | zaydzuhri_stack_edu_python |
comment Author: Gregory Nero
comment Purpose: plots word frequency from list as a barplot
comment Date: July 20th, 2018
function word_frequency_barplot mylist title
begin
string Args: -------- mylist: list of strings title: string Returns: -------- A plot of the word frequencies in mylist Notes: -------- Function requi... | #Author: Gregory Nero
#
#Purpose: plots word frequency from list as a barplot
#
#Date: July 20th, 2018
def word_frequency_barplot(mylist, title):
'''
Args:
--------
mylist: list of strings
title: string
Returns:
--------
A plot of the word frequencies in mylist
Notes:
---... | Python | zaydzuhri_stack_edu_python |
function _check_duplicate_extensions self
begin
set result = list
for folder in folders
begin
set result = result + call get_extensions
end
comment omit files with no extension
set result = list comprehension occur for occur in result if occur
set occurrences = list comprehension count result phrase for phrase in resu... | def _check_duplicate_extensions(self):
result = []
for folder in self.folders:
result += folder.get_extensions()
# omit files with no extension
result = [occur for occur in result if occur]
occurrences = [result.count(phrase) for phrase in result]
validator ... | Python | nomic_cornstack_python_v1 |
comment O(n^2)
function inversionCount q
begin
set n = length q
set total_bribes = 0
for i in range 0 n
begin
set bribes = 0
for j in range i + 1 n
begin
if q at i > q at j
begin
set bribes = bribes + 1
end
end
if bribes > 2
begin
comment if more than 2 inversions
print string Too chaotic
break
end
else
begin
set total... | # O(n^2)
def inversionCount(q):
n = len(q)
total_bribes = 0
for i in range(0, n):
bribes = 0
for j in range(i+1, n):
if q[i] > q[j]:
bribes += 1
if bribes > 2:
print("Too chaotic") # if more than 2 inversions
break
else:
... | Python | zaydzuhri_stack_edu_python |
function run xhpl_path parse=false verbose=false early_termination=false thresh=0.5
begin
set starttime = now
end function
comment If using early termination then parsing line by line must also be enabled | def run(xhpl_path, parse=False, verbose=False, early_termination=False, thresh=0.5):
starttime = datetime.datetime.now()
# If using early termination then parsing line by line must also be enabled | Python | nomic_cornstack_python_v1 |
function build_expression_tree tokens
begin
set s = list
for t in tokens
begin
if t in string +-*/
begin
append s t
end
else
if is digit t
begin
append s call ExpressionTree t
end
else
if t == string )
begin
set right = pop s
set op = pop s
set left = pop s
append s call ExpressionTree op left right
end
end
return pop... | def build_expression_tree(tokens):
s = []
for t in tokens:
if t in '+-*/':
s.append(t)
elif t.isdigit():
s.append(ExpressionTree(t))
elif t == ')':
right = s.pop()
op = s.pop()
left = s.pop()
s.append(ExpressionTree(... | Python | nomic_cornstack_python_v1 |
function _evaluateBoard self board
begin
set score = 0
set score_map = dict PAWN list 10.0 10.0 10.0 10.0 10.0 10.0 10.0 10.0 15.0 15.0 15.0 15.0 15.0 15.0 15.0 15.0 11.0 11.0 12.0 13.0 13.0 12.0 11.0 11.0 10.5 10.5 11.0 12.5 12.5 11.0 10.5 10.5 10.0 10.0 10.0 12.0 12.0 10.0 10.0 10.0 10.5 9.5 9.0 10.0 10.0 9.0 9.5 10.... | def _evaluateBoard(self, board):
score = 0
score_map = {
chess.PAWN: [
10.0,
10.0,
10.0,
10.0,
10.0,
10.0,
10.0,
10.0,
15.0,
15.0,
... | Python | nomic_cornstack_python_v1 |
function parse self name contents
begin
try
begin
set errors = list
call set_contents name contents
set ret = parse yacc lexer=lexer tracking=true
end
except SyntaxError as e
begin
comment Place this error first since we can't continue parsing with it; but
comment keep any errors we saw already.
set errors = list e + ... | def parse(self, name, contents):
try:
self.errors = []
self.lexer.set_contents(name, contents)
ret = self.yacc.parse(lexer=self.lexer, tracking=True)
except SyntaxError as e:
# Place this error first since we can't continue parsing with it; but
# keep any errors we saw already.
... | Python | nomic_cornstack_python_v1 |
comment import the random package so that we can generate random numbers
from random import randint
comment choices is an array => a container that can hold multiple items
comment arrays are 0-based -> the first item is 0, the second is 1, etc
set choices = list string Rock string Paper string Scissors
set player = fal... | # import the random package so that we can generate random numbers
from random import randint
# choices is an array => a container that can hold multiple items
# arrays are 0-based -> the first item is 0, the second is 1, etc
choices = ["Rock", "Paper", "Scissors"]
player = False
player_lives = 5
computer_lives = 5
... | Python | zaydzuhri_stack_edu_python |
function greetings_page
begin
set form = call MyForm
if call validate_on_submit
begin
call clear_log
set text = data
set terms_ = dict string full_text text
for term in call term_extractor text nested=true
begin
if normalized not in terms_
begin
set terms_ at normalized = call get_links normalized
end
end
comment Downl... | def greetings_page():
form = MyForm()
if form.validate_on_submit():
clear_log()
text = form.input_data.data
terms_ = {'full_text': text}
for term in term_extractor(text, nested=True):
if term.normalized not in terms_:
terms_[term.normalized] = get_link... | Python | nomic_cornstack_python_v1 |
function ready self
begin
return get pulumi self string ready
end function | def ready(self) -> bool:
return pulumi.get(self, "ready") | Python | nomic_cornstack_python_v1 |
comment @lc app=leetcode.cn id=491 lang=python3
comment [491] 递增子序列
comment @lc code=start
class Solution
begin
function findSubsequences self nums
begin
set n = length nums
set res = list
set pth = list
function dfs d start_idx
begin
if d > 1
begin
append res pth at slice : :
end
comment 本层使用过的元素
set cur_layer_use... | #
# @lc app=leetcode.cn id=491 lang=python3
#
# [491] 递增子序列
#
# @lc code=start
class Solution:
def findSubsequences(self, nums):
n = len(nums)
res = []
pth = []
def dfs(d, start_idx):
if d > 1:
res.append(pth[:])
cur_layer_used = set() # 本层使用过... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
import os , sys , math
comment Area Per Lipid (chi 90 kappa 50)
set APL = 0.10983521
comment thickness
set Thick = 2.462681
function main dir_name
begin
set fin_a_name = join path dir_name string elem_in_each.txt
set fin_rg_name = join path dir_name string rg.txt
set fout_name = join path dir_n... | #!/usr/bin/python
import os, sys, math
APL = 0.10983521 # Area Per Lipid (chi 90 kappa 50)
Thick = 2.462681 # thickness
def main(dir_name):
fin_a_name = os.path.join(dir_name, "elem_in_each.txt")
fin_rg_name = os.path.join(dir_name, "rg.txt")
fout_name = os.path.join(dir_name, "sc_ratio.txt")
wi... | Python | zaydzuhri_stack_edu_python |
function definearguments self customparser
begin
if not customparser
begin
return
end
call add_option string --url dest=string url help=string Use the provided iLO URL to login. default=none
call add_option string -u string --user dest=string user help=string If you are not logged in yet, including this flag along with... | def definearguments(self, customparser):
if not customparser:
return
customparser.add_option(
'--url',
dest='url',
help="Use the provided iLO URL to login.",
default=None,
)
customparser.add_option(
'-u',... | Python | nomic_cornstack_python_v1 |
function _create_model
begin
set tableModel = call QSqlTableModel
call setTable string core
call setEditStrategy OnFieldChange
select tableModel
set headers = tuple string ID string Name string Job string Email string Mobile
for tuple columnIndex header in enumerate headers
begin
call setHeaderData columnIndex Horizont... | def _create_model():
tableModel = QSqlTableModel()
tableModel.setTable("core")
tableModel.setEditStrategy(QSqlTableModel.OnFieldChange)
tableModel.select()
headers = ("ID", "Name", "Job", "Email", "Mobile")
for columnIndex, header in enumerate(headers):
tableM... | Python | nomic_cornstack_python_v1 |
function grouped iterable n fillvalue=none
begin
set args = list iterate iterable * n
return call zip_longest *args fillvalue=fillvalue
end function | def grouped(iterable, n, fillvalue=None):
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue) | 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.