code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function _write_text_descriptor outfile props begin set bmf = text write bmf call _create_textdict string info props at string info write bmf call _create_textdict string common props at string common for page in props at string pages begin write bmf call _create_textdict string page page end write bmf format string ch...
def _write_text_descriptor(outfile, props): bmf = outfile.text bmf.write(_create_textdict('info', props['info'])) bmf.write(_create_textdict('common', props['common'])) for page in props['pages']: bmf.write(_create_textdict('page', page)) bmf.write('chars count={}\n'.format(len(props['chars'...
Python
nomic_cornstack_python_v1
function _addjob self job begin if domain is not none and model is not none begin set job = deep copy job call _add_hydro_namelist base_hydro_namelist call _add_hrldas_namelist base_hrldas_namelist append jobs job end else begin raise call AttributeError string Can not add a job to a simulation without a model and a do...
def _addjob(self, job: Job): if self.domain is not None and self.model is not None: job = copy.deepcopy(job) job._add_hydro_namelist(self.base_hydro_namelist) job._add_hrldas_namelist(self.base_hrldas_namelist) self.jobs.append(job) else: rais...
Python
nomic_cornstack_python_v1
for i in word begin print i end set guess = string for i in range 0 length word begin set guess = guess + string _ end print guess
for i in word: print(i) guess="" for i in range(0, len(word)): guess+="_" print(guess)
Python
zaydzuhri_stack_edu_python
import time comment "\n" print string 你是可以看见我的? comment print("你是ssss",end = '',flush = False) comment print("你是ssss",flush = False) #"\n" comment flush = True print string 你是ssss end=string flush=true comment print("----------------") sleep 6 print string end
import time print("你是可以看见我的?")# "\n" # print("你是ssss",end = '',flush = False) # print("你是ssss",flush = False) #"\n" print("你是ssss",end = '',flush = True) #flush = True # print("----------------") time.sleep(6) print("end")
Python
zaydzuhri_stack_edu_python
import pyglet from math import floor import pyglet.window.key as key import pyglet.window.mouse as mouse from threading import Thread set egg = load image string egg.png set food = load image string food.png set linemate = load image string stone7.png set deraumere = load image string stone3.png set sibur = load image ...
import pyglet from math import floor import pyglet.window.key as key import pyglet.window.mouse as mouse from threading import Thread egg = pyglet.image.load('egg.png') food = pyglet.image.load('food.png') linemate = pyglet.image.load('stone7.png') deraumere = pyglet.image.load('stone3.png') sibur = pyglet.image.load...
Python
zaydzuhri_stack_edu_python
from validators.validate_age import ValidateAge as Va from validators.validate_bmi import ValidateBmi as Vb from validators.validate_date import ValidateDate as Vd from validators.validate_emp_id import ValidateEmpId as Ve from validators.validate_gender import ValidateGender as Vg from validators.validate_salary impor...
from validators.validate_age import ValidateAge as Va from validators.validate_bmi import ValidateBmi as Vb from validators.validate_date import ValidateDate as Vd from validators.validate_emp_id import ValidateEmpId as Ve from validators.validate_gender import ValidateGender as Vg from validators.validate_salary ...
Python
zaydzuhri_stack_edu_python
function unpack_wb wb n_features begin set w = wb at slice : n_features : set b = wb at - 1 return tuple w b end function
def unpack_wb(wb, n_features): w = wb[:n_features] b = wb[-1] return (w,b)
Python
nomic_cornstack_python_v1
function Get self request global_params=none begin set config = call GetMethodConfig string Get return call _RunMethod config request global_params=global_params end function
def Get(self, request, global_params=None): config = self.GetMethodConfig('Get') return self._RunMethod( config, request, global_params=global_params)
Python
nomic_cornstack_python_v1
from keras.optimizers import adam_v2 from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers.core import Dense , Dropout , Flatten from keras.layers.convolutional import Conv2D , MaxPooling2D from keras import metrics import numpy as np comment x/y dimensions to re...
from keras.optimizers import adam_v2 from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers.core import Dense, Dropout, Flatten from keras.layers.convolutional import Conv2D, MaxPooling2D from keras import metrics import numpy as np img_size = 48 # x/y dimension...
Python
zaydzuhri_stack_edu_python
function set_callback begin set calls = list if cnfg at string n_check != 0 begin set period = ceil cnfg at string n_epochs / cnfg at string n_check if cnfg at string n_check > 0 begin append calls call ModelCheckpoint join path cnfg at string dir_current nn_best save_best_only=true save_weights_only=false period=1 en...
def set_callback(): calls = [] if cnfg[ 'n_check' ] != 0: period = ceil( cnfg[ 'n_epochs' ] / cnfg[ 'n_check' ] ) if cnfg[ 'n_check' ] > 0: calls.append( callbacks.ModelCheckpoint( os.path.join( cnfg[ 'dir_current' ], nn_best ), save_best_...
Python
nomic_cornstack_python_v1
import plaidml.keras call install_backend import pandas as pd import numpy as np seed 1337 from keras.models import load_model comment AI Powered Sentiment Predictive Tool for Sustainability Awareness and Advocacy function main filename begin set tuple x_orig y_orig = call preprocess filename set x_orig = as type x_ori...
import plaidml.keras plaidml.keras.install_backend() import pandas as pd import numpy as np np.random.seed(1337) from keras.models import load_model # AI Powered Sentiment Predictive Tool for Sustainability Awareness and Advocacy def main(filename): x_orig, y_orig = preprocess(filename) x_orig = x_orig.asty...
Python
zaydzuhri_stack_edu_python
function _bind_old self target begin if is instance target Cluster begin call _subcall string bind string create export_cluster_id=cluster_id end else if is instance target Service begin call _subcall string bind string create export_cluster_id=cluster_id export_service_id=service_id end else begin raise NotImplemented...
def _bind_old(self, target): if isinstance(target, Cluster): self._subcall("bind", "create", export_cluster_id=target.cluster_id) elif isinstance(target, Service): self._subcall( "bind", "create", export_cluster_id=target.cluster_id...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Command line and file operations. import subprocess import tempfile import errno from contextlib import contextmanager class CommandLineError extends Exception begin string The traceback of all CommandLineError's is supressed when the errors occur on the command line to provide a us...
# -*- coding: utf-8 -*- """Command line and file operations.""" import subprocess import tempfile import errno from contextlib import contextmanager class CommandLineError(Exception): """ The traceback of all CommandLineError's is supressed when the errors occur on the command line to provide a usef...
Python
zaydzuhri_stack_edu_python
function deltaMemory start_memory stop_memory begin set memory_diff = call compare_to start_memory string filename set delta_memory = 0.0 comment suma de las diferencias en uso de memoria for stat in memory_diff begin set delta_memory = delta_memory + size_diff end comment de Byte -> kByte set delta_memory = delta_memo...
def deltaMemory(start_memory, stop_memory): memory_diff = stop_memory.compare_to(start_memory, "filename") delta_memory = 0.0 # suma de las diferencias en uso de memoria for stat in memory_diff: delta_memory = delta_memory + stat.size_diff # de Byte -> kByte delta_memory = delta_memory/...
Python
nomic_cornstack_python_v1
if a > 21 begin if b > 3 begin if c > 0.87 begin print string Mưa end else begin print string Không mưa end end else begin print string Không mưa end end else if b > 7 begin print string Mưa end else if c > 1.04 begin print string Mưa end else begin print string Không mưa end
if a > 21: if b > 3: if c > 0.87: print('Mưa') else: print('Không mưa') else: print('Không mưa') else: if b > 7: print('Mưa') else: if c > 1.04: print('Mưa') else: print('Không mưa')
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Tue Jul 28 21:36:30 2020 @author: user set tuple a b c = eval input string 請輸入三邊長: if c >= b and c >= a begin if c < b + a begin print c + b + a end end else if a >= b and a >= c begin if a < b + c begin print c + b + a end end else if b >= a and b >= c begin if b < a + c...
# -*- coding: utf-8 -*- """ Created on Tue Jul 28 21:36:30 2020 @author: user """ a,b,c = eval(input("請輸入三邊長:")) if(c>=b) and (c>=a): if(c<b+a): print(c+b+a) elif(a>=b) and(a>=c): if(a<b+c): print(c+b+a) elif(b>=a) and(b>=c): if(b<a+c): print(a+b+c) False==prin...
Python
zaydzuhri_stack_edu_python
function wide_resnet101_2 pretrained=false progress=true **kwargs begin set kwargs at string width_per_group = 64 * 2 return call _resnet string wide_resnet101_2 Bottleneck list 3 4 23 3 pretrained progress keyword kwargs end function
def wide_resnet101_2(pretrained=False, progress=True, **kwargs): kwargs['width_per_group'] = 64 * 2 return _resnet('wide_resnet101_2', models.resnet.Bottleneck, [3, 4, 23, 3], pretrained, progress, **kwargs)
Python
nomic_cornstack_python_v1
from epicovid.main.data import Data from datetime import datetime function getConfirmedCasesByCountry begin set data = confirmedByCountry set sorted_list = sorted data key=lambda x -> x at 1 reverse=true return sorted_list end function function getTotalDeathsByCountry begin set data = deathByCountry set sorted_list = s...
from epicovid.main.data import Data from datetime import datetime def getConfirmedCasesByCountry(): data = Data().confirmedByCountry sorted_list = sorted(data, key=lambda x: x[1], reverse=True) return sorted_list def getTotalDeathsByCountry(): data = Data().deathByCountry sorted_list = sorted(da...
Python
zaydzuhri_stack_edu_python
function getSize self begin Ellipsis end function
def getSize(self) -> int: ...
Python
nomic_cornstack_python_v1
function make_subsequent_mask embedding_sequence begin set sequence_length = size embedding_sequence 1 set attn_shape = tuple sequence_length sequence_length set subsequent_mask = as type call triu ones attn_shape k=1 string uint8 set subsequent_mask = call from_numpy subsequent_mask == 0 set subsequent_mask = call byt...
def make_subsequent_mask(embedding_sequence: torch.Tensor) -> torch.Tensor: sequence_length = embedding_sequence.size(1) attn_shape = (sequence_length, sequence_length) subsequent_mask = np.triu(np.ones(attn_shape), k=1).astype("uint8") subsequent_mask = torch.from_numpy(subsequent_mask) == 0 subseq...
Python
nomic_cornstack_python_v1
function test_POST_post_comment_create_comment self begin comment Login user call login username=string test password=string test comment Create a post set post = call create user=user content=string test comment Post a comment on this post set response = post string /post-comment/comment dict string content string com...
def test_POST_post_comment_create_comment(self): # Login user self.c.login(username="test", password="test") # Create a post post = UpPost.objects.create(user=self.user, content="test") # Post a comment on this post response = self.c.post('/post-comment/comment', { ...
Python
nomic_cornstack_python_v1
comment A Numpy implementation for Generalized LVQ comment Testing with iris dataset comment By: Akash Anand import numpy as np from sklearn.datasets import make_moons from Glvq import Glvq from glvq_utilities import plot2d if __name__ == string __main__ begin set prototype_per_class = 9 set epochs = 30 set tuple input...
# # A Numpy implementation for Generalized LVQ # Testing with iris dataset # # By: Akash Anand ######################################## import numpy as np from sklearn.datasets import make_moons ### from Glvq import Glvq from glvq_utilities import plot2d # # ######################################## if __name__ =...
Python
zaydzuhri_stack_edu_python
from PIL import Image function add_bgc I begin set im = open I comment your new background color set fill_color = tuple 0 0 64 comment it had mode P after DL it from OP set im = call convert string RGBA if mode in tuple string RGBA string LA begin set background = call new mode at slice : - 1 : size fill_color commen...
from PIL import Image def add_bgc(I): im = Image.open(I) fill_color = (0, 0, 64) # your new background color im = im.convert("RGBA") # it had mode P after DL it from OP if im.mode in ('RGBA', 'LA'): background = Image.new(im.mode[:-1], im.size, fill_color) background.paste...
Python
zaydzuhri_stack_edu_python
function part1 begin set north = 0 set east = 0 set facing = 1 for x in input begin set dir = x at 0 set mag = integer x at slice 1 : : if dir == string N begin set north = north + mag end else if dir == string S begin set north = north - mag end else if dir == string E begin set east = east + mag end else if dir == s...
def part1(): north = 0 east = 0 facing = 1 for x in input: dir = x[0] mag = int(x[1:]) if(dir == "N"): north += mag elif(dir == "S"): north -= mag elif(dir == "E"): east += mag elif(dir == "W"): east -= mag ...
Python
zaydzuhri_stack_edu_python
function desactivate_tweet self begin if rt begin call stop comment update Feed set flux_info = first filter by query id=idflux set Tweet_actif = false commit session end end function
def desactivate_tweet(self): if self.rt: self.rt.stop() # update Feed flux_info = Feed.query.filter_by(id=self.idflux).first() flux_info.Tweet_actif = False db.session.commit()
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- comment @Author: bobur554395 comment @Date: 2017-05-23 13:38:38 comment @Last Modified by: bobur554395 comment @Last Modified time: 2017-06-01 14:50:38 class ConfigOptions extends object begin string docstring for ConfigOptions function __init__ self _year day_hours days_num semesterId beg...
# -*- coding: utf-8 -*- # @Author: bobur554395 # @Date: 2017-05-23 13:38:38 # @Last Modified by: bobur554395 # @Last Modified time: 2017-06-01 14:50:38 class ConfigOptions(object): """docstring for ConfigOptions""" def __init__(self, _year, day_hours, days_num, semesterId): super(ConfigOptions, s...
Python
zaydzuhri_stack_edu_python
import random function minimax board current_player begin set winner = call get_winner if winner == 1 begin return - 1 end else if winner == 2 begin return 1 end else if call is_board_full begin return 0 end else begin if current_player == 1 begin set best_value = 1000 end else begin set best_value = - 1000 end for x i...
import random def minimax(board, current_player): winner = board.get_winner() if winner == 1: return -1 elif winner == 2: return 1 elif board.is_board_full(): return 0 else: if current_player == 1: best_value = 1000 else: best_value =...
Python
zaydzuhri_stack_edu_python
import streamlit as st import pandas as pd comment pylint: disable=pointless-statement set df = call DataFrame dict string first column list 1 2 3 4 ; string second column list 10 20 30 40 set option = call selectbox string Which number do you like best? df at string first column tuple string You selected: option
import streamlit as st import pandas as pd # pylint: disable=pointless-statement df = pd.DataFrame({"first column": [1, 2, 3, 4], "second column": [10, 20, 30, 40]}) option = st.selectbox("Which number do you like best?", df["first column"]) "You selected: ", option
Python
zaydzuhri_stack_edu_python
function GetTextExtent *args **kwargs begin return call GraphicsContext_GetTextExtent *args keyword kwargs end function
def GetTextExtent(*args, **kwargs): return _gdi_.GraphicsContext_GetTextExtent(*args, **kwargs)
Python
nomic_cornstack_python_v1
function writeToLog logName message writeOrAppend begin with open logName writeOrAppend as out begin write out message end end function
def writeToLog(logName, message, writeOrAppend): with open(logName, writeOrAppend) as out: out.write(message)
Python
nomic_cornstack_python_v1
function get_content_preview self content begin raise call NotImplementedError end function
def get_content_preview(self, content): raise NotImplementedError()
Python
nomic_cornstack_python_v1
import json import urllib from urlparse import urljoin class Octopart begin class PartsMatch begin function __init__ self octopart begin set _octopart = octopart set _queries = list end function function query_mpn self mpn brand reference begin append _queries dict string mpn mpn ; string brand brand ; string referenc...
import json import urllib from urlparse import urljoin class Octopart: class PartsMatch: def __init__(self, octopart): self._octopart = octopart self._queries = [] def query_mpn(self, mpn, brand, reference): self._queries.append({ "mpn": mpn, ...
Python
zaydzuhri_stack_edu_python
function cast obj begin return call itkImageToMeshFilterISS3MSS3_cast obj end function
def cast(obj: 'itkLightObject') -> "itkImageToMeshFilterISS3MSS3 *": return _itkImageToMeshFilterPython.itkImageToMeshFilterISS3MSS3_cast(obj)
Python
nomic_cornstack_python_v1
from selenium import webdriver import time comment 打印 title 和 url set driver = call Chrome get driver string https://www.baidu.com/ comment 3.界面最大化 call maximize_window sleep 5 comment 4.界面最小化 call minimize_window sleep 5 comment 1.打印标题 set title = title print title comment 2.打印url set url = current_url print url call ...
from selenium import webdriver import time #打印 title 和 url driver = webdriver.Chrome() driver.get("https://www.baidu.com/") #3.界面最大化 driver.maximize_window() time.sleep(5) #4.界面最小化 driver.minimize_window() time.sleep(5) #1.打印标题 title = driver.title print(title) #2.打印url url = driver.current_url print(url) driver.i...
Python
zaydzuhri_stack_edu_python
import pygame as pyg class Bullet begin function __init__ self x y win speed begin set win = win set speed = speed set h = 5 set w = 5 set x = x set y = y call rect win tuple 0 0 255 tuple x y w h end function function shot self x y begin call rect win tuple 0 0 255 tuple x y w h end function end class
import pygame as pyg class Bullet(): def __init__(self, x, y, win, speed): self.win = win self.speed = speed self.h = 5 self.w = 5 self.x = x self.y = y pyg.draw.rect(win, (0,0,255), (x, y, self.w, self.h) ) def shot(self, x, y): pyg.draw.rect(s...
Python
zaydzuhri_stack_edu_python
function choosetablegroup self message=string begin set dbinteract = call TableGroupHandlerInteract db_path set tablegrouplist = call gettablegroups if message begin print message end if tablegrouplist begin call printtuple tablegrouplist end set userchoice = call askuser string Pick a table group please : set tablegro...
def choosetablegroup(self, message=""): dbinteract = TableGroupHandlerInteract(self.db_path) tablegrouplist = dbinteract.gettablegroups() if message: print(message) if tablegrouplist: self.printtuple(tablegrouplist) userchoice = self.askuser("Pick a table group please : ") tablegroup = dbinteract._tes...
Python
nomic_cornstack_python_v1
comment 九九乘法表 set j = 1 while j <= 9 begin set i = 1 while i <= j begin print string { i } * { j } = { i * j } end=string set i = i + 1 end print set j = j + 1 end while else begin print string 结束!!! end for i in range 1 10 begin for j in range 1 i + 1 begin print string { j } * { i } = { i * j } end=string end print e...
# 九九乘法表 j = 1 while j <= 9: i = 1 while i <= j: print(f'{i}*{j}={i * j}', end=' ') i += 1; print() j += 1; else: print('结束!!!') for i in range(1, 10): for j in range(1, i+1): print(f'{j}*{i}={i * j}', end=' ') print()
Python
zaydzuhri_stack_edu_python
function test_does_not_validate_invalid_files self begin set bad_files = tuple string newstest2019-defr-src-ts.de.sgm string newstest2019-defr-src-ts.de.xml for bad_file in bad_files begin set bad_path = join get current directory string testdata bad_file with assert raises ValueError begin set _ = call ValidatableTest...
def test_does_not_validate_invalid_files(self): bad_files = ( 'newstest2019-defr-src-ts.de.sgm', 'newstest2019-defr-src-ts.de.xml', ) for bad_file in bad_files: bad_path = join(getcwd(), 'testdata', bad_file) with self.assertRaises(ValueError): ...
Python
nomic_cornstack_python_v1
from math import radians , cos , sin , asin , sqrt import sys import numpy as np import pandas as pd import matplotlib.pyplot as plt from statsmodels.nonparametric.smoothers_lowess import lowess import datetime as dt from datetime import datetime from pandas.plotting import register_matplotlib_converters call register_...
from math import radians, cos, sin, asin, sqrt import sys import numpy as np import pandas as pd import matplotlib.pyplot as plt from statsmodels.nonparametric.smoothers_lowess import lowess import datetime as dt from datetime import datetime from pandas.plotting import register_matplotlib_converters register_matplotli...
Python
zaydzuhri_stack_edu_python
function display_news_notifications news_counts begin set newsReaderDisplay = false for tuple repo count in items news_counts begin if count > 0 begin if not newsReaderDisplay begin set newsReaderDisplay = true print end print call colorize string WARN string * IMPORTANT: end=string print string %s news items need read...
def display_news_notifications(news_counts): newsReaderDisplay = False for repo, count in news_counts.items(): if count > 0: if not newsReaderDisplay: newsReaderDisplay = True print() print(colorize("WARN", " * IMPORTANT:"), end=' ') print("%s news items need reading for repository '%s'." % (count,...
Python
nomic_cornstack_python_v1
function bit_flip_map p begin set mat1 = array list list square root 1 - p 0 list 0 square root 1 - p set mat2 = array list list 0 square root p list square root p 0 return list mat1 mat2 end function
def bit_flip_map(p): mat1 = np.array([[np.sqrt(1 - p), 0], [0, np.sqrt(1 - p)]]) mat2 = np.array([[0, np.sqrt(p)], [np.sqrt(p), 0]]) return [mat1, mat2]
Python
nomic_cornstack_python_v1
import some_xyz_module set list_data = list 2 4 6 8 set x = list_data at 3 set dict_data = dict string 2 string two ; string 4 string four ; string 6 string six dict_data at string 8 set list_data = iterate list 3 5 7 9 11 print next list_data print next list_data print next list_data print next list_data print next li...
################################# import some_xyz_module list_data=[2,4,6,8] x=list_data[3] ################################# dict_data={'2':"two", '4':"four", '6':"six"} dict_data['8'] ################################### list_data=iter([3,5,7,9,11]) print(next(list_data)) print(next(list_data)) print(next(list_da...
Python
zaydzuhri_stack_edu_python
comment -*- coding: cp949 -*- print string ***** 1 ***** set cash = integer 5000 set candyPrice = integer 120 set max = cash // candyPrice print string cash cash print string candyPrice candyPrice print string max max print print string ***** 2-1 ***** set appleOfMyEye = string ,,,ȭ,,, comment ̸ print string appleOfMyE...
# -*- coding: cp949 -*- print("***** 1 *****") cash=int(5000) candyPrice=int(120) max=cash//candyPrice print("cash",cash) print("candyPrice",candyPrice) print("max", max) print() print("***** 2-1 *****") appleOfMyEye=(",,,ȭ,,,") print("appleOfMyEye",appleOfMyEye) # ̸ print("appleOfMyEye") # ڿ print(ap...
Python
zaydzuhri_stack_edu_python
function clean_text input_file begin set path = format string {}.txt input_file with open path string r as f begin set lines = read lines f end set unique = set list comprehension strip l for l in lines set sorted_unique = sorted list unique set out_path = format string {}_clean.txt input_file with open out_path string...
def clean_text(input_file): path = "{}.txt".format(input_file) with open(path, 'r') as f: lines = f.readlines() unique = set([l.strip() for l in lines]) sorted_unique = sorted(list(unique)) out_path = "{}_clean.txt".format(input_file) with open(out_path, 'w') as f: f.write("\n"...
Python
zaydzuhri_stack_edu_python
class MyClass begin string A simple example class set i = 123 function f self begin return string Hello world end function pass end class comment 方法的特别之处在于实例对象作为函数的第一个参数传给了函数。 print i comment 这个时候需要一个参数 print f dist 1 print __doc__ set x = call MyClass print x print __doc__ print i comment 这个时候就不需要参数了 print f dist
# class MyClass: """A simple example class""" i = 123 def f(self): return "Hello world" pass #方法的特别之处在于实例对象作为函数的第一个参数传给了函数。 print(MyClass.i) print(MyClass.f(1)) # 这个时候需要一个参数 print(MyClass.__doc__) x = MyClass() print(x) print(x.__doc__) print(x.i) print(x.f()) # 这个时候就不需要参数了
Python
zaydzuhri_stack_edu_python
function validar self id_vlan begin string Validates ACL - IPv4 of VLAN from its identifier. Assigns 1 to 'acl_valida'. :param id_vlan: Identifier of the Vlan. Integer value and greater than zero. :return: None :raise InvalidParameterError: Vlan identifier is null and invalid. :raise VlanNaoExisteError: Vlan not regist...
def validar(self, id_vlan): """Validates ACL - IPv4 of VLAN from its identifier. Assigns 1 to 'acl_valida'. :param id_vlan: Identifier of the Vlan. Integer value and greater than zero. :return: None :raise InvalidParameterError: Vlan identifier is null and invalid. :r...
Python
jtatman_500k
comment %% set date = string 등록213.3243.324 작업 set date = replace date string 등록 string print date import time import json set data_list = list string 1,2,3 sleep 10 try begin 1 + 2 end except KeyboardInterrupt begin print string 크롤링이 완료됐습니다. with open string nahonja_2015.json string w encoding=string utf-8 as make_fil...
#%% date = '등록213.3243.324 작업' date = date.replace('등록', '') print(date) import time import json data_list = ["1,2,3"] time.sleep(10) try : 1+2 except KeyboardInterrupt : print('크롤링이 완료됐습니다.') with open('nahonja_2015.json', 'w', encoding="utf-8") as make_file: json.dump(data_list, make_file, ensu...
Python
zaydzuhri_stack_edu_python
import numpy as np import matplotlib.pyplot as plt function harmoic_oscillator_drive y t args begin set omega = args set dydt = list y at 1 - omega * omega * y at 0 return dydt end function function forward_euler f y0 t args=none begin set dt = t at 1 - t at 0 set y = zeros tuple length t size set y at 0 = y0 for n in ...
import numpy as np import matplotlib.pyplot as plt def harmoic_oscillator_drive(y,t,args): omega = args dydt = [y[1], -omega*omega*y[0]] return dydt def forward_euler(f,y0,t,args=None): dt = t[1] - t[0] y = np.zeros((len(t), y0.size)) y[0] = y0 for n in range(0, len(t) - 1): y[...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding: utf-8 comment In[1]: from sklearn.metrics import confusion_matrix import numpy as np import pandas as pd from sklearn import metrics comment In[2]: from sklearn.ensemble import RandomForestClassifier from sklearn.naive_bayes import GaussianNB from sklearn.ensemble import Gra...
#!/usr/bin/env python # coding: utf-8 # In[1]: from sklearn.metrics import confusion_matrix import numpy as np import pandas as pd from sklearn import metrics # In[2]: from sklearn.ensemble import RandomForestClassifier from sklearn.naive_bayes import GaussianNB from sklearn.ensemble import GradientBoostingClass...
Python
zaydzuhri_stack_edu_python
class Block begin function __init__ self left top begin set left = left set top = top set height = 10 set width = 10 end function end class
class Block: def __init__(self, left, top): self.left = left self.top = top self.height = 10 self.width = 10
Python
zaydzuhri_stack_edu_python
function docother self object name=none mod=none *ignored begin set lhs = name and string <strong>%s</strong> = % name or string return lhs + call repr object end function
def docother(self, object, name=None, mod=None, *ignored): lhs = name and '<strong>%s</strong> = ' % name or '' return lhs + self.repr(object)
Python
nomic_cornstack_python_v1
function _check_edges edges begin for edge in edges begin try begin set tuple start end = tuple integer start integer end end except ValueError begin raise call InvalidEdgeError format string {}, edge start and end must be integers edge end if start == end begin raise call InvalidEdgeError format string {}, edges must ...
def _check_edges(edges: typing.Iterable[model.Edge]) -> typing.Generator: for edge in edges: try: start, end = int(edge.start), int(edge.end) except ValueError: raise InvalidEdgeError( '{}, edge start and end must be integers'.format(e...
Python
nomic_cornstack_python_v1
comment Using module keyboard import keyboard from time import sleep set keyList = list string  for char in string abcdefghijklmnopqrstuvwxyz 123456789 begin append keyList char end function key_check begin set keys = list for key in keyList begin if call is_pressed key == true begin append keys key end end return ke...
import keyboard #Using module keyboard from time import sleep keyList = ["\b"] for char in "abcdefghijklmnopqrstuvwxyz 123456789": keyList.append(char) def key_check(): keys = [] for key in keyList: if keyboard.is_pressed(key) == True: keys.append(key) return keys ...
Python
zaydzuhri_stack_edu_python
import pygame import time import random call init comment suitable music file is .wav set crash_sound = call Sound string Your music file for crash set display_width = 800 set display_height = 600 set car_width = 73 set screen = call set_mode tuple display_width display_height call set_caption string Dodge It!!! set bl...
import pygame import time import random pygame.init() crash_sound = pygame.mixer.Sound('Your music file for crash') #suitable music file is .wav display_width = 800 display_height = 600 car_width = 73 screen = pygame.display.set_mode((display_width, display_height)) pygame.display.set_caption("Dodge It!!!") blac...
Python
zaydzuhri_stack_edu_python
string Procedure: Same as isomorphic strings question. Complexity: n -> length of pattern Time: O(n) Space: O(n) class Solution begin function wordPattern self pattern s begin set words = split s string set tuple pLen wLen = tuple length pattern length words if pLen != wLen begin return false end set d = dict for i in...
""" Procedure: Same as isomorphic strings question. Complexity: n -> length of pattern Time: O(n) Space: O(n) """ class Solution: def wordPattern(self, pattern: str, s: str) -> bool: words = s.split(' ') pLen, wLen = len(pattern), len(words) if pLen != wLen: r...
Python
zaydzuhri_stack_edu_python
comment 'space' is the folder name, 'planet' is the name of the class file. comment this is enabled by the "__init___.py" file in the space directory from space.planet import Planet comment importing specific functions in the 'calc' file. from space.calc import planet_mass , planet_vol set naboo = call Planet string Na...
# 'space' is the folder name, 'planet' is the name of the class file. # this is enabled by the "__init___.py" file in the space directory from space.planet import Planet # importing specific functions in the 'calc' file. from space.calc import planet_mass, planet_vol naboo = Planet('Naboo', 300000, 8, 'Naboo System')...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python import sys if __name__ == string __main__ begin set infile = argv at 1 set d = dict for line in open infile begin set tuple actual predicted = split strip line string : set tuple actual predicted = tuple strip actual strip predicted if actual not in d begin set d at actual = dict end if predi...
#!/usr/bin/python import sys if __name__ == "__main__": infile = sys.argv[1] d = {} for line in open(infile): actual, predicted = line.strip().split(':') actual, predicted = actual.strip(), predicted.strip() if actual not in d: d[actual] = {} if predicted not ...
Python
zaydzuhri_stack_edu_python
string #################################################################### # author wudong # date 20190816 # 在连续的puckworld空间中测试DDPG # 状态空间和行为空间连续 # 状态空间:x,y # 行为空间:水平和竖直方向上的力的大小[-1,1] # ps 不知道是计算机的原因还是算法的原因,训练不动 ###################################################################### import gym from puckworld_continuous...
''' #################################################################### # author wudong # date 20190816 # 在连续的puckworld空间中测试DDPG # 状态空间和行为空间连续 # 状态空间:x,y # 行为空间:水平和竖直方向上的力的大小[-1,1] # ps 不知道是计算机的原因还是算法的原因,训练不动 ###################################################################### ''' import gym from puckworld_continuo...
Python
jtatman_500k
function validate_ip ip begin try begin set ipobj = call IP ip if call iptype == string PRIVATE begin print format string IP addresses {} will be ignored as it is in a private network range. ip set ip = none end end except ValueError as ve begin print format string Invalid IP: {} args set ip = none end finally begin re...
def validate_ip(ip): try: ipobj = IPy.IP(ip) if ipobj.iptype() == 'PRIVATE': print("IP addresses {} will be ignored as it is in a private network range.".format(ip)) ip = None except ValueError as ve: print("Invalid IP: {}".format(ve.args)) ip = None f...
Python
nomic_cornstack_python_v1
function __init__ self begin set black = 9 set red = 1 set striker = 1 set player1 = none set player2 = none set next_player = none end function
def __init__(self): self.black = 9 self.red = 1 self.striker = 1 self.player1 = None self.player2 = None self.next_player = None
Python
nomic_cornstack_python_v1
for _ in range m begin set tuple a b = map int split input set mawari at a = max mawari at a height at b set mawari at b = max mawari at b height at a end for i in range 1 n + 1 begin if height at i > mawari at i begin set ans = ans + 1 end end print ans
for _ in range(m): a, b = map(int, input().split()) mawari[a] = max(mawari[a], height[b]) mawari[b] = max(mawari[b], height[a]) for i in range(1,n+1): if height[i]> mawari[i]: ans += 1 print(ans)
Python
zaydzuhri_stack_edu_python
class Element begin function __init__ self name symbol number begin set name = name set symbol = symbol set number = number end function comment 6.6 function dump self begin print format string name: {}, symbol: {}, number: {} name symbol number end function end class set example = call Element string Hydrogen string H...
class Element(): def __init__(self, name, symbol, number): self.name = name self.symbol = symbol self.number = number # 6.6 def dump(self): print('name: {}, symbol: {}, number: {}'.format(self.name, self.symbol, self.number)) example = Element('Hydrogen', 'H', 1) # 6.5 di...
Python
zaydzuhri_stack_edu_python
function countWords textFile numReviews begin set word_counts = counter set i = 0 while i < numReviews begin set review = read line textFile if review is not string begin set word_counts = word_counts + counter split review end set i = i + 1 end return word_counts end function
def countWords(textFile, numReviews): word_counts = Counter() i = 0 while i < numReviews: review = textFile.readline() if review is not '': word_counts = word_counts + Counter(review.split()) i = i + 1 return word_counts
Python
nomic_cornstack_python_v1
function GetAdTaggingProfileFiles chrome_output_directory begin if chrome_output_directory is none begin return list end set gen_path = join path chrome_output_directory string gen string components string subresource_filter string tools set ruleset_path = join path gen_path string GeneratedRulesetData if not exists p...
def GetAdTaggingProfileFiles(chrome_output_directory): if chrome_output_directory is None: return [] gen_path = os.path.join(chrome_output_directory, 'gen', 'components', 'subresource_filter', 'tools') ruleset_path = os.path.join(gen_path, 'GeneratedRulesetData') if not os.path.ex...
Python
nomic_cornstack_python_v1
function start_scripter view begin global scripter_view set scripter_view = view end function
def start_scripter(view): global scripter_view scripter_view = view
Python
nomic_cornstack_python_v1
function get_date n begin return split glob glob format string /home/ana/data/hectochelle/tiles/gd1_{:d}/d* n at 0 string / at - 1 end function
def get_date(n): return glob.glob('/home/ana/data/hectochelle/tiles/gd1_{:d}/d*'.format(n))[0].split('/')[-1]
Python
nomic_cornstack_python_v1
function club_data_plus request page_title=none begin set common_data = call render_data request page_title string users_club_detail string users_events_todo string users_messages string users_alerts string users_events_done return common_data end function
def club_data_plus(request, page_title=None): common_data = Rendering.render_data(request, page_title, 'users_club_detail', 'users_events_todo', 'users_messages', ...
Python
nomic_cornstack_python_v1
function tile self pio parallel=none cli_progress=false **kwargs begin from par_util import resolve_parallelism set parallel = call resolve_parallelism parallel if parallel > 1 begin call _tile_parallel pio cli_progress parallel keyword kwargs end else begin call _tile_serial pio cli_progress keyword kwargs end comment...
def tile(self, pio, parallel=None, cli_progress=False, **kwargs): from .par_util import resolve_parallelism parallel = resolve_parallelism(parallel) if parallel > 1: self._tile_parallel(pio, cli_progress, parallel, **kwargs) else: self._tile_serial(pio, cli_pro...
Python
nomic_cornstack_python_v1
function subexerA begin set corners = list array list 0 0 array list 1 0 array list 1 / 2 square root 0.75 scatter plt *zip(*corners) marker=string . color=string red alpha=0.8 title plt string Test for equilateral triangle axis string equal show end function
def subexerA(): corners = [ np.array([0,0]), np.array([1,0]), np.array([1/2,m.sqrt(0.75)])] plt.scatter(*zip(*corners), marker=".", color="red", alpha=0.8) plt.title("Test for equilateral triangle") plt.axis("equal")...
Python
nomic_cornstack_python_v1
function analyseDecryption self filesAddress begin for i in filesAddress begin set result = list if i at slice length i - 5 : : == string crypt begin append result 0 end else begin append result 1 end end if sum result == 0 begin return true end else begin return false end end function
def analyseDecryption(self,filesAddress): for i in filesAddress: result=[] if i[len(i)-5:] == "crypt": result.append(0) else: result.append(1) if sum(result)==0: return True else : return False
Python
nomic_cornstack_python_v1
function output_to_file *args **kwargs begin call assert_param string df keyword kwargs call assert_param string filepath keyword kwargs call assert_param string desired_format keyword kwargs call validate_format kwargs at string desired_format if kwargs at string desired_format == string csv begin if string delimiter ...
def output_to_file(*args, **kwargs): assert_param('df', **kwargs) assert_param('filepath', **kwargs) assert_param('desired_format', **kwargs) validate_format(kwargs['desired_format']) if kwargs['desired_format'] == 'csv': if 'delimiter' in kwargs.keys() and kwargs['delimiter'] is not None...
Python
nomic_cornstack_python_v1
comment Author: Dimos from global_variables import get_dollars comment Collects money for 2 rounds and goes all in class CollectingBot begin function __init__ self begin set money = 0 set wins = list set round = 0 end function function play_round self winner win_amount begin set money = money + call get_dollars set ro...
# Author: Dimos from global_variables import get_dollars # Collects money for 2 rounds and goes all in class CollectingBot: def __init__(self): self.money = 0 self.wins = [] self.round = 0 def play_round(self, winner, win_amount): self.money += get_dollars() self.round...
Python
zaydzuhri_stack_edu_python
function validate_limits driver value limits name begin if not call validate value begin call raise_limits_error name value limits end else begin return value end end function
def validate_limits(driver, value, limits, name): if not limits.validate(value): raise_limits_error(name, value, limits) else: return value
Python
nomic_cornstack_python_v1
function has_intersection self obj begin set distance = square root power call get_x - __x 2 + power call get_y - __y 2 return distance <= call get_radius + call get_radius end function
def has_intersection(self, obj): distance = math.sqrt(math.pow(obj.get_x() - self.__x, 2) + math.pow(obj.get_y() - self.__y, 2)) return distance <= self.get_radius() + obj.get_radius()
Python
nomic_cornstack_python_v1
import json import os import pprint import csv import datetime with open join path string in_files string users.json string r as file begin set person_lst = loads read file end with open join path string in_files string books.csv newline=string as f begin set reader = reader f set header = next reader set books_lst = l...
import json import os import pprint import csv import datetime with open(os.path.join("in_files", "users.json"), "r") as file: person_lst = json.loads(file.read()) with open(os.path.join("in_files", "books.csv"), newline='') as f: reader = csv.reader(f) header = next(reader) books_lst = [] for row...
Python
zaydzuhri_stack_edu_python
from game.document.documents.prompt import Prompt from game.gameflow.actions.script_card_action import ScriptCardAction from game.scripting.discipline_card_script_runner import DisciplineCardScriptRunner class DisciplineAction extends ScriptCardAction begin function __init__ self data begin call __init__ data set promp...
from game.document.documents.prompt import Prompt from game.gameflow.actions.script_card_action import ScriptCardAction from game.scripting.discipline_card_script_runner import DisciplineCardScriptRunner class DisciplineAction(ScriptCardAction): def __init__(self, data) -> None: super().__init__(data) ...
Python
zaydzuhri_stack_edu_python
function __contains__ self value begin set current_node = front comment "walk" the linked list while current_node is not none begin comment if any node has a value == value, return True if value == value begin return true end set current_node = next_ end comment if you get to the end without finding value, comment retu...
def __contains__(self, value: object) -> bool: current_node = self.front # "walk" the linked list while current_node is not None: # if any node has a value == value, return True if current_node.value == value: return True current_node = current...
Python
nomic_cornstack_python_v1
function ls_files self patern=string * sort=none begin return list comprehension e for e in call ls patern sort if call is_file end function
def ls_files(self, patern="*", sort=None): return [e for e in self.ls(patern, sort) if e.is_file()]
Python
nomic_cornstack_python_v1
function direct_smoothing v f smoothness=0.1 Ltype=string cotangent begin if Ltype == string cotangent begin set L = call numpy_laplacian_cot v f end else if Ltype == string uniform begin set L = call numpy_laplacian_uniform v f end else begin raise AttributeError end set new_v = v + smoothness * dot v return new_v end...
def direct_smoothing(v, f, smoothness=0.1, Ltype='cotangent'): if Ltype == 'cotangent': L = numpy_laplacian_cot(v, f) elif Ltype == 'uniform': L = numpy_laplacian_uniform(v, f) else: raise AttributeError new_v = v + smoothness * L.dot(v) return new_v
Python
nomic_cornstack_python_v1
function solve self begin set user_list_bridge = call solve list_circle end function
def solve(self): self.user_list_bridge = self.solver.solve(self.list_circle)
Python
nomic_cornstack_python_v1
import time import random import sys set SLEEP_BETWEEN_ACTIONS = 0.5 set MAX_VAL = 100 set DICE_FACE = 6 set snakes = dict 8 4 ; 18 1 ; 26 10 ; 39 5 ; 51 6 ; 54 36 ; 56 1 ; 60 23 ; 75 28 ; 83 45 ; 85 59 ; 90 48 ; 92 25 ; 97 87 ; 99 63 set ladders = dict 3 20 ; 6 14 ; 11 28 ; 15 34 ; 17 74 ; 22 37 ; 38 59 ; 49 67 ; 57 7...
import time import random import sys SLEEP_BETWEEN_ACTIONS = 0.5 MAX_VAL = 100 DICE_FACE = 6 snakes = { 8: 4, 18: 1, 26: 10, 39: 5, 51: 6, 54: 36, 56: 1, 60: 23, 75: 28, 83: 45, 85: 59, 90: 48, 92: 25, 97: 87, 99: 63 } ladders = { 3: 20, 6: 14, ...
Python
zaydzuhri_stack_edu_python
function insert_sort A begin for i in range length A begin set key = A at i set j = i - 1 while j >= 0 and A at j > key begin set A at j + 1 = A at j set j = j - 1 end while else begin set A at j + 1 = key end end end function function bucket_sort A begin set A_length = length A set B = list comprehension list for _ i...
def insert_sort(A): for i in range(len(A)): key = A[i] j = i-1 while j >= 0 and A[j] > key: A[j+1] = A[j] j -= 1 else: A[j+1] = key def bucket_sort(A): A_length = len(A) B = [[] for _ in range(A_length)] for i in range(A_length): ...
Python
zaydzuhri_stack_edu_python
comment python 3 version import matplotlib.pyplot as plt import numpy as np comment Benjamin Klimko, PHYS 416 Spring 2018 comment Code originally by Frank Toffoletto, edited by B. Klimko comment The program calculates the height of two objects numerically and then based on theory and plots all comment define interpolat...
# python 3 version import matplotlib.pyplot as plt import numpy as np # Benjamin Klimko, PHYS 416 Spring 2018 #Code originally by Frank Toffoletto, edited by B. Klimko # The program calculates the height of two objects numerically and then based on theory and plots all # define interpolation functions def intrpf(xi, x...
Python
zaydzuhri_stack_edu_python
function generate_formatted_image color word icon_image begin set image_dims = tuple 1476 772 set text_vertical_offset = 130 set image_vertical_offset = 205 set image = call new string RGBA image_dims color=color comment Load the font and draw the word. set image_font = call truetype IMAGE_FONT text_vertical_offset set...
def generate_formatted_image(color: str, word: str, icon_image: str) -> None: image_dims = (1476, 772) text_vertical_offset = 130 image_vertical_offset = 205 image = Image.new("RGBA", image_dims, color=color) # Load the font and draw the word. image_font = ImageFont.truetype(IMAGE_FONT, text_ver...
Python
nomic_cornstack_python_v1
import m2secret import hashlib set PASSW = string SOMMELIER_APP function encrypt_userid userid begin string Encrypt userid to construct the URL for each user. set secret = call Secret call encrypt userid PASSW set serialized = call serialize return serialized end function function decrypt_userid encrypted_userid begin ...
import m2secret import hashlib PASSW = 'SOMMELIER_APP' def encrypt_userid(userid): """ Encrypt userid to construct the URL for each user. """ secret = m2secret.Secret() secret.encrypt(userid, PASSW) serialized = secret.serialize() return serialized def decrypt_userid(encrypted_userid): ...
Python
zaydzuhri_stack_edu_python
function setup_web begin from servers import setup_common from servers import setup_run_dirs comment execute(setup_common) from fabric.colors import yellow end function
def setup_web(): from .servers import setup_common from .servers import setup_run_dirs #execute(setup_common) from fabric.colors import yellow
Python
nomic_cornstack_python_v1
import pygame as pg from pygame.math import Vector2 function _rotate surface angle pivot offset begin string Rotate the surface around the pivot point Args: surface (pygame.Surface): The surface that is to be rotated angle (float): Rotate by this angle pivot (tuple, list, pygame.math.Vector2): The pivot point offset (p...
import pygame as pg from pygame.math import Vector2 def _rotate(surface, angle, pivot, offset): """Rotate the surface around the pivot point Args: surface (pygame.Surface): The surface that is to be rotated angle (float): Rotate by this angle pivot (tuple, list, pygame.math.Vector2): ...
Python
zaydzuhri_stack_edu_python
function create_project_hook self project_id url begin return call _post format string /projects/{0}/hooks project_id data=dict string url url end function
def create_project_hook(self, project_id, url): return self._post('/projects/{0}/hooks'.format(project_id), data={'url': url})
Python
nomic_cornstack_python_v1
function suma a b begin set salida = a + b return salida end function
def suma(a,b) : salida = a + b return salida
Python
zaydzuhri_stack_edu_python
set character = string A set unicode_value = ordinal character print unicode_value
character = 'A' unicode_value = ord(character) print(unicode_value)
Python
jtatman_500k
function plot_feature_correlations self begin set fig = figure figsize=tuple 18 18 tight_layout=true call suptitle string Feature correlations fontsize=24 call heatmap call corr method=string kendall linewidths=0.1 vmin=- 1.0 vmax=1.0 square=true linecolor=string white annot=true cmap=string PiYG save figure string dat...
def plot_feature_correlations(self): fig = plt.figure(figsize=(18,18), tight_layout=True) fig.suptitle('Feature correlations', fontsize=24) sns.heatmap(self.train_data.astype(float).corr(method='kendall'), linewidths=0.1, vmin=-1.0, vmax=1.0, square=True, linecolor='white',...
Python
nomic_cornstack_python_v1
function test_fma_nan_param_ninfarray_nanarray_okarray_none_a_409 self begin comment This version is expected to pass. call fma okarrayx okarrayy okarrayz matherrors=true comment This should raise an error. with assert raises ArithmeticError begin call fma ninfarrayx nanarrayy okarrayz end end function
def test_fma_nan_param_ninfarray_nanarray_okarray_none_a_409(self): # This version is expected to pass. arrayfunc.fma(self.okarrayx, self.okarrayy, self.okarrayz, matherrors=True) # This should raise an error. with self.assertRaises(ArithmeticError): arrayfunc.fma(self.ninfarrayx, self.nanarrayy, self.okarr...
Python
nomic_cornstack_python_v1
import csv import pandas as pd import numpy as np import scipy as sp import matplotlib.pyplot as plt from tqdm import tqdm from sklearn import linear_model from sklearn.metrics import mean_squared_error , r2_score set division = string College set year = string 2018 comment gender = "Women" set gender = string Men comm...
import csv import pandas as pd import numpy as np import scipy as sp import matplotlib.pyplot as plt from tqdm import tqdm from sklearn import linear_model from sklearn.metrics import mean_squared_error, r2_score division = "College" year = "2018" #gender = "Women" gender = "Men" #load rankings from fil...
Python
zaydzuhri_stack_edu_python
function mal bot trigger begin set synopsis = false set list_results = false set query = call group 2 if strip call group 3 == string -s begin set synopsis = true set query = replace call group 2 string -s string 1 end else if strip call group 3 == string -a begin set list_results = true set query = replace call group...
def mal(bot, trigger): synopsis = False list_results = False query = trigger.group(2) if trigger.group(3).strip() == '-s': synopsis = True query = trigger.group(2).replace('-s', '', 1) elif trigger.group(3).strip() == '-a': list_results = True query = trigger.group(2)...
Python
nomic_cornstack_python_v1
function insert self row begin if not loaded begin print string Database is not loaded return false end append rows row return true end function
def insert(self, row): if not self.loaded: print("Database is not loaded") return False self.rows.append(row) return True
Python
nomic_cornstack_python_v1
function m_array self value begin return string <array id="%s" typecode="%s" encoding="base64">%s</array> % tuple call register value typecode encode call tostring string base64 end function
def m_array(self, value): return '<array id="%s" typecode="%s" encoding="base64">%s</array>' % \ (self.register(value), value.typecode, value.tostring().encode('base64'))
Python
nomic_cornstack_python_v1
function portals_id_members_fk_put_with_http_info self id fk **kwargs begin set all_params = list string id string fk string data append all_params string callback append all_params string _return_http_data_only set params = locals for tuple key val in call iteritems params at string kwargs begin if key not in all_para...
def portals_id_members_fk_put_with_http_info(self, id, fk, **kwargs): all_params = ['id', 'fk', 'data'] all_params.append('callback') all_params.append('_return_http_data_only') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params:...
Python
nomic_cornstack_python_v1
function __init__ self layers begin set pnetwork = list for layer in layers begin append pnetwork call Perceptronlayer layer end end function
def __init__(self, layers): self.pnetwork = [] for layer in layers: self.pnetwork.append(perceptronlayer.Perceptronlayer(layer))
Python
nomic_cornstack_python_v1
string The main idea is to count all the occurring characters in a string. If you have a string like aba, then the result should be {'a': 2, 'b': 1}. from collections import Counter function count string begin comment Separate each character set empty_dict = dict if length string >= 1 begin for i in string begin set c...
"""The main idea is to count all the occurring characters in a string. If you have a string like aba, then the result should be {'a': 2, 'b': 1}.""" from collections import Counter def count(string): # Separate each character empty_dict = {} if len(string) >= 1: for i in string: count...
Python
zaydzuhri_stack_edu_python
import cv2 class KeyEvent begin function __init__ self init_params begin set continue_while = true set init_params = init_params set display = 0 end function function update_key self begin set value_key = call waitKey 1 if value_key == ordinal string q begin set continue_while = false end else if value_key == ordinal s...
import cv2 class KeyEvent(): def __init__(self, init_params): self.continue_while = True self.init_params = init_params self.display = 0 def update_key(self): self.value_key = cv2.waitKey(1) if self.value_key == ord('q'): self.continue_while = False ...
Python
zaydzuhri_stack_edu_python