code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function convertToGray img
begin
set gray_img = call cvtColor img COLOR_BGR2GRAY
return gray_img
end function | def convertToGray(img):
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
return gray_img | Python | nomic_cornstack_python_v1 |
function notify_participant_event_waitlist request user event
begin
comment Send email to the participant to confirm their that their registration request was received
set subject = string { SITE_NAME } Event Registration
set context = dict string name call get_full_name ; string domain call get_current_site request ; ... | def notify_participant_event_waitlist(request, user, event):
# Send email to the participant to confirm their that their registration request was received
subject = f"{settings.SITE_NAME} Event Registration"
context = {
'name': user.get_full_name(),
'domain': get_current_site(request),
... | Python | nomic_cornstack_python_v1 |
function add_layer self layer
begin
append _layers layer
end function | def add_layer(self, layer):
self._layers.append(layer) | Python | nomic_cornstack_python_v1 |
function loadUpdate file
begin
set up_data = dict string url list ; string num list ; string street list ; string suburb list
with open file as fstrm
begin
set data = reader fstrm
set vals = list data
end
comment url | street_num | road_name | suburb
set val_ind = list
if string url in vals at 0
begin
append val_i... | def loadUpdate(file):
up_data = {
'url' : [],
'num' : [],
'street' : [],
'suburb' : []
}
with open(file) as fstrm:
data = csv.reader(fstrm)
vals = list(data)
val_ind = [] #url | street_num | road_name | suburb
if 'url' in vals[0]:
val_ind.appe... | Python | nomic_cornstack_python_v1 |
for i in range num
begin
set fact = fact * i + 1
end
print fact | for i in range(num):
fact *= i + 1
print(fact) | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Wed Jan 24 21:02:34 2018 @author: YudongCai @Email: yudongcai216@gmail.com
import sys
import click
import numpy as np
import matplotlib
call use string Agg
import matplotlib.pyplot as plt
import pysam
function get_ref_len alnfile contig
begin
for tuple n seqinfo in enumer... | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 24 21:02:34 2018
@author: YudongCai
@Email: yudongcai216@gmail.com
"""
import sys
import click
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import pysam
def get_ref_len(alnfile, contig):
for n, seqinfo in enumerate(al... | Python | zaydzuhri_stack_edu_python |
function load_data self features=none labels=none
begin
if features is none or labels is none
begin
set _features = none
set _labels = none
return
end
if length features != length labels
begin
raise call DataMismatchError string Features and labels lists are different lengths
end
try
begin
set _features = array feature... | def load_data(self, features=None, labels=None):
if features is None or labels is None:
self._features = None
self._labels = None
return
if len(features) != len(labels):
raise DataMismatchError('Features and labels lists are different lengths')
try... | Python | nomic_cornstack_python_v1 |
import random
import time
import math
comment This function receives number of email entries we want and create those entries
comment and returns a list with emails , half of which are duplicate.
comment If given number//2 does not give perfect square root then it would give a little more entries than desired entries.
... | import random
import time
import math
# This function receives number of email entries we want and create those entries
# and returns a list with emails , half of which are duplicate.
# If given number//2 does not give perfect square root then it would give a little more entries than desired entries.
# This is made g... | Python | zaydzuhri_stack_edu_python |
function Bidirection self
begin
if force_auto_sync
begin
get self string Bidirection
end
return _Bidirection
end function | def Bidirection(self):
if self.force_auto_sync:
self.get('Bidirection')
return self._Bidirection | Python | nomic_cornstack_python_v1 |
function filterBam inf outf params
begin
set tuple infile outfile = params
set samfile = call Samfile infile string rb
set mappedreads = call Samfile outfile string wb template=samfile
for read in call fetch
begin
if is_unmapped
begin
continue
end
else
if is_secondary
begin
continue
end
else
begin
write mappedreads rea... | def filterBam( inf, outf, params ):
infile, outfile = params
samfile = pysam.Samfile( infile, "rb" )
mappedreads = pysam.Samfile( outfile, "wb", template=samfile )
for read in samfile.fetch():
if read.is_unmapped:
continue
elif read.is_secondary:
continue
... | Python | nomic_cornstack_python_v1 |
string Classes and methods related to the :class:`.DTMModelManager`\.
import os
import re
import shutil
import tempfile
import subprocess
import numpy as np
from networkx import Graph
import logging
call basicConfig
set logger = call getLogger __name__
call setLevel string ERROR
from classes import GraphCollection
from... | """
Classes and methods related to the :class:`.DTMModelManager`\.
"""
import os
import re
import shutil
import tempfile
import subprocess
import numpy as np
from networkx import Graph
import logging
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel('ERROR')
from ...classes import GraphColl... | Python | zaydzuhri_stack_edu_python |
function initialized self
begin
return repo_is_initialized
end function | def initialized(self) -> bool:
return self._env.repo_is_initialized | Python | nomic_cornstack_python_v1 |
import copy
import random
comment Consider using the modules imported above.
class Hat
begin
function __init__ self **kwargs
begin
set contents = list
for tuple key value in items kwargs
begin
for i in range value
begin
append contents key
end
end
end function
function draw self number
begin
if number > length content... | import copy
import random
# Consider using the modules imported above.
class Hat():
def __init__(self, **kwargs):
self.contents = []
for key, value in kwargs.items():
for i in range(value):
self.contents.append(key)
def draw(self, number):
if number > len(se... | Python | zaydzuhri_stack_edu_python |
function reverse_words sentence
begin
set vowels = string aeiouAEIOU
set words = split sentence
set reversed_words = list
for word in words
begin
if any generator expression char in vowels for char in word
begin
append reversed_words word at slice : : - 1
end
else
begin
append reversed_words word
end
end
return join... | def reverse_words(sentence):
vowels = "aeiouAEIOU"
words = sentence.split()
reversed_words = []
for word in words:
if any(char in vowels for char in word):
reversed_words.append(word[::-1])
else:
reversed_words.append(word)
return ' '.join(reversed_w... | Python | jtatman_500k |
string Project Euler Problem 3: The prime factors of 13195 are 5,7,13,and 29 What is the largest prime factor of! 600851475143?
comment Main.. | '''
Project Euler Problem 3:
The prime factors of 13195 are 5,7,13,and 29
What is the largest prime factor of! 600851475143?
'''
# Main.. | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
import tkinter
function vcmd *args
begin
print string vcmd( args string )
comment print spinbox.cget("validate")
print get text
return true
end function
set root = call Tk
set text = call StringVar
call trace string w vcmd
set spinbox = call Scale root from_=5 to=150 command=vcmd orient=HORIZON... | #!/usr/bin/python
import tkinter
def vcmd(*args):
print("vcmd(", args, ")")
#print spinbox.cget("validate")
print(text.get())
return True
root = tkinter.Tk()
text = tkinter.StringVar()
text.trace('w', vcmd)
spinbox = tkinter.Scale(root, from_= 5, to=150, command=vcmd, orient=tkinter.HORIZONTAL)
spinb... | Python | zaydzuhri_stack_edu_python |
function playbook self
begin
return playbook
end function | def playbook(self) -> 'Playbook':
return self.app.playbook | Python | nomic_cornstack_python_v1 |
function amount self
begin
if output is none
begin
raise call ValueError string Cannot get input value without referenced output.
end
return amount
end function | def amount(self):
if self.output is None:
raise ValueError('Cannot get input value without referenced output.')
return self.output.amount | Python | nomic_cornstack_python_v1 |
function _get_nb_pages self
begin
string Compute the number of pages in the document. It basically counts how many JPG files there are in the document.
try
begin
set filelist = list directory path
set count = 0
for filepath in filelist
begin
set filename = base name fs filepath
if lower filename at slice - 4 : : != st... | def _get_nb_pages(self):
"""
Compute the number of pages in the document. It basically counts
how many JPG files there are in the document.
"""
try:
filelist = self.fs.listdir(self.path)
count = 0
for filepath in filelist:
filen... | Python | jtatman_500k |
comment 从这个封装里导入神经网络这个类
from sklearn.neural_network import MLPClassifier
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
import matplotlib.pyplot as plt
set digits = call load_digits
set x_data = data
set y_data = target
pri... | from sklearn.neural_network import MLPClassifier #从这个封装里导入神经网络这个类
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
import matplotlib.pyplot as plt
digits = load_digits()
x_data = digits.data
y_data = digits.target
print(x_... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
comment @Author : guowr
comment @Time : 2019/9/6 0:25
from tkinter import *
import subprocess
import threading
import time
import re
function btn_click
begin
delete 0.0 END
insert text INSERT string IP地址状态!
set i = 0
set j = 1
set thread_id = list
set ip = integer get ipText
set v = gener... | # -*- coding: utf-8 -*-
# @Author : guowr
# @Time : 2019/9/6 0:25
from tkinter import *
import subprocess
import threading
import time
import re
def btn_click():
text.delete(0.0, END)
text.insert(INSERT, ("IP地址状态!\n"))
i = 0
j = 1
thread_id = []
ip = int(ipText.get())
... | Python | zaydzuhri_stack_edu_python |
from celery.utils.log import get_task_logger
import time
from backend_2.celery_config import celery_app
set logger = call get_task_logger __name__
comment acks_late=True
try
begin
import pika
end
except Exception as e
begin
print call format_map e
end
class MetaClass extends type
begin
set _instance = dict
function __... | from celery.utils.log import get_task_logger
import time
from backend_2.celery_config import celery_app
logger = get_task_logger(__name__)
#acks_late=True
try:
import pika
except Exception as e:
print("Sone Modules are missings {}".format_map(e))
class MetaClass(type):
_instance ={}
def __call__(cl... | Python | zaydzuhri_stack_edu_python |
function run_info self
begin
return string MPI: %d, OMP: %d % tuple mpi_procs omp_threads
end function | def run_info(self):
return "MPI: %d, OMP: %d" % (self.mpi_procs, self.omp_threads) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
set x = integer input
set ans = x
set ans2 = 0
print
for i in range 1 1000
begin
set temp = ans * i
if temp % 360 == 0
begin
set ans2 = i
break
end
end
print ans2 | # -*- coding: utf-8 -*-
x = int(input())
ans = x
ans2 = 0
print
for i in range(1, 1000):
temp = ans * i
if temp % 360 == 0:
ans2 = i
break
print(ans2)
| Python | zaydzuhri_stack_edu_python |
function available_versions appname
begin
set s = call Shell
set tmp = named temporary file suffix=string .log
set command = string SetupProject.sh --ask %s % appname
set tuple rc output m = call cmd1 string echo 'q ' | %s >& %s; echo % tuple command name
set output = read tmp
close tmp
set versions = split output at s... | def available_versions(appname):
s = Shell()
tmp = tempfile.NamedTemporaryFile(suffix='.log')
command = 'SetupProject.sh --ask %s' % appname
rc,output,m=s.cmd1("echo 'q\n' | %s >& %s; echo" % (command,tmp.name))
output = tmp.read()
tmp.close()
versions = output[output.rfind('(')+1:output.rfind('q[uit]'... | Python | nomic_cornstack_python_v1 |
comment sends a text when a website's content changes.
from bs4 import BeautifulSoup
from urllib.request import urlopen
from lxml.html.clean import clean_html
import lxml
import time
from twilio.rest import TwilioRestClient
set sensitive_list = list
set sensitive = open string sun-sensitive string r
for line in sensit... | # sends a text when a website's content changes.
from bs4 import BeautifulSoup
from urllib.request import urlopen
from lxml.html.clean import clean_html
import lxml
import time
from twilio.rest import TwilioRestClient
sensitive_list = []
sensitive = open('sun-sensitive', 'r')
for line in sensitive:
sensitive_list.app... | Python | zaydzuhri_stack_edu_python |
function f_extract_ene index_homo_line line_ene_ab
begin
comment 2d means alpha, beta
if length index_homo_line == 1
begin
set beta = 0
end
else
begin
set beta = 1
end
comment print len(index_homo_line), len(line_ene_ab)
set f_imo_line2d = list
set iab = 0
comment 2D variables are here
comment 2d for [[alpha], [beta]]... | def f_extract_ene(index_homo_line, line_ene_ab):
#### 2d means alpha, beta
if len(index_homo_line) == 1:
beta = 0
else:
beta = 1
#print len(index_homo_line), len(line_ene_ab)
f_imo_line2d=[]
iab=0
### 2D variables are here
list_ene_ab=[] # 2d for [[alpha], [beta]]
... | Python | nomic_cornstack_python_v1 |
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChai... | from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChai... | Python | zaydzuhri_stack_edu_python |
string Trains an agent with (stochastic) Policy Gradients on Pong. Uses OpenAI Gym.
import numpy as np
import gym
import os
import time
import keras
from keras.layers import Conv2D , Dense , Flatten , Input
from keras.models import Model
from keras.optimizers import RMSprop
from keras.models import load_model
from kera... | """ Trains an agent with (stochastic) Policy Gradients on Pong. Uses OpenAI Gym. """
import numpy as np
import gym
import os
import time
import keras
from keras.layers import Conv2D, Dense, Flatten, Input
from keras.models import Model
from keras.optimizers import RMSprop
from keras.models import load_model
from keras.... | Python | zaydzuhri_stack_edu_python |
function test_chunkedhdf5_chunks_property_directory_root chunked_hdf5_data chunk_config
begin
set dataset = call ChunkedHDF5Dataset chunked_hdf5_data
assert chunks == tuple sorted call iterdir
assert chunk_sizes == tuple list 1 * num_chunks
end function | def test_chunkedhdf5_chunks_property_directory_root(
chunked_hdf5_data: Path, chunk_config: ChunkedDataConfig
) -> None:
dataset = ChunkedHDF5Dataset(chunked_hdf5_data)
assert dataset.chunks == tuple(sorted(chunked_hdf5_data.iterdir()))
assert dataset.chunk_sizes == tuple([1] * chunk_config.num_chunks) | Python | nomic_cornstack_python_v1 |
import boto3
import csv
import os
import datetime
function file_validator all_file_data first_row file_name_local file_name_aws s3 bucketName
begin
for data in all_file_data
begin
if length first_row == length data
begin
print string data is matched with header
set date_time_index = index first_row string Date&Time
pri... | import boto3
import csv
import os
import datetime
def file_validator(all_file_data, first_row, file_name_local, file_name_aws, s3, bucketName):
for data in all_file_data:
if len(first_row) == len(data):
print("data is matched with header")
date_time_index = first_row.index("Date&Ti... | Python | zaydzuhri_stack_edu_python |
function radialHeatMap self goal_pos r
begin
for i in range r
begin
set radius = call vonNeumannNeighbors goal_pos i + 1
set reward_radius = 1.0 / i + 1 ^ 1.5 * 25
for pos in radius
begin
set pos_numeric = tuple integer split pos string : at 0 integer split pos string : at 1
print pos_numeric
print goal_pos
set rewards... | def radialHeatMap(self, goal_pos, r):
for i in range(r):
radius = self.vonNeumannNeighbors(goal_pos, i+1)
reward_radius = (1.0/((i+1)**1.5))*25
for pos in radius:
pos_numeric = (int(pos.split(":")[0]), int(pos.split(":")[1]))
print (pos_num... | Python | nomic_cornstack_python_v1 |
function softmax_loss_naive W X y reg
begin
comment Initialize the loss and gradient to zero.
set loss = 0.0
set dW = zeros like W
comment TODO: Compute the softmax loss and its gradient using explicit loops. #
comment Store the loss in loss and the gradient in dW. If you are not careful #
comment here, it is easy to r... | def softmax_loss_naive(W, X, y, reg):
# Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W)
#############################################################################
# TODO: Compute the softmax loss and its gradient using explicit loops. #
# Store the loss in... | Python | nomic_cornstack_python_v1 |
async function get_data data_date data_type=none from_folder=none
begin
set data = dict
if data_type is none
begin
async_with call ClientSession as session
begin
for f_type in FileType
begin
if not from_folder
begin
set data at f_type = call decompress await call _download_file data_date f_type session
end
else
begin
... | async def get_data(data_date: date, data_type: FileType = None, from_folder: str = None):
data = {}
if data_type is None:
async with aiohttp.ClientSession() as session:
for f_type in FileType:
if not from_folder:
data[f_type] = decompress(await _download_file(data_date, f_type, session))
else:
... | Python | nomic_cornstack_python_v1 |
import unittest
from Alexey.Text.count_of_words_in_a_string.main.count_words_in_a_string import words_counter
class TestCountWordsInAString extends TestCase
begin
function test_send_normal_sentence_and_expect_count_words self
begin
set expect_set = 2
set actual_set = call words_counter string Captain Cold
assert equal ... | import unittest
from Alexey.Text.count_of_words_in_a_string.main.count_words_in_a_string import words_counter
class TestCountWordsInAString(unittest.TestCase):
def test_send_normal_sentence_and_expect_count_words(self):
expect_set = 2
actual_set = words_counter('Captain Cold')
self.assert... | Python | zaydzuhri_stack_edu_python |
function set_info_service self firmware_revision=none manufacturer=none model=none serial_number=none
begin
set serv_info = call get_service string AccessoryInformation
if firmware_revision
begin
call configure_char string FirmwareRevision value=firmware_revision
end
if manufacturer
begin
call configure_char string Man... | def set_info_service(self, firmware_revision=None, manufacturer=None,
model=None, serial_number=None):
serv_info = self.get_service('AccessoryInformation')
if firmware_revision:
serv_info.configure_char(
'FirmwareRevision', value=firmware_revision)
... | Python | nomic_cornstack_python_v1 |
comment Updated on May 29 2020
comment Done on May 16 2020
class Solution
begin
function groupAnagrams self strs
begin
comment N is length of list
comment K is length of longest word in the list
comment in ordered dict we need not make sure that we have a key already, we can create key while assigning the value
comment... | # Updated on May 29 2020
# Done on May 16 2020
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
# N is length of list
# K is length of longest word in the list
# in ordered dict we need not make sure that we have a key already, we can create key while a... | Python | zaydzuhri_stack_edu_python |
function pick_door self
begin
set remaining_doors = copy available_doors
set final_door_number = random integer 0 2
if swap == true
begin
pop remaining_doors final_door_number
set open_door = random choice remaining_doors
set open_door_idx = index remaining_doors open_door
if doors at open_door == string car
begin
if o... | def pick_door(self):
remaining_doors = self.available_doors.copy()
self.final_door_number = random.randint(0, 2)
if self.swap == True:
remaining_doors.pop(self.final_door_number)
open_door = random.choice(remaining_doors)
open_door_idx = rema... | Python | nomic_cornstack_python_v1 |
import requests
import json
import logging
from time import sleep
call basicConfig filename=string server.log filemode=string a level=INFO format=string {levelname} {asctime} {name} : {message} style=string {
set log = call getLogger __name__
function main url
begin
try
begin
set r = get requests url
call raise_for_sta... | import requests
import json
import logging
from time import sleep
logging.basicConfig(
filename="server.log",
filemode='a',
level=logging.INFO,
format='{levelname} {asctime} {name} : {message}',
style='{'
)
log = logging.getLogger(__name__)
def main(url):
try:
r = requests.get(url)
... | Python | zaydzuhri_stack_edu_python |
async function seeder name
begin
set stub = directory name path __file__ + string /stubs/seeder.py
set dest = call config string app.paths.seeders + string / + name + string .py
call generate
call nl
call notice string Be sure to add this seeder to your ./database/seeders/__init__.py
end function | async def seeder(name: str):
stub = os.path.dirname(__file__) + '/stubs/seeder.py'
dest = uvicore.config('app.paths.seeders') + '/' + name + '.py'
Schematic(
type='seeder',
stub=stub,
dest=dest,
replace = [
('xx_modelname', name),
('xx_ModelName', str... | Python | nomic_cornstack_python_v1 |
comment This script downloads house share CSVs and geojson's into the pwd.
comment Gets Chicago's CSVs as a default
import urllib2
set input_url = call raw_input string Enter your city's listings.csv.gz URL (Hit enter for default of Chicago):
if input_url == string
begin
print string Default of http://data.insideairbn... | #This script downloads house share CSVs and geojson's into the pwd.
#Gets Chicago's CSVs as a default
import urllib2
input_url = raw_input("Enter your city's listings.csv.gz URL (Hit enter for default of Chicago): ")
if input_url == '':
print('Default of http://data.insideairbnb.com/united-states/il/chicago/2015-... | Python | zaydzuhri_stack_edu_python |
function __extract_author line
begin
return call __extract_attribute line string author
end function | def __extract_author(line):
return __extract_attribute(line, 'author') | Python | nomic_cornstack_python_v1 |
function create_table_connection
begin
set str_date = string format time now string %b-%Y
set file_name = path_to_database + string library- + str_date + string .db
set conn = call connect file_name
try
begin
set c = call cursor
execute c create_table
return conn
end
except Error as e
begin
print e
end
end function | def create_table_connection():
str_date = datetime.now().strftime("%b-%Y")
file_name = constants.path_to_database + "library-" + str_date + ".db"
conn = sqlite3.connect(file_name)
try:
c = conn.cursor()
c.execute(constants.create_table)
return conn
except Error as e:
... | Python | nomic_cornstack_python_v1 |
function lstm_forward x a0 parameters
begin
comment Initialize "caches", which will track the list of all the caches
set caches = list
comment Retrieve dimensions from shapes of x and parameters['Wy'] (≈2 lines)
set tuple n_x m T_x = shape
set tuple n_y n_a = shape
comment initialize "a", "c" and "y" with zeros (≈3 li... | def lstm_forward(x, a0, parameters):
# Initialize "caches", which will track the list of all the caches
caches = []
# Retrieve dimensions from shapes of x and parameters['Wy'] (≈2 lines)
n_x, m, T_x = x.shape
n_y, n_a = parameters["Wy"].shape
# initialize "a", "c" and "y" with zeros (≈3 lines... | Python | nomic_cornstack_python_v1 |
function get_sso_change_saml_identity_mode self
begin
if not call is_sso_change_saml_identity_mode
begin
raise call AttributeError string tag 'sso_change_saml_identity_mode' not set
end
return _value
end function | def get_sso_change_saml_identity_mode(self):
if not self.is_sso_change_saml_identity_mode():
raise AttributeError("tag 'sso_change_saml_identity_mode' not set")
return self._value | Python | nomic_cornstack_python_v1 |
function serve_file load fnd
begin
if string env in load
begin
comment "env" is not supported; Use "saltenv".
pop load string env
end
set ret = dict string data string ; string dest string
if string path not in load or string loc not in load or string saltenv not in load
begin
return ret
end
if string path not in fnd... | def serve_file(load, fnd):
if "env" in load:
# "env" is not supported; Use "saltenv".
load.pop("env")
ret = {"data": "", "dest": ""}
if "path" not in load or "loc" not in load or "saltenv" not in load:
return ret
if "path" not in fnd or "bucket" not in fnd:
return ret
... | Python | nomic_cornstack_python_v1 |
function test_api_can_create_a_event self
begin
assert equal status_code HTTP_201_CREATED
end function | def test_api_can_create_a_event(self):
self.assertEqual(self.response.status_code, status.HTTP_201_CREATED) | Python | nomic_cornstack_python_v1 |
function test_rem_detect self
begin
set file_rem = load np string notebooks/data_EOGs_REM_256Hz.npz
set data_rem = file_rem at string data
set tuple loc roc = tuple data_rem at tuple 0 slice : : data_rem at tuple 1 slice : :
set sf_rem = file_rem at string sf
set hypno_rem = 4 * ones like loc
comment Parameters p... | def test_rem_detect(self):
file_rem = np.load('notebooks/data_EOGs_REM_256Hz.npz')
data_rem = file_rem['data']
loc, roc = data_rem[0, :], data_rem[1, :]
sf_rem = file_rem['sf']
hypno_rem = 4 * np.ones_like(loc)
# Parameters product testing
freq_rem = [(0.5, 5), (... | Python | nomic_cornstack_python_v1 |
import sys
set N = next stdin
set numbers = sorted map int split next stdin | import sys
N = next(sys.stdin)
numbers = sorted(map(int, next(sys.stdin).split()))
| Python | zaydzuhri_stack_edu_python |
function reverse_query self
begin
string Changes the coordinates as if the query sequence has been reverse complemented
set qry_start = qry_length - qry_start - 1
set qry_end = qry_length - qry_end - 1
end function | def reverse_query(self):
'''Changes the coordinates as if the query sequence has been reverse complemented'''
self.qry_start = self.qry_length - self.qry_start - 1
self.qry_end = self.qry_length - self.qry_end - 1 | Python | jtatman_500k |
function find_most_common numbers
begin
pass
end function
set numbers = list 2 3 4 2 3 2 3 2
assert call find_most_common numbers == 2
set numbers = list 2 3 4 2 3 4 3 2
assert call find_most_common numbers == 2
set numbers = list
assert call find_most_common numbers == none
set numbers = list 1 1 1 1 1 1 1 1
assert c... | def find_most_common(numbers: List[int]) -> int:
pass
numbers = [2, 3, 4, 2, 3, 2, 3, 2]
assert find_most_common(numbers) == 2
numbers = [2, 3, 4, 2, 3, 4, 3, 2]
assert find_most_common(numbers) == 2
numbers = []
assert find_most_common(numbers) == None
numbers = [1, 1, 1, 1, 1, 1, 1, 1]
assert find_most_co... | Python | greatdarklord_python_dataset |
function login_form_invalid db_tieto_user
begin
set invalid_password = call password length=8
while invalid_password == db_tieto_user at 1
begin
set invalid_password = call password length=8
end
set form = call LoginForm email=email password=invalid_password
yield form
end function | def login_form_invalid(db_tieto_user):
invalid_password = g.person.password(length=8)
while(invalid_password == db_tieto_user[1]):
invalid_password = g.person.password(length=8)
form = LoginForm(
email=User.query.filter_by(id=db_tieto_user[0].id).first().email,
password=invalid_pass... | Python | nomic_cornstack_python_v1 |
from Bio import SeqIO
set list_of_chriii_syn_genes = list
for seq_record in parse SeqIO string C:\Biopyhton_files\chriii_syn.fasta string fasta
begin
if description at 22 != string and description at 23 != string
begin
if description at 28 + 7 != string ]
begin
append list_of_chriii_syn_genes description at slice 28... | from Bio import SeqIO
list_of_chriii_syn_genes = []
for seq_record in SeqIO.parse("C:\Biopyhton_files\chriii_syn.fasta", "fasta"):
if ((seq_record.description[22]) != ' ') and ((seq_record.description[23] != ' ')):
if (seq_record.description[28+7] != ']'):
list_of_chriii_syn_genes.append(seq_rec... | Python | zaydzuhri_stack_edu_python |
comment Name- MOHD MUSTAJAB KHAN
comment En.No- A180570
comment Roll No- 33
set a = - 1
set b = 1
print string For Fibbonacci series
while 1
begin
try
begin
set terms = input string Enter no of terms U want-:
set terms = integer terms
print string The Fibbonacci series formed is-:
for i in range terms
begin
set c = a +... | #Name- MOHD MUSTAJAB KHAN
#En.No- A180570
#Roll No- 33
a = -1
b = 1
print("For Fibbonacci series")
while 1:
try:
terms = input("Enter no of terms U want-: ")
terms = int(terms)
print("The Fibbonacci series formed is-:")
for i in range(terms):
c = a+b
... | Python | zaydzuhri_stack_edu_python |
comment ! /usr/bin/env python
comment Tutorial for creating your own dataloader function
comment Link to download sample data: https://download.pytorch.org/tutorial/hymenoptera_data.zip
import os
import pandas as pd
from skimage import io , transform
import torch
import torch.nn as nn
from torch.utils.data import Datas... | #! /usr/bin/env python
# Tutorial for creating your own dataloader function
# Link to download sample data: https://download.pytorch.org/tutorial/hymenoptera_data.zip
import os
import pandas as pd
from skimage import io, transform
import torch
import torch.nn as nn
from torch.utils.data import Dataset
# Dataset cl... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import time
import code_generator
function get_graph file
begin
set g = dict
set f = open file string r
for line in read lines f
begin
set tuple x y = split line
if x in keys g
begin
if y not in g at x
begin
append g at x y
end
end
else
begin
update g dict x list y
end
if y in keys g
begin
if x not ... | import numpy as np
import time
import code_generator
def get_graph(file):
g = {}
f = open(file,'r')
for line in f.readlines():
x,y = line.split()
if x in g.keys():
if y not in g[x]:
g[x].append(y)
else:
g.update({x: [y]})
if y in g.key... | Python | zaydzuhri_stack_edu_python |
function check_if_hit ship_list move
begin
for ship in ship_list
begin
if move in ship
begin
remove ship move
return true
end
end
for else
begin
return false
end
end function | def check_if_hit(ship_list, move):
for ship in ship_list:
if move in ship:
ship.remove(move)
return True
else:
return False | Python | nomic_cornstack_python_v1 |
function biggerIsGreater w
begin
function splitString word
begin
return list comprehension char for char in word
end function
function ASCII chars
begin
set listASCII = list
for i in range length chars
begin
append listASCII ordinal chars at i
end
return listASCII
end function
function reverseList list
begin
set rev =... | def biggerIsGreater(w):
def splitString(word):
return [char for char in word]
def ASCII(chars):
listASCII = []
for i in range(len(chars)):
listASCII.append(ord(chars[i]))
return listASCII
def reverseList(list):
rev = []
for i in reversed(range(len(... | Python | zaydzuhri_stack_edu_python |
function setUp self
begin
call implicitly_wait
end function | def setUp(self):
Browser.page.implicitly_wait() | Python | nomic_cornstack_python_v1 |
function getSession self
begin
set session = get session session
return session
end function | def getSession(self):
session = app.settings.cherrypy.session.get(self.session)
return session | Python | nomic_cornstack_python_v1 |
function build_service_info_response datasets qparams authorized_datasets=list
begin
set schemas = requestedSchemasServiceInfo at 0
if not schemas or list
begin
comment We let it throw a KeyError
set default_schema = DEFAULT_SCHEMAS at string ServiceInfo
set schemas = list tuple default_schema SUPPORTED_SCHEMAS at def... | def build_service_info_response(datasets, qparams, authorized_datasets=[]):
schemas = qparams.requestedSchemasServiceInfo[0]
if not (schemas or []):
default_schema = DEFAULT_SCHEMAS['ServiceInfo'] # We let it throw a KeyError
schemas = [(default_schema, SUPPORTED_SCHEMAS[default_schema])]
... | Python | nomic_cornstack_python_v1 |
for i in range n
begin
append words input
end
for i in range length words at 0
begin
set mark = 0
for word in words
begin
if word at slice : i + 1 : != words at 0 at slice : i + 1 :
begin
set mark = 1
break
end
end
if mark == 1
begin
continue
end
append ans words at 0 at i
end
if length ans != 0
begin
print join st... | for i in range(n):
words.append(input())
for i in range(len(words[0])):
mark=0
for word in words:
if word[:i+1]!=words[0][:i+1]:
mark=1
break
if (mark==1):
continue
ans.append(words[0][i])
if (len(ans)!=0):
print("".join(ans))
else:
print... | Python | zaydzuhri_stack_edu_python |
function compress_string s
begin
comment Count occurences of each character
set dict = dict
for c in s
begin
if c in dict
begin
set dict at c = dict at c + 1
end
else
begin
set dict at c = 1
end
end
comment Create a new string with the format
comment <character><number_of_occurences>
set compressed = list
for c in ke... | def compress_string(s):
# Count occurences of each character
dict = {}
for c in s:
if c in dict:
dict[c] += 1
else:
dict[c] = 1
# Create a new string with the format
# <character><number_of_occurences>
compressed = []
for c in dict.keys():... | Python | jtatman_500k |
function _set_pspf_scheduled self v load=false
begin
if has attribute v string _utype
begin
set v = call _utype v
end
try
begin
set t = call YANGDynClass v base=unicode is_leaf=true yang_name=string pspf-scheduled rest_name=string pspf-scheduled parent=self path_helper=_path_helper extmethods=_extmethods register_paths... | def _set_pspf_scheduled(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=unicode, is_leaf=True, yang_name="pspf-scheduled", rest_name="pspf-scheduled", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment Enuerates all possible words of edit distance 1 away from a given term
comment given the specified alphabet.
comment This version is very lengthy and could be made much tighter using
comment list comprehensions. You should be able to write a single line each for
comment the assignme... | #!/usr/bin/env python
# Enuerates all possible words of edit distance 1 away from a given term
# given the specified alphabet.
#
# This version is very lengthy and could be made much tighter using
# list comprehensions. You should be able to write a single line each for
# the assignments of splits, deletes, transpose... | Python | zaydzuhri_stack_edu_python |
function _calc_col_from_left self top_row left_col bottom_row right_col
begin
comment set up initial column (all indels)
set num_rows = bottom_row - top_row + 1
set last_col = list comprehension i_p * i for i in range num_rows
set cur_col = list last_col
comment sweep from one right of start column to end column
for co... | def _calc_col_from_left(self, top_row: int, left_col: int,
bottom_row: int, right_col: int) -> list:
# set up initial column (all indels)
num_rows = (bottom_row - top_row) + 1
last_col = [self.i_p * i for i in range(num_rows)]
cur_col = list(last_col)
... | Python | nomic_cornstack_python_v1 |
function get_time
begin
return dict string timestamp now + time delta hours=- 1
end function | def get_time():
return {
'timestamp': datetime.now()+ timedelta(hours=-1)
} | Python | nomic_cornstack_python_v1 |
import wx
string import wx.lib.agw.genericmessagedialog as GMD # Our normal wxApp-derived class, as usual app = wx.App(0) main_message = "Hello world! I am the main message." dlg = GMD.GenericMessageDialog(None, main_message, "A Nice Message Box", agwStyle=wx.ICON_INFORMATION | wx.OK) dlg.ShowModal() dlg.Destroy() app.... | import wx
'''
import wx.lib.agw.genericmessagedialog as GMD
# Our normal wxApp-derived class, as usual
app = wx.App(0)
main_message = "Hello world! I am the main message."
dlg = GMD.GenericMessageDialog(None, main_message, "A Nice Message Box",
agwStyle=wx.ICON_INFORMATION | wx.OK)
dl... | Python | zaydzuhri_stack_edu_python |
import numpy as np
from numpy import arange
import math
from matplotlib import pyplot as mp
import numpy as np
from scipy.spatial import distance
import input_module
from input_module import subject_subject_dictionary_constant
function gaussian x mu sig
begin
return exp - call power x - mu 2.0 / 2 * call power sig 2.0
... | import numpy as np
from numpy import arange
import math
from matplotlib import pyplot as mp
import numpy as np
from scipy.spatial import distance
import input_module
from input_module import subject_subject_dictionary_constant
def gaussian(x, mu, sig):
return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function solve self a
begin
set l = length a
set area = a at 0 * 1
for i in range 0 l
begin
for j in range 0 l
begin
set c = absolute j - i
if a at i < a at j
begin
set area1 = a at i * c
if area1 > area
begin
set area = area1
end
end
end
end
return area
end function
end class
set s = call Solution... | class Solution():
def solve(self,a):
l=len(a)
area = a[0]*1
for i in range(0,l):
for j in range(0,l):
c=abs(j-i)
if a[i] < a[j]:
area1= a[i] * c
if area1 > area:
area = area1
r... | Python | zaydzuhri_stack_edu_python |
string Script to accurately measure CCF bisector spans Take in a CCF Apply lower and upper contrast cuts Split it in half about the mid-point Step through in even steps in contrast Find the nearest two points Fit a line between them and solve for the veloicty at the contrast step Store contrast step and velocity in dic... | """
Script to accurately measure CCF bisector spans
Take in a CCF
Apply lower and upper contrast cuts
Split it in half about the mid-point
Step through in even steps in contrast
Find the nearest two points
Fit a line between them and solve for the veloicty at the contrast step
Store contrast step and velocity in dicti... | Python | zaydzuhri_stack_edu_python |
comment =============================================================================
comment >> IMPORTS
comment =============================================================================
comment Python
import cPickle as pickle
comment discover_win
from database import Database
comment ==============================... | # =============================================================================
# >> IMPORTS
# =============================================================================
# Python
import cPickle as pickle
# discover_win
from database import Database
# ===============================================================... | Python | zaydzuhri_stack_edu_python |
function black_general_valid_movements bit_boards piece_location=none
begin
from engine.engine_constants import RANK_9 , BLACK_PALACE_BITBOARD
comment The general may only move in an orthogonal manner in its palace. We therefore construct the grid of it moving in
comment all orthogonal directions. 'g' is the inner repr... | def black_general_valid_movements(bit_boards: BitBoard, piece_location: Optional[int] = None):
from engine.engine_constants import RANK_9, BLACK_PALACE_BITBOARD
# The general may only move in an orthogonal manner in its palace. We therefore construct the grid of it moving in
# all orthogonal directions. 'g'... | Python | nomic_cornstack_python_v1 |
function test_create_token_invalid_credentials self
begin
comment create user
call create_user email=string test@gmail.com password=string abcd1234
set payload = dict string email string test@gmail.com ; string password string wrong
comment We do not expect a token and should get a HTTP 400
set response = post TOKEN_UR... | def test_create_token_invalid_credentials(self):
# create user
create_user(email='test@gmail.com', password='abcd1234')
payload = {
'email': 'test@gmail.com',
'password': 'wrong'
}
# We do not expect a token and should get a HTTP 400
response = sel... | Python | nomic_cornstack_python_v1 |
function writeToFile self outFile
begin
for chrom in call get_chroms
begin
for bedItem in call get_BEDs chrom
begin
write outFile call to_string + string
end
end
flush outFile
end function
comment FIXME: Currently, explicitly printing just the first 4 fields.
comment It would be nice to have a more flexible and general... | def writeToFile(self, outFile):
for chrom in self.get_chroms():
for bedItem in self.get_BEDs(chrom):
outFile.write(bedItem.to_string() + "\n")
outFile.flush()
# FIXME: Currently, explicitly printing just the first 4 fields.
# It would be nice t... | Python | nomic_cornstack_python_v1 |
function calculate_signal_power self sender freq_range
begin
set distance = square root call power x - x 2 + call power y - y 2
set avg_frequency = call average freq_range * 1000000.0
set wavelength = speed_of_light / avg_frequency
set received_signal_power = tx_power * gain * gain * call power wavelength 2 / call powe... | def calculate_signal_power(self, sender, freq_range):
distance = np.sqrt(
np.power(self.x - sender.x, 2) + np.power(self.y - sender.y, 2))
avg_frequency = np.average(freq_range) * 1e6
wavelength = settings.speed_of_light / avg_frequency
received_signal_power = (
... | Python | nomic_cornstack_python_v1 |
function _translate__l3vpn_ntw_vpn_services_vpn_service_vpn_nodes_vpn_node_status_admin_status input_yang_obj translated_yang_obj=none
begin
if call _changed
begin
set status = status
end
if call _changed
begin
set last_updated = last_updated
end
return translated_yang_obj
end function | def _translate__l3vpn_ntw_vpn_services_vpn_service_vpn_nodes_vpn_node_status_admin_status(input_yang_obj,
translated_yang_obj=None):
if input_yang_obj.status._changed():
input_yang_obj.status = input_yang_obj.status
... | Python | nomic_cornstack_python_v1 |
function sed pattern replace source dest
begin
string Reads a source file and writes the destination file. In each line, replaces pattern with replace. pattern: string replace: string source: string filename dest: string filename
set fin = open source string r
set fout = open dest string w
for line in fin
begin
write f... | def sed(pattern, replace, source, dest):
"""Reads a source file and writes the destination file.
In each line, replaces pattern with replace.
pattern: string
replace: string
source: string filename
dest: string filename
"""
fin = open(source, 'r')
fout = open(dest, 'w')
for line ... | Python | zaydzuhri_stack_edu_python |
class StemReader
begin
function __init__ self filename
begin
set f = open filename string rb
end function
function reset self
begin
seek f 0
end function
function getNextWordAndStems self
begin
set stem = string
set line = read line f
if not line
begin
return tuple none string
end
try
begin
set line = decode line str... | class StemReader:
def __init__(self, filename):
self.f = open(filename, 'rb')
def reset(self):
self.f.seek(0)
def getNextWordAndStems(self):
stem = ''
line = self.f.readline()
if not line:
return (None, '')
try:
... | Python | zaydzuhri_stack_edu_python |
class Node
begin
function __init__ self value
begin
set value = value
set prev = none
set next = none
end function
end class
class MaxStack
begin
function __init__ self
begin
set top = none
set max_value = none
end function
function push self value
begin
set new_node = call Node value
set next = top
if top is not none
... | class Node:
def __init__(self, value):
self.value = value
self.prev = None
self.next = None
class MaxStack:
def __init__(self):
self.top = None
self.max_value = None
def push(self, value):
new_node = Node(value)
new_node.next = self.top
if s... | Python | jtatman_500k |
function checkIfCompaniesCloseMatchesNeeded dfToPredict dataSetDf
begin
clear predictCompaniesCloseMatchBooleanList
set toPredictCompanies = split string dfToPredict at string production_companies string |
for company in toPredictCompanies
begin
set companyMatches = dataSetDf at call contains string \| + company + stri... | def checkIfCompaniesCloseMatchesNeeded(dfToPredict,dataSetDf):
predictCompaniesCloseMatchBooleanList.clear()
toPredictCompanies = str(dfToPredict['production_companies']).split("|")
for company in toPredictCompanies:
companyMatches = dataSetDf[dataSetDf['production_companies'].str.contains(u'\|'+co... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
string Add Binary Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "1" Return "100".
class Solution
begin
comment @param a, a string
comment @param b, a string
comment @return a string
function addBinary self a b
begin
set c = binary integer a 2 + int... | #!/usr/bin/python
"""
Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
"""
class Solution:
# @param a, a string
# @param b, a string
# @return a string
def addBinary(self, a, b):
c = bin(int(a,2)+int(b,2))
retur... | Python | zaydzuhri_stack_edu_python |
function get_current_window self
begin
return __window
end function | def get_current_window(self):
return self.__window | Python | nomic_cornstack_python_v1 |
function solve
begin
with open string matrix.txt string r as f
begin
set file = list comprehension strip line for line in f
end
set maze = list
set sol = list
for i in file
begin
set index = 0
set temp = list
for j in range length i
begin
if i at j == string ,
begin
append temp i at slice index : j :
set index = j +... | def solve():
with open('matrix.txt','r') as f:
file = [line.strip() for line in f]
maze = []
sol = []
for i in file:
index = 0
temp = []
for j in range(len(i)):
if i[j] == ",":
temp.append(i[index:j])
... | Python | zaydzuhri_stack_edu_python |
function QueueId self
begin
return call _get_attribute string queueId
end function | def QueueId(self):
return self._get_attribute('queueId') | Python | nomic_cornstack_python_v1 |
from collections import deque
set tuple m n h = map int split input
set graph = list comprehension list for _ in range h
for z in range h
begin
for x in range n
begin
append graph at z list map int split input
end
end
set notriped = list
set visited = list comprehension list comprehension list - 1 * m for _ in range ... | from collections import deque
m, n, h = map(int, input().split())
graph = [[] for _ in range(h)]
for z in range(h):
for x in range(n):
graph[z].append(list(map(int, input().split())))
notriped = []
visited = [[[-1] * m for _ in range(n)] for _ in range(h)]
for i in range(h):
for j in range(n):
... | Python | zaydzuhri_stack_edu_python |
from EC2Handler import EC2Handler
from EC2Handler import *
import sys
comment python Vezba2.py instanceID amiID
function main
begin
comment inform user of proper usage if input arguments are invalid
if length argv != 3
begin
print string Error, invalid usage, examples of valid usage: python Vezba2.py instanceID AMI_ID ... | from EC2Handler import EC2Handler
from EC2Handler import *
import sys
# python Vezba2.py instanceID amiID
def main():
# inform user of proper usage if input arguments are invalid
if len(sys.argv) != 3:
print("Error, invalid usage, examples of valid usage:\n\tpython Vezba2.py instanceID AMI_ID... | Python | zaydzuhri_stack_edu_python |
function transformation_config self
begin
return get pulumi self string transformation_config
end function | def transformation_config(self) -> Optional[pulumi.Input['PreventionJobTriggerInspectJobActionDeidentifyTransformationConfigArgs']]:
return pulumi.get(self, "transformation_config") | Python | nomic_cornstack_python_v1 |
import torch
import torch.nn as nn
import numpy as np
class Loss extends Module
begin
function __init__ self
begin
call __init__
set cross_entropy = cross entropy loss size_average=false reduce=true
end function
function forward self batch_pred captions num_words
begin
comment batch_pred size [batch_size*seq, vocab_siz... | import torch
import torch.nn as nn
import numpy as np
class Loss(nn.Module):
def __init__(self):
super(Loss, self).__init__()
self.cross_entropy = nn.CrossEntropyLoss(size_average=False, reduce=True)
def forward(self, batch_pred, captions, num_words):
#batch_pred size [batch_size... | Python | zaydzuhri_stack_edu_python |
import smbus
import time
comment for RPI revision 1, use "bus = smbus.SMBus(0)"
set bus = call SMBus 1
comment This must match in the Arduino Sketch
set SLAVE_ADDRESS = 4
function request_reading
begin
set reading = integer call read_byte SLAVE_ADDRESS
print reading
end function
while true
begin
set command = call raw_... | import smbus
import time
# for RPI revision 1, use "bus = smbus.SMBus(0)"
bus = smbus.SMBus(1)
# This must match in the Arduino Sketch
SLAVE_ADDRESS = 0x04
def request_reading():
reading = int(bus.read_byte(SLAVE_ADDRESS))
print(reading)
while True:
command = raw_input("Enter command: l - toggle LED, r - read A0 ")... | Python | zaydzuhri_stack_edu_python |
function plot_na df
begin
bar range integer length df at string columns df at string percent_nan color=string blue
call xticks fontsize=8
title plt string Percent NaN by Column fontsize=12
y label string Percent NaN
x label string Column Number
save figure string na.png
end function
comment plt.show() | def plot_na(df):
plt.bar(range(int(len(df['columns']))), df['percent_nan'], color="blue")
plt.xticks(fontsize=8)
plt.title('Percent NaN by Column', fontsize=12)
plt.ylabel('Percent NaN')
plt.xlabel('Column Number')
plt.savefig('na.png')
# plt.show() | Python | nomic_cornstack_python_v1 |
function test_post_user_not_the_author self
begin
set user2 = call create email=string user2@gmail.com password=string apsso2@dwwW
set kwargs = dict string task_id pk
set req = post string /
set user = user2
set response = post req keyword kwargs
assert equal status_code 403
assert equal reason_phrase string Forbidden
... | def test_post_user_not_the_author(self):
user2 = User.create(
email='user2@gmail.com',
password='apsso2@dwwW'
)
kwargs = {'task_id': self.task.pk}
req = self.request.post('/')
req.user = user2
response = self.view.post(req, **kwargs)
self... | Python | nomic_cornstack_python_v1 |
import sys
import os
from PIL import Image
set PATH = string ./
set OUTDIR = string ./cropped_images
function crop_all base_path outdir_name crop_rect rename_as_seq=false
begin
set out_path = join path base_path outdir_name
if not exists path out_path
begin
make directory os out_path
end
set files_list = list directory... | import sys
import os
from PIL import Image
PATH = "./"
OUTDIR = "./cropped_images"
def crop_all(base_path:str,
outdir_name:str,
crop_rect: tuple,
*,
rename_as_seq=False):
out_path = os.path.join(base_path, outdir_name)
if not os.path.exists(out_path):
os.mkdir... | Python | zaydzuhri_stack_edu_python |
function perform_gauss_jordan_elimination m show
begin
if show
begin
print string Initial State
call print_matrix m
end
set tuple r c = tuple 0 0
set rows = length m
set cols = length m at 0
if show
begin
print string rows: %s cols: %s % tuple rows cols
end
while true
begin
set _swap = false
if show
begin
print string ... | def perform_gauss_jordan_elimination(m, show):
if show:
print("Initial State")
print_matrix(m)
r, c = 0, 0
rows = len(m)
cols = len(m[0])
if show:
print("rows: %s cols: %s"%(rows, cols))
while True:
_swap = False
if show:
print("r %s c %s"%... | Python | nomic_cornstack_python_v1 |
function getAqueousStateprimaryConcentrations self
begin
return call getCellConcAtEqui 1
end function | def getAqueousStateprimaryConcentrations(self):
return self.solver.getCellConcAtEqui(1) | Python | nomic_cornstack_python_v1 |
from logic import *
comment Sentence: "If it's rains, it's wet".
function rainWet
begin
comment whether it's raining
set Rain = call Atom string Rain
comment whether it's wet
set Wet = call Atom string Wet
return call Implies Rain Wet
end function
comment Sentence: "There is a light that shines."
function lightShines
b... | from logic import *
# Sentence: "If it's rains, it's wet".
def rainWet():
Rain = Atom('Rain') # whether it's raining
Wet = Atom('Wet') # whether it's wet
return Implies(Rain, Wet)
# Sentence: "There is a light that shines."
def lightShines():
def Light(x): return Atom('Light', x) # whether x is lit... | Python | zaydzuhri_stack_edu_python |
function update_template_recipient_document_visibility_with_http_info self account_id recipient_id template_id **kwargs
begin
set all_params = list string account_id string recipient_id string template_id string template_document_visibility_list
append all_params string callback
append all_params string _return_http_da... | def update_template_recipient_document_visibility_with_http_info(self, account_id, recipient_id, template_id, **kwargs):
all_params = ['account_id', 'recipient_id', 'template_id', 'template_document_visibility_list']
all_params.append('callback')
all_params.append('_return_http_data_only')
... | Python | nomic_cornstack_python_v1 |
function remove_words_from_review_list
begin
set students = call load_students
set student_name = call get_student_name_from_user
call check_student_name_in_list student_name
set words_to_keep = call get_words_to_keep_from_review_list
for tuple index student in enumerate students
begin
if students at index at string na... | def remove_words_from_review_list():
students = load_students()
student_name = get_student_name_from_user()
check_student_name_in_list(student_name)
words_to_keep = get_words_to_keep_from_review_list()
for index, student in enumerate(students):
if students[index]["name"] == student_name:
... | Python | nomic_cornstack_python_v1 |
import os
import time
import numpy as np
import tensorflow as tf
from tensorflow import keras
import tensorflow.keras.backend as K
import distiller
import models.ResNet_v1 as RN
set CP_PATH = string data/rn44_cp/rn44_cp
set BATCH_SIZE = 128
set EPOCHS = 5
set LR = 0.1
set MOMENTUM = 0.9
set WEIGHT_DECAY = 0.0005
set AU... | import os
import time
import numpy as np
import tensorflow as tf
from tensorflow import keras
import tensorflow.keras.backend as K
import distiller
import models.ResNet_v1 as RN
CP_PATH = 'data/rn44_cp/rn44_cp'
BATCH_SIZE = 128
EPOCHS = 5
LR = 0.1
MOMENTUM = 0.9
WEIGHT_DECAY = 5e-4
AUTO = tf.data.... | Python | zaydzuhri_stack_edu_python |
from machine import Pin
import machine
import time
function my_callback p
begin
set interrupt_state = call disable_irq
print string in interrupt
call sleep_ms 800
print 11111
call enable_irq interrupt_state
return
end function
set p2 = call Pin 2 IN
call irq trigger=IRQ_FALLING ? IRQ_RISING handler=my_callback | from machine import Pin
import machine
import time
def my_callback(p):
interrupt_state = machine.disable_irq()
print('in interrupt')
time.sleep_ms(800)
print(11111)
machine.enable_irq(interrupt_state)
return
p2 = Pin(2, Pin.IN)
p2.irq(trigger=Pin.IRQ_FALLING|Pin.IRQ_RISING, handler=my_callback... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.