code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
import scraperwiki import requests import lxml.html import urllib function geocode address begin try begin set r = get requests string http://open.mapquestapi.com/nominatim/v1/search.php?format=json&q= + call quote_plus encode address string utf-8 set lat = json r at 0 at string lat set lon = json r at 0 at string lon ...
import scraperwiki import requests import lxml.html import urllib def geocode(address): try: r = requests.get('http://open.mapquestapi.com/nominatim/v1/search.php?format=json&q=' + urllib.quote_plus(address.encode('utf-8'))) lat = r.json()[0]["lat"] lon = r.json()[0]["lon"] return [...
Python
zaydzuhri_stack_edu_python
function isGoalState self state begin set coordinates = state at 0 set edges = state at 1 set corners = corners set TotalCorners = 4 if length edges == TotalCorners begin return true end else begin if coordinates in corners begin if not coordinates in edges begin append edges coordinates end end return false end end fu...
def isGoalState(self, state): coordinates = state[0] edges = state[1] corners = self.corners TotalCorners = 4 if(len(edges) == TotalCorners): return True else: if coordinates in corners: if not coordinates in edges: ...
Python
nomic_cornstack_python_v1
from sqlalchemy import Column , String , create_engine from sqlalchemy.orm import sessionmaker , scoped_session import threading from sqlalchemy.ext.declarative import declarative_base set Base = call declarative_base class User extends Base begin set __tablename__ = string web set id = call Column call String 20 prima...
from sqlalchemy import Column, String, create_engine from sqlalchemy.orm import sessionmaker, scoped_session import threading from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class User(Base): __tablename__ = 'web' id = Column(String(20), primary_key=True) name = Column(S...
Python
zaydzuhri_stack_edu_python
comment coding=utf8 from neuralnetwork import neuralnetwork from matplotlib import pyplot import numpy comment 创建一个神经网络,输入层784个节点,隐含层300个节点,输出层十个节点,训练速率0.2 comment network_1 = neuralnetwork(784, 300, 10, 0.2) comment 保存网络参数到配置文件 function save_net network_1 begin set wih_csv = open string conf/wih.csv string w for i in ...
# coding=utf8 from neuralnetwork import neuralnetwork from matplotlib import pyplot import numpy # 创建一个神经网络,输入层784个节点,隐含层300个节点,输出层十个节点,训练速率0.2 # network_1 = neuralnetwork(784, 300, 10, 0.2) # 保存网络参数到配置文件 def save_net(network_1): wih_csv = open('conf/wih.csv', 'w') for i in network_1.wih: for j in i...
Python
zaydzuhri_stack_edu_python
from sklearn.datasets import fetch_20newsgroups import matplotlib.pyplot as plt from sklearn.feature_extraction.text import CountVectorizer from nltk.stem import SnowballStemmer from sklearn.feature_extraction import text from sklearn.feature_extraction.text import TfidfTransformer from sklearn.decomposition import Tru...
from sklearn.datasets import fetch_20newsgroups import matplotlib.pyplot as plt from sklearn.feature_extraction.text import CountVectorizer from nltk.stem import SnowballStemmer from sklearn.feature_extraction import text from sklearn.feature_extraction.text import TfidfTransformer from sklearn.decomposition import Tru...
Python
zaydzuhri_stack_edu_python
function updateTable self fileIndex begin comment Assume delimiter is either whitespace or tab, read data comment Try to catch any runtime errors like changing the file etc. try begin set data = read csv session at string datafiles at fileIndex delim_whitespace=true engine=string python header=0 usecols=range length se...
def updateTable(self, fileIndex): # Assume delimiter is either whitespace or tab, read data # Try to catch any runtime errors like changing the file etc. try: data = pd.read_csv(self._model.session['datafiles'][fileIndex], delim_wh...
Python
nomic_cornstack_python_v1
function makeIntfPair cls intfname1 intfname2 addr1=none addr2=none node1=none node2=none deleteIntfs=true begin comment Leave this as a class method for now assert cls return call makeIntfPair intfname1 intfname2 addr1 addr2 node1 node2 deleteIntfs=deleteIntfs end function
def makeIntfPair( cls, intfname1, intfname2, addr1=None, addr2=None, node1=None, node2=None, deleteIntfs=True ): # Leave this as a class method for now assert cls return makeIntfPair( intfname1, intfname2, addr1, addr2, node1, node2, deleteIntfs...
Python
nomic_cornstack_python_v1
function regression func num_params data estimation=estimation begin set realdata = call RealData x y sx=sx sy=sy set model = model func set odr = call ODR realdata model beta0=call estimation x y num_params comment If sx is given do odr, else just do least-squares set fit_type = if expression is instance sx ndarray th...
def regression(func: Callable, num_params: int, data: Data, estimation: Callable = estimation, ) -> Tuple[np.ndarray, np.ndarray, float, float]: realdata = RealData(data.x, data.y, sx=data.sx, sy=data.sy) model = Model(func) odr = ODR(realdata, mode...
Python
nomic_cornstack_python_v1
function get_marketplace_listings begin set listed_games = all return listed_games end function
def get_marketplace_listings(): listed_games = ListedGame.query.all() return listed_games
Python
nomic_cornstack_python_v1
comment https://leetcode.com/problems/strange-printer/ comment Question : There is a strange printer with the following two special properties: comment The printer can only print a sequence of the same character each time. comment At each turn, the printer can print new characters starting from and ending at comment an...
# https://leetcode.com/problems/strange-printer/ # Question : There is a strange printer with the following two special properties: # The printer can only print a sequence of the same character each time. # At each turn, the printer can print new characters starting from and ending at # any place and will cover the ori...
Python
zaydzuhri_stack_edu_python
function platform_set_elevation self elevation begin call set_elevation elevation end function
def platform_set_elevation(self, elevation): self.platform.set_elevation(elevation)
Python
nomic_cornstack_python_v1
function calc_beta fx dfx begin assert ndim == 1 and shape == shape set n = size set f_bar = mean fx set ratio = sum / sum * n - 1 / decimal n set beta = square root sum / n - 1 * exp - ratio return beta end function
def calc_beta(fx, dfx): assert fx.ndim == 1 and fx.shape == dfx.shape n = fx.size f_bar = fx.mean() ratio = (dfx**2).sum() / ((fx - f_bar)**2).sum() * (n-1) / float(n) beta = sqrt(((fx - f_bar)**2).sum() / (n-1) * exp(-ratio)) return beta
Python
nomic_cornstack_python_v1
function process_compactible_shard_sequences broker sequences begin set timestamp = now set acceptor_ranges = list set shrinking_ranges = list for sequence in sequences begin set donors = sequence at slice : - 1 : extend shrinking_ranges donors comment Update the acceptor container with its expanded bounds to preve...
def process_compactible_shard_sequences(broker, sequences): timestamp = Timestamp.now() acceptor_ranges = [] shrinking_ranges = [] for sequence in sequences: donors = sequence[:-1] shrinking_ranges.extend(donors) # Update the acceptor container with its expanded bounds to prevent...
Python
nomic_cornstack_python_v1
function add_hardware_args parser begin comment TODO consider packaging as a dict/NestedNamespace comment TODO consider a boolean or something to indicate when to pass a comment tensorflow session or to use it as default call add_argument string --cpu default=1 type=int help=string The number of available CPUs. call ad...
def add_hardware_args(parser): # TODO consider packaging as a dict/NestedNamespace # TODO consider a boolean or something to indicate when to pass a # tensorflow session or to use it as default parser.add_argument( '--cpu', default=1, type=int, help='The number of availa...
Python
nomic_cornstack_python_v1
comment non-zero value check while length msg begin write outputFile msg + string set msg = read inputFile 10 end close inputFile close outputFile
while len(msg):#non-zero value check outputFile.write(msg+"\n") msg = inputFile.read(10) inputFile.close() outputFile.close()
Python
zaydzuhri_stack_edu_python
comment Andrew Smith comment RPC from random import randint comment instructions print string Jarvis has challenged you to rock, paper, scissors. print string What will you choose? set inpoot = integer input string Rock(1), Paper(2) or Scissors(3)? comment intitializing wins and losses set wins = 0 set losses = 0 comme...
# Andrew Smith # RPC from random import randint # instructions print("Jarvis has challenged you to rock, paper, scissors.") print("What will you choose?") inpoot = int(input("Rock(1), Paper(2) or Scissors(3)? ")) # intitializing wins and losses wins = 0 losses = 0 # game loop while(wins!=3 and losses !...
Python
zaydzuhri_stack_edu_python
comment DOES NOT CHECK FOR MISSING SEQUENCES comment ONLY DELETES DUPLICATES AND BUILDS A LIST OF SUBJECTS import os , glob , shutil import json function get_max_n_elements_in_dir_index dir_list begin import numpy as np return argument maximum list comprehension length glob glob d for d in dir_list end function set dic...
# DOES NOT CHECK FOR MISSING SEQUENCES # ONLY DELETES DUPLICATES AND BUILDS A LIST OF SUBJECTS # import os, glob, shutil import json def get_max_n_elements_in_dir_index(dir_list): import numpy as np return np.argmax([len(glob.glob(d)) for d in dir_list]) dicom_dir='/scr/adenauer2/nki_r5_onwards/r6_onwards/dic...
Python
zaydzuhri_stack_edu_python
function dir_to_fields self current_dir=string depth=0 manifest=list begin set fields = dict if not current_dir begin set current_dir = docdir end for name in list directory current_dir begin set current_path = join path current_dir name set rel_path = call _replace_backslash call relpath current_path docdir if start...
def dir_to_fields(self, current_dir='', depth=0, manifest=[]): fields={} if not current_dir: current_dir = self.docdir for name in os.listdir(current_dir): current_path = os.path.join(current_dir, name) rel_path = _replace_backslash(utils.relp...
Python
nomic_cornstack_python_v1
for i in range 1 11 begin set sum = sum + integer input string i + string 回目の入力: end print string 合計: sum sep=string
for i in range(1,11): sum += int(input(str(i) + "回目の入力:")) print("合計:",sum,sep="")
Python
zaydzuhri_stack_edu_python
import tkinter as tk from tkinter import ttk , messagebox from tkinter.scrolledtext import ScrolledText class ChatLogWidget extends Frame begin function __init__ self parent begin call __init__ parent set log_text = call Text self comment self.log_text['borderwidth'] = 0 comment self.log_text['background'] = self['back...
import tkinter as tk from tkinter import ttk, messagebox from tkinter.scrolledtext import ScrolledText class ChatLogWidget(ttk.Frame): def __init__(self, parent): super().__init__(parent) self.log_text = tk.Text(self) #self.log_text['borderwidth'] = 0 #self.log_text['background'] =...
Python
zaydzuhri_stack_edu_python
import json import re function get_cities_data begin with open string data/polish_cities/data string r as file begin set dic = dict set lines = read lines file for line in lines begin set line = strip line string set values = split re string + line if length values == 3 begin if values at 2 at - 1 == string N or value...
import json import re def get_cities_data(): with open('data/polish_cities/data', 'r') as file: dic = {} lines = file.readlines() for line in lines: line = line.strip("\n") values = re.split(" +", line) if len(values) == 3: if values[2]...
Python
zaydzuhri_stack_edu_python
class Solution begin function removeDuplicates self nums begin set arrayLength = length nums set unique = 0 if arrayLength == 0 begin return 0 end for index in range 1 arrayLength begin if nums at index != nums at unique begin set unique = unique + 1 set nums at unique = nums at index end end return unique + 1 end func...
class Solution: def removeDuplicates(self, nums: List[int]) -> int: arrayLength = len(nums) unique = 0 if(arrayLength == 0): return 0 for index in range(1, arrayLength): if nums[index] != nums[unique]: unique = unique...
Python
zaydzuhri_stack_edu_python
comment Collect all the coins! comment The peasants are unable to get the coins from other areas comment However, each area only spawns a certain value of coin! comment Filter through all the items and command the peasants accordingly. function commandPeasant peasant coins begin comment Command the peasant to the neare...
# Collect all the coins! # The peasants are unable to get the coins from other areas # However, each area only spawns a certain value of coin! # Filter through all the items and command the peasants accordingly. def commandPeasant(peasant, coins): # Command the peasant to the nearest of their array coin = peas...
Python
zaydzuhri_stack_edu_python
function login_open_sheet oauth_key_file spreadsheet begin try begin set scope = list string https://spreadsheets.google.com/feeds string https://www.googleapis.com/auth/drive set credentials = call from_json_keyfile_name oauth_key_file scope set gc = call authorize credentials set worksheet = sheet1 return worksheet e...
def login_open_sheet(oauth_key_file, spreadsheet): try: scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive'] credentials = ServiceAccountCredentials.from_json_keyfile_name(oauth_key_file, scope) gc = gspread.authorize(credentials) worksheet =...
Python
nomic_cornstack_python_v1
string arraylr.py Given an array of n integers and a number, d, perform d left rotations on the array. Then print the updated array as a single line of space-separated integers. mpmsimo 1/27/17 function list_left_rotation n d begin string Perform a left rotation on a list. end function if __name__ == string __main__ be...
""" arraylr.py Given an array of n integers and a number, d, perform d left rotations on the array. Then print the updated array as a single line of space-separated integers. mpmsimo 1/27/17 """ def list_left_rotation(n, d): """Perform a left rotation on a list.""" if __name__ == "__main__": n, k = map(int,...
Python
zaydzuhri_stack_edu_python
function rigids_mul_vecs r v begin set rots = call rots_mul_vecs r v set vecs_add_r = list rots at 0 + r at 9 rots at 1 + r at 10 rots at 2 + r at 11 return vecs_add_r end function
def rigids_mul_vecs(r, v): rots = rots_mul_vecs(r, v) vecs_add_r = [rots[0] + r[9], rots[1] + r[10], rots[2] + r[11]] return vecs_add_r
Python
nomic_cornstack_python_v1
comment 모의고사 : https://programmers.co.kr/learn/courses/30/lessons/42840 from itertools import cycle function solution answers begin set answer = list set count = list 0 0 0 set player_1 = list 1 2 3 4 5 set player_2 = list 2 1 2 3 2 4 2 5 set player_3 = list 3 3 1 1 2 2 4 4 5 5 for tuple p1 p2 p3 answer in zip cycle p...
# 모의고사 : https://programmers.co.kr/learn/courses/30/lessons/42840 from itertools import cycle def solution(answers): answer = [] count = [0,0,0] player_1 = [1,2,3,4,5] player_2 = [2,1,2,3,2,4,2,5] player_3 = [3,3,1,1,2,2,4,4,5,5] for p1, p2, p3, answer in zip(cycle(player_1), cycle(player_2),...
Python
zaydzuhri_stack_edu_python
import cv2 import numpy as np import matplotlib.pyplot as plt set image = call imread string nowwwwwww2.jpg set gray = call cvtColor image COLOR_BGR2GRAY set mask = zeros shape dtype=uint8 string cv2.imshow('Original Image', gray) cv2.waitKey(0) cv2.destroyWindow('Original Image') #make sure window closes cleanly cv2.i...
import cv2 import numpy as np import matplotlib.pyplot as plt image = cv2.imread('nowwwwwww2.jpg') gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) mask = np.zeros(image.shape, dtype=np.uint8) ''' cv2.imshow('Original Image', gray) cv2.waitKey(0) cv2.destroyWindow('Original Image') #make sure window closes cleanly cv2...
Python
zaydzuhri_stack_edu_python
function destroy self request cid begin set ret = call JsonResponse for telnet in telnet_list begin set ret = call simple_httpccm_action telnet string r cid end return ret end function
def destroy(self, request, cid): ret = JsonResponse() for telnet in request.telnet_list: ret = self.simple_httpccm_action(telnet, 'r', cid) return ret
Python
nomic_cornstack_python_v1
function draw_bounding_box_on_image image ymin xmin ymax xmax color=tuple 255 0 0 thickness=4 display_str=string use_normalized_coordinates=true begin set draw = call Draw image set tuple im_width im_height = size if use_normalized_coordinates begin set tuple left right top bottom = tuple xmin * im_width xmax * im_wid...
def draw_bounding_box_on_image(image, ymin, xmin, ymax, xmax, color=(255, 0, 0), thickness=4, display_s...
Python
nomic_cornstack_python_v1
comment This file is part of PSAMM. comment PSAMM is free software: you can redistribute it and/or modify comment it under the terms of the GNU General Public License as published by comment the Free Software Foundation, either version 3 of the License, or comment (at your option) any later version. comment PSAMM is di...
# This file is part of PSAMM. # # PSAMM is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # PSAMM is distributed in the hope that it wi...
Python
zaydzuhri_stack_edu_python
function parseNodes fname nodes center=none begin set context = call iterparse fname events=tuple string end comment First parse lat and lon from all way nodes for tuple event element in context begin if tag != string node begin pass end else begin set i = integer get element string id if i in nodes begin set node = no...
def parseNodes(fname, nodes, center = None): context = cElementTree.iterparse(fname, events=("end",)) # First parse lat and lon from all way nodes for event, element in context: if element.tag != "node": pass else: i = int(element.get("id")) ...
Python
nomic_cornstack_python_v1
function top2eq_m ha dec begin set tuple sin_H cos_H = tuple sin ha cos ha set tuple sin_d cos_d = tuple sin dec cos dec set mat = array list list sin_H - cos_H * sin_d cos_d * cos_H list cos_H sin_d * sin_H - cos_d * sin_H list zeros like ha cos_d sin_d if length shape == 3 begin set mat = transpose mat list 2 0 1 end...
def top2eq_m(ha, dec): sin_H, cos_H = np.sin(ha), np.cos(ha) sin_d, cos_d = np.sin(dec), np.cos(dec) mat = np.array([[sin_H, -cos_H * sin_d, cos_d * cos_H], [cos_H, sin_d * sin_H, -cos_d * sin_H], [np.zeros_like(ha), cos_d, sin_d]]) if len(mat.shape) == 3: ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment Copyright 2007 Google Inc. comment Licensed under the Apache License, Version 2.0 (the "License"); comment you may not use this file except in compliance with the License. comment You may obtain a copy of the License at comment http://www.apache.org/licenses/LICENSE-2.0 comment Unle...
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
Python
zaydzuhri_stack_edu_python
function _init_metadata self begin string stub call _init_metadata self call _init_metadata self call _init_metadata end function
def _init_metadata(self): """stub""" ItemTextsFormRecord._init_metadata(self) ItemFilesFormRecord._init_metadata(self) super(ItemTextsAndFilesMixin, self)._init_metadata()
Python
jtatman_500k
function fib N begin set sqrt5 = square root 5 set phi = sqrt5 + 1 / 2 return integer round power phi N / sqrt5 end function
def fib(N): sqrt5 = math.sqrt(5) phi = (sqrt5 + 1) / 2 return int(round(math.pow(phi, N) / sqrt5))
Python
nomic_cornstack_python_v1
function get_schools begin set school_objects_list = list set elementary_schools = dict reader open string data_transformation/2017-18 Elementary School Description- Responses.csv string rU dialect=excel_tab delimiter=string , set middle_schools = dict reader open string data_transformation/2017-18 Middle School Descr...
def get_schools(): school_objects_list = [] elementary_schools = csv.DictReader(open('data_transformation/2017-18 Elementary School Description- Responses.csv', 'rU'), dialect=csv.excel_tab, delimiter=",") middle_schools = csv.DictReader(open('data_transformation/2017-18 Middle School Description- Responses.csv',...
Python
nomic_cornstack_python_v1
function get_routers_directory self begin return _routers_directory end function
def get_routers_directory(self): return self._routers_directory
Python
nomic_cornstack_python_v1
import sympy as sp import numpy as np import matplotlib.pyplot as plt comment my symbols set tuple x0 x1 x2 x3 t = call symbols string x0, x1, x2, x3, t comment the polynomial function comment positon set pos = x0 + x1 * t + x2 * t ^ 2 + x3 * t ^ 3 comment velocity, deravative of positon set vel = diff sp pos t comment...
import sympy as sp import numpy as np import matplotlib.pyplot as plt #my symbols x0, x1, x2, x3, t = sp.symbols('x0, x1, x2, x3, t') #the polynomial function pos= x0 + x1*t + x2*t**2 + x3*t**3 #positon vel = sp.diff(pos,t) #velocity, deravative of positon acc = sp.diff(vel,t) #acceleration, deravative of velocit...
Python
zaydzuhri_stack_edu_python
import leveldb import rlp import hashlib function sha256 x begin return call digest end function class DB begin function __init__ self dbfile begin set db = call LevelDB dbfile end function function get self key begin try begin return get db key end except any begin return string end end function function put self key...
import leveldb import rlp import hashlib def sha256(x): return hashlib.sha256(x).digest() class DB(): def __init__(self,dbfile): self.db = leveldb.LevelDB(dbfile) def get(self,key): try: return self.db.Get(key) except: return '' def put(self,key,value): return self.db.Put(key,value) de...
Python
zaydzuhri_stack_edu_python
function Figure4Main self supplemental1=false begin if not supplemental1 begin set example_cells = list 5 9 17 30 end else begin set example_cells = list 2 6 10 11 13 18 end set start_letter = string A set parent_figure = none if not supplemental1 begin set sizer = dict string D dict string pos list 6.5 2.2 4.25 2.5 ; ...
def Figure4Main(self, supplemental1=False): if not supplemental1: example_cells = [5, 9, 17, 30] else: example_cells = [2, 6, 10, 11, 13, 18] start_letter = "A" parent_figure = None if not supplemental1: sizer = { "D": {"pos":...
Python
nomic_cornstack_python_v1
function find_second_largest nums begin set largest = decimal string -inf set secondLargest = decimal string -inf set largestFreq = 0 set secondLargestFreq = 0 for num in nums begin if num > largest begin set secondLargest = largest set largest = num set secondLargestFreq = largestFreq set largestFreq = 1 end else if n...
def find_second_largest(nums): largest = float('-inf') secondLargest = float('-inf') largestFreq = 0 secondLargestFreq = 0 for num in nums: if num > largest: secondLargest = largest largest = num secondLargestFreq = largestFreq largestFreq = 1...
Python
greatdarklord_python_dataset
function id self begin return get pulumi self string id end function
def id(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "id")
Python
nomic_cornstack_python_v1
from basegamestate import BaseGameState import random class TicTacToeState extends BaseGameState begin set WIN_INDICE_LISTS = list list 0 1 2 list 0 3 6 list 0 4 8 list 1 4 7 list 2 5 8 list 3 4 5 list 6 7 8 list 2 4 6 function __init__ self state_list parent=none children=none begin set state_list = state_list set mov...
from basegamestate import BaseGameState import random class TicTacToeState(BaseGameState): WIN_INDICE_LISTS = [[0, 1, 2], [0, 3, 6], [0, 4, 8], [1, 4, 7], [2, 5, 8], [3, 4, 5], ...
Python
zaydzuhri_stack_edu_python
function _factory self response begin for factory in reversed _factories begin set event = call factory response if event begin return event end end return none end function
def _factory(self, response): for factory in reversed(self._factories): event = factory(response) if event: return event return None
Python
nomic_cornstack_python_v1
from turtle import * import random set screen = call Screen setup screen width=500 height=400 set is_game_on = false set user_bet = call textinput title=string guess a colour prompt=string bet a colour which will win on this turtle race? set color = list string red string orange string yellow string blue string purple ...
from turtle import * import random screen = Screen() screen.setup(width=500,height=400) is_game_on = False user_bet = screen.textinput(title="guess a colour", prompt="bet a colour which will win on this turtle race? ") color = ["red", "orange", "yellow", "blue", "purple", "green"] y_position =[-100, -60, -20, 20, 60, ...
Python
zaydzuhri_stack_edu_python
class ListNode extends object begin function __init__ self val next=none begin set val = val set next = next end function end class class Solution begin function removeElements self head val begin if head == none begin return head end set dummy = call ListNode 0 set next = head set pre = dummy while head begin if val =...
class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next class Solution: def removeElements(self, head, val): if head == None: return head dummy = ListNode(0) dummy.next = head pre = dummy while head: ...
Python
zaydzuhri_stack_edu_python
function filter_strings my_list character begin set filtered_list = list for string in my_list begin if string at 0 == character and string at - 1 == character begin append filtered_list string end end return filtered_list end function set my_list = list string Hello string World string Hi string Python set character ...
def filter_strings(my_list, character): filtered_list = [] for string in my_list: if string[0] == character and string[-1] == character: filtered_list.append(string) return filtered_list my_list = ['Hello', 'World', 'Hi', 'Python'] character = 'o' filtered_list = filter_strings(my_list...
Python
jtatman_500k
function customOrder self begin return _custom_order end function
def customOrder(self): return self._custom_order
Python
nomic_cornstack_python_v1
function test_log_to_stdout self begin set version = call get_nodes_version if string 6.5 > version at slice : 3 : begin call fail format string Test not supported for versions pre 6.5.0Version was run with {} version end set log_to_stdout = true comment Test config set tuple output err = call backup_create if err be...
def test_log_to_stdout(self): version = RestConnection(self.backupset.backup_host).get_nodes_version() if "6.5" > version[:3]: self.fail("Test not supported for versions pre 6.5.0" "Version was run with {}".format(version)) self.backupset.log_to_stdout = True ...
Python
nomic_cornstack_python_v1
function test_get_effective_min_val_float_overrides_inherited self begin call __test_get_effective_num_constraint_BC_overrides_inherited_h FLOAT FLOAT MIN_VAL 33 30 end function
def test_get_effective_min_val_float_overrides_inherited(self): self.__test_get_effective_num_constraint_BC_overrides_inherited_h( self.FLOAT, self.FLOAT, BasicConstraint.MIN_VAL, 33, 30 )
Python
nomic_cornstack_python_v1
function set_feature self feature kwargs begin return call get attribute _sdk string set_ { feature } keyword kwargs end function
def set_feature(self, feature, kwargs): return getattr(self._sdk, f"set_{feature}")(**kwargs)
Python
nomic_cornstack_python_v1
function hasRequiredElements self begin return call Delay_hasRequiredElements self end function
def hasRequiredElements(self): return _libsbml.Delay_hasRequiredElements(self)
Python
nomic_cornstack_python_v1
function total_unsubscribes self begin return _total_unsubscribes end function
def total_unsubscribes(self): return self._total_unsubscribes
Python
nomic_cornstack_python_v1
from bs4 import BeautifulSoup from helpers.utility import strip_html_tags , transform_length class MovieScraper begin function __init__ self body begin set html = call BeautifulSoup body string lxml end function function get_details self item begin comment OVERVIEW set item at string overview = text comment GENRES try ...
from bs4 import BeautifulSoup from helpers.utility import strip_html_tags, transform_length class MovieScraper: def __init__(self, body): self.html = BeautifulSoup(body, "lxml") def get_details(self, item): # OVERVIEW item['overview'] = self.html.find("div", {"class": 'inline canwrap...
Python
zaydzuhri_stack_edu_python
function fd_names_list chain_pos thrds begin set name_list = call fd_data_names_list thrds return name_list end function
def fd_names_list(chain_pos, thrds): name_list = fd_data_names_list(thrds) return name_list
Python
nomic_cornstack_python_v1
function get_assignment begin try begin set assignment_id = integer assignmentid end except tuple TypeError ValueError begin set assignment_row = none end try else begin set assignment_row = first select call db id == assignment_id end comment Assemble the assignment-level properties if not assignment_row begin error f...
def get_assignment(): try: assignment_id = int(request.vars.assignmentid) except (TypeError, ValueError): assignment_row = None else: assignment_row = db(db.assignments.id == assignment_id).select().first() # Assemble the assignment-level properties if not assignment_row: ...
Python
nomic_cornstack_python_v1
function partition arr l r begin set compare = arr at r set i = l - 1 for j in range l r begin if arr at j < compare begin set i = i + 1 set tuple arr at i arr at j = tuple arr at j arr at i end end set tuple arr at i + 1 arr at r = tuple arr at r arr at i + 1 return i + 1 end function function quickSort arr l r begin ...
def partition(arr,l,r): compare=arr[r] i=l-1 for j in range(l,r): if arr[j]<compare: i+=1 arr[i],arr[j]=arr[j],arr[i] arr[i+1],arr[r]=arr[r],arr[i+1] return i+1 def quickSort(arr,l,r): if l<r: pivot=partition(arr,l,r) quickSort(arr,l,pivo...
Python
zaydzuhri_stack_edu_python
import spacy set nlp = load spacy string en_core_web_sm set doc = call nlp string This is a sentence. This is a second sentence. This is a third sentence probably greater than the other two. for sents in sents begin print sents end comment doc.sents[0] set listdoc = list sents listdoc at 0 set doc = call nlp string "Ma...
import spacy nlp = spacy.load('en_core_web_sm') doc = nlp("This is a sentence. This is a second sentence. This is a third sentence probably greater than the other two.") for sents in doc.sents: print(sents) #doc.sents[0] listdoc = list(doc.sents) listdoc[0] doc = nlp(u'"Management is doing the right things; lea...
Python
zaydzuhri_stack_edu_python
function test_post_add_workflow_step self begin pass end function
def test_post_add_workflow_step(self): pass
Python
nomic_cornstack_python_v1
function distance lat1 lon1 lat2 lon2 begin import math comment metres set r = 6371000 set phi_1 = call radians lat1 set phi_2 = call radians lat2 set d_phi = call radians lat2 - lat1 set d_lam = call radians lon2 - lon1 set a = sin d_phi / 2 * sin d_phi / 2 + cos phi_1 * cos phi_2 * sin d_lam / 2 * sin d_lam / 2 set c...
def distance(lat1, lon1, lat2, lon2): import math r = 6371000 # metres phi_1 = math.radians(lat1) phi_2 = math.radians(lat2) d_phi = math.radians(lat2 - lat1) d_lam = math.radians(lon2 - lon1) a = math.sin(d_phi / 2) * math.sin(d_phi / 2) + \ math.cos(phi_1) * math.cos(phi_2) * \ ...
Python
nomic_cornstack_python_v1
import json import ast import os function parses_load parses_file begin string open parses file with open parses_file as data_file begin set data = load json data_file end return data end function function get_words_dict parses_file begin string create a dict with DocID as keys and list of triples (sent_id, token_id, t...
import json import ast import os def parses_load(parses_file): ''' open parses file ''' with open(parses_file) as data_file: data = json.load(data_file) return data def get_words_dict(parses_file): ''' create a dict with DocID as keys and list of triples (sent_id, token_id, token) for eac...
Python
zaydzuhri_stack_edu_python
function test_argmax_split self begin comment Create the left cost volume, with ZNCC measure, window size 1, subpixel 2, disp_min -3 disp_max 1 set stereo_plugin = call AbstractStereo keyword dict string stereo_method string zncc ; string window_size 1 ; string subpix 2 set cv = call compute_cost_volume ref sec - 3 1 k...
def test_argmax_split(self): # Create the left cost volume, with ZNCC measure, window size 1, subpixel 2, disp_min -3 disp_max 1 stereo_plugin = stereo.AbstractStereo(**{'stereo_method': 'zncc', 'window_size': 1, 'subpix': 2}) cv = stereo_plugin.compute_cost_volume(self.ref, self.sec, -3, 1, **{...
Python
nomic_cornstack_python_v1
import sys from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait , Select from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.chrome.options import Options import time import datetime import webbrowser set ...
import sys from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait, Select from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.chrome.options import Options import time import datetime import webbrowser PAT...
Python
zaydzuhri_stack_edu_python
from math import sqrt from abc import ABC , abstractmethod from src.raytracing import snell from src.ray import Ray class Component begin function __init__ self position diameter n begin set _position = position set _diameter = diameter set _refractive_index = n end function decorator abstractmethod function interact_w...
from math import sqrt from abc import ABC, abstractmethod from src.raytracing import snell from src.ray import Ray class Component: def __init__(self, position, diameter, n): self._position = position self._diameter = diameter self._refractive_index = n @abstractmethod def intera...
Python
zaydzuhri_stack_edu_python
comment @team 35 comment @author Jiacheng Ye 904973 Shanghai, China comment @author Shiyi Xu 780801 Melbourne, Australia comment @author Yuyao Ma 1111182 Yinchuan, China comment @author Yujing Guan 1011792 Fuzhou, China comment @author Zexin Yu 10328021 Dalian, China import json , requests , sys from os.path import dir...
# @team 35 # @author Jiacheng Ye 904973 Shanghai, China # @author Shiyi Xu 780801 Melbourne, Australia # @author Yuyao Ma 1111182 Yinchuan, China # @author Yujing Guan 1011792 Fuzhou, China # @author Zexin Yu 10328021 Dalian, China import json, requests, sys from os.path import...
Python
zaydzuhri_stack_edu_python
comment !/bin/python3 import math import os import random import re import sys comment Complete the timeInWords function below. function timeInWords h m begin set hours = tuple string one string two string three string four string five string six string seven string eight string nine string ten string eleven string twe...
#!/bin/python3 import math import os import random import re import sys # Complete the timeInWords function below. def timeInWords(h, m): hours = ("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve") minutes = ("on...
Python
zaydzuhri_stack_edu_python
function run self begin set running = 1 while running begin try begin set data = call recv size end except Exception begin set data = none end if data begin set running = call handle data end else begin set running = 0 close client end end end function
def run(self): running = 1 while running: try: data = self.client.recv( self.size ) except Exception: data = None if data: running = self.handle( data ) else: running = 0 self.client.close()
Python
nomic_cornstack_python_v1
function clean_on self begin try begin set cmd = call pack string BB MOTORSCMD 7 end except error begin raise call RoombaError string Fatal error in clean_off end call _send_command cmd end function
def clean_on(self): try: cmd = struct.pack('BB', MOTORSCMD, 7) except struct.error: raise RoombaError('Fatal error in clean_off') self._send_command(cmd)
Python
nomic_cornstack_python_v1
function smallestPositive nums begin if nums == list begin return 1 end sort nums if max nums <= 0 begin return 1 end for i in range max nums + 1 begin if i not in nums begin if i != 0 begin return i end end end return max nums + 1 end function set ar = list 0 2 1 3 5 print call smallestPositive ar
def smallestPositive(nums): if nums == []: return 1 nums.sort() if max(nums) <= 0: return 1 for i in range(max(nums) + 1): if i not in nums: if i != 0: return i return max(nums) + 1 ar=[0,2,1,3,5] print(smallestPositive(ar))
Python
zaydzuhri_stack_edu_python
import numpy as np import matplotlib.pyplot as plt import scipy.stats import sys comment =============================================================== comment References comment =============================================================== comment https://www.python-course.eu/neural_networks.php comment https://www...
import numpy as np import matplotlib.pyplot as plt import scipy.stats import sys # =============================================================== # References # =============================================================== # https://www.python-course.eu/neural_networks.php # https://www.python-course.eu/neural_netw...
Python
zaydzuhri_stack_edu_python
comment -*- coding:utf-8 -*- import sfml as sf set pencere = call RenderWindow call VideoMode 640 480 string AB2015 python oyun kursu while is_open begin for event in events begin if type event is CloseEvent begin close pencere end if type event is KeyEvent begin if released and code is ESCAPE begin close pencere end e...
# -*- coding:utf-8 -*- import sfml as sf pencere = sf.RenderWindow(sf.VideoMode(640, 480), "AB2015 python oyun kursu") while pencere.is_open: for event in pencere.events: if type(event) is sf.CloseEvent: pencere.close() if type(event) is sf.KeyEvent: ...
Python
zaydzuhri_stack_edu_python
function calculate_C self interval off=0 begin set C = list 0 set C_int = 0 set EN = index set P1 = data at string c+ set P2 = data at string c- + off for i in range interval at 0 interval at 1 + 1 begin set c_int = EN at i + 1 - EN at i * P1 at i + P2 at i + P1 at i + 1 + P2 at i + 1 / 4 set C_int = C_int + c_int appe...
def calculate_C(self, interval, off = 0): C = [0] C_int = 0 EN = self.data.index P1 = self.data['c+'] P2 = self.data['c-'] + off for i in range(interval[0], interval[1] + 1): c_int = (EN[i+1] - EN[i]) * ((P1[i] + P2[i]) + (P1[i+1] + P2[i+1]))/4 ...
Python
nomic_cornstack_python_v1
function get_unique_artist user begin set seen_ids = call values_list string artist_id flat=true return first call order_by string ? end function
def get_unique_artist(user): seen_ids = user.opinion_set.values_list("artist_id", flat=True) return Artist.objects.exclude(id__in=seen_ids).order_by('?').first()
Python
nomic_cornstack_python_v1
string Contains code, related to ESPNow packet handling. comment Maximum length of a packet in bytes comment (255 or 256 characters will lead to errors) set MAX_PACKET_LENGTH = 217 function index_or_false packet byte begin string If there's a byte in bytearray, tells its first position. Otherwise returns False. set ind...
"""Contains code, related to ESPNow packet handling.""" # Maximum length of a packet in bytes # (255 or 256 characters will lead to errors) MAX_PACKET_LENGTH = 217 def index_or_false(packet, byte): """If there's a byte in bytearray, tells its first position. Otherwise returns False.""" index = False ...
Python
zaydzuhri_stack_edu_python
from tkinter import * set root = call Tk title root string GUI tests call geometry string 540x380+540+300 call resizable false false call pack side=string top call pack side=string bottom comment relief: 테두리모양 comment bd: 외곽선 굵기 set frame_burger = call Frame root relief=string solid bd=1 call pack side=string left fill...
from tkinter import * root = Tk() root.title("GUI tests") root.geometry("540x380+540+300") root.resizable(False,False) Label(root, text="메뉴를 선택해주세요").pack(side="top") Button(root, text="주문하기").pack(side="bottom") #relief: 테두리모양 #bd: 외곽선 굵기 frame_burger = Frame(root, relief="solid", bd=1) frame_burger.pack(side="left...
Python
zaydzuhri_stack_edu_python
while novaEntrada == string sim begin set idade = integer input string Digite sua idade: set contI = contI + 1 set soma = soma + idade set media = soma / contI set novaEntrada = lower str input string Deseja computar idades: end if media <= 25 begin print string A média de idade classifica a turma como JOVEM end else i...
while novaEntrada == "sim": idade = int(input("Digite sua idade: ")) contI +=1 soma += idade media = soma / contI novaEntrada = str.lower(input("Deseja computar idades: ")) if media <=25: print("A média de idade classifica a turma como JOVEM") elif media > 25 and media <=60: print("A média d...
Python
zaydzuhri_stack_edu_python
function rasterize self mode=string polar axes=list 0 1 pixel_length=0.01 begin if mode == string pts begin set arr = pts end if mode == string polar begin set arr = polar end set tuple x y z = T set xs = array range min max pixel_length set ys = array range min max pixel_length set avg = list for tuple col_num tuple ...
def rasterize(self, mode='polar', axes=[0, 1], pixel_length=.01): if mode == 'pts': arr = self.pts if mode == 'polar': arr = self.polar x, y, z = arr.T xs = np.arange(x.min(), x.max(), pixel_length) ys = np.arange(y.min(), y.max(), pixel_length) ...
Python
nomic_cornstack_python_v1
function test_card_id_present_and_signup_complete self begin set machine_id = call create_coffee_machine app string Senseo Floor 5 0.35 string EUR set card_id = call create_coffee_addict app string john string john@doe.com machine_id set res = put coffee_count_api_path data=dict string machine_id machine_id ; string ca...
def test_card_id_present_and_signup_complete(self): machine_id = helpers.create_coffee_machine(self.app, \ "Senseo Floor 5", 0.35, "EUR" ) card_id = helpers.create_coffee_addict(self.app, \ "john", "john@doe.com", machine_id) res = self.app.put(co...
Python
nomic_cornstack_python_v1
function main begin set n = integer input string Quantidade de números: for i in range n begin set numeros = input string Números: set dados = split numeros set n1 = decimal dados at 0 set n2 = decimal dados at 1 set n3 = decimal dados at 2 set num1 = n1 * 2 set num2 = n2 * 3 set num3 = n3 * 5 set media = num1 + num2 +...
def main(): n = int(input('Quantidade de números: ')) for i in range(n): numeros = input('Números: ') dados = numeros.split() n1 = float(dados[0]) n2 = float(dados[1]) n3 = float(dados[2]) num1 = n1*2 num2 = n2*3 num3 = n3*5 me...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- set num = integer call raw_input string Give me a number. function build_pyramid bacis_num begin set brick = string * comment 一次增加兩階 for i in range 1 bacis_num + 1 2 begin set bricks = brick * i print call center bacis_num string end end function call build_pyramid num
#-*- coding: utf-8 -*- num = int(raw_input("Give me a number.")) def build_pyramid(bacis_num): brick = '*' # 一次增加兩階 for i in range(1, bacis_num + 1, 2): bricks = brick * i print(bricks.center(bacis_num, ' ')) build_pyramid(num)
Python
zaydzuhri_stack_edu_python
import unittest import ugradio.gauss import numpy as np seed 0 class TestGauss extends TestCase begin function test_pack_prms self begin set tuple amp0 avg0 sig0 = tuple 1.5 0.1 2.2 set prms0 = call _pack_prms amp0 avg0 sig0 call assert_equal prms0 array list amp0 avg0 sig0 set tuple amp0 avg0 sig0 = tuple list 1.0 2 l...
import unittest import ugradio.gauss import numpy as np np.random.seed(0) class TestGauss(unittest.TestCase): def test_pack_prms(self): amp0, avg0, sig0 = 1.5, .1, 2.2 prms0 = ugradio.gauss._pack_prms(amp0,avg0,sig0) np.testing.assert_equal(prms0, np.array([amp0, avg0, sig0])) amp0...
Python
zaydzuhri_stack_edu_python
function get_latest_version begin set found_version = string unknown set version_re = string ^## \[(\d+\.\d+\.\d+)\] with open join path __repo_root__ string CHANGELOG.md as changelog_file begin for line in changelog_file begin set found = search version_re line if found begin set found_version = call group 1 break end...
def get_latest_version(): found_version = "unknown" version_re = r"^## \[(\d+\.\d+\.\d+)\]" with open(os.path.join(__repo_root__, "CHANGELOG.md")) as changelog_file: for line in changelog_file: found = re.search(version_re, line) if found: found_version = fou...
Python
nomic_cornstack_python_v1
comment ! /usr/bin/python comment This script runs under python 3.x comment The objective of this script is to detect fusion transcript comment from cufflinks/stringtie assembled GTF file comment If a transcript C contain some exons belong to A, and some exons comment belong to B, it will output as a candidate fusion t...
#! /usr/bin/python ## This script runs under python 3.x ## The objective of this script is to detect fusion transcript ## from cufflinks/stringtie assembled GTF file ## If a transcript C contain some exons belong to A, and some exons ## belong to B, it will output as a candidate fusion transcript ## It's bettter fil...
Python
zaydzuhri_stack_edu_python
import turtle from random import * call bgcolor string white set text = string Python Turtle set colors = list string black string red string yellow string purple string blue string green for pos in range 50 begin call pencolor colors at random integer 0 5 call penup call forward pos * 5 call pendown write turtle text ...
import turtle from random import * turtle.bgcolor("white") text="Python Turtle" colors=['black','red','yellow','purple','blue','green'] for pos in range(50): turtle.pencolor(colors[randint(0,5)]) turtle.penup() turtle.forward(pos*5) turtle.pendown() turtle.write(text,font=("Arial",pos+10)) tur...
Python
zaydzuhri_stack_edu_python
function angkaUrut x end angka begin while x < end begin set i = 0 while i < end begin if angka at x < angka at i begin set y = angka at x set angka at x = angka at i set angka at i = y end set i = i + 1 end set x = x + 1 end end function function deviasiAngka ragam begin set x = 0 set y = 0 set input = ragam comment T...
def angkaUrut(x, end, angka): while x < end: i = 0 while i < end: if angka[x] < angka[i]: y = angka[x] angka[x] = angka[i] angka[i] = y i = i + 1 x = x + 1 def deviasiAngka(ragam): x = 0 y = 0 input = ragam ...
Python
zaydzuhri_stack_edu_python
function enoughForLeader self votes begin set entry = call getConfig if entry at string config == string single begin set validVotes = length set keys entry at string data ? set votes return validVotes > length entry at string data / 2 end set validVotesOld = length set keys entry at string data at 0 ? set votes set va...
def enoughForLeader(self, votes): entry = self.getConfig() if entry['config'] == 'single': validVotes = len(set(entry['data'].keys()) & set(votes)) return validVotes > len(entry['data']) / 2 validVotesOld = len(set(entry['data'][0].keys()) & set(votes)) validVotes...
Python
nomic_cornstack_python_v1
function parse_dept url begin set x = parse html url set course_roots = call xpath string //*[@class="course"] set subcourse_list = list for course_root in course_roots begin set day_elems = call xpath string div//*[@class="mtgpat"] set time_elems = call xpath string div//*[@class="mtg_time"] for j in range 0 length d...
def parse_dept(url): x = lxml.html.parse(url) course_roots = x.xpath('//*[@class="course"]') subcourse_list = [] for course_root in course_roots: day_elems = course_root.xpath('div//*[@class="mtgpat"]') time_elems = course_root.xpath('div//*[@class="mtg_time"]') for j in ran...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import configparser import logging import os import sqlalchemy import sys import time set delay = 5 set default_config_file = join path directory name path absolute path path __file__ string probes.cfg set log = call getLogger string db-wait call setLevel DEBUG set ch = call StreamHandler ...
# -*- coding: utf-8 -*- import configparser import logging import os import sqlalchemy import sys import time delay = 5 default_config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'probes.cfg') log = logging.getLogger('db-wait') log.setLevel(logging.DEBUG) ch = logging.StreamHandler(sys.stdout) ch...
Python
zaydzuhri_stack_edu_python
import pandas as pd import os import socket import time set df2015 = read csv string ../datasets/2015.csv at list string Country string Region string Happiness Score set df2016 = read csv string ../datasets/2016.csv at list string Country string Region string Happiness Score set df = concat list df2015 df2016 set tuple...
import pandas as pd import os import socket import time df2015 = pd.read_csv('../datasets/2015.csv')[['Country', 'Region', 'Happiness Score']] df2016 = pd.read_csv('../datasets/2016.csv')[['Country', 'Region', 'Happiness Score']] df = pd.concat([df2015, df2016]) host, port = ('127.0.0.1', 9999) print("Starting serv...
Python
zaydzuhri_stack_edu_python
function create self **kwargs begin set d = dict string Name name ; string CallerReference string uuid 4 ; string HostedZoneConfig dict string PrivateZone false set annotations = get kwargs string annotations none if annotations begin set d at string HostedZoneConfig at string Comment = dumps annotations end try begin ...
def create(self, **kwargs): d = { "Name": self.name, "CallerReference": str(uuid.uuid4()), "HostedZoneConfig": { "PrivateZone": False } } annotations = kwargs.get("annotations", None) if annotations: d["HostedZon...
Python
nomic_cornstack_python_v1
function to_ot2_equivalent self begin return get _ot3_to_ot2 self self end function
def to_ot2_equivalent(self) -> DeckSlotName: return _ot3_to_ot2.get(self, self)
Python
nomic_cornstack_python_v1
function __init__ self observation_space action_space parallel_envs cfg begin set observation_space = observation_space set action_space = action_space set obs_size = call flatdim observation_space set action_size = call flatdim action_space set parallel_envs = parallel_envs comment set all values from config as attrib...
def __init__(self, observation_space, action_space, parallel_envs, cfg): self.observation_space = observation_space self.action_space = action_space self.obs_size = flatdim(observation_space) self.action_size = flatdim(action_space) self.parallel_envs = parallel_envs #...
Python
nomic_cornstack_python_v1
function get self request begin set context = call get_context_data request=request set ban = call get_object_or_404 Ban ip=call get_client_ip request set context at string ban_reason = reason return call render request string boards/staticpages/banned.html context end function
def get(self, request): context = self.get_context_data(request=request) ban = get_object_or_404(Ban, ip=utils.get_client_ip(request)) context['ban_reason'] = ban.reason return render(request, 'boards/staticpages/banned.html', context)
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import numpy as np from matplotlib import pyplot as plt comment If the "residual" |f(x_k)| < tol, stop iteration set tol = 1e-12 set printouts = true comment Define the function, its derivative, and all the methods function f x begin comment Basic idea, superlinear convergence, comparing N...
# -*- coding: utf-8 -*- import numpy as np from matplotlib import pyplot as plt tol = 1e-12 # If the "residual" |f(x_k)| < tol, stop iteration printouts = True # Define the function, its derivative, and all the methods def f(x): # Basic idea, superlinear convergence, comparing Newton, Secant, and Newton2: # retur...
Python
zaydzuhri_stack_edu_python
comment coding: utf-8 function quick_sort b begin set blen = length b comment 注意,使用递归算法, 这个判断必须要有 if blen < 2 begin return b end set mid = b at blen / 2 set tuple left right = tuple list list remove b mid for i in b begin if i > mid begin append right i end else begin append left i end end return call quick_sort left...
# coding: utf-8 def quick_sort(b): blen = len(b) if blen < 2: #注意,使用递归算法, 这个判断必须要有 return b mid = b[blen/2] left, right = [], [] b.remove(mid) for i in b: if i > mid: right.append(i) else: left.append(i) return quick_sort(left) + [mid] + qu...
Python
zaydzuhri_stack_edu_python
import random function password_generator a begin set length = a set passwd = list string 1234567890abcdABCD!@#$%^&*()-=_?qwertySDFGH shuffle random passwd set passwd = join string list comprehension random choice passwd for x in range length print passwd set my_file = open string PWTask2_2.txt string a write my_file ...
import random def password_generator(a): length = a passwd = list('1234567890abcdABCD!@#$%^&*()-=_?qwertySDFGH') random.shuffle(passwd) passwd = ''.join([random.choice(passwd) for x in range(length)]) print(passwd) my_file = open("PWTask2_2.txt", 'a') my_file.write(f'{passwd} \n') my_...
Python
zaydzuhri_stack_edu_python
function unescape_latex_entities text begin set out = text set out = replace out string \& string & return out end function
def unescape_latex_entities(text): out = text out = out.replace('\\&', '&') return out
Python
nomic_cornstack_python_v1
function send_mail api_url user key sender receiver subject text file_name begin set authorization = tuple user key set data = dict string from sender ; string to receiver ; string subject subject ; string text text try begin return post api_url auth=authorization files=list tuple string attachment tuple file_name read...
def send_mail(api_url, user, key, sender, receiver, subject, text, file_name): authorization = (user, key) data = { "from": sender, "to": receiver, "subject": subject, "text": text } try: return requests.post(api_url, auth=authorizati...
Python
nomic_cornstack_python_v1
import math function calculate_standard_deviation numbers begin set n = length numbers set mean = sum numbers / n set variance = sum generator expression x - mean ^ 2 for x in numbers / n set std_deviation = square root variance return std_deviation end function import math import statistics function calculate_standard...
import math def calculate_standard_deviation(numbers): n = len(numbers) mean = sum(numbers) / n variance = sum((x - mean) ** 2 for x in numbers) / n std_deviation = math.sqrt(variance) return std_deviation import math import statistics def calculate_standard_deviation(numbers): n = len(numbers) mean = statisti...
Python
jtatman_500k