code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
from dataclasses import dataclass , field
from enum import Enum , IntEnum , auto
from re import Pattern , compile
from typing import Any , Dict , List , NamedTuple , Optional , Text , Union
import unittest
from json_data import DeserializingFailError , InvalidAnnotationError , JsonFormat , from_data_to , serializing_op... | from dataclasses import dataclass, field
from enum import Enum, IntEnum, auto
from re import Pattern, compile
from typing import Any, Dict, List, NamedTuple, Optional, Text, Union
import unittest
from json_data import DeserializingFailError, InvalidAnnotationError, JsonFormat, from_data_to, serializing_option
from log... | Python | zaydzuhri_stack_edu_python |
function tripartite_lcls x links y score=false
begin
set s = shape at 0
set lcl_links = zeros s dtype=object
set nodes_class1 = unique links at tuple slice : : 0
set nodes_class2 = unique links at tuple slice : : 1
set ne_class2 = dictionary
set ne_class3 = dictionary
for i in range shape at 0
begin
if any i == n... | def tripartite_lcls(x, links, y, score=False):
s = links.shape[0]
lcl_links = np.zeros(s, dtype=object)
nodes_class1 = np.unique(links[:,0])
nodes_class2 = np.unique(links[:,1])
ne_class2 = dict()
ne_class3 = dict()
for i in range(x.shape[0]):
if any(i == nodes_cl... | Python | nomic_cornstack_python_v1 |
string coding: utf-8 This code locates matching subsequences between either two timestamped Subtitle Rip (.srt) or a series of .srt files a .txt text file on sample data provided. The files are first processed to remove punctuation and code certain words. Clips for each match are created from the audio (.wav) files for... | """coding: utf-8
This code locates matching subsequences between either two timestamped Subtitle Rip (.srt)
or a series of .srt files a .txt text file on sample data provided.
The files are first processed to remove punctuation
and code certain words. Clips for each match are created from the audio (.wav) files for th... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_filter1d
from audio2numpy import open_audio
from scipy.io.wavfile import write
from scipy import signal
from scipy.signal import hilbert
import math
function low_pass_filter sig Cutoff
begin
comment Filter order
set N = 3
comment Cuto... | import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_filter1d
from audio2numpy import open_audio
from scipy.io.wavfile import write
from scipy import signal
from scipy.signal import hilbert
import math
def low_pass_filter(sig, Cutoff):
N = 3 # Filter order
Wn = Cutoff # Cut... | Python | zaydzuhri_stack_edu_python |
function generate_test_method test_name
begin
function run_test self
begin
comment backup any existing files with our expected output_name
set output_name = format string {}.png test_name
set backup_name = output_name + string .backup
if is file path output_name
begin
rename output_name backup_name
call addCleanup clea... | def generate_test_method(test_name):
def run_test(self):
# backup any existing files with our expected output_name
output_name = "{}.png".format(test_name)
backup_name = output_name + ".backup"
if os.path.isfile(output_name):
os.rename(output_name, backup_name)
... | Python | nomic_cornstack_python_v1 |
class Solution extends object
begin
function isMatch self s p
begin
string PROBLEM STATEMENT: Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'. '.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover th... | class Solution(object):
def isMatch(self, s, p):
"""
PROBLEM STATEMENT:
Given an input string (s) and a pattern (p),
implement regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element... | Python | zaydzuhri_stack_edu_python |
function update self other
begin
if is instance other __class__
begin
update _spec _spec
end
else
begin
update _spec other
end
return self
end function | def update(self, other: SpecLike):
if isinstance(other, self.__class__):
self._spec.update(other._spec)
else:
self._spec.update(other)
return self | Python | nomic_cornstack_python_v1 |
string Name: Ketaki Thatte CWID: 10419625
string Descrption: Search engine using Inverted Index for documents. It asks you to enter a search query, and then returns all documents matching the query, in decreasing order of similarity.
from nltk.tokenize import RegexpTokenizer
from collections import defaultdict
from fun... | """
Name: Ketaki Thatte
CWID: 10419625
"""
"""
Descrption: Search engine using Inverted Index for documents.
It asks you to enter a search query, and then returns all documents
matching the query, in decreasing order of similarity.
"""
from nltk.tokenize import RegexpTokenizer
from collections import defaultdict
from... | Python | zaydzuhri_stack_edu_python |
function block_inverse iA B C D
begin
set logger = call getLogger __name__
info string ------- block_inverse(iA, B, C, D) -------
debug format string Input matrix types are: {} {} {} {} type iA type B type C type D
debug format string Input matrix shapes are: {} {} {} {} shape shape shape shape
set n = shape at 0
set r... | def block_inverse(iA, B, C, D):
logger = logging.getLogger(__name__)
logger.info("------- block_inverse(iA, B, C, D) -------")
logger.debug("Input matrix types are: {} {} {} {}".format(type(iA), type(B),
type(C), type(D)))
logger.debug("Input... | Python | nomic_cornstack_python_v1 |
function bubble_sort_1 l
begin
set start = length wakeup_times - 1
while start
begin
for time in range 1 length wakeup_times
begin
set tuple prev_time current_time = tuple wakeup_times at time - 1 wakeup_times at time
if prev_time > current_time
begin
set tuple wakeup_times at time - 1 wakeup_times at time = tuple curr... | def bubble_sort_1(l):
start = len(wakeup_times) - 1
while start:
for time in range(1, len(wakeup_times)):
prev_time, current_time = wakeup_times[time-1], wakeup_times[time]
if prev_time > current_time:
wakeup_times[time-1], wakeup_times[time] = current_time, prev... | Python | zaydzuhri_stack_edu_python |
comment import scipy.stats.linregress as lreg
from scipy import stats
import os
from tools.plots import plot_philip
function philip ks s t
begin
return 0.5 * s * t ^ - 0.5 + ks
end function
function transform_time time
begin
string transform time in order to Linearize Philip formula
return 0.5 * time ^ - 0.5
end functi... | #import scipy.stats.linregress as lreg
from scipy import stats
import os
from tools.plots import plot_philip
def philip(ks, s, t):
return 0.5*s*t**(-0.5) + ks
def transform_time(time):
""" transform time in order to Linearize Philip formula """
return 0.5*time**(-0.5)
def get_ks_s(data, out_dir, plot=... | Python | zaydzuhri_stack_edu_python |
function get_xrange_indices self lower upper
begin
set lower_index = argument maximum x >= lower
set upper_index = argument maximum x >= upper
return tuple integer lower_index integer upper_index
end function | def get_xrange_indices(self, lower, upper):
lower_index = np.argmax(self.x >= lower)
upper_index = np.argmax(self.x >= upper)
return int(lower_index), int(upper_index) | Python | nomic_cornstack_python_v1 |
function wifi self
begin
if not has attribute self string _wifi
begin
set cmd = list string networksetup string -getairportpower string en0
set output = check output cmd
set _wifi = string On in string output
end
return _wifi
end function | def wifi(self):
if not hasattr(self, "_wifi"):
cmd = ["networksetup", "-getairportpower", "en0"]
output = subprocess.check_output(cmd)
self._wifi = "On" in str(output)
return self._wifi | Python | nomic_cornstack_python_v1 |
function freq_method spts *labels
begin
set spts = copy spts
if not labels
begin
set labels = tuple string home string work
end
for tuple name group in group by spts string user_id
begin
if string duration not in columns
begin
set group at string duration = group at string finished_at - group at string started_at
end
c... | def freq_method(spts, *labels):
spts = spts.copy()
if not labels:
labels = ("home", "work")
for name, group in spts.groupby("user_id"):
if "duration" not in group.columns:
group["duration"] = group["finished_at"] - group["started_at"]
# pandas keeps inner order of groups
... | Python | nomic_cornstack_python_v1 |
comment 题目
comment 题目描述
comment 在一个国家仅有1分,2分,3分硬币,将钱N分兑换成硬币有很多种兑法。请你编程序计算出共有多少种兑法。
comment 解答要求
comment 时间限制:1000ms, 内存限制:64MB
comment 输入
comment 输入每行包含一个正整数N(0<N<32768)。输入到文件末尾结束。
comment 输出
comment 输出对应的兑换方法数。
comment 样例
comment 输入样例 1 复制
comment 3
comment 2934
comment 输出样例 1
comment 3
comment 718831
function change_... | # 题目
# 题目描述
# 在一个国家仅有1分,2分,3分硬币,将钱N分兑换成硬币有很多种兑法。请你编程序计算出共有多少种兑法。
#
# 解答要求
# 时间限制:1000ms, 内存限制:64MB
# 输入
# 输入每行包含一个正整数N(0<N<32768)。输入到文件末尾结束。
#
# 输出
# 输出对应的兑换方法数。
#
# 样例
# 输入样例 1 复制
#
# 3
# 2934
# 输出样例 1
#
# 3
# 718831
def change_cion():
from pip._vendor.distlib.compat import raw_input
n = int( input('input a n... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Wed Nov 18 15:23:37 2020 @author: Fernando Garcia (fergarciadlc)
import cv2
import json
comment Settings and constants
with open string config_photo.json string r as fp
begin
set data = load json fp
end
set object_height_mm = data at string object at string height_mm
comm... | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 18 15:23:37 2020
@author: Fernando Garcia (fergarciadlc)
"""
import cv2
import json
# Settings and constants
with open("config_photo.json", "r") as fp:
data = json.load(fp)
object_height_mm = data["object"]["height_mm"]
# Validation data
# Camera
if type(data["camer... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
import torch
from torch import nn
from torch.autograd import Variable
import torch.nn.functional as F
class Net extends Module
begin
function __init__ self
begin
call __init__
comment Conv1d(in_channels, out_channels, kernel_size, stride, padding)
set conv_hidden_size = 64
set conv1 = sequ... | # -*- coding: utf-8 -*-
import torch
from torch import nn
from torch.autograd import Variable
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# Conv1d(in_channels, out_channels, kernel_size, stride, padding)
conv_hidden_size = 64
... | Python | zaydzuhri_stack_edu_python |
from tkinter import *
from tkinter import scrolledtext
from tkinter.filedialog import askopenfilename , askdirectory
import back
comment -------------------BACKEND---------------------------
function clicked_start
begin
global FILE_NAME_OLD_ARC
global NAME_SEP_DIR
global BATCH
global START
if FILE_NAME_OLD_ARC != none ... | from tkinter import *
from tkinter import scrolledtext
from tkinter.filedialog import askopenfilename,askdirectory
import back
#-------------------BACKEND---------------------------
def clicked_start():
global FILE_NAME_OLD_ARC
global NAME_SEP_DIR
global BATCH
global START
if FILE_NAME_OLD_ARC!=... | Python | zaydzuhri_stack_edu_python |
function test_is_match_for_all_true self
begin
set msg = call MIMEText string this is some test content
set msg at string Subject = string this is a critical alert
assert true call is_match msg
end function | def test_is_match_for_all_true(self):
msg = MIMEText('this is some test content')
msg['Subject'] = 'this is a critical alert'
self.assertTrue(self.subject_sieve.is_match(msg)) | Python | nomic_cornstack_python_v1 |
import openpyxl as xl
from openpyxl.utils.exceptions import InvalidFileException
from datetime import date
function process_workbook
begin
while true
begin
set fhandle = input string Enter the name of the spreadsheet you want to open (hit 'Enter' if you want to use the default):
if length fhandle < 1
begin
set workbook... | import openpyxl as xl
from openpyxl.utils.exceptions import InvalidFileException
from datetime import date
def process_workbook():
while True:
fhandle = input("Enter the name of the spreadsheet you want to open (hit 'Enter' if you want to use the default): ")
if len(fhandle) < 1:
workbo... | Python | zaydzuhri_stack_edu_python |
import tensorflow as tf
function model cifar
begin
set _IMAGE_SIZE = 32
set _IMAGE_CHANNELS = 3
if cifar == 10
begin
set _NUM_CLASSES = 10
end
else
begin
set _NUM_CLASSES = 100
end
comment define functions
function weight_variable shape stddev=0.05
begin
set initial = call random_normal shape stddev=stddev dtype=float3... | import tensorflow as tf
def model(cifar):
_IMAGE_SIZE = 32
_IMAGE_CHANNELS = 3
if cifar == 10:
_NUM_CLASSES = 10
else:
_NUM_CLASSES = 100
# define functions
def weight_variable(shape, stddev=0.05):
initial = tf.random_normal(shape, stddev=stddev, dtype=tf.float32)
... | Python | zaydzuhri_stack_edu_python |
comment len() funktion - ger längden på en lista.
print string Alfabetet innehåller { length alfabet } bokstäver
comment indexera
print string Bokstav på index 0: { alfabet at 0 }
print string Bokstav på index -2: { alfabet at - 2 }
print string Bokstav på index 6: { alfabet at 6 }
print string Alfabetet baklänges: { a... | # len() funktion - ger längden på en lista.
print(f"Alfabetet innehåller {len(alfabet)} bokstäver")
# indexera
print(f"Bokstav på index 0: {alfabet[0]}")
print(f"Bokstav på index -2: {alfabet[-2]}")
print(f"Bokstav på index 6: {alfabet[6]}")
print(f"Alfabetet baklänges: {alfabet[::-1]}") | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
function func a b=dict
begin
set b at a = a
return b
end function
set dic = dict string x 2 ; string y 22
print call func 3
print call func 4
print call func 5 dic
print call func 2 | #!/usr/bin/python3
def func(a,b = {}):
b[a]= a
return b
dic={'x':2,'y':22}
print(func(3))
print(func(4))
print(func(5,dic))
print(func(2))
| Python | zaydzuhri_stack_edu_python |
function radius_from_slug slug
begin
set slug = call unicode slug
set radius = split slug string - at 0
assert is digit radius
return radius
end function | def radius_from_slug(slug):
slug = unicode(slug)
radius = slug.split('-')[0]
assert radius.isdigit()
return radius | Python | nomic_cornstack_python_v1 |
import numpy as np
from numpy import *
from matplotlib import pyplot
from matplotlib import pyplot as plt
import scipy as sp
import pylab
comment creo listas de ceros con la respectiva cantidad de bits que quiero trabajar
set lista16 = zeros 6 dtype=float16
set lista32 = zeros 6 dtype=float32
set lista64 = zeros 6 dtyp... | import numpy as np
from numpy import *
from matplotlib import pyplot
from matplotlib import pyplot as plt
import scipy as sp
import pylab
#creo listas de ceros con la respectiva cantidad de bits que quiero trabajar
lista16= np.zeros((6), dtype=np.float16)
lista32 = np.zeros((6), dtype=np.float32)
lista64 = np.zeros((6... | Python | zaydzuhri_stack_edu_python |
import unittest
import collections
class Queue
begin
function __init__ self
begin
set _queue = list
end function
function enqueue self value
begin
insert _queue 0 value
return value
end function
function dequeue self
begin
return pop _queue
end function
end class
class QueueFromDeque
begin
function __init__ self
begin... | import unittest
import collections
class Queue():
def __init__(self):
self._queue = []
def enqueue(self, value):
self._queue.insert(0, value)
return value
def dequeue(self):
return self._queue.pop()
class QueueFromDeque():
def __init__(self):
self._queue = c... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment coding: utf-8
import argparse
import io
import os
import pandas
import sys
function main argv=none
begin
if argv is none
begin
set argv = argv
end
comment prepare ArgumentParser
set parser = call ArgumentParser description=string Reads a .csv file full of analyzed peaks and annotate... | #!/usr/bin/env python
# coding: utf-8
import argparse
import io
import os
import pandas
import sys
def main(argv=None):
if argv is None:
argv = sys.argv
## prepare ArgumentParser
parser = argparse.ArgumentParser(description="Reads a .csv file full of analyzed peaks and annotates it with raw peak... | Python | zaydzuhri_stack_edu_python |
string 融联云短信平台测试脚本
comment from ronglian_sms_sdk import SmsSDK
comment accId = '8aaf070875e449d70175f48b39ad06e9'
comment accToken = 'f2154c75234a44329bd680dcf6fe9ff5'
comment appId = '8aaf070875e449d70175f48b3a9d06f0'
comment def send_message():
comment sdk = SmsSDK(accId, accToken, appId)
comment tid = '1'
comment mo... | '''融联云短信平台测试脚本'''
# from ronglian_sms_sdk import SmsSDK
# accId = '8aaf070875e449d70175f48b39ad06e9'
# accToken = 'f2154c75234a44329bd680dcf6fe9ff5'
# appId = '8aaf070875e449d70175f48b3a9d06f0'
# def send_message():
# sdk = SmsSDK(accId, accToken, appId)
# tid = '1'
# mobile = '18329520409'
# # datas传入一... | Python | zaydzuhri_stack_edu_python |
import requests
import json
import webbrowser
import datetime
comment 2021-0308
comment Jefferson Abreu Martinez
comment 27-6-2021
set hoy = today
set cedula = string input string Introduce tu cedula:
set cedula = replace cedula string - string
set nameFile = string input string Introduce el nombre que le daras al arch... | import requests
import json
import webbrowser
import datetime
# 2021-0308
# Jefferson Abreu Martinez
# 27-6-2021
hoy = datetime.date.today()
cedula = str(input("Introduce tu cedula: "))
cedula = cedula.replace("-","")
nameFile = str(input("Introduce el nombre que le daras al archivo html"))
datos = req... | Python | zaydzuhri_stack_edu_python |
function plot_hole self ax hole stroke score t_round=none flag_loc=none plotly=true
begin
set par = get list values __course_par at 0 hole
set shot_df = call hole_data hole stroke score t_round=t_round flag_loc=flag_loc
set all_scores = unique
for score in all_scores
begin
set c = call color_palette integer score par
s... | def plot_hole(
self, ax, hole, stroke, score, t_round=None, flag_loc=None, plotly=True,
):
par = list(self.__course_par.values())[0].get(hole)
shot_df = self.hole_data(
hole, stroke, score, t_round=t_round, flag_loc=flag_loc
)
all_scores = shot_df.score.unique()... | Python | nomic_cornstack_python_v1 |
function load_pretrained_network self
begin
if manager is none or checkpoint is none
begin
return false
end
set status = call restore latest_checkpoint
return status
end function | def load_pretrained_network(self):
if self.manager is None or self.checkpoint is None:
return False
status = self.checkpoint.restore(self.manager.latest_checkpoint)
return status | Python | nomic_cornstack_python_v1 |
function top_n self n=10
begin
return members at slice : n :
end function | def top_n(self, n: int = 10) -> dict:
return self.members[:n] | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import logging
import os
import random
import shlex
import subprocess
import signal
import threading
import time
class CommandPlayer extends Thread
begin
function __init__ self command callback
begin
string Constructor Parameters ---------- command : str Command to execute. callback: funct... | # -*- coding: utf-8 -*-
import logging
import os
import random
import shlex
import subprocess
import signal
import threading
import time
class CommandPlayer(threading.Thread):
def __init__(self, command, callback):
"""Constructor
Parameters
----------
command : str
... | Python | zaydzuhri_stack_edu_python |
function data_append data key value
begin
assert is instance data dict
assert is instance key str
set lst = get data key list
append lst value
if lst
begin
set data at key = lst
end
end function | def data_append(data, key, value):
assert isinstance(data, dict)
assert isinstance(key, str)
lst = data.get(key, [])
lst.append(value)
if lst:
data[key] = lst | Python | nomic_cornstack_python_v1 |
function hash_exists_remotely self
begin
try
begin
call lookup_by_hash
end
except HTTPError
begin
return false
end
return true
end function | def hash_exists_remotely(self):
try:
self.lookup_by_hash()
except requests.exceptions.HTTPError:
return False
return True | Python | nomic_cornstack_python_v1 |
function project map shape wcs order=3 mode=string constant cval=0.0 force=false prefilter=true mask_nan=false safe=true bsize=1000
begin
comment Skip expensive operation if map is compatible
if not force
begin
if call equal wcs wcs and tuple shape at slice - 2 : : == tuple shape at slice - 2 : :
begin
return copy ma... | def project(map, shape, wcs, order=3, mode="constant", cval=0.0, force=False, prefilter=True, mask_nan=False, safe=True, bsize=1000):
# Skip expensive operation if map is compatible
if not force:
if wcsutils.equal(map.wcs, wcs) and tuple(shape[-2:]) == tuple(shape[-2:]):
return map.copy()
elif wcsutils.is_comp... | Python | nomic_cornstack_python_v1 |
function hq_address1 self hq_address1
begin
set _hq_address1 = hq_address1
end function | def hq_address1(self, hq_address1):
self._hq_address1 = hq_address1 | Python | nomic_cornstack_python_v1 |
function raindrop_pic num_drop
begin
if num_drop == 0
begin
return 0
end
else
begin
set rand_rad = random integer 1 20
set rand_rip = random integer 3 8
call raindrop rand_rad
call up
call left 90
call forward rand_rad
call right 90
call ripple rand_rip rand_rad
return pi * rand_rad ^ 2 + call raindrop_pic num_drop - 1... | def raindrop_pic(num_drop):
if(num_drop == 0):
return 0
else:
rand_rad = random.randint(1,20)
rand_rip = random.randint(3,8)
raindrop(rand_rad)
tt.up()
tt.left(90)
tt.forward(rand_rad)
tt.right(90)
ripple(rand_rip, rand_rad... | Python | nomic_cornstack_python_v1 |
function forward self inputs attention_mask=none
begin
set input_dtype = dtype
if seq_op_in_fp32
begin
set inputs = to inputs dtype=float
end
return to call logcumsumexp dim=- 1 * power shape at 2 - 0.5 dtype=input_dtype
end function | def forward(self, inputs, attention_mask: Optional[torch.Tensor] = None):
input_dtype = inputs.dtype
if self.seq_op_in_fp32:
inputs = inputs.to(dtype=torch.float)
return (inputs.logcumsumexp(dim=-1) * pow(inputs.shape[2], -0.5)).to(dtype=input_dtype) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
comment 可变参数
comment 在Python函数中,还可以定义可变参数。顾名思义,可变参数就是传入的参数个数是可变的,可以是1个、2个到任意个,还可以是0个。
comment 可变参数允许你传入0个或任意个参数,这些可变参数在函数调用时自动组装为一个tuple。
comment demo
function calc *numbers
begin
set sum = 0
for n in numbers
begin
set sum = sum + n * n
end
return sum
end func... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 可变参数
# 在Python函数中,还可以定义可变参数。顾名思义,可变参数就是传入的参数个数是可变的,可以是1个、2个到任意个,还可以是0个。
# 可变参数允许你传入0个或任意个参数,这些可变参数在函数调用时自动组装为一个tuple。
# demo
def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
# 定义可变参数和定义一个list或tuple参数相比,仅仅在参数前面加了一个*号。在函数内部,参数... | Python | zaydzuhri_stack_edu_python |
import cv2
import pyautogui
import pytesseract
from PIL import Image , ImageGrab , ImageOps
import numpy as np
import sys
from getch import Getch
set tesseract_cmd = string C:\Program Files\Tesseract-OCR\tesseract.exe
set SAVE_LOCATION = string C:\Users\Andy\Downloads\temp.png
set CLONES_TSV = string clones.tsv
functio... | import cv2
import pyautogui
import pytesseract
from PIL import Image, ImageGrab, ImageOps
import numpy as np
import sys
from getch import Getch
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
SAVE_LOCATION = r'C:\Users\Andy\Downloads\temp.png'
CLONES_TSV = 'clones.tsv'
def get_... | Python | zaydzuhri_stack_edu_python |
set holidays = integer input
set days_in_year = 365
set work_days = days_in_year - holidays
set playing_time_workday = 63
set playing_time_holiday = 127
set playing_standard_yearly = 30000
set total_playing_time = work_days * playing_time_workday + holidays * playing_time_holiday
set difference = absolute total_playing... | holidays = int(input())
days_in_year = 365
work_days = days_in_year - holidays
playing_time_workday = 63
playing_time_holiday = 127
playing_standard_yearly = 30000
total_playing_time = work_days * playing_time_workday + holidays * playing_time_holiday
difference = abs(total_playing_time - playing_standard_yearly)
diff... | Python | zaydzuhri_stack_edu_python |
function moveObject self id position
begin
set ordering = call getOrdering
if call providedBy ordering
begin
return call moveObjectToPosition id position
end
else
begin
return 0
end
end function | def moveObject(self, id, position):
ordering = self.getOrdering()
if IExplicitOrdering.providedBy(ordering):
return ordering.moveObjectToPosition(id, position)
else:
return 0 | Python | nomic_cornstack_python_v1 |
function argmin data=none axis=_Null keepdims=_Null name=none attr=none out=none **kwargs
begin
return tuple 0
end function | def argmin(data=None, axis=_Null, keepdims=_Null, name=None, attr=None, out=None, **kwargs):
return (0,) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
import argparse
from rest_client import RestClient
if __name__ == string __main__
begin
comment parse parameters
set parser = call ArgumentParser description=string Send API calls to easy_phi web application. Results will be printed to console
call add_argument... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
from rest_client import RestClient
if __name__ == '__main__':
# parse parameters
parser = argparse.ArgumentParser(
description="Send API calls to easy_phi web application. "
"Results will be printed to console")
par... | Python | zaydzuhri_stack_edu_python |
set foodPositive = set literal string food good string food great string food really good string food pretty good string food always good string authentic mexican food string best mexican food string good mexican food string great food string good food string fresh string food amazing string never bad meal string best ... | foodPositive = {
'food good',
'food great',
'food really good',
'food pretty good',
'food always good',
'authentic mexican food',
'best mexican food',
'good mexican food',
'great food',
'good food',
'fresh',
'food amazing',
'never bad meal',
'best chinese food',
... | Python | zaydzuhri_stack_edu_python |
function adc self value
begin
call sendValue string value
end function | def adc(self, value):
self.sendValue(str(value)) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
import SocketServer
import time
import os
import socket
class PARAM
begin
set host = string 0.0.0.0
set port = 9444
set MAX_RECV_SIZE = 8196
set CURRENT_DIR = string fileroot
end class
class MyFtpServer extends BaseRequestHandler
begin
function recvfile self fi... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import SocketServer
import time
import os
import socket
class PARAM:
host = "0.0.0.0"
port = 9444
MAX_RECV_SIZE = 8196
CURRENT_DIR="fileroot"
class MyFtpServer(SocketServer.BaseRequestHandler):
def recvfile(self, filename):
filename=filename... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on 2018/4/18 21:57 @author: dream01
import matplotlib.pyplot as plt
import numpy as np
function get_pictual
begin
string 读取csv文件 :return:
set data_txt = call loadtxt string mydata2.csv dtype=str delimiter=string ,
set data = as type data_txt at tuple slice 1 : : slice : -... | # -*- coding: utf-8 -*-
"""
Created on 2018/4/18 21:57
@author: dream01
"""
import matplotlib.pyplot as plt
import numpy as np
def get_pictual():
"""
读取csv文件
:return:
"""
data_txt = np.loadtxt("mydata2.csv", dtype=np.str, delimiter=",")
data = data_txt[1:, :-1].astype(np.float)
theta = da... | Python | zaydzuhri_stack_edu_python |
import pyglet
from pyglet.gl import *
from ctypes import pointer , sizeof
set window = call Window width=800 height=800
string update function
set c = 0
function update dt
begin
global c
set c = c + 1
set data = call calc_point c
comment if there's only on VBO, you can comment out the 'glBindBuffer' call
call glBindBuf... | import pyglet
from pyglet.gl import *
from ctypes import pointer, sizeof
window = pyglet.window.Window(width=800, height=800)
''' update function '''
c = 0
def update(dt):
global c
c+=1
data = calc_point(c)
# if there's only on VBO, you can comment out the 'glBindBuffer' call
glBindBuffer(GL_ARRA... | Python | zaydzuhri_stack_edu_python |
function getIntersectionNode self headA headB
begin
string :type head1, head1: ListNode :rtype: ListNode
if headA == none or headB == none
begin
return none
end
set tuple curr1 curr2 = tuple headA headB
while curr1 != curr2
begin
if curr1 == none
begin
set curr1 = headB
end
else
begin
set curr1 = next
end
if curr2 == n... | def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
if headA == None or headB == None:
return None
curr1, curr2 = headA, headB
while curr1 != curr2:
if curr1 == None:
curr1 = headB
else:
curr1 = ... | Python | zaydzuhri_stack_edu_python |
function reset_queue self name namespace
begin
raise call NotImplementedError
end function | def reset_queue(self, name, namespace):
raise NotImplementedError() | Python | nomic_cornstack_python_v1 |
function login self email password **kwargs
begin
assert is instance email basestring
assert is instance password basestring
comment Always use a new connection, so it doesn't get invalidated
comment after a while
set conn = call initialize url
call set_option OPT_REFERRALS 0
comment let the connection die reasonably f... | def login(self, email, password, **kwargs):
assert isinstance(email, basestring)
assert isinstance(password, basestring)
# Always use a new connection, so it doesn't get invalidated
# after a while
self.conn = ldap.initialize(self.url)
self.conn.set_option(ldap.OPT_REFER... | Python | nomic_cornstack_python_v1 |
function __init__ __self__ duration=none
begin
if duration is not none
begin
set __self__ string duration duration
end
end function | def __init__(__self__, *,
duration: Optional[pulumi.Input[str]] = None):
if duration is not None:
pulumi.set(__self__, "duration", duration) | Python | nomic_cornstack_python_v1 |
function converterF tempC
begin
return 9 / 5 * tempC + 32
end function
function converterK tempC
begin
return tempC + 273
end function
set temperatura_c = decimal input string Informe um valor de temp:
print string Temp F: call converterF temperatura_c
print string Temp K: call converterK temperatura_c | def converterF(tempC):
return ((9/5)*tempC) + 32
def converterK(tempC):
return tempC + 273
temperatura_c = float(input("Informe um valor de temp:"))
print("Temp F:", converterF(temperatura_c))
print("Temp K:", converterK(temperatura_c))
| Python | zaydzuhri_stack_edu_python |
class Vehicle
begin
set _ACCELERATION = 5
function __init__ self
begin
set _speed = 0
end function
function speed_up self
begin
if _speed + _ACCELERATION <= 240
begin
set _speed = _speed + _ACCELERATION
end
end function
function __str__ self
begin
return format string 현재 속도는 {} 입니다. _speed
end function
end class
class ... | class Vehicle:
_ACCELERATION =5
def __init__(self):
self._speed = 0
def speed_up(self):
if self._speed + self._ACCELERATION <=240:
self._speed +=self._ACCELERATION
def __str__(self):
return "현재 속도는 {} 입니다.".format(self._speed)
class AutonomousVehicle(Vehicle):
de... | Python | zaydzuhri_stack_edu_python |
function addStaticPath self url_prefix os_path
begin
call addStaticPath url_prefix os_path
end function | def addStaticPath(self, url_prefix, os_path):
self.static_handler.addStaticPath(url_prefix, os_path) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
comment -*- coding: utf-8 -*-
string # add the 16 types of plots you have scripted for in here -- Functions for plotting with Matplotlib and Seaborn packages, in relation to the GEOS-Chem chemical transport model (CTM). NOTE(S): - This module is just beginning to be developed, these are being m... | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
# add the 16 types of plots you have scripted for in here --
Functions for plotting with Matplotlib and Seaborn packages, in relation to the GEOS-Chem chemical transport model (CTM).
NOTE(S):
- This module is just beginning to be developed, these are being moved across... | Python | zaydzuhri_stack_edu_python |
set x = string Guru
print x at slice 1 : 3 : | x="Guru"
print (x[1:3]) | Python | zaydzuhri_stack_edu_python |
function isValidDate self dateStr
begin
set date = string parse time dateStr string %d/%m/%y
if length resultList == 0
begin
return false
end
else
begin
set prevDate = dateList at - 1
if date < prevDate
begin
return false
end
else
begin
set weekday = call weekday
set prevWeekday = call weekday
set daysAhead = days
if w... | def isValidDate(self, dateStr):
date = datetime.datetime.strptime(dateStr, '%d/%m/%y')
if len(self.resultList) == 0:
return False
else:
prevDate = self.dateList[-1]
if date < prevDate :
return False
else:
weekday = date.weekday()
prevWeekday = prevDate.weekday()
daysAhead = (date - pre... | Python | nomic_cornstack_python_v1 |
comment url: https://note.nkmk.me/python-union-find/ より
comment n個の要素を0~N-1で管理
class UnionFind
begin
comment 各要素の親要素の番号を格納するリスト
comment 要素が根(ルート)の場合は-(そのグループの要素数)を格納する
function __init__ self n
begin
set n = n
set parents = list - 1 * n
end function
comment 要素xが属するグループの根を返す
function find self x
begin
if parents at x < 0... | # url: https://note.nkmk.me/python-union-find/ より
# n個の要素を0~N-1で管理
class UnionFind:
# 各要素の親要素の番号を格納するリスト
# 要素が根(ルート)の場合は-(そのグループの要素数)を格納する
def __init__(self, n):
self.n = n
self.parents = [-1] * n
# 要素xが属するグループの根を返す
def find(self, x):
if self.parents[x] < 0:
ret... | Python | zaydzuhri_stack_edu_python |
comment if n % 2 == 0:
comment print("median:", (scr_lst[(n // 2) - 1] + scr_lst[(n // 2)]) / 2)
comment else:
comment p = math.floor(n / 2)
comment print("median:", scr_lst[p])
import numpy as np
import pandas as pd
import math
function cal_med num
begin
print num
set n = length num
if n % 2 == 0
begin
return integer ... | # if n % 2 == 0:
# print("median:", (scr_lst[(n // 2) - 1] + scr_lst[(n // 2)]) / 2)
# else:
# p = math.floor(n / 2)
# print("median:", scr_lst[p])
import numpy as np
import pandas as pd
import math
def cal_med(num):
print(num)
n = len(num)
if n % 2 == 0:
return (int(nu... | Python | zaydzuhri_stack_edu_python |
comment ! /usr/bin/python
import numpy as np
class Voxel
begin
set Red = 0.0
set Green = 0.0
set Blue = 0.0
set lightray = none
end class
comment scene1 = np.empty([200,200]);
comment scene2 = np.empty([200,200]);
comment scene1 = [[0]*200 for j in range[200]]
set scene1 = dict
comment scene2 = [[0 for i in range(200)... | #! /usr/bin/python
import numpy as np
class Voxel:
Red = 0.0
Green = 0.0
Blue = 0.0
lightray = None
#scene1 = np.empty([200,200]);
#scene2 = np.empty([200,200]);
#scene1 = [[0]*200 for j in range[200]]
scene1 = {}
#scene2 = [[0 for i in range(200)] for j in range[200]]
scene2 = {}
for i in range(0,200... | Python | zaydzuhri_stack_edu_python |
function roadsBuilding cities roads
begin
if cities == 1
begin
return list
end
set result = list
for i in range 0 cities
begin
for j in range i + 1 cities
begin
if i != j
begin
if list i j not in roads and list j i not in roads
begin
append result list i j
append roads list j i
append roads list i j
end
end
end
end
r... | def roadsBuilding(cities, roads):
if cities == 1:
return []
result = []
for i in range(0, cities):
for j in range(i+1, cities):
if i != j:
if [i, j] not in roads and [j,i] not in roads:
result.append([i,j])
roads.append... | Python | zaydzuhri_stack_edu_python |
string fps_test1.py
import sys
import pygame
from pygame.locals import QUIT
import timeit
call init
set SURFACE = call set_mode tuple 400 300
function main
begin
string main routine
set sysfont = call SysFont none 36
set counter = 0
set time_ellapsed = 0
set fps = 0
while true
begin
set start = call default_timer
for e... | """ fps_test1.py """
import sys
import pygame
from pygame.locals import QUIT
import timeit
pygame.init()
SURFACE = pygame.display.set_mode((400, 300))
def main():
""" main routine """
sysfont = pygame.font.SysFont(None, 36)
counter = 0
time_ellapsed = 0
fps = 0
while True:
start = time... | Python | zaydzuhri_stack_edu_python |
function get_y_range self min_ix=none max_ix=none
begin
set min_ix = if expression min_ix is none then 0 else min_ix
set max_ix = if expression max_ix is none then last_ix else max_ix
set min_v = inf
set max_v = - inf
if not empty
begin
set min_v = min min_v min
set max_v = max max_v max
end
return tuple min_v max_v
en... | def get_y_range(self, min_ix: int = None, max_ix: int = None) -> Tuple[float, float]:
min_ix = 0 if min_ix is None else min_ix
max_ix = self.last_ix if max_ix is None else max_ix
min_v = np.inf
max_v = -np.inf
if not self.records_df.empty:
min_v = min(min_v, self.re... | Python | nomic_cornstack_python_v1 |
from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt
from math import sqrt
from frmPythagoras import Ui_frmMain
class Pythagoras extends QDialog Ui_frmMain
begin
function __init__ self
begin
string CTor
call __init__
call setupUi self
comment Disable the maximize button
call setWindowFlags call windowFlags ? Customi... | from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt
from math import sqrt
from frmPythagoras import Ui_frmMain
class Pythagoras(QtWidgets.QDialog, Ui_frmMain):
def __init__(self):
"""
CTor
"""
super(Pythagoras, self).__init__()
self.setupUi(self)
# Disable the m... | Python | zaydzuhri_stack_edu_python |
function _get_ml_task self
begin
call _validate_ml_task
if ml_task == string auto
begin
set classes_number = n_classes
if classes_number == 2
begin
comment for sk-learn api
set _estimator_type = string classifier
return BINARY_CLASSIFICATION
end
else
if classes_number <= 20
begin
comment for sk-learn api
set _estimator... | def _get_ml_task(self):
self._validate_ml_task()
if self.ml_task == "auto":
classes_number = self.n_classes
if classes_number == 2:
self._estimator_type = "classifier" # for sk-learn api
return BINARY_CLASSIFICATION
elif classes_number... | Python | nomic_cornstack_python_v1 |
import random
set list1 = list string abcd sdasdsn das das string bcdefsdf dfjds fksdjf string c sdfdsfsd string d dsds string b string c string d string x string e string z
print list1
shuffle random list1
print list1
print integer 0.9 * length list1
set list2 = list1 at slice : integer 0.9 * length list1 :
set list... | import random
list1 = ['abcd sdasdsn das das','bcdefsdf dfjds fksdjf ','c sdfdsfsd','d dsds ','b','c','d','x','e','z']
print(list1)
random.shuffle(list1)
print(list1)
print((int)(0.9*len(list1)))
list2 = list1[:(int)(0.9*len(list1))]
list3 = list1[(int)(0.9*len(list1)):]
print(list2)
print(list3)
| Python | zaydzuhri_stack_edu_python |
from games import Game , Hex
import numpy as np
class StateManager
begin
string Manages states of games and moving between them. Can be subclassed to be adapted to any game
function __init__ self game
begin
set game = game
set init_state = none
set rollout_mode = false
set pre_rollout_state = none
set current_player = ... | from games import Game, Hex
import numpy as np
class StateManager:
"""
Manages states of games and moving between them.
Can be subclassed to be adapted to any game
"""
def __init__(self, game : Game):
self.game = game
self.init_state = None
self.rollout_mode = False
... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
comment Load and preprocess the data
set df = read csv string house_data.csv
set X = df at list string sqft string rooms string loc
set y = df at string price
comment Split the d... | import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
# Load and preprocess the data
df = pd.read_csv('house_data.csv')
X = df[['sqft', 'rooms', 'loc']]
y = df['price']
# Split the data into train and test sets
X_train, X_test... | Python | flytech_python_25k |
comment !/usr/bin/env python
comment encoding=utf-8
import telegram
import os
from model.division_state_cars import DivisionStateCars
import datetime
from dateutil.parser import parse
from string import Template
class DeltaTemplate extends Template
begin
set delimiter = string %
end class
function strfdelta tdelta fmt
... | #!/usr/bin/env python
# encoding=utf-8
import telegram
import os
from model.division_state_cars import DivisionStateCars
import datetime
from dateutil.parser import parse
from string import Template
class DeltaTemplate(Template):
delimiter = "%"
def strfdelta(tdelta, fmt):
d = {"D": tdelta.days}
d["H"]... | Python | zaydzuhri_stack_edu_python |
function translate self v
begin
return call fromnp call translate call tonp v
end function | def translate(self, v):
return Position.fromnp(translate(self.tonp(), v)) | Python | nomic_cornstack_python_v1 |
for i in range 5
begin
for j in range 5
begin
if i + j == 4
begin
print string * end=string
end
else
if i == 0 and j in list 0 1 2 3 4
begin
print string * end=string
end
else
if i == 5 and j in list 0 1 2 3 4
begin
print string * end=string
end
else
begin
print string end=string
end
end
print
end | for i in range(5):
for j in range(5):
if(i+j==4):
print("*",end=" ")
elif(i==0 and (j in [0,1,2,3,4])):
print("*",end=" ")
elif(i==5 and (j in [0,1,2,3,4])):
print("*",end=" ")
else:
print(" ",end = " ")
print()
| Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
from scrapy.item import Field
from scrapy.item import Item
from scrapy.spiders import Spider
from scrapy.selector import Selector
from scrapy.contrib.loader import ItemLoader
comment from bs4 import BeautifulSoup
comment from selenium import webdriver
import re
from odepa_srv.items import ... | # -*- coding: utf-8 -*-
from scrapy.item import Field
from scrapy.item import Item
from scrapy.spiders import Spider
from scrapy.selector import Selector
from scrapy.contrib.loader import ItemLoader
#from bs4 import BeautifulSoup
#from selenium import webdriver
import re
from odepa_srv.items import *
#Página : http://... | Python | zaydzuhri_stack_edu_python |
string Module for converting xarray datasets to and from matrix formats for Machine learning purposes.
import numpy as np
import pandas as pd
import xarray as xr
import pytest
from datasets import tiltwave
from data_matrix import DataMatrix , Normalizer , dataset_to_mat , compute_weighted_scale , stack_cat , unstack_ca... | """Module for converting xarray datasets to and from matrix formats for Machine
learning purposes.
"""
import numpy as np
import pandas as pd
import xarray as xr
import pytest
from .datasets import tiltwave
from .data_matrix import (DataMatrix, Normalizer, dataset_to_mat, compute_weighted_scale,
... | Python | zaydzuhri_stack_edu_python |
function d value
begin
if value < 1
begin
return 0
end
else
begin
return value
end
end function | def d(value):
if value < 1:
return 0
else:
return value | Python | nomic_cornstack_python_v1 |
function delete_backup_vault BackupVaultName=none
begin
pass
end function | def delete_backup_vault(BackupVaultName=None):
pass | Python | nomic_cornstack_python_v1 |
import re
from ch3_module import ch3_extract_json
set lines = split call extract_json string イギリス string
for line in lines
begin
set section_line = search string ^(=+)\s*(.*?)\s*(=+)$ line
if section_line is not none
begin
print call group 2
end
end | import re
from ch3_module import ch3_extract_json
lines = ch3_extract_json.extract_json('イギリス').split('\n')
for line in lines:
section_line = re.search("^(=+)\s*(.*?)\s*(=+)$", line)
if section_line is not None:
print(section_line.group(2))
| Python | zaydzuhri_stack_edu_python |
function max_score self
begin
set max_score = none
if call check_if_done_and_scored
begin
set max_score = _max_score
end
return max_score
end function | def max_score(self):
max_score = None
if self.check_if_done_and_scored():
max_score = self._max_score
return max_score | Python | nomic_cornstack_python_v1 |
comment https://leetcode.com/problems/most-common-word/description/
from collections import Counter
class Solution
begin
function mostCommonWord self paragraph banned
begin
string :type paragraph: str :type banned: List[str] :rtype: str
set count = counter generator expression piece for piece in split re string [ !?',;... | # https://leetcode.com/problems/most-common-word/description/
from collections import Counter
class Solution:
def mostCommonWord(self, paragraph, banned):
"""
:type paragraph: str
:type banned: List[str]
:rtype: str
"""
count=collections.Counter(piece for piece in re.... | Python | zaydzuhri_stack_edu_python |
comment lista = []
comment maior = menor = 0
comment for i in range(1, 6):
comment numero = int(input('Digite um número: '))
comment if i == 1:
comment lista.append(numero)
comment print('Número adicionado no final da lista')
comment else:
comment for i in range(0, len(lista) + 1):
comment if i == 0:
comment maior = nu... | # lista = []
# maior = menor = 0
# for i in range(1, 6):
# numero = int(input('Digite um número: '))
# if i == 1:
# lista.append(numero)
# print('Número adicionado no final da lista')
# else:
# for i in range(0, len(lista) + 1):
# if i == 0:
# ma... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment -*- coding: utf-8 -*-
comment import os
comment import subprocess
function fdf_txt_object field_name field_value
begin
set fdf_obj = string <</T( + string field_name + string )/V( + string field_value + string )>>
return fdf_obj
end function
comment filename = "output.pdf"
comment filen... | #!/usr/bin/python
# -*- coding: utf-8 -*-
#import os
#import subprocess
def fdf_txt_object(field_name, field_value):
fdf_obj = "<</T("+str(field_name)+")/V("+str(field_value)+")>>"
return fdf_obj
#filename = "output.pdf"
#filename should be the same as the pdf you are going to merge the data with
def fdf_make(fil... | Python | zaydzuhri_stack_edu_python |
function squareEach nums
begin
for i in range length nums
begin
set nums at i = nums at i * nums at i
end
end function
function main
begin
comment Testing
set list_of_lists = list list list 2 list 1 2 4 10 list - 1 - 6 1 6 list 1.1 2.2
for lst in list_of_lists
begin
call squareEach lst
print lst
end
end function
call ... | def squareEach(nums):
for i in range(len(nums)):
nums[i] = nums[i] * nums[i]
def main():
# Testing
list_of_lists = [[], [2], [1,2,4,10], [-1,-6,1,6], [1.1,2.2]]
for lst in list_of_lists:
squareEach(lst)
print(lst)
main()
| Python | zaydzuhri_stack_edu_python |
function _sortChunk records key chunkIndex fields
begin
string Sort in memory chunk of records records - a list of records read from the original dataset key - a list of indices to sort the records by chunkIndex - the index of the current chunk The records contain only the fields requested by the user. _sortChunk() wil... | def _sortChunk(records, key, chunkIndex, fields):
"""Sort in memory chunk of records
records - a list of records read from the original dataset
key - a list of indices to sort the records by
chunkIndex - the index of the current chunk
The records contain only the fields requested by the user.
_sortChunk(... | Python | jtatman_500k |
function force_delete_bucket conn bucket_name
begin
set marker = none
set keep_deleting = true
while keep_deleting
begin
set kwargs = dict
comment botocore won't let us include this if it's ``None``.
if marker is not none
begin
set kwargs at string marker = marker
end
set resp = call list_objects bucket=bucket_name ke... | def force_delete_bucket(conn, bucket_name):
marker = None
keep_deleting = True
while keep_deleting:
kwargs = {}
# botocore won't let us include this if it's ``None``.
if marker is not None:
kwargs['marker'] = marker
resp = conn.list_objects(
... | Python | nomic_cornstack_python_v1 |
import pygame
import datetime
call init
call init
set myfont = call SysFont string monospace 60
set size = tuple 600 300
set screen = call set_mode size
set bgcolor = tuple 255 255 255
call set_caption string clock
set done = false
while done == false
begin
call fill bgcolor
comment Listens for pygame events such as mo... | import pygame
import datetime
pygame.init()
pygame.font.init()
myfont = pygame.font.SysFont("monospace", 60)
size = (600,300)
screen = pygame.display.set_mode(size)
bgcolor = (255,255,255)
pygame.display.set_caption("clock")
done = False
while done == False:
screen.fill(bgcolor)
# Listens for py... | Python | zaydzuhri_stack_edu_python |
function shape_of_variables fgraph input_shapes
begin
if not has attribute fgraph string shape_feature
begin
call attach_feature call ShapeFeature
end
set input_dims = list comprehension dimension for inp in inputs for dimension in shape_of at inp
set output_dims = list comprehension dimension for shape in values shape... | def shape_of_variables(fgraph, input_shapes):
if not hasattr(fgraph, 'shape_feature'):
fgraph.attach_feature(theano.tensor.opt.ShapeFeature())
input_dims = [dimension for inp in fgraph.inputs
for dimension in fgraph.shape_feature.shape_of[inp]]
output_dims = ... | Python | nomic_cornstack_python_v1 |
function checkValidityOfMove self move
begin
return move in call getValidMovesMasked list at 0
end function | def checkValidityOfMove(self, move):
return move in self.getValidMovesMasked([])[0] | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Thu Aug 3 17:40:23 2017 @author: Weikang_Wan
set balance = 42
set annualInterestRate = 0.2
set monthlyPaymentRate = 0.04
for i in range 12
begin
set balance = balance + annualInterestRate / 12 * balance
set balance = balance * 1 - monthlyPaym... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 3 17:40:23 2017
@author: Weikang_Wan
"""
balance = 42
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
for i in range(12):
balance = balance + annualInterestRate/12*balance
balance = balance*(1- monthlyPaymentRate)
print('Remaining ba... | Python | zaydzuhri_stack_edu_python |
function forward self x
begin
set pool_2_out = call pool_2 x
set pool_3_out = call pool_3 pool_2_out
set conv_4_out = call conv_4 pool_3_out
set conv_5_out = call conv_5 conv_4_out
set pool_2_out = call skip_pool_2 pool_2_out
set pool_3_out = call skip_pool_3 pool_3_out
set conv_4_out = call skip_conv_4 conv_4_out
set ... | def forward(self, x):
pool_2_out = self.pool_2(x)
pool_3_out = self.pool_3(pool_2_out)
conv_4_out = self.conv_4(pool_3_out)
conv_5_out = self.conv_5(conv_4_out)
pool_2_out = self.skip_pool_2(pool_2_out)
pool_3_out = self.skip_pool_3(pool_3_out)
conv_4_out = self... | Python | nomic_cornstack_python_v1 |
import cv2
import numpy as np
comment funtion to apply eclipse kernel for an image
function multiply_kernel matrix row col
begin
set matrix at tuple row col = 255
if row - 1 >= 0
begin
set matrix at tuple row - 1 col = 255
end
if row + 1 < shape at 0
begin
set matrix at tuple row + 1 col = 255
end
if col - 1 >= 0
begin... | import cv2
import numpy as np
# funtion to apply eclipse kernel for an image
def multiply_kernel(matrix, row, col):
matrix[row,col] = 255
if row-1 >=0:
matrix[row-1, col]=255
if row+1 < matrix.shape[0] :
matrix[row+1,col] = 255
if col-1 >= 0:
matrix[row,col-1] = 255
if co... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
string
from ILAMB.ModelResult import ModelResult
from ILAMB.Scoreboard import Scoreboard
from ILAMB.Regions import Regions
from ILAMB import ilamblib as il
import os , time , sys , argparse
import numpy as np
import datetime , glob
comment Some color constants for printing to the terminal
... | #!/usr/bin/env python
"""
"""
from ILAMB.ModelResult import ModelResult
from ILAMB.Scoreboard import Scoreboard
from ILAMB.Regions import Regions
from ILAMB import ilamblib as il
import os,time,sys,argparse
import numpy as np
import datetime,glob
# Some color constants for printing to the terminal
OK = '\033[92m'
FA... | Python | zaydzuhri_stack_edu_python |
function importCourses path=string classes.csv delimit=string , datatype=string str header=1
begin
comment Generate an array from the input file of course details
set courses = call genfromtxt path delimiter=delimit dtype=datatype skip_header=header
comment Prepare a list of courses to return
set courseList = list
com... | def importCourses(path='classes.csv', delimit=',', datatype='str', header=1):
# Generate an array from the input file of course details
courses = N.genfromtxt(path, delimiter=delimit, dtype=datatype, skip_header=header)
# Prepare a list of courses to return
courseList = []
# Iterate t... | Python | nomic_cornstack_python_v1 |
function set_fast_diacritic_sensitive_searches self enabled=true
begin
call validate_boolean enabled
set _config at string fast-diacritic-sensitive-searches = enabled
return self
end function | def set_fast_diacritic_sensitive_searches(self, enabled=True):
validate_boolean(enabled)
self._config['fast-diacritic-sensitive-searches'] = enabled
return self | Python | nomic_cornstack_python_v1 |
function create_predict_keys db predict_file
begin
set tsv = call SimpleTsv predict_file
with open predict_file as fp ; open predict_file + string .keys string w as kfp
begin
for offset in call offsets
begin
set cols = call tsv_read fp 1 seek_offset=offset
set uid = call uid_of_image_key cols at 0
write kfp format stri... | def create_predict_keys(db, predict_file):
tsv = SimpleTsv(predict_file)
with open(predict_file) as fp, open(predict_file + ".keys", "w") as kfp:
for offset in tsv.offsets():
cols = tsv_read(fp, 1, seek_offset=offset)
uid = db.uid_of_image_key(cols[0])
kfp.write("{}\t... | Python | nomic_cornstack_python_v1 |
string Instructions for programming Exercise 5.9 In Case Study: Nondirective Psychotherapy, when the patient addresses the therapist personally, the therapist’s reply does not change persons appropriately. To see an example of this problem, test the program with “you are not a helpful therapist.” Fix this problem by re... | """
Instructions for programming Exercise 5.9
In Case Study: Nondirective Psychotherapy, when the patient addresses the
therapist personally, the therapist’s reply does not change persons
appropriately. To see an example of this problem, test the program with “you are
not a helpful therapist.” Fix this problem by repa... | Python | zaydzuhri_stack_edu_python |
function from_date cls date_obj
begin
set year = none
if length string year == 2
begin
if year <= 17
begin
set year = year + 2000
end
else
begin
set year = year + 1900
end
end
else
begin
set year = year
end
set date_string = format string {0}, {1} {2}, {3} at 12:00am PDT WEEK_INDEXES_TO_DAY_OF_WEEK at call weekday MONT... | def from_date(cls, date_obj: date):
year = None
if len(str(date_obj.year)) == 2:
if date_obj.year <= 17:
year = date_obj.year + 2000
else:
year = date_obj.year + 1900
else:
year = date_obj.year
date_string = "{0}, {1} {2... | Python | nomic_cornstack_python_v1 |
function prepare_dataset frac_training=0.5 use_sentiment=true
begin
set d2 = call read_pickle string complete_dataset.pickle
comment df2 = pd.read_pickle('all_tickers_combined.pickle')
comment df2a = df2.loc[:,['ticker_price_beginning', 'ticker_price_end', 'mkt_price_beginning','mkt_price_end','Sentiment']]
set df11_al... | def prepare_dataset(frac_training=0.5, use_sentiment=True):
d2 = pd.read_pickle('complete_dataset.pickle')
#df2 = pd.read_pickle('all_tickers_combined.pickle')
#df2a = df2.loc[:,['ticker_price_beginning', 'ticker_price_end', 'mkt_price_beginning','mkt_price_end','Sentiment']]
df11_all = pd.read_pickle(... | Python | nomic_cornstack_python_v1 |
function write self
begin
write nxlink
if not infile
begin
with nxlink as path
begin
set target = call getgroupID
end
with nxgroup as path
begin
call makelink target
end
set _infile = true
set _saved = true
end
end function | def write(self):
self.nxlink.write()
if not self.infile:
with self.nxlink as path:
target = path.getgroupID()
with self.nxgroup as path:
path.makelink(target)
self._infile = self._saved = True | 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.