code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
for month in range 1 months + 1 begin set electricity_bill = decimal input set electricity_sum = electricity_sum + electricity_bill set water_bill = 20 set net_bill = 15 set others = electricity_bill + water_bill + net_bill set others_bill = others * 1.2 set others_sum = others_sum + others_bill set avg_bill = electric...
for month in range(1, months + 1): electricity_bill = float(input()) electricity_sum += electricity_bill water_bill = 20 net_bill = 15 others = electricity_bill + water_bill + net_bill others_bill = others * 1.2 others_sum += others_bill avg_bill = (electricity_sum + water_bill * months ...
Python
zaydzuhri_stack_edu_python
function do_host_downgrade cc args begin call _find_ihost cc hostid set tuple system_type system_mode = call _get_system_info cc set simplex = system_mode == SYSTEM_MODE_SIMPLEX if simplex begin set warning_message = string WARNING: THIS OPERATION WILL COMPLETELY ERASE ALL DATA FROM THE SYSTEM. Only proceed once the sy...
def do_host_downgrade(cc, args): ihost_utils._find_ihost(cc, args.hostid) system_type, system_mode = utils._get_system_info(cc) simplex = system_mode == constants.SYSTEM_MODE_SIMPLEX if simplex: warning_message = ( '\n' 'WARNING: THIS OPERATION WILL COMPLETELY ERASE ALL ...
Python
nomic_cornstack_python_v1
import sys , getopt import json set filename = string urls.json function addGroup group begin with open filename as f begin set data = load json f end set tmp = data set data at group = list print values data with open filename string w as f begin dump data f end end function function addAddress group address begin wi...
import sys, getopt import json filename = "urls.json" def addGroup(group): with open(filename) as f: data = json.load(f) tmp = data data[group] = [] print(data.values()) with open(filename, 'w') as f: json.dump(data, f) def addAddress(group, address): with open(filename) ...
Python
zaydzuhri_stack_edu_python
comment rapid_cooling.py # comment # comment Read in decompressed HRIT files (currently only # comment 10.8 micron BT) and output netcdf of cells and # comment a text file with id information. # comment # comment Written by Alexander Roberts # comment June 2019 # comment NCAS, ICAS, University of Leeds # comment # comm...
######################################################### # rapid_cooling.py # # # # Read in decompressed HRIT files (currently only # # 10.8 micron BT) and output netcdf of cells and # # a text file with id info...
Python
zaydzuhri_stack_edu_python
import pandas as pd import numpy as np import re import jieba from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import MultinomialNB from sklearn.multiclass import OneVsRest...
import pandas as pd import numpy as np import re import jieba from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import MultinomialNB from sklearn.multiclass import OneVsRe...
Python
zaydzuhri_stack_edu_python
function relpath path start=none begin if is instance path bytes begin set sep = b'\\' set curdir = b'.' set pardir = b'..' end else begin set sep = string \ set curdir = string . set pardir = string .. end if start is none begin set start = curdir end if not path begin raise call ValueError string no path specified en...
def relpath(path, start=None): if isinstance(path, bytes): sep = b'\\' curdir = b'.' pardir = b'..' else: sep = '\\' curdir = '.' pardir = '..' if start is None: start = curdir if not path: raise ValueError("no path specified") try: ...
Python
nomic_cornstack_python_v1
function details id begin set details = first filter by query id=id if details is not none begin return call render_template string details.html details=details end else begin return call render_template string 404.html end end function
def details(id): details = Article.query.filter_by(id=id).first() if details is not None: return render_template('details.html', details=details) else: return render_template('404.html')
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np import sklearn.feature_selection as fs from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error from sklearn.preprocessing import StandardScaler class Utils begin string Utility class for ...
import pandas as pd import numpy as np import sklearn.feature_selection as fs from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error from sklearn.preprocessing import StandardScaler class Utils: """ Utility class fo...
Python
zaydzuhri_stack_edu_python
function whitelist_provided technology begin set upper = upper technology return upper in TECHNOLOGIES_MAPPING and whitelist_archive end function
def whitelist_provided(technology): upper = technology.upper() return upper in TECHNOLOGIES_MAPPING and TECHNOLOGIES_MAPPING[ upper].whitelist_archive
Python
nomic_cornstack_python_v1
string Length of LIS You are given an array A. You need to find the length of the Longest Increasing Subsequence in the array. In other words, you need to find a subsequence of array A in which the elements are in sorted order, (strictly increasing) and as long as possible. Problem Constraints 1 ≤ length(A), A[i] ≤ 10^...
''' Length of LIS You are given an array A. You need to find the length of the Longest Increasing Subsequence in the array. In other words, you need to find a subsequence of array A in which the elements are in sorted order, (strictly increasing) and as long as possible. Problem Constraints 1 ≤ length(A), A[i] ≤ 10^...
Python
zaydzuhri_stack_edu_python
async function test_watch_initialize begin for current_type in WatchKubernetesEventType begin call WatchKubernetesEvent current_type dict end end function
async def test_watch_initialize(): for current_type in WatchKubernetesEventType: WatchKubernetesEvent(current_type, {})
Python
nomic_cornstack_python_v1
comment ! /usr/bin/env python comment coding=utf-8 comment 第四章 操作列表 comment 遍历整个列表 set magicians = list string alice string david string carolina
#! /usr/bin/env python # coding=utf-8 # 第四章 操作列表 # 遍历整个列表 magicians = ['alice', 'david', 'carolina']
Python
zaydzuhri_stack_edu_python
function preset_speke20_audio self begin return get pulumi self string preset_speke20_audio end function
def preset_speke20_audio(self) -> 'OriginEndpointEncryptionContractConfigurationPresetSpeke20Audio': return pulumi.get(self, "preset_speke20_audio")
Python
nomic_cornstack_python_v1
function read_in_all_images address_list shuffle=true is_random_label=false begin set data = reshape array list list 0 IMG_WIDTH * IMG_HEIGHT * IMG_DEPTH set label = array list for address in address_list begin print string Reading images from + address set tuple batch_data batch_label = call _read_one_batch address is...
def read_in_all_images(address_list, shuffle=True, is_random_label=False): data = np.array([]).reshape([0, IMG_WIDTH * IMG_HEIGHT * IMG_DEPTH]) label = np.array([]) for address in address_list: print('Reading images from ' + address) batch_data, batch_label = _read_one_batch(address, ...
Python
nomic_cornstack_python_v1
comment Importing OpenCV library import cv2 , os comment user define function comment that return None or function check_empty_img img begin comment Reading Image comment You can give path to the comment image as first argument set image = call imread img comment Checking if the image is empty or not if image is none b...
# Importing OpenCV library import cv2, os # user define function # that return None or def check_empty_img(img): # Reading Image # You can give path to the # image as first argument image = cv2.imread(img) # Checking if the image is empty or not if image is None: result = "Image is em...
Python
zaydzuhri_stack_edu_python
set a = 10 set b = 10.5 set c = a + b print c set d = a ^ 2 print integer 450.0 set name = string John print name print name print upper name print ends with name string n set is_ok = false set a_greater_than_b = a > b print a_greater_than_b set coords = list 1 2.406 print coords at 1
a = 10 b = 10.5 c = a + b print(c) d = a **2 print(int(450.0)) name = "John" print(name) print(name) print(name.upper()) print(name.endswith("n")) is_ok = False a_greater_than_b = a > b print(a_greater_than_b) coords = [1, 2.406] print(coords[1])
Python
zaydzuhri_stack_edu_python
import pyautogui , os class Functionality begin function __init__ self profile=none begin set profile = profile set func_list = list set hotkeys = call fromkeys list 1 2 3 4 5 6 7 8 9 10 string if profile == 1 begin for i in range 10 begin append func_list pressHotkey call setHotkey i + 1 list string Ctrl string i end...
import pyautogui, os class Functionality(): def __init__(self, profile=None): self.profile = profile self.func_list = [] self.hotkeys = dict.fromkeys([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], "") if profile == 1: for i in range(10): self.func_list.append(self.pr...
Python
zaydzuhri_stack_edu_python
comment ! /usr/bin/env python comment -*- coding: utf8 -*- comment author: dreampython comment date: 2018-10-22 comment 第 0005 题: 你有一个目录,装了很多照片, comment 把它们的尺寸变成都不大于 iPhone5 分辨率的大小 comment iphone5的分辨率大小: 320*568 from PIL import Image import os import imghdr comment iphone5分辨率大小 set iphone_size = tuple 320 568 comment 获...
#! /usr/bin/env python # -*- coding: utf8 -*- # author: dreampython # date: 2018-10-22 # 第 0005 题: 你有一个目录,装了很多照片, # 把它们的尺寸变成都不大于 iPhone5 分辨率的大小 # iphone5的分辨率大小: 320*568 from PIL import Image import os import imghdr # iphone5分辨率大小 iphone_size = (320, 568) # 获取目录中所有的图片文件 def get_image_file(image_path): image_file...
Python
zaydzuhri_stack_edu_python
import cv2 import matplotlib.pyplot as plt comment mở file ảnh set img = call imread string E://hoa.jpg 0 comment cân bằng hist cho ảnh img set img_equalized = call equalizeHist img comment Tạo vùng vẽ tỷ lệ 16:9 set fig = figure figsize=tuple 16 9 comment Tạo 4 vùng vẽ con, 2 cột 2 hàng set tuple tuple ax1 ax2 tuple a...
import cv2 import matplotlib.pyplot as plt img = cv2.imread('E://hoa.jpg',0) # mở file ảnh img_equalized = cv2.equalizeHist(img) # cân bằng hist cho ảnh img fig = plt.figure(figsize=(16, 9))#Tạo vùng vẽ tỷ lệ 16:9 (ax1, ax2), (ax3,ax4) = fig.subplots(2, 2)#Tạo 4 vùng vẽ con, 2 cột 2 hàng # Vẽ ảnh gốc trong vùng ax1 ...
Python
zaydzuhri_stack_edu_python
function sort_string string begin set sorted_string = sorted string return join string sorted_string end function
def sort_string(string): sorted_string = sorted(string) return ''.join(sorted_string)
Python
jtatman_500k
if n at 0 == string а begin print string Да end else begin print string Нет end
if n[0] == 'а': print('Да') else: print('Нет')
Python
zaydzuhri_stack_edu_python
function getScheduleById self scheduleId begin set url = _v2BaseURL + string /api/v2/schedule/ + scheduleId set headers = dict string Content-Type string application/json ; string Accept string application/json ; string icSessionID _v2icSessionID info string getScheduleById URL - + url info string API Headers: + string...
def getScheduleById(self, scheduleId): url=self._v2BaseURL + "/api/v2/schedule/" + scheduleId headers = {'Content-Type': "application/json", 'Accept': "application/json","icSessionID":self._v2icSessionID} infapy.log.info("getScheduleById URL - " + url) infapy.log.info("API Headers: " + s...
Python
nomic_cornstack_python_v1
function _compute_reward self observations done begin raise call NotImplementedError end function
def _compute_reward(self, observations, done): raise NotImplementedError()
Python
nomic_cornstack_python_v1
for i in range n begin set name = input if length name <= 10 begin print name end else begin print name at 0 + string length name at slice 1 : - 1 : + name at - 1 end end
for i in range(n): name = input() if len(name) <= 10: print(name) else: print(name[0] + str(len(name[1:-1])) + name[-1])
Python
zaydzuhri_stack_edu_python
function get_ssm_secret_value parameter_name begin comment https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ssm.html#SSM.Client.get_parameter return get get call get_parameter Name=parameter_name WithDecryption=true string Parameter string Value end function
def get_ssm_secret_value(parameter_name): # https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ssm.html#SSM.Client.get_parameter return SSM.get_parameter( Name=parameter_name, WithDecryption=True ).get("Parameter").get("Value")
Python
nomic_cornstack_python_v1
comment @lc app=leetcode.cn id=344 lang=python comment [344] reverse-string class Solution extends object begin function reverseString self s begin string :type s: List[str] :rtype: None Do not return anything, modify s in-place instead. for i in range length s // 2 begin set tuple s at i s at length s - i - 1 = tuple ...
# # @lc app=leetcode.cn id=344 lang=python # # [344] reverse-string # class Solution(object): def reverseString(self, s): """ :type s: List[str] :rtype: None Do not return anything, modify s in-place instead. """ for i in range(len(s)//2): s[i],s[len(s)-i-1]=s[len...
Python
zaydzuhri_stack_edu_python
function set_transformation_anchor self mode begin call setTransformationAnchor call get_enum_value mode end function
def set_transformation_anchor(self, mode: ViewportAnchorStr | mod.ViewportAnchor): self.setTransformationAnchor(VIEWPORT_ANCHOR.get_enum_value(mode))
Python
nomic_cornstack_python_v1
function test_adjust_gamma_less_zero_uint8 self begin with call cached_session begin set x_data = uniform 0 255 tuple 8 8 set x_np = array x_data dtype=uint8 set x = call constant x_np shape=shape set err_msg = string Gamma should be a non-negative real number with call assertRaisesRegex tuple ValueError InvalidArgumen...
def test_adjust_gamma_less_zero_uint8(self): with self.cached_session(): x_data = np.random.uniform(0, 255, (8, 8)) x_np = np.array(x_data, dtype=np.uint8) x = constant_op.constant(x_np, shape=x_np.shape) err_msg = "Gamma should be a non-negative real number" with self.assertRaisesRe...
Python
nomic_cornstack_python_v1
import json , pygame import enemies as E import render from render import width , height from math import degrees , radians from movement import get_deg_direction from main import calculate_damage_mod from animations import Animation class Special begin function __init__ self position speed direction surface damage=0 l...
import json, pygame import enemies as E import render from render import width, height from math import degrees, radians from movement import get_deg_direction from main import calculate_damage_mod from animations import Animation class Special: def __init__(self, position, speed, direction, surface, damage=0, lifet...
Python
zaydzuhri_stack_edu_python
import csv import mysql.connector from mysql.connector import Error import os.path as path import datetime set path_dir = string C:\Assignment\Data-CaseStudy set source_csv = string sales_data_sample.csv set host_name = string 127.0.0.1 set db_name = string salesdwh set my_username = string raouf set my_password = stri...
import csv import mysql.connector from mysql.connector import Error import os.path as path import datetime path_dir = r"C:\Assignment\Data-CaseStudy" source_csv = r"sales_data_sample.csv" host_name="127.0.0.1" db_name = "salesdwh" my_username = "raouf" my_password = "123456" def test_database_connection(host, db, us...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from keras.utils import np_utils from tensorflow.contrib import rnn string Created by Mohsen Naghipourfar on 2019-01-03. Email : mn7697np@gmail.com or naghipourfar@ce.sharif.edu Website: http://ce.sharif.edu/~naghipourfar Github: https://github....
import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from keras.utils import np_utils from tensorflow.contrib import rnn """ Created by Mohsen Naghipourfar on 2019-01-03. Email : mn7697np@gmail.com or naghipourfar@ce.sharif.edu Website: http://ce.sharif.edu/~naghipourfar Github: h...
Python
zaydzuhri_stack_edu_python
function get_model cls begin if model == none begin set model = call Graph with call as_default begin set od_graph_def = call GraphDef with call GFile string detect_model_idcardv3.pb string rb as fid begin set serialized_graph = read fid call ParseFromString serialized_graph call import_graph_def od_graph_def name=stri...
def get_model(cls): if cls.model == None: cls.model = tf.Graph() with cls.model.as_default(): od_graph_def = tf.GraphDef() with tf.gfile.GFile('detect_model_idcardv3.pb', 'rb') as fid: serialized_graph = fid.read() o...
Python
nomic_cornstack_python_v1
async function userinfo ctx user=none begin if user is none begin set user = author end set roles = list comprehension mention for role in roles if not call is_default set voice = voice if voice is not none begin set vc = channel set other_people = length members - 1 set voice = if expression other_people then string I...
async def userinfo(ctx, *, user: discord.Member=None): if user is None: user = ctx.author roles = [role.mention for role in user.roles if not role.is_default()] voice = user.voice if voice is not None: vc = voice.channel other_people = len(vc.members) - 1 voice = f'In {vc.name} with {other_people} other(s...
Python
nomic_cornstack_python_v1
function __eq__ self other begin if not is instance other PostTaxRatesTaxRate begin return false end return call to_dict == call to_dict end function
def __eq__(self, other): if not isinstance(other, PostTaxRatesTaxRate): return False return self.to_dict() == other.to_dict()
Python
nomic_cornstack_python_v1
comment Insert a node in a sorted circular linked list class LinkedList begin function __init__ self data begin set data = data set next = none end function function insert self node begin set current = self while next is not none begin set current = next end set next = node end function end class function PrintLinkedL...
#Insert a node in a sorted circular linked list class LinkedList: def __init__(self,data): self.data = data self.next = None def insert(self,node): current = self while(current.next is not None): current = current.next current.next = node def PrintLinkedList(list): while list is not None: if list.n...
Python
zaydzuhri_stack_edu_python
function spm_dartel_make gm wm template_dir template_nme begin set startdir = get current directory change directory template_dir set dartel = call DARTEL matlab_cmd=string matlab-spm8 set image_files = list gm wm set template_prefix = template_nme set dartel_out = run change directory startdir return dartel_out end fu...
def spm_dartel_make(gm, wm, template_dir, template_nme): startdir = os.getcwd() os.chdir(template_dir) dartel = npe.DARTEL(matlab_cmd = 'matlab-spm8') dartel.inputs.image_files = [gm, wm] dartel.inputs.template_prefix = template_nme dartel_out = dartel.run() os.chdir(startdir) return dar...
Python
nomic_cornstack_python_v1
comment Zeit wird gezaehlt import math import pygame import random import os import time from pygame.locals import * function load_image name color_key=none begin set fullname = join path string data name try begin set image = load image fullname end except error as message begin print string Cannot load image: name ra...
# Zeit wird gezaehlt import math import pygame import random import os import time from pygame.locals import * def load_image(name, color_key=None): fullname = os.path.join('data', name) try: image = pygame.image.load(fullname) except pygame.error as message: print('Cannot lo...
Python
zaydzuhri_stack_edu_python
comment coding: utf-8 function quick_sort array begin if length array < 1 begin return array end set mid = array length array // 2 set r = list comprehension a for a in array if a > mid set l = list comprehension a for a in array if a < mid set mid = list return call quick_sort l + mid + call quick_sort r end function...
# coding: utf-8 def quick_sort(array): if len(array) < 1: return array mid = array(len(array) // 2) r = [a for a in array if a > mid] l = [a for a in array if a < mid] mid = [] return quick_sort(l) + mid + quick_sort(r) aaa = quick_sort([1, 4, 5, 3, 6]) print(aaa)
Python
zaydzuhri_stack_edu_python
function row_factory self begin set row_factory = Row set _cursor = call cursor end function
def row_factory(self): self._connection.row_factory = sqlite3.Row self._cursor = self._connection.cursor()
Python
nomic_cornstack_python_v1
function setExclusive self val=string True **kwargs begin pass end function
def setExclusive(self, val='True', **kwargs): pass
Python
nomic_cornstack_python_v1
function postprocess self x begin set data_mismatch = norm x at 1 - call matvec x at 0 comment Update min_error and best solution if required if data_mismatch < min_error begin if best_estimate is not none begin print string Better solution found! end set best_estimate = x at 0 set min_error = data_mismatch end return ...
def postprocess(self, x: list) -> np.ndarray: data_mismatch = np.linalg.norm(x[1] - self.linear_op.matvec(x[0])) # Update min_error and best solution if required if data_mismatch < self.min_error: if self.best_estimate is not None: print('Better solution found!') ...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Thu Apr 29 09:21:00 2021 @author: Nishith set lst = list 33 4 45 31 23 442 12 sort lst print lst at length lst - 2
# -*- coding: utf-8 -*- """ Created on Thu Apr 29 09:21:00 2021 @author: Nishith """ lst=[33,4,45,31,23,442,12] lst.sort() print(lst[len(lst)-2])
Python
zaydzuhri_stack_edu_python
function compress_array array begin return tuple compress array shape dtype end function
def compress_array(array: np.ndarray) -> CompressedArray: return snappy.compress(array), array.shape, array.dtype
Python
nomic_cornstack_python_v1
import matplotlib.pyplot as plt import numpy as np import matplotlib.path as mpath import matplotlib.lines as mlines import matplotlib.patches as mpatches from matplotlib.collections import PatchCollection comment -------------------------------------------------------- import predict set data = call loadtxt string wif...
import matplotlib.pyplot as plt import numpy as np import matplotlib.path as mpath import matplotlib.lines as mlines import matplotlib.patches as mpatches from matplotlib.collections import PatchCollection #-------------------------------------------------------- import predict data = np.loadtxt('wifi_db/noisy_dataset....
Python
zaydzuhri_stack_edu_python
function contact request begin if method == string POST begin set contact_form = call ContactForm POST comment sends emails to admin and user. if call is_valid begin set user_email = cleaned_data at string email set subject = string Message Receipt Confirmation: + cleaned_data at string subject set body = call render_t...
def contact(request): if request.method == 'POST': contact_form = ContactForm(request.POST) # sends emails to admin and user. if contact_form.is_valid(): user_email = contact_form.cleaned_data['email'] subject = (" Message Receipt Confirmation: " + ...
Python
nomic_cornstack_python_v1
function get_version begin try begin with open string PyRuSH/version.py string r as f begin return strip replace split split read f string at 0 string = at - 1 string ' string end end except IOError begin return string 0.0.0a1 end end function
def get_version(): try: with open('PyRuSH/version.py', 'r') as f: return f.read().split('\n')[0].split('=')[-1].replace('\'', '').strip() except IOError: return "0.0.0a1"
Python
nomic_cornstack_python_v1
comment Performing natural language translation using Transformers. from transformers import AutoTokenizer , AutoModelForSeq2SeqLM comment Initialize the tokenizer and model. comment Implement the translation functionality.
# Performing natural language translation using Transformers. from transformers import AutoTokenizer, AutoModelForSeq2SeqLM # Initialize the tokenizer and model. # Implement the translation functionality.
Python
flytech_python_25k
comment ****************************************************************************** comment tictactoe.py comment ****************************************************************************** comment Name: Ron Balaban comment ****************************************************************************** comment Coll...
#****************************************************************************** # tictactoe.py #****************************************************************************** # Name: Ron Balaban #****************************************************************************** # Collaborators/outside sources used #...
Python
zaydzuhri_stack_edu_python
comment Crie um programa que leia um número inteiro e mostre na tela se ele é par ou impar. set num = integer input string Digite um número inteiro para saber se é par ou impar: set divi = num % 2 if divi == 0 begin print string É par! end else begin print string É ímpar! end
#Crie um programa que leia um número inteiro e mostre na tela se ele é par ou impar. num = int(input('Digite um número inteiro para saber se é par ou impar: ')) divi = num % 2 if divi == 0: print('É par!') else: print('É ímpar!')
Python
zaydzuhri_stack_edu_python
function permutationdecompose N begin print N set seed = 1 while seed < N begin print seed end=string , set t = seed * 2 % N + 1 while t != seed begin print t end=string , set t = t * 2 % N + 1 end print set seed = 3 * seed end end function if __name__ == string __main__ begin call permutationdecompose 8 call permutati...
def permutationdecompose(N): print(N) seed = 1 while seed < N: print(seed,end=',') t = (seed*2)%(N+1) while t != seed: print(t,end=',') t = (t*2)%(N+1) print() seed = 3*seed if __name__ == '__main__': permutationdecompose(8) permutationdecompose(6) permutationdecompose(0)
Python
zaydzuhri_stack_edu_python
function getInputHkl begin set focus = call getFocusObject if focus begin set thread = windowThreadID end else begin set thread = 0 end return call GetKeyboardLayout thread end function
def getInputHkl(): focus = api.getFocusObject() if focus: thread = focus.windowThreadID else: thread = 0 return winUser.user32.GetKeyboardLayout(thread)
Python
nomic_cornstack_python_v1
string @Descripttion: 计数V2.0 @Author: daxiong @Date: 2019-09-20 20:17:18 @LastEditors: daxiong @LastEditTime: 2019-09-20 20:20:27 set T = integer strip input for round in range T begin set s = split strip input set tuple n m = tuple integer s at 0 integer s at 1 set points = list comprehension integer val for val in sp...
''' @Descripttion: 计数V2.0 @Author: daxiong @Date: 2019-09-20 20:17:18 @LastEditors: daxiong @LastEditTime: 2019-09-20 20:20:27 ''' T = int(input().strip()) for round in range(T): s = input().strip().split() n, m = int(s[0]), int(s[1]) points = [int(val) for val in input().strip().split()] intervals = l...
Python
zaydzuhri_stack_edu_python
function directories self begin return get pulumi self string directories end function
def directories(self) -> Optional[Sequence['outputs.DirectoryPathResponse']]: return pulumi.get(self, "directories")
Python
nomic_cornstack_python_v1
import json import pandas as pd import sys import random import numpy as np from parser import * class JobCatVecotrizer extends object begin function __init__ self begin set pat = dict string medical list string nurse string healthcare string physician string rn ; string engineer list string engineer string software st...
import json import pandas as pd import sys import random import numpy as np from parser import * class JobCatVecotrizer(object): def __init__(self): self.pat = {'medical':['nurse','healthcare','physician', ' rn '] , 'engineer':['engineer','software','developer',' it '] ,'analysis':['analyst','analytics','data s...
Python
zaydzuhri_stack_edu_python
comment CaesarCode.py set org = input set enc = string
#CaesarCode.py org = input() enc = ''
Python
zaydzuhri_stack_edu_python
function check_in self request pk=none begin set book = call get_object set serializer_context = dict string request request set serializer = call BookSerializer book context=serializer_context if checked_out_by == none begin raise call BookCheckedInException end set checked_out_by = none save return call Response data...
def check_in(self, request, pk=None): book = self.get_object() serializer_context = { 'request': request, } serializer = BookSerializer(book, context=serializer_context) if book.checked_out_by == None: raise BookCheckedInException() book.checked_o...
Python
nomic_cornstack_python_v1
for i in range integer input begin set s = list input set flag = 0 for j in range 0 length s begin if s at j != string . begin for k in range j + 1 length s begin if s at k != string . begin comment print(j+int(s[j]),k-int(s[k])) if j + integer s at j >= k - integer s at k begin set flag = 1 break end end end end if fl...
for i in range(int(input())): s=list(input()) flag=0 for j in range(0,len(s)): if s[j]!='.': for k in range(j+1,len(s)): if s[k]!='.' : #print(j+int(s[j]),k-int(s[k])) if j+int(s[j])>=k-int(s[k]): flag=1 ...
Python
zaydzuhri_stack_edu_python
import random function a_Move arr begin for i in range 4 begin for j in range 3 begin if arr at i at j == arr at i at j + 1 begin set arr at i at j = 2 * arr at i at j set arr at i at j + 1 = 0 end end end for i in range 4 begin for j in range 1 4 begin if arr at i at j != 0 begin set temp = j while temp > 0 and arr at...
import random def a_Move(arr): for i in range(4): for j in range(3): if arr[i][j] == arr[i][j + 1]: arr[i][j] = 2 * arr[i][j] arr[i][j + 1] = 0 for i in range(4): for j in range(1,4): if arr[i][j] != 0: temp = j ...
Python
zaydzuhri_stack_edu_python
from tkinter import * set root = call Tk comment window configuration title root string Calculator call iconbitmap string calc.ico call config bg=string gray79 comment Entry widget to display the value set e = call Entry root width=60 borderwidth=10 grid row=0 column=0 columnspan=5 padx=10 pady=10 set operation = strin...
from tkinter import * root = Tk() # window configuration root.title("Calculator") root.iconbitmap('calc.ico') root.config(bg="gray79") # Entry widget to display the value e = Entry(root, width=60, borderwidth=10) e.grid(row=0, column=0, columnspan=5, padx=10, pady=10) operation = "" f_num = "" # This will take what...
Python
zaydzuhri_stack_edu_python
function array self begin comment if self._pars[pkeys[0]].size() > 1: set x = zeros tuple length _pars size for tuple i p in enumerate _pars begin set x at i = value end return x end function
def array(self): # if self._pars[pkeys[0]].size() > 1: x = np.zeros((len(self._pars),self._pars[0].size)) for i, p in enumerate(self._pars): x[i] = p.value return x
Python
nomic_cornstack_python_v1
set name = input string ¿Como te llamas? set n = input string Introduce un numero entero: print name + string * integer n
name = input("¿Como te llamas?") n = input("Introduce un numero entero: ") print((name + "\n") * int (n))
Python
zaydzuhri_stack_edu_python
comment rje, 5/07, example 5 comment list the words in Windows Haiku comment rje, Python 3 import os set haiku = string set fp = open string Haiku.txt for line in fp begin set haiku = haiku + line end print haiku print string set words = split haiku set word_list = list for w in words begin set w = strip w string .,;...
# rje, 5/07, example 5 # list the words in Windows Haiku # rje, Python 3 import os haiku = '' fp = open("Haiku.txt") for line in fp: haiku += line print(haiku) print("\n") words = haiku.split() word_list = [] for w in words: w = w.strip(' .,;:"!-?') w = w.lower() word_list.append(w) wo...
Python
zaydzuhri_stack_edu_python
function input self begin string Return a list of all the aesthetics covered by the scales. set lst = list comprehension aesthetics for s in self return list chain *lst end function
def input(self): """ Return a list of all the aesthetics covered by the scales. """ lst = [s.aesthetics for s in self] return list(itertools.chain(*lst))
Python
jtatman_500k
from socket import * import sys from constants import * function receive_Line sock begin set data = string while true begin set data = data + decode call recv BUFSIZE if data == string begin raise call RuntimeError string socket connection broken end else if data at length data - 1 == string begin return data end en...
from socket import * import sys from constants import * def receive_Line(sock): data = "" while True: data += sock.recv(BUFSIZE).decode() if data == '': raise RuntimeError("socket connection broken") elif data[len(data)-1] == "\n": return data def send_Line(sock...
Python
zaydzuhri_stack_edu_python
function update_answer self answer_form begin string Updates an existing answer. arg: answer_form (osid.assessment.AnswerForm): the form containing the elements to be updated raise: IllegalState - ``answer_form`` already used in an update transaction raise: InvalidArgument - the form contains an invalid value raise: Nu...
def update_answer(self, answer_form): """Updates an existing answer. arg: answer_form (osid.assessment.AnswerForm): the form containing the elements to be updated raise: IllegalState - ``answer_form`` already used in an update transaction raise: Inva...
Python
jtatman_500k
function validate_packages self data begin from utils import Constant if call get_packages_schema_version not in data begin set result_message = string Javatar packages are incompatible + string with current version call add_action string javatar.core.packages_updater.validate_packages result_message return none end se...
def validate_packages(self, data): from ..utils import Constant if Constant.get_packages_schema_version() not in data: self.result_message = ("Javatar packages are incompatible" + " with current version") ActionHistory().add_action( ...
Python
nomic_cornstack_python_v1
comment table creation import mysql.connector as sql set mycon = call connect host=string localhost user=string root passwd=string lj2002 database=string ljdaosm set cursor = call cursor if call is_connected begin print string connection succesful end comment (i) execute cursor string select teacher.name, salary.da fro...
#table creation import mysql.connector as sql mycon=sql.connect(host="localhost",user="root",passwd="lj2002",database="ljdaosm") cursor=mycon.cursor() if mycon.is_connected(): print("connection succesful") #(i) cursor.execute('select teacher.name, salary.da from teacher,salary where teacher...
Python
zaydzuhri_stack_edu_python
comment Vypis (s pomoci funkce input). comment Zadej prosim cislo x: comment Zadej prosim cislo y: comment Uzivatel zada cislo x a pote cislo y comment Vypis soucet mezi x a y. comment Soucet je: [soucet x a y] function soucet begin set x = integer input string Zadej prosim cislo x: set y = integer input string Zadej p...
# Vypis (s pomoci funkce input). # Zadej prosim cislo x: # Zadej prosim cislo y: # Uzivatel zada cislo x a pote cislo y # Vypis soucet mezi x a y. # Soucet je: [soucet x a y] def soucet(): x = int(input("Zadej prosim cislo x:")) y = int(input("Zadej prosim cislo y:")) soucet = x + y print("Soucet je: "...
Python
zaydzuhri_stack_edu_python
comment calculating pascal's row based on line condition and calculating inline pascal's kth line. comment time - O(N), where the N is the given input k, so we will iterate k number of times. comment space - O(N), output array. class Solution begin function getPascalRow self k begin comment if k is 0 return 1. set line...
# calculating pascal's row based on line condition and calculating inline pascal's kth line. # time - O(N), where the N is the given input k, so we will iterate k number of times. # space - O(N), output array. class Solution: def getPascalRow(self, k): line = [1] # if k is 0 return 1. for i ...
Python
zaydzuhri_stack_edu_python
function __ne__ self other begin return not self == other end function
def __ne__(self, other: 'MessageContextGlobalStateless') -> bool: return not self == other
Python
nomic_cornstack_python_v1
function from_word cls word begin return call cls word=word definition=definition end function
def from_word(cls, word): return cls(word=word.word, definition=word.definition)
Python
nomic_cornstack_python_v1
import pandas as pd function get_data begin comment ローカルに保存済みのデータセット(このフォルダと同じ階層のinputフォルダ内に「train.csv」「test.csv」を想定)を読み込む set train = read csv string ../input/train.csv set test = read csv string ../input/test.csv set X = drop train list string label axis=1 set X = values set y = array train at string label comment 分類...
import pandas as pd def get_data(): # ローカルに保存済みのデータセット(このフォルダと同じ階層のinputフォルダ内に「train.csv」「test.csv」を想定)を読み込む train = pd.read_csv('../input/train.csv') test= pd.read_csv('../input/test.csv') X = train.drop(["label"],axis=1) X =X.values y = np.array(train["label"]) n_labels = len(np.unique(y...
Python
zaydzuhri_stack_edu_python
function addToList item begin if item in myUniqueList begin append myLeftovers item return false end else begin append myUniqueList item end end function call addToList string Hello call addToList string World call addToList string World call addToList string It call addToList string Is call addToList string Is call ad...
def addToList(item): if item in myUniqueList: myLeftovers.append(item) return False else: myUniqueList.append(item) addToList("Hello") addToList("World") addToList("World") addToList("It") addToList("Is") addToList("Is") addToList("A") addToList("Great") addToList("Day!") addToList(35) addToList("Degrees") a...
Python
zaydzuhri_stack_edu_python
function _get_shapefile_regions sourcefile attr_key attr_vals projection=none projection_key=string projection_forUKCP begin debug format string Reading shapefile {} sourcefile comment Create the shapefile Reader object: set regfileReader = reader sourcefile try begin if attr_vals is none begin debug string All availab...
def _get_shapefile_regions(sourcefile, attr_key, attr_vals, projection=None, projection_key='projection_forUKCP'): log.debug("Reading shapefile {}".format(sourcefile)) # Create the shapefile Reader object: regfileReader = shpreader.Reader(sourcefile) ...
Python
nomic_cornstack_python_v1
function isSafe y x begin return 0 <= y < N and 0 <= x < N and maze at y at x == 0 or maze at y at x == 3 end function function bfs sy sx begin global result append q tuple sy sx append visited tuple sy sx while q begin set tuple sy sx = pop q 0 for i in range 4 begin set ny = sy + dy at i set nx = sx + dx at i if call...
def isSafe(y,x): return 0 <= y < N and 0<= x < N and (maze[y][x] == 0 or maze[y][x] == 3) def bfs(sy, sx): global result q.append((sy, sx)) visited.append((sy, sx)) while q: sy, sx = q.pop(0) for i in range(4): ny = sy + dy[i] nx = sx + dx[i] if ...
Python
zaydzuhri_stack_edu_python
function __str__ self begin set result = string for row in from_grid begin for element in row begin set result = result + string element set result = result + string end set result = strip result string set result = result + string end set result = strip result string return result end function
def __str__(self): result = "" for row in self.from_grid: for element in row: result += str(element) result += " " result = result.strip(" ") result += "\n" result = result.strip("\n") return result
Python
nomic_cornstack_python_v1
function create_model mode model_creator input_pipeline_creator hparams begin set sess_config = call ConfigProto allow_soft_placement=allow_soft_placement gpu_options=call GPUOptions per_process_gpu_memory_fraction=gpu_mem_frac inter_op_parallelism_threads=cpu_threads intra_op_parallelism_threads=cpu_threads call reset...
def create_model(mode, model_creator, input_pipeline_creator, hparams): sess_config = tf.ConfigProto(allow_soft_placement=hparams.allow_soft_placement, gpu_options=tf.GPUOptions( per_process_gpu_memory_fraction=hparams.gpu_mem_frac ...
Python
nomic_cornstack_python_v1
function setUp self begin set env = call EnvironmentStub default_data=true enable=list string ticket-field-config.* comment this is the default data that is in the test Trac database set default = dict string priority list string blocker string critical string major string minor string trivial ; string severity list ;...
def setUp(self): self.env = EnvironmentStub(default_data=True, enable=['ticket-field-config.*']) # this is the default data that is in the test Trac database self.default = { 'priority':['blocker', 'critical', 'major', 'minor', 'trivial'], ...
Python
nomic_cornstack_python_v1
function pc_input_buffers_full self *args begin return call atsc_field_sync_mux_sptr_pc_input_buffers_full self *args end function
def pc_input_buffers_full(self, *args): return _atsc_swig.atsc_field_sync_mux_sptr_pc_input_buffers_full(self, *args)
Python
nomic_cornstack_python_v1
function click_play_button self begin call click end function
def click_play_button(self): self.SABL.play_button().click()
Python
nomic_cornstack_python_v1
function Run self _ begin set client = call GetClientFromFlags set params = call GetGlobalParamsFromFlags for field in call all_fields begin set value = call get_assigned_value name if value != default begin call AddGlobalParam name value end end set banner = string == dns interactive console == client: a dns client ap...
def Run(self, _): client = GetClientFromFlags() params = GetGlobalParamsFromFlags() for field in params.all_fields(): value = params.get_assigned_value(field.name) if value != field.default: client.AddGlobalParam(field.name, value) banner = """ == dns interactive console =...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string from mmc import MMC import random as r from operator import itemgetter import numpy as np import math as m import matplotlib.pyplot as plt function make_choice p begin string chooses an action from a set with discrete cumulative distribution p. Returns index of p based on a generat...
# -*- coding: utf-8 -*- """ """ from mmc import MMC import random as r from operator import itemgetter import numpy as np import math as m import matplotlib.pyplot as plt def make_choice(p): '''chooses an action from a set with discrete cumulative distribution p. Returns index of p based on a generated rando...
Python
zaydzuhri_stack_edu_python
function quantiles x qlist=tuple 2.5 25 50 75 97.5 begin comment Make a copy of trace set x = copy x comment For multivariate node if ndim > 1 begin comment Transpose first, then sort, then transpose back set sx = T end else begin comment Sort univariate node set sx = sort np x end try begin comment Generate specified ...
def quantiles(x, qlist=(2.5, 25, 50, 75, 97.5)): # Make a copy of trace x = x.copy() # For multivariate node if x.ndim > 1: # Transpose first, then sort, then transpose back sx = np.sort(x.T).T else: # Sort univariate node sx = np.sort(x) try: ...
Python
nomic_cornstack_python_v1
function chek_data_type type data begin if type == string int begin print integer data * 2 end else if type == string real begin print string { decimal data * 1.5 } end else if type == string string begin print string $ { data } $ end end function set type_data = input set input_data = input call chek_data_type type_da...
def chek_data_type(type, data): if type == "int": print(int(data) * 2) elif type == "real": print(f"{(float(data) * 1.5):.2f}") elif type == "string": print(f"${data}$") type_data = input() input_data = input() chek_data_type(type_data, input_data)
Python
zaydzuhri_stack_edu_python
comment !/bin/python comment Name: Vanessa Kang comment HackerRank comment Algorithm Track - Warm-up Challenges comment Time Conversion comment Purpose: Given a time in -hour AM/PM format, convert it to military (-hour) time. import sys function timeConversion s begin comment obtain the hour from real time set hour = s...
#!/bin/python #Name: Vanessa Kang #HackerRank #Algorithm Track - Warm-up Challenges #Time Conversion #Purpose: Given a time in -hour AM/PM format, convert it to military (-hour) time. import sys def timeConversion(s): #obtain the hour from real time hour = s[:2] #If the time is in the afternoon, add 12...
Python
zaydzuhri_stack_edu_python
comment Tufts University, Comp 160 wordInterpret coding assignment comment main.py comment wordInterpret comment simple main to test wordInterpret comment NOTE: this main is only for you to test wordInterpret. We will compile comment your code against a different main in our autograder directory from interpret import w...
########################################################################## # # Tufts University, Comp 160 wordInterpret coding assignment # # main.py # wordInterpret # # simple main to test wordInterpret # NOTE: this main is only for you to test wordInterpret. We will compile # your cod...
Python
zaydzuhri_stack_edu_python
function _int64_feature value begin return call Feature int64_list=call Int64List value=list value end function
def _int64_feature(value): return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
Python
nomic_cornstack_python_v1
function call_script name args=list begin function fn begin call list call script name + args end function call time_duration fn end function
def call_script(name, args=[]): def fn(): lib.call([env.script(name)] + args) time_duration(fn)
Python
nomic_cornstack_python_v1
import numpy as np import math from utility import * string This is the implementation of the BP approximation model class Node begin function __init__ self name begin set connections = list set inbox = dict set name = name end function function append self to_node begin append connections to_node append connections ...
import numpy as np import math from utility import * """ This is the implementation of the BP approximation model """ class Node: def __init__(self, name): self.connections = [] self.inbox = {} self.name = name def append(self, to_node): self.connections.append(to_node) ...
Python
zaydzuhri_stack_edu_python
string type: SofaContent from splib.objectmodel import SofaPrefab decorator SofaPrefab class SimplePrefab begin function __init__ self node begin string This is a documented prefab. It creates a simple node called SimplePrefab, and creates a MechanicalObject in it set node = call createChild string SimplePrefab call cr...
""" type: SofaContent """ from splib.objectmodel import SofaPrefab @SofaPrefab class SimplePrefab: def __init__(self, node): """ This is a documented prefab. It creates a simple node called SimplePrefab, and creates a MechanicalObject in it """ self.node = node.createChi...
Python
zaydzuhri_stack_edu_python
from kivy.app import App from kivy.uix.widget import Widget from kivy.core.window import Window from kivy.graphics import Ellipse , Color , Line from tkinter import colorchooser import random from kivy.uix.button import Button comment RGBA = Red, Green, Blue, Opacity set color_value = list 1 1 1 function color_change r...
from kivy.app import App from kivy.uix.widget import Widget from kivy.core.window import Window from kivy.graphics import Ellipse, Color, Line from tkinter import colorchooser import random from kivy.uix.button import Button # RGBA = Red, Green, Blue, Opacity color_value = [1, 1, 1] def color_change(r, g...
Python
zaydzuhri_stack_edu_python
import zlib import codecs set data = string varun123 set compressed = compress data print compressed set hexdata = encode codecs compressed string hex print hexdata
import zlib import codecs data = "varun123" compressed= zlib.compress(data) print(compressed) hexdata = codecs.encode(compressed,'hex') print(hexdata)
Python
zaydzuhri_stack_edu_python
function serialize self root begin if not root begin return string ^$ end else begin return string ^ + string val + call serialize left + call serialize right + string $ end end function
def serialize(self, root): if not root: return '^$' else: return '^' + str(root.val) + self.serialize(root.left) + \ self.serialize(root.right) + '$'
Python
nomic_cornstack_python_v1
function __repr__ self begin set out = string hex(id(self))::: capacity: { capacity } ; next_index: { next_index } return out end function
def __repr__(self): out = f'hex(id(self))::: capacity: {self.capacity}; next_index: {self.next_index}' return out
Python
nomic_cornstack_python_v1
from euler import * import time comment start timer set start = time comment question number set questionno = 34 comment print the problem call print_problem questionno comment Solution function factorial n begin if n == 0 begin return 1 end else begin return n * call factorial n - 1 end end function comment create a d...
from euler import * import time #start timer start = time.time() #question number questionno = 34 #print the problem print_problem(questionno) # # Solution # def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) # create a dictionary of factorials factorials = [factorial(...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding:utf-8 -*- comment Author Jmz comment 一个空格一个星星 string # 面向过程编程 max_level = 4 count =0 tag = True while tag: num = 2 * max_level - 1 star=(2*count+1)*'*' print(star.center(num,' ')) count +=1 if count >= max_level: tag=False comment 函数式编程 function order_star max_level order...
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author Jmz #一个空格一个星星 ''' # 面向过程编程 max_level = 4 count =0 tag = True while tag: num = 2 * max_level - 1 star=(2*count+1)*'*' print(star.center(num,' ')) count +=1 if count >= max_level: tag=False ''' # 函数式编程 def order_star(max_level:int,o...
Python
zaydzuhri_stack_edu_python
comment coding=UTF-8 from app.models import db , Temperature from sqlalchemy import desc , cast , DATE , and_ import datetime class TemperatureDao begin function saveTemperature self employeeId temperature begin set temperatureObj = call Temperature employeeId=employeeId temperature=temperature createdAt=now updatedAt=...
# coding=UTF-8 from app.models import db, Temperature from sqlalchemy import desc, cast, DATE, and_ import datetime class TemperatureDao(): def saveTemperature(self, employeeId, temperature): temperatureObj = Temperature(employeeId=employeeId, temperature=temperature, ...
Python
zaydzuhri_stack_edu_python
function _extract_argmax_and_embed embedding output_projection=none update_embedding=true begin function loop_function prev _ begin if output_projection is not none begin set prev = call xw_plus_b prev output_projection at 0 output_projection at 1 end set prev_symbol = argument maximum prev 1 comment Note that gradient...
def _extract_argmax_and_embed(embedding, output_projection=None, update_embedding=True): def loop_function(prev, _): if output_projection is not None: prev = tf.nn.xw_plus_b(prev, output_projection[0], output_projection[1]) prev_symbol = math_...
Python
nomic_cornstack_python_v1
function getCurrentHealth self begin return currentHealth end function
def getCurrentHealth(self): return self.currentHealth
Python
nomic_cornstack_python_v1
import unittest from roots import list from symbol import * import sexpr function interned L begin return list comprehension call intern x for x in L end function class TestSexpr extends TestCase begin function testsymbol self begin assert equal call str2sexpr string a at 0 call Symbol string a end function function te...
import unittest from roots import list from symbol import * import sexpr def interned(L): return [intern(x) for x in L] class TestSexpr(unittest.TestCase): def testsymbol(self): self.assertEqual(sexpr.str2sexpr('a')[0], Symbol('a')) def teststring(self): self.assertEqual(sexpr.str2sexpr('"1"')[0], '1...
Python
zaydzuhri_stack_edu_python