code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function expand keys
begin
set finalkeys = set
for key in keys
begin
set returnkeyset = set
if SLASH in key
begin
set has_tags = true
set tag_tail = split key SLASH at 1
set key = split key SLASH at 0
end
else
begin
set has_tags = false
set tag_tail = EMPTYCHAR
end
if ATSIGN in key or PERIOD not in key or PERIOD + BLAN... | def expand (keys):
finalkeys = set()
for key in keys:
returnkeyset = set()
if SLASH in key:
has_tags = True
tag_tail = key.split(SLASH)[1]
key = key.split(SLASH)[0]
else:
... | Python | nomic_cornstack_python_v1 |
if country == string Ferelden
begin
print string Ah, { country } . Heard that place has the best war dogs. A little smelly, though.
end
else
if country == string Nevarra or country == string Free Marches
begin
print string Ah, { country } . Well, that's just a short passage down to here. Must have taken you no time at ... | if country == "Ferelden":
print(f"Ah, {country}. Heard that place has the best war dogs. A little smelly, though.")
elif country == "Nevarra" or country == "Free Marches":
print(f"Ah, {country}. Well, that's just a short passage down to here. Must have taken you no time at all!")
elif country == "Tevint... | Python | zaydzuhri_stack_edu_python |
comment Psalm 13: 5,6
comment TCS DIGITAL PYQ
set n = integer input
set m = integer input
set p = integer input
for i in range n - 1
begin
set m = p * m // 100
end
print m | #Psalm 13: 5,6
#TCS DIGITAL PYQ
n = int(input())
m = int(input())
p = int(input())
for i in range(n-1):
m=(p*m)//100
print (m) | Python | zaydzuhri_stack_edu_python |
function lstm_backward da caches
begin
comment Retrieve values from the first cache (t=1) of caches.
set tuple caches x = caches
set tuple a1 c1 a0 c0 f1 i1 cc1 o1 x1 parameters = caches at 0
comment START CODE HERE ###
comment Retrieve dimensions from da's and x1's shapes (≈2 lines)
set tuple n_a m T_x = none
set tupl... | def lstm_backward(da, caches):
# Retrieve values from the first cache (t=1) of caches.
(caches, x) = caches
(a1, c1, a0, c0, f1, i1, cc1, o1, x1, parameters) = caches[0]
### START CODE HERE ###
# Retrieve dimensions from da's and x1's shapes (≈2 lines)
n_a, m, T_x = None
n_x, m = None
... | Python | nomic_cornstack_python_v1 |
function customizations record
begin
comment record = bibtexparser.customization.author(record)
set record = call add_plaintext_fields record
set record = call doi record
return record
end function | def customizations(record):
#record = bibtexparser.customization.author(record)
record = bibtexparser.customization.add_plaintext_fields(record)
record = bibtexparser.customization.doi(record)
return record | Python | nomic_cornstack_python_v1 |
function post self
begin
set data = call get_json
if data is none
begin
raise call ClientDataError string Must include request data
end
set event_date = get data string date none
set description = get data string description none
set note = get data string note none
set bike_id = get data string bike_id none
if bike_id... | def post(self):
data = request.get_json()
if data is None:
raise ClientDataError('Must include request data')
event_date = data.get('date', None)
description = data.get('description', None)
note = data.get('note', None)
bike_id = data.get('bike_id', None)
... | Python | nomic_cornstack_python_v1 |
import os.path
from os import path
class Validator
begin
function __init__ self data=none
begin
set data = data
end function
function is_csv self file_name
begin
if not call check_is_csv file_name
begin
set error = string file_name + string Is not a valid CSV .
raise call ValueError error
end
end function
function chec... | import os.path
from os import path
class Validator:
def __init__ (self, data=None):
self.data = data
def is_csv (self, file_name):
if not self.check_is_csv(file_name):
error = str(file_name) + ' Is not a valid CSV .'
raise ValueError(error)
def check_is_file (self,... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import matplotlib.pyplot as plt
set fig = figure figsize=tuple 8 3
set ax1 = call add_subplot 231 projection=string 3d
set ax2 = call add_subplot 232 projection=string 3d
set ax3 = call add_subplot 233 projection=string 3d
set ax4 = call add_subplot 234 projection=string 3d
set ax5 = call add_subplot... | import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8, 3))
ax1 = fig.add_subplot(231, projection='3d')
ax2 = fig.add_subplot(232, projection='3d')
ax3 = fig.add_subplot(233, projection='3d')
ax4 = fig.add_subplot(234, projection='3d')
ax5 = fig.add_subplot(235, projection='3d')
ax6 = ... | Python | zaydzuhri_stack_edu_python |
function cons13 p
begin
comment for i in range(0, len(p)):
comment print i, p[i]
if length p < 4
begin
if p at 1 == none
begin
set p at 0 = list
end
else
begin
set p at 0 = list p at 1
end
end
else
begin
set p at 0 = list p at 1 + p at 3
end
end function
comment print "->", p[0]
comment print "" | def cons13(p):
# for i in range(0, len(p)):
# print i, p[i]
if len(p) < 4:
if p[1] == None:
p[0] = []
else:
p[0] = [p[1]]
else:
p[0] = [p[1]] + p[3]
# print "->", p[0]
# print "" | Python | nomic_cornstack_python_v1 |
string Created on Mar 30, 2015 @author: Andrea Martire
import Utils , Constants
comment Calculate anti-diagonal distance for bitshop's moves
function antidiagonalDistance col row
begin
if row == 1 or col == 8
begin
return 0
end
else
if row == 2 or col == 7
begin
return 1
end
else
if row == 3 or col == 6
begin
return 2
... | '''
Created on Mar 30, 2015
@author: Andrea Martire
'''
import Utils, Constants
#Calculate anti-diagonal distance for bitshop's moves
def antidiagonalDistance(col, row):
if(row == 1 or col == 8):
return 0
elif(row == 2 or col == 7):
return 1
elif(row == 3 or col == 6):
... | Python | zaydzuhri_stack_edu_python |
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
comment 第三方SMTP服务
comment 设置服务器
set mail_host = string smtp.qq.com
comment 用户名
set mail_user = string xxx@qq.com
comment 口令
set mail_pass = string xxxxx
set sender = string xxx.com
comment ... | import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
#第三方SMTP服务
mail_host = "smtp.qq.com" #设置服务器
mail_user = "xxx@qq.com" #用户名
mail_pass = "xxxxx" #口令
sender = 'xxx.com'
receivers = ['xxx@qq.com'] #接收邮件,可以设置为你的QQ邮箱或者其他邮箱
#创建一个... | Python | zaydzuhri_stack_edu_python |
function GetBuildVariable build_top_dir var
begin
set build_core = join path build_top_dir string build string core
set env = dictionary environ
set env at string CALLED_FROM_SETUP = string true
set env at string BUILD_SYSTEM = build_core
set cmd = list string make string --no-print-directory string -f join path build_... | def GetBuildVariable(build_top_dir, var):
build_core = os.path.join(build_top_dir, "build", "core")
env = dict(os.environ)
env["CALLED_FROM_SETUP"] = "true"
env["BUILD_SYSTEM"] = build_core
cmd = ["make", "--no-print-directory",
"-f", os.path.join(build_core, "config.mk"),
"dum... | Python | nomic_cornstack_python_v1 |
from dependencies import *
class ImageExporter
begin
function __init__ self frames bounding_boxes export_path box_counter frame_counter
begin
set frames = frames
set frame_counter = frame_counter
set bounding_boxes = bounding_boxes
set export_path = export_path
set box_counter = box_counter
end function
function export... | from dependencies import *
class ImageExporter:
def __init__(self, frames, bounding_boxes, export_path, box_counter, frame_counter):
self.frames = frames
self.frame_counter = frame_counter
self.bounding_boxes = bounding_boxes
self.export_path = export_path
self.box_counter =... | Python | zaydzuhri_stack_edu_python |
comment time complexity is O(n+m) where n number of vertices and m number of edges
comment Longest path in directed acyclic graph
from collections import defaultdict
class Graph
begin
function __init__ self v
begin
set vcount = v
set adjlist = default dictionary list
end function
function insert self v1 v2
begin
append... | #time complexity is O(n+m) where n number of vertices and m number of edges
#Longest path in directed acyclic graph
from collections import defaultdict
class Graph:
def __init__(self,v):
self.vcount=v
self.adjlist=defaultdict(list)
def insert(self,v1,v2):
self.adjlist[v1].append(v2)
... | Python | zaydzuhri_stack_edu_python |
function import_string import_name silent=false
begin
string Imports an object based on a string. This is useful if you want to use import paths as endpoints or something similar. An import path can be specified either in dotted notation (``xml.sax.saxutils.escape``) or with a colon as object delimiter (``xml.sax.saxut... | def import_string(import_name, silent=False):
"""Imports an object based on a string. This is useful if you want to
use import paths as endpoints or something similar. An import path can
be specified either in dotted notation (``xml.sax.saxutils.escape``)
or with a colon as object delimiter (``xml... | Python | jtatman_500k |
function plot_blade_path ax R=0.5
begin
set p = call Circle tuple 0 0 R linestyle=string dashed edgecolor=string black facecolor=string none linewidth=1
call add_patch p
end function | def plot_blade_path(ax, R=0.5):
p = plt.Circle((0, 0), R, linestyle="dashed", edgecolor="black",
facecolor="none", linewidth=1)
ax.add_patch(p) | Python | nomic_cornstack_python_v1 |
function left self expand=none
begin
string Returns a new Region left of the current region with a width of ``expand`` pixels. Does not include the current region. If range is omitted, it reaches to the left border of the screen. The new region has the same height and y-position as the current region.
if expand == none... | def left(self, expand=None):
""" Returns a new Region left of the current region with a width of ``expand`` pixels.
Does not include the current region. If range is omitted, it reaches to the left border
of the screen. The new region has the same height and y-position as the current region.
... | Python | jtatman_500k |
function isCurrent element
begin
set rr = find element string RecordStatus
if rr == none
begin
return false
end
else
begin
return text == string current
end
end function | def isCurrent(element):
rr = element.find("RecordStatus")
if rr == None:
return False
else:
return(rr.text == "current") | Python | nomic_cornstack_python_v1 |
function factorial n
begin
set fac = list
while n > 0
begin
append fac n
set n = n - 1
end
set mul = 1
for i in fac
begin
set mul = mul * i
end
return mul
end function
set a = string call factorial 100
set fa = list comprehension b for b in a
set x = list comprehension integer a for a in fa
sum x | def factorial(n):
fac=[]
while n>0:
fac.append(n)
n -= 1
mul = 1
for i in fac:
mul *= i
return mul
a = str(factorial(100))
fa = [b for b in a]
x = [int(a) for a in fa]
sum(x) | Python | zaydzuhri_stack_edu_python |
comment !/bin/python
comment this file will load files made by level loader, and retrun all the values in the format expected by the GUI,
comment To not have to change the GUI's functionality to much, levelLoader is kind of like a helper class for GUI
import Entity
import weapon
from library import *
from levelLibrary ... | #!/bin/python
#this file will load files made by level loader, and retrun all the values in the format expected by the GUI,
#To not have to change the GUI's functionality to much, levelLoader is kind of like a helper class for GUI
import Entity
import weapon
from library import *
from levelLibrary import *
import json... | Python | zaydzuhri_stack_edu_python |
import cv2
import numpy as np
import stitch
import imutils
import transformation
set dist = array list 0.053314 - 0.117603 - 0.004064 - 0.001819 0.0
set K = array list list 1173.12262 0.0 969.335924 list 0.0 1179.612539 549.524382 list 0.0 0.0 1.0
comment # input videos
comment leftCap = cv2.VideoCapture('video4/small_... | import cv2
import numpy as np
import stitch
import imutils
import transformation
dist = np.array([0.053314, -0.117603, -0.004064, -0.001819, 0.000000])
K = np.array([
[1173.122620, 0.000000, 969.335924],
[0.000000, 1179.612539, 549.524382],
[0.000000, 0.000000, 1.000000]
])
# # input videos
# leftCap = c... | Python | zaydzuhri_stack_edu_python |
import cv2
import requests
import os
from matplotlib import pyplot as plt
class Histogram
begin
decorator staticmethod
function from_local_file image_path
begin
try
begin
set image_file = call imread image_path 0
histogram call ravel 256 list 0 256
show
end
except AttributeError as err
begin
print string Application er... | import cv2
import requests
import os
from matplotlib import pyplot as plt
class Histogram:
@staticmethod
def from_local_file(image_path: str):
try:
image_file = cv2.imread(image_path, 0)
plt.hist(image_file.ravel(), 256, [0, 256])
plt.show()
e... | Python | zaydzuhri_stack_edu_python |
from google.cloud import texttospeech
from pydub import AudioSegment
from pydub.playback import play
import io
function playaudio text
begin
set client = call TextToSpeechClient
set synthesis_input = call SynthesisInput text=text
set voice = call VoiceSelectionParams language_code=string zh-CN ssml_gender=NEUTRAL
comme... | from google.cloud import texttospeech
from pydub import AudioSegment
from pydub.playback import play
import io
def playaudio(text):
client = texttospeech.TextToSpeechClient()
synthesis_input = texttospeech.SynthesisInput(text=text)
voice = texttospeech.VoiceSelectionParams(
language_code="... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding: UTF-8 -*-
string @author: qxb @copyright: 2014 organization_name. All rights reserved. @license: license @contact: user_email @deffield updated: Updated
import random
import pickle
import math
import matplotlib.pyplot as plt
class Generator
begin
function generate_2d_fun... | #!/usr/bin/env python
#-*- coding: UTF-8 -*-
'''
@author: qxb
@copyright: 2014 organization_name. All rights reserved.
@license: license
@contact: user_email
@deffield updated: Updated
'''
import random
import pickle
import math
import matplotlib.pyplot as plt
class Generator:
def generate_2d_fu... | Python | zaydzuhri_stack_edu_python |
import codecs
import pandas as pd
from urllib import parse as up
import re
comment @REFS https://github.com/xkumiyu/imagenet-downloader
comment ImageNetから、ILSVRC2012で使用された1000クラスに絞ったURLリストを作成する
comment 1. すべての画像のURLリスト → fall11_urls.txt: tsv['id', 'url']
comment eg.
comment n00004475_6590 http://farm4.static.flickr.com... | import codecs
import pandas as pd
from urllib import parse as up
import re
# @REFS https://github.com/xkumiyu/imagenet-downloader
#
# ImageNetから、ILSVRC2012で使用された1000クラスに絞ったURLリストを作成する
#
# 1. すべての画像のURLリスト → fall11_urls.txt: tsv['id', 'url']
# eg.
# n00004475_6590 http://farm4.static.flickr.com/3175/2737866473_7958dc... | Python | zaydzuhri_stack_edu_python |
function __init__ self size=8
begin
call __init__ self string Many Queens
set size = size
set model = call QueensModel size
comment Add chess squares to the grid
set squares = list
set background = string white
for row in range 0 size
begin
for column in range 0 size
begin
if background == string white
begin
set backgr... | def __init__(self, size = 8):
EasyFrame.__init__(self, "Many Queens")
self.size = size
self.model = QueensModel(size)
# Add chess squares to the grid
self.squares = list()
background = "white"
for row in range(0, size):
for column in range(0, size):
... | Python | nomic_cornstack_python_v1 |
import errno
import sys
from fynance_core.utils import accountmanager , exceptions
call check_paydays
try
begin
set arg = lower argv at 1
end
except IndexError
begin
print string Positional argument must be one of the following: 'account', 'category', 'expenditures'.
exit EAGAIN
end
if arg == string account
begin
set a... | import errno
import sys
from fynance_core.utils import accountmanager, exceptions
accountmanager.check_paydays()
try:
arg = sys.argv[1].lower()
except IndexError:
print("Positional argument must be one of the following: 'account', 'category', 'expenditures'.")
sys.exit(errno.EAGAIN)
if arg == "account":... | Python | zaydzuhri_stack_edu_python |
function name self
begin
return get pulumi self string name
end function | def name(self) -> pulumi.Input[str]:
return pulumi.get(self, "name") | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
import argparse
import json
import requests
import time
set BLOG_ID = string
set TOKEN = string
set API_BASE = string https://public-api.wordpress.com/rest/v1.1
set CATEGORY_DEFAULT = string maximes
set CATEGORY_SUPPRIMEES = string supprimees
set CATEGORY_POSTHUMES = string posthumes
func... | #!/usr/bin/env python
import argparse
import json
import requests
import time
BLOG_ID = ''
TOKEN = ''
API_BASE = 'https://public-api.wordpress.com/rest/v1.1'
CATEGORY_DEFAULT = 'maximes'
CATEGORY_SUPPRIMEES = 'supprimees'
CATEGORY_POSTHUMES = 'posthumes'
def get_category(category_str):
return {
'defaul... | Python | zaydzuhri_stack_edu_python |
class animal
begin
function __init__ self name age color size
begin
set name = name
set age = age
set color = color
set size = size
end function
function print_all self
begin
print name
print age
print color
print size
end function
function eat self food
begin
print string the animal name string eats food
end function
... | class animal:
def __init__(self,name,age,color,size):
self.name=name
self.age=age
self.color=color
self.size=size
def print_all(self):
print(self.name)
print(self.age)
print(self.color)
print(self.size)
def eat(self,food):
print("the animal",self.name,"eats",food)
def sleep(self,hours,dream):
... | Python | zaydzuhri_stack_edu_python |
from base import TodoFunctionalTest
class ManyListsTests extends TodoFunctionalTest
begin
function change_list_name self list_name
begin
set inputbox = call find_element_by_id string id_rename_list
clear inputbox
call send_keys list_name + string
end function
function test_can_create_and_view_multiple_lists self
begin
... | from .base import TodoFunctionalTest
class ManyListsTests(TodoFunctionalTest):
def change_list_name(self, list_name):
inputbox = self.browser.find_element_by_id('id_rename_list')
inputbox.clear()
inputbox.send_keys(list_name + '\n')
def test_can_create_and_view_multiple_lists(self):
... | Python | zaydzuhri_stack_edu_python |
for i in range k
begin
if s at cnt == string o
begin
append l cnt + 1
set cnt = cnt + c + 1
end
else
begin
while s at cnt != string o
begin
set cnt = cnt + 1
end
append l cnt + 1
set cnt = cnt + c + 1
end
end
set cnt = 1
for i in range k
begin
if s at - cnt == string o
begin
append r n - cnt + 1
set cnt = cnt + c + 1
e... | for i in range(k):
if s[cnt]=="o":
l.append(cnt+1)
cnt+=c+1
else:
while s[cnt]!="o":
cnt+=1
l.append(cnt+1)
cnt+=c+1
cnt=1
for i in range(k):
if s[-cnt]=="o":
r.append(n-cnt+1)
cnt+=c+1
else:
while s[-cnt]!="o":
cnt+... | Python | zaydzuhri_stack_edu_python |
comment inverte os elementos de uma lista
set lista = list string rafael string rose string vitor string heitor
print lista
reverse lista
print lista
reverse lista
print lista
print
print string =====função sort======
comment acendente
sort lista
print lista
sort lista reverse=true
print lista | #inverte os elementos de uma lista
lista = ['rafael', 'rose', 'vitor', 'heitor']
print(lista)
lista.reverse()
print(lista)
lista.reverse()
print(lista)
print()
print("=====função sort======")
#acendente
lista.sort()
print(lista)
lista.sort(reverse=True)
print(lista) | Python | zaydzuhri_stack_edu_python |
function username_encryption_level self **kwargs
begin
string Auto Generated Code
set config = call Element string config
set username = call SubElement config string username xmlns=string urn:brocade.com:mgmt:brocade-aaa
set name_key = call SubElement username string name
set text = pop kwargs string name
set encrypti... | def username_encryption_level(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
username = ET.SubElement(config, "username", xmlns="urn:brocade.com:mgmt:brocade-aaa")
name_key = ET.SubElement(username, "name")
name_key.text = kwargs.pop('name')
... | Python | jtatman_500k |
comment Create a script that converts all items of the range to strings
set my_range = range 1 21
print list map str my_range | #Create a script that converts all items of the range to strings
my_range = range(1, 21)
print(list(map(str, my_range)))
| Python | zaydzuhri_stack_edu_python |
from pyautogui import size as pysize
from kivy.animation import Animation
function resize window
begin
string This function is only calibrated to work with WINDOW os with task bar at the bottom
set sys_size = call pysize
if size at 1 == 128
begin
set win_size = tuple size at 0 428
if top + 300 > sys_size at 1
begin
set... | from pyautogui import size as pysize
from kivy.animation import Animation
def resize(window):
""" This function is only calibrated to work with WINDOW os with task bar at the bottom """
sys_size = pysize()
if window.size[1] == 128:
win_size = window.size[0], 428
if window.top ... | Python | zaydzuhri_stack_edu_python |
function get_created_charge_name self
begin
global charge_name
return charge_name
end function | def get_created_charge_name(self):
global charge_name
return charge_name | Python | nomic_cornstack_python_v1 |
from leezy import Solution , solution
from math import sqrt
class Q633 extends Solution
begin
decorator solution
function judgeSquareSum self c
begin
comment 124ms 74.87%
set hay = list comprehension n * n for n in range integer square root c + 1
set tuple i j = tuple 0 length hay - 1
while i <= j
begin
set s = hay at ... | from leezy import Solution, solution
from math import sqrt
class Q633(Solution):
@solution
def judgeSquareSum(self, c):
# 124ms 74.87%
hay = [n*n for n in range(int(sqrt(c)+1))]
i, j = 0, len(hay)-1
while i <= j:
s = hay[i] + hay[j]
if s == c:
... | Python | zaydzuhri_stack_edu_python |
function discrete_map u table
begin
comment O(n)
for tuple item probability in table
begin
if u < probability
begin
return item
end
else
begin
set u = u - probability
end
end
comment program should not arrive here if sum table[1]
return item
end function | def discrete_map(u, table):
# O(n)
for item,probability in table:
if u<probability:
return item
else:
u=u-probability
return item #program should not arrive here if sum table[1]
| Python | nomic_cornstack_python_v1 |
async function replace_review review_id review_model
begin
set review = await run
if not review
begin
return call JSONResponse dict status_code=404
end
for tuple key value in items __dict__
begin
set attribute review key value
end
await run
return call to_dict
end function | async def replace_review(review_id: int, review_model: ReviewModelIn):
review = await Review.objects().where(Review.id == review_id).first().run()
if not review:
return JSONResponse({}, status_code=404)
for key, value in review_model.__dict__.items():
setattr(review, key, value)
await ... | Python | nomic_cornstack_python_v1 |
import torch.nn as nn
class DCDiscriminator extends Module
begin
function __init__ self input_dim num_filters output_dim
begin
call __init__
set hidden_layer = sequential
for i in range length num_filters
begin
if i == 0
begin
set conv = conv 2d input_dim num_filters at i kernel_size=4 stride=2 padding=1 bias=false
end... | import torch.nn as nn
class DCDiscriminator(nn.Module):
def __init__(self, input_dim, num_filters, output_dim):
super(DCDiscriminator, self).__init__()
self.hidden_layer = nn.Sequential()
for i in range(len(num_filters)):
if i == 0:
conv = nn.Conv2d(input_dim, n... | Python | zaydzuhri_stack_edu_python |
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
import numpy as np
from itertools import product , combinations
from math import sin , cos , pi
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d
from matplotlib.widgets impo... | from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
import numpy as np
from itertools import product, combinations
from math import sin, cos, pi
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d
from matplotlib.widgets import ... | Python | zaydzuhri_stack_edu_python |
function addSubQueue self priority matcher name=none maxdefault=none maxtotal=none defaultQueueClass=FifoQueue
begin
string add a sub queue to current queue, with a priority and a matcher :param priority: priority of this queue. Larger is higher, 0 is lowest. :param matcher: an event matcher to catch events. Every even... | def addSubQueue(self, priority, matcher, name = None, maxdefault = None, maxtotal = None, defaultQueueClass = FifoQueue):
'''
add a sub queue to current queue, with a priority and a matcher
:param priority: priority of this queue. Larger is higher, 0 is lowest.
:param m... | Python | jtatman_500k |
function _get_ambiguous_stop_sequences ambiguous_trip_paths schedule
begin
set ambiguous_stop_sequences = dict
comment Populate pairs of origin times + corresponding previous stops for
comment each possible trip path for a given StopID + service code
for trip_object in call GetTripList
begin
set tuple service_id origi... | def _get_ambiguous_stop_sequences(ambiguous_trip_paths, schedule):
ambiguous_stop_sequences = {}
# Populate pairs of origin times + corresponding previous stops for
# each possible trip path for a given StopID + service code
for trip_object in schedule.GetTripList():
service... | Python | nomic_cornstack_python_v1 |
string This builds upon my solution for assignment 3, adding error identification and handling.
class ConfigDict extends dict
begin
function __init__ self filename
begin
set _filename = filename
call __init__
try
begin
with open _filename string r as fp
begin
for line in fp
begin
set entry = split line string = 1
call ... | """
This builds upon my solution for assignment 3, adding error identification and handling.
"""
class ConfigDict(dict):
def __init__(self,filename):
self._filename = filename
super(dict,self).__init__()
try:
with open(self._filename,'r') as fp:
for line in fp:
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
import sys
import os
from error import printError
comment If given arg, read sensor by id which is arg
comment On success returns: { "temperature": float }
comment On error returns: { "err":
comment {
comment "type": integer (0: Invalid value, 1: Device does not exist)
comment "msg": string
com... | #!/usr/bin/python
import sys
import os
from error import printError
# If given arg, read sensor by id which is arg
#
# On success returns: { "temperature": float }
#
# On error returns: { "err":
# {
# "type": integer (0: Invalid value, 1: Device does not ... | Python | zaydzuhri_stack_edu_python |
function __len__ self
begin
return length _list
end function | def __len__(self):
return len(self._list) | Python | nomic_cornstack_python_v1 |
class Solution
begin
function searchInsert self nums target
begin
set i = 0
set j = length nums - 1
while i <= j
begin
print i string | j string | nums at slice i : j + 1 :
set mid = i + j // 2
if target == nums at mid
begin
return mid
end
else
if target < nums at mid
begin
set j = mid - 1
end
else
if target > nums at ... | class Solution:
def searchInsert(self, nums , target: int) -> int:
i = 0
j = len(nums)-1
while(i <= j):
print(i,"|",j,"|",nums[i:j+1])
mid = (i+j)//2
if(target == nums[mid]):
return mid
elif(target < nums[mid]):
... | Python | zaydzuhri_stack_edu_python |
function process_chat self chat
begin
string Generate chat data :param chat: :return:
if not chat
begin
return
end
yield tuple string chat_id id
yield tuple string chat_type type
if include_content
begin
yield tuple string chat_title full_name
if username
begin
yield tuple string chat_name string @ { username }
end
end... | def process_chat(self, chat: types.Chat):
"""
Generate chat data
:param chat:
:return:
"""
if not chat:
return
yield 'chat_id', chat.id
yield 'chat_type', chat.type
if self.include_content:
yield 'chat_title', chat.full_na... | Python | jtatman_500k |
function setRasterBounds self lims
begin
set rasterBottom = lims at 0
set rasterTop = lims at 1
call updateRasterBounds
end function | def setRasterBounds(self, lims):
self.rasterBottom = lims[0]
self.rasterTop = lims[1]
self.updateRasterBounds() | Python | nomic_cornstack_python_v1 |
comment class Solution:
comment def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
comment dic = collections.Counter(a + b for a in A for b in B)
comment return sum(dic.get(- c - d, 0) for c in C for d in D)
class Solution extends object
begin
function fourSumcount self A B C D
begin... | # class Solution:
# def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
# dic = collections.Counter(a + b for a in A for b in B)
# return sum(dic.get(- c - d, 0) for c in C for d in D)
class Solution(object):
def fourSumcount(self, A, B, C, D):
"""
:type A: List[i... | Python | zaydzuhri_stack_edu_python |
from collections import defaultdict
function maxQualityRec adjDict values node timeLeft visited
begin
if timeLeft < 0
begin
return decimal string -inf
end
set maxQuality = 0
add visited node
for tuple neighbor time in adjDict at node
begin
remove adjDict at neighbor tuple node time
set maxQuality = max maxQuality call ... | from collections import defaultdict
def maxQualityRec(adjDict, values, node, timeLeft, visited):
if timeLeft < 0:
return float('-inf')
maxQuality = 0
visited.add(node)
for neighbor, time in adjDict[node]:
adjDict[neighbor].remove((node, time))
maxQuality = max(maxQuality, maxQu... | Python | jtatman_500k |
comment Proview Medicine Clustering
comment Clustering method: Agglomerative Clustering
comment Dimension Reduction methods: PCA, LLE, SE, MDS, TSNE
comment Date: July 17, 2018
comment Author: Yuwei Bao(yuweibao@umich.edu)
comment Sponcered by: Department of Anesthesiology, University of Michigan
import pandas as pd
im... | # Proview Medicine Clustering
# Clustering method: Agglomerative Clustering
# Dimension Reduction methods: PCA, LLE, SE, MDS, TSNE
#
# Date: July 17, 2018
# Author: Yuwei Bao(yuweibao@umich.edu)
# Sponcered by: Department of Anesthesiology, University of Michigan
import pandas as pd
import numpy as np
# import data
... | Python | zaydzuhri_stack_edu_python |
function tearDownClass cls
begin
call tearDownClass
end function | def tearDownClass(cls):
super(ModifyAccountTestCase, cls).tearDownClass() | Python | nomic_cornstack_python_v1 |
function __init__ self entry_id coordinator
begin
call __init__ entry_id=entry_id coordinator=coordinator icon=none
set _attr_unique_id = string { mac_address }
end function | def __init__(
self, entry_id: str, coordinator: ModernFormsDataUpdateCoordinator
) -> None:
super().__init__(
entry_id=entry_id,
coordinator=coordinator,
icon=None,
)
self._attr_unique_id = f"{self.coordinator.data.info.mac_address}" | Python | nomic_cornstack_python_v1 |
function gpml2json path_in path_out pathway_iri wp_id pathway_version wd_sparql
begin
set dir_out = directory name path path_out
comment example base_out: 'WP4542.json'
set base_out = base name path path_out
set list stub_out ext_out_with_dot = call splitext base_out
set gpml2pvjson_cmd = string gpml2pvjson --id { path... | def gpml2json(path_in, path_out, pathway_iri, wp_id, pathway_version, wd_sparql):
dir_out = path.dirname(path_out)
# example base_out: 'WP4542.json'
base_out = path.basename(path_out)
[stub_out, ext_out_with_dot] = path.splitext(base_out)
gpml2pvjson_cmd = (
f"gpml2pvjson --id {pathway_iri... | Python | nomic_cornstack_python_v1 |
function getContactRows self instid fetch=none
begin
set path = string api/v1/inst/%(instid)s/contact-rows
set path_params = dict string instid instid
set query_params = dict string fetch fetch
set form_params = dict
set result = call invoke_method string GET path path_params query_params form_params
if error
begin
ra... | def getContactRows(self,
instid,
fetch=None):
path = "api/v1/inst/%(instid)s/contact-rows"
path_params = {"instid": instid}
query_params = {"fetch": fetch}
form_params = {}
result = self.conn.invoke_method("GET", path, path_par... | Python | nomic_cornstack_python_v1 |
function variational_free_energy_loss model scale_factor kl_alpha
begin
comment KL Divergence should be applied once per epoch only, so
comment scale_factor should be num_samples / batch_size.
set kl = sum losses / scale_factor
function loss y_true y_pred
begin
set bce = call binary_crossentropy y_true y_pred
return bc... | def variational_free_energy_loss(model, scale_factor, kl_alpha):
# KL Divergence should be applied once per epoch only, so
# scale_factor should be num_samples / batch_size.
kl = sum(model.losses) / scale_factor
def loss(y_true, y_pred):
bce = binary_crossentropy(y_true, y_pred)
return... | Python | nomic_cornstack_python_v1 |
with open string day3.txt string r as f
begin
set map = list comprehension list comprehension x == string # for x in right strip row for row in read lines f
set result = 1
for d in DIRECTIONS
begin
set tuple pos trees = tuple tuple 0 0 0
while true
begin
set pos = tuple pos at 0 + d at 0 pos at 1 + d at 1 % length map ... | with open("day3.txt", "r") as f:
map = [[x == "#" for x in row.rstrip()] for row in f.readlines()]
result = 1
for d in DIRECTIONS:
pos, trees = (0, 0), 0
while True:
pos = x, y = pos[0] + d[0], (pos[1] + d[1]) % len(map[0])
if x >= len(map):
break
trees += map[x][y]
res... | Python | zaydzuhri_stack_edu_python |
import pyautogui as AI
import time
call typewrite string sudo tcpdump -i eth0 -w capture.pcap
sleep 1
call hotkey string enter
comment Code executed. | import pyautogui as AI
import time
AI.typewrite('sudo tcpdump -i eth0 -w capture.pcap')
time.sleep(1)
AI.hotkey('enter')
# Code executed.
| Python | flytech_python_25k |
function test_calculator_multiply
begin
assert call calculator_multiply 4 4 == 16
assert call calculator_multiply 0 0 == 0
assert call calculator_multiply 0 1 == 0
assert call calculator_multiply 0 - 5 == 0
end function | def test_calculator_multiply():
assert calculator.calculator_multiply(4, 4) == 16
assert calculator.calculator_multiply(0, 0) == 0
assert calculator.calculator_multiply(0, 1) == 0
assert calculator.calculator_multiply(0, -5) == 0 | Python | nomic_cornstack_python_v1 |
comment Neopet Base Class
class Neopet
begin
function __init__ self name
begin
set name = name
end function
function GetSpecies self
begin
pass
end function
end class | # Neopet Base Class
class Neopet():
def __init__(self, name):
self.name = name
def GetSpecies(self): pass | Python | zaydzuhri_stack_edu_python |
function CreateErrorResponse reason
begin
comment ############################
set data = dict string result false ; string reason reason
return call JSONResponse data
end function | def CreateErrorResponse(reason):
### ############################
data = {"result": False, "reason": reason};
return JSONResponse(data); | Python | nomic_cornstack_python_v1 |
function __and__ self other
begin
return call and_ other
end function | def __and__(self, other):
return self.and_(other) | Python | nomic_cornstack_python_v1 |
function show_node self node
begin
if show_builtin
begin
return true
end
return name != BUILTINS_NAME
end function | def show_node(self, node):
if self.config.show_builtin:
return True
return node.root().name != BUILTINS_NAME | Python | nomic_cornstack_python_v1 |
function convert_temperatures temperatures
begin
set converted_temperatures = list
for temperature in temperatures
begin
if not - 459.67 <= temperature <= 1000
begin
raise call ValueError string Invalid temperature: must be between -459.67°F and 1000°F
end
if temperature % 5 != 0
begin
raise call ValueError string Inv... | def convert_temperatures(temperatures):
converted_temperatures = []
for temperature in temperatures:
if not (-459.67 <= temperature <= 1000):
raise ValueError("Invalid temperature: must be between -459.67°F and 1000°F")
if temperature % 5 != 0:
raise ValueError("Inva... | Python | jtatman_500k |
from animals import Animal
from movements import Swimming
class Frog extends Animal Swimming
begin
function __init__ self name chip_number species food
begin
call __init__ self name chip_number species food
call __init__ self
end function
function feed self
begin
return string { name } must meditate for 3 hours before ... | from animals import Animal
from movements import Swimming
class Frog(Animal, Swimming):
def __init__(self, name, chip_number, species, food):
Animal.__init__(self, name, chip_number, species, food)
Swimming.__init__(self)
def feed(self):
return f'{self.name} must meditate for 3 ho... | Python | zaydzuhri_stack_edu_python |
function LowerDistanceParameters self *args
begin
return call Geom2dAPI_ExtremaCurveCurve_LowerDistanceParameters self *args
end function | def LowerDistanceParameters(self, *args):
return _Geom2dAPI.Geom2dAPI_ExtremaCurveCurve_LowerDistanceParameters(self, *args) | Python | nomic_cornstack_python_v1 |
function move_point_in_y_direction self x=0 new_y=0
begin
set point = call get_point_by_x x
call move_point point x new_y
end function | def move_point_in_y_direction(self, x=0, new_y=0):
point = self.get_point_by_x(x)
self.move_point(point, x, new_y) | Python | nomic_cornstack_python_v1 |
function load_all_models z lats lons t_LAB lab=string
begin
set vs = zeros tuple size size size
set bls = zeros tuple size size 4 dtype=float
set bis = zeros tuple size size 4 dtype=int
set i_lat = 0
set i_lon = 0
comment range(34, 41):
for lat in lats
begin
for lon in lons
begin
set fname = format string {}N_{}W_{}kmL... | def load_all_models(z:np.array, lats:np.array, lons:np.array, t_LAB:int, lab:str=''
) -> (np.array, np.array, np.array):
vs = np.zeros((lats.size, lons.size, z.size))
bls = np.zeros((lats.size, lons.size, 4), dtype=float)
bis = np.zeros((lats.size, lons.size, 4), dtype=int)
i_lat =... | Python | nomic_cornstack_python_v1 |
function groupSelector self
begin
return __groupSelector
end function | def groupSelector(self):
return self.__groupSelector | Python | nomic_cornstack_python_v1 |
comment Tree sort
string Adds each item to a BST and then performs in-order traversal Time complexity: Best case O(nlogn) Average case O(nlogn) Worst case O(n^2) (occurs when tree is skewed) Space complexity: O(n)
comment Counting sort
string - Assums each of the elements in in range 0 to k - Efficient if range of inpu... | # Tree sort
"""
Adds each item to a BST and then performs in-order traversal
Time complexity:
Best case O(nlogn)
Average case O(nlogn)
Worst case O(n^2) (occurs when tree is skewed)
Space complexity: O(n)
"""
# Counting sort
"""
- Assums each of the elements in in range 0 to k
- Ef... | Python | zaydzuhri_stack_edu_python |
from abc import ABCMeta , abstractmethod
comment 单例
class Zoo
begin
function __init__ self name
begin
set name = name
end function
function add_animal self obj
begin
set species = __name__
if not has attribute self species
begin
set attribute self species list
end
if call id obj not in get attribute self species
begin
... | from abc import ABCMeta, abstractmethod
# 单例
class Zoo:
def __init__(self, name):
self.name = name
def add_animal(self, obj):
species = type(obj).__name__
if not hasattr(self, species):
setattr(self, species, [])
if id(obj) not in getattr(self, species):
... | Python | zaydzuhri_stack_edu_python |
import discord
import os
set client = call Client
decorator event
async function on_ready
begin
print format string We have logged in as {0.user} client
end function
decorator event
async function on_message message
begin
if starts with content string clear
begin
set channel = call get_channel integer get environ strin... | import discord
import os
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.content.startswith('clear'):
channel = client.get_channel(int(os.environ.get('CHANNEL')))
history = await ... | Python | zaydzuhri_stack_edu_python |
comment There are two types of loops in Python, for and while
comment The "for" loop
set dlist = list 1 2 3 4
for item in dlist
begin
print item
end
string For loops can iterate over a sequence of numbers using the "range" and "xrange" functions. The difference between range and xrange is that the range function return... | # There are two types of loops in Python, for and while
# The "for" loop
dlist = [1, 2, 3, 4]
for item in dlist:
print(item)
"""
For loops can iterate over a sequence of numbers using the "range" and "xrange" functions.
The difference between range and xrange is that the range function returns a new list with... | Python | zaydzuhri_stack_edu_python |
function test_cuboids_exist self fake_get_region
begin
set os = call AWSObjectStore object_store_config
set expected_keys = list string CACHED-CUBOID&1&1&1&0&0&12 string CACHED-CUBOID&1&1&1&0&0&13 string CACHED-CUBOID&1&1&1&0&0&14
set test_keys = list string CACHED-CUBOID&1&1&1&0&0&100 string CACHED-CUBOID&1&1&1&0&0&13... | def test_cuboids_exist(self, fake_get_region):
os = AWSObjectStore(self.object_store_config)
expected_keys = ["CACHED-CUBOID&1&1&1&0&0&12", "CACHED-CUBOID&1&1&1&0&0&13", "CACHED-CUBOID&1&1&1&0&0&14"]
test_keys = ["CACHED-CUBOID&1&1&1&0&0&100", "CACHED-CUBOID&1&1&1&0&0&13", "CACHED-CUBOID&1&1&1&... | Python | nomic_cornstack_python_v1 |
import enum
class Color extends Enum
begin
set GREEN = string green
set YELLOW = string yellow
set RED = string red
end class | import enum
class Color(enum.Enum):
GREEN = 'green'
YELLOW = 'yellow'
RED = 'red'
| Python | zaydzuhri_stack_edu_python |
function music_inference_model LSTM_cell densor n_values=78 n_a=64 Ty=100
begin
comment Define the input of your model with a shape
set x0 = input shape=tuple 1 n_values
comment Define s0, initial hidden state for the decoder LSTM
set a0 = input shape=tuple n_a name=string a0
set c0 = input shape=tuple n_a name=string ... | def music_inference_model(LSTM_cell, densor, n_values = 78, n_a = 64, Ty = 100):
# Define the input of your model with a shape
x0 = Input(shape=(1, n_values))
# Define s0, initial hidden state for the decoder LSTM
a0 = Input(shape=(n_a,), name='a0')
c0 =... | Python | nomic_cornstack_python_v1 |
from app import Pygamer , BLUE , FPS , BLACK , BLUER , YELLOW
import pygame
import math
set RED = tuple 255 0 0
set GREEN = tuple 255 255 0
set GAP = 20
set FPS = 30
set SIZE = tuple 800 800
set tuple WIDTH HEIGHT = tuple 800 800
class Vec2
begin
function __init__ self x=0 y=0
begin
set x = x
set y = y
end function
fun... | from app import Pygamer, BLUE, FPS, BLACK, BLUER, YELLOW
import pygame
import math
RED = (255, 0, 0)
GREEN = (255, 255, 0)
GAP = 20
FPS = 30
SIZE = WIDTH, HEIGHT = 800, 800
class Vec2:
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
def __add__(self, vec2):
x = self.x + vec2.... | Python | zaydzuhri_stack_edu_python |
from models.FState import FState
from models.SState import SState
from models.Interval import Interval
comment Tries to find the given state in the support list.
comment Returns: index of state if found
comment None if not found
function GetIndex stateName stateSupportList
begin
set index = 0
for element in stateSuppor... | from models.FState import FState
from models.SState import SState
from models.Interval import Interval
# Tries to find the given state in the support list.
# Returns: index of state if found
# None if not found
def GetIndex(stateName, stateSupportList):
index = 0
for element in stateSupportList:
... | Python | zaydzuhri_stack_edu_python |
import configparser
from datetime import datetime
import os
from pyspark.sql import SparkSession
from pyspark.sql.functions import udf , col
from pyspark.sql.functions import year , month , dayofmonth , hour , weekofyear , date_format
from pyspark.sql.types import StructType as R , StructField as Fld , DoubleType as Db... | import configparser
from datetime import datetime
import os
from pyspark.sql import SparkSession
from pyspark.sql.functions import udf, col
from pyspark.sql.functions import year, month, dayofmonth, hour, weekofyear, date_format
from pyspark.sql.types import StructType as R, StructField as Fld, DoubleType as Dbl, Strin... | Python | zaydzuhri_stack_edu_python |
import sys , pygame , pygame.gfxdraw , time
from math import cos , sin , acos , atan2 , pi , sinh , cosh , acosh , sqrt , fabs , copysign
set scale = 0.01
set npoints = 4
set speed = 10
set screen_size = tuple 1000 700
set fps_cap = 30
comment Maths ###
comment The hyperbolic plane is characterised by polar coordinates... | import sys, pygame, pygame.gfxdraw, time
from math import cos, sin, acos, atan2, pi, sinh, cosh, acosh, sqrt, fabs, copysign
scale = 0.01
npoints = 4
speed = 10
screen_size = 1000, 700
fps_cap = 30
### Maths ###
## The hyperbolic plane is characterised by polar coordinates (r,a),
## the radial length and angle fro... | Python | zaydzuhri_stack_edu_python |
function SetDisplay self Display=defaultNamedNotOptArg
begin
return call InvokeTypes 21 LCID 1 tuple 11 0 tuple tuple 3 1 Display
end function | def SetDisplay(self, Display=defaultNamedNotOptArg):
return self._oleobj_.InvokeTypes(21, LCID, 1, (11, 0), ((3, 1),),Display
) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
function anagram s
begin
set count = 0
set char_set = list
if length s % 2 != 0
begin
return - 1
end
else
begin
set a = s at slice : length s // 2 :
set b = s at slice length s // 2 : :
set c = sorted a
set d = sorted b
end
for i in range 128
begin
if character i in a
begin
append char_se... | #!/usr/bin/python3
def anagram(s):
count = 0
char_set = []
if len(s)%2 != 0:
return -1
else:
a = (s[:(len(s)//2)])
b = (s[(len(s)//2):])
c = sorted(a)
d = sorted(b)
for i in range(128):
if chr(i) in a:
char_set.append(chr(i))
for j i... | Python | zaydzuhri_stack_edu_python |
function get_checker_executable name
begin
string Return checker executable in the form of a list of arguments for subprocess.Popen
if call is_program_installed name
begin
comment Checker is properly installed
return list name
end
else
begin
set path1 = call python_script_exists package=none module=name + string _scrip... | def get_checker_executable(name):
"""Return checker executable in the form of a list of arguments
for subprocess.Popen"""
if programs.is_program_installed(name):
# Checker is properly installed
return [name]
else:
path1 = programs.python_script_exists(package=None,
... | Python | jtatman_500k |
function iter_items iterable
begin
if has attribute iterable string keys
begin
for key in keys iterable
begin
yield tuple key iterable at key
end
end
else
begin
for tuple key value in iterable
begin
yield tuple key value
end
end
end function | def iter_items(iterable):
if hasattr(iterable, "keys"):
for key in iterable.keys():
yield key, iterable[key]
else:
for key, value in iterable:
yield key, value | Python | nomic_cornstack_python_v1 |
function predict self sess states actions
begin
return run _raw_outputs feed_dict=dict states states ; actions actions
end function | def predict(self, sess, states, actions):
return sess.run(
self._raw_outputs,
feed_dict={
self.states: states,
self.actions: actions
}
) | Python | nomic_cornstack_python_v1 |
comment -*- coding:utf-8 -*-
from jawiki import search_by_title , basic_info
import re
set text = call search_by_title string イギリス
set basic = call basic_info text
set value = string
set dic = dict
set pattern = compile string ('{2,3}|'{5})\s*([^']+?)\s*\1
for line in split basic string
begin
if line at 0 == string |... | # -*- coding:utf-8 -*-
from jawiki import search_by_title, basic_info
import re
text = search_by_title('イギリス')
basic = basic_info(text)
value=''
dic = {}
pattern = re.compile(r"('{2,3}|'{5})\s*([^']+?)\s*\1")
for line in basic.split('\n'):
if line[0] == '|':
key = line.split('=')[0].strip()[1:]
v... | Python | zaydzuhri_stack_edu_python |
function start_pending_mission sender instance **kwargs
begin
if started is not none and not is_started
begin
start instance
end
end function | def start_pending_mission(sender, instance, **kwargs):
if instance.started is not None and not instance.is_started:
instance.start() | Python | nomic_cornstack_python_v1 |
import math
function calcula_volume_da_esfera R
begin
set volume = 2 * pi * R
return volume
end function | import math
def calcula_volume_da_esfera(R):
volume = 2*math.pi*R
return volume
| Python | zaydzuhri_stack_edu_python |
function make_col_vector array
begin
return reshape array - 1 1
end function | def make_col_vector(array):
return array.reshape(-1, 1) | Python | nomic_cornstack_python_v1 |
comment https://www.hackerearth.com/challenge/competitive/april-circuits-18/algorithm/t1-1-6064aa64/
set n = integer input
set l = list map int split input
set ol = list l
sort l
set count = 0
while l != ol
begin
set i = 0
for i in range n
begin
if ol at i != l at i
begin
set a = index ol l at i
break
end
end
set x = l... | #https://www.hackerearth.com/challenge/competitive/april-circuits-18/algorithm/t1-1-6064aa64/
n=int(input())
l=list(map(int,input().split()))
ol=list(l)
l.sort()
count=0
while(l!=ol):
i=0
for i in range(n):
if ol[i]!=l[i]:
a=ol.index(l[i])
break
x=l[i:a+1]
x.reverse()
... | Python | zaydzuhri_stack_edu_python |
function loss_2 self three_d_matrix
begin
set sum = 0
for i in range length images
begin
set sum = sum + call diff_norm_2 images at i call get_image_projection three_d_matrix i
end
return sum
end function | def loss_2(self, three_d_matrix):
sum = 0
for i in range(len(self.images)):
sum += diff_norm_2(self.images[i], self.get_image_projection(
three_d_matrix, i))
return sum | Python | nomic_cornstack_python_v1 |
comment 一次元熱拡散方程式の陽解法
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
comment 一次元の棒を考える
comment この棒の左半分の温度に初期条件 T0 = 20
comment 右半分の温度に T0 = 100 が与えられている
comment この温度が時間とともに拡散していく様子を
comment シミュレーションする
comment (つまり温度Tは時間tと位置xの2変数関数)
comment T(t, x) と表す。このとき、初期温度は
comment T(0,... | # 一次元熱拡散方程式の陽解法
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# 一次元の棒を考える
# この棒の左半分の温度に初期条件 T0 = 20
# 右半分の温度に T0 = 100 が与えられている
# この温度が時間とともに拡散していく様子を
# シミュレーションする
# (つまり温度Tは時間tと位置xの2変数関数)
# T(t, x) と表す。このとき、初期温度は
# T(0, x) = 20 (0 < x < 0.5)
# T(0, x) = 100 (0.5 <= x <... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
string extract the command line to ignore all warnings
import traceback , sys , os
from util import *
function read
begin
set results = list
for line in stdin
begin
set results = results + list call readIssuesParts line
end
return results
end function
function countRules lines
begin
set r... | #!/usr/bin/env python3
""" extract the command line to ignore all warnings
"""
import traceback, sys, os
from util import *
def read():
results = []
for line in sys.stdin:
results += [readIssuesParts(line)]
return results
def countRules(lines):
results = {}
for parts in lines:
rul... | Python | zaydzuhri_stack_edu_python |
string 1. More attributes In addition to attributes TENSE, NUM, we can still specify a boolean property which indicates the type of word which the current word can receive. For example: V[TENSE=pres, +AUX] -> 'can' V[TENSE=pres, +AUX] -> 'may' V[TENSE=pres, -AUX] -> 'walks' V[TENSE=pres, -AUX] -> 'likes' V[TENSE=pres, ... | """
1. More attributes
In addition to attributes TENSE, NUM, we can still specify a boolean property
which indicates the type of word which the current word can receive.
For example:
V[TENSE=pres, +AUX] -> 'can'
V[TENSE=pres, +AUX] -> 'may'
V[TENSE=pres, -AUX] -> 'walks'
V[TENSE=pres, -AUX] -> 'likes'... | Python | zaydzuhri_stack_edu_python |
function reclass_groups reclass_csv_file
begin
set data = default dictionary list
with open reclass_file string rb as f
begin
set reader = reader f
next reader
for row in reader
begin
append data at row at 1 row at 0
end
end
set groups = list
end function | def reclass_groups(reclass_csv_file):
data = defaultdict(list)
with open(reclass_file, 'rb') as f:
reader = csv.reader(f)
next(reader)
for row in reader:
data[row[1]].append(row[0])
groups = [] | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
string Created on 2016年7月7日 @author: chendq
import base64
import time
import json
from courierAes import CourierAes
function _get_requests_data requestsData
begin
string 将请求出去base64解码
return base64 decode requestsData
end function
function _get_json_str data
be... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 2016年7月7日
@author: chendq
'''
import base64
import time
import json
from courierAes import CourierAes
def _get_requests_data(requestsData):
'''将请求出去base64解码'''
return base64.b64decode(requestsData)
def _get_json_str(data):
'''获取请求数据中json数据包''... | Python | zaydzuhri_stack_edu_python |
function buildFromClassAndRawData cls id mass=none spin=none parity=none charge=none halflife=none label=string default
begin
set particle = call cls id
call buildFromRawData mass=mass spin=spin parity=parity charge=charge halflife=halflife label=label
return particle
end function | def buildFromClassAndRawData(cls, id, mass = None, spin = None, parity = None, charge = None, halflife = None, label = 'default'):
particle = cls(id)
particle.buildFromRawData(mass=mass, spin=spin, parity=parity, charge=charge, halflife=halflife, label=label)
return particle | Python | nomic_cornstack_python_v1 |
import copy
import math
from node import Node
import sys
function ID3 data_set attribute_metadata numerical_splits_count depth
begin
string See Textbook for algorithm. Make sure to handle unknown values, some suggested approaches were given in lecture. ===================================================================... | import copy
import math
from node import Node
import sys
def ID3(data_set, attribute_metadata, numerical_splits_count, depth):
'''
See Textbook for algorithm.
Make sure to handle unknown values, some suggested approaches were
given in lecture.
===========================================... | 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.