code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
import argparse
import json
import sys
class Json2NestedJson
begin
string main class doing json to nested json transformation
function read_stdin_input self
begin
string load input via stdin : inpit : stdin : output : python dict
set input_data = string
for line in read lines stdin
begin
set input_data = input_data + ... | import argparse
import json
import sys
class Json2NestedJson:
"""
main class doing json to nested json transformation
"""
def read_stdin_input(self):
"""
load input via stdin
: inpit : stdin
: output : python dict
"""
input_data = ''
for line ... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Sat May 29 13:11:02 2021 @author: 林
comment 108021016 林雨璇 11-3.py
import re
set a = string 床前明月光,疑是地上霜,舉頭望明月,低頭思故鄉。
set c = string 012958664、555476
set e = string I am Ironman
set g = string xyxyzzz
comment 開頭是否為'床前'
set b = find all string ^床前 a
print b
comment 結尾是否為'思故鄉... | # -*- coding: utf-8 -*-
"""
Created on Sat May 29 13:11:02 2021
@author: 林
"""
#108021016 林雨璇 11-3.py
import re
a = '床前明月光,疑是地上霜,舉頭望明月,低頭思故鄉。'
c = '012958664、555476'
e = 'I am Ironman'
g = 'xyxyzzz'
b = re.findall('^床前', a) #開頭是否為'床前'
print(b)
b1 = re.findall('思故鄉。$', a) #結尾是否為'思故鄉。'
print(b1)
b2... | Python | zaydzuhri_stack_edu_python |
function option self
begin
pass
end function | def option(self):
pass | Python | nomic_cornstack_python_v1 |
import numpy as np
function calc_standard_deviation input
begin
string :param input: 1D input data :return: standard deviation of input s = sqrt(Singma_1_n((x_i - x_avg) ^ 2) / (n - 1))
set avg = call calc_average input
set total = 0
for item in input
begin
set total = total + item - avg ^ 2
end
return square root tota... | import numpy as np
def calc_standard_deviation(input):
'''
:param input: 1D input data
:return: standard deviation of input
s = sqrt(Singma_1_n((x_i - x_avg) ^ 2) / (n - 1))
'''
avg = calc_average(input)
total = 0
for item in input:
total += (item - avg) ** 2
retur... | Python | zaydzuhri_stack_edu_python |
function make_name_expression parse_result
begin
return call NameExpression parse_result
end function | def make_name_expression(parse_result):
return expressions.NameExpression(parse_result) | Python | nomic_cornstack_python_v1 |
function getSelected self
begin
return filter lambda row -> row at active store
end function | def getSelected(self):
return filter(lambda row: row[self.active], self.store) | Python | nomic_cornstack_python_v1 |
comment 数字三角形(POJ1163)
string 在上面的数字三角形中寻找一条从顶部到底边的路径,使得路径上所经过的数字之和最大。 路径上的每一步都只能往左下或 右下走。只需要求出这个最大和即可,不必给出具体路径。 三角形的行数大于1小于等于100,数字为 0 - 99 输入格式: 5 //表示三角形的行数 接下来输入三角形 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5 要求输出最大和
comment 法一:递归
comment MaxSum(r, j)表示从D(r,j)到底边的各条路径中,最佳路径的数字之和。求 MaxSum(1,1)
comment 但是运行超时 D(r, j)出发,下一步只能走D(r+1... | # 数字三角形(POJ1163)
'''
在上面的数字三角形中寻找一条从顶部到底边的路径,使得路径上所经过的数字之和最大。
路径上的每一步都只能往左下或 右下走。只需要求出这个最大和即可,不必给出具体路径。
三角形的行数大于1小于等于100,数字为 0 - 99
输入格式:
5 //表示三角形的行数 接下来输入三角形
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
要求输出最大和
'''
# 法一:递归
# MaxSum(r, j)表示从D(r,j)到底边的各条路径中,最佳路径的数字之和。求... | Python | zaydzuhri_stack_edu_python |
function frequency self w s=1.0
begin
set x = w * s
comment Heaviside mock
set Hw = array w
set Hw at w <= 0 = 0
set Hw at w > 0 = 1
return pi ^ - 0.25 * Hw * exp - x - w0 ^ 2 / 2
end function | def frequency(self, w, s=1.0):
x = w * s
# Heaviside mock
Hw = np.array(w)
Hw[w <= 0] = 0
Hw[w > 0] = 1
return np.pi ** -0.25 * Hw * np.exp((-((x - self.w0) ** 2)) / 2) | Python | nomic_cornstack_python_v1 |
function grad_lnp gi ni wki Ii
begin
set tuple gi wfk wfki = call calc_wfk gi ni wki
set glnp = - T / wfk
return glnp
end function | def grad_lnp(gi,ni,wki,Ii):
gi, wfk, wfki = calc_wfk(gi,ni,wki)
glnp = -wfki.T/wfk
return glnp | Python | nomic_cornstack_python_v1 |
function get self item default=none
begin
try
begin
return call _get item or_raise=KeyError
end
except tuple ConfigurationError KeyError
begin
return default
end
end function | def get(self, item: str, default=None):
try:
return self._get(item, or_raise=KeyError)
except (ConfigurationError, KeyError):
return default | Python | nomic_cornstack_python_v1 |
comment facebook hackers cup 2015
comment qualification round problem 2
import sys
from itertools import combinations
set DEBUG = 0
set TESTCASE = string input/new_years_resolution_example_input.txt
function parse infile
begin
set cases = integer right strip read line infile string
set ll = list
for case in range case... | # facebook hackers cup 2015
# qualification round problem 2
import sys
from itertools import combinations
DEBUG = 0
TESTCASE = 'input/new_years_resolution_example_input.txt'
def parse(infile):
cases = int(infile.readline().rstrip('\n'))
ll = []
for case in range(cases):
gp, gc, gf = map(int, i... | Python | zaydzuhri_stack_edu_python |
function module_remove name
begin
string Removes SELinux module name The name of the module to remove .. versionadded:: 2016.11.6
set ret = dict string name name ; string result true ; string comment string ; string changes dict
set modules = call
if name not in modules
begin
set ret at string comment = format string... | def module_remove(name):
'''
Removes SELinux module
name
The name of the module to remove
.. versionadded:: 2016.11.6
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}}
modules = __salt__['selinux.list_semod']()
if name not i... | Python | jtatman_500k |
string 1) Ler um conjunto aleatório de registros do teclado; 2) Em seguida, calcule a média de cada um ; 3) Por fim, imprimir a lista de estudantes com as três notas, média e se aprovado ou não (aprovado com média igual ou superior a 7.00). OBS: Use Funções para cada ítem Lembre-se use def para: 1) Ler os registros; 2)... | '''
1) Ler um conjunto aleatório de registros do teclado;
2) Em seguida, calcule a média de cada um ;
3) Por fim, imprimir a lista de estudantes com as três notas, média e se aprovado ou não (aprovado com média igual ou superior a 7.00).
OBS: Use Funções para cada ítem
Lembre-se use def para:
1) Ler os registros;
... | Python | zaydzuhri_stack_edu_python |
function get_data_list self axis_index
begin
set data = list
comment for axes in self.view.axes[axis_index]:
set axes = axes at axis_index
if show_origin_axis
begin
for line in lines at slice : - 2 :
begin
append data tuple call get_xdata call get_ydata
end
end
else
begin
for line in lines
begin
append data tuple ca... | def get_data_list(self, axis_index):
data = []
# for axes in self.view.axes[axis_index]:
axes = self.view.axes[axis_index]
if self.show_origin_axis:
for line in axes.lines[:-2]:
data.append((line.get_xdata(), line.get_ydata()))
else:
for... | Python | nomic_cornstack_python_v1 |
comment ----------------------------
comment PY.OS ver 1.1
comment by joe
comment ----------------------------
import time
import os
import Commands
set file = list directory
call system string mode con cols=40 lines=15
function AfBoot
begin
set IorG = input string Command-line (Cl) mode or Graphics mode (Gr) not made ... | #----------------------------
# PY.OS ver 1.1
# by joe
#----------------------------
import time
import os
import Commands
file=os. listdir()
os.system("mode con cols=40 lines=15")
def AfBoot():
IorG=input("""Command-line (Cl) mode or Graphics mode (Gr) not made yet
(type Cl or Gr to select)
>""")
... | Python | zaydzuhri_stack_edu_python |
from engine import GrammarEngine
function component5a
begin
set engine = call GrammarEngine file_path=string grammars/c5a_grammar.txt
for i in range 5
begin
set output = call generate start_symbol_name=string origin debug=false
set output_list = split output string \n
for j in range length output_list
begin
print strin... | from engine import GrammarEngine
def component5a():
engine = GrammarEngine(file_path="grammars/c5a_grammar.txt")
for i in range(5):
output = engine.generate(start_symbol_name="origin", debug=False)
output_list = output.split('\\n')
for j in range (len(output_list)):
print(f"{out... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Задание 12.3 Создать функцию print_ip_table, которая отображает таблицу доступных и недоступных IP-адресов. Функция ожидает как аргументы два списка: * список доступных IP-адресов * список недоступных IP-адресов Результат работы функции - вывод на стандартный поток вывода таблицы ви... | # -*- coding: utf-8 -*-
"""
Задание 12.3
Создать функцию print_ip_table, которая отображает таблицу доступных
и недоступных IP-адресов.
Функция ожидает как аргументы два списка:
* список доступных IP-адресов
* список недоступных IP-адресов
Результат работы функции - вывод на стандартный поток вывода таблицы вида:
R... | Python | zaydzuhri_stack_edu_python |
import requests , json
from bs4 import BeautifulSoup
from multiprocessing import Pool
function searchPage page
begin
set phones = list
set r = get requests string https://www.gsmarena.com/ + page at string link
set soup = call BeautifulSoup text string lxml
for phone in select select one soup string .makers string a
b... | import requests, json
from bs4 import BeautifulSoup
from multiprocessing import Pool
def searchPage(page):
phones = []
r = requests.get('https://www.gsmarena.com/'+page['link'])
soup = BeautifulSoup(r.text, 'lxml')
for phone in soup.select_one(".makers").select("a"):
phoneName = phone.text
... | Python | zaydzuhri_stack_edu_python |
comment 出于什么样的原因,诞生了「协程」这一概念?
comment https://www.zhihu.com/question/50185085
string 程序开发的一大矛盾是,你要用控制流去完成逻辑流。 在刚开始学程序的时候,往往都是从控制流等价于执行流的情况下学起,执行到哪,就意味着逻辑走到了哪。 这样的程序结构清晰,可读性好。 但是问题是中间有些过程是不能立即得到结果的,程序为了等结果就会阻塞。这种情况多见于一些io操作。 为了提升效率,我们可以使用异步的api,通过回调/通知函数来响应操作结果,同时接着执行下一轮的逻辑。 异步回调/通知的问题在于,它把原本统一的逻辑流拆开成了几个阶段,这样控制流和逻辑流就不等价... | #出于什么样的原因,诞生了「协程」这一概念?
#https://www.zhihu.com/question/50185085
"""
程序开发的一大矛盾是,你要用控制流去完成逻辑流。
在刚开始学程序的时候,往往都是从控制流等价于执行流的情况下学起,执行到哪,就意味着逻辑走到了哪。
这样的程序结构清晰,可读性好。
但是问题是中间有些过程是不能立即得到结果的,程序为了等结果就会阻塞。这种情况多见于一些io操作。
为了提升效率,我们可以使用异步的api,通过回调/通知函数来响应操作结果,同时接着执行下一轮的逻辑。
异步回调/通知的问题在于,它把原本统一的逻辑流拆开成了几个阶段,这样控制流和逻辑流就不等价了。
为了保证逻辑数据的传... | Python | zaydzuhri_stack_edu_python |
function write_to_file self f
begin
with named temporary file suffix=string .xlsx as tmp_file
begin
save name
write f read tmp_file
end
end function | def write_to_file(self, f):
with tempfile.NamedTemporaryFile(suffix='.xlsx') as tmp_file:
self.book.save(tmp_file.name)
f.write(tmp_file.read()) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
comment -*- coding: UTF-8 -*-
set var = 1
comment 条件var等于1成立,就一直循环
while var == 1
begin
set num = call raw_input string 请输入你要的数值:
end | #!/usr/bin/python
# -*- coding: UTF-8 -*-
var = 1
while var ==1: #条件var等于1成立,就一直循环
num = raw_input("请输入你要的数值:") | Python | zaydzuhri_stack_edu_python |
import RollingHash
import time
set RollingHash = RollingHash
function KarpRabin s t
begin
comment hashing s
set rs = call RollingHash 256 2147483647
for c in s
begin
append rs c
end
set rt = call RollingHash 256 2147483647
comment hashing the string consisting of the first |s| chars
for c in t at slice : length s :
b... | import RollingHash
import time
RollingHash = RollingHash.RollingHash
def KarpRabin(s,t):
#hashing s
rs = RollingHash(256,2147483647)
for c in s: rs.append(c)
rt = RollingHash(256,2147483647)
#hashing the string consisting of the first |s| chars
for c in t[:len(s)]: rt.append(c)
if(rs... | Python | zaydzuhri_stack_edu_python |
function print self file=none
begin
set listOfValues = split currentAssignment string ,
for i in range 81
begin
print listOfValues at i end=string file=file
if i % 9 == 8
begin
print file=file
end
end
end function | def print(self, file=None):
listOfValues = self.currentAssignment.split(',')
for i in range(81):
print(listOfValues[i], end=' ', file=file)
if(i % 9 == 8):print(file=file) | Python | nomic_cornstack_python_v1 |
function requests_by_date self
begin
try
begin
set requests = all
if length requests == 0
begin
return dict string error string Not Found
end
else
begin
return dict string requests list comprehension call _request_info request for request in requests
end
end
except ValueError
begin
return dict string error string Not F... | def requests_by_date(self):
try:
requests = self.request.database.query(Request).filter(
Request.date == dt.strptime(self.request.matchdict['date'], '%Y-%m-%d').date()).all()
if len(requests) == 0:
return {"error": "Not Found"}
else:
... | Python | nomic_cornstack_python_v1 |
function sent_personal_employee_invite cls user token company
begin
set link_url = format string {}/auth/invite environ at string DEFAULT_CLIENT_HOST
set msg = call render_to_string string company_invite.html dict string company company ; string link_url link_url ; string token token
set topic = string Company invite m... | def sent_personal_employee_invite(cls, user, token, company):
link_url = '{}/auth/invite'.format(
os.environ['DEFAULT_CLIENT_HOST']
)
msg = render_to_string('company_invite.html', {
'company': company,
'link_url': link_url,
'token': token}
... | Python | nomic_cornstack_python_v1 |
function setUpTestData cls
begin
call call_command string loaddata string db.json verbosity=0
end function | def setUpTestData(cls):
call_command('loaddata', 'db.json', verbosity=0) | Python | nomic_cornstack_python_v1 |
string This module will handle all testing related to logging out of an active user.
import UserCreation
from UserCreation import UserCreation
from UserManager import UserManager
from Authenticator import Authenticator
import pytest
from unittest import mock
from unittest.mock import MagicMock
from io import StringIO
c... | '''
This module will handle all testing related to logging out of an active user.
'''
import UserCreation
from UserCreation import UserCreation
from UserManager import UserManager
from Authenticator import Authenticator
import pytest
from unittest import mock
from unittest.mock import MagicMock
from io impo... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Mon Sep 18 14:48:32 2017 @author: rocia
import tkinter as tk
set top = call Tk
set CheckVar1 = call IntVar
set CheckVar2 = call IntVar
set C1 = call Checkbutton top text=string Music variable=CheckVar1 onvalue=1 offvalue=0 height=5 width=20
s... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 18 14:48:32 2017
@author: rocia
"""
import tkinter as tk
top = tk.Tk()
CheckVar1 = tk.IntVar()
CheckVar2 = tk.IntVar()
C1 = tk.Checkbutton(top, text = "Music", variable = CheckVar1, \
onvalue = 1, offvalue = 0, height=5, \
... | Python | zaydzuhri_stack_edu_python |
for i in range 0 10
begin
set n = integer input string Digite um numero:
set i = i + 1
set soma = soma + n
end
print string A soma dos numeros é: { soma } | for i in range(0, 10):
n = int(input('Digite um numero: '))
i += 1
soma += n
print(f'A soma dos numeros é: {soma}')
| Python | zaydzuhri_stack_edu_python |
function priority_impact_factor self priority_impact_factor
begin
set _priority_impact_factor = priority_impact_factor
end function | def priority_impact_factor(self, priority_impact_factor):
self._priority_impact_factor = priority_impact_factor | Python | nomic_cornstack_python_v1 |
comment counts TF barcodes from fastq for TF screening with 10X scRNA-seq readout
from Bio import SeqIO
import csv
from collections import OrderedDict
import numpy as np
import sys
import argparse
from Bio.SeqIO.QualityIO import FastqGeneralIterator
from Bio import pairwise2
comment start index of key region
set KEY_RE... | #counts TF barcodes from fastq for TF screening with 10X scRNA-seq readout
from Bio import SeqIO
import csv
from collections import OrderedDict
import numpy as np
import sys
import argparse
from Bio.SeqIO.QualityIO import FastqGeneralIterator
from Bio import pairwise2
KEY_REGION_START = 25 #start index of key region
... | Python | zaydzuhri_stack_edu_python |
function init_piles
begin
global piles
global num_piles
comment TODO - Done
set num_piles = integer input string How many piles do you want to play with?
while num_piles <= 0 or num_piles > 15
begin
if num_piles <= 0
begin
print string Sorry, the number of piles must be greater than 0.
set num_piles = integer input str... | def init_piles():
global piles
global num_piles
# TODO - Done
num_piles = int(input("How many piles do you want to play with? "))
while num_piles <= 0 or num_piles > 15:
if num_piles <= 0:
print("Sorry, the number of piles must be greater than 0.")
num... | Python | nomic_cornstack_python_v1 |
if question > 100
begin
print string Congrats, you get a free toaster. Enjoy your toast!
end
print string Have a nice day! | if question > 100 :
print ("Congrats, you get a free toaster. Enjoy your toast!")
print ("Have a nice day!") | Python | zaydzuhri_stack_edu_python |
comment 硬币组合
string 硬币。给定数量不限的硬币,币值为25分、10分、5分和1分,编写代码计算n分有几种表示法。(结果可能会很大,你需要将结果模上1000000007) 输入: n = 5 输出:2 解释: 有两种方式可以凑成总金额: 5=5 5=1+1+1+1+1 输入: n = 10 输出:4 解释: 有四种方式可以凑成总金额: 10=10 10=5+5 10=5+1+1+1+1+1 10=1+1+1+1+1+1+1+1+1+1 ----------------------------------------- 题解:[25,10,5,1] 如果以 f(i, v) 表示前 i 种硬币构成总金额 v 的组合数,那... | # 硬币组合
'''
硬币。给定数量不限的硬币,币值为25分、10分、5分和1分,编写代码计算n分有几种表示法。(结果可能会很大,你需要将结果模上1000000007)
输入: n = 5
输出:2
解释: 有两种方式可以凑成总金额:
5=5
5=1+1+1+1+1
输入: n = 10
输出:4
解释: 有四种方式可以凑成总金额:
10=10
10=5+5
10=5+1+1+1+1+1
10=1+1+1+1+1+1+1+1+1+1
-----------------------------------------
题解:[25,10,5,1] 如果以 f(i, v) 表示前 i... | Python | zaydzuhri_stack_edu_python |
string Helper methods for parsing twiki source and html pages
function _getStr results default=string
begin
if length results > 0
begin
return string
end
else
begin
return default
end
end function
function _getAttr results attName default=string
begin
if length results > 0
begin
return results at 0 at attName
end
else
... | """ Helper methods for parsing twiki source and html pages """
def _getStr(results, default=""):
if len(results) > 0:
return results[0].string
else:
return default
def _getAttr(results, attName, default=""):
if len(results) > 0:
return results[0][attName]
else:
return d... | Python | zaydzuhri_stack_edu_python |
function swap self *args
begin
return call vectorPose2D_swap self *args
end function | def swap(self, *args):
return _almathswig.vectorPose2D_swap(self, *args) | Python | nomic_cornstack_python_v1 |
async function weather self zip_code
begin
if enable_wunderground == true
begin
set wunderground_key = call config_load false string wunderground_key
call wunderground_set_key wunderground_key
set location = call wunderground_weather_get zip_code string city get_location=true
set icon_url = call wunderground_weather_ge... | async def weather(self, zip_code : str):
if self.enable_wunderground == True:
wunderground_key = pingbot.config_load(False, 'wunderground_key')
pingbot.wunderground_set_key(wunderground_key)
location = pingbot.wunderground_weather_get(zip_code, 'city', get_location=True)
icon_url = pingbot.wunderground_w... | Python | nomic_cornstack_python_v1 |
function partition lst callback
begin
set list1 = list
set list2 = list
for element in lst
begin
if call callback element
begin
append list1 element
end
else
begin
append list2 element
end
end
return list list1 list2
end function | def partition(lst, callback):
list1 = []
list2 = []
for element in lst:
if callback(element):
list1.append(element)
else:
list2.append(element)
return [list1, list2]
| Python | zaydzuhri_stack_edu_python |
from flask import Flask , request , jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
set app = call Flask __name__
set basedir = absolute path path directory name path __file__
set config at string SQLALCHEMY_DATABASE_URI = string sqlite:/// + join path basedir string ... | from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'crud.sqlite')
db = SQLAlchemy(ap... | Python | zaydzuhri_stack_edu_python |
string
import json
from bson.son import SON
from pymarc import JSONReader
class Subfield extends object
begin
function __init__ self sub
begin
set code = sub at string code
set value = sub at string value
end function
function to_bson self
begin
return call SON data=dict string code code ; string value value
end funct... | '''
'''
import json
from bson.son import SON
from pymarc import JSONReader
class Subfield(object):
def __init__(self,sub):
self.code = sub['code']
self.value = sub['value']
def to_bson(self):
return SON(data = {'code' : self.code, 'value' : self.value})
class Controlfield(object):
def __init__(self,fiel... | Python | zaydzuhri_stack_edu_python |
function Range self
begin
return Cutoff_radius
end function | def Range(self):
return self.Cutoff_radius | Python | nomic_cornstack_python_v1 |
function get_info self
begin
set my_string = string Explosive. Model name: {}.
return format my_string name
end function | def get_info(self):
my_string = "Explosive. Model name: {}."
return my_string.format(self.name) | Python | nomic_cornstack_python_v1 |
function orderbind self order
begin
set Class = __class__
return call Class call orderbind order
end function | def orderbind(self, order):
Class = self.__class__
return Class(self.thing.orderbind(order)) | Python | nomic_cornstack_python_v1 |
function load_tmdb_credits path
begin
set df = read csv path
set json_columns = list string cast string crew
for column in json_columns
begin
set df at column = apply df at column loads
end
return df
end function | def load_tmdb_credits(path):
df = pd.read_csv(path)
json_columns = ['cast', 'crew']
for column in json_columns:
df[column] = df[column].apply(json.loads)
return df | Python | nomic_cornstack_python_v1 |
comment 参考 https://blog.csdn.net/longgb123/article/details/79090559
comment 需要管理员权限,不要再运行脚本的 cmd 框里面点击,会很卡!!!直接点击赛尔号就行!!
from pynput.mouse import Listener , Button
set events = list
set base = list - 1 - 1
function on_click x y button pressed
begin
if pressed
begin
comment 监听鼠标点击
if button == left
begin
print x y
if b... | # 参考 https://blog.csdn.net/longgb123/article/details/79090559
# 需要管理员权限,不要再运行脚本的 cmd 框里面点击,会很卡!!!直接点击赛尔号就行!!
from pynput.mouse import Listener,Button
events = []
base = [-1,-1]
def on_click(x, y, button, pressed):
if pressed:
# 监听鼠标点击
if button == Button.left:
print(x,y)
... | Python | zaydzuhri_stack_edu_python |
string 练习随机加法考试 随机数(1-10) 控制台中获取两数相加的结果
import random
set score = 0
for item in range 3
begin
set random_number01 = random integer 1 10
set random_number02 = random integer 1 10
set input_number = integer input string 请输入 + string random_number01 + string 加 + string random_number02 + string 等于
if input_number == random... | """
练习随机加法考试
随机数(1-10)
控制台中获取两数相加的结果
"""
import random
score = 0
for item in range(3):
random_number01 = random.randint(1, 10)
random_number02 = random.randint(1, 10)
input_number = int(input("请输入" + str(random_number01) + "加" + str(random_number02) + "等于"))
if input_number == random_number... | Python | zaydzuhri_stack_edu_python |
function read_amiga_center amiga_data output_fn ds
begin
set output_number = integer split base name path output_fn string . at 0 at slice - 3 : :
set halo = amiga_data at tuple slice : : 0 == output_number
set center = amiga_data at tuple halo slice 1 : 4 : at 0
return call arr center string code_length
end funct... | def read_amiga_center(amiga_data, output_fn, ds):
output_number = int(os.path.basename(output_fn).split('.')[0][-3:])
halo = amiga_data[:,0] == output_number
center = amiga_data[halo,1:4][0]
return ds.arr(center, 'code_length') | Python | nomic_cornstack_python_v1 |
while true
begin
set input_list = input string Enter a list numbers or elements separated by space or 'q' to exit the program:
set list_1 = split input_list
print string user list is list_1
set sum = 0
for i in range 0 length list_1 1
begin
if is digit list_1 at i == true
begin
set sum = sum + integer list_1 at i
end
e... | while True:
input_list = input("Enter a list numbers or elements separated by space or 'q' to exit the program: ")
list_1 = input_list.split()
print("user list is ", list_1)
sum = 0
for i in range(0, len(list_1), 1):
if list_1[i].isdigit() == True:
sum = sum + int(list_1[i])
... | Python | zaydzuhri_stack_edu_python |
while year < 10
begin
set year = year + 1
if rabbit_pop > 150
begin
set rabbit_pop = rabbit_pop - 100
end
set rabbit_pop = rabbit_pop * 2
print string In year + string year + string the rabbit population is: + string rabbit_pop + string .
end | while year < 10:
year += 1
if rabbit_pop > 150:
rabbit_pop -= 100
rabbit_pop *= 2
print('In year ' + str(year) + ' the rabbit population is: ' + \
str(rabbit_pop) + '.')
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment -*- coding: UTF-8 -*-
function print_rangoli size
begin
set ch = string a
set l = list
end function | #!/usr/bin/python
#-*- coding: UTF-8 -*-
def print_rangoli(size):
ch = 'a'
l = [] | Python | zaydzuhri_stack_edu_python |
import fnmatch
import os
from IODevice import IODevice
class Device
begin
set _PATH_TO_DEV_DIR = string /dev
set map_device = dict
set available_port = list string /dev/usbtmc0 string /dev/usbtmc1
function available_device self
begin
set list_of_path_usb_device = call _create_list_of_usb_device
for path_usb_device in ... | import fnmatch
import os
from IODevice import IODevice
class Device:
_PATH_TO_DEV_DIR = "/dev"
map_device = {}
available_port = ["/dev/usbtmc0", "/dev/usbtmc1"]
def available_device(self):
list_of_path_usb_device = self._create_list_of_usb_device()
for path_usb_device in list_of_path_... | Python | zaydzuhri_stack_edu_python |
function make_move self board
begin
set global_score = if expression is_white then - 100000000.0 else 100000000.0
set chosen_move = none
for move in legal_moves
begin
call push move
set local_score = call minimax board depth - 1 not is_white - 100000000.0 100000000.0
set cache at call hash_board board depth - 1 not is_... | def make_move(self, board):
global_score = -1e8 if self.is_white else 1e8
chosen_move = None
for move in board.legal_moves:
board.push(move)
local_score = self.minimax(board, self.depth - 1, not self.is_white, -1e8, 1e8)
self.cache[hash_board(board, ... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
import re
from collections import Counter
import sys , string
import os
import os.path
from pathlib import Path
set args = argv at slice 1 : :
if length args < 1
begin
print string usage
exit 1
end
if not exists call Path argv at 1
begin
print string usage
exit 1
end
set x = list compreh... | #!/usr/bin/env python3
import re
from collections import Counter
import sys, string
import os
import os.path
from pathlib import Path
args = sys.argv[1:]
if len(args) < 1:
print('usage')
sys.exit(1)
if not Path(sys.argv[1]).exists():
print('usage')
sys.exit(1)
x = [line.rstrip('\n') for line in open(sys.argv[1])... | Python | zaydzuhri_stack_edu_python |
function play_happy_song self
begin
if _happy_song_num is none
begin
call set_happy_song 1
end
call send_command string 141 + string _happy_song_num
end function | def play_happy_song(self):
if self._happy_song_num is None:
self.set_happy_song(1)
self._serial_conn.send_command("141 " + str(self._happy_song_num)) | Python | nomic_cornstack_python_v1 |
function getField self name
begin
return value
end function | def getField(self, name):
return self.fields[name].value | Python | nomic_cornstack_python_v1 |
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
comment Load in the data
set training_data = read csv string training_data.csv index_col=string ListingKey
set testing_data = read csv string testing... | import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
# Load in the data
training_data = pd.read_csv("training_data.csv", index_col="ListingKey")
testing_data = pd.read_csv("testing_data.csv", index_col... | Python | zaydzuhri_stack_edu_python |
function __init__ self *args
begin
pass
end function | def __init__(self,*args):
pass | Python | nomic_cornstack_python_v1 |
string Generate a random number between 1 and 9 (including 1 and 9). Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right. (Hint: remember to use the user input lessons from the very first exercise) Extras: Keep the game going until the user types “exit” Keep track o... | """
Generate a random number between 1 and 9 (including 1 and 9).
Ask the user to guess the number, then tell them whether they guessed
too low, too high, or exactly right. (Hint: remember to use the user
input lessons from the very first exercise)
Extras:
Keep the game going until the user types “exit”
Keep track of... | Python | zaydzuhri_stack_edu_python |
string from concepts import Context c = Context.fromstring(''' |human|knight|king |mysterious| King Arthur| X | X | X | | Sir Robin | X | X | | | holy grail | | | | X | ''') print(c.intension(['King Arthur', 'Sir Robin']))
string import os,glob from nltk.stem import WordNetLemmatizer from xlwt import Workbook lemmatize... | """from concepts import Context
c = Context.fromstring('''
|human|knight|king |mysterious|
King Arthur| X | X | X | |
Sir Robin | X | X | | |
holy grail | | | | X |
''')
print(c.intension(['King Arthur', 'Sir Robin']))
"""
"""
import os,glo... | Python | zaydzuhri_stack_edu_python |
comment import time
comment while True:
comment print("cada segundo")
comment time.sleep(1)
comment from tkinter import messagebox
comment siono=messagebox.askyesno("","Decidir entre sí o no")
comment if siono==True:
comment messagebox.showinfo("","Se decidió sí")
comment else:
comment messagebox.showinfo("","Se decidi... | #import time
#while True:
#print("cada segundo")
#time.sleep(1)
#from tkinter import messagebox
#siono=messagebox.askyesno("","Decidir entre sí o no")
#if siono==True:
#messagebox.showinfo("","Se decidió sí")
#else:
#messagebox.showinfo("","Se decidió no")
def bloquear(entrada):
entrad... | Python | zaydzuhri_stack_edu_python |
function predict self X
begin
comment TODO - your code here
set predictions = list
for tuple x_idx x_vec in enumerate X
begin
set x_with_one = append np list 1 x_vec
set in_products = array list comprehension list dot x_with_one weights at cls cls for cls in range classes
set sorted_prod = in_products at call argsort
... | def predict(self, X: np.ndarray) -> np.ndarray:
# TODO - your code here
predictions = []
for x_idx, x_vec in enumerate(X):
x_with_one = np.append([1], x_vec)
in_products = np.array([[np.dot(x_with_one, self.weights[cls]),
cls] for cls... | Python | nomic_cornstack_python_v1 |
import numpy as np
from scipy.io import wavfile
import matplotlib.pyplot as plt
comment Read the input file
set tuple sampling_freq audio = read wavfile string input_freq.wav
comment Normalize the values
set audio = audio / 2.0 ^ 15
comment Get length of the Numpy Array
set len_audio = length audio
comment Apply the Fo... | import numpy as np
from scipy.io import wavfile
import matplotlib.pyplot as plt
#Read the input file
sampling_freq, audio = wavfile.read('input_freq.wav')
#Normalize the values
audio = audio / (2.**15)
#Get length of the Numpy Array
len_audio = len(audio)
#Apply the Fourier transform for the first half... | Python | zaydzuhri_stack_edu_python |
class Node extends object
begin
function __init__ self data
begin
set data = data
set next = none
end function
function __repr__ self
begin
return string data
end function
end class
class LinkedList extends object
begin
function __init__ self
begin
set head = none
set length = 0
end function
function is_empty self
begi... | class Node(object):
def __init__(self, data):
self.data = data
self.next = None
def __repr__(self):
return str(self.data)
class LinkedList(object):
def __init__(self):
self.head = None
self.length = 0
def is_empty(self):
return self.length == 0
de... | Python | zaydzuhri_stack_edu_python |
set numbers = list 1 3 5 7 9 11 13 15 17 19
set sum = 0
for num in numbers
begin
set sum = sum + num
end
print string Sum: sum | numbers = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
sum = 0
for num in numbers:
sum += num
print("Sum:", sum)
| Python | jtatman_500k |
function test_svm_count
begin
assert call svms > 0
end function | def test_svm_count():
assert templates.svms() > 0 | Python | nomic_cornstack_python_v1 |
import sys
set N = integer read line stdin
set M = integer read line stdin
set S = strip read line stdin | import sys
N = int(sys.stdin.readline())
M = int(sys.stdin.readline())
S = sys.stdin.readline().strip()
| Python | zaydzuhri_stack_edu_python |
import numpy as np
import pandas as pd
import json
from fonctions import *
set meta_df = read csv string metadata_full.csv
function fonction_search keywords
begin
call give_note meta_df keywords
set top = call tolist
set list_full = list comprehension true for i in range 5
for i in range 5
begin
if string top at i at 7... | import numpy as np
import pandas as pd
import json
from fonctions import *
meta_df=pd.read_csv("metadata_full.csv")
def fonction_search(keywords):
give_note(meta_df,keywords)
top=meta_df.sort_values(by=["note"],ascending=False)[0:5].values.tolist()
list_full=[True for i in range(5)]
for i in rang... | Python | zaydzuhri_stack_edu_python |
function prune_selector_dict selector_dict
begin
set new_selector_dict = dict
for tuple sel_key sel_info in items selector_dict
begin
if sel_key == GROUPBY and get sel_info ENTRIES
begin
set new_selector_dict at sel_key = sel_info
end
if sel_key == FILTER and sel_info
begin
set new_sel_info = list
comment Getting rid... | def prune_selector_dict(selector_dict):
new_selector_dict = {}
for sel_key, sel_info in selector_dict.items():
if sel_key == GROUPBY and sel_info.get(ENTRIES):
new_selector_dict[sel_key] = sel_info
if sel_key == FILTER and sel_info:
new_sel_info = []
# Gettin... | Python | nomic_cornstack_python_v1 |
function calc x z y
begin
if z == string *
begin
set c = x * y
end
else
if z == string +
begin
set c = x + y
end
else
if z == string -
begin
set c = x - y
end
else
if z == string /
begin
set c = x / y
end
else
begin
set c = string Duzgun daxil edin
end
return c
end function
set x = integer input string X deyishenini da... | def calc(x,z,y):
if z=='*':
c=x*y
elif z=='+':
c=x+y
elif z=='-':
c=x-y
elif z=='/':
c=x/y
else:
c="Duzgun daxil edin"
return c
x=int(input("X deyishenini daxil edin:"))
y=int(input("Y deyishenini daxil edin:"))
z=input("Operatoru daxil edin:") | Python | zaydzuhri_stack_edu_python |
function test_create_mongo_client monkeypatch
begin
call setenv string MONGO_USERNAME string None
set app = call Flask __name__
set res = call create_mongo_client app=app
assert is instance res PyMongo
end function | def test_create_mongo_client(monkeypatch):
monkeypatch.setenv("MONGO_USERNAME", 'None')
app = Flask(__name__)
res = create_mongo_client(
app=app,
)
assert isinstance(res, PyMongo) | Python | nomic_cornstack_python_v1 |
function block_sites proxy_url
begin
comment Create a request instance
set req = call Request proxy_url
comment Download page data
with url open req as response
begin
set page_data = read response
end
comment Parse page data
set page_soup = call BeautifulSoup page_data string html.parser
comment Extract block-list item... | def block_sites(proxy_url):
# Create a request instance
req = urllib.request.Request(proxy_url)
# Download page data
with urllib.request.urlopen(req) as response:
page_data = response.read()
# Parse page data
page_soup = BeautifulSoup(page_data, "html.parser")
# Extract block-list ite... | Python | iamtarun_python_18k_alpaca |
comment This Python script dumps the data from csv file into SQLite3 database
import csv , sqlite3
comment con = sqlite3.connect(":memory:")
set con = call connect string ec.db
set cur = call cursor
with open string output.csv string rb as fin
begin
set dr = dict reader fin
set to_db = list comprehension tuple i at str... | # This Python script dumps the data from csv file into SQLite3 database
import csv, sqlite3
#con = sqlite3.connect(":memory:")
con = sqlite3.connect("ec.db")
cur = con.cursor()
with open('output.csv', 'rb') as fin:
dr = csv.DictReader(fin)
to_db = [(i['cl'], i['username'], i['jobname'], i['jobid'], i['st... | Python | zaydzuhri_stack_edu_python |
comment 一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下,求它在第10次落地时,共经过多少米?第10次反弹多高?
set time = integer input string 输入第几次落地:
set high_now = 100
set high_list = list
set high_amount = 100
for i in range 1 time + 1
begin
set high_now = high_now / 2
append high_list high_now
end
for high in high_list
begin
set high_amount = high_amount... | #一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下,求它在第10次落地时,共经过多少米?第10次反弹多高?
time = int(input('输入第几次落地:'))
high_now = 100
high_list = []
high_amount = 100
for i in range(1,time+1):
high_now = high_now / 2
high_list.append(high_now)
for high in high_list:
high_amount += (high * 2)
high_amount -= high_list[time-1] * 2
... | Python | zaydzuhri_stack_edu_python |
function sort_data_by_label n_data labels metrics method=string km manual_vote=none direct_label=none
begin
if direct_label is not none
begin
set label = direct_label
end
else
begin
set vote = if expression manual_vote is none then call vote else manual_vote
set label = labels at method at vote
end
set label_df = sort ... | def sort_data_by_label(n_data,labels,metrics,method='km',manual_vote=None,direct_label=None):
if direct_label is not None:
label = direct_label
else:
vote = metrics[method].vote() if manual_vote is None else manual_vote
label = labels[method][vote]
label_df=pd.DataFrame({'x':range(n_... | Python | nomic_cornstack_python_v1 |
import psycopg2
set dbname = input string Your database name:
set dbuser = input string Your database user:
set dbpswd = input string Your database password:
set conn = call connect dbname=dbname user=dbuser password=dbpswd host=string localhost
set cursor = call cursor
function sta
begin
set cmd = string SELECT descri... | import psycopg2
dbname = input("Your database name: ")
dbuser = input("Your database user: ")
dbpswd = input("Your database password: ")
conn = psycopg2.connect(
dbname=dbname,
user=dbuser,
password=dbpswd,
host='localhost')
cursor = conn.cursor()
def sta():
cmd = 'SELECT description FROM vaca... | Python | zaydzuhri_stack_edu_python |
function mk_phase3_newheader header=none debug=true
begin
set keyword_list_mandatory = list string TTYPE string TFORM
set keyword_list_optional = list string TCOMM string TUNIT string TUCD
comment keyword_list_all = keyword_list_mandatory.append(keyword_list_optional)
set keyword_list_all = keyword_list_mandatory + key... | def mk_phase3_newheader(header=None, debug=True):
keyword_list_mandatory = ['TTYPE', 'TFORM']
keyword_list_optional = ['TCOMM', 'TUNIT', 'TUCD']
# keyword_list_all = keyword_list_mandatory.append(keyword_list_optional)
keyword_list_all = keyword_list_mandatory + keyword_list_optional
print('keywo... | Python | nomic_cornstack_python_v1 |
import sys
set f = open argv at 1 string r
set cases = read line f
for case in range integer cases
begin
set blocks = integer read line f
set row = read line f
set naomi_blocks = list split strip row
set row = read line f
set ken_blocks = list split strip row
comment print "Naomi Blocks " , naomi_blocks
comment print "... | import sys
f = open(sys.argv[1], "r")
cases = f.readline()
for case in range(int(cases)):
blocks = int(f.readline())
row = f.readline()
naomi_blocks = list(row.strip().split())
row = f.readline()
ken_blocks = list(row.strip().split())
#print "Naomi Blocks " , naomi_blocks
#print "Ken Blocks " , ken_b... | Python | zaydzuhri_stack_edu_python |
function on_fail self
begin
set state = FAILURE
if graph_uuid
begin
set graph_dict = call graph_get graph_uuid
set graph = call from_dict graph_dict
set current = call vertex_by_uuid uuid
set state = state
set error = error
set exc = exc
call update_graph_states graph=graph vertex=current graph_state=state error=error
... | def on_fail(self):
self.state = FAILURE
if self.graph_uuid:
graph_dict = self.app.backend_adapter.graph_get(self.graph_uuid)
graph = Graph.from_dict(graph_dict)
current = graph.vertex_by_uuid(self.uuid)
current.state = self.state
current.error ... | Python | nomic_cornstack_python_v1 |
function mutiply_matrix A B
begin
set tuple m n = tuple length A length B at 0
set res = list comprehension list 0 * n for i in range m
for i in range m
begin
for j in range length A at 0
begin
for k in range n
begin
set res at i at k = A at i at j * B at j at k
end
end
end
return res
end function
set res = call mutipl... | def mutiply_matrix( A, B):
m, n = len(A), len(B[0])
res = [[0]*n for i in range(m)]
for i in range(m):
for j in range(len(A[0])):
for k in range(n):
res[i][k] = A[i][j]*B[j][k]
return res
res = mutiply_matrix([[1, 2, 4]], [[3], [4], [5]])
print(res) | Python | zaydzuhri_stack_edu_python |
function as_pdb self
begin
return string %-6s%5d % tuple string CONECT id + join string list comprehension string %5d % m for m in conects + string
end function | def as_pdb(self):
return "%-6s%5d" % ("CONECT", self.id) + ''.join(["%5d" % m for m in self.conects]) + '\n' | Python | nomic_cornstack_python_v1 |
function IsDownloading self
begin
if _eggcount
begin
return true
end
else
begin
return false
end
end function | def IsDownloading(self):
if self._eggcount:
return True
else:
return False | Python | nomic_cornstack_python_v1 |
function check_server_url srvurl
begin
set good_name = starts with srvurl string http:// or starts with srvurl string https://
if not good_name
begin
set msg = string You must include http(s):// in your servers address, %s doesn't % srvurl
raise call ValueError msg
end
end function | def check_server_url(srvurl):
good_name = srvurl.startswith('http://') or srvurl.startswith('https://')
if not good_name:
msg = "You must include http(s):// in your servers address, %s doesn't" % srvurl
raise ValueError(msg) | Python | nomic_cornstack_python_v1 |
comment A multiple RkNN implementation for feature selection
comment ********************************************************
comment This code is dvideds in two blocks:
comment 1st block: MODEL CONSTRUCTION
comment Based upon Li S, Harner EJ, Adjeroh DA. Random KNN feature selection algorithm this code
comment splits ... | ###
# A multiple RkNN implementation for feature selection
#********************************************************
# This code is dvideds in two blocks:
#
#1st block: MODEL CONSTRUCTION
##
##Based upon Li S, Harner EJ, Adjeroh DA. Random KNN feature selection algorithm this code
#splits dataset in s subsets of a rand... | Python | zaydzuhri_stack_edu_python |
from ui.components.button import Button
class Prompt
begin
function __init__ self text game_state game_manager action
begin
set display = display
set game_state = game_state
set game_manager = game_manager
set font = font
set text = text
set x_offset = 0.0
set y_offset = - 0.05
set ok_button = call Button string Ok but... | from ui.components.button import Button
class Prompt():
def __init__(self, text, game_state, game_manager, action):
self.display = game_state.display
self.game_state = game_state
self.game_manager = game_manager
self.font = game_state.font
self.text = text
self.x_o... | Python | zaydzuhri_stack_edu_python |
import sys
import serial
import time
import re
from os.path import join , dirname
from datetime import datetime
from threading import Thread , Lock
from audio import play_audio
set TIME_INTERVAL = 5
comment Globally accessible
set ser = call Serial string /dev/cu.usbmodem141101 9600 timeout=5
set serial_lock = lock
fun... | import sys
import serial
import time
import re
from os.path import join, dirname
from datetime import datetime
from threading import Thread, Lock
from audio import play_audio
TIME_INTERVAL = 5
# Globally accessible
ser = serial.Serial('/dev/cu.usbmodem141101', 9600, timeout=5)
serial_lock = Lock()
def eventMonitori... | Python | zaydzuhri_stack_edu_python |
set arr1 = list 1 2 3 3 4 5 5 6 7 8 9
set arr2 = list 4 5 6 6 7 8 8 10 11 12 13
comment Remove duplicate elements from arr1 and arr2
set arr1 = list set arr1
set arr2 = list set arr2
comment Combine the elements of arr1 and arr2
set arr3 = arr1 + arr2
comment Sort arr3 in ascending order
set arr3 = sorted arr3
print ar... | arr1 = [1, 2, 3, 3, 4, 5, 5, 6, 7, 8, 9]
arr2 = [4, 5, 6, 6, 7, 8, 8, 10, 11, 12, 13]
# Remove duplicate elements from arr1 and arr2
arr1 = list(set(arr1))
arr2 = list(set(arr2))
# Combine the elements of arr1 and arr2
arr3 = arr1 + arr2
# Sort arr3 in ascending order
arr3 = sorted(arr3)
print(arr3)
| Python | jtatman_500k |
comment 集合的運算
set s1 = set literal 3 4 5 6 7 8 8 9
print 10 not in s1 9 in s1
set s2 = set literal 4 5 6 7 8
comment 交集(&):取兩個資料中相同的部分
set s3 = s1 ? s2
print s3
comment 聯集(|):取兩個集合的相同資料,但不重複
set s4 = s1 ? s2
print s4
comment 差級(-):從s1中減去s2重疊的部分
set s5 = s1 - s2
print s5
comment 反交級(^):兩個集合中,取不重複的部分
set s6 = s1 ? s2
pri... | #集合的運算
s1={3,4,5,6,7,8,8,9}
print(10 not in s1, 9 in s1)
s2={4,5,6,7,8}
#交集(&):取兩個資料中相同的部分
s3=s1&s2
print(s3)
#聯集(|):取兩個集合的相同資料,但不重複
s4=s1|s2
print(s4)
#差級(-):從s1中減去s2重疊的部分
s5=s1-s2
print(s5)
#反交級(^):兩個集合中,取不重複的部分
s6=s1^s2
print(s6)
#把字串中的字母改成集合,set("字串")
sss=set("hello")
print(sss)
#dict 的多種寫法
#list裡面set
a=dict([('ap... | Python | zaydzuhri_stack_edu_python |
comment Assignment 2 - Even Odd
print string Is your number even or odd?
set num = integer input string Please enter your number:
if num % 2 == 0
begin
print string { num } is Even
end
else
begin
print string { num } is Odd
end | ### Assignment 2 - Even Odd
print("Is your number even or odd?")
num = int(input("Please enter your number: "))
if (num % 2) == 0:
print(f"{num} is Even")
else:
print(f"{num} is Odd") | Python | zaydzuhri_stack_edu_python |
function listta lista
begin
for x in lista
begin
print x
end
end function
call listta lista
append lista string d
print lista
print lista at 3
set copylista = lista
print copylista | def listta(lista):
for x in lista:
print(x)
listta(lista)
lista.append("d")
print(lista)
print(lista[3])
copylista = lista
print(copylista) | Python | zaydzuhri_stack_edu_python |
function get_version path=none
begin
if not path
begin
set path = call get_path string suricata
end
if not path
begin
return none
end
set output = check output list path string -V
if output
begin
set m = search string version ((\d+)\.(\d+)\.?(\d+|\w+)?) strip output
if m
begin
set full = call group 1
set major = call g... | def get_version(path=None):
if not path:
path = get_path("suricata")
if not path:
return None
output = subprocess.check_output([path, "-V"])
if output:
m = re.search("version ((\d+)\.(\d+)\.?(\d+|\w+)?)", output.strip())
if m:
full = m.group(1)
maj... | Python | nomic_cornstack_python_v1 |
string UPDATED ON March 19th 2020
import numpy as np
import matplotlib.pyplot as plt
from Func_b_SlipZone import *
import timeit
set start_time = call default_timer
set save_plots_to = string /Users/Peidong/0_Python_Code/Slip_SumAll/Plots/
comment Effect of Frictional Coefficient
set delta = 0.0002
set y_wide = 0.3
set... | '''
UPDATED ON March 19th 2020
'''
import numpy as np
import matplotlib.pyplot as plt
from Func_b_SlipZone import *
import timeit
start_time = timeit.default_timer()
save_plots_to = '/Users/Peidong/0_Python_Code/Slip_SumAll/Plots/'
############################################################################... | Python | zaydzuhri_stack_edu_python |
import pygame
import sys
import time
import random
call init
call init
call pre_init 22000 16 2 2049
load music string dundertale.mp3
call play
comment pygame.mixer.init()
comment pygame.mixer.pre_init(44100, -16, 2, 2048)
comment pygame.mixer.music.load('midi.midi')
comment pygame.mixer.music.play()
set size = tuple 6... | import pygame
import sys
import time
import random
pygame.init()
pygame.mixer.init()
pygame.mixer.pre_init(22000, 16, 2, 2049)
pygame.mixer.music.load("dundertale.mp3")
pygame.mixer.music.play()
#pygame.mixer.init()
#pygame.mixer.pre_init(44100, -16, 2, 2048)
#pygame.mixer.music.load('midi.midi')
#pygame.... | Python | zaydzuhri_stack_edu_python |
function test_make_predictions
begin
set test_data = call load_dataset filename=string test.csv
set test_json = to json test_data at slice 0 : 1 : orient=string records
set subject = call make_predictions test_json
assert subject is not none
assert is instance get subject string predictions at 0 float
assert ceil get ... | def test_make_predictions():
test_data = load_dataset(filename='test.csv')
test_json = test_data[0:1].to_json(orient='records')
subject = make_predictions(test_json)
assert subject is not None
assert isinstance(subject.get('predictions')[0], float)
assert math.ceil(subject.get('predictions')[... | Python | nomic_cornstack_python_v1 |
import os
import numpy as np
set filepath = string /home/kennardngpoolhua/Downloads/segment.txt
set N_GT_SEGMENTS = 1284
function check_segment_txt
begin
with open filepath string r as f
begin
set segments = read lines f
end
comment remove first line
set segments = list comprehension split strip segment string for segm... | import os
import numpy as np
filepath = '/home/kennardngpoolhua/Downloads/segment.txt'
N_GT_SEGMENTS = 1284
def check_segment_txt():
with open(filepath, 'r') as f:
segments = f.readlines()
# remove first line
segments = [segment.strip().split(' ') for segment in segments]
n_video_segments =... | Python | zaydzuhri_stack_edu_python |
function retrofit_linear X in_edges out_edges n_iter=10 alpha=none beta=none tol=0.01 lr=1.0 lr_decay=0.9 lam=1e-05 verbose=false A=none orthogonal=true
begin
set n_relation_types = length in_edges
if not alpha
begin
set alpha = lambda i -> 1
end
if not beta
begin
set beta = lambda i j r -> 1 / max list sum list compre... | def retrofit_linear(X, in_edges, out_edges, n_iter=10, alpha=None, beta=None,
tol=1e-2, lr=1.0, lr_decay=0.9, lam=1e-5, verbose=False,
A=None, orthogonal=True):
n_relation_types = len(in_edges)
if not alpha:
alpha = lambda i: 1
if not beta:
beta = lam... | Python | nomic_cornstack_python_v1 |
comment ! /usr/bin/env python3
import sys
import cv2
import argparse
import numpy as np
import math
import vtk
set _EPS = eps * 4.0
function vector_norm data axis=none out=none
begin
string Return length, i.e. Euclidean norm, of ndarray along axis. >>> v = np.random.random(3) >>> n = vector_norm(v) >>> np.allclose(n, n... | #! /usr/bin/env python3
import sys
import cv2
import argparse
import numpy as np
import math
import vtk
_EPS = np.finfo(float).eps * 4.0
def vector_norm(data, axis=None, out=None):
"""Return length, i.e. Euclidean norm, of ndarray along axis.
>>> v = np.random.random(3)
>>> n = vector_norm(v)
>>> np... | Python | zaydzuhri_stack_edu_python |
import docx
import pandas as pd
comment install openpyxl first
import openpyxl
import os
import xlsxwriter
import sys
import datetime
import re
import warnings
call reload sys
call setdefaultencoding string utf8
from docx.document import Document
from docx.oxml.table import CT_Tbl
from docx.oxml.text.paragraph import C... | import docx
import pandas as pd
import openpyxl #install openpyxl first
import os
import xlsxwriter
import sys
import datetime
import re
import warnings
reload(sys)
sys.setdefaultencoding('utf8')
from docx.document import Document
from docx.oxml.table import CT_Tbl
from docx.oxml.text.paragraph import CT_P
from docx.ta... | Python | zaydzuhri_stack_edu_python |
function was_begin_click self
begin
return _begin_clicked
end function | def was_begin_click(self) -> bool:
return self._begin_clicked | Python | nomic_cornstack_python_v1 |
function PathFindExtension self emu argv ctx=dict
begin
set tuple pszPath = argv
set cw = call get_char_width ctx
set s = call read_mem_string pszPath cw
set argv at 0 = s
set idx1 = reverse find s string \
set t = s at slice idx1 + 1 : :
set idx2 = reverse find t string .
if idx2 == - 1
begin
return pszPath + length... | def PathFindExtension(self, emu, argv, ctx={}):
pszPath, = argv
cw = self.get_char_width(ctx)
s = self.read_mem_string(pszPath, cw)
argv[0] = s
idx1 = s.rfind('\\')
t = s[idx1 + 1:]
idx2 = t.rfind('.')
if idx2 == -1:
return pszPath + len(s)
... | Python | nomic_cornstack_python_v1 |
function enter self address
begin
get driver address
end function | def enter(self, address):
self.driver.get(address) | 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.