code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function handle self begin set auth = false while true begin set request_packet = call recieve_from_socket request if not request_packet begin break end if auth begin set response = call exec_command request_packet call send_to_socket request end else begin set auth = call authenticate request_packet end end end functi...
def handle(self): auth = False while True: request_packet = RconPacket().recieve_from_socket(self.request) if not request_packet: break if auth: response = self.exec_command(request_packet) RconPacket(request_packet.pac...
Python
nomic_cornstack_python_v1
try begin from PIL import Image end except ImportError begin import Image end import pytesseract import time import os import asyncio set images = list directory string images * 2 comment Simple image to string set t0 = time for image in images begin set start = time print format string {}...starting image set translat...
try: from PIL import Image except ImportError: import Image import pytesseract import time import os import asyncio images = os.listdir("images") * 2 # Simple image to string t0 = time.time() for image in images: start = time.time() print("{}...starting".format(image)) translation = pytesseract.im...
Python
zaydzuhri_stack_edu_python
import sys insert path 0 string ../ import numpy as np import matplotlib.pyplot as plt from tqdm import trange import lightgrad as light import lightgrad.nn as nn from lightgrad.autograd.utils.profiler import Profiler class CNN extends Module begin function __init__ self begin call __init__ self set c1 = conv 2d 1 8 ke...
import sys sys.path.insert(0, "../") import numpy as np import matplotlib.pyplot as plt from tqdm import trange import lightgrad as light import lightgrad.nn as nn from lightgrad.autograd.utils.profiler import Profiler class CNN(nn.Module): def __init__(self): nn.Module.__init__(self) ...
Python
zaydzuhri_stack_edu_python
comment ISP - Zasada rozdzielenia interfejsów comment Złamanie ISP class Machine begin function print_doc self doc begin NotImplementedError end function function scan self doc begin NotImplementedError end function function fax self doc begin NotImplementedError end function end class class MultiFunctionPrinter extend...
# ISP - Zasada rozdzielenia interfejsów # Złamanie ISP class Machine: def print_doc(self, doc): NotImplementedError def scan(self, doc): NotImplementedError def fax(self, doc): NotImplementedError class MultiFunctionPrinter(Machine): def print_doc(self, doc): print(f...
Python
zaydzuhri_stack_edu_python
function get_me self begin set req_str = BASE_URL + BOT_REQUEST at co_name set req = get requests req_str return json req end function
def get_me(self): req_str = SETTING.BASE_URL + SETTING.BOT_REQUEST[inspect.currentframe().f_code.co_name] req = requests.get(req_str) return req.json()
Python
nomic_cornstack_python_v1
comment https://docs.python.org/2/library/xml.dom.minidom.html#module-xml.dom.minidom import xml.etree.ElementTree as ET import random , string function RandomNumber len begin set char_set = digits set text = join string random sample char_set * len len return text end function comment ************** TEST DATA - UPDAT...
# https://docs.python.org/2/library/xml.dom.minidom.html#module-xml.dom.minidom import xml.etree.ElementTree as ET import random,string def RandomNumber(len): char_set = string.digits text = ''.join(random.sample(char_set*len, len)) return text # ************** TEST DATA - UPDATE BEFORE RUNNING ****************...
Python
zaydzuhri_stack_edu_python
set c = list set a = split input append c a print string maximum element in the list is: max a
c=[] a=input().split() c.append(a) print("maximum element in the list is: ",max(a))
Python
zaydzuhri_stack_edu_python
import re set S = input set k = string keyence for i in range 0 length k + 1 begin set rs = string ^ + k at slice : i : + string .* + k at slice i : : + string $ if match rs S is not none begin print string YES break end end for else begin print string NO end
import re S = input() k = 'keyence' for i in range(0, len(k)+1): rs = '^' + k[:i] + '.*' + k[i:] + '$' if re.match(rs, S) is not None: print('YES') break else: print('NO')
Python
zaydzuhri_stack_edu_python
function account_link_group_includes self begin return get pulumi self string account_link_group_includes end function
def account_link_group_includes(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: return pulumi.get(self, "account_link_group_includes")
Python
nomic_cornstack_python_v1
function tasks self pipeline_id begin raise call NotImplementedError string Should implement tasks() end function
def tasks(self, pipeline_id): raise NotImplementedError('Should implement tasks()')
Python
nomic_cornstack_python_v1
from alogrithm import Algorithm class FirstFitAlgorithm extends Algorithm begin set name = string first_fit function __call__ self machine clock begin set accelerators = free_accelerators set tasks = tasks_which_has_waiting_instance set candidate_task = none set candidate_accelerator = none for accelerator in accelerat...
from .alogrithm import Algorithm class FirstFitAlgorithm(Algorithm): name = "first_fit" def __call__(self, machine, clock): accelerators = machine.free_accelerators tasks = machine.tasks_which_has_waiting_instance candidate_task = None candidate_accelerator = None for...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python2 from PIL import Image import os import sys import numpy as np
#!/usr/bin/python2 from PIL import Image import os import sys import numpy as np
Python
zaydzuhri_stack_edu_python
comment !python comment File happynumbers.py string Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends ...
#!python # File happynumbers.py """ Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are ...
Python
zaydzuhri_stack_edu_python
function test_weirdColorFormatting self begin call assertAssembledEqually string 1kinda valid black at string kinda valid call assertAssembledEqually string 999,999kinda valid green at string 9,999kinda valid call assertAssembledEqually string 1,2kinda valid black at blue at string kinda valid call assertAssembledEq...
def test_weirdColorFormatting(self): self.assertAssembledEqually("\x031kinda valid", A.fg.black["kinda valid"]) self.assertAssembledEqually( "\x03999,999kinda valid", A.fg.green["9,999kinda valid"] ) self.assertAssembledEqually( "\x031,2kinda valid", A.fg.black[A....
Python
nomic_cornstack_python_v1
string WEEK 4 June 2-8 Variables and Names set variables = string store and recall values, composed of 'name' = 'value' comment EXAMPLE F1.0 set age = 3 string DATA TYPES Integers (int) DEFINITION: An integer is a whole number and is treated as such when entered. Floats (float) DEFINITION: numeric values with decimals....
""" WEEK 4 June 2-8 Variables and Names """ variables = "store and recall values, composed of 'name' = 'value'" # EXAMPLE F1.0 age = 3 """ DATA TYPES Integers (int) DEFINITION: An integer is a whole number and is treated as such when entered. Floats (float) DEFINITION: numeric values with decimals. Floats store re...
Python
zaydzuhri_stack_edu_python
function match_allowed_origin self parsed_origin pattern begin if parsed_origin is none begin return false end comment Get ResultParse object set parsed_pattern = url parse lower pattern if hostname is none begin return false end if not scheme begin set pattern_hostname = hostname or pattern return call is_same_domain ...
def match_allowed_origin(self, parsed_origin, pattern): if parsed_origin is None: return False # Get ResultParse object parsed_pattern = urlparse(pattern.lower()) if parsed_origin.hostname is None: return False if not parsed_pattern.scheme: pa...
Python
nomic_cornstack_python_v1
from abc import ABC , abstractmethod comment Abstract Class class Bank extends ABC begin function bank_info self begin print string Welcome to bank end function decorator abstractmethod function interest self begin string Abstarct Method pass end function end class comment Sub class/ child class of abstract class class...
from abc import ABC, abstractmethod #Abstract Class class Bank(ABC): def bank_info(self): print("Welcome to bank") @abstractmethod def interest(self): "Abstarct Method" pass #Sub class/ child class of abstract class class SBI(Bank): def interest(self): "Implementation of abstra...
Python
zaydzuhri_stack_edu_python
from requests import get from requests.auth import HTTPBasicAuth from time import sleep from bs4 import BeautifulSoup import binascii comment The script makes the first request to natas19.natas.labs.overthewire.org, using username and password; comment It loops from 0 to MAX_PHPSSID (in this case 640), comment for each...
from requests import get from requests.auth import HTTPBasicAuth from time import sleep from bs4 import BeautifulSoup import binascii #The script makes the first request to natas19.natas.labs.overthewire.org, using username and password; # # #It loops from 0 to MAX_PHPSSID (in this case 640), # for each loop it # ...
Python
zaydzuhri_stack_edu_python
for i in range 1 number_of_rows + 1 begin if not i % 2 == 0 begin print string # * i end end
for i in range(1, number_of_rows + 1): if not i % 2 == 0: print("#"*i)
Python
zaydzuhri_stack_edu_python
function recover self reduced begin return dot reduced w + mu end function
def recover(self, reduced): return np.dot(reduced, self.w)+self.mu
Python
nomic_cornstack_python_v1
async function async_setup_entry hass config_entry async_add_entities begin decorator callback function async_add_binary_sensor binary_sensor begin string Add Z-Wave binary sensor. call async_add_entities list binary_sensor end function call async_dispatcher_connect hass string zwave_new_binary_sensor async_add_binary_...
async def async_setup_entry(hass, config_entry, async_add_entities): @callback def async_add_binary_sensor(binary_sensor): """Add Z-Wave binary sensor.""" async_add_entities([binary_sensor]) async_dispatcher_connect(hass, "zwave_new_binary_sensor", async_add_binary_sensor)
Python
nomic_cornstack_python_v1
function SetTabCtrlHeight self height begin set _requested_tabctrl_height = height comment if window is already initialized, recalculate the tab height if _dummy_wnd begin call UpdateTabCtrlHeight end end function
def SetTabCtrlHeight(self, height): self._requested_tabctrl_height = height # if window is already initialized, recalculate the tab height if self._dummy_wnd: self.UpdateTabCtrlHeight()
Python
nomic_cornstack_python_v1
for num in range 2 number begin if number % num == 0 begin print string It's not a prime number. end else begin print string It's a prime number. end end
for num in range(2, number): if number % num == 0: print("It's not a prime number.") else: print("It's a prime number.")
Python
zaydzuhri_stack_edu_python
function test_step self batch batch_idx begin set tuple x y = batch set pred = call forward x set loss = call m_loss_function pred y return loss end function
def test_step(self, batch, batch_idx): x, y = batch pred = self.forward(x) loss = self.m_loss_function(pred, y) return loss
Python
nomic_cornstack_python_v1
function management_clusters self begin return get pulumi self string management_clusters end function
def management_clusters(self) -> Sequence['outputs.GetPrivateCloudManagementClusterResult']: return pulumi.get(self, "management_clusters")
Python
nomic_cornstack_python_v1
function _get_flatchoices self begin return list comprehension tuple value label or name for e in enum end function
def _get_flatchoices(self): return [(e.value, e.label or e.name) for e in self.enum]
Python
nomic_cornstack_python_v1
import random print string Magic 8 Ball Fortunes print string Reveal your name and recieve a fortune. set name_for_number = input string Type name set rn = length name_for_number function eight_ball random_number begin string The random number to tell a corresponding fortune. if random_number == 1 begin return string L...
import random print('Magic 8 Ball Fortunes') print('Reveal your name and recieve a fortune.') name_for_number = input('Type name ') rn = len(name_for_number) def eight_ball(random_number): ''' The random number to tell a corresponding fortune.''' if random_number == 1: return 'Look forward and the pa...
Python
zaydzuhri_stack_edu_python
function get_comp_graph self begin return call create_computational_graph self end function
def get_comp_graph(self): return create_computational_graph(self)
Python
nomic_cornstack_python_v1
from gpiozero import DistanceSensor from time import sleep from pythonosc import osc_message_builder , udp_client import argparse import sys function control spip begin set sensor = call DistanceSensor echo=17 trigger=4 threshold_distance=0.5 set sensor2 = call DistanceSensor echo=23 trigger=24 threshold_distance=0.5 c...
from gpiozero import DistanceSensor from time import sleep from pythonosc import osc_message_builder, udp_client import argparse import sys def control(spip): sensor = DistanceSensor(echo=17, trigger=4,threshold_distance=0.5) sensor2 = DistanceSensor(echo=23, trigger=24,threshold_distance=0.5) # make sure...
Python
zaydzuhri_stack_edu_python
import subprocess as sp import threading import time import os class RTPTools begin function __init__ self begin set proc = none set lock = lock end function function isalive self begin string Checks if the process is non-'None', and if so returns its poll status. return proc is not none and poll proc is none end funct...
import subprocess as sp import threading import time import os class RTPTools: def __init__(self): self.proc = None self.lock = threading.Lock() def isalive(self): """ Checks if the process is non-'None', and if so returns its poll status. """ return se...
Python
zaydzuhri_stack_edu_python
comment for문 _ 코드 작성 for i in list 10 20 30 begin print i end
#for문 _ 코드 작성 for i in [10, 20, 30]: print(i)
Python
zaydzuhri_stack_edu_python
function _get_monthly_suffix_name date begin return format string {0!s} string format time date string %Y.%m end function
def _get_monthly_suffix_name(date): return "{0!s}".format(date.strftime('%Y.%m'))
Python
nomic_cornstack_python_v1
function random_update ratings begin set names = keys ratings set random_rest = random choice names end function
def random_update(ratings): names = ratings.keys() random_rest = random.choice(names)
Python
nomic_cornstack_python_v1
function check_rts self begin if call have_duplicate_packet incoming_packet begin call send_ack incoming_packet at string source end else begin call send_cts set current_state = string WAIT_DATA end end function
def check_rts(self): if self.layercake.net.have_duplicate_packet(self.incoming_packet): self.send_ack(self.incoming_packet["source"]) else: self.send_cts() self.fsm.current_state = "WAIT_DATA"
Python
nomic_cornstack_python_v1
function company_prefix self begin string Return the identifier's company prefix part. set offset = EXTRA_DIGITS return _id at slice offset : _ref_idx : end function
def company_prefix(self): """Return the identifier's company prefix part.""" offset = self.EXTRA_DIGITS return self._id[offset:self._ref_idx]
Python
jtatman_500k
function plotdft_paper td figw figh figdpi fontsz ylim border ylabel xaxisticks yaxisticks xlimhz color lw begin set m = td at string peakf comment fontv = mpl.font_manager.FontProperties() comment Uncomment line below to set the font to verdana; the default matplotlib font is very comment similar (just slightly narrow...
def plotdft_paper(td, figw, figh, figdpi, fontsz, ylim, border, ylabel, xaxisticks, yaxisticks, xlimhz, color, lw): m = td['peakf'] #fontv = mpl.font_manager.FontProperties() # Uncomment line below to set the font to verdana; the default matplotlib font is very #similar (just sli...
Python
nomic_cornstack_python_v1
import sys from InitializeDB import connect_db try begin set tuple conn c = call connect_db end except Exception begin print string Error connecting to database. Exiting.. exit 1 end class Elder begin function registration self begin string Class method used to register elder couples. set eid = integer input string Cre...
import sys from InitializeDB import connect_db try: conn, c = connect_db() except Exception: print("Error connecting to database. Exiting..") sys.exit(1) class Elder: def registration(self): """ Class method used to register elder couples. """ eid = int(input("\nCreate login (enter u...
Python
zaydzuhri_stack_edu_python
function GetConsiderLeadersAsLines self begin return call InvokeTypes 65994 LCID 1 tuple 11 0 tuple end function
def GetConsiderLeadersAsLines(self): return self._oleobj_.InvokeTypes(65994, LCID, 1, (11, 0), (),)
Python
nomic_cornstack_python_v1
function trustRootValid self begin if not trust_root begin return true end set tr = parse TrustRoot trust_root if tr is none begin raise call MalformedTrustRoot message trust_root end if return_to is not none begin return call validateURL return_to end else begin return true end end function
def trustRootValid(self): if not self.trust_root: return True tr = TrustRoot.parse(self.trust_root) if tr is None: raise MalformedTrustRoot(self.message, self.trust_root) if self.return_to is not None: return tr.validateURL(self.return_to) els...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Tue Nov 20 12:16:13 2018 @author: hubert import pickle set DEBUG = false function readfiltres begin string Lire la liste des filtres sauvegardée set filename = string data/filtres.fil if DEBUG begin print string readfiltes filename end with o...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 20 12:16:13 2018 @author: hubert """ import pickle DEBUG = False def readfiltres(): ''' Lire la liste des filtres sauvegardée ''' filename = 'data/filtres.fil' if DEBUG: print("readfiltes", filename) with open(filename, "r...
Python
zaydzuhri_stack_edu_python
function _generate_and_test self use_task_queue num_initial_executions num_tasks_generated num_new_executions num_active_executions pipeline=none expected_exec_nodes=none begin return call run_generator_and_test self _mlmd_connection SyncPipelineTaskGenerator pipeline or _pipeline _task_queue use_task_queue _mock_servi...
def _generate_and_test(self, use_task_queue, num_initial_executions, num_tasks_generated, num_new_executions, num_active_executions, pipeline=None, ...
Python
nomic_cornstack_python_v1
function _pull_handler self name ID begin set new_tensor = call gather_row _data_store at name ID return new_tensor end function
def _pull_handler(self, name, ID): new_tensor = F.gather_row(self._data_store[name], ID) return new_tensor
Python
nomic_cornstack_python_v1
comment USAGE comment python barcode_scanner_image.py --image barcode_example.png comment import the necessary packages from pyzbar import pyzbar import zbar import argparse import cv2 import numpy as np function image_resize image width=none height=none inter=INTER_AREA begin comment initialize the dimensions of the i...
# USAGE # python barcode_scanner_image.py --image barcode_example.png # import the necessary packages from pyzbar import pyzbar import zbar import argparse import cv2 import numpy as np def image_resize(image, width = None, height = None, inter = cv2.INTER_AREA): # initialize the dimensions of the image to be re...
Python
zaydzuhri_stack_edu_python
string Copyright (C) 2019 NVIDIA Corporation. All rights reserved. Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode). Based on https://github.com/NVlabs/SPADE/blob/master/models/pix2pix_model.py import torch import torch.nn as nn import torch.nn.functional as F imp...
""" Copyright (C) 2019 NVIDIA Corporation. All rights reserved. Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode). Based on https://github.com/NVlabs/SPADE/blob/master/models/pix2pix_model.py """ import torch import torch.nn as nn import torch.nn.functional as...
Python
zaydzuhri_stack_edu_python
comment ! /usr/bin/env python comment Code to demux the GBS raw sequence files using the li- # comment rary number. The input files are read from other files # comment You could import using the grammar 'from sys import argv' so you could type comment argv instead of sys.argv with each use... but know that this decreas...
#! /usr/bin/env python ########################################################## # Code to demux the GBS raw sequence files using the li- # # rary number. The input files are read from other files # ########################################################## # You could import using the grammar 'from sys import argv' ...
Python
zaydzuhri_stack_edu_python
function get_ipv6_list begin set ipv6 = get __grains__ string ipv6 return join string list comprehension string [ + ip + string ] for ip in ipv6 end function
def get_ipv6_list(): ipv6 = __grains__.get("ipv6") return " ".join(["[" + ip + "]" for ip in ipv6])
Python
nomic_cornstack_python_v1
import argparse from collections import Counter import time import pandas as pd from pathlib import Path import numpy as np import numpy.ma as ma import matplotlib.pyplot as plt from skimage.io import imread , imshow from sklearn import metrics from sklearn.cluster import DBSCAN from sklearn.decomposition import PCA fr...
import argparse from collections import Counter import time import pandas as pd from pathlib import Path import numpy as np import numpy.ma as ma import matplotlib.pyplot as plt from skimage.io import imread, imshow from sklearn import metrics from sklearn.cluster import DBSCAN from sklearn.decomposition import PCA f...
Python
zaydzuhri_stack_edu_python
function average array begin set sum1 = sum set arr set len1 = length set arr set avg1 = sum1 / len1 return avg1 end function set n = integer input set arr = list map int split input set result = call average arr print result
def average(array): sum1 = sum(set(arr)) len1 = len(set(arr)) avg1 = sum1 / len1 return avg1 n=int(input()) arr=list(map(int,input().split())) result = average(arr) print(result)
Python
zaydzuhri_stack_edu_python
import numpy as np import tensorflow as tf from advoc.audioio import decode_audio from advoc.spectral import waveform_to_melspec_tf , stft_tf function decode_extract_and_batch fps batch_size slice_len audio_fs=22050 audio_mono=true audio_normalize=false decode_fastwav=false decode_parallel_calls=1 extract_type=none ext...
import numpy as np import tensorflow as tf from advoc.audioio import decode_audio from advoc.spectral import waveform_to_melspec_tf, stft_tf def decode_extract_and_batch( fps, batch_size, slice_len, audio_fs=22050, audio_mono=True, audio_normalize=False, decode_fastwav=False, decode_p...
Python
zaydzuhri_stack_edu_python
class Employee begin function __init__ self name salary department begin set name = name set salary = salary set department = department end function end class set emp = call Employee string John 10000 string Accounting print name comment Output: John
class Employee: def __init__(self, name, salary, department): self.name = name self.salary = salary self.department = department emp = Employee("John", 10000, "Accounting") print(emp.name) # Output: John
Python
jtatman_500k
string GRID LAYOUT Jeff Thompson | 2017 | jeffreythompson.org Converts the cloud of 2D data from t-SNE into a nice grid using Rasterfairy. import rasterfairy comment import GridOptimizer import numpy as np comment how many images across? (essentially sqrt(num_images)) set grid_width = 315 comment ditto height set grid_...
''' GRID LAYOUT Jeff Thompson | 2017 | jeffreythompson.org Converts the cloud of 2D data from t-SNE into a nice grid using Rasterfairy. ''' import rasterfairy # import GridOptimizer import numpy as np grid_width = 315 # how many images across? (essentially sqrt(num_images)) grid_height = 395 # ...
Python
zaydzuhri_stack_edu_python
function test_metadata aggregator mocked_request mocked_metadata_request datadog_agent begin set instance = HDFS_DATANODE_CONFIG at string instances at 0 set hdfs_datanode = call HDFSDataNode string hdfs_datanode dict list instance comment Run the check once set check_id = CHECK_ID call check instance comment Make sur...
def test_metadata(aggregator, mocked_request, mocked_metadata_request, datadog_agent): instance = HDFS_DATANODE_CONFIG['instances'][0] hdfs_datanode = HDFSDataNode('hdfs_datanode', {}, [instance]) # Run the check once hdfs_datanode.check_id = CHECK_ID hdfs_datanode.check(instance) # Make sure...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import numpy as np import sys from classes import Quaternion from utils import show_robot , shows_origins comment ------ Variables ------ comment Número de variables set number_var = 4 if length argv != number_var + 1 begin exit string El número de articulaciones no es el correcto ( + stri...
# -*- coding: utf-8 -*- import numpy as np import sys from classes import Quaternion from utils import show_robot, shows_origins # ------ Variables ------ # Número de variables number_var = 4 if len(sys.argv) != number_var + 1: sys.exit('El número de articulaciones no es el correcto (' + str(number_var) + ')') ...
Python
zaydzuhri_stack_edu_python
function find self interval begin set contig = contig if contig not in interlaps begin return end yield from find interlaps at contig interval end function
def find(self, interval: GenomeInterval) -> Iterator[GenomeInterval]: contig = interval.contig if contig not in self.interlaps: return yield from self.interlaps[contig].find(interval)
Python
nomic_cornstack_python_v1
import cv2 import numpy as np set img = call imread string ../Result_Images/eye1.jpg set gray = call cvtColor img COLOR_BGR2GRAY set minin = 1000000 set minj = 0 set mini = 0 for i in range shape at 0 begin for j in range shape at 1 begin if gray at i at j < minin begin set minin = gray at i at j set mini = i set minj ...
import cv2 import numpy as np img = cv2.imread('../Result_Images/eye1.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) minin = 1000000 minj=0 mini=0 for i in range(gray.shape[0]): for j in range(gray.shape[1]): if (gray[i][j]<minin): minin=gray[i][j] mini=i minj=j print(mini,minj) cv2.circle(img,(min...
Python
zaydzuhri_stack_edu_python
comment https://leetcode.com/problems/reverse-integer/ comment 1. Restating the problem comment # Reverse the digits of a number. Emphasis on digits because it can be a negative symbol too. comment 2. Ask clarifying questions comment - Why does the 32 bit signed matter? What will this be used for? comment - Any time/sp...
# https://leetcode.com/problems/reverse-integer/ # 1. Restating the problem # # Reverse the digits of a number. Emphasis on digits because it can be a negative symbol too. # 2. Ask clarifying questions # - Why does the 32 bit signed matter? What will this be used for? # - Any time/space constraints? # 3. State y...
Python
zaydzuhri_stack_edu_python
from copy import deepcopy from sys import stdin class MatrixError extends BaseException begin function __init__ self matrix1 matrix2 begin set matrix1 = matrix1 set matrix2 = matrix2 end function end class class Matrix begin function __init__ self list_of_lists begin set matrix = deep copy list_of_lists end function fu...
from copy import deepcopy from sys import stdin class MatrixError(BaseException): def __init__(self, matrix1, matrix2): self.matrix1 = matrix1 self.matrix2 = matrix2 class Matrix: def __init__(self, list_of_lists): self.matrix = deepcopy(list_of_lists) def __str__(self): s...
Python
zaydzuhri_stack_edu_python
function get_cpu_jiffies self begin try begin set path = format string /proc/{}/stat call getpid with open path string r as f begin set fields = split strip read f string return call Jiffies user=integer fields at 13 system=integer fields at 14 end end except IOError as e begin return none end except ValueError as e be...
def get_cpu_jiffies(self): try: path = "/proc/{}/stat".format(os.getpid()) with open(path, 'r') as f: fields = f.read().strip().split(" ") return Jiffies(user=int(fields[13]), system=int(fields[14])) except IOError as e: return None ...
Python
nomic_cornstack_python_v1
function test_add_to_nonEmp begin set code = string nonemp += test with call StringIO code as f begin with raises ParseException begin set ast = call parse_it f end end end function
def test_add_to_nonEmp(): code = "nonemp += test" with StringIO(code) as f: with pytest.raises(pyparsing.ParseException): ast = parser.parse_it(f)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding: utf-8 comment # Distâncias e matrizes comment A matriz de distância é feita através da utilização da função `pdist`; como já mencionado a distância euclidiana entre dois pontos $p$ e $q$ é $ d\left( p,q\right) = \sqrt {\sum _{i=1}^{n} \left( q_{i}-p_{i}\right)^2 }$, para $n$...
#!/usr/bin/env python # coding: utf-8 # # Distâncias e matrizes # # A matriz de distância é feita através da utilização da função `pdist`; como já mencionado a distância euclidiana entre dois pontos $p$ e $q$ é $ d\left( p,q\right) = \sqrt {\sum _{i=1}^{n} \left( q_{i}-p_{i}\right)^2 }$, para $n$ dimensões. De forma...
Python
zaydzuhri_stack_edu_python
from classes import Board function parse cmd game_gestion begin set data = split cmd try begin return call data at slice 1 : : game_gestion end except KeyError begin return 0 end end function function start data game_gestion begin try begin if length data != 1 begin print string ERROR message - unsupported size retur...
from classes import Board def parse(cmd, game_gestion): data = cmd.split() try: return CMD[data[0]](data[1:], game_gestion) except KeyError: return 0 def start(data, game_gestion): try: if (len(data) != 1): print("ERROR message - unsupported size") return 84 size = int(data[0]) if (size < 2): p...
Python
zaydzuhri_stack_edu_python
function onDestroyOptionsMenu self begin pass end function
def onDestroyOptionsMenu(self): pass
Python
nomic_cornstack_python_v1
from exercicio.model.reacao_model import ReacaoModel class Reacao begin function __init__ self begin set model = call ReacaoModel 1 1 1 1 end function function salvar self model begin set reacao = open string C:/Users/900145/Documents/PythonPro/Amdev/exercicio/arquivos_txt/reacao.txt string a set tipo_reacao = string L...
from exercicio.model.reacao_model import ReacaoModel class Reacao: def __init__(self): self.model = ReacaoModel(1,1,1,1) def salvar(self,model:ReacaoModel): reacao = open('C:/Users/900145/Documents/PythonPro/Amdev/exercicio/arquivos_txt/reacao.txt', 'a') self.model.tipo_reacao = 'Like...
Python
zaydzuhri_stack_edu_python
function compute_clips self num_frames step frame_rate=none begin set num_frames = num_frames set step = step set frame_rate = frame_rate set clips = list set resampling_idxs = list comment print('length of video_pts',len(self.video_pts),'length of video_paths',len(self.video_paths)) for tuple video_pts fps in zip vi...
def compute_clips(self, num_frames, step, frame_rate=None): self.num_frames = num_frames self.step = step self.frame_rate = frame_rate self.clips = [] self.resampling_idxs = [] # print('length of video_pts',len(self.video_pts),'length of video_paths',len(self.video_paths)...
Python
nomic_cornstack_python_v1
function __handle_primitive_event pattern statistics nested_topologies nested_arrival_rates nested_cost nested_args begin append nested_topologies none append nested_args none append nested_cost none append nested_arrival_rates pop statistics at ARRIVAL_RATES 0 return tuple pattern nested_topologies nested_arrival_rate...
def __handle_primitive_event(pattern, statistics, nested_topologies, nested_arrival_rates, nested_cost, nested_args): nested_topologies.append(None) nested_args.append(None) nested_cost.append(None) nested_arrival_rates.append(statistics[StatisticsTypes.A...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Tue Aug 25 19:09:27 2020 @author: Pawan string You are given words. Some words may repeat. For each word, output its number of occurrences. The output order should correspond with the input order of appearance of the word. See the sample input/output for clarification. No...
# -*- coding: utf-8 -*- """ Created on Tue Aug 25 19:09:27 2020 @author: Pawan """ ''' You are given words. Some words may repeat. For each word, output its number of occurrences. The output order should correspond with the input order of appearance of the word. See the sample input/output for clarification. ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment Copyright (c) 2015 Baidu.com, Inc. All Rights Reserved string File: config.py Author: baidu(baidu@baidu.com) Date: 2015/10/13 21:14:18 import os import ConfigParser import utils set CONF = none class Conf extends dict begin set __getattr__ = __getitem__...
#!/usr/bin/env python # -*- coding: utf-8 -*- ######################################################################## # # Copyright (c) 2015 Baidu.com, Inc. All Rights Reserved # ######################################################################## """ File: config.py Author: baidu(baidu@baidu.com) Date: 2015/1...
Python
zaydzuhri_stack_edu_python
import numpy as np import matplotlib.pyplot as plt from scipy.signal import argrelextrema set infile = open string build-Cpp-Desktop-Debug/variables.txt string r set number_of_planets = 0 set steps = 0 for line in infile begin set words = split line set steps = integer words at 0 set number_of_planets = integer words a...
import numpy as np import matplotlib.pyplot as plt from scipy.signal import argrelextrema infile = open("build-Cpp-Desktop-Debug/variables.txt", "r") number_of_planets = 0 steps = 0 for line in infile: words = line.split() steps = int(words[0]) number_of_planets = int(words[1]) infile.close() infile = ope...
Python
zaydzuhri_stack_edu_python
function plot_standardized_pud pud_shp_4plot begin set shp = call read_file pud_shp_4plot comment Create a figure of the desired size: set fig = figure figsize=tuple 10 10 set ax = call axes call set_aspect string equal grid false call tick_params axis=string both which=string both right=string off left=string off bott...
def plot_standardized_pud(pud_shp_4plot): shp = gpd.read_file(pud_shp_4plot) # Create a figure of the desired size: fig = plt.figure(figsize=(10,10)) ax = plt.axes() ax.set_aspect('equal') ax.grid(False) plt.tick_params( axis='both', which='both', right='off', ...
Python
nomic_cornstack_python_v1
function op pos arr begin set opcode = arr at pos set in_pos_1 = arr at pos + 1 set in_pos_2 = arr at pos + 2 set out_pos = arr at pos + 3 if opcode == 1 begin set arr at out_pos = arr at in_pos_1 + arr at in_pos_2 end else if opcode == 2 begin set arr at out_pos = arr at in_pos_1 * arr at in_pos_2 end else if opcode =...
def op(pos, arr): opcode = arr[pos] in_pos_1 = arr[pos+1] in_pos_2 = arr[pos+2] out_pos = arr[pos+3] if opcode == 1: arr[out_pos] = arr[in_pos_1] + arr[in_pos_2] elif opcode == 2: arr[out_pos] = arr[in_pos_1] * arr[in_pos_2] elif opcode == 99: pass else: ...
Python
zaydzuhri_stack_edu_python
comment The below trick is applicable to your custom Classes, comment Objects as well as complex data structures such as JSON import heapq set grades = list 32 43 654 34 132 66 99 532 comment The 3 largest values in a list print call nlargest 3 grades set stocks = list dict string ticker string GOOG ; string price 520....
# The below trick is applicable to your custom Classes, # Objects as well as complex data structures such as JSON import heapq grades = [32, 43, 654, 34, 132, 66, 99, 532] # The 3 largest values in a list print(heapq.nlargest(3, grades)) stocks = [ {'ticker': 'GOOG', 'price': 520.54}, {'ticker': 'FB', 'price...
Python
zaydzuhri_stack_edu_python
function run_ab3dmot classname pose_dir dets_dump_dir tracks_dump_dir max_age=3 min_hits=1 min_conf=0.3 match_algorithm=string h match_threshold=4 match_distance=string iou p=call eye 10 thr_estimate=0.8 thr_prune=0.1 ps=0.9 begin set dl = call SimpleArgoverseTrackingDataLoader data_dir=pose_dir labels_dir=dets_dump_di...
def run_ab3dmot( classname: str, pose_dir: str, dets_dump_dir: str, tracks_dump_dir: str, max_age: int = 3, min_hits: int = 1, min_conf: float = 0.3, match_algorithm: str = 'h', match_threshold: float = 4, match_distance: float = 'iou', p: np.ndarray = np.eye(10), thr_es...
Python
nomic_cornstack_python_v1
function test_get_tables_restaurant_not_found self client db begin set restaurant_id = 100 set response = get client string /restaurants/ + string restaurant_id + string /tables follow_redirects=true assert status_code == 404 set json_data = json assert json_data at string message == string Restaurant not found end fun...
def test_get_tables_restaurant_not_found(self, client, db): restaurant_id = 100 response = client.get( "/restaurants/" + str(restaurant_id) + "/tables", follow_redirects=True ) assert response.status_code == 404 json_data = response.json assert json_data["mes...
Python
nomic_cornstack_python_v1
function to_json self begin return dict string source_ns source_ns ; string source_id source_id ; string target_ns target_ns ; string target_id target_id ; string rel_type rel_type ; string data data end function
def to_json(self): return { "source_ns": self.source_ns, "source_id": self.source_id, "target_ns": self.target_ns, "target_id": self.target_id, "rel_type": self.rel_type, "data": self.data, }
Python
nomic_cornstack_python_v1
function add_me self data begin debug string Executing add me set person = call add_to_queue data if not person begin call create_message string Failed to add to queue because queue is already at maximum of " + string QUEUE_THRESHOLD + string " roomId=data at string roomId end else begin call list_queue data after=ADD ...
def add_me(self, data): logger.debug("Executing add me") person = self.q.add_to_queue(data) if not person: self.create_message( 'Failed to add to queue because queue is already at maximum of "' + str(QUEUE_THRESHOLD) + '"', roomId=data['roomId'] ...
Python
nomic_cornstack_python_v1
function square_numbers nums begin return list comprehension num ^ 2 for num in nums end function
def square_numbers(nums): return [num ** 2 for num in nums]
Python
jtatman_500k
import numpy as np import tensorflow.compat.v1 as tf from matplotlib import pyplot as plt call disable_v2_behavior set x_data = linear space 0 10 10 + uniform - 1.5 1.5 10 set y_label = linear space 0 10 10 + uniform - 1.5 1.5 10 plot x_data y_label string * title plt string Linear points with noise show comment y = mx...
import numpy as np import tensorflow.compat.v1 as tf from matplotlib import pyplot as plt tf.disable_v2_behavior() x_data = np.linspace(0, 10, 10) + np.random.uniform(-1.5, 1.5, 10) y_label = np.linspace(0, 10, 10) + np.random.uniform(-1.5, 1.5, 10) plt.plot(x_data, y_label, '*') plt.title('Linear points with noise...
Python
zaydzuhri_stack_edu_python
string We implement a Perceptron. References : - P. Vincent, H. Larochelle, Y. Bengio, P.A. Manzagol: Extracting and Composing Robust Features with Denoising Autoencoders, ICML'08, 1096-1103, 2008 - Y. Bengio, P. Lamblin, D. Popovici, H. Larochelle: Greedy Layer-Wise Training of Deep Networks, Advances in Neural Inform...
""" We implement a Perceptron. References : - P. Vincent, H. Larochelle, Y. Bengio, P.A. Manzagol: Extracting and Composing Robust Features with Denoising Autoencoders, ICML'08, 1096-1103, 2008 - Y. Bengio, P. Lamblin, D. Popovici, H. Larochelle: Greedy Layer-Wise Training of Deep Networks, Advance...
Python
zaydzuhri_stack_edu_python
function format_position df begin set df at string FantPos = upper str return df end function
def format_position(df): df['FantPos'] = df['FantPos'].str.upper() return df
Python
nomic_cornstack_python_v1
import matplotlib.pyplot as plt import numpy as np import serial import time comment time vector; create Fs samples between 0 and 1.0 sec. set t = array range 0 10 0.1 set data = zeros 400 set x = zeros 100 set y = zeros 100 set z = zeros 100 set tilt = zeros 100 set serdev = string /dev/ttyACM0 set s = call Serial ser...
import matplotlib.pyplot as plt import numpy as np import serial import time t = np.arange(0,10,0.1) # time vector; create Fs samples between 0 and 1.0 sec. data=np.zeros(400) x=np.zeros(100) y=np.zeros(100) z=np.zeros(100) tilt=np.zeros(100) serdev = '/dev/ttyACM0' s = serial.Serial(serdev,115200) for i in r...
Python
zaydzuhri_stack_edu_python
function beginPath self identifier=none begin assert not isOpenPath msg string %s.beginPath: Pen path is already open % __name__ set isOpenPath = true call beginPath identifier end function
def beginPath(self, identifier=None): assert not self.isOpenPath, ('%s.beginPath: Pen path is already open' % self.__class__.__name__) self.isOpenPath = True self.bp.beginPath(identifier)
Python
nomic_cornstack_python_v1
function get_output command element ctx numerical_ref=none begin set element_path : str = path set element_path = element_path + string /output/*[@id=' { element } '] set element = call get_language_element element_path lang return call convert element ctx=ctx numerical_ref=numerical_ref end function
def get_output(command: Command, element: str, ctx: Context, *, numerical_ref: int = None) -> Output: element_path: str = command.path element_path += f"/output/*[@id='{element}']" element = LanguageManager.get_language_element(element_path, ctx.lang) return convert(element, ctx=ctx, nu...
Python
nomic_cornstack_python_v1
function test_square_to_spherical_coordinates_shape_exception_not_raised self *shape begin call assert_exception_is_not_raised square_to_spherical_coordinates shape end function
def test_square_to_spherical_coordinates_shape_exception_not_raised( self, *shape): self.assert_exception_is_not_raised( math_helpers.square_to_spherical_coordinates, shape)
Python
nomic_cornstack_python_v1
function createJS self begin set js = string function highlight(code) { var newcode = code; var configs = new Array(); //Registers configs["#81BEF7"] = [/([ |,](eax|ax|ah|al))/g, /([ |,](ebx|bx|bh|bl))/g, /([ |,](ecx|cx|ch|cl))/g, /([ |,](edx|dx|dh|dl))/g, /([ |,](esi|si))/g, /([ |,](edi|di))/g, /([ |,](ebp|bp))/g, /([...
def createJS(self): self.js = """ function highlight(code) { var newcode = code; var configs = new Array(); //Registers configs["#81BEF7"] = [/([ |,](eax|ax|ah|al))/g, /([ |,](ebx|bx|bh|bl))/g, /([ |,](ecx|cx|ch|cl))/g, /([ |,](edx|dx|dh|dl))/g, /([ ...
Python
nomic_cornstack_python_v1
function abspath self path begin comment Return it if it's already an absolute path if path == absolute path path path begin return path end comment Get root path, or use script directory set root_path = get attribute self string root_path none if root_path is none begin set root_path = path at 0 end comment Add root p...
def abspath(self, path): # Return it if it's already an absolute path if path == os.path.abspath(path): return path # Get root path, or use script directory root_path = getattr(self, 'root_path', None) if root_path is None: root_path = sys.path[0]...
Python
nomic_cornstack_python_v1
set a = 10 set b = 20 set soma = a + b print string A soma dos números é: soma set x = 10 set y = 30 set x = x + 10 set y = x + 10 print x set x = x + y print string A soma de x = x + y é igual a: x set x = 50 set y = 20 set aux = x set x = y set y = aux print x print y set a = 1 set b = 2 print string a + 2 * b é igua...
a = 10 b = 20 soma = a +b print("A soma dos números é:", soma) x = 10 y = 30 x = x + 10 y = x + 10 print (x) x = x + y print ("A soma de x = x + y é igual a:", x) x = 50 y = 20 aux = x x=y y = aux print (x) print (y) a = 1 b = 2 print ("a + 2 * b é igual a:", a + 2 * b)
Python
zaydzuhri_stack_edu_python
function get_events_stations fname_all_geoNet_stats=none loc_all_geoNet_stats=none loc_Vol1=join string / list get current directory string Vol1 save_stats=false fname=none loc=get current directory begin set all_geoNet_stats = call read_statsll loc_all_geoNet_stats fname_all_geoNet_stats set event_stats_V1A = glob joi...
def get_events_stations( fname_all_geoNet_stats=None, loc_all_geoNet_stats=None, loc_Vol1="/".join([os.getcwd(), "Vol1"]), save_stats=False, fname=None, loc=os.getcwd(), ): all_geoNet_stats = read_statsll(loc_all_geoNet_stats, fname_all_geoNet_stats) event_stats_V1A = glob("/".join([lo...
Python
nomic_cornstack_python_v1
function save self **kwargs begin comment only add days if it's the first time the model is saved if not id begin set d = time delta days=10 set date_due = now + d end call full_clean save end function
def save(self, **kwargs): # only add days if it's the first time the model is saved if not self.id: d = timedelta(days=10) self.date_due = datetime.now() + d self.full_clean() super(Classnotes, self).save()
Python
nomic_cornstack_python_v1
function fun s begin comment return True if s is a valid email, else return False set s = split s string @ if length s != 2 begin return false end set s = list s at 0 + split s at 1 string . if length s != 3 begin return false end set lettersNums = string abcdefghijklmnopqrstuvwxyz0123456789 set usernameChars = letters...
def fun(s): # return True if s is a valid email, else return False s = s.split('@') if(len(s) != 2): return False s = [s[0]] + s[1].split('.') if(len(s) != 3): return False lettersNums = 'abcdefghijklmnopqrstuvwxyz0123456789' usernameChars = lettersNums + '-_' if(len...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt import numpy as np set x = array range 0 20 0.1 set y = cos x plot x y show
import matplotlib.pyplot as plt import numpy as np x = np.arange(0,20,0.1) y = np.cos(x) plt.plot(x,y) plt.show()
Python
zaydzuhri_stack_edu_python
import sys import numpy as np from PyQt5 import QtWidgets , QtCore from queue import Queue set SHOW = false class AuthWorker extends QObject begin set authenticate = call pyqtSignal function __init__ self begin call __init__ end function function run self begin sleep 1 call emit end function end class class Worker exte...
import sys import numpy as np from PyQt5 import QtWidgets, QtCore from queue import Queue SHOW = False class AuthWorker(QtCore.QObject): authenticate = QtCore.pyqtSignal() def __init__(self): super(AuthWorker, self).__init__() def run(self): QtCore.QThread.sleep(1) self.authent...
Python
zaydzuhri_stack_edu_python
comment Write a function "max_magnitude" that accepts a single list full of numbers. It should return the magnitude of the number with the largest magnitude(the number that is furthest away from zero). comment max_magnitude([300, 20, -900]) #900 comment max_magnitude([10, 11, 12]) #12 comment max_magnitude([-5, -1, -89...
#Write a function "max_magnitude" that accepts a single list full of numbers. It should return the magnitude of the number with the largest magnitude(the number that is furthest away from zero). #max_magnitude([300, 20, -900]) #900 #max_magnitude([10, 11, 12]) #12 #max_magnitude([-5, -1, -89]) #89 #Hint: use max a...
Python
zaydzuhri_stack_edu_python
comment Project Euler - Problem 37 comment 3/3/2017 import math set PrimeList = list 2 3 5 7 function isPrime n begin for k in PrimeList begin if n % k == 0 begin return false end end append PrimeList n return true end function function CheckPrime num begin set n = string num set size = length n if count PrimeList inte...
# Project Euler - Problem 37 # 3/3/2017 import math PrimeList = [2, 3, 5, 7] def isPrime(n): for k in PrimeList: if n%k == 0: return False PrimeList.append(n) return True def CheckPrime(num): n = str(num) size = len(n) if PrimeList.count(int(n[0])) != 1: return False if PrimeList.count(int(n[size-1])) ...
Python
zaydzuhri_stack_edu_python
comment python cryptography package: comment 'pip install cryptography' comment install mysql from 'mysql.com' comment Command line (from mysql.com): comment mysql --host=localhost --user='your username' --password pw_db comment mysql -h localhost -u 'your username' -p pw_db comment Python db connect: comment pw_db = m...
# python cryptography package: # 'pip install cryptography' # install mysql from 'mysql.com' # Command line (from mysql.com): # mysql --host=localhost --user='your username' --password pw_db # mysql -h localhost -u 'your username' -p pw_db # Python db connect: # pw_db = mysql.connector.connect( # host='localho...
Python
zaydzuhri_stack_edu_python
function inject self *gens begin raise NotImplementedError end function
def inject(self, *gens): raise NotImplementedError
Python
nomic_cornstack_python_v1
function is_overlap self transposon begin if first <= last <= last begin return true end else if first <= first <= last begin return true end else begin return false end end function
def is_overlap(self, transposon): if self.first <= transposon.last <= self.last: return True elif self.first <= transposon.first <= self.last: return True else: return False
Python
nomic_cornstack_python_v1
function visit_page_with_browser visit_url begin warning string Opening an authorization web page in your browser; if it does not open, please open this URL: %s visit_url open visit_url new=1 end function
def visit_page_with_browser(visit_url): logger.warning( "Opening an authorization web page in your browser; if it does not open, " "please open this URL: %s", visit_url, ) webbrowser.open(visit_url, new=1)
Python
nomic_cornstack_python_v1
function get self begin return val end function
def get(self): return self.val
Python
nomic_cornstack_python_v1
function _extract_device_name_from_event event begin string Extract device name from a tf.Event proto carrying tensor value. set plugin_data_content = loads call as_str content return plugin_data_content at string device end function
def _extract_device_name_from_event(event): """Extract device name from a tf.Event proto carrying tensor value.""" plugin_data_content = json.loads( tf.compat.as_str(event.summary.value[0].metadata.plugin_data.content)) return plugin_data_content['device']
Python
jtatman_500k
import inspect import fnmatch import os import subprocess import time import sys class PatrolModule extends object begin function __init__ self actual_module postcmd=none begin string Create a representation of a patrol module that can be used. set method_dict = dict set all_methods = list set postcmd = postcmd for t...
import inspect import fnmatch import os import subprocess import time import sys class PatrolModule(object): def __init__(self, actual_module, postcmd = None): """Create a representation of a patrol module that can be used.""" self.method_dict = {} self.all_methods = [] self.postcm...
Python
zaydzuhri_stack_edu_python