code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function __fspath__ self
begin
raise NotImplementedError
end function | def __fspath__(self):
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
comment Tilte: Extract_STOPS_Tables
comment Purpose: Extracts specified tables from the STOPS report
comment Description: Identifies specified tables and writes out each table a text file
comment Author: Amar Sarvepalli
comment Email: sarvepalli@pbworld.com
comment Data: April 27, 2017
comment User's Settings
comment d... | # Tilte: Extract_STOPS_Tables
# Purpose: Extracts specified tables from the STOPS report
# Description: Identifies specified tables and writes out each table a text file
#
# Author: Amar Sarvepalli
# Email: sarvepalli@pbworld.com
# Data: April 27, 2017
################################################################... | Python | zaydzuhri_stack_edu_python |
function make_random_context num_obj num_att d
begin
set obj_ls = list comprehension string g + string x for x in range num_obj
set att_ls = list comprehension string m + string x for x in range num_att
set table = list comprehension list comprehension integer d > random for _ in range num_att for _ in range num_obj
re... | def make_random_context(num_obj, num_att, d):
obj_ls = ['g' + str(x) for x in range(num_obj)]
att_ls = ['m' + str(x) for x in range(num_att)]
table = [[int(d > random.random())
for _ in range(num_att)]
for _ in range(num_obj)]
return Context(table, obj_ls, att_ls) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf8 -*-
from ply import yacc
from lex_analysis import tokens
set precedence = tuple tuple string left string and string or string XOR tuple string left string LSS string LEQ string GTR string GEQ string EQL string NEQ tuple string left string PLUS string MINUS tuple string left string TIMES string ... | # -*- coding: utf8 -*-
from ply import yacc
from lex_analysis import tokens
precedence = (
('left', 'and', 'or', 'XOR'),
('left', 'LSS', 'LEQ', 'GTR', 'GEQ', 'EQL', 'NEQ'),
('left', 'PLUS', 'MINUS'),
('left', 'TIMES', 'DIVIDE', 'MOD'),
('right', 'SFPLUS', 'SFMINUS', 'not')
)
table_max_... | Python | zaydzuhri_stack_edu_python |
function is_even_statement param
begin
if param % 2 == 0
begin
return true
end
else
begin
return false
end
end function | def is_even_statement(param):
if param % 2 == 0:
return True
else:
return False | Python | nomic_cornstack_python_v1 |
comment -*- coding:utf-8 -*-
comment Definition for singly-linked list.
class ListNode
begin
function __init__ self x
begin
set val = x
set next = none
end function
end class
class Solution
begin
function detectCycle self head
begin
if head is none
begin
return none
end
if next is none
begin
return none
end
set first =... | # -*- coding:utf-8 -*-
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
if head is None: return None
if head.next is None: return None
first = h... | Python | zaydzuhri_stack_edu_python |
set m = decimal input string Escreva uma medida em metros:
set c = m * 100
set mm = m * 1000
print string { m } metros é { c } centímetros e { mm } milímetros | m = float(input('Escreva uma medida em metros: '))
c = m * 100
mm = m * 1000
print(f'{m} metros é {c} centímetros e {mm} milímetros')
| Python | zaydzuhri_stack_edu_python |
comment Task: implement a merge sort with additional arrays for left and right ...
function split array
begin
string Splits array into two halves and returns left and right half
if length array < 2
begin
raise call ValueError string Cant split array with less than 2 values!
end
set middle = length array // 2
set left =... | # Task: implement a merge sort with additional arrays for left and right ...
def split(array):
"""Splits array into two halves and returns left and right half"""
if len(array) < 2:
raise ValueError("Cant split array with less than 2 values!")
middle = len(array) // 2
left = array[0:middle]
... | Python | zaydzuhri_stack_edu_python |
function test_rtsp_0
begin
comment String 0
set cam1 = call CameraFactory
set rtsp = string 0
save
set stream1 = call Stream rtsp=rtsp camera_id=id
assert rtsp == 0
comment Integer 0
set rtsp = 0
save
set stream1 = call Stream rtsp=rtsp camera_id=id
assert rtsp == 0
end function | def test_rtsp_0():
# String 0
cam1 = CameraFactory()
cam1.rtsp = "0"
cam1.save()
stream1 = Stream(rtsp=cam1.rtsp, camera_id=cam1.id)
assert stream1.rtsp == 0
# Integer 0
cam1.rtsp = 0
cam1.save()
stream1 = Stream(rtsp=cam1.rtsp, camera_id=cam1.id)
assert stream1.rtsp == 0 | Python | nomic_cornstack_python_v1 |
function to_str action
begin
comment TODO: Improve this render
return call render_card_number discard
end function | def to_str(action):
# TODO: Improve this render
return Card.render_card_number(action.discard) | Python | nomic_cornstack_python_v1 |
function get_proficiency_search self
begin
comment Implemented from azosid template for -
comment osid.resource.ResourceSearchSession.get_resource_search_template
if not call _can string search
begin
raise call PermissionDenied
end
return call get_proficiency_search
end function | def get_proficiency_search(self):
# Implemented from azosid template for -
# osid.resource.ResourceSearchSession.get_resource_search_template
if not self._can('search'):
raise PermissionDenied()
return self._provider_session.get_proficiency_search() | Python | nomic_cornstack_python_v1 |
from control_demo import Demo
import logging
import argparse
set logger = call getLogger __name__
call setLevel DEBUG
set CONTROL_TYPES = dict string 1 string EEImpedance ; string 2 string JointVelocity ; string 3 string JointImpedance ; string 4 string JointTorque ; string 5 string EEPosture
set DEMO_TYPES = dict stri... | from control_demo import Demo
import logging
import argparse
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
CONTROL_TYPES = {
"1": "EEImpedance",
"2": "JointVelocity",
"3": "JointImpedance",
"4": "JointTorque",
"5": "EEPosture"}
DEMO_TYPES = {
"0": "Zero",
"1": "Sequen... | Python | zaydzuhri_stack_edu_python |
import cv2
import numpy as np
set cap = call VideoCapture 0
set face_cascade = call CascadeClassifier string haarcascade_frontalface_alt.xml
set face_data = list
set dataset_path = string ./data/
set file_name = input string Enter the name of person:-
while true
begin
set tuple ret frame = read cap
if ret == false
beg... | import cv2
import numpy as np
cap = cv2.VideoCapture(0)
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
face_data = []
dataset_path = './data/'
file_name = input("Enter the name of person:- ")
while True:
ret, frame = cap.read()
if ret == False:
continue
gray_frame = cv2.cvtColor(frame... | Python | zaydzuhri_stack_edu_python |
function partition_list arr m
begin
set n = integer ceil length arr / decimal m
return list comprehension arr at slice i : i + n : for i in range 0 length arr n
end function | def partition_list(arr, m):
n = int(math.ceil(len(arr) / float(m)))
return [arr[i:i + n] for i in range(0, len(arr), n)] | Python | nomic_cornstack_python_v1 |
comment flake8: noqa
from typing import Generic , TypeVar
from datatypes import __version__ , datatype
function test_version
begin
assert __version__ == string 0.1.0
end function
set A = call TypeVar string A
decorator call datatype expose=locals
class Maybe extends Generic at A
begin
set Just : A
set Nothing : tuple
... | # flake8: noqa
from typing import Generic, TypeVar
from datatypes import __version__, datatype
def test_version():
assert __version__ == "0.1.0"
A = TypeVar("A")
@datatype(expose=locals())
class Maybe(Generic[A]):
Just: A
Nothing: ()
def fmap(self, f):
from datatypes import match, placeh... | Python | zaydzuhri_stack_edu_python |
string Thought: loop through the input, distinguish the segments by looking for blank spaces. In order to avoid the problem of wrong format such as two blank spaces between words and having a blank spaces at the end of the input, I added a boolean variable word_before which is used to determine if the index before the ... | """
Thought: loop through the input, distinguish the segments by looking for blank
spaces. In order to avoid the problem of wrong format such as two blank spaces
between words and having a blank spaces at the end of the input, I added a
boolean variable word_before which is used to determine if the index before the
bla... | Python | zaydzuhri_stack_edu_python |
function test_multiple_keep self
begin
set extractor = call keep string //div[@id="main"]
set html = extract extractor TEST_HTML
set expected_html = string <html><body><div id="main"><a href="test">Test <em>Link</em></a></div><footer>I am the <span>footer</span></footer></body></html>
assert equal call format_output ht... | def test_multiple_keep(self):
extractor = Extractor().keep("//footer").keep('//div[@id="main"]')
html = extractor.extract(TEST_HTML)
expected_html = """<html><body><div id="main"><a href="test">Test <em>Link</em></a></div><footer>I am the <span>footer</span></footer></body></html>"""
s... | Python | nomic_cornstack_python_v1 |
function chain_len n
begin
set ret = 0
while n > 1
begin
if n % 2 == 0
begin
set n = n // 2
end
else
begin
set n = 3 * n + 1
end
set ret = ret + 1
end
return ret
end function | def chain_len(n):
ret = 0
while n > 1:
if n%2 == 0:
n //= 2
else:
n = 3*n+1
ret += 1
return ret | Python | nomic_cornstack_python_v1 |
import nltk
from nltk.corpus import stopwords
import string
import random
import sklearn
import json
from time import time
from keras.models import Sequential
from keras.layers import *
from keras.callbacks import TensorBoard
from TensorFlow.Chatbot.viaKeras_constants import *
from TensorFlow.Chatbot.viaKeras_utils imp... | import nltk
from nltk.corpus import stopwords
import string
import random
import sklearn
import json
from time import time
from keras.models import Sequential
from keras.layers import *
from keras.callbacks import TensorBoard
from TensorFlow.Chatbot.viaKeras_constants import *
from TensorFlow.Chatbot.viaKeras_utils imp... | Python | zaydzuhri_stack_edu_python |
comment -*- coding=utf-8 -*-
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.events import EVENT_JOB_EXECUTED , EVENT_JOB_ERROR
from datetime import datetime
import logging
from ssh import write_config_md5_to_db
comment 记录日志
call basicConfig level=INFO format=string %(asctime)s %(filename... | # -*- coding=utf-8 -*-
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ERROR
from datetime import datetime
import logging
from ssh import write_config_md5_to_db
# 记录日志
logging.basicConfig(level=logging.INFO,
format='%(ascti... | Python | zaydzuhri_stack_edu_python |
import csv , string
set printable = set printable
set sanitized_data = dict
set key = 0
set first_col = string
set prev_first_col = string
with open string new_combi_sheet.csv encoding=string latin-1 as infile
begin
set csv_raw = reader infile
for row_list in csv_raw
begin
comment remove non printable chars and lead... | import csv, string
printable = set(string.printable)
sanitized_data = {}
key = 0
first_col = ''
prev_first_col = ''
with open('new_combi_sheet.csv', encoding='latin-1') as infile:
csv_raw = csv.reader(infile)
for row_list in csv_raw:
# remove non printable chars and leading and trailing whitesp... | Python | zaydzuhri_stack_edu_python |
function change_map self map_name
begin
set cmd = format string {}changeMap {} console map_name
call write_command cmd
end function | def change_map(self, map_name):
cmd = '{}changeMap {}'.format(self.console, map_name)
self.write_command(cmd) | Python | nomic_cornstack_python_v1 |
function sort_activities activities
begin
function sort_order value
begin
string Sort activities by the number of connected members.
return - get value string members 0 or 0
end function
return sorted values activities key=sort_order
end function | def sort_activities(activities):
def sort_order(value):
"""
Sort activities by the number of connected members.
"""
return -(value.get('members', 0) or 0)
return sorted(activities.values(), key=sort_order) | Python | nomic_cornstack_python_v1 |
import sys
comment Range for the passwords is 248345-746315
set low = 248345
set high = 746315
comment Generates the list of possible passowrds
comment Input is the starting point and endpoint
comment Create them all since there is a small list
function GeneratePasswords low high
begin
set passwords = list
for num in ... | import sys
# Range for the passwords is 248345-746315
low = 248345
high = 746315
# Generates the list of possible passowrds
# Input is the starting point and endpoint
# Create them all since there is a small list
def GeneratePasswords(low, high):
passwords = []
for num in range(low, high, 1):
password... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import pandas as pd
comment create apandas dateframe
comment arr= np.array([['zhang',60,90],['Li',80,70],['Wang',100,50]])
comment arr=dict({'name':['zhang','li','wang'],'math':[60,80,90],'english':[90,100,20]})
comment DateFrame 输出列表:列表,数轴标签,横轴标签
comment df=pd.DataFrame(arr,index=[1,2,3],columns=['n... | import numpy as np
import pandas as pd
#create apandas dateframe
#arr= np.array([['zhang',60,90],['Li',80,70],['Wang',100,50]])
#arr=dict({'name':['zhang','li','wang'],'math':[60,80,90],'english':[90,100,20]})
#DateFrame 输出列表:列表,数轴标签,横轴标签
#df=pd.DataFrame(arr,index=[1,2,3],columns=['name','math','english'])
#csv读取... | Python | zaydzuhri_stack_edu_python |
import os
import random
import numpy as np
import torch
from text import text_to_sequence
class TextMelDataset extends Dataset
begin
string 1) loads filepath,text pairs 2) normalizes text and converts them to sequences of one-hot vectors 3) loads mel-spectrograms from mel files
function __init__ self melpaths_and_text ... | import os
import random
import numpy as np
import torch
from text import text_to_sequence
class TextMelDataset(torch.utils.data.Dataset):
"""
1) loads filepath,text pairs
2) normalizes text and converts them to sequences of one-hot vectors
3) loads mel-spectrograms from mel fi... | Python | zaydzuhri_stack_edu_python |
function vall *args
begin
return if expression args then all generator expression boolean a for a in args else true
end function | def vall(*args: A) -> bool:
return all(bool(a) for a in args) if args else True | Python | nomic_cornstack_python_v1 |
comment coding: UTF-8
comment 数据来源:http://www.di.unipi.it/optimize/Data/MEX.html
comment sscflp(Capacitated Facility Location Problem)
import numpy as np
import re
import time
import csv
import os
class Solution
begin
comment tag是标记
comment filename是计算的数据来源
comment mode可以是
comment "greed"(贪心)
comment "la"(局部搜索——爬山法)
co... | # coding: UTF-8
# 数据来源:http://www.di.unipi.it/optimize/Data/MEX.html
# sscflp(Capacitated Facility Location Problem)
import numpy as np
import re
import time
import csv
import os
class Solution:
# tag是标记
# filename是计算的数据来源
# mode可以是
# "greed"(贪心)
# "la"(局部搜索——爬山法)
# "sa"(模拟退火法)
# c... | Python | zaydzuhri_stack_edu_python |
import plotly.graph_objects as go
import numpy as np
import pandas as pd
from scipy.stats.kde import gaussian_kde
from plotly.subplots import make_subplots
from matplotlib.colors import LinearSegmentedColormap
set af_df = read csv string simulations.csv
set af_df = concat list af_df read csv string simulations_noPressu... | import plotly.graph_objects as go
import numpy as np
import pandas as pd
from scipy.stats.kde import gaussian_kde
from plotly.subplots import make_subplots
from matplotlib.colors import LinearSegmentedColormap
af_df = pd.read_csv("simulations.csv")
af_df = pd.concat([af_df,pd.read_csv("simulations_noPressure.csv")],ig... | Python | zaydzuhri_stack_edu_python |
from scene import Manager as SceneManager , Scene , DisplayScene
from io_event import IOEvent
from scenes import SceneId
from set_interval import set_interval
from datetime import datetime
class Dummy extends DisplayScene
begin
function __init__ self display
begin
call __init__ DUMMY display
set timer = none
set time =... | from scene import Manager as SceneManager, Scene, DisplayScene
from io_event import IOEvent
from scenes import SceneId
from set_interval import set_interval
from datetime import datetime
class Dummy(DisplayScene):
def __init__(self, display):
super().__init__(SceneId.DUMMY, display)
self.timer = N... | Python | zaydzuhri_stack_edu_python |
function encode alphabet seq needsort=false
begin
set output_seq = list
if needsort
begin
set alphabet = sorted alphabet
end
set seq = list seq
set alphabet = list alphabet
for x in seq
begin
set index = index alphabet x
append output_seq index
set alphabet = call move_to_front alphabet index
end
return output_seq
end... | def encode(alphabet, seq, needsort=False):
output_seq = []
if needsort:
alphabet = sorted(alphabet)
seq = list(seq)
alphabet = list(alphabet)
for x in seq:
index = alphabet.index(x)
output_seq.append(index)
alphabet = move_to_front(alphabet, index)
return output_s... | Python | nomic_cornstack_python_v1 |
function call_api self access_token
begin
comment API endpoint URL
set url = string https://www.googleapis.com/oauth2/v2/userinfo
comment set request headers
set headers = dict string Authorization string OAuth %s % access_token
comment make API request
set response = call fetch url headers=headers
comment check if we ... | def call_api(self, access_token):
# API endpoint URL
url = 'https://www.googleapis.com/oauth2/v2/userinfo'
# set request headers
headers = {'Authorization': 'OAuth %s' % access_token}
# make API request
response = urlfetch.fetch(url, headers=headers)
# check if ... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import serial
comment 打开串口
comment 串口
set serialPort = string COM5
comment 波特率
set baudRate = 9600
set ser = call Serial serialPort baudRate timeout=0.05
print string 参数设置:串口=%s ,波特率=%d % tuple serialPort baudRate
comment 收发数据
while 1
begin
set str = input string 请输入要发送的数据(非中文)并同时接收数据:
wri... | # -*- coding: utf-8 -*-
import serial
# 打开串口
serialPort = "COM5" # 串口
baudRate = 9600 # 波特率
ser = serial.Serial(serialPort, baudRate, timeout=0.05)
print("参数设置:串口=%s ,波特率=%d" % (serialPort, baudRate))
# 收发数据
while 1:
str = input("请输入要发送的数据(非中文)并同时接收数据: ")
ser.write((str + '\r\n').encode())
#print(ser.readline())... | Python | zaydzuhri_stack_edu_python |
import functools
function bounded mini maxi
begin
function dector func
begin
decorator wraps func
function wrapper *args **kargs
begin
set result = call func *args keyword kargs
if result < mini
begin
return mini
end
if result > maxi
begin
return maxi
end
return result
end function
return wrapper
end function
return de... | import functools
def bounded(mini,maxi):
def dector(func):
@functools.wraps(func)
def wrapper(*args,**kargs):
result = func(*args,**kargs)
if result < mini:
return mini
if result > maxi:
return maxi
return result
return wrapper
return dector
@bounded(0,100)
def percent(amonut,total):
retu... | Python | zaydzuhri_stack_edu_python |
from threading import Thread
import requests
import json
import yaml
import re
import xml.etree.ElementTree as ET
import csv
function safe_request route headers
begin
set response = none
try
begin
set response = get requests route headers=headers
end
except ConnectionError as e
begin
print e
end
return response
end fun... | from threading import Thread
import requests
import json
import yaml
import re
import xml.etree.ElementTree as ET
import csv
def safe_request(route, headers):
response = None
try:
response = requests.get(route, headers=headers)
except requests.ConnectionError as e:
print(e)
return resp... | Python | zaydzuhri_stack_edu_python |
function is_shared_folder_transfer_ownership_details self
begin
return _tag == string shared_folder_transfer_ownership_details
end function | def is_shared_folder_transfer_ownership_details(self):
return self._tag == 'shared_folder_transfer_ownership_details' | Python | nomic_cornstack_python_v1 |
function center_window self
begin
set frame_geometry = call frameGeometry
set center_point = call center
call moveCenter center_point
move call topLeft
end function | def center_window(self):
frame_geometry = self.frameGeometry()
center_point = QDesktopWidget().availableGeometry().center()
frame_geometry.moveCenter(center_point)
self.move(frame_geometry.topLeft()) | Python | nomic_cornstack_python_v1 |
function no_moves position
begin
string Finds if the game is over. :type: position: Board :rtype: bool
return call no_moves white or call no_moves black
end function | def no_moves(position):
"""
Finds if the game is over.
:type: position: Board
:rtype: bool
"""
return position.no_moves(color.white) \
or position.no_moves(color.black) | Python | jtatman_500k |
for e in flist
begin
if total + integer e > minutes
begin
break
end
else
begin
set total = total + integer e
set tasknum = tasknum + 1
end
end
print tasknum | for e in flist:
if total + int(e) > minutes:
break
else:
total += int(e)
tasknum += 1
print(tasknum)
| Python | zaydzuhri_stack_edu_python |
function read_maze file_name
begin
try
begin
with open file_name as fh
begin
set maze = list comprehension list comprehension ch for ch in strip line string for line in fh
end
set num_col_top_row = length maze at 0
for row in maze
begin
if length row != num_col_top_row
begin
print string Maze is not rectangular
raise S... | def read_maze(file_name):
try:
with open(file_name) as fh:
maze = [[ch for ch in line.strip("\n")] for line in fh]
num_col_top_row = len(maze[0])
for row in maze:
if len(row) != num_col_top_row:
print("Maze is not rectangular")
raise SystemError
return maze
except IOError:
print("Th... | Python | zaydzuhri_stack_edu_python |
import mysql.connector
from pathlib import Path
from config import ZONES_CONFIG_FILEPATH , DIR_FOR_ZONES_FILES
from db_config import *
function create_zone_file zones_and_hosts files_dir_path
begin
string Создание файлов с описанием хостов каждой зоны :param a_records: :param file_path: :return:
make directory files_di... | import mysql.connector
from pathlib import Path
from config import ZONES_CONFIG_FILEPATH, DIR_FOR_ZONES_FILES
from db_config import *
def create_zone_file(zones_and_hosts: dict, files_dir_path: Path):
"""
Создание файлов с описанием хостов каждой зоны
:param a_records:
:param file_path:
:return:
... | Python | zaydzuhri_stack_edu_python |
comment Create your views here.
from django.http import HttpResponseBadRequest , HttpResponseForbidden , HttpResponse
from django.views.decorators.csrf import csrf_exempt
from models import SMS , Device
from util import authorize , get_callable
import json
from django.conf import settings
decorator csrf_exempt
function... | # Create your views here.
from django.http import HttpResponseBadRequest, HttpResponseForbidden, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from models import SMS, Device
from util import authorize, get_callable
import json
from django.conf import settings
@csrf_exempt
... | Python | zaydzuhri_stack_edu_python |
comment kNN Algorithm, assignment 1 for Machine Learning course
comment Author : Amro Amro
comment each item in the dataset has x-coordinate, y-coordinate and class (0 or 1)
set dataset = list list 7.5 5 1 list 8 5.5 1 list 4 3 0 list 4 4 0 list 3 4 0 list 6.5 3 1 list 7 5 1 list 4.5 4.5 0 list 5 5 0 list 7 4 1
set k =... | # kNN Algorithm, assignment 1 for Machine Learning course
# Author : Amro Amro
# each item in the dataset has x-coordinate, y-coordinate and class (0 or 1)
dataset = [
[7.5, 5, 1],
[8, 5.5, 1],
[4, 3, 0],
[4, 4, 0],
[3, 4, 0],
[6.5, 3, 1],
[7, 5, 1],
[4.5, 4.5, 0],
[5, 5, 0],
[... | Python | zaydzuhri_stack_edu_python |
string [===============================================================================================] [ ] [ Assignment NO: 3 ] [ Question NO: 4 ] [ Part: C ] [ Author: Mahdi Amini ] ] [ P.Con: Creating The Game of Pure Strategy card game ] [ Date Started: 2020-03-25 ] [ Date Finished: 2020-03-28 ] [ ] [-------------... | """
[===============================================================================================]
[ ]
[ Assignment NO: 3 ... | Python | zaydzuhri_stack_edu_python |
from sys import argv
set tuple script filename = argv
set file = open filename
print string This is your file:
print string { file }
print read file | from sys import argv
script, filename = argv
file = open(filename)
print("This is your file: ")
print(f"{file}")
print(file.read())
| Python | zaydzuhri_stack_edu_python |
function plot_tdc_violation_batch collection_paths_n_names query_length=0 top_n_docs=100 _type=1 terms_type=0 ofn_format=string png
begin
set results_root = join path string ../../all_results string tdc_violation
if not exists path results_root
begin
make directories results_root
end
set all_qids = list
if _type == 1
... | def plot_tdc_violation_batch(collection_paths_n_names, query_length=0,
top_n_docs=100, _type=1, terms_type=0, ofn_format='png'):
results_root = os.path.join('../../all_results', 'tdc_violation')
if not os.path.exists(results_root):
os.makedirs(results_root)
all_qids = []... | Python | nomic_cornstack_python_v1 |
string A palindromic number reads the same both ways. The largest palindrome madefrom the product of two 2-digit numbers is 9009 = 91 * 99. Find the largest palindrome made from the product of two 3-digit numbers.
comment Algo in ENG
comment biggest palindrom = 0
comment for all 3 digit number x
comment for all 3 digit... | """ A palindromic number reads the same both ways. The largest palindrome madefrom the product
of two 2-digit numbers is 9009 = 91 * 99.
Find the largest palindrome made from the product of two 3-digit numbers."""
#Algo in ENG
# biggest palindrom = 0
# for all 3 digit number x
# for all 3 digit number y
# product = x*y... | Python | zaydzuhri_stack_edu_python |
function all_videos self
begin
return call get_all_videos
end function | def all_videos(self):
return self._video_library.get_all_videos() | Python | nomic_cornstack_python_v1 |
function setLow2Max self
begin
call __setArrayValue __LOW arrayDefs at version at string Mask at __LOW
end function | def setLow2Max(self):
self.__setArrayValue(self.__LOW, self.arrayDefs[self.version]["Mask"][self.__LOW]) | Python | nomic_cornstack_python_v1 |
function load_pickle self args
begin
comment only to be used in no_scrape mode
set pickle_filepath = join path args at string data_path string jobs_ { date_string } .pkl
try
begin
set scrape_data = load pickle open pickle_filepath string rb
end
except FileNotFoundError as e
begin
error string { pickle_filepath } not fo... | def load_pickle(self, args):
# only to be used in no_scrape mode
pickle_filepath = os.path.join(args['data_path'],
f'jobs_{self.date_string}.pkl')
try:
self.scrape_data = pickle.load(open(pickle_filepath, 'rb'))
except FileNotFoundError ... | Python | nomic_cornstack_python_v1 |
from googlesearch import search
import time
import random
import webbrowser
import urllib.request
from bs4 import BeautifulSoup
while true
begin
print string STUDY HELPER
print string
set tool = input string 1. Google Search, 2. Calculator, 3. definition finder, 4. Exit:
if tool == string 1
begin
set query = input stri... | from googlesearch import search
import time
import random
import webbrowser
import urllib.request
from bs4 import BeautifulSoup
while True:
print("STUDY HELPER")
print("")
tool = input("1. Google Search, 2. Calculator, 3. definition finder, 4. Exit: ")
if tool == "1":
query = inpu... | Python | zaydzuhri_stack_edu_python |
for linha in range 0 3
begin
for coluna in range 0 3
begin
append matriz at cont integer input string Digite um valor para posição { linha } , { coluna } :
set cont = cont + 1
end
end
print string -=- * 20
print string { matriz at 0 } { matriz at 1 } { matriz at 2 } { matriz at 3 } { matriz at 4 } { matriz at 5 } { mat... | for linha in range(0,3):
for coluna in range(0,3):
matriz[cont].append(int(input(f'Digite um valor para posição {linha}, {coluna}: ')))
cont += 1
print('-=-' * 20)
print(f' { matriz[0] } { matriz[1]} { matriz[2]} '
f'\n { matriz[3] } { matriz[4]} { matriz[5] } '
f'\n { matriz[6] } { matr... | Python | zaydzuhri_stack_edu_python |
function get_predictions model serialization_dir reader device
begin
set dev = read reader string raw_data/drop/drop_dataset_dev.json
set vocab = call from_files join serialization_dir string vocabulary
set iterator = call BasicIterator batch_size=1
call index_with vocab
set dev_iter = call iterator dev num_epochs=1
se... | def get_predictions(model, serialization_dir, reader, device):
dev = reader.read('raw_data/drop/drop_dataset_dev.json')
vocab = Vocabulary.from_files(join(serialization_dir, 'vocabulary'))
iterator = BasicIterator(batch_size = 1)
iterator.index_with(vocab)
dev_iter = iterator(dev, num_epochs=1)
dev_batches =... | Python | nomic_cornstack_python_v1 |
from collections import deque
function is_pouch_filled bomb_pouch
begin
for bomb in bomb_pouch
begin
if bomb_pouch at bomb < 3
begin
return false
end
end
return true
end function
function get_result_message bomb_pouch
begin
if call is_pouch_filled bomb_pouch
begin
return string Bene! You have successfully filled the bo... | from collections import deque
def is_pouch_filled(bomb_pouch):
for bomb in bomb_pouch:
if bomb_pouch[bomb] < 3:
return False
return True
def get_result_message(bomb_pouch):
if is_pouch_filled(bomb_pouch):
return "Bene! You have successfully filled the bomb pouch!"
return ... | Python | zaydzuhri_stack_edu_python |
comment coding=gbk
string ICE(zeroc)С
import Ice
function initAppData xcfg=none props=none
begin
string ʼһICEӦ xcfg XmlConfigõ·ѡ props ָԣѡ
set data = call InitializationData
set properties = call createProperties
if xcfg
begin
import XmlConfig
if xcfg at slice - 1 : : != string /
begin
set xcfg = xcfg + string /
end
... | #coding=gbk
"""ICE(zeroc)С
"""
import Ice
def initAppData(xcfg=None, props=None):
"""ʼһICEӦ
xcfg XmlConfigõ·ѡ
props ָԣѡ
"""
data = Ice.InitializationData()
data.properties = Ice.createProperties()
if xcfg:
import XmlConfig
if xcfg[-1:] != '/':
... | Python | zaydzuhri_stack_edu_python |
function __init__ self description pkt_dec=32 pkt_sync=128 pkt_rrc=512 pkt_out=16
begin
call __init__ description
set xlnk = call Xlnk
set buf_out = call cma_array shape=tuple pkt_out * 2 dtype=int16
set buf_dec = call cma_array shape=tuple pkt_dec * 2 dtype=int16
set buf_sync = call cma_array shape=tuple pkt_sync * 2 ... | def __init__(self,
description,
pkt_dec=32,
pkt_sync=128,
pkt_rrc=512,
pkt_out=16):
super().__init__(description)
xlnk = Xlnk()
self.buf_out = xlnk.cma_array(shape=(pkt_out * 2, ), dtype=np.int16)
self... | Python | nomic_cornstack_python_v1 |
comment Code to compute the efficiency function for a certain energy injecting dark matter particle model
string Created on April 23 19:00 2017 @author J. Reynoso-Cordova eventhought this code is of the author's property you must cite 1506.03811 this is only to make a Python version. The necesarry files to run this cod... | #Code to compute the efficiency function for a certain energy injecting dark matter particle model
"""
Created on April 23 19:00 2017
@author J. Reynoso-Cordova
eventhought this code is of the author's property you must cite 1506.03811
this is only to make a Python version.
The necesarry files to run this code... | Python | zaydzuhri_stack_edu_python |
function GetApplicationHexFile self
begin
set callResult = call _Call string GetApplicationHexFile
if callResult is none
begin
return none
end
return callResult
end function | def GetApplicationHexFile(self):
callResult = self._Call("GetApplicationHexFile", )
if callResult is None:
return None
return callResult | Python | nomic_cornstack_python_v1 |
function test_gear_single_view_set_get_successful self
begin
comment Create test data
set gear = call create_or_update link=string http://site.com/canon item_make=string Canon item_model=string EOS 5D Mark II Test
set user = call create_user email=string mrtest@mypapaya.io password=string WhoAmI username=string aov1
co... | def test_gear_single_view_set_get_successful(self):
# Create test data
gear = account_models.Gear.objects\
.create_or_update(link='http://site.com/canon', item_make='Canon', item_model='EOS 5D Mark II Test')
user = account_models.User.objects.create_user(email='mrtest@mypapaya.io', ... | Python | nomic_cornstack_python_v1 |
function test_get_category_id self
begin
set response = get call client string /categories/1
set data = loads data
assert equal status_code 404
assert equal data at string message string resource not found
assert equal data at string success false
end function | def test_get_category_id(self):
response = self.client().get('/categories/1')
data = json.loads(response.data)
self.assertEqual(response.status_code, 404)
self.assertEqual(data['message'], 'resource not found')
self.assertEqual(data['success'], False) | Python | nomic_cornstack_python_v1 |
function isCorrectAnswer self buffer
begin
if length buffer < 3
begin
return false
end
set packetId = call unpack string >B buffer at slice : 1 : at 0
set packetLength = call unpack string >H buffer at slice 1 : 3 : at 0
return packetId == packetId and packetLength == length
end function | def isCorrectAnswer(self, buffer):
if len(buffer) < 3:
return False
packetId = unpack('>B', buffer[:1])[0]
packetLength = unpack('>H', buffer[1:3])[0]
return (packetId == self.packetId) and \
(packetLength == self.length) | Python | nomic_cornstack_python_v1 |
function cvv_ttype_table argv
begin
set p = call OptionParser
call add_option string -D string --drop action=string store_true default=false dest=string drop help=string drop the table
call add_option string -d string --debug action=string store_true default=false dest=string debug help=string run the debugger
call add... | def cvv_ttype_table(argv):
p = optparse.OptionParser()
p.add_option('-D', '--drop',
action='store_true', default=False, dest='drop',
help='drop the table')
p.add_option('-d', '--debug',
action='store_true', default=False, dest='debug',
help... | Python | nomic_cornstack_python_v1 |
function _reset self pos=none
begin
if pos is none
begin
comment I cant really get started...can i?
raise exception string No pos given
end
comment self.energy = 1
set pos = copy np pos
set _trying_this_pos = copy np pos
set provision_dir = none
set succeed = 0
set failed = 0
set failed_reset = 0
end function | def _reset(self, pos: Optional[np.ndarray] = None):
if pos is None:
# I cant really get started...can i?
raise Exception("No pos given")
# self.energy = 1
self.pos = np.copy(pos)
self._trying_this_pos = np.copy(pos)
self.provision_dir = None
self.... | Python | nomic_cornstack_python_v1 |
function da arg **kwargs
begin
set deck = call Deck 50
function doita
begin
set aa : Tuple at tuple int int = call _qcpy deck qs at dpQ qs at dbQ arg
return aa
end function
comment update the interval and function
set mma = call _replace doit=doita
comment run it
return call _thread_template mma printfun=myprint keywor... | def da(arg: Threadargs, **kwargs):
deck = Deck(50)
def doita():
aa: Tuple[int, int] = trackermain._qcpy(
deck, mma.qs[QK.dpQ], mma.qs[QK.dbQ], arg)
return aa
# update the interval and function
mma = arg._replace(
... | Python | nomic_cornstack_python_v1 |
function check_ssh_known_host name_or_ip known_hosts_file=KNOWN_HOSTS_FILE
begin
try
begin
with KNOWN_HOSTS_MUTEX
begin
check call list string ssh-keygen string -F name_or_ip string -f known_hosts_file
end
return true
end
except CalledProcessError as e
begin
if returncode == 1
begin
return false
end
else
begin
raise
en... | def check_ssh_known_host(name_or_ip, known_hosts_file=KNOWN_HOSTS_FILE):
try:
with KNOWN_HOSTS_MUTEX:
subprocess.check_call(['ssh-keygen', '-F', name_or_ip,
'-f', known_hosts_file])
return True
except subprocess.CalledProcessError as e:
if e... | Python | nomic_cornstack_python_v1 |
function source_data tmp_path_factory
begin
set source_path = call mktemp string source_data
return call Path source_path
end function | def source_data(tmp_path_factory):
source_path = tmp_path_factory.mktemp("source_data")
return Path(source_path) | Python | nomic_cornstack_python_v1 |
function revComp s
begin
set d = dict string A string T ; string C string G ; string G string C ; string T string A ; string N string N
set s = s at slice : : - 1
set x = list comprehension d at c for c in s
return join string x
end function | def revComp(s):
d = {"A": "T", "C": "G", "G": "C", "T": "A", "N": "N"}
s = s[::-1]
x = [d[c] for c in s]
return "".join(x) | Python | nomic_cornstack_python_v1 |
comment coding=utf-8
comment 笑脸爆炸
comment 精灵图形的使用 pygame.sprite.Sprite类
comment pygame.sprite.Sprite是pygame精灵的基类,一般来说,你总是需要写一个自己的精灵类继承一下它然后加入自己的代码
import pygame
import random
call init
set BLACK = tuple 0 0 0
comment step1. 页面初始化:设置屏幕,设置标题,变量,初始化clock类,加载笑脸图片,初始化精灵类Group
set screen = call set_mode list 800 600
call set... | # coding=utf-8
# 笑脸爆炸
# 精灵图形的使用 pygame.sprite.Sprite类
# pygame.sprite.Sprite是pygame精灵的基类,一般来说,你总是需要写一个自己的精灵类继承一下它然后加入自己的代码
import pygame
import random
pygame.init()
BLACK = (0, 0, 0)
# step1. 页面初始化:设置屏幕,设置标题,变量,初始化clock类,加载笑脸图片,初始化精灵类Group
screen = pygame.display.set_mode([800, 600])
pygame.display.set_caption('Smiley ... | Python | zaydzuhri_stack_edu_python |
function edit_artist artist_id
begin
set artist = get query artist_id
set form = call ArtistForm
set data = dict string id id ; string name name ; string genres split genres string ; ; string city city ; string state state ; string phone phone ; string seeking_venue seeking_venue ; string seeking_description seeking_de... | def edit_artist(artist_id):
artist = Artist.query.get(artist_id)
form = ArtistForm()
data = {
"id": artist.id,
"name": artist.name,
"genres": artist.genres.split(';'),
"city": artist.city,
"state": artist.state,
"phone": artist.phone,
"seeking_venue": artist.seeking_venue,
"seeking... | Python | nomic_cornstack_python_v1 |
function getData
begin
set powerInfo = call getoutput string pmset -g ps
set ouputString = string
set powerState = string
set powerSource = string
set powerState = string
set percentage = string
set time = string
if string AC Power in powerInfo
begin
set powerSource = string AC
end
else
if string Battery in power... | def getData():
powerInfo = commands.getoutput("pmset -g ps")
ouputString = ""
powerState = ""
powerSource = ""
powerState = ""
percentage = ""
time = ""
if "AC Power" in powerInfo:
powerSource = "AC"
elif "Battery" in powerInfo:
powerSource = "Battery"
if "charged" in powerInfo:
powerState = "Charge... | Python | nomic_cornstack_python_v1 |
function verify self **kwargs
begin
string Implementations MUST either return both a Client Configuration Endpoint and a Registration Access Token or neither of them. :param kwargs: :return: True if the message is OK otherwise False
call verify keyword kwargs
set has_reg_uri = string registration_client_uri in self
set... | def verify(self, **kwargs):
"""
Implementations MUST either return both a Client Configuration Endpoint
and a Registration Access Token or neither of them.
:param kwargs:
:return: True if the message is OK otherwise False
"""
super(RegistrationResponse, self).veri... | Python | jtatman_500k |
function read_data_from_csv path_to_csv n_epochs height width training=true
begin
set csv_path = call string_input_producer list path_to_csv num_epochs=n_epochs
set textReader = call TextLineReader
set tuple _ csv_content = read textReader csv_path
set tuple im_name im_label = call decode_csv csv_content record_default... | def read_data_from_csv(path_to_csv, n_epochs, height, width, training = True):
csv_path = tf.train.string_input_producer([path_to_csv], num_epochs=n_epochs)
textReader = tf.TextLineReader()
_, csv_content = textReader.read(csv_path)
im_name, im_label = tf.decode_csv(csv_content, record_defaults=[["... | Python | nomic_cornstack_python_v1 |
function exit
begin
Ellipsis
end function | def exit(retval=0, /) -> Any:
... | Python | nomic_cornstack_python_v1 |
from mpi4py import MPI
import math as m
import time
import sys
set comm = COMM_WORLD
set rank = call Get_rank
set size = call Get_size
set termino = false
function isPrime n
begin
set sw = true
if n < 2
begin
return false
end
set j = 2
while j <= square root n and sw
begin
if n % j == 0
begin
set sw = false
end
set j =... | from mpi4py import MPI
import math as m
import time
import sys
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
termino = False
def isPrime(n):
sw = True
if(n < 2):
return False
j = 2
while(j <= m.sqrt(n) and sw):
if n % j == 0:
sw = False
... | Python | zaydzuhri_stack_edu_python |
comment coding=utf-8
string Created on 2015年10月6日 @author: Administrator
from __future__ import division
import sys
call reload sys
comment @UndefinedVariable
call setdefaultencoding string utf-8
import numpy as np
from sklearn import linear_model
comment 数据集
set train_x = array list list 0 0 list 1 1 list 2 2 list 50 ... | #coding=utf-8
'''
Created on 2015年10月6日
@author: Administrator
'''
from __future__ import division
import sys
reload(sys)
sys.setdefaultencoding('utf-8') # @UndefinedVariable
import numpy as np
from sklearn import linear_model
# 数据集
train_x= np.array([[0, 0], [1, 1], [2, 2],[50,50]]) | Python | zaydzuhri_stack_edu_python |
function ScoreCpuPsnr target_bitrate result
begin
set score = result at string psnr
comment We penalize bitrates that exceed the target bitrate.
comment Score reduction is 0.1 dB per percentage point over target.
if result at string bitrate > integer target_bitrate
begin
set percent_overshoot = 100.0 * result at string... | def ScoreCpuPsnr(target_bitrate, result):
score = result['psnr']
# We penalize bitrates that exceed the target bitrate.
# Score reduction is 0.1 dB per percentage point over target.
if result['bitrate'] > int(target_bitrate):
percent_overshoot = 100.0 * ((result['bitrate'] - float(target_bitrate))
/... | 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 |
import cv2
comment load the cascade
set face_cascade = call cv2CascadeClassifier string haarcascade_frontalface_default.xml
comment Read the input image
set img = call imread string messi.jpg
comment convert into grayscale
set gray = call cvtColor img COLOR_BGR2GRAY
comment Detect faces
set faces = call detectMultiScal... | import cv2
# load the cascade
face_cascade = cv2CascadeClassifier('haarcascade_frontalface_default.xml')
# Read the input image
img = cv2.imread(r'messi.jpg')
# convert into grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Detect faces
faces = face_cascade.detectMultiScale(gray, 1.1, 4)
# draw rectangle aroun... | Python | zaydzuhri_stack_edu_python |
function has_any_from_unimported_type t
begin
return call accept call HasAnyFromUnimportedType
end function | def has_any_from_unimported_type(t: Type) -> bool:
return t.accept(HasAnyFromUnimportedType()) | Python | nomic_cornstack_python_v1 |
comment d) Disene una funcion que permita el ingreso de dos numeros
comment naturales j y h e imprima jh utilizando solo la operacion
comment multiplicacion.
function numeros j h acumulador=0 cont=1
begin
set acumulador = j
while cont < h
begin
set cont = cont + 1
set acumulador = acumulador * j
end
end function | # d) Disene una funcion que permita el ingreso de dos numeros
# naturales j y h e imprima jh utilizando solo la operacion
# multiplicacion.
def numeros(j,h,acumulador=0,cont=1):
acumulador=j
while cont<h:
cont=cont+1
acumulador=acumulador*j | Python | zaydzuhri_stack_edu_python |
function ensure_object_is_string item title
begin
string Checks that the item is a string. If not, raises ValueError.
assert is instance title str
if not is instance item str
begin
set msg = string {} must be a string. {} passed instead.
raise call TypeError format msg title type item
end
return none
end function | def ensure_object_is_string(item, title):
"""
Checks that the item is a string. If not, raises ValueError.
"""
assert isinstance(title, str)
if not isinstance(item, str):
msg = "{} must be a string. {} passed instead."
raise TypeError(msg.format(title, type(item)))
return None | Python | jtatman_500k |
function exp_filter_pan err_i alpha=0.1
begin
set filtered_err = alpha * err_i + 1 - alpha * filtered_err_prev
set filtered_err_prev = filtered_err
return filtered_err
end function | def exp_filter_pan(err_i, alpha = 0.1):
filtered_err = (alpha * err_i) + ((1 - alpha) * exp_filter_pan.filtered_err_prev)
exp_filter_pan.filtered_err_prev = filtered_err
return filtered_err | Python | nomic_cornstack_python_v1 |
function send_cluster_command self *argv **kwargs
begin
if refresh_table_asap
begin
call initialize_slots_cache
end
set ttl = RedisClusterRequestTTL
set asking = false
set try_random_node = false
while ttl > 0
begin
set ttl = ttl - 1
set key = call get_key_from_command argv
if not key
begin
raise exception string No wa... | def send_cluster_command(self, *argv, **kwargs):
if self.refresh_table_asap:
self.initialize_slots_cache()
ttl = self.RedisClusterRequestTTL
asking = False
try_random_node = False
while ttl > 0:
ttl -= 1
key = self.get_key_from_command(argv)
... | Python | nomic_cornstack_python_v1 |
import argparse
function terminal_arguments
begin
set parser = call ArgumentParser
call add_argument string --first_run action=string store_true help=string Запускается ли программа в первый раз
call add_argument string --email type=str required=false help=string Email при авторизации
call add_argument string --passwor... | import argparse
def terminal_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('--first_run', action='store_true', help='Запускается ли программа в первый раз')
parser.add_argument('--email', type=str, required=False, help='Email при авторизации')
parser.add_argument('--password', ty... | Python | zaydzuhri_stack_edu_python |
function isHappy n
begin
set tracker = set
while true
begin
if n == 1
begin
return true
end
else
if n in tracker
begin
return false
end
else
begin
add tracker n
set n = sum list comprehension integer c ^ 2 for c in string n
end
end
end function | def isHappy(n):
tracker = set()
while True:
if n == 1:
return True
elif n in tracker:
return False
else:
tracker.add(n)
n = sum([int(c)**2 for c in str(n)])
| Python | zaydzuhri_stack_edu_python |
string The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3. Find the sum of the only eleven primes that are both truncatable ... | '''
The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.
Find the sum of the only eleven primes that are both truncatable f... | Python | zaydzuhri_stack_edu_python |
from easyMail import EasyMail
import pandas as pd
print string ***** Welcome to EasyMail *****
comment create an object of EasyMail class
set mailerObject = call EasyMail
comment read your data into a dataframe
set data = call read_excel string demo.xlsx
comment list all columns in the excel sheet to be present in the ... | from easyMail import EasyMail
import pandas as pd
print("\n***** Welcome to EasyMail *****\n")
# create an object of EasyMail class
mailerObject = EasyMail()
# read your data into a dataframe
data = pd.read_excel("demo.xlsx")
# list all columns in the excel sheet to be present in the email
columnsList = ["Roll Nu... | Python | zaydzuhri_stack_edu_python |
function __test_function
begin
set sheet = call Spreadsheet
assert length sheet > 0 msg string Spreadsheet size is 0 on FlaskDriver.py home function.
assert length sheet at __python_query > 0 msg string FlaskDriver.py: ' + __python_query + string ' is not a header in Spreadsheet
assert exists __RESULT_PATH msg string Y... | def __test_function():
sheet = Spreadsheet()
assert len(sheet) > 0, 'Spreadsheet size is 0 on FlaskDriver.py home function.'
assert len(sheet[__python_query]) > 0, 'FlaskDriver.py: \'' + __python_query + '\' is not a header in Spreadsheet'
assert __RESULT_PATH.exists(), 'You\'r missing or misspelled the... | Python | nomic_cornstack_python_v1 |
function get self page=none per_page=none category=none filter=none sort=none updated_after_date=none
begin
set params = call get_params none locals
set request = call Request string GET call get_url params
return tuple request parse_json
end function | def get(self, page=None, per_page=None, category=None,
filter=None, sort=None, updated_after_date=None):
params = base.get_params(None, locals())
request = http.Request('GET', self.get_url(), params)
return request, parsers.parse_json | Python | nomic_cornstack_python_v1 |
function add_matrix matrix1 matrix2
begin
if length matrix1 != length matrix2
begin
return string Matrices not compatible
end
if length matrix1 at 0 != length matrix2 at 0
begin
return string Matrices not compatible
end
set rows = length matrix1
set cols = length matrix1 at 0
set result = list comprehension list compre... | def add_matrix(matrix1, matrix2):
if len(matrix1) != len(matrix2):
return 'Matrices not compatible'
if len(matrix1[0]) != len(matrix2[0]):
return 'Matrices not compatible'
rows = len(matrix1)
cols = len(matrix1[0])
result = [[sum(row) for row in zip(*size)] for size in zip(matri... | Python | jtatman_500k |
function maxSubArray A
begin
set max_sum = A at 0
set sum = A at 0
for i in range 1 length A
begin
set sum = max sum + A at i A at i
set max_sum = max max_sum sum
end
return max_sum
end function | def maxSubArray(A):
max_sum=A[0]
sum=A[0]
for i in range(1,len(A)):
sum=max(sum+A[i],A[i])
max_sum=max(max_sum,sum)
return max_sum
| Python | zaydzuhri_stack_edu_python |
import turtle
call forward 100
call left 120
call forward 100
call left 120
call forward 100
call penup
import time
sleep 100 | import turtle
turtle.forward(100)
turtle.left(120)
turtle.forward(100)
turtle.left(120)
turtle.forward(100)
turtle.penup()
import time
time.sleep(100) | Python | zaydzuhri_stack_edu_python |
function get_port_connected_with_t0_vm duthost nbrhosts
begin
set port_list = list
set t0_vm_list = list comprehension vm_name for vm_name in keys nbrhosts if ends with vm_name string T0
for t0_vm in t0_vm_list
begin
set port = call shell format string show ip interface | grep -w {} | awk '{{print $1}}' t0_vm at strin... | def get_port_connected_with_t0_vm(duthost, nbrhosts):
port_list = []
t0_vm_list = [vm_name for vm_name in nbrhosts.keys() if vm_name.endswith('T0')]
for t0_vm in t0_vm_list:
port = duthost.shell("show ip interface | grep -w {} | awk '{{print $1}}'".format(t0_vm))['stdout']
port_list.append(p... | Python | nomic_cornstack_python_v1 |
comment 1.다음과 같은 문자열이 있을 때 이를 대문자 BTC_KRW로 변경하세요.
comment ticker = "btc_krw"
set ticker = string btc_krw
print upper ticker
comment 2.다음과 같은 문자열이 있을 때 이를 소문자 btc_krw로 변경하세요.
comment ticker = "BTC_KRW"
set ticker = string btc_krw
print lower ticker
comment 3.다음과 같은 문자열이 있을 때 공백을 기준으로 문자열을 나눠보세요.
comment a = "hello world... | # 1.다음과 같은 문자열이 있을 때 이를 대문자 BTC_KRW로 변경하세요.
# ticker = "btc_krw"
ticker = "btc_krw"
print(ticker.upper())
# 2.다음과 같은 문자열이 있을 때 이를 소문자 btc_krw로 변경하세요.
# ticker = "BTC_KRW"
ticker = "btc_krw"
print(ticker.lower())
# 3.다음과 같은 문자열이 있을 때 공백을 기준으로 문자열을 나눠보세요.
# a = "hello world"
a = "hello world"
print(a.split(" "))
# 4.다음... | Python | zaydzuhri_stack_edu_python |
function distro_plot real_samples generator discriminator
begin
set inputs = random tuple shape at 0 1
set fake_samples = call generator inputs
set groups = horizontal stack tuple real_samples call numpy
histogram groups density=true color=list string blue string red label=list string True string Generated bins=20 rwid... | def distro_plot(real_samples: np.ndarray, generator: Model,
discriminator: Model):
inputs = np.random.random((real_samples.shape[0],1))
fake_samples = generator(inputs)
groups = np.hstack((real_samples, fake_samples.numpy()))
plt.hist(
groups,
density=True,
color=['blue', 're... | Python | nomic_cornstack_python_v1 |
function seq self dm state0
begin
set ui = call UIs dm state0
set narr = string
if not ui
begin
comment stable since the dm has no UIs available
set seqStab = 1
set narr = narr + call chattyHelper dm state0 + string is SEQ stable for DM + name + string since they have no UIs from this state.
end
else
begin
set narr = ... | def seq(self,dm,state0):
ui=self.UIs(dm,state0)
narr = ''
if not ui:
seqStab = 1 #stable since the dm has no UIs available
narr += self.chattyHelper(dm,state0)+' is SEQ stable for DM '+ dm.name +' since they have no UIs from this state.\n'
else:
... | Python | nomic_cornstack_python_v1 |
import os
import re
from StringIO import StringIO
from fabric.api import sudo , put
set script_dir = directory name path real path path __file__
set bashrc_file = join path script_dir call normpath string ./.bashrc
class ServerUtils
begin
decorator staticmethod
function set_bash_rc
begin
string Upload shell preferences... | import os
import re
from StringIO import StringIO
from fabric.api import sudo, put
script_dir = os.path.dirname(os.path.realpath(__file__))
bashrc_file = os.path.join(script_dir,os.path.normpath("./.bashrc"))
class ServerUtils():
@staticmethod
def set_bash_rc():
""" Upload shell preferences
"... | Python | zaydzuhri_stack_edu_python |
function _dump_json self
begin
if not _current_id == length _img_ids
begin
warn format string Recorded {} out of {} validation images, incomplete results _current_id length _img_ids
end
try
begin
with open _filename string w as f
begin
dump _results f
end
end
except IOError as e
begin
raise call RuntimeError format str... | def _dump_json(self):
if not self._current_id == len(self._img_ids):
warnings.warn(
'Recorded {} out of {} validation images, incomplete results'.format(
self._current_id, len(self._img_ids)))
try:
with open(self._filename, 'w') as f:
... | Python | nomic_cornstack_python_v1 |
import win_unicode_console
call enable
string 7.1 处理缺失数据
import pandas as pd
import numpy as np
set string_data = call Series list string aardvark string artichoke nan string avocado
print is null string_data
string 1.过滤缺失值
comment 可以使用pandas.isnull和boolean indexing, 配合使用dropna。
comment 对于series,只会返回non-null数据和index va... | import win_unicode_console
win_unicode_console.enable()
"""
7.1 处理缺失数据
"""
import pandas as pd
import numpy as np
string_data = pd.Series(['aardvark', 'artichoke', np.nan, 'avocado'])
print(string_data.isnull())
"""
1.过滤缺失值
"""
# 可以使用pandas.isnull和boolean indexing, 配合使用dropna。
# 对于series,只会返回non-null数据和index values
fr... | Python | zaydzuhri_stack_edu_python |
function inorder self
begin
call _inorder root
end function | def inorder(self):
self._inorder(self.root) | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.