code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function parse_apidoc file_or_branch from_github=false save_github_version=true
begin
string read file and parse apiDoc lines
comment type: List[ApiEndpoint]
set apis = list
set regex = string (?P<group>\([^)]*\)){0,1} *(?P<type_>{[^}]*}){0,1} *
set regex = regex + string (?P<field>[^ ]*) *(?P<description>.*)$
set par... | def parse_apidoc(
file_or_branch,
from_github=False,
save_github_version=True
) -> List['ApiEndpoint']:
"""read file and parse apiDoc lines"""
apis = [] # type: List[ApiEndpoint]
regex = r'(?P<group>\([^)]*\)){0,1} *(?P<type_>{[^}]*}){0,1} *'
regex += r'(?P<field>[^ ]*) *(?P<description>.*)... | Python | jtatman_500k |
set unsorted_list = list 52 34 12 33 16
set sorted_list = sorted unsorted_list
comment prints [12, 16, 33, 34, 52]
print sorted_list | unsorted_list = [52, 34, 12, 33, 16]
sorted_list = sorted(unsorted_list)
print(sorted_list) # prints [12, 16, 33, 34, 52]
| Python | flytech_python_25k |
comment -*- coding: utf-8 -*-
string Created on Sun Jul 4 23:12:22 2021 @author: Farzana Eva
function generateMatrix A
begin
set tuple top bottom = tuple 0 A - 1
set tuple left right = tuple 0 A - 1
set val = 1
set direction = 1
set matrix = list comprehension list 0 * A for i in range A
while val <= A * A
begin
commen... | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 4 23:12:22 2021
@author: Farzana Eva
"""
def generateMatrix(A):
top, bottom = 0, A-1
left, right = 0, A-1
val = 1
direction = 1
matrix = [[0]*A for i in range(A)]
while val <= A*A:
if direction == 1: #left -> right
... | Python | zaydzuhri_stack_edu_python |
from collections import defaultdict
function func_a
begin
print string A
end function
function func_b
begin
print string B
end function
comment the default value for the default dict must be callable
comment when a missing key is accessed d['missing_key']
comment the below method will be invoked and will return the fin... | from collections import defaultdict
def func_a():
print('A')
def func_b():
print('B')
# the default value for the default dict must be callable
# when a missing key is accessed d['missing_key']
# the below method will be invoked and will return the finc_default object
# as value for the missing key
def get_d... | Python | zaydzuhri_stack_edu_python |
function OnRightClick self event
begin
skip
comment zoom out on right click
call set_autoscale_on true
set scl = call get_yscale
if scl == string log
begin
call set_yscale string linear
end
else
begin
call set_yscale string log
end
update self
end function | def OnRightClick(self, event):
event.Skip()
# zoom out on right click
self.axes.set_autoscale_on(True)
scl = self.axes.get_yscale()
if scl=='log':
self.axes.set_yscale('linear')
else:
self.axes.set_yscale('log')
self.Update() | Python | nomic_cornstack_python_v1 |
function ExtractSecurityMarksFromResponse response args
begin
del args
set list_asset_response = list response
assert list_asset_response msg string Asset or resource does not exist.
assert length list_asset_response == 1 msg string ListAssetResponse must only return one asset since it is filtered by Asset Name.
for as... | def ExtractSecurityMarksFromResponse(response, args):
del args
list_asset_response = list(response)
assert list_asset_response, ("Asset or resource does not exist.")
assert len(list_asset_response) == 1, (
"ListAssetResponse must only return one asset since it is filtered "
"by Asset Name.")
for a... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
import numpy as np
import time
from iminuit import Minuit
from probfit import Chi2Regression
from pycrysray import *
set rand = random
function similar a epsilon=1e-12
begin
string Return True if a.max()-a.min()<epsilon.
set aa = array a
return max - min < epsilon
end function
function sim_timi... | #!/usr/bin/python
import numpy as np
import time
from iminuit import Minuit
from probfit import Chi2Regression
from pycrysray import *
rand = np.random
def similar(a, epsilon=1e-12):
'''
Return True if a.max()-a.min()<epsilon.
'''
aa = np.array(a)
return aa.max()-aa.min()<epsilon
def sim_timing(... | Python | zaydzuhri_stack_edu_python |
import random
class Carta
begin
function __init__ self numero seme
begin
set value = numero
set seme = seme
end function
function valore self
begin
return value
end function
function __str__ self
begin
set stringa = value + string di + seme
return stringa
end function
end class
class Deck
begin
function __init__ self
b... | import random
class Carta():
def __init__(self, numero, seme):
self.value = numero
self.seme = seme
def valore(self):
return value
def __str__(self):
stringa = self.value + " di " + self.seme
return stringa
class Deck():
def __init__(self):
pass
... | Python | zaydzuhri_stack_edu_python |
comment Given a set of distinct integers, nums, return all possible subsets (the power set).
comment Note: The solution set must not contain duplicate subsets.
comment Example:
comment Input: nums = [1,2,3]
comment Output:
comment [
comment [3],
comment [1],
comment [2],
comment [1,2,3],
comment [1,3],
comment [2,3],
c... | # Given a set of distinct integers, nums, return all possible subsets (the power set).
# Note: The solution set must not contain duplicate subsets.
# Example:
# Input: nums = [1,2,3]
# Output:
# [
# [3],
# [1],
# [2],
# [1,2,3],
# [1,3],
# [2,3],
# [1,2],
# []
# ]
class Solution:
def subsets(sel... | Python | zaydzuhri_stack_edu_python |
function __listintersect self c1 c2
begin
set s2 = dict
for delta in c2
begin
set s2 at delta = 1
end
end function | def __listintersect(self, c1, c2):
s2 = {}
for delta in c2:
s2[delta] = 1
| Python | nomic_cornstack_python_v1 |
comment add libraries
import os
import pandas as pd
import datetime
import time
import ast
comment functions
function create_dataframe
begin
string this function takes all files in a data folder from the current directory and creates a dataframe from them
set files = list directory string Data
set df = call DataFrame
s... | ## add libraries
import os
import pandas as pd
import datetime
import time
import ast
## functions
def create_dataframe():
'''this function takes all files in a data folder from the current directory and creates a dataframe from them'''
files = os.listdir('Data')
df = pd.DataFrame()
path = os.get... | Python | zaydzuhri_stack_edu_python |
function analyze_parameter_value self value
begin
if is digit value
begin
return integer value
end
else
if is digit replace value string . string 1
begin
return decimal value
end
return value
end function | def analyze_parameter_value(self, value):
if value.isdigit():
return int(value)
elif value.replace('.', '', 1).isdigit():
return float(value)
return value | Python | nomic_cornstack_python_v1 |
function array_converter roodataobject obs_name
begin
try
begin
from numpy import array
end
except ImportError
begin
from array import array as array
end
comment Create the histogram with respect the observable
set histo = call createHistogram obs_name
comment Normalize
call Scale 1.0 / call Integral
set _provlist = li... | def array_converter(roodataobject,obs_name):
try:
from numpy import array
except ImportError:
from array import array as array
# Create the histogram with respect the observable
histo = roodataobject.createHistogram(obs_name)
# Normalize
histo.Scale(1.0/histo.Integral())
_pr... | Python | nomic_cornstack_python_v1 |
function find_by_id self user_id
begin
call set_function CORE_USER_GET_USERS
set response = post _url params=dict string criteria[0][key] string id ; string criteria[0][value] user_id
return json response at string users at 0
end function | def find_by_id(self, user_id: int) -> None:
self.set_function(MoodleFunction.CORE_USER_GET_USERS)
response = requests.post(self._url,
params={
"criteria[0][key]": "id",
"criteria[0][value]": user... | Python | nomic_cornstack_python_v1 |
function insert self kwargs
begin
set tuple conn cur = call get_conn_cur
set region_insert_template = string INSERT INTO "Region" (region_number, region_name) VALUES (%s, %s) RETURNING id;
set id = none
try
begin
for tuple name value in items kwargs
begin
if name in keys FIELDS
begin
set kwargs at name = call value
end... | def insert(self, kwargs):
conn, cur = get_conn_cur()
region_insert_template = "INSERT INTO \"Region\" (region_number, region_name) VALUES (%s, %s) RETURNING id;"
id = None
try:
for name, value in kwargs.items():
if name in self.FIELDS.keys():
... | Python | nomic_cornstack_python_v1 |
import serial , time , string
set ser = call Serial string /dev/ttyUSB0 9600 timeout=1
function read_n_print ser
begin
set line = read line ser
end function | import serial, time, string
ser = serial.Serial("/dev/ttyUSB0", 9600, timeout=1)
def read_n_print(ser):
line = ser.readline() | Python | zaydzuhri_stack_edu_python |
string Genetic Algorithm for music generation. Takes a user defined key and tempo and evolves a melody according to those
import random
from midiutil import MIDIFile
set POPULATION_SIZE = 10
set MAX_GENERATIONS = 100
set MUTATION_RATE = 0.05
set MAX_FITNESS = 30
comment MIDI information will be encoded by list of numbe... | """ Genetic Algorithm for music generation. Takes a user defined key and tempo and evolves a melody according to those """
import random
from midiutil import MIDIFile
POPULATION_SIZE = 10
MAX_GENERATIONS = 100
MUTATION_RATE = 0.05
MAX_FITNESS = 30
# MIDI information will be encoded by list of numbers corresponding to... | Python | zaydzuhri_stack_edu_python |
from pydub import AudioSegment
function detect_leading_silence sound silence_threshold=- 50.0 chunk_size=10
begin
string sound is a pydub.AudioSegment silence_threshold in dB chunk_size in ms iterate over chunks until you find the first one with sound
comment ms
set trim_ms = 0
while dBFS < silence_threshold
begin
set ... | from pydub import AudioSegment
def detect_leading_silence(sound, silence_threshold=-50.0, chunk_size=10):
'''
sound is a pydub.AudioSegment
silence_threshold in dB
chunk_size in ms
iterate over chunks until you find the first one with sound
'''
trim_ms = 0 # ms
while sound[trim_ms:tr... | Python | zaydzuhri_stack_edu_python |
function save_model self request obj form change
begin
call likeNumIncrease
save
end function | def save_model(self, request, obj, form, change):
obj.post.likeNumIncrease()
obj.save() | Python | nomic_cornstack_python_v1 |
function main_info_function file_name
begin
set lines = call read_pdb file
comment extracts the sequence residues lines
set all_sequences = call extract_chain_sequences lines
comment extracts the sequence of amino acids in the protein
set sequence = call chain_sequence all_sequences
set chains_in_prot = call collect_ch... | def main_info_function(file_name):
lines = read_pdb(file)
all_sequences = extract_chain_sequences(lines) #extracts the sequence residues lines
sequence = chain_sequence(all_sequences) # extracts the sequence of amino acids in the protein
chains_in_prot = collect_chain_ids(all_sequences)
pdb_info(a... | Python | nomic_cornstack_python_v1 |
string https://leetcode-cn.com/problems/subarray-sum-equals-k/ 找出所有和为 k 的连续子数组 输入:nums = [1,1,1], k = 2 输出: 2 , [1,1] 与 [1,1] 为两种不同的情况。 前缀和
from typing import List
class Solution
begin
function subarraySum_bf self nums k
begin
string 所有和为 k 的连续子数组; 通过记录前缀和,方便计算任意 i,j 之间子数组的和 数组的长度为 [1, 20,000]
set n = length nums
comme... | """
https://leetcode-cn.com/problems/subarray-sum-equals-k/
找出所有和为 k 的连续子数组
输入:nums = [1,1,1], k = 2
输出: 2 , [1,1] 与 [1,1] 为两种不同的情况。
前缀和
"""
from typing import List
class Solution:
def subarraySum_bf(self, nums: List[int], k: int) -> int:
"""
所有和为 k 的连续子数组;
通过记录前缀和,方便计算任意 i,j 之间子数组的和... | Python | zaydzuhri_stack_edu_python |
function smallest a b c
begin
if a < b and a < c
begin
print string Smallest number is a
end
else
if b < c and b < a
begin
print string Smallest number is b
end
else
begin
print string Smallest number is c
end
end function | def smallest(a, b, c):
if (a<b and a<c):
print("Smallest number is ",a)
elif (b<c and b<a):
print("Smallest number is ",b)
else:
print("Smallest number is ",c) | Python | nomic_cornstack_python_v1 |
string 学生信息录取 服务端
from socket import *
import pymysql
class Database
begin
function __init__ self
begin
set db = call connect host=string localhost port=3306 user=string root password=string 123456 database=string stu charset=string utf8
comment 创建游标(调用sql语句,获取执行结果)
set cur = call cursor
end function
comment 关闭游标和数据库
f... | """
学生信息录取
服务端
"""
from socket import *
import pymysql
class Database:
def __init__(self):
self.db = pymysql.connect(host="localhost",
port=3306,
user="root",
password="123456",
... | Python | zaydzuhri_stack_edu_python |
function FindIdxValues X
begin
set data = call select_dtypes include=list string float64
set idx = call argwhere ? call isnan values
comment add ID variable columns
set idx at tuple slice : : 1 = idx at tuple slice : : 1 + 4
set StoE = read csv string msresist/data/MS/CPTAC/IDtoExperiment.csv
assert all iloc at t... | def FindIdxValues(X):
data = X.select_dtypes(include=["float64"])
idx = np.argwhere(~np.isnan(data.values))
idx[:, 1] += 4 # add ID variable columns
StoE = pd.read_csv("msresist/data/MS/CPTAC/IDtoExperiment.csv")
assert all(StoE.iloc[:, 0] == data.columns), "Sample labels don't match."
StoE = S... | Python | nomic_cornstack_python_v1 |
string Demonstrates how an application can monitor sessions with session hooks
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
comment Random input values
set N = 40
set x = call random_normal list N
set m_real = call truncated_normal ... | ''' Demonstrates how an application can monitor sessions with session hooks '''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
# Random input values
N = 40
x = tf.random_normal([N])
m_real = tf.truncated_normal([N], mean=2.0)
b_rea... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sympy import *
from pylab import rcParams
from sympy.sets import Interval
from sympy.calculus.util import continuous_domain
set tuple x w = call symbols string x w
comment função que calcula o polinômio interpolado pela fórmula de lagrange
func... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sympy import *
from pylab import rcParams
from sympy.sets import Interval
from sympy.calculus.util import continuous_domain
x, w = symbols('x w')
#função que calcula o polinômio interpolado pela fórmula de lagrange
def interpoladoLagrange(x, ... | Python | zaydzuhri_stack_edu_python |
function lower_func v
begin
global match
set w = match at v
if w < 0
begin
set match at v = v + 1
print string lower_func: match
print string lower_func: call id match
end
return true
end function
function higher_func
begin
global match
set match = list - 1 * V
for v in range V
begin
call lower_func v
print string high... | def lower_func(v):
global match
w = match[v]
if(w < 0):
match[v] = v+1
print("lower_func:", match)
print("lower_func:", id(match))
return True
def higher_func():
global match
match = [-1] * V
for v in range(V):
lower_func(v)
print("higher_func:", match)
print("higher_func:", id(match))
return
V =... | Python | zaydzuhri_stack_edu_python |
function _XMLremoveWhitespaceNodes parent
begin
for child in list childNodes
begin
if nodeType == TEXT_NODE and strip data == string
begin
call removeChild child
end
else
begin
call removeWhitespaceNodes child
end
end
end function | def _XMLremoveWhitespaceNodes(parent):
for child in list(parent.childNodes):
if child.nodeType==node.TEXT_NODE and node.data.strip()=='':
parent.removeChild(child)
else:
removeWhitespaceNodes(child) | Python | nomic_cornstack_python_v1 |
function evaluation_periods self
begin
return get pulumi self string evaluation_periods
end function | def evaluation_periods(self) -> Optional[pulumi.Input[int]]:
return pulumi.get(self, "evaluation_periods") | Python | nomic_cornstack_python_v1 |
function alunos_impares lista_alunos
begin
set lista_impares = lista_alunos at slice 1 : : 2
return lista_impares
end function | def alunos_impares(lista_alunos):
lista_impares = lista_alunos[1::2]
return lista_impares | Python | zaydzuhri_stack_edu_python |
function non_asn_rootnames
begin
set query = filter ? where call and_ rootname == rootname
set query_results = all
print format string Query performed: {} string query
for result in query_results
begin
print result at 0
end
return query
end function | def non_asn_rootnames():
query = session.query(Master.rootname)\
.filter(~exists().where(and_(Master.rootname == WFC_asn_0.rootname)))
query_results = query.all()
print('\nQuery performed:\n\n{}\n'.format(str(query)))
for result in query_results:
print(result[0])
return query | Python | nomic_cornstack_python_v1 |
function process_options arglist=none
begin
set parser = call OptionParser arglist
comment parser.add_option("-f", "--file", dest="filename",
comment help="file to be converted", metavar="FILE")
call add_option string -c string --code dest=string selection_code help=string selection code metavar=string SELECTION_CODE
c... | def process_options(arglist=None):
parser = OptionParser(arglist)
#parser.add_option("-f", "--file", dest="filename",
# help="file to be converted", metavar="FILE")
parser.add_option("-c", "--code", dest="selection_code",
help="selection code", metavar="SELECTION_C... | Python | nomic_cornstack_python_v1 |
class InsertionSort
begin
function run self input_arr
begin
set length = length input_arr
for i in range 0 length 1
begin
set key = input_arr at i
set j = i - 1
while j >= 0 and key < input_arr at j
begin
set input_arr at j + 1 = input_arr at j
set j = j - 1
end
set input_arr at j + 1 = key
end
end function
end class | class InsertionSort:
def run(self, input_arr):
length = len(input_arr)
for i in range(0, length, 1):
key = input_arr[i]
j = i - 1
while j >= 0 and key < input_arr[j]:
input_arr[j + 1] = input_arr[j]
j -= 1
input_arr[j +... | Python | zaydzuhri_stack_edu_python |
function test_global_override self
begin
set suspect = call Suspect string sender@unittests.fuglu.org string someotherrec@unittests2.fuglu.org string /dev/null
set candidate = call DBConfig config suspect
call add_section string testsection
set string testsection string nooverride string 100
set string testsection stri... | def test_global_override(self):
suspect=Suspect(u'sender@unittests.fuglu.org','someotherrec@unittests2.fuglu.org','/dev/null')
candidate=DBConfig(self.config, suspect)
candidate.add_section('testsection')
candidate.set('testsection', 'nooverride', '100')
candida... | Python | nomic_cornstack_python_v1 |
function align_rasters raster alignraster how=mean cxsize=none cysize=none masked=false
begin
string Align two rasters so that data overlaps by geographical location Usage: (alignedraster_o, alignedraster_a, geot_a) = AlignRasters(raster, alignraster, how=np.mean) where: raster: string with location of raster to be ali... | def align_rasters(raster, alignraster, how=np.ma.mean, cxsize=None, cysize=None, masked=False):
'''
Align two rasters so that data overlaps by geographical location
Usage:
(alignedraster_o, alignedraster_a, geot_a) = AlignRasters(raster, alignraster, how=np.mean)
where:
raster: string with ... | Python | jtatman_500k |
comment -*- coding: utf-8 -*-
comment @TIME : 2021/3/16 19:58
comment @AUTHOR : Xu Bai
comment @FILE : 7-1.装饰器通常把函数替换成另一个函数.py
comment @DESCRIPTION :
string python何时执行装饰器
set registry = list
function register func
begin
print string runnig registry (%s) % func
append registry func
return func
end function
decorator re... | # -*- coding: utf-8 -*-
# @TIME : 2021/3/16 19:58
# @AUTHOR : Xu Bai
# @FILE : 7-1.装饰器通常把函数替换成另一个函数.py
# @DESCRIPTION :
"""
python何时执行装饰器
"""
registry = []
def register(func):
print('runnig registry (%s)' % func)
registry.append(func)
return func
@register
def f1():
print('runing f1()')
@register
... | Python | zaydzuhri_stack_edu_python |
function getNote self
begin
return tuple noteName at 0 accidental octave
end function | def getNote(self):
return (self.noteName[0], self.accidental, self.octave) | Python | nomic_cornstack_python_v1 |
from random import *
set pocet = integer input string Zadaj počet hesiel:
function nahodne_heslo subor
begin
set heslo = string
for i in range 8
begin
set heslo = heslo + character random integer 97 122
end
print heslo file=subor
end function
set subor = open string hesla.txt string w
for i in range pocet
begin
call n... | from random import *
pocet = int(input('Zadaj počet hesiel:'))
def nahodne_heslo(subor):
heslo = ''
for i in range(8):
heslo += chr(randint(97, 122))
print(heslo, file=subor)
subor = open('hesla.txt', 'w')
for i in range(pocet):
nahodne_heslo(subor)
subor.close()
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
from random import *
set player_score = 0
set computer_score = 0
function draw_hangman hangman
begin
set graphic = list string +-------+ | | | | | ================= string +-------+ | | | O | | | ================= string +-------+ | | | O | | | | ================= string +-------+ | | | O ... | #!/usr/bin/env python3
from random import *
player_score = 0
computer_score = 0
def draw_hangman(hangman):
graphic = [
"""
+-------+
|
|
|
|
|
=================
"""
,
"""
+-------+
| |
| O
|
|
|
=================
"""
,
"""
+-------+
| ... | Python | zaydzuhri_stack_edu_python |
function _update_pos self action
begin
raise NotImplementedError
end function | def _update_pos(self, action):
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
import math
class Cell
begin
pass
end class
string klasa Water Cell, odpowiada komorce (bloczkowi) z roznym poziomem wody
class Water_Cell extends Cell
begin
function __init__ self
begin
set level = 0
set new_level = 0
set old_level = 0
set capacity = 100
end function
function __str__ self
begin
return call zfill 3
end... | import math
class Cell: pass
'''klasa Water Cell, odpowiada komorce (bloczkowi) z roznym poziomem wody'''
class Water_Cell(Cell):
def __init__(self):
self.level=0
self.new_level=0
self.old_level=0
self.capacity=100;
def __str__(self):
return str(self.level).zfill(3)
'''klasa Solid Cell, odpowiada k... | Python | zaydzuhri_stack_edu_python |
import sys
from socket import *
from lib import Lib
set HOST = string 10.0.0.1
set PORT = 9000
set BUFSIZE = 1000
function main argv
begin
comment TO DO Your Code
comment creation of socket
set sock = call socket AF_INET SOCK_STREAM
comment bind socket to ip and port
call bind tuple HOST PORT
comment waiting for connec... | import sys
from socket import *
from lib import Lib
HOST = '10.0.0.1'
PORT = 9000
BUFSIZE = 1000
def main(argv):
# TO DO Your Code
sock = socket(AF_INET, SOCK_STREAM) #creation of socket
sock.bind((HOST,PORT)) #bind socket to ip and port
sock.listen(1) # waiting for connectiong
print("Server is Re... | Python | zaydzuhri_stack_edu_python |
comment append
append subjects string Natural language Processing
print subjects
comment insert
insert languages 3 string Bootstrap | # append
subjects.append('Natural language Processing')
print(subjects)
#insert
languages.insert(3, 'Bootstrap') | Python | zaydzuhri_stack_edu_python |
function stamp self
begin
commit connection
close cursor
close connection
end function | def stamp(self):
self.connection.commit()
self.cursor.close()
self.connection.close() | Python | nomic_cornstack_python_v1 |
function profile_sim_dist_corr current reference
begin
set ref_len = length reference
assert ref_len == length current msg string Activity Profiles must have the same length to be compared.
set result = 1 - call correlation current reference
if result < 0.0
begin
set result = 0.0
end
return result
end function | def profile_sim_dist_corr(current, reference):
ref_len = len(reference)
assert ref_len == len(
current), "Activity Profiles must have the same length to be compared."
result = 1 - dist.correlation(current, reference)
if result < 0.0: result = 0.0
return result | Python | nomic_cornstack_python_v1 |
function set_boundaries self feature_id start end organism=none sequence=none
begin
set data = dict string features list dict string uniquename feature_id ; string location dict string fmin start ; string fmax end
set data = call _update_data data organism sequence
return post string setBoundaries data
end function | def set_boundaries(self, feature_id, start, end, organism=None, sequence=None):
data = {
'features': [{
'uniquename': feature_id,
'location': {
'fmin': start,
'fmax': end,
}
}]
}
data ... | Python | nomic_cornstack_python_v1 |
function max_matches self batch
begin
comment Handle simple sequence
if not is instance batch SequenceBatch
begin
return call __call__ call SequenceBatch batch
end
comment Batched processing is not handled yet
if batch_size > 1
begin
return list comprehension call max_matches batch at b for b in range batch_size
end
co... | def max_matches(self, batch):
# Handle simple sequence
if not isinstance(batch, SequenceBatch):
return self.__call__(SequenceBatch(batch))
# Batched processing is not handled yet
if batch.batch_size > 1:
return [self.max_matches(batch[b])
for b... | Python | nomic_cornstack_python_v1 |
comment 1684. Count the Number of Consistent Strings
comment Easy
comment 30
comment 2
comment Add to List
comment Share
comment You are given a string allowed consisting of distinct characters and an array of strings words. A string is consistent if all characters in the string appear in the string allowed.
comment Re... | # 1684. Count the Number of Consistent Strings
# Easy
# 30
# 2
# Add to List
# Share
# You are given a string allowed consisting of distinct characters and an array of strings words. A string is consistent if all characters in the string appear in the string allowed.
# Return the number of consistent strings in th... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding:utf-8 -*-
import os
from datetime import datetime
from datetime import timedelta
import time
import yaml
import os
import os.path
function notify title subtitle text
begin
call system format string osascript -e 'display notification "{}" with title "{}" subtitle "{}"' tex... | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
from datetime import datetime
from datetime import timedelta
import time
import yaml
import os
import os.path
def notify(title, subtitle, text):
os.system("""
osascript -e 'display notification "{}" with title "{}" subtitle "{}"'
... | Python | zaydzuhri_stack_edu_python |
comment for working with numbers
import numpy as np
comment for plotting graphs
import matplotlib.pyplot as plt
comment import package for libraries of basic NN algorithms with flexible network
comment configurations and learning algorithms
import neurolab as nl
comment generate data points
set min_val = - 30
set max_v... | # for working with numbers
import numpy as np
# for plotting graphs
import matplotlib.pyplot as plt
# import package for libraries of basic NN algorithms with flexible network
# configurations and learning algorithms
import neurolab as nl
# generate data points
min_val = -30
max_val = 30
num_points... | Python | zaydzuhri_stack_edu_python |
comment coding=utf8
import tornado.ioloop
from tornado import stack_context
set IL = call instance | #coding=utf8
import tornado.ioloop
from tornado import stack_context
IL = tornado.ioloop.IOLoop.instance()
| Python | zaydzuhri_stack_edu_python |
import datetime
from django.contrib.auth.models import AnonymousUser , User
from django.core import serializers
from django.core.urlresolvers import reverse
from django.test import TestCase , RequestFactory , Client
from django.utils import timezone
from import views
from models import Vote , Question
comment checking... | import datetime
from django.contrib.auth.models import AnonymousUser, User
from django.core import serializers
from django.core.urlresolvers import reverse
from django.test import TestCase, RequestFactory, Client
from django.utils import timezone
from . import views
from .models import Vote, Question
# checking that... | Python | zaydzuhri_stack_edu_python |
function activate_aqua **kwargs
begin
for aqua in filter date_begin__isnull=true is_paid_activate=false
begin
if date_start < today
begin
set date_begin = today
set date_end = call date_end today aqua_aerobics
save
end
end
end function | def activate_aqua(**kwargs):
for aqua in ClientAquaAerobics.objects.filter(
date_begin__isnull=True, is_paid_activate=False):
if aqua.date_start < date.today():
aqua.date_begin = date.today()
aqua.date_end = date_end(date.today(), aqua.aqua_aerobics)
aqua.save... | Python | nomic_cornstack_python_v1 |
import numpy as np
set a = array list 1 2 3
comment a = np.array([1, 2, 3], dtype='int16')
set b = array list list 9.0 8.0 7.0 list 6.0 5.0 4.0
print b
comment Get Dimension
ndim
ndim
comment Get Shape
comment (3, )
shape
comment (2, 3)
shape
comment Get Type
comment int32
dtype
comment Get Size
comment 4
itemsize
comm... | import numpy as np
a = np.array([1, 2, 3])
# a = np.array([1, 2, 3], dtype='int16')
b = np.array( [ [ 9.0, 8.0, 7.0 ] , [ 6.0, 5.0, 4.0 ] ])
print(b)
# Get Dimension
a.ndim
b.ndim
# Get Shape
a.shape # (3, )
b.shape # (2, 3)
# Get Type
a.dtype # int32
# Get Size
a.itemsize # 4
b.itemsize # 8
# Get Total Size
a.... | Python | zaydzuhri_stack_edu_python |
function find_eyes image_path base_img_size
begin
comment TODO Make this a filter_eyes thing that also checks relative coords
set eye_cascade = call CascadeClassifier string templates/cascades/haarcascade_eye.xml
set cv2_img = call imread image_path
set gray = call cvtColor cv2_img COLOR_BGR2GRAY
set image_path = call ... | def find_eyes(
image_path: str, base_img_size: int
) -> Tuple[Tuple[int, int], Tuple[int, int]]:
# TODO Make this a filter_eyes thing that also checks relative coords
eye_cascade = cv2.CascadeClassifier('templates/cascades/haarcascade_eye.xml')
cv2_img = cv2.imread(image_path)
... | Python | nomic_cornstack_python_v1 |
set user_info = dict string name string John Doe ; string age 25 ; string gender string Male
set age = 30
if 18 <= age <= 65
begin
set user_info at string age = age
end
else
begin
print string Invalid age!
end
set gender = string Male
if gender == string Male or gender == string Female
begin
set user_info at string gen... | user_info = {
"name": "John Doe",
"age": 25,
"gender": "Male"
}
age = 30
if 18 <= age <= 65:
user_info["age"] = age
else:
print("Invalid age!")
gender = "Male"
if gender == "Male" or gender == "Female":
user_info["gender"] = gender
else:
print("Invalid gender!")
| Python | jtatman_500k |
import requests
import getpass
import time
function buildUrl after
begin
set url = string http://www.reddit.com/user/ + user + string /liked.json?limit=100
if after is not none
begin
set url = url + string &after= + after
end
return url
end function
set dictionary = dict
set likes = list
set user = call raw_input str... | import requests
import getpass
import time
def buildUrl(after):
url = 'http://www.reddit.com/user/' + user + '/liked.json?limit=100'
if(after is not None):
url = url + '&after=' + after
return url
dictionary = {}
likes = []
user = raw_input("Please input the username: ")
prompt = "Please input ... | Python | zaydzuhri_stack_edu_python |
function getDefaultSource self
begin
set xrefs = dict
for xref in call getElementsByTagName string xrefs
begin
set xrefs at value = 1
end
set xrefs = keys xrefs
set standaloneXrefs = list comprehension e for e in keys refs if e not in xrefs
print standaloneXrefs
if not standaloneXrefs
begin
raise tuple NoSourceError s... | def getDefaultSource(self):
xrefs = {}
for xref in self.grammar.getElementsByTagName("xrefs"):
xrefs[xref.attributes["id"].value] = 1
xrefs = xrefs.keys()
standaloneXrefs = [e for e in self.refs.keys() if e not in xrefs]
print(standaloneXrefs)
if not standalo... | Python | nomic_cornstack_python_v1 |
from neuron_layer import NeuronLayer
from neuron_layer import InputError
import numpy as np
class ArchError extends Exception
begin
function __init__ self message errors
begin
comment Call the base class constructor with the parameters it needs
call __init__ message
comment Now for your custom code...
set errors = erro... | from neuron_layer import NeuronLayer
from neuron_layer import InputError
import numpy as np
class ArchError(Exception):
def __init__(self, message, errors):
# Call the base class constructor with the parameters it needs
super(ArchError, self).__init__(message)
# Now for your custom code..... | Python | zaydzuhri_stack_edu_python |
function knightDialer n
begin
if n == 1
begin
return 10
end
set MOD = 10 ^ 9 + 7
set moves = list list 4 6 list 6 8 list 7 9 list 4 8 list 0 3 9 list list 1 7 0 list 2 6 list 1 3 list 2 4
set dp = list 1 * 10
for _ in range 2 n + 1
begin
set new_dp = list 0 * 10
for j in range 10
begin
for move in moves at j
begin
set... | def knightDialer(n: int) -> int:
if n == 1:
return 10
MOD = 10**9 + 7
moves = [
[4, 6], [6, 8], [7, 9], [4, 8], [0, 3, 9],
[], [1, 7, 0], [2, 6], [1, 3], [2, 4]
]
dp = [1] * 10
for _ in range(2, n + 1):
new_dp = [0] * 10
for j in range(10):
for... | Python | jtatman_500k |
function biginputterm_imp self lastup stackobject=none series_enter=EMPTYCHAR
begin
set rawbig = string
function add_mark index
begin
if string index in default_dict at string marked
begin
return POUND
end
return EMPTYCHAR
end function
while true
begin
if size command_stack == 0
begin
set temp_insert = EMPTYCHAR
if pr... | def biginputterm_imp (self,lastup,stackobject=None,series_enter=EMPTYCHAR):
rawbig = ''
def add_mark (index):
if str(index) in self.default_dict['marked']:
return POUND
return EMPTYCHAR
while True:
if command_stack.size() == 0... | Python | nomic_cornstack_python_v1 |
function __init__ self
begin
call __init__
call initUI
end function | def __init__(self):
super(MainWindow, self).__init__()
self.initUI() | Python | nomic_cornstack_python_v1 |
import csv
import json
set d = dict
with open string continents.csv string r as cont_csv
begin
set cont_read = reader cont_csv
for row in cont_read
begin
set d at row at 0 = row at 1
end
end
set j = open string continents.json string w
write j dumps d separators=tuple string , string :
close j | import csv
import json
d = {}
with open('continents.csv', 'r') as cont_csv:
cont_read = csv.reader(cont_csv)
for row in cont_read:
d[row[0]] = row[1]
j = open('continents.json', 'w')
j.write(json.dumps(d, separators = (',', ':')))
j.close()
| Python | zaydzuhri_stack_edu_python |
import random
function dString_to_iarray indata label
begin
set ilist = list
set s = string
for i in indata at label
begin
if is digit str i or i == string - or i == string .
begin
set s = s + i
end
else
if s != string
begin
append ilist integer s
set s = string
end
end
return ilist
end function
function dString_to... | import random
def dString_to_iarray(indata, label):
ilist = []
s = ''
for i in indata[label]:
if str.isdigit(i) or i == '-' or i == '.':
s += i
elif s != '':
ilist.append(int(s))
s = ''
return ilist
def dString_to_farray(indata, label='0'):
ilis... | Python | zaydzuhri_stack_edu_python |
comment 循环输入3个名字
set L = list string Bart string Lisa string Adam
set n = 0
while n <= 2
begin
print string Hello, L at n
set n = n + 1
end | #循环输入3个名字
L = ['Bart','Lisa','Adam']
n = 0
while n <= 2:
print('Hello,',L[n])
n = n + 1 | Python | zaydzuhri_stack_edu_python |
from typing import List
class Solution
begin
function merge self nums1 m nums2 n
begin
string In-place merge of two sorted integers lists to form one sorted list. Params: nums1: A sorted list of integers with right padding equal to the length of nums2. m - The number of elements initialized in nums1, excludes right pad... | from typing import List
class Solution:
def merge(self, nums1: List[int], m: int,
nums2: List[int], n: int) -> None:
'''
In-place merge of two sorted integers lists to form one sorted list.
Params:
nums1: A sorted list of integers with right padding equal ... | Python | zaydzuhri_stack_edu_python |
function deploy_token
begin
with call REDMetricsTracker
begin
info string Processing Token Contract Deployment Request request=request
set data = call validate_and_deserialize call get_json
set rpc_client = data at string client
set token_name = get data string token_name or data at string constructor_args at 1
set con... | def deploy_token():
with REDMetricsTracker():
log.info("Processing Token Contract Deployment Request", request=request)
data = token_create_schema.validate_and_deserialize(request.get_json())
rpc_client = data["client"]
token_name = data.get("token_name") or data["constructor_args"][... | Python | nomic_cornstack_python_v1 |
function requireOwn func
begin
function wrappedFunc self unit *args
begin
if owner != playerID is not self
begin
return string You do not own %s % id
end
else
begin
return call func self unit *args
end
end function
return wrappedFunc
end function | def requireOwn(func):
def wrappedFunc(self, unit,*args):
if unit.owner != self.playerID is not self:
return "You do not own %s" % unit.id
else:
return func(self, unit, *args)
return wrappedFunc | Python | nomic_cornstack_python_v1 |
import cube
import math
import numpy
import matplotlib.pyplot as plt
import random
from sortedcontainers import SortedList
function CreateStones dimension
begin
set stones = list
if dimension == 6
begin
comment working, but not solved
comment https://www.knobelbox.com/geduldsspiele/wuerfelpuzzle/9/der-t-wuerfel?c=7
se... | import cube
import math
import numpy
import matplotlib.pyplot as plt
import random
from sortedcontainers import SortedList
def CreateStones(dimension):
stones = []
if (dimension == 6):
# working, but not solved
# https://www.knobelbox.com/geduldsspiele/wuerfelpuzzle/9/der-t-wuerfel?c=7
inStones = [ [[ 0,0,0]... | Python | zaydzuhri_stack_edu_python |
from constants import Basic
class Float extends float
begin
set EPS = EPS
function __eq__ self other
begin
return absolute decimal self - decimal other < EPS
end function
function __ne__ self other
begin
return not self == other
end function
function __lt__ self other
begin
return self != other and decimal self < decim... | from constants import Basic
class Float(float):
EPS = Basic.EPS
def __eq__(self, other):
return abs(float(self) - float(other)) < self.EPS
def __ne__(self, other):
return not (self == other)
def __lt__(self, other):
return self != other and float(self) < float(other)
de... | Python | zaydzuhri_stack_edu_python |
function vsp_hard self
begin
return call immediate
end function | def vsp_hard(self):
return self.operation(PowerOffOperation.VSP).immediate() | Python | nomic_cornstack_python_v1 |
function input_to_int value
begin
if value == string 1 or value == string 2 or value == string 3 or value == string 4 or value == string 5 or value == string 6
begin
set value = integer value
return value
end
else
begin
print string Your input was invalid. Please choose from one of the options next time.
return false
e... | def input_to_int(value):
if value == "1" or value == "2" or value == "3" or value == "4" or value == "5" or value == "6":
value = int(value)
return value
else:
print("Your input was invalid. Please choose from one of the options next time.")
return False | Python | nomic_cornstack_python_v1 |
function create_staff_user user_id staff_type department_ids
begin
comment create a staff user instance
set staff = call StaffUser user_id=user_id staff_type=staff_type
comment save staff information
save
comment set the departments for the staff
set department_ids
return staff
end function | def create_staff_user(user_id: int, staff_type: int, department_ids: list):
# create a staff user instance
staff = StaffUser(
user_id=user_id,
staff_type=staff_type
)
# save staff information
staff.save()
# set the departments for the staff
staff.departments.set(department_id... | Python | nomic_cornstack_python_v1 |
function test_run_experiment
begin
with call temporary_directory as tmp_dir
begin
set yaml_content = format string --- options: resume_setup: no resume_simulation: no default_number_of_iterations: 0 output_dir: {} setup_dir: '' experiments_dir: '' minimize: no annihilate_sterics: yes molecules: T4lysozyme: filepath: {}... | def test_run_experiment():
with mmtools.utils.temporary_directory() as tmp_dir:
yaml_content = """
---
options:
resume_setup: no
resume_simulation: no
default_number_of_iterations: 0
output_dir: {}
setup_dir: ''
experime... | Python | nomic_cornstack_python_v1 |
function __init__ self
begin
set __tokens = list
set __messages = call MessageList
end function | def __init__(self):
self.__tokens = list()
self.__messages = MessageList() | Python | nomic_cornstack_python_v1 |
function send self s
begin
try
begin
set next_msg = call get_nowait
end
except QueueEmpty
begin
comment print >>sys.stderr, 'output queue for', s.getpeername(), 'is empty'
comment No messages waiting so stop checking for writability.
remove outputs s
end
except SocketError
begin
remove self s
end
try else
begin
log str... | def send(self, s):
try:
next_msg = self.mq[s.fileno()].get_nowait()
except QueueEmpty:
#print >>sys.stderr, 'output queue for', s.getpeername(), 'is empty'
# No messages waiting so stop checking for writability.
self.outputs.remove(s)
except Socket... | Python | nomic_cornstack_python_v1 |
function plot *argv
begin
comment Unpack arguments
set tuple data args features scan_features points jsd_limits masscut pt_range = argv
with call TemporaryStyle as style
begin
comment Compute yaxis range
set ranges = integer pt_range is not none + integer masscut
set mult = if expression ranges == 2 then 10.0 else if e... | def plot (*argv):
# Unpack arguments
data, args, features, scan_features, points, jsd_limits, masscut, pt_range = argv
with TemporaryStyle() as style:
# Compute yaxis range
ranges = int(pt_range is not None) + int(masscut)
mult = 10. if ranges == 2 else (5. if ranges == 1 else 1.... | Python | nomic_cornstack_python_v1 |
for index in range 1 length brackets
begin
set prev_limit = brackets at index - 1 at 1
set tuple rate limit = brackets at index
end | for index in range(1, len(brackets)):
prev_limit = brackets[index-1][1]
rate, limit = brackets[index]
| Python | zaydzuhri_stack_edu_python |
from app import Monster
class Monkey extends Monster
begin
function __init__ self *args **kwargs
begin
call __init__
set hp = 20
set xp = 5
set ascii_rep = string M
set name = string monkey
set type = string monkey
set damage = 3
for dictionary in args
begin
for key in dictionary
begin
set attribute self key dictionary... | from app import Monster
class Monkey(Monster):
def __init__(self, *args, **kwargs):
super(Monster, self).__init__()
self.hp = 20
self.xp = 5
self.ascii_rep = 'M'
self.name = 'monkey'
self.type = 'monkey'
self.damage = 3
for dictionary in args:
... | Python | zaydzuhri_stack_edu_python |
function str_from_int_list int_list
begin
set string = decode join b'' generator expression call to_bytes 4 byteorder=string big for integer in int_list string utf-8
comment remove leading or trailing whitespaces
set string = strip string
comment remove null bytes
set string = replace string string string
comment rep... | def str_from_int_list(int_list):
string = b"".join(
integer.to_bytes(4, byteorder="big") for integer in int_list
).decode("utf-8")
# remove leading or trailing whitespaces
string = string.strip()
# remove null bytes
string = string.replace("\x00", "")
# replace multiple whitespaces w... | Python | nomic_cornstack_python_v1 |
function solve n
begin
set k = split n
set g = list
set h = list
for i in k
begin
set p = upper i at 0
set k = replace i i at 0 p
append g k
end
for i in g
begin
set m = list
for j in i
begin
append m j
for k in range 1 length m
begin
set m at k = lower m at k
end
end
set s = join string m
append h s
end
set z = jo... | def solve(n):
k=n.split()
g=[]
h=[]
for i in k:
p=i[0].upper()
k=i.replace(i[0],p)
g.append(k)
for i in g:
m=[]
for j in i:
m.append(j)
for k in range(1,len(m)):
m[k]=m[k].lower()
s=''.join(m)
h.append(... | Python | zaydzuhri_stack_edu_python |
function cancel_request request_id=none request=none
begin
set request = request or call query_unique Request raise_missing=true id=request_id
set status = string CANCELED
set request = update db request
comment TODO - Metrics here?
return request
end function | def cancel_request(request_id: str = None, request: Request = None) -> Request:
request = request or db.query_unique(Request, raise_missing=True, id=request_id)
request.status = "CANCELED"
request = db.update(request)
# TODO - Metrics here?
return request | Python | nomic_cornstack_python_v1 |
function encodeBase58 b
begin
comment Convert big-endian bytes to integer
set n = integer string 0x0 + decode call hexlify b string utf8 16
comment Divide that integer into bas58
set res = list
while n > 0
begin
set tuple n r = divide mod n 58
append res B58_DIGITS at r
end
set res = join string res at slice : : - ... | def encodeBase58(b):
# Convert big-endian bytes to integer
n = int('0x0' + hexlify(b).decode('utf8'), 16)
# Divide that integer into bas58
res = []
while n > 0:
n, r = divmod(n, 58)
res.append(B58_DIGITS[r])
res = ''.join(res[::-1])
# Encode leading zeros as base58 zeros
... | Python | nomic_cornstack_python_v1 |
comment this file reads the what'sApp .txt output to generate a nice web interface
import codecs
import re
function parseTxtFile filepath outputname
begin
comment takes the file path to a what'sApp.txt chat and generates a python output
comment every line of the input file is as follows
comment date, time: number: mess... | #this file reads the what'sApp .txt output to generate a nice web interface
import codecs
import re
def parseTxtFile(filepath, outputname):
#takes the file path to a what'sApp.txt chat and generates a python output
#every line of the input file is as follows
#date, time: number: message
#note: message can be mul... | Python | zaydzuhri_stack_edu_python |
string Faça um programa que calcule as raízes de uma equação do segundo grau, na forma ax2 + bx + c. O programa deverá pedir os valores de a, b e c e fazer as consistências, informando ao usuário nas seguintes situações: a. Se o usuário informar o valor de A igual a zero, a equação não é do segundo grau e o programa nã... | """
Faça um programa que calcule as raízes de uma equação do segundo grau,
na forma ax2 + bx + c. O programa deverá pedir os valores de a, b e c e fazer
as consistências, informando ao usuário nas seguintes situações:
a. Se o usuário informar o valor de A igual a zero, a equação não é do
segundo grau e o progr... | Python | zaydzuhri_stack_edu_python |
function message_interpret_binary read
begin
comment store first byte as a string
set temp_str = string read at 5
comment join to an empty string '' and assign to opener
set opener = join string map bin bytearray temp_str string ascii
set opener_id = integer opener at slice 2 : :
comment 1010 is linefeed in ascii
if ... | def message_interpret_binary(read):
temp_str = str(read[5]) #store first byte as a string
opener = ''.join(map(bin, bytearray(temp_str, 'ascii'))) # join to an empty string '' and assign to opener
opener_id = int(opener[2:])
if opener_id == 1010: #1010 is linefeed in ascii
print('this is an ope... | Python | zaydzuhri_stack_edu_python |
import re
class Solution
begin
function diffWaysToCompute self expression strs=dict
begin
comment 遍历字符串中每一符号,递归得出符号左右子字符串不同的括号方式,其不同方式加总为结果
if not search string [\+\-\*] expression
begin
return list integer expression
end
set N = length expression
for i in range 0 N
begin
set ch = expression at i
if ch in string +-*
be... | import re
class Solution:
def diffWaysToCompute(self, expression: str, strs={}) -> List[int]:
# 遍历字符串中每一符号,递归得出符号左右子字符串不同的括号方式,其不同方式加总为结果
if not re.search("[\+\-\*]", expression):
return [int(expression)]
N = len(expression)
for i in range(0, N):
ch = expression[i]
if ch in '+-*'... | Python | zaydzuhri_stack_edu_python |
from tkinter import *
set root = call Tk
set menubar = call Menu
set filemenu = call Menu root tearoff=0
call add_command label=string New
call add_command label=string Open
call add_separator
call add_command label=string Exit
call add_cascade label=string File underline=0 menu=filemenu
set editmenu = call Menu root t... | from tkinter import *
root=Tk()
menubar=Menu()
filemenu=Menu(root,tearoff=0)
filemenu.add_command(label="New")
filemenu.add_command(label="Open")
filemenu.add_separator()
filemenu.add_command(label="Exit")
menubar.add_cascade(label="File", underline=0,menu=filemenu)
editmenu=Menu(root,tearoff=1)
editmenu.add_command(... | Python | zaydzuhri_stack_edu_python |
with open string .gitignore as f
begin
print read f
end | with open('.gitignore') as f:
print(f.read())
| Python | zaydzuhri_stack_edu_python |
class UnknownCmdError extends Exception
begin
function __init__ self cmd
begin
set message = string Unknown command type: %s % cmd
end function
function __str__ self
begin
return message
end function
end class | class UnknownCmdError(Exception):
def __init__(self, cmd):
self.message = 'Unknown command type: %s' % cmd
def __str__(self):
return self.message
| Python | zaydzuhri_stack_edu_python |
function __init__ __self__ resource_name args opts=none
begin
Ellipsis
end function | def __init__(__self__,
resource_name: str,
args: SharedTargetArgs,
opts: Optional[pulumi.ResourceOptions] = None):
... | Python | nomic_cornstack_python_v1 |
function put self key column value table=none
begin
pass
end function | def put(self, key, column, value, table=None):
pass | Python | nomic_cornstack_python_v1 |
import random
set dealer_cards = list
set player_cards = list
set player_total = sum player_cards
set dealer_total = sum dealer_cards
set player_move_array = list string placeholder
while length dealer_cards != 2
begin
append dealer_cards random integer 1 11
if length dealer_cards == 2
begin
print string
print string... | import random
dealer_cards = []
player_cards = []
player_total = sum(player_cards)
dealer_total = sum(dealer_cards)
player_move_array = ['placeholder']
while len(dealer_cards) != 2:
dealer_cards.append(random.randint(1, 11))
if len(dealer_cards) == 2:
print(" ")
print("The visible dealer car... | Python | zaydzuhri_stack_edu_python |
function task3 nums
begin
if length nums < 2
begin
return nums
end
set pivot = random choice nums
set l_nums = list comprehension n for n in nums if n < pivot
set e_nums = list pivot * count nums pivot
set r_nums = list comprehension n for n in nums if n > pivot
return call task3 l_nums + e_nums + call task3 r_nums
end... | def task3(nums):
if len(nums) < 2:
return nums
pivot = random.choice(nums)
l_nums = [n for n in nums if n < pivot]
e_nums = [pivot] * nums.count(pivot)
r_nums = [n for n in nums if n > pivot]
return task3(l_nums) + e_nums + task3(r_nums) | Python | nomic_cornstack_python_v1 |
from flask import Flask
from flask import url_for , render_template , request
from pymystem3 import Mystem
from collections import defaultdict
import re , requests , json , os , random , pymorphy2
comment from nltk import word_tokenize
set app = call Flask __name__
set m = call Mystem
set morph = call MorphAnalyzer
fun... | from flask import Flask
from flask import url_for, render_template, request
from pymystem3 import Mystem
from collections import defaultdict
import re, requests, json, os, random, pymorphy2
#from nltk import word_tokenize
app = Flask(__name__)
m = Mystem()
morph = pymorphy2.MorphAnalyzer()
def analyse_verbs(text):
... | Python | zaydzuhri_stack_edu_python |
function __call__ self letter
begin
return occurrences at letter
end function | def __call__(self, letter):
return self.occurrences[letter] | Python | nomic_cornstack_python_v1 |
from django.db import models
comment Create your models here.
comment each model is a table
class Airport extends Model
begin
set code = call CharField max_length=3
set city = call CharField max_length=64
function __str__ self
begin
return string { city } ( { code } )
end function
end class
class Flight extends Model
b... | from django.db import models
# Create your models here.
# each model is a table
class Airport(models.Model):
code = models.CharField(max_length=3)
city = models.CharField(max_length=64)
def __str__(self):
return f"{self.city} ({self.code})"
class Flight(models.Model):
# reference another ... | Python | zaydzuhri_stack_edu_python |
function action self action
begin
if action is none
begin
comment noqa: E501
raise call ValueError string Invalid value for `action`, must not be `None`
end
set _action = action
end function | def action(self, action):
if action is None:
raise ValueError("Invalid value for `action`, must not be `None`") # noqa: E501
self._action = action | Python | nomic_cornstack_python_v1 |
function boost_t inputt boost_vector gamma=- 1.0
begin
set b2 = call square_t boost_vector
if gamma < 0.0
begin
set gamma = 1.0 / square root 1.0 - b2
end
set inputt_space = inputt at tuple slice : : slice 1 : :
set bp = sum inputt_space * boost_vector - 1
set gamma2 = where b2 > 0 gamma - 1.0 / b2 zeros like b2
s... | def boost_t(inputt, boost_vector, gamma=-1.):
b2 = square_t(boost_vector)
if gamma < 0.:
gamma = 1.0 / torch.sqrt(1.0 - b2)
inputt_space = inputt[:,1:]
bp = torch.sum(inputt_space*boost_vector,-1)
gamma2=torch.where(b2>0, (gamma-1.0)/b2,torc... | Python | nomic_cornstack_python_v1 |
function say_hello
begin
print string Assalamualaikum.
end function | def say_hello():
print("Assalamualaikum.") | 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.