code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function show begin pass end function
def show(): pass
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding: utf-8 comment # Simulate and Parse Data Generated from SDE comment ## with: *fractional Brownian Driver* comment --- comment # Get Path(s) comment In[1]: comment load dataset set results_path = string ./outputs/models/ set results_tables_path = string ./outputs/results/ set ...
#!/usr/bin/env python # coding: utf-8 # # Simulate and Parse Data Generated from SDE # ## with: *fractional Brownian Driver* # --- # # Get Path(s) # In[1]: # load dataset results_path = "./outputs/models/" results_tables_path = "./outputs/results/" raw_data_path_folder = "./inputs/raw/" data_path_folder = "./inp...
Python
zaydzuhri_stack_edu_python
function gen_covariates labels m1=0.8 m2=0.2 agreement=1 d=3 begin set N = length labels set d = 3 set B = call full tuple d d m2 set B at call diag_indices_from B = m1 set base = call eye d set membership = zeros tuple N d set n_misassign = 0 for i in range 0 N begin set assign = boolean call binomial 1 agreement if a...
def gen_covariates(labels, m1=0.8, m2=0.2, agreement=1, d=3): N = len(labels) d = 3 B = np.full((d, d), m2) B[np.diag_indices_from(B)] = m1 base = np.eye(d) membership = np.zeros((N, d)) n_misassign = 0 for i in range(0, N): assign = bool(np.random.binomial(1, agreement)) ...
Python
nomic_cornstack_python_v1
function update_mass_simulator_parameters_dynamic self begin comment Get the system dict set system_dict = mass_simulator_parameters at string system_dict comment Get combustion table set combustion_table = mass_simulator_parameters at string combustion_table comment ----------------------- Calculate propellant mass co...
def update_mass_simulator_parameters_dynamic(self): # Get the system dict system_dict = self.mass_simulator_parameters['system_dict'] # Get combustion table combustion_table = self.mass_simulator_parameters['combustion_table'] # ----------------------- Calculate propellant mas...
Python
nomic_cornstack_python_v1
comment f = open("input.txt", 'r') comment line = f.readline() set line = input set num = integer line set array = list for i in range num begin comment line = f.readline() set line = input append array integer line end function mergeSort list begin if length list <= 1 begin return list end set mid = length list // 2 ...
# f = open("input.txt", 'r') # line = f.readline() line = input() num = int(line) array = [] for i in range(num): # line = f.readline() line = input() array.append(int(line)) def mergeSort(list): if(len(list)<=1): return list mid = len(list)//2 leftList = list[0:mid] rightList = ...
Python
zaydzuhri_stack_edu_python
function test_rectangle8 self begin with assert raises TypeError begin set R13 = call Rectangle string Holberton 7 end with assert raises TypeError begin set R14 = call Rectangle 5 string Betty end with assert raises TypeError begin set R15 = call Rectangle tuple 4 8 2 end with assert raises TypeError begin set R16 = c...
def test_rectangle8(self): with self.assertRaises(TypeError): R13 = Rectangle("Holberton", 7) with self.assertRaises(TypeError): R14 = Rectangle(5, "Betty") with self.assertRaises(TypeError): R15 = Rectangle((4, 8), 2) with self.assertRaises(TypeError)...
Python
nomic_cornstack_python_v1
function put_internal_result self job_result begin append internal_result_queue job_result end function
def put_internal_result(self, job_result): self.internal_result_queue.append(job_result)
Python
nomic_cornstack_python_v1
function get_delivery_stats api_key=none secure=none test=none **request_args begin string Get delivery stats for your Postmark account. :param api_key: Your Postmark API key. Required, if `test` is not `True`. :param secure: Use the https scheme for the Postmark API. Defaults to `True` :param test: Use the Postmark Te...
def get_delivery_stats(api_key=None, secure=None, test=None, **request_args): '''Get delivery stats for your Postmark account. :param api_key: Your Postmark API key. Required, if `test` is not `True`. :param secure: Use the https scheme for the Postmark API. Defaults to `True` :param test: Use ...
Python
jtatman_500k
function discovered self begin return get pulumi self string discovered end function
def discovered(self) -> pulumi.Output['outputs.DiscoveredResponse']: return pulumi.get(self, "discovered")
Python
nomic_cornstack_python_v1
function remove self begin for inst in reversed generated_instances begin delete inst end commit session end function
def remove(self): for inst in reversed(self.generated_instances): self.db.session.delete(inst) self.db.session.commit()
Python
nomic_cornstack_python_v1
import markov class antClass begin function __init__ self x=0 y=0 begin call place x y set Markov = call Markov set direction = integer random 4 end function function reset self x y begin call place x y set state = integer random num_states set direction = integer random 4 end function function place self x y begin set...
import markov class antClass: def __init__(self, x = 0, y = 0): self.place(x, y) self.Markov = markov.Markov() self.direction = int(random(4)) def reset(self, x, y): self.place(x, y) self.Markov.state = int(random(self.Markov.num_states)) self.direction ...
Python
zaydzuhri_stack_edu_python
class Trial begin function __init__ self items capacity begin set items = items set capacity = capacity end function function run self begin set value = 0 set weight = 0 set taken = list 0 * length items for item in items begin if weight + weight <= capacity begin set taken at index = 1 set value = value + value set we...
class Trial: def __init__(self, items, capacity): self.items = items self.capacity = capacity def run(self): value = 0 weight = 0 taken = [0]*len(self.items) for item in self.items: if weight + item.weight <= self.capacity: taken[ite...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- string 给你一个整数list L, 如 L=[2,-3,3,50], 求L的一个连续子序列,使其和最大,输出最大子序列的和。 例如,对于L=[2,-3,3,50], 输出53(分析:很明显,该列表最大连续子序列为[3,50]). function maxSubSum L begin set tuple maxSum thisSum = tuple 0 0 for item in L begin set thisSum = thisSum + item if thisSum > maxSum begin set ...
# !/usr/bin/env python # -*- coding: utf-8 -*- ''' 给你一个整数list L, 如 L=[2,-3,3,50], 求L的一个连续子序列,使其和最大,输出最大子序列的和。 例如,对于L=[2,-3,3,50], 输出53(分析:很明显,该列表最大连续子序列为[3,50]). ''' def maxSubSum(L): maxSum,thisSum= 0,0 for item in L: thisSum += item; if thisSum > maxSum: maxSum = thisSum ...
Python
zaydzuhri_stack_edu_python
comment coding=utf-8 import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np import d0_util_3d import Fig3_8_BDS_weakness_draw function get_EU_distance_3d v1 v2 begin set v1 = array v1 set v2 = array v2 set d = square root sum v1 - v2 ^ 2 return d end function function get_pair_point_...
# coding=utf-8 import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np import d0_util_3d import Fig3_8_BDS_weakness_draw def get_EU_distance_3d(v1, v2): v1 = np.array(v1) v2 = np.array(v2) d = np.sqrt(np.sum((v1-v2)**2)) return d def get_pair_point_in_DTW(Q, R): ...
Python
zaydzuhri_stack_edu_python
class Node begin function __init__ self data begin set data = data set left = none set right = none end function function add self value begin if data == value begin return end if value < data begin if left begin add left value end else begin set left = call Node value end end else if right begin add right value end el...
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def add(self, value): if self.data == value: return if value<self.data: if self.left: self.left.add(value) else: ...
Python
zaydzuhri_stack_edu_python
function test_8_func_decl self begin set input = string class test { void foo(int a,b;float c) { string _str_,o,c; } } set expect = string successful assert true call test input expect 208 end function
def test_8_func_decl(self): input = r""" class test { void foo(int a,b;float c) { string _str_,o,c; } } """ expect = r"successful" self.assertTrue(TestParser.test(input, expect, 208))
Python
nomic_cornstack_python_v1
function sha256_checksum self begin return get pulumi self string sha256_checksum end function
def sha256_checksum(self) -> pulumi.Input[str]: return pulumi.get(self, "sha256_checksum")
Python
nomic_cornstack_python_v1
function kingMoves begin comment Prompts the user for the position of the knight set position = string input string Enter input: comment Possible board positions set coordinates = list list string H string G string F string E string D string C string B string A list 1 2 3 4 5 6 7 8 comment Chess board visualization in ...
def kingMoves(): position = str(input('Enter input: ')) #Prompts the user for the position of the knight coordinates = [['H', 'G', 'F', 'E', 'D', 'C', 'B', 'A'], [1, 2, 3, 4, 5, 6, 7, 8]] #Possible board positions board = [ ...
Python
zaydzuhri_stack_edu_python
function _no_running_stats_instancenorm_check module begin set is_instancenorm = call get_layer_type module in tuple string InstanceNorm1d string InstanceNorm2d string InstanceNorm3d if is_instancenorm begin return not track_running_stats end return true end function
def _no_running_stats_instancenorm_check(module: nn.Module) -> bool: is_instancenorm = get_layer_type(module) in ( "InstanceNorm1d", "InstanceNorm2d", "InstanceNorm3d", ) if is_instancenorm: return not module.track_running_stats return True
Python
nomic_cornstack_python_v1
class Solution begin function restoreIpAddresses self s begin set answer = list if length s < 4 or length s > 12 begin return list end function validIP depth ip idx answer begin comment s를 4번 잘랐을 때, ip에 '.'을 제거한 것과 s가 동일하다면 valid한 IP if depth == 4 begin set ip_check = replace ip string . string if ip_check == s begin...
class Solution: def restoreIpAddresses(self, s: str) -> List[str]: answer = [] if len(s) < 4 or len(s) > 12: return [] def validIP(depth, ip, idx, answer): # s를 4번 잘랐을 때, ip에 '.'을 제거한 것과 s가 동일하다면 valid한 IP if depth == 4: i...
Python
zaydzuhri_stack_edu_python
function write_byte self addr data erase=true begin string Write a single byte to static memory area (blocks 0-14). The target byte is zero'd first if *erase* is True. if addr < 0 or addr >= 128 begin raise call ValueError string invalid byte address end debug format string write byte at address {0} ({0:02X}h) addr set...
def write_byte(self, addr, data, erase=True): """Write a single byte to static memory area (blocks 0-14). The target byte is zero'd first if *erase* is True. """ if addr < 0 or addr >= 128: raise ValueError("invalid byte address") log.debug("write byte at address {0}...
Python
jtatman_500k
function clear_watermarks self begin comment Look up the debug information. call _lookup_debuginfo set free_heap = value comment Wash down the watermark (min available = current available) call set_data address list free_heap end function
def clear_watermarks(self): # Look up the debug information. self._lookup_debuginfo() free_heap = self.chipdata.get_var_strict("$_heap_debug_free").value # Wash down the watermark (min available = current available) self.chipdata.set_data( self.chipdata.get_var_stri...
Python
nomic_cornstack_python_v1
function replace self filename photo_id callback=none **kwargs begin if not photo_id begin raise call IllegalArgumentException string photo_id must be specified end set kwargs at string photo_id = photo_id return call __upload_to_form flickr_replace_form filename callback keyword kwargs end function
def replace(self, filename, photo_id, callback=None, **kwargs): if not photo_id: raise IllegalArgumentException("photo_id must be specified") kwargs['photo_id'] = photo_id return self.__upload_to_form( FlickrAPI.flickr_replace_form, filename, callback, **kwa...
Python
nomic_cornstack_python_v1
function equipped_effect self entity begin add effect_queue call AddSpoofChild entity spoof_child 1 if status_icon begin add effect_queue call StatusIconEntityEffect entity status_icon 1 end end function
def equipped_effect(self, entity): entity.effect_queue.add(entityeffect.AddSpoofChild(entity, self.spoof_child, 1)) if self.status_icon: entity.effect_queue.add(entityeffect.StatusIconEntityEffect(entity, self.status_icon, 1))
Python
nomic_cornstack_python_v1
import os , requests class GMGaming begin function __init__ self search_term begin set search_term = search_term end function function set_url self begin return string https://www.greenmangaming.com/search/ { search_term } end function function make_request self begin set url = call set_url return call request string G...
import os, requests class GMGaming: def __init__(self,search_term): self.search_term = search_term def set_url(self): return f"https://www.greenmangaming.com/search/{self.search_term}" def make_request(self): url = self.set_url() return requests.request("GET", url) gm...
Python
zaydzuhri_stack_edu_python
from Tkinter import * import tkFont import RPi.GPIO as GPIO call setwarnings false call setmode BOARD setup GPIO 11 OUT setup GPIO 13 OUT setup GPIO 15 OUT call output 11 LOW call output 13 LOW call output 15 LOW set win = call Tk set v = call IntVar set myFont = call Font family=string Comic Sans MS size=24 weight=str...
from Tkinter import * import tkFont import RPi.GPIO as GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(11, GPIO.OUT) GPIO.setup(13, GPIO.OUT) GPIO.setup(15, GPIO.OUT) GPIO.output(11, GPIO.LOW) GPIO.output(13, GPIO.LOW) GPIO.output(15, GPIO.LOW) win = Tk() v = IntVar() myFont = tkFont.Font(family = 'C...
Python
zaydzuhri_stack_edu_python
function inverseCholesky vecL begin set size = integer square root 2 * size vecL 0 set L = zeros size size set mask = call tril_mask size set L at mask == 1 = vecL set P = call mm t dist return P end function
def inverseCholesky(vecL): size = int(np.sqrt(2 * vecL.size(0))) L = torch.zeros(size, size) mask = tril_mask(size) L[mask == 1] = vecL P = L.mm(L.t()) return P
Python
nomic_cornstack_python_v1
function test_app_model_in_app_index_body_class self begin set response = get client reverse string admin:app_list args=tuple string admin_views call assertContains response string <body class=" dashboard app-admin_views end function
def test_app_model_in_app_index_body_class(self): response = self.client.get(reverse('admin:app_list', args=('admin_views',))) self.assertContains(response, '<body class=" dashboard app-admin_views')
Python
nomic_cornstack_python_v1
for i in range pontosMax begin append abcissa decimal input string Insira a abcissa do ponto: + string i + 1 + string . append ordenada decimal input string Insira a ordenada do ponto: + string i + 1 + string . end for i in range pontosMax begin set sumx = sumx + abcissa at i set sumy = sumy + ordenada at i set sumxy =...
for i in range(pontosMax): abcissa.append(float(input("Insira a abcissa do ponto: " + str(i+1) + ".\n"))) ordenada.append(float(input("Insira a ordenada do ponto: " + str(i+1) + ".\n"))) for i in range(pontosMax): sumx = sumx + abcissa[i] sumy = sumy + ordenada[i] sumxy = sumxy + abcissa[i] * ordena...
Python
zaydzuhri_stack_edu_python
function insert_one self key score=60 expire=600 begin if not call get_one key begin set expire_stamp = integer time + expire set value = format _value_pattern expire_stamp score set key value call expireat key expire_stamp end end function
def insert_one(self, key, score=60, expire=600): if not self.get_one(key): expire_stamp = int(time.time() + expire) value = self._value_pattern.format(expire_stamp, score) self._client.set(key, value) self._client.expireat(key, expire_stamp)
Python
nomic_cornstack_python_v1
function get_stopwords language begin set language = lower language try begin set words = call words language end except OSError begin set words_path = string parent + sep + string stopwords with open string { words_path } { sep } { language } .txt string r encoding=string utf-8 as f begin set words = read lines f set ...
def get_stopwords(language): language = language.lower() try: words = stopwords.words(language) except OSError: words_path = str(Path(os.getcwd()).parent) + os.sep + 'stopwords' with open(f'{words_path}{os.sep}{language}.txt', 'r', encoding='utf-8') as f: words = f.readli...
Python
nomic_cornstack_python_v1
function estimate_log_error_Z self begin if not has attribute self string logZ begin raise call RuntimeError string You must run_logZ before calculating the final estimates. end set logZ = call placeholder shape=shape comment this is the mean factor from the weights set logZ_mean = call logsumexp logZ - log n_runs comm...
def estimate_log_error_Z(self): if not hasattr(self, 'logZ'): raise RuntimeError('You must run_logZ before calculating the final estimates.') logZ = B.placeholder(shape=self.logZ.shape) # this is the mean factor from the weights logZ_mean = B.logsumexp(logZ) - B.log(self....
Python
nomic_cornstack_python_v1
import os import sys import pytesseract import numpy as np import matplotlib.pyplot as plt from pathlib import Path from PIL import Image from src.face_detection import cropped_images from skimage.color import rgb2gray from skimage.filters import threshold_otsu , gaussian , frangi from skimage.measure import find_conto...
import os import sys import pytesseract import numpy as np import matplotlib.pyplot as plt from pathlib import Path from PIL import Image from src.face_detection import cropped_images from skimage.color import rgb2gray from skimage.filters import threshold_otsu, gaussian, frangi from skimage.measure import find_contou...
Python
zaydzuhri_stack_edu_python
function get_lines self begin set cursor_style = call get_style string cursor set fill_style = call get_style string fill comment Cache value to be reset later set old = value comment Create sides separated by cursor set left = call fill_style value at slice : cursor : set right = call fill_style value at slice cursor...
def get_lines(self) -> list[str]: cursor_style = self.get_style("cursor") fill_style = self.get_style("fill") # Cache value to be reset later old = self.value # Create sides separated by cursor left = fill_style(self.value[: self.cursor]) right = fill_style(sel...
Python
nomic_cornstack_python_v1
comment Imports import pandas as pd import numpy as np from matplotlib import pyplot as plt comment Alias set file_deads = string time_series_covid19_deaths_global.csv set file_cases = string time_series_covid19_confirmed_global.csv set pays = list string Italy string Spain string France string Hubei (China) string US ...
# Imports import pandas as pd import numpy as np from matplotlib import pyplot as plt # Alias file_deads = 'time_series_covid19_deaths_global.csv' file_cases = 'time_series_covid19_confirmed_global.csv' pays = ['Italy', 'Spain', 'France', 'Hubei (China)', 'US', 'Netherlands', 'Jiangxi (China)', 'Singapore', 'Argentina...
Python
zaydzuhri_stack_edu_python
async function read_pickle self begin return loads await call read_binary end function
async def read_pickle(self) -> Any: return pickle.loads(await self.read_binary())
Python
nomic_cornstack_python_v1
comment coding: utf-8 import os import sys class cueFile begin function __init__ self filename begin set _fileName = filename set _Performer = string 佚名 set _Title = string 未知专辑名 set _Content = list end function function SetTitle self title begin set _Title = title end function function SetPerformer self performer beg...
# coding: utf-8 import os import sys class cueFile: def __init__(self, filename): self._fileName = filename self._Performer = '佚名' self._Title = '未知专辑名' self._Content = [] def SetTitle(self, title): self._Title = title def SetPerformer(self, performer): s...
Python
zaydzuhri_stack_edu_python
function plot_fit_sine tracklist_subset tracklist sin_corr_df begin for trial in tracklist_subset begin set raw_data = tracklist at trial at string data at string pt2y set behavior = tracklist at trial at string behavior set init_speed = tracklist at trial at string start_spd_BLs comment Find bkgrd trend set base = cal...
def plot_fit_sine(tracklist_subset, tracklist, sin_corr_df): for trial in tracklist_subset: raw_data = tracklist[trial]['data']['pt2y'] behavior = tracklist[trial]['behavior'] init_speed = tracklist[trial]['start_spd_BLs'] base = peakutils.baseline(raw_data, 3) # Find bkgrd trend ...
Python
nomic_cornstack_python_v1
comment ejemplo en Python 2.x from pyparsing import Word , alphas set greet = call Word alphas + string , + call Word alphas + string ! set greeting = call parseString string Una2palabra, World!
# ejemplo en Python 2.x from pyparsing import Word, alphas greet = Word( alphas ) + "," + Word( alphas ) + "!" greeting = greet.parseString( "Una2palabra, World!" )
Python
zaydzuhri_stack_edu_python
import cv2 set cam = call VideoCapture 0 set img_counter = 0 while true begin set tuple ret frame = read cam if not ret begin break end set img_name = format string webcam_photo_{}.png img_counter call imwrite img_name frame print format string {} written! img_name set img_counter = img_counter + 1 break end release ca...
import cv2 cam = cv2.VideoCapture(0) img_counter = 0 while True: ret, frame = cam.read() if not ret: break img_name = "webcam_photo_{}.png".format(img_counter) cv2.imwrite(img_name, frame) print("{} written!".format(img_name)) img_counter += 1 break cam.release()
Python
zaydzuhri_stack_edu_python
function concatenate columns_of_interest files begin set sources = list string ICEberg string islander string paidb string Dimob string islandviewer string Islander string Sigi string Islandpick set islands = list set island_IDs = list set island_dct = list comprehension dict for source in sources for source in file...
def concatenate(columns_of_interest,files): sources = ['ICEberg','islander','paidb','Dimob','islandviewer','Islander','Sigi','Islandpick'] islands = [] island_IDs = [] island_dct = [ {} for source in sources ] for source in files : with open(source, 'r') as f: for island in f : if not island.startswith('A...
Python
nomic_cornstack_python_v1
function swap_characters_before_cursor self begin set pos = cursor_position if pos >= 2 begin set a = text at pos - 2 set b = text at pos - 1 set text = text at slice : pos - 2 : + b + a + text at slice pos : : end end function
def swap_characters_before_cursor(self) -> None: pos = self.cursor_position if pos >= 2: a = self.text[pos - 2] b = self.text[pos - 1] self.text = self.text[: pos - 2] + b + a + self.text[pos:]
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- import numpy as np import pandas as pd comment reading the dataset set df = read csv string AllBooks_baseline_DTM_Labelled.csv set df = drop df list index at 13 set split_names = rename columns=dict 0 string text ; 1 string chapter set df = concat list split_n...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import pandas as pd #reading the dataset df=pd.read_csv("AllBooks_baseline_DTM_Labelled.csv") df=df.drop([df.index[13]]) split_names = (df['Unnamed: 0'] .str.strip() .str.split('_', n=1, expand=True) .rename(columns={0:'text', 1:'chapter'})) ...
Python
zaydzuhri_stack_edu_python
function on_n_event_report self dataset context info begin raise call NotImplementedError string User must implement the AE.on_n_event_report function prior to calling AE.start() end function
def on_n_event_report(self, dataset, context, info): raise NotImplementedError("User must implement the " "AE.on_n_event_report function prior to " "calling AE.start()")
Python
nomic_cornstack_python_v1
import csv import codecs with open string ../data/test_02.csv string w string utf-8 as fp begin set writer = writer fp delimiter=string , quotechar=string " write row writer list string ID string 이름 string 가격 write row writer list string 1000 string SD 카드 30000 write row writer list string 1001 string 키보드 21000 write r...
import csv import codecs with codecs.open("../data/test_02.csv",'w','utf-8') as fp: writer = csv.writer(fp,delimiter=",", quotechar='"') writer.writerow(["ID", "이름", "가격"]) writer.writerow(["1000", "SD 카드 ", 30000]) writer.writerow(["1001", "키보드", 21000]) writer.writerow(["1002", "마우스", 15000])
Python
zaydzuhri_stack_edu_python
from game import Game from player import Player import random function main begin set asking = 1 while asking == 1 begin print string ==================================== print string COUP print string S.D.T soft print string 2021 print string ==================================== print string How many people want to pl...
from game import Game from player import Player import random def main(): asking = 1 while asking == 1: print("====================================") print(" COUP ") print(" S.D.T soft ") print(" 2021 ...
Python
zaydzuhri_stack_edu_python
function get_unique_microtime self begin with _nonce_lock begin set microtime = integer time * 1000000.0 if microtime <= _last_unique_microtime begin set microtime = _last_unique_microtime + 1 end set _last_unique_microtime = microtime return microtime end end function
def get_unique_microtime(self): with self._nonce_lock: microtime = int(time.time() * 1e6) if microtime <= self._last_unique_microtime: microtime = self._last_unique_microtime + 1 self._last_unique_microtime = microtime return microtime
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding: utf-8 from __future__ import absolute_import , division , print_function , unicode_literals from builtins import input import gym import deeprl_hw1.lake_envs as lake_env import time import rl import matplotlib.pyplot as plt import numpy as np function run_random_policy env b...
#!/usr/bin/env python # coding: utf-8 from __future__ import (absolute_import, division, print_function, unicode_literals) from builtins import input import gym import deeprl_hw1.lake_envs as lake_env import time import rl import matplotlib.pyplot as plt import numpy as np def run_random_pol...
Python
zaydzuhri_stack_edu_python
function run_interactive_shell serial_port_name=none begin print string - * 14 print string Qontrol Interactive Shell print string - * 14 + string set baudrate = 115200 function tty_supports_color begin string Returns True if the running system's terminal supports color, and False otherwise. From django.core.management...
def run_interactive_shell(serial_port_name = None): print ("- "*14) print (" Qontrol Interactive Shell") print ("- "*14+"\n") baudrate = 115200 def tty_supports_color(): """ Returns True if the running system's terminal supports color, and False otherwise. From django.core.management.color.s...
Python
nomic_cornstack_python_v1
function expires delta begin if is instance delta tuple int long begin set delta = time delta seconds=delta end set date_obj = call utcnow + delta call header string Expires call httpdate date_obj end function
def expires(delta): if isinstance(delta, (int, long)): delta = datetime.timedelta(seconds=delta) date_obj = datetime.datetime.utcnow() + delta web.header('Expires', net.httpdate(date_obj))
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding:utf-8 -*- import asyncio async function func begin print 123 await sleep 1 print 456 end function set loop = call get_event_loop set t1 = call create_task call func set t2 = call create_task call func set task = list t1 t2 set wait_obj = wait asyncio task call run_until_c...
#!/usr/bin/env python # -*- coding:utf-8 -*- import asyncio async def func(): print(123) await asyncio.sleep(1) print(456) loop = asyncio.get_event_loop() t1 = loop.create_task(func()) t2 = loop.create_task(func()) task = [t1, t2] wait_obj = asyncio.wait(task) loop.run_until_complete(wait_obj) for i in ...
Python
zaydzuhri_stack_edu_python
string Creates the train, val and test image data files: Data/image_features_train.pkl Data/image_features_val.pkl Data/image_features_test.pkl import numpy as np import pickle set classes = split read open string ../classes.txt string r string at slice : - 1 : set new_classes = split read open string ../new_classes....
''' Creates the train, val and test image data files: Data/image_features_train.pkl Data/image_features_val.pkl Data/image_features_test.pkl ''' import numpy as np import pickle classes = open('../classes.txt','r').read().split('\n')[:-1] new_classes = open('../new_classes.txt','r').read().split('\n')[:-1] for c in n...
Python
zaydzuhri_stack_edu_python
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as seabornInstance from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn import metrics comment Read the dataset set df = read csv string data/Weather.csv print describe df...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as seabornInstance from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn import metrics # Read the dataset df = pd.read_csv('data/Weather.csv') print(df.describe()) # do...
Python
zaydzuhri_stack_edu_python
string Pattern Structure Client AbstractFactory ConcreteFactories AbstractProduct ConcreteProduct https://www.youtube.com/watch?v=CVlpjFJN17U https://devexperto.com/patrones-de-diseno-software/ from abc import ABC , abstractmethod class AbstractProduct extends ABC begin string AbstractProduct class for definition decor...
""" Pattern Structure Client AbstractFactory ConcreteFactories AbstractProduct ConcreteProduct https://www.youtube.com/watch?v=CVlpjFJN17U https://devexperto.com/patrones-de-diseno-software/ """ from abc import ABC, abstractmethod class AbstractProduct(ABC): """AbstractProduct class fo...
Python
zaydzuhri_stack_edu_python
function frame name state width=none height=none content_gen=none drag_tag=none down_tag=none hover_tag=none show_grid=true begin function content_gen_with_opt_events tf event_gen begin if drag_tag or down_tag or hover_tag begin set kwargs = dictionary tf=tf event_gen=event_gen end else begin set kwargs = dictionary tf...
def frame(name, state, width=None, height=None, content_gen=None, drag_tag=None, down_tag=None, hover_tag=None, show_grid=True): def content_gen_with_opt_events(tf, event_gen): if drag_tag or down_tag or hover_tag: kwargs = dict(tf=tf, event_gen=event_gen) else: kwargs = dict...
Python
nomic_cornstack_python_v1
function find_word word begin try begin from learn.models import Word set result = call find_word_in_db word if not result or not detailed_meanings begin set xx = call lookup_iciba_word_api word if xx begin if not result begin set result = call Word end set spelling = word if string ph_am in xx at string symbols at 0 b...
def find_word(word): try: from learn.models import Word result = find_word_in_db(word) if not result or not result.detailed_meanings: xx = lookup_iciba_word_api(word) if xx: if not result: result = Word() result.spel...
Python
nomic_cornstack_python_v1
function find_uncommitted_filefields sender instance **kwargs begin set uncommitted = list set _uncommitted_filefields = list set fields = fields if get kwargs string update_fields none begin set update_fields = set kwargs at string update_fields set fields = intersection update_fields fields end for field in fields ...
def find_uncommitted_filefields(sender, instance, **kwargs): uncommitted = instance._uncommitted_filefields = [] fields = sender._meta.fields if kwargs.get('update_fields', None): update_fields = set(kwargs['update_fields']) fields = update_fields.intersection(fields) for field in field...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Sun Aug 26 15:03:06 2018 @author: Darko import pandas as pd import numpy as np from pandas import Series , DataFrame import matplotlib.pyplot as plt set filename = string C:/Users/Darko/Downloads/tidytuesday-master/tidytuesday-master/data/week18_dallas_animals.xlsx set da...
# -*- coding: utf-8 -*- """ Created on Sun Aug 26 15:03:06 2018 @author: Darko """ import pandas as pd import numpy as np from pandas import Series, DataFrame import matplotlib.pyplot as plt filename = "C:/Users/Darko/Downloads/tidytuesday-master/tidytuesday-master/data/week18_dallas_animals.xlsx" data = pd.read_exce...
Python
zaydzuhri_stack_edu_python
comment coding: utf-8 comment 当前项目的名称: python13-api-test comment 新文件名称:json comment 当前登录名:LuckyLu comment 创建日期:2019/1/24 14:35 comment 文件IDE名称:PyCharm import json from common.contants import json_test_file class OperationJson begin function __init__ self file_name=none begin if file_name begin set file_name = file_name...
# coding: utf-8 # 当前项目的名称: python13-api-test # 新文件名称:json # 当前登录名:LuckyLu # 创建日期:2019/1/24 14:35 # 文件IDE名称:PyCharm import json from common.contants import json_test_file class OperationJson: def __init__(self, file_name=None): if file_name: self.file_name = file_name else: ...
Python
zaydzuhri_stack_edu_python
from enum import Enum class Endian extends Enum begin set LITTLE = string little set BIG = string big decorator staticmethod function get_names begin return list comprehension lower name for tuple name member in items __members__ end function decorator staticmethod function is_supported endian begin return lower endian...
from enum import Enum class Endian(Enum): LITTLE = "little" BIG = "big" @staticmethod def get_names() -> [str]: return [name.lower() for name, member in Endian.__members__.items()] @staticmethod def is_supported(endian: str) -> bool: return endian.lower() in Endian.get_names(...
Python
zaydzuhri_stack_edu_python
function generate_dungeon x y height **options begin set terrain = zeros list x y dtype=int set rooms = call generate_rooms x y yield rooms for room in rooms begin call carve room terrain end yield call net_from_points list comprehension centre for r in rooms call Triangle tuple 0 0 tuple 0 x + y tuple x + y 0 set net ...
def generate_dungeon(x, y, height, **options): terrain = np.zeros([x, y], dtype=int) rooms = generate_rooms(x, y) yield rooms for room in rooms: carve(room, terrain) yield net_from_points([r.centre for r in rooms], Triangle((0, 0), (0, x+y), (x+y, 0))) net = net...
Python
nomic_cornstack_python_v1
function _convert_inputs amount src_currency dest_currency reference_date begin return tuple call _convert_amount amount call _convert_src_currency src_currency call _convert_dest_currency dest_currency call _validate_reference_date reference_date end function
def _convert_inputs(amount, src_currency, dest_currency, reference_date): return _convert_amount(amount), _convert_src_currency(src_currency), _convert_dest_currency( dest_currency), _validate_reference_date(reference_date)
Python
nomic_cornstack_python_v1
function concat_links folder_list begin set path = string for folder in folder_list begin set path = join path path folder end return path end function
def concat_links(folder_list): path = '' for folder in folder_list: path = os.path.join(path, folder) return path
Python
nomic_cornstack_python_v1
function build_new_custom self *args begin set dialog = call DrCustomImageDialog self set result = run if result == OK begin set tuple width height rgba = call get_values call _build_new_tab width=width height=height background_rgba=rgba call set_picture_title end call destroy end function
def build_new_custom(self, *args): dialog = DrCustomImageDialog(self) result = dialog.run() if result == Gtk.ResponseType.OK: width, height, rgba = dialog.get_values() self._build_new_tab(width=width, height=height, background_rgba=rgba) self.set_picture_title() dialog.destroy()
Python
nomic_cornstack_python_v1
function dimension self begin return max _l1 call ZZ 0 end function
def dimension(self): return max(self._l1, ZZ(0))
Python
nomic_cornstack_python_v1
import Functions as func import PriorityQueue as pque import GraphEdge as ge class GraphSearch_AStar begin function __init__ self gr source target begin set graph = gr set gCosts = list 0 * length nodes set fCosts = list 0 * length nodes set shortestPathTree = list none * length nodes set searchFrontier = list none * l...
import Functions as func import PriorityQueue as pque import GraphEdge as ge class GraphSearch_AStar: def __init__(self, gr, source, target): self.graph = gr self.gCosts = [0] * len(self.graph.nodes) self.fCosts = [0] * len(self.graph.nodes) self.shortestPathTree = [None] * len(self.graph.nodes) self.searc...
Python
zaydzuhri_stack_edu_python
function typeName self begin pass end function
def typeName(self): pass
Python
nomic_cornstack_python_v1
string Soumil Nitin Shah B.E in Electronic MS Electrical Engineering MS Computer Engineering import requests import datetime import time import matplotlib.pyplot as plt import matplotlib.animation as animation from matplotlib import style set x_axis = list set y_axis = list function get_time begin set time_z = now se...
''' Soumil Nitin Shah B.E in Electronic MS Electrical Engineering MS Computer Engineering ''' import requests import datetime import time import matplotlib.pyplot as plt import matplotlib.animation as animation from matplotlib import style x_axis=[] y_axis=[] def get_time(): time_z=datetime.datetime.now()...
Python
zaydzuhri_stack_edu_python
import numpy as np import sys append path string ../ from frozen_lake_env import * import math class nStepSarsa begin function __init__ self number_of_states epsilon alpha gamma n begin set env = call FrozenLakeEnv comment learning parameters set actions = dict string LEFT 0 ; string RIGHT 2 ; string UP 3 ; string DOWN...
import numpy as np import sys sys.path.append("../") from frozen_lake_env import * import math class nStepSarsa: def __init__(self, number_of_states, epsilon, alpha, gamma, n): self.env = FrozenLakeEnv() # learning parameters self.actions = {'LEFT':0, 'RIGHT':2, 'UP':3, 'DOWN':1} ...
Python
zaydzuhri_stack_edu_python
comment ROS2 lib. import rclpy from rclpy.node import Node from rclpy.exceptions import ParameterNotDeclaredException from rcl_interfaces.msg import ParameterType from rclpy.parameter import Parameter comment ROS2 Msg from geometry_msgs.msg import Twist from std_msgs.msg import String , Int32 , Float32MultiArray , Int3...
# ROS2 lib. import rclpy from rclpy.node import Node from rclpy.exceptions import ParameterNotDeclaredException from rcl_interfaces.msg import ParameterType from rclpy.parameter import Parameter # ROS2 Msg from geometry_msgs.msg import Twist from std_msgs.msg import String, Int32, Float32MultiArray, Int32MultiArray #...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- import pygame from pygame.locals import * import time class Vais begin comment Permet de creer le vaisseau function __init__ self begin set image = call convert_alpha end function end class
# -*- coding: utf-8 -*- import pygame from pygame.locals import * import time class Vais: #Permet de creer le vaisseau def __init__(self): # self.image = pygame.image.load("image/vaisseau.png").convert_alpha()
Python
zaydzuhri_stack_edu_python
function position self begin return x end function
def position(self): return self.x
Python
nomic_cornstack_python_v1
import urllib.request as url import json import time set COLWIDTH = 18 while true begin set septa = url open string http://www3.septa.org/hackathon/Arrivals/Temple%20U set retstr = decode read septa encoding=string utf-8 set js = loads retstr for train in js at next iterate keys js at 1 at string Southbound begin set o...
import urllib.request as url import json import time COLWIDTH=18 while True: septa = url.urlopen('http://www3.septa.org/hackathon/Arrivals/Temple%20U') retstr = septa.read().decode(encoding='utf-8') js = json.loads(retstr) for train in js[next(iter(js.keys()))][1]['Southbound']: orig = str(tra...
Python
zaydzuhri_stack_edu_python
import kivy call require string 1.11.1 from kivy.app import App from kivy.lang import Builder from kivy.uix.screenmanager import ScreenManager , Screen from kivy.properties import ObjectProperty from kivy.uix.popup import Popup from kivy.uix.label import Label from kivy.uix.button import Button from kivy.uix.gridlayout...
import kivy kivy.require('1.11.1') from kivy.app import App from kivy.lang import Builder from kivy.uix.screenmanager import ScreenManager, Screen from kivy.properties import ObjectProperty from kivy.uix.popup import Popup from kivy.uix.label import Label from kivy.uix.button import Button from kivy.uix.grid...
Python
zaydzuhri_stack_edu_python
import yaml comment encapsulating class for vignette .yml files class Vignette begin set TITLE_NAME = string title set INPUTS_NAME = string inputs set ACTIONS_NAME = string actions set BAD_OPS = list string CREATE string DELETE string SET string REMOVE function __init__ self begin comment required of vignettes comment ...
import yaml # encapsulating class for vignette .yml files class Vignette: TITLE_NAME = "title" INPUTS_NAME = "inputs" ACTIONS_NAME = "actions" BAD_OPS = ["CREATE", "DELETE", "SET", "REMOVE"] def __init__(self): # required of vignettes # inputs, actions are lists of queries self.title = None ...
Python
zaydzuhri_stack_edu_python
function customCall self call value begin set paramDict at string customCall at string value = value set paramDict at string customCall at string execute = ex + call set param = string customCall call dbGrab param return copy dfDict at string customCall end function
def customCall(self, call, value): paramDict['customCall']['value'] = value paramDict['customCall']['execute'] = ex + call param = 'customCall' self.dbGrab(param) return self.dfDict['customCall'].copy()
Python
nomic_cornstack_python_v1
function preorder_traverse_to_list self begin if not call root begin return none end call _synchronize_attributes return call _preorder_traverse_to_list_helper call root 1 end function
def preorder_traverse_to_list(self): if (not self.root()): return None self._synchronize_attributes() return self._preorder_traverse_to_list_helper(self.root(), 1)
Python
nomic_cornstack_python_v1
function id self begin return get pulumi self string id end function
def id(self) -> str: return pulumi.get(self, "id")
Python
nomic_cornstack_python_v1
string Bullet renderer class pygame "engine" example Designed to test different functionality import pygame from engine.behaviour import Behaviour class BulletRenderer extends Behaviour begin function __init__ self begin call __init__ set name = string BulletRenderer set colour = tuple 255 255 0 set radius = 5 end func...
''' Bullet renderer class pygame "engine" example Designed to test different functionality ''' import pygame from engine.behaviour import Behaviour class BulletRenderer(Behaviour): def __init__(self): super().__init__() self.name = "BulletRenderer" self.colour = (255, 255, 0) ...
Python
zaydzuhri_stack_edu_python
function select_images_for_digits digits indexes_of_images begin set images_index = list for digit in digits begin append images_index random choice indexes_of_images at string digit size=1 at 0 end return images_index end function
def select_images_for_digits(digits, indexes_of_images): images_index = [] for digit in digits: images_index.append(np.random.choice(indexes_of_images[str(digit)], size=1)[0]) return images_index
Python
nomic_cornstack_python_v1
function retrieve self request pk=none begin return call Response dict string http_method string GET end function
def retrieve(self, request, pk=None): return Response({'http_method': 'GET'})
Python
nomic_cornstack_python_v1
function get_labels self begin raise call NotImplementedError end function
def get_labels(self): raise NotImplementedError()
Python
nomic_cornstack_python_v1
from logic.Container import * class Hero begin function __init__ self name creatures begin set name = name set __creatures = call Container creatures end function function getAllCreatures self begin return call getElements end function function addCreature self creature begin call addElement creature end function decor...
from logic.Container import * class Hero: def __init__(self, name, creatures): self.name = name self.__creatures = Container(creatures) def getAllCreatures(self): return self.__creatures.getElements() def addCreature(self, creature): self.__creatures.addElement(creature) ...
Python
zaydzuhri_stack_edu_python
comment keys cannot be duplicate add s 4 print s remove s 4 print s set s1 = set list 1 2 3 set s2 = set list 2 3 4 print string intersection: s1 ? s2 print string union: s1 ? s2 comment For mutable (won't function if different type) set a = list string c string b string a sort a reverse=true print a set b = list 342 5...
# keys cannot be duplicate s.add(4) print(s) s.remove(4) print(s) s1 = set([1,2,3]) s2 = set([2,3,4]) print('intersection:',s1&s2) print('union:', s1|s2) # For mutable (won't function if different type) a=['c', 'b', 'a'] a.sort(reverse=True) print(a) b=[342,543,3.54,453663] b.sort() print(b) # For Immutable(i.e St...
Python
zaydzuhri_stack_edu_python
function heterogenous_config_validator self instance value begin if value is none begin return end comment Check that the correct keys are supplied for the heterogenous_inflow_config dict for k in list string speed_multipliers string x string y begin if k not in keys value begin raise call ValueError string heterogenou...
def heterogenous_config_validator(self, instance: attrs.Attribute, value: dict | None) -> None: if value is None: return # Check that the correct keys are supplied for the heterogenous_inflow_config dict for k in ["speed_multipliers", "x", "y"]: if k not in value.keys():...
Python
nomic_cornstack_python_v1
function scan text transitions accepts begin comment initial state set pos = 0 set state = string s0 comment memory for last seen accepting states set last_token = none set last_pos = none while true begin comment get next char (category) set c = call getchar text pos if state in transitions and c in transitions at sta...
def scan(text, transitions, accepts): # initial state pos = 0 state = 's0' # memory for last seen accepting states last_token = None last_pos = None while True: c = getchar(text, pos) # get next char (category) if state in transitions and c in transitions[state]: ...
Python
nomic_cornstack_python_v1
function __call__ self req begin set user_locale = call best_match_language comment Replace the body with fault details. set code = status_int set fault_name = get _fault_names code string computeFault set explanation = explanation debug call _ string Returning %(code)s to user: %(explanation)s dict string code code ; ...
def __call__(self, req): user_locale = req.best_match_language() # Replace the body with fault details. code = self.wrapped_exc.status_int fault_name = self._fault_names.get(code, "computeFault") explanation = self.wrapped_exc.explanation LOG.debug(_("Returning %(code)s ...
Python
nomic_cornstack_python_v1
function _gen_stats self stats name=none begin set cstats = list comprehension x for x in stats if x is not none if length cstats > 0 begin set ret_dict = dict string low min cstats ; string high max cstats ; string total sum cstats ; string reported length cstats ; string number_none length stats - length cstats ; str...
def _gen_stats(self, stats, name=None): cstats = [x for x in stats if x is not None] if len(cstats) > 0: ret_dict = {'low': min(cstats), 'high': max(cstats), 'total': sum(cstats), 'reported': len(cstats), 'number_none': len(stats) - len(cs...
Python
nomic_cornstack_python_v1
function yank_path self path begin string Clear cache of results from a specific path for func in _caches begin set cache = dict for key in keys _caches at func begin debug string cache key %s for func %s key func if path in key at 0 begin debug string del cache key %s key del _caches at func at key end end end end fu...
def yank_path(self, path): """Clear cache of results from a specific path""" for func in self._caches: cache = {} for key in self._caches[func].keys(): log.debug("cache key %s for func %s", key, func) if path in key[0]: log.debu...
Python
jtatman_500k
function __init__ __self__ completed=none contains_update=none failed_provisioning=none flattened_secrets=none message=none output=none polling_url=none provisioned=none provisioning=none requested=none resource_id=none spec_hash=none state=none begin if completed is not none begin set __self__ string completed complet...
def __init__(__self__, *, completed: Optional[str] = None, contains_update: Optional[bool] = None, failed_provisioning: Optional[bool] = None, flattened_secrets: Optional[bool] = None, message: Optional[str] = None, ou...
Python
nomic_cornstack_python_v1
function estimate_max_dn exposure gain=1 begin return random integer 100 * exposure 500 * exposure end function
def estimate_max_dn(exposure, gain=1): return np.random.randint(100*exposure, 500*exposure)
Python
nomic_cornstack_python_v1
function s_function t N=1024 epsilon=0.1 begin set nomerator = square root N - 1 * tan 2 * t * epsilon * square root N - 1 - N * call arctan square root N - 1 / N set denominator = 1 - N return 1 / 2 * 1 - nomerator / denominator end function
def s_function(t ,N = 1024 , epsilon = 0.1 ): nomerator = np.sqrt(N-1) * np.tan((2 * t * epsilon * np.sqrt(N-1) - N * np.arctan(np.sqrt(N-1)))/ N) denominator = 1 - N return 1/2*(1 - nomerator / denominator)
Python
nomic_cornstack_python_v1
import sys call setrecursionlimit 100000 set t = integer read line stdin set dx = list 1 - 1 0 0 set dy = list 0 0 - 1 1 for i in range t begin set tuple m n k = map int split read line stdin set map1 = list comprehension list 0 * n for _ in range m set group = list comprehension list 0 * n for _ in range m for dd in r...
import sys sys.setrecursionlimit(100000) t = int(sys.stdin.readline()) dx = [1,-1,0,0] dy = [0,0,-1,1] for i in range(t): m,n,k = map(int,sys.stdin.readline().split()) map1 = [[0]*n for _ in range(m)] group = [[0]*n for _ in range(m)] for dd in range(k): a,b = map(int,sys.stdin.readline().split(...
Python
zaydzuhri_stack_edu_python
function check_for_export self context volume_id begin comment NYI pass end function
def check_for_export(self, context, volume_id): # NYI pass
Python
nomic_cornstack_python_v1
function GetImageRegion self begin return call itkScalarImageKmeansImageFilterISS2IUC2_GetImageRegion self end function
def GetImageRegion(self) -> "itkImageRegion2 const &": return _itkScalarImageKmeansImageFilterPython.itkScalarImageKmeansImageFilterISS2IUC2_GetImageRegion(self)
Python
nomic_cornstack_python_v1
comment -*- coding: utf:8 -*- import sys import numpy as np import subprocess import math from PyQt5 import QtCore , QtWidgets , QtGui from PyQt5.QtWidgets import * from PyQt5.QtCore import QSize from PyQt5.QtGui import * class Sobel extends QWidget begin function __init__ self begin call __init__ call initUI end funct...
# -*- coding: utf:8 -*- import sys import numpy as np import subprocess import math from PyQt5 import QtCore, QtWidgets, QtGui from PyQt5.QtWidgets import * from PyQt5.QtCore import QSize from PyQt5.QtGui import * class Sobel(QWidget): def __init__(self): super().__init__() self.initUI...
Python
zaydzuhri_stack_edu_python
comment coding=utf-8 comment 数据保存到csv文件 function saveCsv filename data begin import codecs import csv set csvfile = call file filename string wb write csvfile BOM_UTF8 set writer = writer csvfile write rows writer data close csvfile end function comment 获取csv文件内容,可以指定分隔符号,数据起始行(从1开始),指定要取的数据列号例如:[['A', '字段名', '描述'], ['...
#coding=utf-8 #数据保存到csv文件 def saveCsv(filename, data): import codecs import csv csvfile = file(filename, 'wb') csvfile.write(codecs.BOM_UTF8) writer = csv.writer(csvfile) writer.writerows(data) csvfile.close() #获取csv文件内容,可以指定分隔符号,数据起始行(从1开始),指定要取的数据列号例如:[['A', '字段名', '描述'], ['BX', 'id', '行号']] def getCsvInfo(f...
Python
zaydzuhri_stack_edu_python
string Completed on 14/10/2020 Difficulty: Easy Url: https://www.hackerrank.com/challenges/acm-icpc-team/problem from itertools import combinations function acmTeam topic begin set best = 0 set count = 0 set teamList = sorted map sorted call combinations set topic 2 for pair in teamList begin set total = call calculate...
""" Completed on 14/10/2020 Difficulty: Easy Url: https://www.hackerrank.com/challenges/acm-icpc-team/problem """ from itertools import combinations def acmTeam(topic): best = 0 count = 0 teamList = sorted(map(sorted, combinations(set(topic), 2))) for pair in teamList: total =...
Python
zaydzuhri_stack_edu_python
import os , sys , inspect set currentdir = directory name path absolute path path call getfile call currentframe set parentdir = directory name path currentdir insert path 0 parentdir import mymodule
import os,sys,inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(0,parentdir) import mymodule
Python
jtatman_500k
while true begin set a = integer input if a < 10 begin continue end else if a > 100 begin break end else begin print a end end comment 2 comment b = "" comment while True: comment a = int(input()) comment if a < 10: comment continue comment elif a > 100: comment break comment else: comment b = b + str(a) + "\n" comment...
while True: a = int(input()) if a < 10: continue elif a > 100: break else: print(a) #2 # b = "" # while True: # a = int(input()) # if a < 10: # continue # elif a > 100: # break # else: # b = b + str(a) + "\n" # print(b)
Python
zaydzuhri_stack_edu_python