code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment -*- coding: utf-8 -*-
comment @Time : 2020/3/9 14:35
comment @Author : WuxieYaYa
string 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。 注意你不能在买入股票前卖出股票。 示例 1: 输入: [7,1,5,3,6,4] 输出: 5 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格... | # -*- coding: utf-8 -*-
# @Time : 2020/3/9 14:35
# @Author : WuxieYaYa
"""
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。
注意你不能在买入股票前卖出股票。
示例 1:
输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
示例 2:
输... | Python | zaydzuhri_stack_edu_python |
function udp_spoof_start target_ip target_port spoofed_ip spoofed_port payload
begin
set spoofed_packet = call udp_spoof_pck target_ip target_port spoofed_ip spoofed_port payload
set sock = call socket AF_INET SOCK_RAW IPPROTO_RAW
while true
begin
call sendto spoofed_packet tuple target_ip target_port
sleep 0.01
end
en... | def udp_spoof_start(target_ip, target_port, spoofed_ip, spoofed_port, payload):
spoofed_packet = udp_spoof_pck(target_ip, target_port, spoofed_ip,
spoofed_port, payload)
sock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)
while True:
sock.sendto(spoofed_packet, (target_i... | Python | nomic_cornstack_python_v1 |
function from_dict self data
begin
set attribute self string target_queue call _generate_queue_name data
set attribute self string hostname data at string hostname
set attribute self string status string active
set attribute self string startup_info data at string startup_info
end function | def from_dict(self, data):
setattr(self, 'target_queue', self._generate_queue_name(data))
setattr(self, 'hostname', data['hostname'])
setattr(self, 'status', 'active')
setattr(self, 'startup_info', data['startup_info']) | Python | nomic_cornstack_python_v1 |
function validate_string_findall pattern file
begin
try
begin
set file_open = open file string r
end
except any
begin
info string file not found
return - 1
end
set file_data = read file_open
set ret_out = find all pattern file_data
if ret_out
begin
return tuple true ret_out
end
else
begin
return tuple false ret_out
end... | def validate_string_findall(pattern, file):
try:
file_open = open(file, 'r')
except:
logging.info("file not found")
return -1
file_data = file_open.read()
ret_out = re.findall(pattern, file_data)
if ret_out:
return True, ret_out
else:
return Fal... | Python | nomic_cornstack_python_v1 |
string Języki skryptowe - Cwiczenia - Rafał Stepkowski GD30982 - Napisz program, który liczy za użytkownika. Umożliwi użytkownikowi wprowadzenie liczby początkowej, liczby końcowej i wielkości odstępu między kolejnymi liczbami.
comment ! /usr/bin/env python3
comment -*- coding: utf-8 -*-
set start = integer input strin... | """ Języki skryptowe - Cwiczenia - Rafał Stepkowski GD30982 -
Napisz program, który liczy za użytkownika. Umożliwi użytkownikowi
wprowadzenie liczby początkowej, liczby końcowej i wielkości odstępu między kolejnymi
liczbami. """
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
start = int(input("Podaj liczbe p... | Python | zaydzuhri_stack_edu_python |
function check_file_exists self path format
begin
comment Let's consider all the latest files
for bibdoc in call list_bibdocs
begin
if call check_file_exists path format
begin
return true
end
end
return false
end function | def check_file_exists(self, path, format):
# Let's consider all the latest files
for bibdoc in self.list_bibdocs():
if bibdoc.check_file_exists(path, format):
return True
return False | Python | nomic_cornstack_python_v1 |
comment 1 - Basic
for x in range 0 151 1
begin
print x
end
comment 2 - Multiples of Five
for x in range 5 1001 5
begin
print x
end
comment 3 - Counting, the Dojo Way6
for x in range 1 101 1
begin
if x % 10 == 0
begin
print string Coding Dojo
end
else
if x % 5 == 0
begin
print string Coding
end
else
begin
print x
end
en... | # 1 - Basic
for x in range(0,151,1):
print(x)
# 2 - Multiples of Five
for x in range(5,1001,5):
print(x)
# 3 - Counting, the Dojo Way6
for x in range(1,101,1):
if x % 10 == 0:
print('Coding Dojo')
elif x % 5 == 0:
print('Coding')
else:
print(x)
# 4 - Whoa. T... | Python | zaydzuhri_stack_edu_python |
comment Next Prime Number - Have the program find prime numbers until the user chooses to stop asking for the next one.
set prime_no = list
set prime_count = 1
for num in range 2 1001
begin
if num > 1
begin
for i in range 2 num
begin
if num % i == 0
begin
break
end
end
for else
begin
append prime_no num
end
end
end
pr... | #Next Prime Number - Have the program find prime numbers until the user chooses to stop asking for the next one.
prime_no = []
prime_count = 1
for num in range(2,1001):
if num>1:
for i in range(2,num):
if num%i == 0:
break
else:
prime_no.append(num)
print("We... | Python | zaydzuhri_stack_edu_python |
for i in s
begin
if i < string a or i > string z and i != string
begin
set s = replace s i string
end
end
set s = replace s string string
strip s
set lst = split s string
set Name = string
for x in lst
begin
if x != lst at - 1
begin
set Name = Name + x at 0
end
end
set Name = Name + string . + lst at - 1
print Name | for i in s:
if (i<'a' or i>'z') and i!=' ':
s = s.replace(i, "")
s= s.replace(" ",' ')
s.strip()
lst = s.split(" ")
Name =""
for x in lst:
if x != lst[-1]:
Name = Name + x[0]
Name= Name +'.'+lst[-1]
print(Name)
| Python | zaydzuhri_stack_edu_python |
function lift_chart self pos_label=none
begin
set pos_label = if expression pos_label == none and length classes == 2 then classes at 1 else pos_label
if pos_label not in classes
begin
raise call ValueError string 'pos_label' must be one of the response column classes
end
set input_relation = call deploySQL + format st... | def lift_chart(self,
pos_label = None):
pos_label = self.classes[1] if (pos_label == None and len(self.classes) == 2) else pos_label
if (pos_label not in self.classes):
raise ValueError("'pos_label' must be one of the response column classes")
input_relation = self.deploySQL() + " WHERE predict_knc = '... | Python | nomic_cornstack_python_v1 |
function test_meta_interpretation self
begin
function print_location a
begin
return string a=%d % a
end function
set jitdriver = call JitDriver greens=list string a reds=string auto get_printable_location=print_location
function test a b
begin
while a > b
begin
call jit_merge_point a=a
set b = b + 1
end
return 42
end f... | def test_meta_interpretation(self):
def print_location(a):
return "a=%d" % a
jitdriver = JitDriver(greens=['a'], reds='auto', get_printable_location=print_location)
def test(a, b):
while a > b:
jitdriver.jit_merge_point(a=a)
b += 1
... | Python | nomic_cornstack_python_v1 |
string # pygame 游戏编程:按以下要求定义一个乌龟类和鱼类并尝试编写游戏 假设游戏场景为范围(x,y)为0<=x<=10,0<=y<=10 游戏生成1只乌龟和10条鱼 它们的移动方向均随机 乌龟的最大移动能力为2(它可以随机选择1还是2移动),鱼儿的最大移动能力是1 当移动到场景边缘,自动向反方向移动 乌龟初始化体力为100(上限) 乌龟每移动一次,体力消耗1 当乌龟和鱼坐标重叠,乌龟吃掉鱼,乌龟体力增加20 鱼暂不计算体力 当乌龟体力值为0(挂掉)或者鱼儿的数量为0游戏结束
import random
from colorFont import *
class Animal extends object
begin
... | """
# pygame
游戏编程:按以下要求定义一个乌龟类和鱼类并尝试编写游戏
假设游戏场景为范围(x,y)为0<=x<=10,0<=y<=10
游戏生成1只乌龟和10条鱼
它们的移动方向均随机
乌龟的最大移动能力为2(它可以随机选择1还是2移动),鱼儿的最大移动能力是1
当移动到场景边缘,自动向反方向移动
乌龟初始化体力为100(上限)
乌龟每移动一次,体力消耗1
当乌龟和鱼坐标重叠,乌龟吃掉鱼,乌龟体力增加20
鱼暂不计算体力
当乌龟体力值为0(挂掉)或者鱼儿的数量为0游戏结束
"""
import random
from colorFont im... | Python | zaydzuhri_stack_edu_python |
function write_reference reference_uint8 path_to_checking_r list_rotation positions_top_left
begin
for i in range shape at 0
begin
set paths = list join path path_to_checking_r format string reference/reference_{}.png i
set paths = paths + list comprehension join path path_to_checking_r format string reference/referenc... | def write_reference(reference_uint8, path_to_checking_r, list_rotation, positions_top_left):
for i in range(reference_uint8.shape[0]):
paths = [os.path.join(path_to_checking_r, 'reference/reference_{}.png'.format(i))]
paths += [os.path.join(path_to_checking_r, 'reference/reference_{0}_crop_{1}.png'.... | Python | nomic_cornstack_python_v1 |
string this is the main pyglet/pymunk relation file, the world/simulation specific stuff will be handled by the various classes of the worlds.py file referenced in pymunk_space the idea here is that this file should never really have to be changed to render a different world, except to call a different world on one lin... | """this is the main pyglet/pymunk relation file,
the world/simulation specific stuff will be handled by the various classes of the worlds.py file referenced in pymunk_space
the idea here is that this file should never really have to be changed to render a different world, except to call a diffe... | Python | zaydzuhri_stack_edu_python |
function test_method_new_with_two_params self
begin
set obj = call BaseModel
set regex = string takes 2 positional arguments but 3 were given
with call assertRaisesRegex TypeError regex
begin
call new obj none
end
with call assertRaisesRegex TypeError regex
begin
call new obj list
end
with call assertRaisesRegex TypeEr... | def test_method_new_with_two_params(self):
obj = BaseModel()
regex = 'takes 2 positional arguments but 3 were given'
with self.assertRaisesRegex(TypeError, regex):
storage.new(obj, None)
with self.assertRaisesRegex(TypeError, regex):
storage.new(obj, [])
... | Python | nomic_cornstack_python_v1 |
import numpy as np
import matplotlib.pyplot as plt
import datetime
import unittest
import tomograph
from main import compute_tomograph , gaussian_elimination , back_substitution , compute_cholesky , solve_cholesky
class Tests extends TestCase
begin
function test_gaussian_elimination self
begin
set A = randn 4 4
set x =... | import numpy as np
import matplotlib.pyplot as plt
import datetime
import unittest
import tomograph
from main import compute_tomograph, gaussian_elimination, back_substitution, compute_cholesky, solve_cholesky
class Tests(unittest.TestCase):
def test_gaussian_elimination(self):
A = np.random.randn(4, 4)
... | Python | zaydzuhri_stack_edu_python |
function kmeans K X distance num_times=5 max_iter=50
begin
for i in range num_times
begin
set tuple cZ cM cJ cN = call kmeans_ K X distance max_iter
if i == 0 or cJ < J
begin
set J = cJ
set Z = cZ
set M = cM
end
end
return tuple Z M
end function | def kmeans(K, X, distance, num_times=5, max_iter=50):
for i in range(num_times):
cZ, cM, cJ, cN = kmeans_(K, X, distance, max_iter)
if i==0 or cJ < J:
J = cJ
Z = cZ
M = cM
return Z, M | Python | nomic_cornstack_python_v1 |
function getSessionsBySpeaker self request
begin
set sessions = call _getSessionsBySpeaker request
comment Return individual SessionForm object per Session
return call SessionForms items=list comprehension call _copySessionToForm session for session in sessions
end function | def getSessionsBySpeaker(self, request):
sessions = self._getSessionsBySpeaker(request)
# Return individual SessionForm object per Session
return SessionForms(
items=[self._copySessionToForm(session) for session in sessions]
) | Python | nomic_cornstack_python_v1 |
function split_parameter_replacement_list list_string delim=PARAMETER_SEPARATOR
begin
if list_string is none or list_string == string
begin
return list
end
if is instance list_string Number
begin
comment Empty cells in pandas might be turned into nan
comment We might want to allow nan as replacement...
if call isnan ... | def split_parameter_replacement_list(
list_string: Union[str, numbers.Number],
delim: str = PARAMETER_SEPARATOR) -> List[Union[str, numbers.Number]]:
if list_string is None or list_string == '':
return []
if isinstance(list_string, numbers.Number):
# Empty cells in pandas might ... | Python | nomic_cornstack_python_v1 |
comment Thin wrapper for blinkyeyes.BlinkyEyes() to integrate with the sense/plan/
comment act loop of a classrobot.Robot()
comment Copyright Brian Starkey 2014 <stark3y@gmail.com>
import Queue
import threading
import PiWars.blinkyeyes
class EyeManager
begin
function __init__ self
begin
set eyes = call BlinkyEyes
set a... | # Thin wrapper for blinkyeyes.BlinkyEyes() to integrate with the sense/plan/
# act loop of a classrobot.Robot()
# Copyright Brian Starkey 2014 <stark3y@gmail.com>
import Queue
import threading
import PiWars.blinkyeyes
class EyeManager:
def __init__(self):
self.eyes = PiWars.blinkyeyes.BlinkyEyes()
... | Python | zaydzuhri_stack_edu_python |
from dtree import *
from id3 import *
import random
import sys
function get_file
begin
string Tries to extract a filename from the command line. If none is present, it prompts the user for a filename and tries to open the file. If the file exists, it returns it, otherwise it prints an error message and ends execution.
... | from dtree import *
from id3 import *
import random
import sys
def get_file():
"""
Tries to extract a filename from the command line. If none is present, it
prompts the user for a filename and tries to open the file. If the file
exists, it returns it, otherwise it prints an error message and ends
... | Python | zaydzuhri_stack_edu_python |
function method
begin
set a = set list comprehension x for x in numbers if count numbers x > 1
return length a
end function
print call method | def method():
a = set([x for x in numbers if numbers.count(x) > 1])
return len(a)
print(method())
| Python | zaydzuhri_stack_edu_python |
function next self
begin
if call isquiet
begin
raise call QueueNoNext
end
comment Delete old item
set qcurr = base + string . + string curr
call unlink qcurr
comment Next item
set curr = curr + 1
call _setcurr curr
return head self
end function | def next(self):
if self.isquiet():
raise QueueNoNext()
# Delete old item
qcurr = self.base + "." + str(self.curr)
os.unlink(qcurr)
# Next item
self.curr += 1
self._setcurr(self.curr)
return self.head() | Python | nomic_cornstack_python_v1 |
from collections import deque
function reverse_bits num
begin
set stack = deque list
for i in range 32
begin
if expression num ? 1 ? i then append stack 1 else append stack 0
end
print stack
set result = 0
while stack
begin
set value = call popleft
set result = result * 2
if value == 1
begin
set result = result + 1
end... | from collections import deque
def reverse_bits(num):
stack = deque([])
for i in range(32):
stack.append(1) if num & (1 << i) else stack.append(0)
print(stack)
result = 0
while stack:
value = stack.popleft()
result *= 2
if value == 1:
result += 1
prin... | Python | zaydzuhri_stack_edu_python |
function _cleanup_orphaned_chunks self dry_run
begin
string Fixes any chunks who have parent pointers to missing versions. Removes the broken parent pointer and, if there are no other parent pointers for the chunk, removes the chunk.
set lib = self
set chunks_coll = _collection
set versions_coll = versions
info string ... | def _cleanup_orphaned_chunks(self, dry_run):
"""
Fixes any chunks who have parent pointers to missing versions.
Removes the broken parent pointer and, if there are no other parent pointers for the chunk,
removes the chunk.
"""
lib = self
chunks_coll = lib._collect... | Python | jtatman_500k |
comment Python program to illustrate
comment closures
comment A Closure is a function object that remembers values in enclosing scopes even if they are not present in memory.
comment It is a record that stores a function together with an environment: a mapping associating each free variable of
comment the function (var... | # Python program to illustrate
# closures
# A Closure is a function object that remembers values in enclosing scopes even if they are not present in memory.
#
# It is a record that stores a function together with an environment: a mapping associating each free variable of
# the function (variables that are used locally... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment -*- coding: utf-8 -*-
from random import randint
function Is_equal answer num
begin
if answer < num
begin
print string too small!
return false
end
else
if answer > num
begin
print string too big!
return false
end
else
begin
print string bingo!
return true
end
end function
set ret = fals... | #!/usr/bin/python
#-*- coding: utf-8 -*-
from random import randint
def Is_equal(answer,num):
if answer < num:
print("too small!")
return False
elif answer > num:
print("too big!")
return False
else:
print("bingo!")
return True
##########################################
ret = False
name = raw_input("请输... | Python | zaydzuhri_stack_edu_python |
for c in range 1 100
begin
for p in range 1 100
begin
for k in range 1 100
begin
set animals = c + p + k
if animals == 100
begin
set price = c * 10 + p * 3 + k / 2
if price == 100
begin
print string cows= c string pigs= p string chickens= k
end
end
end
end
end
print string all done!
exit 1 | for c in range(1,100):
for p in range(1,100):
for k in range(1,100):
animals = c + p + k
if animals == 100:
price = c*10 + p*3 + k/2
if price == 100:
print("cows=", c, " pigs=", p, " chickens=", k)
print("all done!")
exit(1)
| Python | zaydzuhri_stack_edu_python |
comment ρ a test sűrűsége, kg/m³
comment m a test teljes tömege, kg
comment V a test teljes térfogata, m³,
function suruseg m V
begin
set ρ : float
set ρ = m / V
return ρ
end function
function soros R1 R2
begin
set Re : float
set Re = R1 + R2
return Re
end function
function parhuzamos R1 R2
begin
set Re : float
set Re ... | # ρ a test sűrűsége, kg/m³
#
# m a test teljes tömege, kg
#
# V a test teljes térfogata, m³,
def suruseg(m: float, V: float):
ρ: float
ρ = m / V
return ρ
def soros(R1: float, R2: float):
Re: float
Re = R1+R2
return Re
def parhuzamos(R1: float, R2: float):
Re: float
Re = (R... | Python | zaydzuhri_stack_edu_python |
comment 상, 하, 좌, 우
set dx = list - 1 1 0 0
set dy = list 0 0 - 1 1
if __name__ == string __main__
begin
set tuple n m k = map int split input
set array = list comprehension list map int split input for _ in range n
comment 각 상어의 방향
set direction = list map int split input
comment 상어 정보를 dictionary 형태로 저장
set shark = di... | # 상, 하, 좌, 우
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
if __name__ == "__main__":
n, m, k = map(int, input().split())
array = [list(map(int, input().split())) for _ in range(n)]
direction = list(map(int, input().split())) # 각 상어의 방향
shark = {} # 상어 정보를 dictionary 형태로 저장
for i in range(n):
for... | Python | zaydzuhri_stack_edu_python |
from src.dao.ClientDAO import ClientDAO
from src.repo.inmemory.ClientRepo import ClientRepo
class ClientFileRepository extends ClientRepo
begin
function __init__ self fileName
begin
call __init__
set __fileName = fileName
set __file = none
end function
function hasClientWithId self clientId
begin
call __loadRepo
set ha... | from src.dao.ClientDAO import ClientDAO
from src.repo.inmemory.ClientRepo import ClientRepo
class ClientFileRepository(ClientRepo):
def __init__(self, fileName) -> None:
super().__init__()
self.__fileName = fileName
self.__file = None
def hasClientWithId(self, clientId):
self... | Python | zaydzuhri_stack_edu_python |
function sort_dict_with_value data
begin
return list comprehension list k v for tuple k v in sorted items data key=lambda item -> item at 1
end function | def sort_dict_with_value(data):
return [[k, v] for k, v in sorted(data.items(), key=lambda item: item[1])] | Python | nomic_cornstack_python_v1 |
function GetRegionDisk self disk_name region=none
begin
set disks = call RegionDisks
if match RESOURCE_ID_REGEX disk_name
begin
set disk = get disks disk_name
end
else
begin
set disk = call _FindResourceByName disks disk_name region=region
end
if not disk
begin
raise call ResourceNotFoundError string Disk { disk_name }... | def GetRegionDisk(
self,
disk_name: str,
region: Optional[str] = None) -> 'GoogleRegionComputeDisk':
disks = self.RegionDisks()
if re.match(RESOURCE_ID_REGEX, disk_name):
disk = disks.get(disk_name)
else:
disk = self._FindResourceByName(disks, disk_name, region=region)
if n... | Python | nomic_cornstack_python_v1 |
class TSQ
begin
function __init__ self
begin
set input = list
set output = list
end function
function enqueue self value
begin
append input value
end function
function dequeue self
begin
if length output == 0
begin
while length input
begin
append output pop input
end
end
if length output == 0
begin
return none
end
re... | class TSQ:
def __init__(self):
self.input = []
self.output = []
def enqueue(self, value):
self.input.append(value)
def dequeue(self):
if len(self.output) == 0:
while len(self.input):
self.output.append(self.input.pop())
if len(self.outpu... | Python | zaydzuhri_stack_edu_python |
function GetOperators
begin
return call _get_filtered_classes NexposeCriteriaOperator
end function | def GetOperators():
return _get_filtered_classes(NexposeCriteriaOperator) | Python | nomic_cornstack_python_v1 |
function _build_segment_tree self input_list lo hi pos query_func
begin
if lo == hi
begin
set seg_tree at pos = input_list at lo
return
end
set mid = integer lo + hi / 2
call _build_segment_tree input_list lo mid 2 * pos + 1 query_func
call _build_segment_tree input_list mid + 1 hi 2 * pos + 2 query_func
set seg_tree a... | def _build_segment_tree(self, input_list, lo, hi, pos, query_func):
if lo == hi:
self.seg_tree[pos] = input_list[lo]
return
mid = int((lo + hi) / 2)
self._build_segment_tree(input_list, lo, mid, 2 * pos + 1, query_func)
self._build_segment_tree(input_list, mid + ... | Python | nomic_cornstack_python_v1 |
from math import log10
set tuple p q t = tuple 3 2 0
for i in range 1000
begin
if integer call log10 p > integer call log10 q
begin
set t = t + 1
end
set tuple p q = tuple p + 2 * q p + q
end
print t | from math import log10
p, q, t = 3, 2, 0
for i in range(1000):
if int(log10(p)) > int(log10(q)):
t += 1
p, q = p + 2 * q, p + q
print(t)
| Python | zaydzuhri_stack_edu_python |
function bootstrap_card_with_icon id_ title icon
begin
return call Div call Div call Div call Div list call Div list call I className=icon + string icon-grey fa-2x font-large-2-float-left className=string align-self-center call Div list call H3 id=id_ className=string main-card-value call Span title className=string ma... | def bootstrap_card_with_icon(id_, title, icon):
return html.Div(
html.Div(
html.Div(
html.Div(
[
html.Div(
[
html.I(
className=icon + " icon... | Python | nomic_cornstack_python_v1 |
function ndcg_at ks scores labels log_base=2
begin
set tuple ks scores labels = call _check_inputs ks scores labels
set tuple topk_scores topk_indices topk_labels = call _extract_topk ks scores labels
set ndcgs = call _create_output_placeholder scores ks
comment Compute discounted cumulative gains
set gains = call dcg_... | def ndcg_at(
ks: torch.Tensor, scores: torch.Tensor, labels: torch.Tensor, log_base: int = 2
) -> torch.Tensor:
ks, scores, labels = _check_inputs(ks, scores, labels)
topk_scores, topk_indices, topk_labels = _extract_topk(ks, scores, labels)
ndcgs = _create_output_placeholder(scores, ks)
# Compute ... | Python | nomic_cornstack_python_v1 |
from widgets.bwidget import *
from functools import partial
comment 图片组件
comment 放大、缩小、旋转、打印、上一张、下一站
class PicWidget extends QDialog
begin
set open_new = call pyqtSignal list int
comment 参数1:所有图的二进制数据列表,
comment 参数2:图数量
function __init__ self parent=none
begin
call __init__ parent
call setMinimumHeight 800
call initUI
... | from widgets.bwidget import *
from functools import partial
# 图片组件
# 放大、缩小、旋转、打印、上一张、下一站
class PicWidget(QDialog):
open_new = pyqtSignal(list,int)
# 参数1:所有图的二进制数据列表,
# 参数2:图数量
def __init__(self,parent=None):
super(PicWidget,self).__init__(parent)
self.setMinimumHeight(800)
sel... | Python | zaydzuhri_stack_edu_python |
comment @lc app=leetcode.cn id=57 lang=python3
comment [57] 插入区间
comment https://leetcode-cn.com/problems/insert-interval/description/
comment algorithms
comment Hard (37.25%)
comment Likes: 151
comment Dislikes: 0
comment Total Accepted: 23.7K
comment Total Submissions: 63.5K
comment Testcase Example: '[[1,3],[6,9]]\n... | #
# @lc app=leetcode.cn id=57 lang=python3
#
# [57] 插入区间
#
# https://leetcode-cn.com/problems/insert-interval/description/
#
# algorithms
# Hard (37.25%)
# Likes: 151
# Dislikes: 0
# Total Accepted: 23.7K
# Total Submissions: 63.5K
# Testcase Example: '[[1,3],[6,9]]\n[2,5]'
#
# 给出一个无重叠的 ,按照区间起始端点排序的区间列表。
#
# 在列表... | Python | zaydzuhri_stack_edu_python |
function _set_state self v load=false
begin
if has attribute v string _utype
begin
set v = call _utype v
end
try
begin
set t = call YANGDynClass v base=yc_state_openconfig_telemetry__telemetry_system_destination_groups_destination_group_state is_container=string container yang_name=string state parent=self path_helper=... | def _set_state(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_state_openconfig_telemetry__telemetry_system_destination_groups_destination_group_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=s... | Python | nomic_cornstack_python_v1 |
from lru import LRU
import numpy as np
class topic
begin
function __init__ self c_hash c_user c_words
begin
set topic_count = 1
set l1 = call LRU c_hash
set l2 = call LRU c_user
set l3 = call LRU c_words
end function
function set_hashLRU self l
begin
set l1 l
end function
function set_userLRU self l
begin
set l2 l
end ... | from lru import LRU
import numpy as np
class topic:
def __init__(self, c_hash, c_user, c_words):
self.topic_count =1
self.l1 = LRU(c_hash)
self.l2 = LRU(c_user)
self.l3 = LRU(c_words)
def set_hashLRU(self,l):
self.set(self.l1, l)
def set_userLRU(self,l):... | Python | zaydzuhri_stack_edu_python |
comment Ameet Subedi
comment 1001530023
import math
import numpy as np
import sys
function phi matrix deg
begin
set arr = list
set mat = list
set dat = list
for i in range 0 shape at 0
begin
append arr 1
for j in range 1 shape at 1
begin
for k in range 1 deg + 1
begin
append arr power matrix at i at j k
end
end
appe... | #Ameet Subedi
#1001530023
import math
import numpy as np
import sys
def phi(matrix,deg):
arr = []
mat = []
dat = []
for i in range(0,matrix.shape[0]):
arr.append(1)
for j in range(1,matrix.shape[1]):
for k in range(1,deg+1):
arr.append(pow(matrix[i][j],k))
mat.append(arr)
arr = []
mat = np.array(... | Python | zaydzuhri_stack_edu_python |
function create_zpaq archive compression cmd verbosity interactive filenames
begin
string Create a ZPAQ archive.
set cmdlist = list cmd string a archive
extend cmdlist filenames
extend cmdlist list string -method string 4
return cmdlist
end function | def create_zpaq(archive, compression, cmd, verbosity, interactive, filenames):
"""Create a ZPAQ archive."""
cmdlist = [cmd, 'a', archive]
cmdlist.extend(filenames)
cmdlist.extend(['-method', '4'])
return cmdlist | Python | jtatman_500k |
function advanced self advanced
begin
set _advanced = advanced
end function | def advanced(self, advanced):
self._advanced = advanced | Python | nomic_cornstack_python_v1 |
async function test_ble_device_with_proxy_client_out_of_connections_uses_best_available_macos hass enable_bluetooth macos_adapter
begin
set manager = call _get_manager
set switchbot_proxy_device_no_connection_slot = call generate_ble_device string 44:44:33:11:23:45 string wohand_no_connection_slot dict string source st... | async def test_ble_device_with_proxy_client_out_of_connections_uses_best_available_macos(
hass: HomeAssistant, enable_bluetooth: None, macos_adapter: None
) -> None:
manager = _get_manager()
switchbot_proxy_device_no_connection_slot = generate_ble_device(
"44:44:33:11:23:45",
"wohand_no_con... | Python | nomic_cornstack_python_v1 |
function f X_ K_
begin
return max exp X_ - K_ 0
end function | def f(X_,K_):
return max(exp(X_)-K_,0) | Python | nomic_cornstack_python_v1 |
function compute_assembly_steps self
begin
comment Check first to make sure that the distance_graph has been made.
assert is instance distance_graph DiGraph
assert length call nodes > 0
comment Copy the distance graph.
set G = copy distance_graph
function _assembly_step G current
begin
string Helper function that compu... | def compute_assembly_steps(self):
# Check first to make sure that the distance_graph has been made.
assert isinstance(self.distance_graph, nx.DiGraph)
assert len(self.distance_graph.nodes()) > 0
# Copy the distance graph.
G = self.distance_graph.copy()
def _assembly_ste... | Python | nomic_cornstack_python_v1 |
function exists self key
begin
set node = call get_node key
return node and exists node key or false
end function | def exists(self, key):
node = self.get_node(key)
return node and node.exists(key) or False | Python | nomic_cornstack_python_v1 |
function build_subtree_strut self result *args **kwargs
begin
string Returns a dictionary in form of {node:Resource, children:{node_id: Resource}} :param result: :return:
set items = list result
set root_elem = dict string node none ; string children ordered dictionary
if length items == 0
begin
return root_elem
end
fo... | def build_subtree_strut(self, result, *args, **kwargs):
"""
Returns a dictionary in form of
{node:Resource, children:{node_id: Resource}}
:param result:
:return:
"""
items = list(result)
root_elem = {"node": None, "children": OrderedDict()}
if len... | Python | jtatman_500k |
comment contest url :https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/529/week-2/3297/
class Solution
begin
function lastStoneWeight self stones
begin
while length stones > 1
begin
sort stones reverse=true
if stones at 0 == stones at 1
begin
pop stones 0
pop stones 0
end
else
begin
set stones at ... | #contest url :https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/529/week-2/3297/
class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
while(len(stones)>1):
stones.sort(reverse=True)
if stones[0] == stones[1]:
stones.pop(0)
... | Python | zaydzuhri_stack_edu_python |
from sympy.ntheory import divisors
function is_ab n
begin
if sum call divisors n at slice : - 1 : > n
begin
return true
end
else
begin
return false
end
end function
set abs = list comprehension i for i in range 12 28123 if call is_ab i
set a_sums = set generator expression i + j for i in abs for j in abs
set nums = se... | from sympy.ntheory import divisors
def is_ab(n):
if sum(divisors(n)[:-1]) > n:
return True
else:
return False
abs = [i for i in range(12, 28123) if is_ab(i)]
a_sums = set(i + j for i in abs for j in abs)
nums = set(range(28124))
print(sum(nums.difference(a_sums))) | Python | zaydzuhri_stack_edu_python |
comment June 10, 2018
comment Take a list and write a program that prints out all the elements of the list that are less than input number.
set number = integer input string Number:
set a = list 1 1 2 3 5 8 13 21 34 55 89
set b = list
for i in range 0 length a
begin
if a at i < number
begin
append b a at i
end
else
be... | # June 10, 2018
# Take a list and write a program that prints out all the elements of the list that are less than input number.
number = int(input('Number:\t'))
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = []
for i in range(0, len(a)):
if a[i] < number:
b.append(a[i])
else:
pass
print(b)
# ... | Python | zaydzuhri_stack_edu_python |
import sys
from pprint import pprint
function solve engines queries costs
begin
set prev_best = engines at 0
for query in queries
begin
set d = dict
set best = tuple maxint engines at 0
for engine in engines
begin
if engine == query
begin
set d at engine = maxint
end
else
begin
set not_changing = costs at - 1 at engin... | import sys
from pprint import pprint
def solve (engines, queries, costs):
prev_best = engines[0]
for query in queries:
d = {}
best = (sys.maxint, engines[0])
for engine in engines:
if engine == query:
d[engine] = sys.maxint
else:
... | Python | zaydzuhri_stack_edu_python |
function gather_indexes sequence_tensor positions
begin
set sequence_shape = call get_shape_list sequence_tensor expected_rank=3
set batch_size = sequence_shape at 0
set seq_length = sequence_shape at 1
set width = sequence_shape at 2
set flat_offsets = reshape tf range 0 batch_size dtype=int32 * seq_length list - 1 1
... | def gather_indexes(sequence_tensor, positions):
sequence_shape = modeling.get_shape_list(sequence_tensor, expected_rank=3)
batch_size = sequence_shape[0]
seq_length = sequence_shape[1]
width = sequence_shape[2]
flat_offsets = tf.reshape(
tf.range(0, batch_size, dtype=tf.int32) * seq_length, [-1, 1])
... | Python | nomic_cornstack_python_v1 |
function testNotFound self
begin
set response = get requests url=invalid_url
set headers = headers
set json_data = json response
assert equal status_code 404 WRONG_STATUS_CODE_MSG
assert equal headers at string Content-Type string application/json WRONG_TYPE_RETURN_MSG
assert true city == get storage City city_id
asser... | def testNotFound(self):
response = requests.get(url=self.invalid_url)
headers = response.headers
json_data = response.json()
self.assertEqual(response.status_code, 404, WRONG_STATUS_CODE_MSG)
self.assertEqual(
headers['Content-Type'], 'application/json', WRONG_TYPE_R... | Python | nomic_cornstack_python_v1 |
function _hash anything
begin
set md5 = md5
update md5 encode string anything string utf-8
return call digest
end function | def _hash(anything) -> bytes:
md5 = hashlib.md5()
md5.update(str(anything).encode('utf-8'))
return md5.digest() | Python | nomic_cornstack_python_v1 |
function WaveLengthExtract param folder
begin
comment Finding if using custom file
set no_use_other_file = split right strip param at 9 string string at 4
comment no custom file
if no_use_other_file == string T
begin
set wavelength_line = split right strip param at 8 string string
set n_lambda = decimal wavelength_line... | def WaveLengthExtract(param,folder):
# Finding if using custom file
no_use_other_file = param[9].rstrip('\r\n').split(" ")[4]
# no custom file
if no_use_other_file == 'T':
wavelength_line = param[8].rstrip('\r\n').split(" ")
n_lambda = float(wavelength_line[2])
lambda_min = float... | Python | nomic_cornstack_python_v1 |
comment pragma: no cover
function get_owners_command client
begin
set url = string /api/v3/security/owners?resultLimit=500
set tuple response status = call make_request GET url
set readable_output : str = call tableToMarkdown name=string { INTEGRATION_NAME } - Owners t=list response
return tuple readable_output dict l... | def get_owners_command(client: Client) -> COMMAND_OUTPUT: # pragma: no cover
url = '/api/v3/security/owners?resultLimit=500'
response, status = client.make_request(Method.GET, url)
readable_output: str = tableToMarkdown(name=f"{INTEGRATION_NAME} - Owners",
t=list... | Python | nomic_cornstack_python_v1 |
function generate_df role
begin
set tuple attributes attributes_nested = call get_attributes role
comment df = pd.DataFrame(columns = attributes)
set output = call StringIO
set csv_writer = writer output
with open ROLES_DATA at role string r as infile
begin
for tuple i line in enumerate infile
begin
if i % INTERVAL == ... | def generate_df(role):
attributes, attributes_nested = get_attributes(role)
# df = pd.DataFrame(columns = attributes)
output = StringIO()
csv_writer = writer(output)
with open(ROLES_DATA[role], "r") as infile:
for i, line in enumerate(infile):
if i % INTERVAL == 0:
... | Python | nomic_cornstack_python_v1 |
function readrawdata
begin
global _annemometerCount
global _winddirraw
global _windspeedraw
global _tempraw
global _humidraw
global _pressureraw
global _soiltempraw
set _winddirraw = read winddirecitonPin
set tuple _tempraw _pressureraw _humidraw = call read_compensated_data
set _windspeedraw = _annemometerCount
commen... | def readrawdata():
global _annemometerCount
global _winddirraw
global _windspeedraw
global _tempraw
global _humidraw
global _pressureraw
global _soiltempraw
_winddirraw = winddirecitonPin.read()
_tempraw, _pressureraw, _humidraw = bme280.read_compensated_data()
_windspeedraw = _... | Python | nomic_cornstack_python_v1 |
function write_command self data port=0
begin
write self data command=SETHARDWARE port=port
end function | def write_command(self, data, port=0):
self.write(data, command=SETHARDWARE, port=port) | Python | nomic_cornstack_python_v1 |
function test_post_me_not_allowed self
begin
set res = post ME_URL dict
assert equal status_code HTTP_405_METHOD_NOT_ALLOWED
end function | def test_post_me_not_allowed(self):
res = self.client.post(ME_URL, {})
self.assertEqual(res.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) | Python | nomic_cornstack_python_v1 |
function display_jpeg *objs **kwargs
begin
string Display the JPEG representation of an object. Parameters ---------- objs : tuple of objects The Python objects to display, or if raw=True raw JPEG data to display. raw : bool Are the data objects raw data or Python objects that need to be formatted before display? [defa... | def display_jpeg(*objs, **kwargs):
"""Display the JPEG representation of an object.
Parameters
----------
objs : tuple of objects
The Python objects to display, or if raw=True raw JPEG data to
display.
raw : bool
Are the data objects raw data or Python objects that need to b... | Python | jtatman_500k |
function train_network self epochs
begin
info string Fitting neural network model
fit model X_train Y_train epochs=epochs validation_data=tuple X_test Y_test
end function | def train_network(self, epochs: int) -> None:
log.info('Fitting neural network model')
self.model.fit(self.X_train, self.Y_train, epochs=epochs, validation_data=(self.X_test, self.Y_test)) | Python | nomic_cornstack_python_v1 |
function getText filename encoding=string latin1
begin
with open filename string r encoding=encoding as file
begin
return read file
end
end function | def getText(filename, encoding='latin1'):
with open(filename, 'r', encoding=encoding) as file:
return file.read() | Python | nomic_cornstack_python_v1 |
function to_str self
begin
return call pformat call to_dict
end function | def to_str(self):
return pprint.pformat(self.to_dict()) | Python | nomic_cornstack_python_v1 |
from game.game import Connect4
from minmax.minimax import MiniMax
from memorymontecarlo.memcts import Memcts
import time
from film.animate import *
function minimax_vs_memcts largo=4 alto=6 ancho=7 depth=4 iters=150 start=0 fname=string experiment0 silent=true
begin
set game_board = call Connect4 ancho alto largo
set a... | from game.game import Connect4
from minmax.minimax import MiniMax
from memorymontecarlo.memcts import Memcts
import time
from film.animate import *
def minimax_vs_memcts(largo=4,alto=6,ancho=7,depth=4,iters=150,start=0,fname="experiment0",silent=True):
game_board = Connect4(ancho, alto, largo)
agente = MiniMa... | Python | zaydzuhri_stack_edu_python |
function __init__ self size
begin
set size = size
set values = list 0 * size
set pos = 0
set acu = 0
set n = 0
end function | def __init__(self, size: int):
self.size = size
self.values = [0] * size
self.pos = 0
self.acu = 0
self.n = 0 | Python | nomic_cornstack_python_v1 |
function _create_args_effects_dict spatial_dimension
begin
set effects_dict = dictionary
for i in range 1 spatial_dimension + 1
begin
set max_num = integer call comb spatial_dimension i
set effects_dict at i = random integer 1 max_num + 1
end
return effects_dict
end function | def _create_args_effects_dict(spatial_dimension):
effects_dict = dict()
for i in range(1, spatial_dimension + 1):
max_num = int(comb(spatial_dimension, i))
effects_dict[i] = np.random.randint(1, max_num + 1)
return effects_dict | Python | nomic_cornstack_python_v1 |
comment !/bin/python3
import sys
function countInversions arr
begin
comment Complete this function
set result = 0
if length arr > 1
begin
set mid = length arr // 2
set left_arr = arr at slice : mid :
set right_arr = arr at slice mid : :
set res1 = call countInversions left_arr
set res2 = call countInversions right_... | #!/bin/python3
import sys
def countInversions(arr):
# Complete this function
result = 0
if len(arr) > 1:
mid = len(arr)//2
left_arr = arr[:mid]
right_arr = arr[mid:]
res1 = countInversions(left_arr)
res2 = countInversions(right_arr)
i=0 # l... | Python | zaydzuhri_stack_edu_python |
string You are going to write a program which will select a random name from a list of names. The person selected will have to pay for everybody's food bill. Important: You are not allowed to use the choice() function.
import random
set names_string = string Angela, Ben, Jenny, Michael, Chloe
set names = split names_st... | """
You are going to write a program which will select a random name from a list of names.
The person selected will have to pay for everybody's food bill.
Important: You are not allowed to use the choice() function.
"""
import random
names_string = 'Angela, Ben, Jenny, Michael, Chloe'
names = names_string.s... | Python | zaydzuhri_stack_edu_python |
string Task #887194 Спички Кириченко Виктор М3О-121М-20
set x1 = list 0 0 0
set x2 = list 0 0 0
set inp = input
while not call isnumeric
begin
set inp = input string Try again!
end
set x1 at 0 = integer inp
set inp = input
while not call isnumeric
begin
set inp = input string Try again!
end
set x2 at 0 = integer inp
se... | '''
Task #887194
Спички
Кириченко Виктор
М3О-121М-20
'''
x1 = [0,0,0]
x2 = [0,0,0]
inp = input()
while not inp.isnumeric():
inp = input('Try again! ')
x1[0] = int(inp)
inp = input()
while not inp.isnumeric():
inp = input('Try again! ')
x2[0] = int(inp)
inp = input()
while not inp.isnumeric():
inp = input(... | Python | zaydzuhri_stack_edu_python |
function runner
begin
comment obtain our configuration from the environment
set config = call from_environment EXPECTED_CONFIG
comment configure logging for the application
set log_level = get attribute logging upper string config at string LOG_LEVEL
call basicConfig format=string {asctime} [{threadName}] {levelname:5}... | def runner() -> None:
# obtain our configuration from the environment
config = from_environment(EXPECTED_CONFIG)
# configure logging for the application
log_level = getattr(logging, str(config["LOG_LEVEL"]).upper())
logging.basicConfig(
format="{asctime} [{threadName}] {levelname:5} ({filena... | Python | nomic_cornstack_python_v1 |
import requests
set URL = string http://github.com/favicon.ico
set data = dict string name string Jack ; string age 22
set URL1 = string http://httpbin.org/post
set r = get requests URL
print __doc__
comment with open('github.ico', 'wb') as f:
comment f.write(r.content)
set r1 = post URL1 data=data
print encode decode ... | import requests
URL = 'http://github.com/favicon.ico'
data = {'name' : "Jack", 'age':22}
URL1 = 'http://httpbin.org/post'
r = requests.get(URL)
print(r.__doc__)
# with open('github.ico', 'wb') as f:
# f.write(r.content)
r1 = requests.post(URL1, data=data)
print(r.text.decode('utf-8').encode('gbk')) | Python | zaydzuhri_stack_edu_python |
function get_set_attribute self node set_name attr_name
begin
return call _send dict string name string getSetAttribute ; string args list node set_name attr_name
end function | def get_set_attribute(self, node, set_name, attr_name):
return self._send({'name': 'getSetAttribute', 'args': [node, set_name, attr_name]}) | Python | nomic_cornstack_python_v1 |
for x in range 1 10
begin
if x == 7
begin
continue
end
end | for x in range(1,10):
if x == 7:
continue | Python | zaydzuhri_stack_edu_python |
function setUp self
begin
comment Direct connection used to match the property values
set sockobj = call socket AF_INET SOCK_STREAM
call settimeout socket_timeout
comment Connect to the MSCU
call connect server
set pyclient = call PySimpleClient
set cmd_num = 0
set component_name = string MINORSERVO/SRP
set component =... | def setUp(self):
# Direct connection used to match the property values
self.sockobj = socket(AF_INET, SOCK_STREAM)
self.sockobj.settimeout(socket_timeout)
# Connect to the MSCU
self.sockobj.connect(server)
self.pyclient = PySimpleClient()
self.cmd_num = 0
... | Python | nomic_cornstack_python_v1 |
from datetime import datetime
from datetime import timedelta
import csv
import operator
from multiprocessing import Process , freeze_support
comment the known suspects uids
set susp = list string 2449 string 6796 string 9237 string 4024 string 3538 string 3608 string 7239 string 435 string 5206 string 2211
set moreSusp... | from datetime import datetime
from datetime import timedelta
import csv
import operator
from multiprocessing import Process,freeze_support
# the known suspects uids
susp = ['2449'
,'6796'
,'9237'
,'4024'
,'3538'
,'3608'
,'7239'
,'435'
,'520... | Python | zaydzuhri_stack_edu_python |
from sklearn import cross_validation
from sklearn import datasets
from sklearn import svm
set tuple x y = tuple call load_iris at string data call load_iris at string target
set tuple train_x test_x train_y test_y = train test split x y test_size=0.1
set model = call NuSVC
fit model x y
comment Get the accuracy of the ... | from sklearn import cross_validation
from sklearn import datasets
from sklearn import svm
x, y = datasets.load_iris()['data'], datasets.load_iris()['target']
train_x, test_x, train_y, test_y = cross_validation.train_test_split(x, y, test_size=0.1)
model = svm.NuSVC()
model.fit(x, y)
# Get the accuracy of the training... | Python | zaydzuhri_stack_edu_python |
function starting_control_index self
begin
return _special_index
end function | def starting_control_index(self):
return self._special_index | Python | nomic_cornstack_python_v1 |
function get_clippings_from_filename filename
begin
set clip_strings = list
set clipping_start_line = 0
try
begin
with input filename openhook=call hook_encoded string utf-8 as f
begin
for line in f
begin
if line != RECORD_SEP
begin
append clip_strings line
end
if line == RECORD_SEP
begin
set clipping = call _get_clip... | def get_clippings_from_filename(filename):
clip_strings = []
clipping_start_line = 0
try:
with fileinput.input(filename, openhook=fileinput.hook_encoded("utf-8")) as f:
for line in f:
if line != RECORD_SEP:
clip_strings.append(line)
if ... | Python | nomic_cornstack_python_v1 |
function variance_ambient_light_hourly self lightdata data_frequency=16 minimum_data_percent=40
begin
if length lightdata < 1
begin
return none
end
set data = lightdata
set new_data = list
set tmp_time = deep copy start_time
set tmp_time = replace tmp_time hour=0 minute=0 second=0 microsecond=0
for h in range 0 24
beg... | def variance_ambient_light_hourly(self, lightdata, data_frequency=16, minimum_data_percent=40):
if len(lightdata) < 1:
return None
data = lightdata
new_data = []
tmp_time = copy.deepcopy(data[0].start_time)
tmp_time = tmp_time.replace(hour = 0, minute = 0, second = ... | Python | nomic_cornstack_python_v1 |
function preprocess self overwrite=false
begin
comment Do not preprocess if the preprocessed information already exist
if exists _processed_images_information_path and not overwrite
begin
log WARN string The preprocessed information already exists in %s. It's assumed that the preprocessed images exist too.Specify 'over... | def preprocess(self, overwrite: bool = False) -> None:
# Do not preprocess if the preprocessed information already exist
if self._processed_images_information_path.exists() and not overwrite:
log(
WARN,
"The preprocessed information already exists in %s. "
... | Python | nomic_cornstack_python_v1 |
function calculate_sim_data_ratios sim_df data_df column_names fill_key=string fill
begin
return call DataFrame list comprehension tuple sim_df at string sim_charge_-Z at i / loc at sim_df at fill_key at i at column_names at 0 sim_df at string sim_charge_+Z at i / loc at sim_df at fill_key at i at column_names at 1 for... | def calculate_sim_data_ratios(sim_df, data_df, column_names, fill_key="fill"):
return pd.DataFrame([(
(sim_df["sim_charge_-Z"][i] / data_df.loc[sim_df[fill_key][i]])[column_names[0]],
(sim_df["sim_charge_+Z"][i] / data_df.loc[sim_df[fill_key][i]])[column_names[1]]
) for i in range(len(sim_df))]... | Python | nomic_cornstack_python_v1 |
function verify self format user=none domaincode=none passcode=none challenge=none response=none chap_password=none chap_challenge=none wikid_challenge=none
begin
set xml = string <transaction> <type format="%s">2</type> <data> <user-id>%s</user-id> <passcode>%s</passcode> <domaincode>%s</domaincode> <offline-challenge... | def verify(
self, format, user=None, domaincode=None, passcode=None, challenge=None, response=None,
chap_password=None, chap_challenge=None, wikid_challenge=None):
xml = """<transaction>
<type format="%s">2</type>
<data>
<user-id>%s</user-id>
<passcode>%s</passco... | Python | nomic_cornstack_python_v1 |
function is_excluded regex string
begin
for exc in regex
begin
if exc in string
begin
return true
end
end
return false
end function | def is_excluded(regex, string):
for exc in regex:
if exc in string:
return True
return False | Python | nomic_cornstack_python_v1 |
from helium.api import *
import random
comment NoBrainer authentication tests, using laravel homestead / vagrant
comment @author up821309
function openLoginPage
begin
set browserDriver = call start_chrome string http://homestead.nobrainer
call click call Button string CREATE QUIZ
return browserDriver
end function
funct... | from helium.api import *
import random
# NoBrainer authentication tests, using laravel homestead / vagrant
# @author up821309
def openLoginPage():
browserDriver = start_chrome("http://homestead.nobrainer")
click(Button("CREATE QUIZ"))
return browserDriver
def test_UsernameOrPasswordInvalid():
write("... | Python | zaydzuhri_stack_edu_python |
function __ne__ self other
begin
return not self == other
end function | def __ne__(self, other: 'SearchResult') -> bool:
return not self == other | Python | nomic_cornstack_python_v1 |
function _obtener_ciclo_n_dfs grafo v padres orden origen n aeropuertos
begin
if orden at v == n - 1
begin
for a in aeropuertos
begin
if call estan_unidos a v
begin
return call reconstruir_ciclo padres origen v a
end
end
end
for w in call adyacentes v
begin
if w not in padres and orden at v < n - 1
begin
set padres at ... | def _obtener_ciclo_n_dfs(grafo, v, padres, orden, origen, n, aeropuertos):
if orden[v] == n-1:
for a in aeropuertos:
if grafo.estan_unidos(a,v): return reconstruir_ciclo(padres, origen, v, a)
for w in grafo.adyacentes(v):
if w not in padres and orden[v] < n-1:
padres[w] =... | Python | zaydzuhri_stack_edu_python |
import roslib
call load_manifest string automow_ekf
import numpy as np
from numpy.testing import *
from automow_ekf import AutomowEKF as ekf
import scipy.io as sio
class TestAutomowEKF
begin
function test_modelUpdate self
begin
string Test the model update against the equivalent MATLAB function
for x in range 1 6
begin... | import roslib; roslib.load_manifest('automow_ekf')
import numpy as np
from numpy.testing import *
from automow_ekf import AutomowEKF as ekf
import scipy.io as sio
class TestAutomowEKF():
def test_modelUpdate(self):
""" Test the model update against the equivalent MATLAB function """
for x in rang... | Python | zaydzuhri_stack_edu_python |
import collections
set n = integer input
set a = list map int split input
set ac = counter a
set ac = list items ac
sort ac
comment print(ac)
set mod = integer 1000000000.0 + 7
set ans = 1
if n % 2 == 0
begin
for i in range 1 n 2
begin
if ac at i // 2 at 0 != i or ac at i // 2 at 1 != 2
begin
print 0
exit
end
else
begi... | import collections
n = int(input())
a = list(map(int,input().split()))
ac = collections.Counter(a)
ac = list(ac.items())
ac.sort()
# print(ac)
mod = int(1e9+7)
ans = 1
if n % 2 == 0:
for i in range(1,n,2):
if ac[i//2][0] != i or ac[i//2][1] != 2:
print(0)
exit()
else:
... | Python | zaydzuhri_stack_edu_python |
import random
comment maximum value of random number.
set highest = 1000000
string We set here some variables: - right answer we try to guess. - three variables related to guessing process, including the current guess. - all guesses made so far.
set right_answer = random integer 1 highest
set guess_answer = - 1
set gue... | import random
highest = 1000000 # maximum value of random number.
"""
We set here some variables:
- right answer we try to guess.
- three variables related to guessing process, including the current guess.
- all guesses made so far.
"""
right_answer = random.randint(1, highest)
guess_answer = -1
guess_high = highest... | Python | zaydzuhri_stack_edu_python |
comment Python packages#####################
import numpy as np
from typing import Callable , List
function get_accuracy x constraints
begin
string Return portion of sampled vectors that laid in the constraint :param x: List of proposed vectors :param constraints: Boolean that states if all constraints are satisfied :r... | ####################Python packages#####################
import numpy as np
from typing import Callable, List
def get_accuracy(x: List[np.ndarray], constraints: Callable) -> float:
"""
Return portion of sampled vectors that laid in the constraint
:param x: List of proposed vectors
:param constraints: ... | Python | zaydzuhri_stack_edu_python |
function add_boolean_argument parser name default=false
begin
string Add a boolean argument to an ArgumentParser instance.
set group = call add_mutually_exclusive_group
call add_argument string --set action=string store_true dest=name default=default
call add_argument string --unset action=string store_false dest=name ... | def add_boolean_argument(parser, name, default=False):
"""Add a boolean argument to an ArgumentParser instance."""
group = parser.add_mutually_exclusive_group()
group.add_argument('--set', action='store_true', dest=name,
default=default)
group.add_argument('--unset', action='stor... | Python | jtatman_500k |
comment !/usr/bin/env python
comment http://blog.csdn.net/psrincsdn/article/details/8158182
import sys , pickle , re
class TrieNode extends object
begin
string A Trie Class
function __init__ self
begin
set value = none
set children = dict
end function
end class
class Trie extends object
begin
function __init__ self
be... | #!/usr/bin/env python
# http://blog.csdn.net/psrincsdn/article/details/8158182
import sys, pickle, re
class TrieNode(object):
""" A Trie Class """
def __init__(self):
self.value = None
self.children = {}
class Trie(object):
def __init__(self):
self.root = TrieNode()
def i... | Python | zaydzuhri_stack_edu_python |
import random
import torch
class DynamicNet extends Module
begin
function __init__ self D_in H D_out
begin
call __init__
set linear1 = linear D_in H
set linear2 = linear H H
set linear3 = linear H D_out
end function
function forward self x
begin
string For the forward pass of the model, we randomly choose either 0, 1, ... | import random
import torch
class DynamicNet(torch.nn.Module):
def __init__(self, D_in, H, D_out):
super(DynamicNet, self).__init__()
self.linear1 = torch.nn.Linear(D_in, H)
self.linear2 = torch.nn.Linear(H, H)
self.linear3 = torch.nn.Linear(H, D_out)
def forward(self, x):
... | Python | zaydzuhri_stack_edu_python |
import scrapy
from douban.items import DoubanItem , CommentItem
import re
class DoubanSpiderSpider extends Spider
begin
set name = string douban_spider
set allowed_domains = list string movie.douban.com
set start_urls = list string https://movie.douban.com/top250
set comment_parge = 1
function parse self response
begin... | import scrapy
from douban.items import DoubanItem,CommentItem
import re
class DoubanSpiderSpider(scrapy.Spider):
name = 'douban_spider'
allowed_domains = ['movie.douban.com']
start_urls = ['https://movie.douban.com/top250']
comment_parge = 1
def parse(self, response):
movie_list = respon... | Python | zaydzuhri_stack_edu_python |
function int_list_from_string s
begin
comment To remove line breaks etc
set s = strip s
set list_with_some_empty_strings = split s string
set list_without_empty_strings = list comprehension i for i in list_with_some_empty_strings if i != string
return list map int list_without_empty_strings
end function
function is_tr... | def int_list_from_string(s):
s = s.strip() # To remove line breaks etc
list_with_some_empty_strings = s.split(' ')
list_without_empty_strings = [i for i in list_with_some_empty_strings if i != '']
return list(map(int, list_without_empty_strings))
def is_triangle(int_list):
sorted_list = sorted(in... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.