code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
import random import math import matplotlib.pyplot as plt comment Define player object class player begin comment Default constructor with skill and name as a paramater with default values of wins and rate function __init__ self skill name begin set skill = skill set unique_skills = list 0 0 set name = name set wins = ...
import random import math import matplotlib.pyplot as plt #Define player object class player(): #Default constructor with skill and name as a paramater with default values of wins and rate def __init__(self, skill, name): self.skill = skill self.unique_skills = [0,0] self.name = name self.wins = 0 ...
Python
zaydzuhri_stack_edu_python
function __init__ self *args **kwargs begin pass end function
def __init__(self, *args, **kwargs): pass
Python
nomic_cornstack_python_v1
import numpy as np import gym from collections import deque from keras.models import Sequential from keras.layers import Dense from keras.optimizers import Adam import random class Agent extends object begin function __init__ self env begin comment hyperparameters and parameters set stateSize = shape at 0 set actionSiz...
import numpy as np import gym from collections import deque from keras.models import Sequential from keras.layers import Dense from keras.optimizers import Adam import random class Agent(object): def __init__(self, env): #hyperparameters and parameters self.stateSize = env.observation_sp...
Python
zaydzuhri_stack_edu_python
function has_subobjects_of_module obj module_name begin if not call is_module_available module_name begin return false end for sub_object in call get_object_hierarchy obj begin if call object_belongs_to_module sub_object module_name begin return true end end return false end function
def has_subobjects_of_module(obj, module_name): if not is_module_available(module_name): return False for sub_object in get_object_hierarchy(obj): if object_belongs_to_module(sub_object, module_name): return True return False
Python
nomic_cornstack_python_v1
function get_current_desktop_environment begin set desktop = call getenv string XDG_CURRENT_DESKTOP or string set desktop = split desktop string , set desktop = list comprehension lower name for name in desktop return desktop end function
def get_current_desktop_environment(): desktop = os.getenv('XDG_CURRENT_DESKTOP') or '' desktop = desktop.split(',') desktop = [name.lower() for name in desktop] return desktop
Python
nomic_cornstack_python_v1
set f = open string test.dat string w write f string How are you write f string 4 close f set f = open string test.dat string r print read f close f
f=open('test.dat','w') f.write('How are you') f.write('4') f.close() f=open('test.dat','r') print (f.read()) f.close()
Python
zaydzuhri_stack_edu_python
function train begin set dataset = call QuizBowlDataset guesser_train=true set tfidf_guesser = call TfidfGuesser train tfidf_guesser call training_data save end function
def train(): dataset = QuizBowlDataset(guesser_train=True) tfidf_guesser = TfidfGuesser() tfidf_guesser.train(dataset.training_data()) tfidf_guesser.save()
Python
nomic_cornstack_python_v1
function find_winner racers key_func begin return sorted racers key=key_func reverse=true at 0 end function
def find_winner(racers: List[Reindeer], key_func: Callable) -> Reindeer: return sorted(racers, key=key_func, reverse=True)[0]
Python
nomic_cornstack_python_v1
import argparse import sys function print_file_content file begin set file_object = open file set contents = read file_object print contents end function function write_list_to_file output_file lst begin set file_object = open output_file string w write file_object join string lst end function function write_list_to_f...
import argparse import sys def print_file_content(file): file_object = open(file) contents = file_object.read() print(contents) def write_list_to_file(output_file, lst): file_object = open(output_file, 'w') file_object.write('\n'.join(lst)) def write_list_to_file_v2(output_file, *text_to_add):...
Python
zaydzuhri_stack_edu_python
function save_pixiv_art self namesave owner artid folder=string user/ setpic=false save=false save_msg=false begin try begin print string art id: { artid } set namesave = call while_is_file folder namesave string .png set namesave = call while_is_file folder namesave string _p0.png set savedart = call fetch_illustratio...
def save_pixiv_art(self, namesave, owner, artid, folder='user/', setpic=False, save=False, save_msg=False): try: print(f'art id: {artid}') namesave = u.while_is_file(folder, namesave, '.png') namesave = u.while_is_file(folder, namesave, '_p0.png') savedart = self....
Python
nomic_cornstack_python_v1
class Animal extends object begin pass end class class Chipmunk extends Animal begin function __init__ self name begin set name = name end function end class set charles = call Chipmunk string Charles print name
class Animal(object): pass class Chipmunk(Animal): def __init__(self, name): self.name = name charles = Chipmunk('Charles') print(charles.name)
Python
zaydzuhri_stack_edu_python
comment Created on Mon Jan 26 15:18:15 2017 comment @author: Bharat comment importing the libraries comment for mathematical calculations import numpy as np comment for plotting nice charts import matplotlib.pyplot as plt comment for importing and managing dataset import pandas as pd comment importing the dataset set d...
#Created on Mon Jan 26 15:18:15 2017 #@author: Bharat #importing the libraries #for mathematical calculations import numpy as np #for plotting nice charts import matplotlib.pyplot as plt #for importing and managing dataset import pandas as pd #importing the dataset dataset = pd.read_csv('train.csv') dataset_test ...
Python
zaydzuhri_stack_edu_python
function date_preproccessing self nltk_normalized=false lowercase=true begin comment remove any punctuation followed by whitespace comment In order to convert dates in text to datetime objects we need to get rid of punctuations comment following words, so for e.g. "2017," will become "2017". It affects also words like ...
def date_preproccessing(self, nltk_normalized = False, lowercase = True): # remove any punctuation followed by whitespace ### In order to convert dates in text to datetime objects we need to get rid of punctuations ### following words, so for e.g. "2017," will become "2017". It affects also words like ###...
Python
nomic_cornstack_python_v1
function embedding_code model data n args begin comment STEP 2: optimizing to fit parameter learning fit model data comment STEP 3: retrieve the embeddings set node_onehot = call eye n set res = call feedforward_autoencoder node_onehot set ids = transpose np array range n set ids = call expand_dims ids axis=1 set embed...
def embedding_code(model, data, n, args): # STEP 2: optimizing to fit parameter learning model.fit(data) # STEP 3: retrieve the embeddings node_onehot = np.eye(n) res = model.feedforward_autoencoder(node_onehot) ids = np.transpose(np.array(range(n))) ids = np.expand_dims(ids, axis=1) ...
Python
nomic_cornstack_python_v1
from PySide2 import QtCore from Animal import Animal from random import randint , random class Renard extends Animal begin set nom = string renard function __init__ self position habitat espece timerSimulation listOfTimers begin call __init__ position habitat espece timerSimulation listOfTimers set rayon = 4 set couleu...
from PySide2 import QtCore from Animal import Animal from random import randint, random class Renard(Animal): nom = 'renard' def __init__(self, position, habitat, espece, timerSimulation, listOfTimers): super().__init__(position, habitat, espece, timerSimulation, listOfTimers) self....
Python
zaydzuhri_stack_edu_python
function cipher begin set shiftAmt = integer input string By how much would you like the string to be shifted by? set myString = input string What string would you like me to encrypt? set cipherString = string for c in myString begin if is alpha c begin set asciiValue = ordinal c set asciiValue = asciiValue + shiftAmt...
def cipher(): shiftAmt= int((input)("By how much would you like the string to be shifted by?")) myString= input("What string would you like me to encrypt?") cipherString= " " for c in myString: if c.isalpha(): asciiValue= ord(c) asciiValue+= shiftAmt ...
Python
zaydzuhri_stack_edu_python
for x in range 10 begin append list if expression x % 2 == 0 then 1 else 0 end print list
for x in range(10): list.append( 1 if x % 2 == 0 else 0 ) print(list)
Python
zaydzuhri_stack_edu_python
function test_get_thread self begin set opening_post = call _create_post for i in range 0 2 begin call create_post string title string text thread=call get_thread end set thread = call get_thread assert equal 3 count replies end function
def test_get_thread(self): opening_post = self._create_post() for i in range(0, 2): Post.objects.create_post('title', 'text', thread=opening_post.get_thread()) thread = opening_post.get_thread() self.assertEqual(3, thread.replies.count...
Python
nomic_cornstack_python_v1
function on_enter_callback self previous_mode begin global _stickInitTime _hole_start_time _fish_times _FishingStarted set _stickInitTime = time set _FishingStarted = true if _fishCaught == 0 begin set _hole_start_time = time set _fish_times = list end end function
def on_enter_callback(self, previous_mode): global _stickInitTime, _hole_start_time, _fish_times, _FishingStarted _stickInitTime = time.time() _FishingStarted = True if _fishCaught == 0: _hole_start_time = time.time() _fish_times = []
Python
nomic_cornstack_python_v1
function set_loss self loss_type loss_weight=1 loss_after_nonlin=false **kwargs begin set loss = call get_loss_from_type_name loss_type keyword kwargs call set_weight loss_weight call set_loss loss loss_after_nonlin=loss_after_nonlin end function
def set_loss(self, loss_type, loss_weight=1, loss_after_nonlin=False, **kwargs): self.loss = ls.get_loss_from_type_name(loss_type, **kwargs) self.loss.set_weight(loss_weight) self.layers[-1].set_loss(self.loss, loss_after_nonlin=loss_after_nonlin)
Python
nomic_cornstack_python_v1
comment coding: utf-8 import sys import datetime import KEY string Ticket Grant Server (TGS) Two Responsibilities: 1. Generate TGT(Ticket Grant Ticket) with KDC secret key and TGS session key 2. Generate ST(Service Ticket) with Service secret key and Service session key class tgs begin function __init__ self TGS_name s...
#coding: utf-8 import sys import datetime import KEY ''' Ticket Grant Server (TGS) Two Responsibilities: 1. Generate TGT(Ticket Grant Ticket) with KDC secret key and TGS session key 2. Generate ST(Service Ticket) with Service secret key and Service session key ''' class tgs(): def __init__(self,TGS_name,secret_key...
Python
zaydzuhri_stack_edu_python
comment Author: Mamata Anil Parab comment Project: Accepting list from user and displying addition of prime elements comment Input: 5,6,3,1,9,7,4 comment Output: 16 from NumOperation import * function ListPrime brr begin set addition = 0 for i in brr begin set bret = call ChkPrime i if bret == true begin set addition =...
############################################################################## # # Author: Mamata Anil Parab # Project: Accepting list from user and displying addition of prime elements # Input: 5,6,3,1,9,7,4 # Output: 16 # ################...
Python
zaydzuhri_stack_edu_python
function emit self name data=none begin set data = data or dict set event = event self name data for tuple decorated bound_handler in event_handlers begin if match event begin call bound_handler event end end end function
def emit(self, name, data=None): data = data or {} event = Event(self, name, data) for decorated, bound_handler in self.event_handlers: if decorated.match(event): bound_handler(event)
Python
nomic_cornstack_python_v1
from tkinter import * import tkinter.messagebox function name event begin call showinfo string Hello! string Hello! My name is Aryan Jain!! end function function ques event begin set answer = call askquestion string Ques string Is coding fun? if answer == string yes begin print string Answer is a yes!!! end else begin ...
from tkinter import * import tkinter.messagebox def name(event): tkinter.messagebox.showinfo('Hello!', "Hello! My name is Aryan Jain!!") def ques(event): answer = tkinter.messagebox.askquestion('Ques', 'Is coding fun?') if answer=='yes': print("Answer is a yes!!!") else: print("Answer...
Python
zaydzuhri_stack_edu_python
function obj_to_message obj to_type **updates begin set keys = keys fields_by_name set data = dictionary comprehension k : get attribute obj k for k in keys update data updates return call to_type keyword data end function
def obj_to_message(obj: Union[Task, Worker], to_type: Union[TaskMessage, WorkerMessage], **updates) -> Union[TaskMessage, WorkerMessage]: keys = to_type.DESCRIPTOR.fields_by_name.keys() data = {k: getattr(obj, k) for k in keys} data.update(updates) return to_type(**data)
Python
nomic_cornstack_python_v1
function run self begin call dstruc_loadin if output and needcommit begin write stderr string output and needcommit are two incompatible options. exit 2 end if target_table != string cluster_stat and output == none begin try begin comment 03-18-05 cluster_stat_id is changed to be an integer, because the the name of xxx...
def run(self): self.dstruc_loadin() if self.output and self.needcommit: sys.stderr.write("output and needcommit are two incompatible options.\n") sys.exit(2) if self.target_table != 'cluster_stat' and self.output == None: try: #03-18-05 cluster_stat_id is changed to be an integer, because the th...
Python
nomic_cornstack_python_v1
function apply_pbc pos L begin return pos + L / 2 % L - L / 2 end function
def apply_pbc(pos, L): return ((pos + L / 2) % L) - L / 2
Python
nomic_cornstack_python_v1
class Array begin function __init__ self num begin set num = num end function function numbers self target begin for i in range length num begin for j in range i + 1 length num begin if num at i + num at j == target begin return tuple i j end end end end function end class set A = array list 1 2 3 4 5 6 print call numb...
class Array: def __init__(self,num): self.num = num def numbers(self,target): for i in range(len(self.num)): for j in range(i+1,len(self.num)): if self.num[i]+self.num[j] == target: return (i,j) A = Array([1,2,3,4,5,6]) print(A.numbers(5))
Python
zaydzuhri_stack_edu_python
comment coding=utf-8 import os from util.excel_util import ExcelUtil from keywords.actionMethod import ActionMethod comment 此文件中操作Excel中的数据,有的单元格没有数据,判断时候 ‘’而不是None class KeywordCase begin function run_main self begin set action_method = call ActionMethod set path_file = get current directory set file_name = absolute p...
# coding=utf-8 import os from util.excel_util import ExcelUtil from keywords.actionMethod import ActionMethod # 此文件中操作Excel中的数据,有的单元格没有数据,判断时候 ‘’而不是None class KeywordCase(): def run_main(self): self.action_method = ActionMethod() path_file = os.getcwd() file_name = os.path.abs...
Python
zaydzuhri_stack_edu_python
function populate_db self skip_version begin if skip_version begin info string Skipping version populate end else begin call create_versions end comment Preserve the sequence below call clean_next_release_metrics call create_commits_from_repo call compute_version_metrics end function
def populate_db(self, skip_version): if skip_version: logging.info("Skipping version populate") else: self.create_versions() # Preserve the sequence below self.clean_next_release_metrics() self.create_commits_from_repo() self.compute_versi...
Python
nomic_cornstack_python_v1
from PIL import Image import numpy as np function extractColors file_ ch begin set im = open file_ set img_ = load im set img_mat = array im set size_ = shape at 0 if ch == 2 begin set channels = list string __r_. string __g_. string __b_. string __rg_. string __gb_. string __rb_. set values = list list 1 0 0 list 0 1 ...
from PIL import Image import numpy as np def extractColors(file_, ch): im = Image.open(file_) img_ = im.load() img_mat = np.array(im) size_ = img_mat.shape[0] if(ch == 2): channels = ['__r_.', '__g_.', '__b_.', '__rg_.', '__gb_.', '__rb_.'] values = [[1, 0, 0], [0, 1, 0], [0, 0, ...
Python
zaydzuhri_stack_edu_python
import math class ComplexNumber begin function __init__ self real imaginary begin set real = real set imaginary = imaginary end function function __repr__ self begin return string { real } + { imaginary } i end function function add self other begin set real = real + real set imaginary = imaginary + imaginary return ca...
import math class ComplexNumber: def __init__(self, real, imaginary): self.real = real self.imaginary = imaginary def __repr__(self): return f'{self.real} + {self.imaginary}i' def add(self, other): real = self.real + other.real imaginary = self.imaginary + ...
Python
jtatman_500k
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np function compute_loss pred label weights device_id num_class=8 begin set one_hot_label = cuda call one_hot_encoder label num_class device=device_id set ce = call call MySoftmaxCrossEntropyLoss nbclasses=num_class weight=weights pred l...
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np def compute_loss(pred, label, weights, device_id, num_class=8): one_hot_label = one_hot_encoder(label, num_class).cuda(device=device_id) ce = MySoftmaxCrossEntropyLoss(nbclasses=num_class, weight=weights)(pred, label) dic...
Python
zaydzuhri_stack_edu_python
comment take the user's weight as an input set weight = input string Enter your weight in kg: comment take the user's height as an input set height = input string Enter your height in m: comment calculate and output the BMI set BMI = decimal weight / decimal height ^ 2 set result = integer BMI print string Your BMI is ...
#take the user's weight as an input weight=input("Enter your weight in kg: \n") #take the user's height as an input height=input("Enter your height in m: \n") #calculate and output the BMI BMI=float(weight)/(float(height)**2) result=int(BMI) print("Your BMI is "+str(result))
Python
zaydzuhri_stack_edu_python
from API import stackoverflowAPI comment Model comment business-logic implementation class StackoverflowCrawler begin function __init__ self begin set _questions = none end function function search_questions self query begin comment search for questions similar to query set questions = call search_questions query set _...
from API import stackoverflowAPI # Model # business-logic implementation class StackoverflowCrawler: def __init__(self): self._questions = None def search_questions(self, query): # search for questions similar to query questions = stackoverflowAPI.search_questions(query) self....
Python
zaydzuhri_stack_edu_python
function deserialize_file cls filename uncompress_only_scalars=false begin set histos = list with open filename string rb as buffer begin while true begin set tuple field_number wire_type = call read_field_number_and_wire_type buffer if field_number == 1 and wire_type == 2 begin comment Found a value of the repeated H...
def deserialize_file(cls, filename, uncompress_only_scalars=False): histos = [] with open(filename, 'rb') as buffer: while True: field_number, wire_type = cls.read_field_number_and_wire_type(buffer) if field_number == 1 and wire_type == 2: ...
Python
nomic_cornstack_python_v1
function setBaseAddressRight self value begin call DPxSetAuxBuffBaseAddr value end function
def setBaseAddressRight(self, value): DPxSetAuxBuffBaseAddr(value)
Python
nomic_cornstack_python_v1
function ws_on_message self ws_connection message begin debug string RECEIVE PACKAGE set compressed_msg = loads message if compressed_msg at string type == string live-data begin debug string 📝 ws@job_id #%s received a msg! selected_job at string id set result = call pako_inflate bytes compressed_msg at string data at...
def ws_on_message(self, ws_connection, message) -> None: logger.debug("RECEIVE PACKAGE") compressed_msg = json.loads(message) if compressed_msg["type"] == "live-data": logger.debug("📝 ws@job_id #%s received a msg!", self.selected_job['id']) result = self.pako_inflate(byt...
Python
nomic_cornstack_python_v1
import requests set url = string http://roll-dice-game.com/roll set payload = dict string number-of-dice 1 set r = post url data=payload print text comment Output: The dice rolled a 3!
import requests url = 'http://roll-dice-game.com/roll' payload = { 'number-of-dice': 1 } r = requests.post(url, data=payload) print(r.text) # Output: The dice rolled a 3!
Python
jtatman_500k
function solve N arr begin sort arr reverse=true set cnt0 = count arr 0 set cnt1 = count arr 1 if cnt0 + cnt1 == N begin return - 1 end else begin return N + 1 - cnt0 end end function if __name__ == string __main__ begin set T = integer input for i in range T begin set N = integer input set arr = list map int split inp...
def solve(N,arr): arr.sort(reverse=True) cnt0=arr.count(0) cnt1=arr.count(1) if cnt0+cnt1==N: return -1 else: return N+1-cnt0 if __name__ == "__main__": T=int(input()) for i in range(T): N = int(input()) arr = list(map(int, input().split())) res=solve(...
Python
zaydzuhri_stack_edu_python
from collections import defaultdict class Graph begin function __init__ self connections begin set _graph = default dictionary set call add_connections connections end function function add_connections self connections begin for tuple node1 node2 in connections begin call _add node1 node2 end end function function _add...
from collections import defaultdict class Graph(): def __init__(self, connections): self._graph = defaultdict(set) self.add_connections(connections) def add_connections(self,connections): for node1, node2 in connections: self._add(node1,node2) def _add(self, node1, node2): self._graph[node1].add(node...
Python
zaydzuhri_stack_edu_python
function _create_zl_imgs_given_ids self ids subset ann_type begin assert subset in list string none string small string train string dev string test assert ann_type in list string none string label string bbox string mask if subset == string none begin set ids = list end else if subset == string small begin comment WA...
def _create_zl_imgs_given_ids(self, ids: list, subset: str, ann_type: str) -> ZLIMGS: assert subset in ["none", "small", "train", "dev", "test"] assert ann_type in ["none", "label", "bbox", "mask"] if subset == 'none': ids = [] elif subset == 'small': ### WARNING...
Python
nomic_cornstack_python_v1
function xflr5AirplanePolarReader self filePrefix fileDirectory parameterIdentifier begin for filename in list directory fileDirectory begin if filePrefix in filename begin try begin comment Get Pr number set currentPr = decimal filename at slice find filename parameterIdentifier + 2 : find filename parameterIdentifier...
def xflr5AirplanePolarReader(self, filePrefix, fileDirectory, parameterIdentifier): for filename in os.listdir(fileDirectory): if filePrefix in filename: try: # Get Pr number currentPr = float( filename[filename.find(par...
Python
nomic_cornstack_python_v1
function class_instance_for_config base_class config begin comment TODO [matt.c.mccallum 11.06.19]: Update other codebases to use this function where they can. return call call class_for_config base_class config config end function
def class_instance_for_config(base_class, config): # TODO [matt.c.mccallum 11.06.19]: Update other codebases to use this function where they can. return class_for_config(base_class, config)(config)
Python
nomic_cornstack_python_v1
function tocoo self begin pass end function
def tocoo(self): pass
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- comment g.sorgente: sudoku main comment tests: comment python main.py -n 3 -v 3,0,9,7,0,0,0,0,0,4,8,5,0,0,0,2,0,6,0,0,0,4,5,8,0,0,0,0,2,0,0,3,0,0,9,0,0,7,0,5,0,9,0,4,0,0,5,0,0,1,0,0,8,0,0,0,0,1,4,5,0,0,0,1,0,8,0,0,0,4,6,5,0,0,0,0,0,6,7,0,3 -a solve import sys import Cell from Sudoku import...
# -*- coding: utf-8 -*- # g.sorgente: sudoku main # tests: # python main.py -n 3 -v 3,0,9,7,0,0,0,0,0,4,8,5,0,0,0,2,0,6,0,0,0,4,5,8,0,0,0,0,2,0,0,3,0,0,9,0,0,7,0,5,0,9,0,4,0,0,5,0,0,1,0,0,8,0,0,0,0,1,4,5,0,0,0,1,0,8,0,0,0,4,6,5,0,0,0,0,0,6,7,0,3 -a solve import sys import Cell from Sudoku import Sudoku if (len(s...
Python
zaydzuhri_stack_edu_python
import telebot from extensions import APIException , Convertor from config import TOKEN , exchanges import traceback set bot = call TeleBot TOKEN decorator call message_handler commands=list string start string help function start message begin set text = string /values , Введите : <Валюта 1 > < Валюта 2 > < Сумма > ca...
import telebot from extensions import APIException, Convertor from config import TOKEN, exchanges import traceback bot = telebot.TeleBot(TOKEN) @bot.message_handler(commands=['start', 'help']) def start(message: telebot.types.Message): text = "/values , Введите : <Валюта 1 > < Валюта 2 > < Сумма > " bot.send...
Python
zaydzuhri_stack_edu_python
import random set number = call randrange 10 print number set number = call randrange 5 10 print number set number = call randrange 0 101 10 print number set number = random print number set number = uniform 1.0 10.0 print number
import random number = random.randrange(10) print(number) number = random.randrange(5, 10) print(number) number = random.randrange(0, 101, 10) print(number) number = random.random() print(number) number = random.uniform(1.0, 10.0) print(number)
Python
zaydzuhri_stack_edu_python
string Dynamic Programming routine comment # comment PyMS software for processing of metabolomic mass-spectrometry data # comment Copyright (C) 2005-2012 Vladimir Likic # comment # comment This program is free software; you can redistribute it and/or modify # comment it under the terms of the GNU General Public License...
""" Dynamic Programming routine """ ############################################################################# # # # PyMS software for processing of metabolomic mass-spectrometry data # # Copyright (C) 2005-2012 Vladimir Likic ...
Python
zaydzuhri_stack_edu_python
function dst self begin return _dst_data end function
def dst(self): return self._dst_data
Python
nomic_cornstack_python_v1
function get_processed_data begin set folder = string data/emnlp2018_userstudy/ set data = list for filename in list directory folder begin if starts with filename string processed begin with open join path folder filename string rb as infile begin set data = data + load pickle infile end end end return dict string am...
def get_processed_data(): folder = 'data/emnlp2018_userstudy/' data = [] for filename in os.listdir(folder): if filename.startswith('processed'): with open(os.path.join(folder,filename), 'rb') as infile: data += pickle.load(infile) return {'amazon':data}
Python
nomic_cornstack_python_v1
function aio_wrapper f begin decorator wraps f function decor *args **kwargs begin return run f dist *args keyword kwargs end function return decor end function
def aio_wrapper(f): @wraps(f) def decor(*args,**kwargs): return asyncio.run(f(*args,**kwargs)) return decor
Python
nomic_cornstack_python_v1
function check_ndim self begin if ndim != 4 begin raise exception string Only support 4-D data! end set n_events = shape at 0 end function
def check_ndim(self): if self.rest_data.ndim != 4: raise Exception('Only support 4-D data!') self.n_events = self.rest_data.shape[0]
Python
nomic_cornstack_python_v1
function get_mod_path self root goal begin set to_visit = set literal root set est_cost = dict root 0 set final_cost = dict set visited = set set back_track = dict while to_visit begin set current_node = none set current_score = none for mod in to_visit begin if current_node is none or est_cost at mod < current_score...
def get_mod_path(self, root, goal): to_visit = {root} est_cost = {root: 0} final_cost = {} visited = set() back_track = {} while to_visit: current_node = None current_score = None for mod in to_visit: if current_node is ...
Python
nomic_cornstack_python_v1
string This file tests the kinematics for the cheaper MIT MANUS Author: Benjamin Gutierrez email: bengutie@mit.edu import numpy as np import matplotlib.pylab as plt import scipy as sp from CheaperManusController import Kinematics as Kinematics class Graphics begin function __init__ self begin string Constructor for Gra...
""" This file tests the kinematics for the cheaper MIT MANUS Author: Benjamin Gutierrez email: bengutie@mit.edu """ import numpy as np import matplotlib.pylab as plt import scipy as sp from CheaperManusController import Kinematics as Kinematics class Graphics: def __init__(self): """Constructor for ...
Python
zaydzuhri_stack_edu_python
function compile md_file execute begin set lines = read lines open md_file string r set blocks = call extract_blocks lines set nb = call compile_nb blocks execute=execute set fname = base name path md_file set title = call splitext fname at 0 with open format string {}.ipynb title string w as f begin write nb f end end...
def compile(md_file, execute): lines = open(md_file, 'r').readlines() blocks = extract_blocks(lines) nb = compile_nb(blocks, execute=execute) fname = os.path.basename(md_file) title = os.path.splitext(fname)[0] with open('{}.ipynb'.format(title), 'w') as f: write(nb, f)
Python
nomic_cornstack_python_v1
function test_coming_up_two_days_past self begin set time = now + time delta days=- 2 set tomorrow_event = event event_date=time call assertIs call coming_up false end function
def test_coming_up_two_days_past(self): time = timezone.now() + datetime.timedelta(days=-2) tomorrow_event = Event(event_date=time) self.assertIs(tomorrow_event.coming_up(), False)
Python
nomic_cornstack_python_v1
function test_two_sentinel_one_ko self begin set sentinels = list dict string host string localhost ; string port 44455 dict string host string localhost ; string port 26379 set sentinel = call StrictSentinel retries_sleep=0.001 sentinels=sentinels set strict_redis = call get_strict_redis string sprayer-master assert t...
def test_two_sentinel_one_ko(self): sentinels = [{'host': 'localhost', 'port': 44455}, {'host': 'localhost', 'port': 26379}] sentinel = StrictSentinel(retries_sleep=0.001, sentinels=sentinels) strict_redis = sentinel.get_strict_redis('sprayer-master') self.assertTrue(strict_redis.ping())
Python
nomic_cornstack_python_v1
function Solve begin set temp = 0 for x in range 999 99 - 1 begin for y in range 990 99 - 11 begin set test = x * y if test > temp begin set string = string test if string == string at slice : : - 1 begin set temp = test end end else begin break end end end return temp end function if __name__ == string __main__ begi...
def Solve(): temp = 0 for x in range(999, 99, -1): for y in range(990, 99, -11): test = x * y if test > temp: string = str(test) if string == string[::-1]: temp = test else: break return temp if...
Python
zaydzuhri_stack_edu_python
comment CONTROL FLOW: comment weather = "sunny" comment if weather == "sunny": comment print("Let's go to the beach!") comment elif weather == "snowy": comment print("Let's go skiing!") comment else: comment print("Let's stay inside!") comment break will break the loop
# CONTROL FLOW: # weather = "sunny" # # if weather == "sunny": # print("Let's go to the beach!") # elif weather == "snowy": # print("Let's go skiing!") # else: # print("Let's stay inside!") # # break will break the loop
Python
zaydzuhri_stack_edu_python
function merge_sort arr begin set n = length arr comment Create a temporary array to store the sorted sublists set temp_arr = list 0 * n comment Divide the list into sublists of size 1, then merge them back together set sublist_size = 1 while sublist_size < n begin set left = 0 while left < n - 1 begin comment Find the...
def merge_sort(arr): n = len(arr) # Create a temporary array to store the sorted sublists temp_arr = [0] * n # Divide the list into sublists of size 1, then merge them back together sublist_size = 1 while sublist_size < n: left = 0 while left < n - 1: # Find...
Python
jtatman_500k
comment Errors can be handled with try and except statements. comment The code that could potentially have an error is put in a try clause. comment The program execution moves to the start of a following except clause if an error happens. comment You can put the previous divide-by-zero code in a try clause comment and ...
# Errors can be handled with try and except statements. # The code that could potentially have an error is put in a try clause. # The program execution moves to the start of a following except clause if an error happens. # You can put the previous divide-by-zero code in a try clause # and have an except clause contain...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding: utf-8 function fib n begin set tuple a b = tuple 1 1 for i in range n - 1 begin set tuple a b = tuple b a + b end return a end function comment 输出了第10个斐波那契数列
#!/usr/bin/env python #coding: utf-8 def fib(n): a,b = 1,1 for i in range(n-1): a,b = b,a+b return a # 输出了第10个斐波那契数列
Python
zaydzuhri_stack_edu_python
function discover_root_ip_reservation self **kwargs begin set kwargs at string _return_http_data_only = true if get kwargs string async begin return call discover_root_ip_reservation_with_http_info keyword kwargs end else begin set data = call discover_root_ip_reservation_with_http_info keyword kwargs return data end e...
def discover_root_ip_reservation(self, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return self.discover_root_ip_reservation_with_http_info(**kwargs) else: (data) = self.discover_root_ip_reservation_with_http_info(**kwargs) return...
Python
nomic_cornstack_python_v1
function get_joined_strings self opt_name=none opt=none prefix=string begin set tuple olist rv = call get_string_list opt_name=opt_name opt=opt if rv or olist == none begin return string end if length olist < 1 begin return string end comment we have something return prefix + join string call quotize_list olist end ...
def get_joined_strings(self, opt_name=None, opt=None, prefix=''): olist, rv = self.get_string_list(opt_name=opt_name, opt=opt) if rv or olist == None: return '' if len(olist) < 1: return '' # we have something return prefix + ' '.join(UTIL.quotize_list(olist))
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import random from heapq import heappush , heappop comment Select random job, select first fitting worker comment Instead of backtracking, release random job function constructive_random_heuristic w_price w_space w_capacity begin set available_jobs = set range length w_price at 0 set wc = l...
#!/usr/bin/env python import random from heapq import heappush, heappop # Select random job, select first fitting worker # Instead of backtracking, release random job def constructive_random_heuristic( w_price, w_space, w_capacity ): available_jobs = set( range(len(w_price[0]))) wc = len(w_capacity) ...
Python
zaydzuhri_stack_edu_python
import math import sys import pprint from sortedcontainers import SortedDict import logging import threading import time set filepath = string day23.txt set ids = list comprehension x for x in range 50 set idctr = 0 set RAM = call SortedDict set RAMS = dict set relptr = 0 set relptrs = dict set ptr = 0 set ptrs = dic...
import math import sys import pprint from sortedcontainers import SortedDict import logging import threading import time filepath = "day23.txt" ids = [x for x in range(50)] idctr = 0 RAM = SortedDict() RAMS = {} relptr = 0 relptrs = {} ptr = 0 ptrs = {} inputs = {} queues = {} sleeping = set() ...
Python
zaydzuhri_stack_edu_python
comment ---------------PDF MERGING----------------- import PyPDF2 import os function pdf_merge begin try begin set address_list = list set loop = 1 set count = input string Number of files to be merged: if call isdecimal and integer count > 1 begin print string Please add complete address of pdf that need to be merged...
# ---------------PDF MERGING----------------- import PyPDF2 import os def pdf_merge(): try: address_list = [] loop = 1 count = input('Number of files to be merged: ') if count.isdecimal() and int(count) > 1: print("Please add complete address of pdf that ...
Python
zaydzuhri_stack_edu_python
string create time : 2020-4-16 author: xsz version: v4 description: 目标:进行 100每日指标整理 依赖: 三批数据源的pkl文件, 名称罗列表 import numpy as np import pandas as pd from organize.env import get_df from organize.env import find_table from matplotlib import pyplot as plt class Solution begin function __init__ self input_table begin set tab...
""" create time : 2020-4-16 author: xsz version: v4 description: 目标:进行 100每日指标整理 依赖: 三批数据源的pkl文件, 名称罗列表 """ import numpy as np import pandas as pd from organize.env import get_df from organize.env import find_table from matplotlib import pyplot as plt class Solution: def __init__(self, input_table): se...
Python
zaydzuhri_stack_edu_python
function clip_tokenize_single text begin return call tokenize text at 0 end function
def clip_tokenize_single(text: str) -> torch.LongTensor: return clip.tokenize(text)[0]
Python
nomic_cornstack_python_v1
comment Special characters to represent digits 0-9 set num = list character 245 character 246 character 247 character 248 character 249 character 250 character 251 character 252 character 253 character 254 function encrypt txt ky begin set result = string for i in range length txt begin set char = txt at i if is digit...
# Special characters to represent digits 0-9 num = [chr(245), chr(246), chr(247), chr(248), chr(249), chr(250), chr(251), chr(252), chr(253), chr(254), ] def encrypt(txt, ky): result = "" for i in range(len(txt)): char = txt[i] if char.isdigit(): n = ord(char) result +...
Python
zaydzuhri_stack_edu_python
string Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. The same repeated number may be chosen from candidates unlimited number of times. Note: All numbers (including target) will be po...
""" Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. The same repeated number may be chosen from candidates unlimited number of times. Note: All numbers (including target) will be po...
Python
zaydzuhri_stack_edu_python
function share_settings self other keylist=none include_callbacks=true callback=true begin string Sharing settings with `other` if keylist is none begin set keylist = keys group end if include_callbacks begin for key in keylist begin set tuple oset mset = tuple group at key group at key set group at key = mset call mer...
def share_settings(self, other, keylist=None, include_callbacks=True, callback=True): """Sharing settings with `other` """ if keylist is None: keylist = self.group.keys() if include_callbacks: for key in keylist: oset, mset =...
Python
jtatman_500k
function faktorial n begin set hasil = n while n > 1 begin set n = n - 1 set hasil = hasil * n end return hasil end function function C n m begin return call faktorial n / call faktorial n - m * call faktorial m end function function P n m begin return call faktorial n / call faktorial n - m end function print call P 5...
def faktorial(n): hasil = n while(n > 1): n -= 1 hasil *= n return hasil def C(n,m): return faktorial(n)/(faktorial(n - m) * faktorial(m)) def P(n,m): return faktorial(n) / (faktorial(n-m)) print(P(5,3)) print(C(10,7))
Python
zaydzuhri_stack_edu_python
function write_fr_frame index fr_id mode data payload_length repetition offset channel begin return index end function
def write_fr_frame(index, fr_id, mode, data, payload_length, repetition, offset, channel): return index
Python
nomic_cornstack_python_v1
function instance cls metric_id dataset=none begin set subclasses = call __subclasses__ for tuple idx metric in enumerate sorted subclasses key=func begin if idx == metric_id begin return call metric dataset end end raise call ValueError format string Not existing metric with id {} metric_id end function
def instance(cls, metric_id, dataset=None): subclasses = cls.__subclasses__() for idx, metric in enumerate(sorted(subclasses, key=cls.func)): if idx == metric_id: return metric(dataset) raise ValueError("Not existing metric with id {}".format(metric_id))
Python
nomic_cornstack_python_v1
function random cls span=1 seed=none begin string Creates a randomized coordinate system. Useful for confirming that an *assembly* does not rely on its origin coordinate system to remain intact. For example, the :class:`CoordSysIndicator` *assembly* aligns 3 boxes along each of the :math:`XYZ` axes. Positioning it rand...
def random(cls, span=1, seed=None): """ Creates a randomized coordinate system. Useful for confirming that an *assembly* does not rely on its origin coordinate system to remain intact. For example, the :class:`CoordSysIndicator` *assembly* aligns 3 boxes along each of t...
Python
jtatman_500k
function _run_split_on_punc self text begin set chars = list text set i = 0 set start_new_word = true set output = list while i < length chars begin set char = chars at i if call _is_punctuation char begin append output list char set start_new_word = true end else begin if start_new_word begin append output list end s...
def _run_split_on_punc(self, text): chars = list(text) i = 0 start_new_word = True output = [] while i < len(chars): char = chars[i] if _is_punctuation(char): output.append([char]) start_new_word = True else: if start_new_word: output.append([]) start_new_word = False output[...
Python
nomic_cornstack_python_v1
import sys comment Check size of generator set l1 = generator expression x for x in range 1000 set l2 = list comprehension x for x in range 1000 print call getsizeof l1 print call getsizeof l2 comment print(next(l1)) comment print(next(l1)) comment print(next(l1)) comment print(next(l1)) comment print(next(l1)) comment...
import sys # Check size of generator l1 = (x for x in range(1000)) l2 = [x for x in range(1000)] print(sys.getsizeof(l1)) print(sys.getsizeof(l2)) # print(next(l1)) # print(next(l1)) # print(next(l1)) # print(next(l1)) # print(next(l1)) # print(next(l1)) # def gera(): # n = 'text1' # yield n # n = 'te...
Python
zaydzuhri_stack_edu_python
function add_rule rule begin global RULE_DICT if rule at 0 not in RULE_DICT begin set RULE_DICT at rule at 0 = list end append RULE_DICT at rule at 0 rule at slice 1 : : end function
def add_rule(rule): global RULE_DICT if rule[0] not in RULE_DICT: RULE_DICT[rule[0]] = [] RULE_DICT[rule[0]].append(rule[1:])
Python
nomic_cornstack_python_v1
from pyspark import SparkContext import sys import json import time function main begin set review_filepath = argv at 1 set business_filepath = argv at 2 set output_filepath_question_a = argv at 3 set output_filepath_question_b = argv at 4 set sc = call SparkContext string local[*] string task2 set review_RDD = call pa...
from pyspark import SparkContext import sys import json import time def main(): review_filepath = sys.argv[1] business_filepath = sys.argv[2] output_filepath_question_a = sys.argv[3] output_filepath_question_b = sys.argv[4] sc = SparkContext('local[*]', 'task2') review_RDD = sc.textFile(review...
Python
zaydzuhri_stack_edu_python
function get_children self path watch=none begin set node = call _find path if node is none begin return none end if watch begin comment Currently the only place to register children watch call _register_children_watch path watch end return generator expression name for child in children end function
def get_children(self, path, watch=None): node = self._find(path) if node is None: return None if watch: # Currently the only place to register children watch self._register_children_watch(path, watch) return (child.name for child in node.children)
Python
nomic_cornstack_python_v1
function bellman_ford G N s begin set dist = list INFTY * N set dist at s = 0 for i in range length G begin for tuple fr to d in G begin set new_dist = dist at fr + d if new_dist < dist at to begin set dist at to = new_dist if i == N - 1 begin print string negative loop exists! end end end end for tuple v d in enumerat...
def bellman_ford(G, N, s): dist = [INFTY] * N dist[s] = 0 for i in range(len(G)): for (fr, to, d) in G: new_dist = dist[fr] + d if new_dist < dist[to]: dist[to] = new_dist if i == N - 1: print("negative loop exists!") ...
Python
zaydzuhri_stack_edu_python
import os comment global variables set SIZE = 5 comment colour set tuple red green white blue yellow = tuple 0 1 2 3 4 comment nationality set tuple british swedish danish norwegian german = tuple 5 6 7 8 9 comment drink set tuple tea coffee water beer milk = tuple 10 11 12 13 14 comment cigarette set tuple prince blen...
import os #global variables SIZE = 5 #colour red, green, white, blue, yellow = 0,1,2,3,4 #nationality british, swedish, danish, norwegian, german = 5,6,7,8,9 #drink tea, coffee, water, beer, milk = 10,11,12,13,14 #cigarette prince, blends, pallmall, bluemasters,dunhill = 15,16,17,18,19 #pet dog, cat, bird, horse,...
Python
zaydzuhri_stack_edu_python
function getBufferSize self begin return call DPxGetMicBuffSize end function
def getBufferSize(self): return DPxGetMicBuffSize()
Python
nomic_cornstack_python_v1
comment FIGURE 2.1 comment Plot the occupation probability for different values of <n> import numpy as np import matplotlib import matplotlib.pyplot as plt set rcParams at string mathtext.fontset = string stix set rcParams at string font.family = string STIXGeneral set rcParams at string font.size = 23 comment matplotl...
#FIGURE 2.1 #Plot the occupation probability for different values of <n> import numpy as np import matplotlib import matplotlib.pyplot as plt matplotlib.rcParams['mathtext.fontset'] = 'stix' matplotlib.rcParams['font.family'] = 'STIXGeneral' matplotlib.rcParams['font.size']=23 #matplotlib.rcParams['text.usetex'] = T...
Python
zaydzuhri_stack_edu_python
function set_last_layer_to_non_trainable model begin set non_output_layers = call get_non_output_layer_ids model set layers_to_non_trainable = list comprehension layers at i for i in non_output_layers for layer in layers_to_non_trainable begin set trainable = false end for layer in layers begin debug string Layer %s is...
def set_last_layer_to_non_trainable(model): non_output_layers = get_non_output_layer_ids(model) layers_to_non_trainable = [model.layers[i] for i in non_output_layers] for layer in layers_to_non_trainable: layer.trainable = False for layer in model.layers: logging.debug("Layer %s is t...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Sun Oct 22 12:34:24 2017 @author: jwang import csv import re import os import random import time import numpy as np from tools.record import Record class File extends object begin function __init__ self file_name begin set _label_num = 0 set _file_point = open file_name s...
# -*- coding: utf-8 -*- """ Created on Sun Oct 22 12:34:24 2017 @author: jwang """ import csv import re import os import random import time import numpy as np from tools.record import Record class File(object): def __init__(self, file_name): self._label_num = 0 self._file_point = open(file_name, ...
Python
zaydzuhri_stack_edu_python
string DwyaneTalk@gmail.com https://leetcode.com/problems/add-two-numbers/ function initList nums begin set size = length nums set listNode = none if size < 1 begin return listNode end else begin set listNode = call ListNode nums at 0 end set curNode = listNode for x in range 1 size begin set next = call ListNode nums ...
''' DwyaneTalk@gmail.com https://leetcode.com/problems/add-two-numbers/ ''' def initList(nums): size = len(nums) listNode = None if size < 1: return listNode else: listNode = ListNode(nums[0]) curNode = listNode for x in range(1, size): curNode.next = ListNode(nums[x]) curNode = curNode.next return list...
Python
zaydzuhri_stack_edu_python
function _read_complex self card begin comment msg = 'complex matrices not supported in the DMI reader...' comment raise NotImplementedError(msg) comment column number set j = call integer card 2 string icol comment counter set i = 0 set fields = list comprehension call interpret_value field card for field in card at s...
def _read_complex(self, card): #msg = 'complex matrices not supported in the DMI reader...' #raise NotImplementedError(msg) # column number j = integer(card, 2, 'icol') # counter i = 0 fields = [interpret_value(field, card) for field in card[3:]] # Complex...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Thu Sep 19 14:54:52 2019 ref = 《python3网络爬虫实战》 @author: Limbo comment URL异常 comment URLError处理url的异常 from urllib import request , error try begin set response = url open string http://cuiqingcai.com/index.html end except URLError as e begin print reason end comment HTTPEr...
# -*- coding: utf-8 -*- """ Created on Thu Sep 19 14:54:52 2019 ref = 《python3网络爬虫实战》 @author: Limbo """ #URL异常 #URLError处理url的异常 from urllib import request, error try: response = request.urlopen('http://cuiqingcai.com/index.html') except error.URLError as e: print(e.reason) #HTTPError #用来处理http错误...
Python
zaydzuhri_stack_edu_python
function connect_loop timeout=30 retry_interval=0.25 begin comment Initialize time counter. set t = 0 while t < timeout begin try begin set c = call connect db=environ at string DB_DB passwd=environ at string DB_PASS host=environ at string DB_HOST user=environ at string DB_USER port=integer environ at string DB_PORT en...
def connect_loop(timeout=30, retry_interval=0.25): # Initialize time counter. t = 0 while t < timeout: try: c = MySQLdb.connect(db=os.environ['DB_DB'], passwd=os.environ['DB_PASS'], host=os.environ['DB_HOST'], ...
Python
nomic_cornstack_python_v1
function run self begin try begin set is_activated = true while is_activated begin try begin comment make sure all of the connections are saved. set connection = call accept append _connections connection end except timeout begin pass end end end except Exception as e begin exception e end finally begin call deactivate...
def run(self): try: self.is_activated=True while self.is_activated: try: #make sure all of the connections are saved. connection = self._socket.accept() self._connections.append(connection) except...
Python
nomic_cornstack_python_v1
function vector_to_int a_vec characteristic degree begin set a = 0 set factor = 1 for i in range degree - 1 - 1 - 1 begin set a = a + a_vec at i * factor set factor = factor * characteristic end return a end function
def vector_to_int(a_vec: np.ndarray, characteristic: int, degree: int) -> int: a = 0 factor = 1 for i in range(degree - 1, -1, -1): a += a_vec[i] * factor factor *= characteristic return a
Python
nomic_cornstack_python_v1
function max_sum_subarray array begin string This function will find the maximum sum of a contiguous subarray. Parameters: array: list of integers Returns: maximum sum of contiguuous subarray comment Initialize the max sum and current sum to the start of the array set max_sum = array at 0 set current_sum = array at 0 c...
def max_sum_subarray(array): """ This function will find the maximum sum of a contiguous subarray. Parameters: array: list of integers Returns: maximum sum of contiguuous subarray """ # Initialize the max sum and current sum to the start of the array max_sum = current_sum =...
Python
jtatman_500k
from neuronocr_compilation import easyocr comment get_detector function to load model separately from neuronocr_compilation.easyocr.detection import get_detector function main begin string Function to test the function of OCR detection part. This function loads the model separately, detects text and returns the result ...
from neuronocr_compilation import easyocr # get_detector function to load model separately from neuronocr_compilation.easyocr.detection import get_detector def main(): ''' Function to test the function of OCR detection part. This function loads the model separately, detects text and returns the result ...
Python
zaydzuhri_stack_edu_python
function calculate_largest_rectangle heights begin set i = 1 set stack_of_indices = list 0 set max_area = 0 set tuple start_index end_index = tuple 0 0 while i < length heights begin set curr_height = heights at i set prev_height = heights at stack_of_indices at - 1 comment should be > or >= ???? Looks both OK, but IMO...
def calculate_largest_rectangle(heights): i = 1 stack_of_indices = [0] max_area = 0 start_index, end_index = 0, 0 while i < len(heights): curr_height = heights[i] prev_height = heights[stack_of_indices[-1]] if curr_height > prev_height: # should be > or >= ???? Looks both OK,...
Python
nomic_cornstack_python_v1
import argparse import cv2 set ap = call ArgumentParser call add_argument string -i string --image required=true help=string Path to the image set args = variables call parse_args comment 加载图片并把图像转换为灰度图像 set image = call imread args at string image set gray = call cvtColor image COLOR_BGR2GRAY image show string Origina...
import argparse import cv2 ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="Path to the image") args = vars(ap.parse_args()) # 加载图片并把图像转换为灰度图像 image = cv2.imread(args["image"]) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) cv2.imshow("Original", image) # 使用一系列腐蚀 for i in range(0,...
Python
zaydzuhri_stack_edu_python
string 複数エージェント用の強化学習タスクまとめ 基本的に 環境構築に必要な情報受け取り、初期設定 現状態と行動から、次の状態決定 報酬を決定 持ってる情報は スタート地点 ゴール地点 報酬 状態 取れる行動数 import Policy import random import numpy as numpy comment 基本的な機能 class Enviroment extends object begin function __init__ self begin set currentstate = 0 set nextstate = 0 set reward = 0 set n_state = 0 set start...
""" 複数エージェント用の強化学習タスクまとめ 基本的に 環境構築に必要な情報受け取り、初期設定 現状態と行動から、次の状態決定 報酬を決定 持ってる情報は スタート地点 ゴール地点 報酬 状態 取れる行動数 """ import Policy import random import numpy as numpy #基本的な機能 class Enviroment(object): def __init__(self): self.currentstate = 0 self.nextstate = 0 ...
Python
zaydzuhri_stack_edu_python
function CleanBadPixels spectraUp spectraDown begin set Clean_Up = list set Clean_Do = list set Clean_Av = list comment this is the minumum background Please check set eps = 25.0 set NBSPEC = length spectraUp for index in array range 0 NBSPEC begin set s_up = spectraUp at index set s_do = spectraDown at index set in...
def CleanBadPixels(spectraUp,spectraDown): Clean_Up= [] Clean_Do = [] Clean_Av = [] eps=25. # this is the minumum background Please check NBSPEC=len(spectraUp) for index in np.arange(0,NBSPEC): s_up=spectraUp[index] s_do=spectraDown[index] index_up=np.where(s_...
Python
nomic_cornstack_python_v1