code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
import requests from django.db import models class PERYGis extends Model begin string This class can be used as super class to extend the base class with possibility of geo information. comment create DB fields set geo_lat = call FloatField null=true blank=true editable=true set geo_lon = call FloatField null=true blan...
import requests from django.db import models class PERYGis(models.Model): ''' This class can be used as super class to extend the base class with possibility of geo information. ''' # create DB fields geo_lat = models.FloatField(null=True, blank=True, editable=True) geo_lon = models.Float...
Python
zaydzuhri_stack_edu_python
function _encode self o begin set value = NOT_PROVIDED for value in encode self o begin yield value end if value is NOT_PROVIDED begin raise NotEncodedException end end function
def _encode(self, o): value = WXFEncoder.NOT_PROVIDED for value in self.encode(o): yield value if value is WXFEncoder.NOT_PROVIDED: raise NotEncodedException
Python
nomic_cornstack_python_v1
function getDate row begin set date = row at string publish_time if date begin try begin if is digit date and length date == 4 begin comment Default entries with just year to Jan 1 set date = date + string -01-01 end return parse parser date end comment pylint: disable=W0702 except any begin comment Skip parsing errors...
def getDate(row): date = row["publish_time"] if date: try: if date.isdigit() and len(date) == 4: # Default entries with just year to Jan 1 date += "-01-01" return parser.parse(date) # pylint: disable=W070...
Python
nomic_cornstack_python_v1
import sys import itertools comment input = sys.stdin.readline set stdin = open string input17406.txt function go data begin global res comment 기존 데이터 변형 막기 위한 카피 set nA = list comprehension list comprehension A at i at j for j in range M for i in range N for d in data begin set tuple r c s = tuple d at 0 - 1 d at 1 - ...
import sys import itertools # input = sys.stdin.readline sys.stdin = open('input17406.txt') def go(data): global res # 기존 데이터 변형 막기 위한 카피 nA = [[A[i][j] for j in range(M)] for i in range(N)] for d in data: r, c, s = d[0]-1, d[1]-1, d[2] while s: # (R,C)의 값을 (nR,nC)에 저장하며, ...
Python
zaydzuhri_stack_edu_python
function health_status user_model seldon_metrics begin if has attribute user_model string health_status_raw begin try begin return call health_status_raw end except SeldonNotImplementedError begin pass end end set client_response = call client_health_status user_model set metrics = call client_custom_metrics user_model...
def health_status( user_model: Any, seldon_metrics: SeldonMetrics ) -> Union[prediction_pb2.SeldonMessage, List, Dict]: if hasattr(user_model, "health_status_raw"): try: return user_model.health_status_raw() except SeldonNotImplementedError: pass client_response = c...
Python
nomic_cornstack_python_v1
function numIdenticalPairs nums begin set count = dict for i in nums begin if i in count begin set count at i = count at i + 1 end else begin set count at i = 1 end end set pairs = 0 for i in list values count begin set pairs = pairs + i - 1 * i // 2 end return pairs end function print call numIdenticalPairs list 1 2 ...
def numIdenticalPairs(nums): count={} for i in nums: if i in count: count[i]+=1 else: count[i] = 1 pairs=0 for i in list(count.values()): pairs += (i-1)*i//2 return pairs print(numIdenticalPairs([1,2,3,2,1,1]))
Python
zaydzuhri_stack_edu_python
import os import re function is_file file_name begin return is file path file_name end function function format_size bytes begin set bytes = decimal bytes set kb = bytes / 1024 set m = kb / 1024 return m end function function get_doc_size path begin try begin set size = get size path path return call format_size size e...
import os import re def is_file(file_name): return os.path.isfile(file_name) def format_size(bytes): bytes = float(bytes) kb = bytes / 1024 m = kb / 1024 return m def get_doc_size(path): try: size = os.path.getsize(path) return format_size(size) excep...
Python
zaydzuhri_stack_edu_python
import numpy from keras.datasets import imdb from matplotlib import pyplot as plt set tuple tuple X_train y_train tuple X_test y_test = call load_data comment X_train[i]: 這篇影評的每個詞轉成編碼數字組成陣列 set X = concatenate tuple X_train X_test axis=0 set y = concatenate tuple y_train y_test axis=0 print string x shape shape shape s...
import numpy from keras.datasets import imdb from matplotlib import pyplot as plt (X_train, y_train), (X_test, y_test) = imdb.load_data() # X_train[i]: 這篇影評的每個詞轉成編碼數字組成陣列 X = numpy.concatenate((X_train, X_test), axis=0) y = numpy.concatenate((y_train, y_test), axis=0) print('x shape', X_train.shape, X_test.shape, X.sh...
Python
zaydzuhri_stack_edu_python
function cov_params_approx self begin return call _cov_params_approx _cov_approx_complex_step _cov_approx_centered end function
def cov_params_approx(self): return self._cov_params_approx(self._cov_approx_complex_step, self._cov_approx_centered)
Python
nomic_cornstack_python_v1
import unittest from mock import Mock from domain.chefs.chef.ChefService import ChefService from test_data_provider.ChefDataProvider import ChefDataProvider class ChefServiceTest extends TestCase begin string ChefService Test function setUp self begin set repository = call Mock set model = call Mock set sut = call new ...
import unittest from mock import Mock from domain.chefs.chef.ChefService import ChefService from test_data_provider.ChefDataProvider import ChefDataProvider class ChefServiceTest(unittest.TestCase): ''' ChefService Test ''' def setUp(self): self.repository = Mock() self.model = Mo...
Python
zaydzuhri_stack_edu_python
import csv class WriteFile begin function write_detail self details begin with open string student_info.csv string a as file begin set writer = writer file write row writer details end close file end function function delete_detail self user_inp begin with open string student_info.csv string r newline=string as file be...
import csv class WriteFile: def write_detail(self,details): with open('student_info.csv' ,'a') as file: writer = csv.writer(file) writer.writerow(details) file.close() def delete_detail(self,user_inp): with open('student_info.csv','r',newline='') as file: ...
Python
zaydzuhri_stack_edu_python
function __init__ self x y=none kind=string coord begin if kind == string human begin if y is not none begin raise exception string In kind { kind } , it should receive only a letter representing the movement. end try begin set tuple x y = list comprehension tuple index index row x for tuple index row in enumerate KEYS...
def __init__(self, x, y=None, kind='coord'): if kind == 'human': if y is not None: raise Exception( f'In kind {kind}, it should receive only a letter representing the movement.') try: x, y = [(index, row.index(x)) ...
Python
nomic_cornstack_python_v1
function get_sy_all inner_parameters sy par_edata_idx begin set sy_all = list for inner_parameter in inner_parameters begin for tuple sy_i mask_i edata_idx in zip sy ixs par_edata_idx begin if edata_idx is not none begin set sim_sy = sy_i at tuple slice : : edata_idx slice : : at mask_i end else begin set sim_sy...
def get_sy_all( inner_parameters: List[OptimalScalingParameter], sy: List[np.ndarray], par_edata_idx: List, ): sy_all = [] for inner_parameter in inner_parameters: for sy_i, mask_i, edata_idx in zip( sy, inner_parameter.ixs, par_edata_idx ): if edata_idx is no...
Python
nomic_cornstack_python_v1
comment coding=UTF-8 import unittest , time , re string Représente un log Salesforce class ApexLog begin set rawBody = none set id = none set time = none set body = none set version = none set filename = none set log_levels = none set header = none function isIncomplete self begin return id is none or time is none or v...
# coding=UTF-8 import unittest, time, re ''' Représente un log Salesforce ''' class ApexLog(): rawBody = None id = None time = None body = None version = None filename = None log_levels = None header = None def isIncomplete(self): return (self.id is None) or (self.time is None) or (self.version is None)...
Python
zaydzuhri_stack_edu_python
function get_geoip self begin return if expression ip is not none then call get_geoip else none end function
def get_geoip(self): return self.ip.get_geoip() if self.ip is not None else None
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- comment 基于Sobel边缘检测算子的图像背景切换(测试阶段) import cv2 as cv set img = call imread string jingjiang.png set img = call resize img tuple 640 480 set x = call Sobel img CV_16S 1 0 set y = call Sobel img CV_16S 0 1 comment cv2.convertScaleAbs(src[, dst[, alpha[, beta]]]) comment 可选参数alpha是伸缩系数,beta是加到...
# -*- coding: utf-8 -*- # 基于Sobel边缘检测算子的图像背景切换(测试阶段) import cv2 as cv img = cv.imread('jingjiang.png') img = cv.resize(img,(640,480)) x = cv.Sobel(img, cv.CV_16S, 1, 0) y = cv.Sobel(img, cv.CV_16S, 0, 1) # cv2.convertScaleAbs(src[, dst[, alpha[, beta]]]) # 可选参数alpha是伸缩系数,beta是加到结果上的一个值,结果返回uint类型的图像 Scale_absX = cv.con...
Python
zaydzuhri_stack_edu_python
comment Преобразование серого мира comment Прочитайте изображение из файла img.png. Примените к нему преобразование серого мира. Для этого: comment 1. Сконвертируйте изображение в вещественные числа. comment 2. Подсчитайте коэффициенты rw,gw,bw как описано в видео. comment 3. Поделите каналы изображения на коэффициенты...
# Преобразование серого мира # Прочитайте изображение из файла img.png. Примените к нему преобразование серого мира. Для этого: # 1. Сконвертируйте изображение в вещественные числа. # 2. Подсчитайте коэффициенты rw,gw,bw как описано в видео. # 3. Поделите каналы изображения на коэффициенты. # 4. Обрежьте значения пикс...
Python
zaydzuhri_stack_edu_python
comment !-*- encoding: utf8 -*- from nltk.corpus import floresta from collections import defaultdict function contarPalavras textoP begin set total = 0 set gramatica = 0 set uml = 0 for frase in textoP begin set novaFrase = list set aux = string for palavra in frase begin set total = total + 1 if palavra at 1 != stri...
#!-*- encoding: utf8 -*- from nltk.corpus import floresta from collections import defaultdict def contarPalavras(textoP): total = 0 gramatica = 0 uml = 0 for frase in textoP: novaFrase = [] aux = "" for palavra in frase: total = total + 1 if palavra[1] !=...
Python
zaydzuhri_stack_edu_python
import time import pymysql import datetime import random import string function insert_log_server rfid_id location site locker_name locker status_locker time MQTT_Mass begin comment Open database connection set db = call connect string localhost string pi string 1234 string serverlocker comment prepare a cursor object ...
import time import pymysql import datetime import random import string def insert_log_server(rfid_id, location, site, locker_name, locker, status_locker, time, MQTT_Mass) : # Open database connection db = pymysql.connect("localhost","pi","1234","serverlocker" ) # prepare a cursor object using cu...
Python
zaydzuhri_stack_edu_python
import unittest import LA_Dice class LivingAlchemyTest extends TestCase begin comment Tests that the number of rolled dice equals the function test_equal_dice self begin assert equal 10 length call rollDice 10 end function comment tests whether dice combine correctly. function test_combine_dice self begin set testingli...
import unittest import LA_Dice class LivingAlchemyTest(unittest.TestCase): def test_equal_dice(self): #Tests that the number of rolled dice equals the self.assertEqual(10, len(LA_Dice.DiceRoller.rollDice(10))) def test_combine_dice(self): #tests whether dice combine correctly. testinglist = LA_...
Python
zaydzuhri_stack_edu_python
import io import os import sys import json import glob import urllib.request import gevent from gevent import monkey from gevent.pool import Pool call patch_socket function load_data file_name begin with open file_name encoding=string utf-8 as f begin set data = sorted list comprehension loads line for line in f key=la...
import io import os import sys import json import glob import urllib.request import gevent from gevent import monkey from gevent.pool import Pool monkey.patch_socket() def load_data(file_name): with io.open(file_name, encoding='utf-8') as f: data = sorted( [json.loads(line) for line in f], ...
Python
zaydzuhri_stack_edu_python
function avoid_instr_is_valid bv addr begin return addr not in mui_avoid end function
def avoid_instr_is_valid(bv: BinaryView, addr: int): return addr not in bv.session_data.mui_avoid
Python
nomic_cornstack_python_v1
function getVowelMeasurement vowelFileStem p w speechSoftware formantPredictionMethod measurementPointMethod nFormants maxFormant windowSize preEmphasis padBeg padEnd speaker begin set vowelWavFile = vowelFileStem + string .wav comment get necessary files (LPC or formant) comment via ESPS: ## NOTE: I haven't checked th...
def getVowelMeasurement(vowelFileStem, p, w, speechSoftware, formantPredictionMethod, measurementPointMethod, nFormants, maxFormant, windowSize, preEmphasis, padBeg, padEnd, speaker): vowelWavFile = vowelFileStem + '.wav' # get necessary files (LPC or formant) # via ESPS: ## NOTE: I haven't checked the ...
Python
nomic_cornstack_python_v1
import sys append path string ../.. import game function saisieCoup jeu begin string jeu-> coup retourne un coup a jouer set c = input string joueur + string call getJoueur jeu + string : quelle colonne? set d = input string joueur + string call getJoueur jeu + string : quelle ligne? set coup = list d c while not call ...
import sys sys.path.append("../..") import game def saisieCoup(jeu): """ jeu-> coup retourne un coup a jouer """ c=input("joueur"+str(game.getJoueur(jeu))+": quelle colonne?") d=input("joueur"+str(game.getJoueur(jeu))+": quelle ligne?") coup=[d,c] while(not(game.coupValide(jeu,coup))):...
Python
zaydzuhri_stack_edu_python
comment First question. Imagine you're a host: getting bunch of requests as integer array. Each integer represents a number of nights as back to back reservations. You can pick as a host which requests to take given a constraint - you need one day in between to book a place. Maximizing the total number of nights stayed...
# First question. Imagine you're a host: getting bunch of requests as integer array. Each integer represents a number of nights as back to back reservations. You can pick as a host which requests to take given a constraint - you need one day in between to book a place. Maximizing the total number of nights stayed where...
Python
zaydzuhri_stack_edu_python
function abort_analysis self begin call BNAbortAnalysis handle end function
def abort_analysis(self): core.BNAbortAnalysis(self.handle)
Python
nomic_cornstack_python_v1
comment Primjer jednostrukog nasljeđivanja class Igrac begin function __init__ self ime godine begin set ime = ime set godine = godine end function function display self begin print string ime : ime print string godine : godine end function end class class Nogometas extends Igrac begin function __init__ self id ime god...
# Primjer jednostrukog nasljeđivanja class Igrac: def __init__(self, ime, godine): self.ime = ime self.godine = godine def display(self): print('ime : ', self.ime) print('godine : ', self.godine) class Nogometas(Igrac): def __init__(self, id, ime, godine, fit...
Python
zaydzuhri_stack_edu_python
function saveBuildP self fileName=none begin if fileName is none begin return false end set fileName = configDir + string / + fileName + string .bpts set points = list comprehension tuple x at 0 x at 1 for x in buildP with open fileName string w as handle begin dump points handle indent=4 end return true end function
def saveBuildP(self, fileName=None): if fileName is None: return False fileName = self.configDir + '/' + fileName + '.bpts' points = [(x[0], x[1]) for x in self.buildP] with open(fileName, 'w') as handle: json.dump(points, handle, ...
Python
nomic_cornstack_python_v1
function test_insert_metadata self begin comment Note that query logic is tested separately by integration tests. This comment test just checks that the function maps inputs to outputs as expected. set mock_connection = call MagicMock set mock_cursor = call cursor set database = call Database mock_connection set result...
def test_insert_metadata(self): # Note that query logic is tested separately by integration tests. This # test just checks that the function maps inputs to outputs as expected. mock_connection = MagicMock() mock_cursor = mock_connection.cursor() database = Database(mock_connection) result = d...
Python
nomic_cornstack_python_v1
function mix_predictions_curtesian preds_all list_of_indexes begin comment make cartesian product set all_list = list for i in call combinations_with_replacement list_of_indexes 2 begin if i at 0 != i at 1 begin append all_list list i end end for list_of_indexes in all_list begin for tuple num_val i in enumerate list_...
def mix_predictions_curtesian(preds_all, list_of_indexes): ### make cartesian product all_list = [] for i in combinations_with_replacement(list_of_indexes, 2): if i[0] !=i[1]: all_list.append(list(i)) for list_of_indexes in all_list: for num_val, i in enumerate(list_of_index...
Python
nomic_cornstack_python_v1
import pprint import sys import pickle import csv function main argv begin assert length argv == 2 set csv_file_name = argv at 0 set data_file_name = argv at 1 set file = open data_file_name string rb set data = load pickle file close file close file with open csv_file_name mode=string w as csv_file begin set writer = ...
import pprint import sys import pickle import csv def main(argv): assert len(argv) == 2 csv_file_name = argv[0] data_file_name = argv[1] file = open(data_file_name, 'rb') data = pickle.load(file) file.close() file.close() with open(csv_file_name, mode='w') as csv_file: writer = csv.writer(csv_file) write...
Python
zaydzuhri_stack_edu_python
function fetchReadNodeInTree node begin set readNode = call checkDependencies node string Read return readNode end function
def fetchReadNodeInTree(node): readNode = checkDependencies(node, 'Read') return readNode
Python
nomic_cornstack_python_v1
import ds function finalResult resultNode begin print string print string final result call currentNodeState print string print string result depth: print depth print string print string in memory nodes print string explored nodes : + string length explored print string all nodes nodes : + string length frontier + leng...
import ds def finalResult(resultNode): print("") print("final result") resultNode.currentNodeState() print("") print("result depth:") print(resultNode.depth) print("") print("in memory nodes") print("explored nodes : " + str(len(explored))) print("all nodes nodes : " + str(len(...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding=utf-8 comment HTML找出正文 import requests from bs4 import BeautifulSoup set url = string http://www.baidu.com set html = get requests url set soup = call BeautifulSoup text
#!/usr/bin/env python #coding=utf-8 #HTML找出正文 import requests from bs4 import BeautifulSoup url='http://www.baidu.com' html=requests.get(url) soup=BeautifulSoup(html.text)
Python
zaydzuhri_stack_edu_python
function run self begin set r = run while r != 1 begin if r == 0 begin if index engines engine < length engines - 1 begin set engine = engines at index engines engine + 1 end end end end function
def run(self): r = self.engine.run() while r != 1: if r == 0: if self.engines.index(self.engine) < len(self.engines) - 1: self.engine = self.engines[self.engines.index(self.engine) + 1]
Python
nomic_cornstack_python_v1
import cv2 import pandas as pd import util as util comment Pull in the data from the csv files set data = read csv string ./data/output_0.csv set siz = length data at string image comment Bring in some extra cool pictures comment blueshell = cv2.imread('./blueshell2.png') comment mario = cv2.imread('./mario.png') for i...
import cv2 import pandas as pd import util as util # Pull in the data from the csv files data = pd.read_csv("./data/output_0.csv") siz = len(data['image']) # Bring in some extra cool pictures #blueshell = cv2.imread('./blueshell2.png') #mario = cv2.imread('./mario.png') for i in range(1, siz-1): print('Servo Da...
Python
zaydzuhri_stack_edu_python
function test_f_uni self begin set s = array list 100.0 0 0 0 0 0 set e = array list 0.1 - 0.05 - 0.05 0 0 0 set f_direct = f dist s e t T set sdev = s - array list 1 1 1 0 0 0 * sum s at slice : 3 : / 3.0 set se = square root 3.0 / 2.0 * norm sdev set ee = square root 2.0 / 3.0 * norm e set g_direct = call g se ee t ...
def test_f_uni(self): s = np.array([100.0, 0, 0, 0, 0, 0]) e = np.array([0.1, -0.05, -0.05, 0, 0, 0]) f_direct = self.model.f(s, e, self.t, self.T) sdev = s - np.array([1,1,1,0,0,0]) * np.sum(s[:3]) / 3.0 se = np.sqrt(3.0/2.0) * la.norm(sdev) ee = np.sqrt(2.0/3.0) * la.norm(e) g_direct...
Python
nomic_cornstack_python_v1
function __init__ self type owner=none index=none name=none begin set tag = call scratchpad set type = type if owner is not none and not is instance owner Apply begin raise call TypeError string owner must be an Apply instance owner end set owner = owner if index is not none and not is instance index int begin raise ca...
def __init__(self, type, owner=None, index=None, name=None): self.tag = utils.scratchpad() self.type = type if owner is not None and not isinstance(owner, Apply): raise TypeError("owner must be an Apply instance", owner) self.owner = owner if index is not None a...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: UTF-8 -*- set __author__ = string geyixin import pandas as pd from keras.models import Sequential from keras.layers import Dense , Activation from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt set input = string ../Data/sales_data.xls set data ...
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- __author__ = 'geyixin' import pandas as pd from keras.models import Sequential from keras.layers import Dense, Activation from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt input = '../Data/sales_data.xls' data = pd.read_excel(input, index_col=...
Python
zaydzuhri_stack_edu_python
function testTaskTimeout self begin comment Restart with a working timer call stop start machine _stateType comment Release timer call releaseTimer timeoutEvent comment Test that the timeout worked properly call assertCurrentState Pipe assert false call has_key Start assert false buoyDetector end function
def testTaskTimeout(self): # Restart with a working timer self.machine.stop() self.machine.start(self._stateType) # Release timer self.releaseTimer(self.machine.currentState().timeoutEvent) # Test that the timeout worked properly self.assertCurre...
Python
nomic_cornstack_python_v1
comment -*- coding:utf-8 -*- comment 19:30--20:11 41 mins comment 方法一:T(n) = n class Solution begin function __init__ self begin set cnt = 0 set n = 0 end function function dfs self m cur begin comment m 是起始值 for i in range 10 begin set temp = m * 10 + i if temp <= n and temp > 0 begin if i == 1 begin set cnt = cnt + c...
# -*- coding:utf-8 -*- #19:30--20:11 41 mins #方法一:T(n) = n class Solution: def __init__(self): self.cnt = 0 self.n = 0 def dfs(self,m,cur): # m 是起始值 for i in range(10): temp = m*10 + i if temp <= self.n and temp > 0: if i == 1: ...
Python
zaydzuhri_stack_edu_python
for _ in call R m begin set tuple l r = call I set ans = ans + max 0 sum generator expression a at i for i in call R l - 1 r end print ans
for _ in R(m):l,r=I();ans+=max(0,sum(a[i]for i in R(l-1,r))) print(ans)
Python
jtatman_500k
function row self index begin return data at index end function
def row(self, index): return self.data[index]
Python
nomic_cornstack_python_v1
comment sum.py comment Computes the sum of the first 4 positive integer function summy begin set inputNum = integer input string please give me an integer and i will output the first "n" integers of my summy function: set sum = 0 end function
# sum.py # Computes the sum of the first 4 positive integer def summy(): inputNum = int(input('please give me an integer and i will output the first "n" integers of my summy function: ')) sum = 0
Python
zaydzuhri_stack_edu_python
function is_triangle a b c begin comment conditional to do the checking if a + b < c ? c + b < a ? a + c < b begin return false end else begin return true end end function
def is_triangle(a, b, c): # conditional to do the checking if ((a+b < c) | (c+b < a) | (a+c < b)): return False else: return True
Python
nomic_cornstack_python_v1
function get_connection self dbname ttl_ms timeout=none persistent=false begin with _mu begin set pool = call _get_connection_pool dbname=dbname ttl_ms=ttl_ms timeout=timeout persistent=persistent set db = call getconn timeout=timeout end try begin yield db end finally begin with _mu begin try begin call putconn db if ...
def get_connection(self, dbname: str, ttl_ms: int, timeout: int = None, persistent: bool = False): with self._mu: pool = self._get_connection_pool(dbname=dbname, ttl_ms=ttl_ms, timeout=timeout, persistent=persistent) db = pool.getconn(timeout=timeout) try: yield db ...
Python
nomic_cornstack_python_v1
import sys import re from collections import deque function escape line begin set original = deque line set escaped = list while length original != 0 begin set char = call popleft if char == string " begin append escaped string \" end else if char == string \ and original at 0 == string " begin call popleft append esc...
import sys import re from collections import deque def escape(line): original = deque(line) escaped = [] while len(original) != 0: char = original.popleft() if char == '"': escaped.append('\\"') elif char == "\\" and original[0] == '"': original.popleft() ...
Python
zaydzuhri_stack_edu_python
function do_transform_point point transform begin set tuple _ point = call _decompose_affine matrix multiply call _transform_to_affine transform call _build_affine translation=list x y z set res = call PointStamped set x = point at 0 set y = point at 1 set z = point at 2 set header = header return res end function
def do_transform_point( point: PointStamped, transform: TransformStamped) -> PointStamped: _, point = _decompose_affine( np.matmul( _transform_to_affine(transform), _build_affine(translation=[ point.point.x, point.point.y, ...
Python
nomic_cornstack_python_v1
import socket import threading import time function client_handler sock begin set _ = call recv 1024 sleep 0.3 call sendall b'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: 71\r\n\r\n<html><head><title>Success</title></head><body>Index page</body></html>' close sock end function function main host=string...
import socket import threading import time def client_handler(sock: socket.socket): _ = sock.recv(1024) time.sleep(0.3) sock.sendall( b"HTTP/1.1 200 OK\r\n" b"Content-Type: text/html\r\n" b"Content-Length: 71\r\n\r\n" b"<html><head><title>Success</title></head><body>Index p...
Python
zaydzuhri_stack_edu_python
function room_location_id self room_location_id begin set _room_location_id = room_location_id end function
def room_location_id(self, room_location_id): self._room_location_id = room_location_id
Python
nomic_cornstack_python_v1
function exec_ self begin call connect lambda state -> call done state return call exec_ self end function
def exec_(self) -> int: self._w.finished.connect(lambda state: self.done(state)) return QDialog.exec_(self)
Python
nomic_cornstack_python_v1
import cv2 import os set cam = call VideoCapture string 2.mp4 set face_detector = call CascadeClassifier string data/haarcascade_frontalface_default.xml global user set user = input string ad: print string [BILGI] Kameraya bakın ve bekleyin... set say = 0 make directory os string dataset/ + user while true begin set tu...
import cv2 import os cam = cv2.VideoCapture("2.mp4") face_detector = cv2.CascadeClassifier('data/haarcascade_frontalface_default.xml') global user user = input("ad: ") print("\n[BILGI] Kameraya bakın ve bekleyin...") say = 0 os.mkdir('dataset/'+user) while True: ret, frame = cam.read() frame = cv2.flip(...
Python
zaydzuhri_stack_edu_python
import random class RandomPasswordGenerator begin function __init__ self length=10 begin set length = length set password_chars = string abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890!@#$%^ end function function generate_password self begin set password = string for _ in range length begin set index =...
import random class RandomPasswordGenerator: def __init__(self, length=10): self.length = length self.password_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890!@#$%^" def generate_password(self): password = "" for _ in range(self.length): ind...
Python
jtatman_500k
function add_measurement_at_node self meas_model path begin info string DataModel - add_measurement_at_node - + string path comment Obtain Measurement item if meas_model at 0 == string Measurement begin set meas = call Measurement meas_model at 1 end else if meas_model at 0 == string Completion begin set meas = call Co...
def add_measurement_at_node(self, meas_model, path): log.info('DataModel - add_measurement_at_node - ' + str(path)) # Obtain Measurement item if meas_model[0] == 'Measurement': meas = measurement.Measurement(meas_model[1]) elif meas_model[0] == 'Completion': meas ...
Python
nomic_cornstack_python_v1
import gpiozero as gpzero from time import sleep set resetbutton = call Button 3 set leds = call LEDBoard 26 16 20 21 comment test the button while true begin if is_pressed begin print string Great! The button is correctly connected break end else begin print string Please test the pushbutton now... end end comment tes...
import gpiozero as gpzero from time import sleep resetbutton = gpzero.Button(3) leds = gpzero.LEDBoard(26,16,20,21) # test the button while True: if resetbutton.is_pressed: print("Great! The button is correctly connected") break else: print("Please test the pushbutton now...") # test...
Python
zaydzuhri_stack_edu_python
string Project Euler.net Problem 23: Non-abundant sums Answer = 4179871 import math function listFactors number begin string returns a list of all factors of a number set factors = list for i in range 1 integer square root number + 1 begin if number % i == 0 begin append factors i append factors integer number / i end...
""" Project Euler.net Problem 23: Non-abundant sums Answer = 4179871 """ import math def listFactors(number): """returns a list of all factors of a number""" factors = [] for i in range(1,int(math.sqrt(number)) +1): if number%i == 0: factors.append(i) factor...
Python
zaydzuhri_stack_edu_python
import tkinter as tk set root = call Tk set frame = call Frame root set canvas = call Canvas frame width=600 height=400 bg=string #aaaaff set item = call create_rectangle 10 10 100 80 fill=string green comment cria nova instância set game_object = call GameObject canvas item print call get_position comment [10, 10, 100...
import tkinter as tk root = tk.Tk() frame = tk.Frame(root) canvas = tk.Canvas(frame, width=600, height=400, bg='#aaaaff') item = canvas.create_rectangle(10,10,100,80, fill='green') game_object = GameObject(canvas, item) #cria nova instância print(game_object.get_position()) # [10, 10, 100, 80] game_object.move(20, -10)...
Python
zaydzuhri_stack_edu_python
from bs4 import BeautifulSoup set soup = call BeautifulSoup string <b class="boldest">Extremely bold</b> string lxml set tag = b print tag print type tag print name comment tag.name = "blockquote" comment print(tag) comment print(tag.b) print tag at string class print attrs set tag at string class = string verybold set...
from bs4 import BeautifulSoup soup = BeautifulSoup('<b class="boldest">Extremely bold</b>', 'lxml') tag = soup.b print(tag) print(type(tag)) print(tag.name) # tag.name = "blockquote" # print(tag) # print(tag.b) print(tag['class']) print(tag.attrs) tag['class'] = 'verybold' tag['id'] = 1 print(tag) # 删除属性 del tag['id...
Python
zaydzuhri_stack_edu_python
function serialize self begin return dict string cat_id cat_id ; string id id ; string name name ; string description description end function
def serialize(self): return { 'cat_id': self.cat_id, 'id': self.id, 'name': self.name, 'description': self.description, }
Python
nomic_cornstack_python_v1
function autolabel rects axis begin for rect in rects begin set height = call get_height if height > 0 begin call text call get_x + call get_width / 2.0 1.05 * height string %d % integer height ha=string center va=string bottom end end end function
def autolabel(rects, axis): for rect in rects: height = rect.get_height() if height > 0: axis.text(rect.get_x() + rect.get_width()/2., 1.05*height, '%d' % int(height), ha='center', va='bottom')
Python
nomic_cornstack_python_v1
string Write a Python program to display the first and last colors from the following list. color_list = ["Red","Green","White" ,"Black"] set color_list = list string Red string Green string White string Black print string First Color: + color_list at 0 + string Last Color: + color_list at 3
''' Write a Python program to display the first and last colors from the following list. color_list = ["Red","Green","White" ,"Black"] ''' color_list = ["Red", "Green", "White", "Black"] print("First Color: "+color_list[0]+" \nLast Color: "+color_list[3])
Python
zaydzuhri_stack_edu_python
function start_requests self begin set today_date = call date set start_date = call date 1963 7 17 set week_no = 0 while true begin set next_date = time delta weeks=week_no set new_date = start_date + next_date yield call Request url=string https://www.billboard.com/charts/billboard-global-200/ { call __str__ } callbac...
def start_requests(self): today_date = datetime.datetime.now().date() start_date = datetime.date(1963, 7, 17) week_no = 0 while True: next_date = datetime.timedelta(weeks=week_no) new_date = start_date + next_date yield scrapy.Request( ...
Python
nomic_cornstack_python_v1
class LinguisticLabel begin comment Linguistic label name could be 'verb', 'adjective', 'adverb', 'noun' etc comment Membership functions is function __init__ self linguistic_label_name *membership_functions begin set _linguistic_label_name = linguistic_label_name set _membership_functions = membership_functions end fu...
class LinguisticLabel: # Linguistic label name could be 'verb', 'adjective', 'adverb', 'noun' etc # Membership functions is def __init__(self, linguistic_label_name, *membership_functions): self._linguistic_label_name = linguistic_label_name self._membership_functions = membership_functions def main(): verb = ...
Python
zaydzuhri_stack_edu_python
function current_asset_level2_start_pos list_ begin set current_asset_dict = dict string class_id 1 ; string sub_class_id 1 ; string hiererchy string sub ; string level string class ; string item_name string current_asset ; string matched_with string ; string start_pos - 100 ; string end_position - 100 set list_2 = ca...
def current_asset_level2_start_pos(list_:list)-> dict: current_asset_dict= {"class_id":1,"sub_class_id":1,"hiererchy":"sub","level":"class","item_name":"current_asset","matched_with":"","start_pos":-100,"end_position":-100} list_2=find_list(list_) item_found = 0 current_asset_direct_search = False ...
Python
nomic_cornstack_python_v1
from flask import Flask , request , jsonify from researchGate import findResearchGate from googleAcademic import findGoogle from microsoft import findMicrosoft from database import queryDatabase , insertData from bson import json_util set app = call Flask __name__ decorator call route string / function welcome begin re...
from flask import Flask, request, jsonify from researchGate import findResearchGate from googleAcademic import findGoogle from microsoft import findMicrosoft from database import queryDatabase, insertData from bson import json_util app = Flask(__name__) @app.route('/') def welcome(): return { 'message' :...
Python
zaydzuhri_stack_edu_python
function key self begin return get pulumi self string key end function
def key(self) -> str: return pulumi.get(self, "key")
Python
nomic_cornstack_python_v1
function verifica_preco titulo begin for titulo in values livro begin return cor at titulo end end function print call verifica_preco titulo
def verifica_preco(titulo): for titulo in livro.values(): return(cor[titulo]) print(verifica_preco(titulo))
Python
zaydzuhri_stack_edu_python
function portals_id_members_post_with_http_info self id **kwargs begin set all_params = list string id 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_params begin raise ...
def portals_id_members_post_with_http_info(self, id, **kwargs): all_params = ['id', '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 setInternalState self state begin set transitionTable = state at string transitionTable set order = state at string order set numSteps = state at string numSteps set loopDuration = state at string loopDuration end function
def setInternalState(self, state): self.transitionTable = state["transitionTable"] self.order = state["order"] self.numSteps = state["numSteps"] self.loopDuration = state["loopDuration"]
Python
nomic_cornstack_python_v1
function test_upgrade_subcloud_importing_load_processing_error self begin comment Simulate the target load has not been imported yet on the subcloud set return_value = DEST_LOAD_MISSING comment Simulate an API success on the subclould. set return_value = SUCCESS_IMPORTING_RESPONSE comment mock the get_load queries to r...
def test_upgrade_subcloud_importing_load_processing_error(self): # Simulate the target load has not been imported yet on the subcloud self.sysinv_client.get_loads.return_value = DEST_LOAD_MISSING # Simulate an API success on the subclould. self.sysinv_client.import_load.return_value = ...
Python
nomic_cornstack_python_v1
function _make_lti11_success_authentication_request_args roles=string Instructor ext_roles=string urn:lti:instrole:ims/lis/Instructor lms_vendor=string canvas oauth_consumer_key=string my_consumer_key begin set args = dict string oauth_callback list encode string about:blank ; string oauth_consumer_key list encode oaut...
def _make_lti11_success_authentication_request_args( roles: str = "Instructor", ext_roles: str = "urn:lti:instrole:ims/lis/Instructor", lms_vendor: str = "canvas", oauth_consumer_key: str = "my_consumer_key", ): args = { "oauth_callback": ["about:blank".encode()],...
Python
nomic_cornstack_python_v1
function do_GET self begin comment split the url into a list containing each part of the url. comment The list should look like ['api', 'analog', 'input', '1'] set path_parts = split path string / at slice 1 : : try begin if path_parts at 0 == string api and path_parts at 2 == string input begin if path_parts at 1 no...
def do_GET(self): # split the url into a list containing each part of the url. # The list should look like ['api', 'analog', 'input', '1'] path_parts = self.path.split('/')[1:] try: if path_parts[0] == 'api' and path_parts[2] == 'input': if path_parts[1] not i...
Python
nomic_cornstack_python_v1
import sys from itertools import izip , islice from collections import namedtuple function paintVertical A s=0 e=0 begin return e - s end function function paintHorizontal A M begin set A = list comprehension a - M for a in A return call paint A end function function paint A s=0 e=- 1 waterline=0 begin if e == - 1 begi...
import sys from itertools import izip, islice from collections import namedtuple def paintVertical(A, s=0, e=0): return e-s def paintHorizontal(A, M): A = [a - M for a in A] return paint(A) def paint(A, s=0, e=-1, waterline=0): if e == -1: e = len(A) if e-s == 0: return 0 elif e-s == 1: retu...
Python
zaydzuhri_stack_edu_python
import requests from lxml.html import fromstring from datetime import datetime , time from pytz import timezone from pprint import pprint from typing import List import asyncio import aiohttp set tz = call timezone string America/Detroit set now = time set base_url = string https://dining.umich.edu/menus-locations/dini...
import requests from lxml.html import fromstring from datetime import datetime, time from pytz import timezone from pprint import pprint from typing import List import asyncio import aiohttp tz = timezone('America/Detroit') now = datetime.now(tz).time() base_url = 'https://dining.umich.edu/menus-locations/dining-hal...
Python
zaydzuhri_stack_edu_python
import sys call setrecursionlimit 10 ^ 6 set Black = 0 set Red = 1 class Node begin function __init__ self val=none begin set value = val set left = none set right = none set parent = none set colour = 1 set size = 1 end function end class class RBTree begin function __init__ self root=none begin set root = root end fu...
import sys sys.setrecursionlimit(10**6) Black = 0 Red = 1 class Node: def __init__(self, val = None): self.value = val self.left = None self.right = None self.parent = None self.colour = 1 self.size = 1 class RBTree: def __init__(self, root = None): se...
Python
zaydzuhri_stack_edu_python
function mv_oberrhein scenario=string load cosphi_load=0.98 cosphi_pv=1.0 include_substations=false separation_by_sub=false **kwargs begin if include_substations begin set net = call from_json join path pp_dir string networks string mv_oberrhein_substations.json keyword kwargs end else begin set net = call from_json jo...
def mv_oberrhein(scenario="load", cosphi_load=0.98, cosphi_pv=1.0, include_substations=False, separation_by_sub=False, **kwargs): if include_substations: net = pp.from_json(os.path.join(pp_dir, "networks", "mv_oberrhein_substations.json"), **kwargs) else:...
Python
nomic_cornstack_python_v1
function generate_usgs_avg_daily_flows_opt self reach_id_gage_id_file start_datetime end_datetime out_streamflow_file out_stream_id_file begin string Generate daily streamflow file and stream id file required for calibration or for substituting flows based on USGS gage ids associated with stream ids. Parameters -------...
def generate_usgs_avg_daily_flows_opt(self, reach_id_gage_id_file, start_datetime, end_datetime, out_streamflow_file, ...
Python
jtatman_500k
comment !/usr/bin/python3 import argparse import toml from pathlib import Path import sys import kml import gpsbabel_kml import os_trigs function sanitise_section_args args_dict begin comment If a description was provided use it, otherwise don't have this element if not string description in args_dict begin set args_di...
#!/usr/bin/python3 import argparse import toml from pathlib import Path import sys import kml import gpsbabel_kml import os_trigs def sanitise_section_args(args_dict): # If a description was provided use it, otherwise don't have this element if not "description" in args_dict: args_dict["description"]...
Python
zaydzuhri_stack_edu_python
comment 37. Elabore um algoritmo que leia 10 medidas diferentes em centímetros e apresente quantos metros, comment decímetros e milímetros há nesta medida. set medidas = 1 while medidas <= 10 begin set medidas = medidas + 1 set medida = decimal input string Digite uma medida em centímetros: print string medida string ...
#37. Elabore um algoritmo que leia 10 medidas diferentes em centímetros e apresente quantos metros, # decímetros e milímetros há nesta medida. medidas = 1 while(medidas<=10): medidas += 1 medida = float(input('\nDigite uma medida em centímetros: ')) print('\n', medida, ' centímetros em metros: ', medi...
Python
zaydzuhri_stack_edu_python
from typing import Tuple import torch from torch import nn import flair class DropoutMC extends Module begin function __init__ self p activate=false begin call __init__ set activate = activate set p = p set p_init = p end function function forward self x begin return dropout x p training=training or activate end functi...
from typing import Tuple import torch from torch import nn import flair class DropoutMC(nn.Module): def __init__(self, p: float, activate=False): super().__init__() self.activate = activate self.p = p self.p_init = p def forward(self, x): return nn.functional.dropout(x...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- import numpy as np from scipy.io import loadmat import matplotlib.pyplot as plt set data = call loadmat string ex8data1.mat set X = data at string X set Xval = data at string Xval set yval = data at string yval scatter plt X at tuple slice : : 0 X at tuple slice : : 1 function gaussP...
# -*- coding: utf-8 -*- import numpy as np from scipy.io import loadmat import matplotlib.pyplot as plt data = loadmat("ex8data1.mat") X = data['X'] Xval = data['Xval'] yval = data['yval'] plt.scatter(X[:, 0], X[:, 1]) def gaussParams(X): mu = np.mean(X, axis = 0, keepdims = True) #cov = ((X - mu)**2).sum(...
Python
zaydzuhri_stack_edu_python
function getRemoteComments post_id begin set servers = all for server in servers begin if username and password begin set host = hostname if not ends with host string / begin set host = host + string / end set server_api = format string {}posts/{}/comments host post_id print string Request: print server_api try begin s...
def getRemoteComments(post_id): servers = Server.objects.all() for server in servers: if server.username and server.password: host = server.hostname if not host.endswith("/"): host = host + "/" server_api = "{}posts/{}/comments".format(host, post_id) ...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Sergio Di Deco Sampedro Ejercicio 11.3 Pyhton to Access Web Data In this assignment you will read through and parse a file with text and numbers. You will extract all the numbers in the file and compute the sum of the numbers. Sample data: http://py4e-data.dr-chuck.net/regex_sum_42....
# -*- coding: utf-8 -*- """ Sergio Di Deco Sampedro Ejercicio 11.3 Pyhton to Access Web Data In this assignment you will read through and parse a file with text and numbers. You will extract all the numbers in the file and compute the sum of the numbers. Sample data: http://py4e-data.dr-chuck.net/regex_sum...
Python
zaydzuhri_stack_edu_python
function off self port begin comment Make sure this is a valid port number. call validatePort port info string --------- Disabling port %d ----------- % port comment These commands will disable the given apc port. call sendCmdSequence list string olOff %s % port info string --------- Port %d disabled ------------ % por...
def off(self, port): # Make sure this is a valid port number. self.validatePort(port) self.log.info("--------- Disabling port %d -----------" % port) # These commands will disable the given apc port. self.sendCmdSequence(['olOff %s' % port]) self.log.info("--------- Port...
Python
nomic_cornstack_python_v1
from typing import List from collections import deque comment Definition for a binary tree node. class TreeNode begin function __init__ self val=0 left=none right=none begin set val = val set left = left set right = right end function end class class Solution begin function levelOrder self root begin if not root begin ...
from typing import List from collections import deque # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: ...
Python
zaydzuhri_stack_edu_python
function merge_shift data chopnod header=none variance=none nmc=false maxshift=999999999.0 normmap=none resize=true begin if not is instance header Header begin set header = call Header call addhist header string Created header end set var = if expression is instance variance ndarray then copy variance else none if not...
def merge_shift(data, chopnod, header=None, variance=None, nmc=False, maxshift=999999999., normmap=None, resize=True): if not isinstance(header, fits.header.Header): header = fits.header.Header() addhist(header, 'Created header') var = variance.copy() if isinstance(variance, np....
Python
nomic_cornstack_python_v1
function save model path begin comment PyTorch requires parent directory of savepath to exist. Ensure it does. set parentdir = parent if not exists path parentdir begin make directories parentdir end save state dict model path end function
def save(model, path): # PyTorch requires parent directory of savepath to exist. Ensure it does. parentdir = pathlib.Path(path).parent if not os.path.exists(parentdir): os.makedirs(parentdir) torch.save(model.state_dict(), path)
Python
nomic_cornstack_python_v1
async function reindex_documents begin info format string Reindexing documents from {}|{}|{} project namespace index set has_more = true set start_doc_id = none set total = 0 while has_more begin try begin set documents = await call list_documents project namespace index start_doc_id=start_doc_id include_start_doc=fals...
async def reindex_documents(): logger.info('Reindexing documents from {}|{}|{}' .format(args.project, args.namespace, args.index)) has_more = True start_doc_id = None total = 0 while has_more: try: documents = await adapter.list_documents( args.project, args.n...
Python
nomic_cornstack_python_v1
function _date self _date begin comment noqa: E501 if _date is not none and not search string ^(19|20)\\d\\d[\/](0[1-9]|1[012])[\/](0[1-9]|[12][0-9]|3[01])$ _date begin comment noqa: E501 raise call ValueError string Invalid value for `_date`, must be a follow pattern or equal to `/^(19|20)\d\d[\/](0[1-9]|1[012])[\/](0...
def _date(self, _date): if _date is not None and not re.search(r'^(19|20)\\d\\d[\/](0[1-9]|1[012])[\/](0[1-9]|[12][0-9]|3[01])$', _date): # noqa: E501 raise ValueError("Invalid value for `_date`, must be a follow pattern or equal to `/^(19|20)\\d\\d[\/](0[1-9]|1[012])[\/](0[1-9]|[12][0-9]|3[01])$/`...
Python
nomic_cornstack_python_v1
function getM_new self X Y begin if smiles_clean begin set tuple X0 Y0 = call clean_smiles_vec_io X Y end else begin set tuple X0 Y0 = tuple X Y end comment self.clean_X = X0 if N is none begin set N = length X0 end set tuple X1 Y1 = tuple X0 at slice : N : Y0 at slice : N : set X2 = call gfpM X1 rad=rad nBits=nBit...
def getM_new( self, X, Y): if self.smiles_clean: X0, Y0 = clean_smiles_vec_io( X, Y) else: X0, Y0 = X, Y # self.clean_X = X0 if self.N is None: N = len( X0) X1, Y1 = X0[:N], Y0[:N] X2 = gfpM( X1, rad = self.rad, nBits = self.nBits)...
Python
nomic_cornstack_python_v1
function _get_travel_destinations self is_clean_operatives is_radicalization is_schengen_visas ops begin if is_schengen_visas begin return call travel_destinations_schengen_visas end else if is_clean_operatives begin return list string United States string United States end else begin return call travel_destinations op...
def _get_travel_destinations(self, is_clean_operatives, is_radicalization, is_schengen_visas, ops): if is_schengen_visas: return self.travel_destinations_schengen_visas() elif is_clean_operatives: return ["United States", "United States"] else: return self.tra...
Python
nomic_cornstack_python_v1
function get_files folder_name begin set files = list comprehension f for f in list directory join path get current directory folder_name if is file path join path get current directory folder_name f return files end function
def get_files(folder_name: str) -> list: files = [f for f in os.listdir(os.path.join(os.getcwd(), folder_name)) if os.path.isfile(os.path.join(os.getcwd(), folder_name, f))] return files
Python
nomic_cornstack_python_v1
function generate_qr text fn=none path=string error=string H version=none mode=none output=string svg module_color=string black background=string white quiet_zone=4 begin comment Generate QR code object set qrcode = call create content=text error=error version=version mode=mode comment Render QR code depending on `out...
def generate_qr(text, fn=None, path='', error='H', version=None, mode=None, output='svg', module_color='black', background='white', quiet_zone=4): # Generate QR code object qrcode = pyqrcode.create(content=text, error=error, version=version, mode=mode) # Render QR cod...
Python
nomic_cornstack_python_v1
function to_iso_week_date d begin set tuple w dw = divide mod d - week_epoch 7 set tuple yi wy = call divmoddiv 28 * w + 20 - 4 * 5269 - w // 20871 * 3 // 4 * 4 1461 28 return tuple yi wy + 1 dw + 1 end function
def to_iso_week_date(d): w, dw = divmod(d - week_epoch, 7) yi, wy = divmoddiv(28*w + 20 - 4*(5269 - w)//20871*3//4*4, 1461, 28) return yi, wy + 1, dw + 1
Python
nomic_cornstack_python_v1
function translate_vector_2B pos multiple system begin set x = pos at 0 set y = pos at 1 set z = pos at 2 set x_b = x + xy * multiple set y_b = y + yhi - ylo * multiple set z_b = z + 0 return list x_b y_b z_b end function
def translate_vector_2B(pos, multiple, system): x = pos[0] y = pos[1] z = pos[2] x_b = x + system.xy * multiple y_b = y + (system.yhi - system.ylo) * multiple z_b = z + 0 return [x_b, y_b, z_b]
Python
nomic_cornstack_python_v1
class Solution begin function detectCapitalUse self word begin return call is_lower word or call is_upper word or call is_upper word at 0 and call is_lower word at slice 1 : : end function function is_lower self word begin return lower word == word end function function is_upper self word begin return upper word == wo...
class Solution: def detectCapitalUse(self, word: str) -> bool: return self.is_lower(word) or self.is_upper(word) or (self.is_upper(word[0]) and self.is_lower(word[1:])) def is_lower(self, word: str): return word.lower() == word def is_upper(self, word: str): return word.upper() == ...
Python
zaydzuhri_stack_edu_python
from risk_assess.random_objects.random_variables import RandomVariable import numpy as np class MixtureModel extends RandomVariable begin function __init__ self mixture_components weight_tolerance=1e-06 begin string component_random_variables: list of tuples of the form (weight, RandomVariable) comment List of tuples o...
from risk_assess.random_objects.random_variables import RandomVariable import numpy as np class MixtureModel(RandomVariable): def __init__(self, mixture_components, weight_tolerance = 1e-6): """ component_random_variables: list of tuples of the form (weight, RandomVariable) """ self...
Python
zaydzuhri_stack_edu_python
function decode self outfile=string output.png begin set data = call hilbert signal set data = reshape data integer length data // 5 5 set data = call lum data at tuple slice : : 2 set result = call sync data set image = call fromarray result set image = call convert string RGB save outfile end function
def decode(self, outfile='output.png'): data = self.hilbert(self.signal) data = data.reshape(int(len(data) // 5), 5) data = self.lum(data[:, 2]) result = self.sync(data) image = Image.fromarray(result) image = image.convert('RGB') image.save(outfile)
Python
nomic_cornstack_python_v1
import os import subprocess set path = environ at string PCPATH + string /build/tests set total = 0 set failed = 0 for tuple root subdirs files in walk path begin set list_file_path = join path root string my-directory-list.txt for filename in files begin set total = total + 1 set file_path = join path root filename pr...
import os import subprocess path = os.environ["PCPATH"] + "/build/tests" total = 0 failed = 0 for root, subdirs, files in os.walk(path): list_file_path = os.path.join(root, 'my-directory-list.txt') for filename in files: total += 1 file_path = os.path.join(root, filename) print("R...
Python
zaydzuhri_stack_edu_python
function go_to_page cls url browser_type=none begin set driver = call _check_browser_type browser_type get driver url=strip url return driver end function
def go_to_page(cls, url, browser_type=None): driver = cls._check_browser_type(browser_type) driver.get(url=url.strip()) return driver
Python
nomic_cornstack_python_v1