code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment !/usr/bin/env python from sys import exit from collections import deque set _DEBUG_ENABLE = true set OFFSETLIVETRAFFIC = 4 set ROOTNODEID = - 100 set ALGOS = tuple string BFS string DFS string UCS string A* function Debug_print msg begin string Method to print the debug messages global _DEBUG_ENABLE end functio...
#!/usr/bin/env python from sys import exit from collections import deque _DEBUG_ENABLE = True OFFSETLIVETRAFFIC = 4 ROOTNODEID = -100 ALGOS = ('BFS', 'DFS', 'UCS', 'A*') def Debug_print(msg): """ Method to print the debug messages """ global _DEBUG_ENABLE
Python
zaydzuhri_stack_edu_python
function check_shape data day day_name=string DAY365 begin comment Here we explicit variable "DAY365" because of our specific application in this project if shape at 0 == 0 begin return false end else begin return true end end function
def check_shape(data, day, day_name = 'DAY365'): # Here we explicit variable "DAY365" because of our specific application in this project if(data[data[day_name] == day].shape[0] == 0): return False else: return True
Python
nomic_cornstack_python_v1
function load_rml self rml_name begin set conn = rml_tstore set cache_path = join path CACHE_DATA_PATH string rml_files rml_name if not exists path cache_path begin set results = call get_graph call uri get attribute kdr rml_name false conn with open cache_path string w as file_obj begin write file_obj dumps results in...
def load_rml(self, rml_name): conn = CFG.rml_tstore cache_path = os.path.join(CFG.CACHE_DATA_PATH, 'rml_files', rml_name) if not os.path.exists(cache_path): results = get_graph(NSM.uri(getattr(NSM.kdr, rml_name), False), conn) with open(cac...
Python
nomic_cornstack_python_v1
function reset_models models begin for m in models begin delete end comment set autoincrement to zero using sequence_reset_sql set srs = call sequence_reset_sql call no_style models with call cursor as cursor begin for sql in srs begin execute cursor sql end end end function
def reset_models(models): for m in models: m.objects.all().delete() # set autoincrement to zero using sequence_reset_sql srs = connection.ops.sequence_reset_sql(no_style(), models) with connection.cursor() as cursor: for sql in srs: cursor.execute(sql)
Python
nomic_cornstack_python_v1
comment app.py from flask import Flask , render_template , redirect , request , session , flash from flask_session import Session comment Flask 객체 인스턴스 생성 set app = call Flask __name__ set config at string SECRET_KEY = string ABCD comment CORS from flask_cors import CORS call CORS app comment Session set config at stri...
# app.py from flask import Flask, render_template, redirect, request, session , flash from flask_session import Session #Flask 객체 인스턴스 생성 app = Flask(__name__) app.config["SECRET_KEY"] = "ABCD" #CORS from flask_cors import CORS CORS(app) #Session app.config["SESSION_PERMANENT"] = False app.config["SESSION_TYPE"] = "fil...
Python
zaydzuhri_stack_edu_python
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time import random class InstagramBot begin function __init__ self username password begin set username = username set password = password set browser = call Chrome string /Users/joshmanik/Downloads/chromedriver 3 end function functio...
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time import random class InstagramBot: def __init__(self, username, password): self.username = username self.password = password self.browser = webdriver.Chrome("/Users/joshmanik/Downloads/chromedriver 3"...
Python
zaydzuhri_stack_edu_python
function update_preference_settings_of_username_and_return_instance self username update_dict begin set preference_settings = call get_preference_settings_by_username username call update_preference_settings preference_settings update_dict return preference_settings end function
def update_preference_settings_of_username_and_return_instance(self, username, update_dict): preference_settings = self.get_preference_settings_by_username(username) self.preference_model_handler.update_preference_settings(preference_settings, update_dict) return preference_settings
Python
nomic_cornstack_python_v1
function get_name cls begin string Retrieve the schema name associated with a message class. Returns: str: The schema name. Raises: TypeError: If the message class isn't registered. Check your entry point for correctness. global _registry_loaded if not _registry_loaded begin call load_message_classes end try begin retu...
def get_name(cls): """ Retrieve the schema name associated with a message class. Returns: str: The schema name. Raises: TypeError: If the message class isn't registered. Check your entry point for correctness. """ global _registry_loaded if not _registry_loaded:...
Python
jtatman_500k
comment Dark-Balck-Hat set Stop = false import smtplib set smtpserver = call SMTP string smtp.mail.yahoo.com 465 call ehlo call starttls
#Dark-Balck-Hat Stop = False import smtplib smtpserver = smtplib.SMTP("smtp.mail.yahoo.com",465) smtpserver.ehlo() smtpserver.starttls()
Python
zaydzuhri_stack_edu_python
function read object_id offset=0 begin set api = call init if offset > 1700 begin raise call ValueError string offset should be less than the limit of 1700 bytes end if not is instance object_id ObjectId begin raise call TypeError format string You need to provide an ObjectId you provided {0} object_id end set argtypes...
def read(object_id, offset=0): api = chip.init() if offset > 1700: raise ValueError("offset should be less than the limit of 1700 bytes") if not isinstance(object_id, ObjectId): raise TypeError("You need to provide an ObjectId you provided {0}".format(object_id)) api.exp_optiga_util_read_data.argtypes = c_us...
Python
nomic_cornstack_python_v1
function locations self locations begin set _locations = locations end function
def locations(self, locations): self._locations = locations
Python
nomic_cornstack_python_v1
from base_page import BasePage from locators import ItemPagesLocators class ProductPage extends BasePage begin function should_be_add_to_basket_button self begin assert call is_element_present *ItemPagesLocators.ADD_TO_BASKET_BUTTON msg string Add to basket button is not presented set add_to_basket_button = call find_e...
from .base_page import BasePage from .locators import ItemPagesLocators class ProductPage(BasePage): def should_be_add_to_basket_button(self): assert self.is_element_present(*ItemPagesLocators.ADD_TO_BASKET_BUTTON), "Add to basket button is not presented" self.add_to_basket_button = self.browser.f...
Python
zaydzuhri_stack_edu_python
function best_method self metro curr dest begin return min call metro_cost metro curr dest string cw call metro_cost metro curr dest string ccw tuple BIKING_COST 1 list string map bike locationId=%s % dest end function
def best_method(self, metro, curr, dest): return min( self.metro_cost(metro, curr, dest, 'cw'), self.metro_cost(metro, curr, dest, 'ccw'), (self.BIKING_COST, 1, ['map bike locationId=%s' % dest]) )
Python
nomic_cornstack_python_v1
function __init__ self X K=none k=none gamma=0.001 **kwargs begin if string distance in kwargs begin set distance = kwargs at string distance pop kwargs string distance none warn string If using kmeans, euclidean distance will be used. end else begin set distance = string euclidean end set C = K comment should have eno...
def __init__(self,X, K = None, k = None, gamma = 1e-3, **kwargs): if 'distance' in kwargs: distance = kwargs['distance'] kwargs.pop('distance',None) warnings.warn('If using kmeans, euclidean distance will be used.') else: distance = 'euclid...
Python
nomic_cornstack_python_v1
function gamma_function a exponent=1 negative_number_handling=string Indeterminate begin set a = call as_float_array a set exponent = call as_float_array exponent set negative_number_handling = call validate_method negative_number_handling tuple string Indeterminate string Mirror string Preserve string Clamp string "{0...
def gamma_function( a: ArrayLike, exponent: ArrayLike = 1, negative_number_handling: Literal[ "Clamp", "Indeterminate", "Mirror", "Preserve" ] | str = "Indeterminate", ) -> NDArrayFloat: a = as_float_array(a) exponent = as_float_array(exponent) negative_number_handling = validat...
Python
nomic_cornstack_python_v1
import pymongo from pymongo import MongoClient , errors function store_student_info info begin set client = call MongoClient set db = StudInfo insert db info close client end function function get_student_info id=0 begin set student_info = list set client = call MongoClient set db = StudInfo print id if id != 0 begin ...
import pymongo from pymongo import MongoClient, errors def store_student_info(info): client = MongoClient() db = client.StudentDB.StudInfo db.insert(info) client.close() def get_student_info(id=0): student_info = [] client = MongoClient() db = client.StudentDB.StudInfo print(id) ...
Python
zaydzuhri_stack_edu_python
function adjusted_classes pred_prob threshold begin return list comprehension if expression y >= threshold then 1 else 0 for y in pred_prob end function
def adjusted_classes(pred_prob, threshold): return [1 if y >= threshold else 0 for y in pred_prob]
Python
nomic_cornstack_python_v1
function is_db_view db_table begin if db_table in postgresql_views begin return true end return false end function
def is_db_view(db_table): if db_table in postgresql_views: return True return False
Python
nomic_cornstack_python_v1
comment MHZ19B.py comment DM1CR Nov 14, 2020 comment Class for CO2 Sensor comment for micropython on a ESP32 set MHZ19B_CMD_READCO2 = bytes list 255 1 134 0 0 0 0 0 121 class MHZ19B begin function __init__ self uart=none begin set _uart = uart set _d = bytes 9 set _checksum = 0 set CO2 = 0 if uart is none begin raise c...
# MHZ19B.py # DM1CR Nov 14, 2020 # Class for CO2 Sensor # for micropython on a ESP32 # MHZ19B_CMD_READCO2 = bytes([0xFF,0x01,0x86,0,0,0,0,0,0x79]) class MHZ19B: def __init__(self, uart=None): self._uart = uart self._d = bytes(9) self._checksum = 0 self.CO2 = 0 if uart ...
Python
zaydzuhri_stack_edu_python
function evaluate self rmrs data=none begin comment Initialize the outcome dictionary set outcome = dict if id begin set outcome at string id = id end if description begin set outcome at string description = description end if rmr_context begin set outcome at string rmr_context = rmr_context end comment context will b...
def evaluate(self, rmrs, data = None): # Initialize the outcome dictionary outcome = {} if self.id: outcome['id'] = self.id if self.description: outcome['description'] = self.description if self.rmr_context: outcome['rmr_context'] = self.rmr_c...
Python
nomic_cornstack_python_v1
function get_default_config self begin set config = call get_default_config update config dict string server string 127.0.0.1 ; string topic_exchange string diamond ; string vhost string / ; string user string guest ; string password string guest ; string port string 5672 return config end function
def get_default_config(self): config = super(rmqHandler, self).get_default_config() config.update({ 'server': '127.0.0.1', 'topic_exchange': 'diamond', 'vhost': '/', 'user': 'guest', 'password': 'guest', 'port': '5672', ...
Python
nomic_cornstack_python_v1
import numpy import sklearn print string Finished imports. class FeedForwardNeuralNetwork begin comment member variables comment size - 2 is the number of hidden variables, set shape = list end class comment shape[0] is number of inputs, shape[n] is number of neurons in layer n
import numpy import sklearn print("Finished imports.") class FeedForwardNeuralNetwork(): #member variables shape = [] #size - 2 is the number of hidden variables, #shape[0] is number of inputs, shape[n] is number of neurons in layer n
Python
zaydzuhri_stack_edu_python
function _evaluate_map self opa oha opb ohb begin set amap = zeros tuple call lena dtype=int64 set bmap = zeros tuple call lenb dtype=int64 set apmask = call reverse_integer_index opa set ahmask = call reverse_integer_index oha set bpmask = call reverse_integer_index opb set bhmask = call reverse_integer_index ohb if u...
def _evaluate_map(self, opa: List[int], oha: List[int], opb: List[int], ohb: List[int]): amap = numpy.zeros((self.lena(),), dtype=numpy.int64) bmap = numpy.zeros((self.lenb(),), dtype=numpy.int64) apmask = reverse_integer_index(opa) ahmask = reverse_integer_index(oh...
Python
nomic_cornstack_python_v1
import sys import argparse from bill_share import BillShare from rich.console import Console from table.html_table import HtmlTable from table.rich_table import RichTable function run item_file payer1_share_percent is_html begin set items = call get_items item_file set bill_share = call create_bill_share items set paye...
import sys import argparse from bill_share import BillShare from rich.console import Console from table.html_table import HtmlTable from table.rich_table import RichTable def run(item_file, payer1_share_percent, is_html): items = get_items(item_file) bill_share = create_bill_share(items) payer1_amount =...
Python
zaydzuhri_stack_edu_python
function approx_sign x begin function grad dy begin set abs_x = absolute x set zeros = zeros like dy set mask = call less_equal abs_x 1.0 return where mask 1 - abs_x * 2 * dy zeros end function return tuple call sign x grad end function
def approx_sign(x): def grad(dy): abs_x = tf.math.abs(x) zeros = tf.zeros_like(dy) mask = tf.math.less_equal(abs_x, 1.0) return tf.where(mask, (1 - abs_x) * 2 * dy, zeros) return math.sign(x), grad
Python
nomic_cornstack_python_v1
function release self begin set end function
def release(self): self._thread_shutdown.set()
Python
nomic_cornstack_python_v1
function testD_SquaredAlgo self begin set testJobGroup = call createTestJobGroup nJobs=nJobs set config = call getConfig set plugins = dict string Processing string SquaredAlgo call section_ string SquaredAlgo call section_ string Processing set coolOffTime = dict string create 10 ; string submit 10 ; string job 10 set...
def testD_SquaredAlgo(self): testJobGroup = self.createTestJobGroup(nJobs=self.nJobs) config = self.getConfig() config.RetryManager.plugins = {'Processing': 'SquaredAlgo'} config.RetryManager.section_("SquaredAlgo") config.RetryManager.SquaredAlgo.section_("Processing") ...
Python
nomic_cornstack_python_v1
function find_field schema field_name begin for field in schema begin if field at string name == field_name begin return field end end end function
def find_field(schema, field_name): for field in schema: if field['name'] == field_name: return field
Python
nomic_cornstack_python_v1
function solution self begin set num = num set solution_file = join path EULER_DATA string solutions.txt set solution_line = call getline solution_file num try begin set answer = strip split solution_line string . at 1 end except IndexError begin set answer = none end if answer begin return answer end else begin set ms...
def solution(self): num = self.num solution_file = os.path.join(EULER_DATA, 'solutions.txt') solution_line = linecache.getline(solution_file, num) try: answer = solution_line.split('. ')[1].strip() except IndexError: answer = None if answer: ...
Python
nomic_cornstack_python_v1
function evaluate self begin raise call NotImplementedError string This needs implemented end function
def evaluate(self): raise NotImplementedError("This needs implemented")
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Copyright (C) 2014 walker li <walker8088@gmail.com> This program 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 ...
# -*- coding: utf-8 -*- ''' Copyright (C) 2014 walker li <walker8088@gmail.com> This program 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 versio...
Python
zaydzuhri_stack_edu_python
function update_state state action begin set cartpole = call CartPole call set_state state set tuple _ done = call take_action action comment if the last action takes it out of range, REPEAT comment This could use more attention to make sure behavior is desirable... if done begin print string Warning: action took state...
def update_state(state, action): cartpole = CartPole() cartpole.set_state(state) _, done = cartpole.take_action(action) # if the last action takes it out of range, REPEAT # This could use more attention to make sure behavior is desirable... if done: print ("Warning: action took state ou...
Python
nomic_cornstack_python_v1
function xyz self begin if not _xyz_ begin set convert = 0 comment if self.unit() != 'g': #### need calibration numbers for flight units comment convert = 1 comment if self.unit() == 'volts': comment mx = my = mz = 1.0/3.89791388 comment bx = by = bz = 0 comment else: # must be counts comment if self.gain() == 1.0: com...
def xyz(self): if not self._xyz_: convert = 0 ## if self.unit() != 'g': #### need calibration numbers for flight units ## convert = 1 ## if self.unit() == 'volts': ## mx = my = mz = 1.0/3.89...
Python
nomic_cornstack_python_v1
function to_str self begin return call pformat call to_dict end function
def to_str(self): return pprint.pformat(self.to_dict())
Python
nomic_cornstack_python_v1
comment noqa: E501 function __init__ self component=none version=none dependencies=none begin set openapi_types = dict string component str ; string version str ; string dependencies List at GridDependencies set attribute_map = dict string component string component ; string version string version ; string dependencies...
def __init__(self, component=None, version=None, dependencies=None): # noqa: E501 self.openapi_types = { "component": str, "version": str, "dependencies": List[GridDependencies], } self.attribute_map = { "component": "component", "ver...
Python
nomic_cornstack_python_v1
function comma_choice_list cls string begin string Convert a comma separated string to `CommaChoiceListArgs`. set items = split string string , set items = call CommaChoiceListArgs list comprehension strip item for item in items return items end function
def comma_choice_list(cls, string): '''Convert a comma separated string to `CommaChoiceListArgs`.''' items = string.split(',') items = CommaChoiceListArgs([item.strip() for item in items]) return items
Python
jtatman_500k
comment Strings in python are surrounded by either single or double quotation marks. Let's look at string formatting and some string methods set name = string Cam set age = 29 comment Concatenate print string Hello, my name is + name comment String Formatting comment String Methods
# Strings in python are surrounded by either single or double quotation marks. Let's look at string formatting and some string methods name = 'Cam' age = 29 # Concatenate print('Hello, my name is ' + name) # String Formatting # String Methods
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Thu Sep 15 00:24:32 2016 @author: yyc import pandas as pd from sklearn import neighbors from sklearn.cross_validation import cross_val_score string Use KNN to test cancer prediction accuracy with different range of k function KNN X y begin co...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Sep 15 00:24:32 2016 @author: yyc """ import pandas as pd from sklearn import neighbors from sklearn.cross_validation import cross_val_score """ Use KNN to test cancer prediction accuracy with different range of k """ def KNN(X, y): # Try differ...
Python
zaydzuhri_stack_edu_python
import random set Dicth = string 1234567890!@#$%^&*()_+-=abcdefghijklmnopqrstuvwxyz set Pass_Temp = list set Pass_Exam = string comment def Password_Length(): comment P_Length = int(input()) comment retrun P_Length comment def Password_Come(P_temp): comment exam = [] comment for i in range(P_temp): comment exam.appen...
import random Dicth="1234567890!@#$%^&*()_+-=abcdefghijklmnopqrstuvwxyz" Pass_Temp = [] Pass_Exam = '' # def Password_Length(): # P_Length = int(input()) # retrun P_Length # def Password_Come(P_temp): # exam = [] # for i in range(P_temp): # exam.append(random.choice(Dicth)) # retrun exam ...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Tue Dec 8 10:56:39 2015 @author: winstroth import numpy as np import matplotlib.pyplot as plt from scipy import interpolate import airfoiltools as aft set num_vec = 150 comment Load airfoil coordinates set airf_coord = call loadtxt string ../airfoils/du_91-w2-250.dat usec...
# -*- coding: utf-8 -*- """ Created on Tue Dec 8 10:56:39 2015 @author: winstroth """ import numpy as np import matplotlib.pyplot as plt from scipy import interpolate import airfoiltools as aft num_vec = 150 # Load airfoil coordinates airf_coord = np.loadtxt('../airfoils/du_91-w2-250.dat', ...
Python
zaydzuhri_stack_edu_python
function Cancel self request global_params=none begin set config = call GetMethodConfig string Cancel return call _RunMethod config request global_params=global_params end function
def Cancel(self, request, global_params=None): config = self.GetMethodConfig('Cancel') return self._RunMethod( config, request, global_params=global_params)
Python
nomic_cornstack_python_v1
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import csv import time import copy from re import sub from decimal import De...
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import csv import time import copy from re import sub from decimal import D...
Python
zaydzuhri_stack_edu_python
function _second_scale_update self value begin set string %02d % integer floor decimal value set number_key_mode = MODE_NONE end function
def _second_scale_update(self, value): self._second_var.set('%02d' % int(math.floor(float(value)))) self.number_key_mode = MODE_NONE
Python
nomic_cornstack_python_v1
from tkinter import * class Main begin function resultado self begin set dtb = integer get B set dta = integer get A set dtc = integer get C comment CONTA set p = dtb * dtb set v = 4 * dta * dtc if dtc < 0 begin set v = 4 * dta * - dtc end else if dta < 0 begin set v = 4 * - dta * dtc end else if dta and dtc < 0 begin ...
from tkinter import * class Main: def resultado(self): dtb = int(self.B.get()) dta = int(self.A.get()) dtc = int(self.C.get()) #CONTA p = dtb * dtb v = (4 * dta * dtc) if dtc < 0: v = (4 * dta * (-dtc)) ...
Python
zaydzuhri_stack_edu_python
comment basic skeleton code for viewing and adding functionality to windows created using QtDesigner5 comment prints to the screen when the pushbutton is clicked. comment Source for skeleton: https://www.learnpyqt.com/courses/qt-creator/embed-pyqtgraph-custom-widgets-qt-app/ comment Source for integrating functionality...
# basic skeleton code for viewing and adding functionality to windows created using QtDesigner5 # prints to the screen when the pushbutton is clicked. # Source for skeleton: https://www.learnpyqt.com/courses/qt-creator/embed-pyqtgraph-custom-widgets-qt-app/ # Source for integrating functionality into the layout: https...
Python
zaydzuhri_stack_edu_python
class NumArray begin function __init__ self nums begin set arr = list nums at 0 for i in range 1 length nums begin append arr arr at i - 1 + nums at i end end function function sumRange self left right begin if left == 0 begin return arr at right end return arr at right - arr at left - 1 end function end class comment ...
class NumArray: def __init__(self, nums: List[int]): self.arr = [nums[0]] for i in range(1, len(nums)): self.arr.append(self.arr[i-1]+nums[i]) def sumRange(self, left: int, right: int) -> int: if left == 0: return self.arr[right] return self.arr[right] -...
Python
zaydzuhri_stack_edu_python
set a = integer input string select the starting meter set b = integer input string enter your ending meter print string 1.auto,2.car,3.cab,4.bmw set d = integer input string enter your name set c = a - b if a >= 0 begin if d == 1 begin set c = c * 8 end else if d == 2 begin set c = c * 10 end else if d == 3 begin set ...
a=int(input("select the starting meter ")) b=int(input("enter your ending meter ")) print("1.auto,2.car,3.cab,4.bmw") d=int(input("enter your name")) c=a-b if(a>=0): if(d==1): c=c*8 elif(d==2): c=c*10 elif(d==3): c=c*11 elif(d==4): c=c*12 else: print("enter the option") ...
Python
zaydzuhri_stack_edu_python
import numpy as np import vec_spaces from preprocessing import read_processed_data , DataLoader comment self import import random function test_newsgroup_similarity mat id_to_newsgroups sim_func=compute_cosine_similarity begin string Arguments --------- mat: `np.ndarray` (V, D) Each column is "newsgroup" vector. id_to_...
import numpy as np import vec_spaces from preprocessing import read_processed_data, DataLoader #self import import random def test_newsgroup_similarity( mat, id_to_newsgroups, sim_func=vec_spaces.compute_cosine_similarity ): """ Arguments --------- mat: `np.ndarray` (V, D) Each c...
Python
zaydzuhri_stack_edu_python
comment Imports from strategies.quotes_class import Quote , Quotes import math comment Functions function refresh_quotes conn begin comment Checks wether quotes are in place, updates them if needed set ALPHA_TOLERANCE = 2 set ALPHA_INDEX = - 0.3 set BETA_TOLERANCE = 2 set BETA_INDEX = - 0.1 set GAMMA_TOLERANCE = 10 set...
# Imports from strategies.quotes_class import Quote, Quotes import math # Functions def refresh_quotes(conn): # Checks wether quotes are in place, updates them if needed ALPHA_TOLERANCE = 2 ALPHA_INDEX = - 0.3 BETA_TOLERANCE = 2 BETA_INDEX = -0.1 GAMMA_TOLERANCE = 10 GAMMA_INDEX = 0.0 ...
Python
zaydzuhri_stack_edu_python
function find_highest_point self begin if get tags string kind none == string box begin comment Boxes get special treatment. We ignore their sides. set highest_point = position end else begin set highest_point = max call iter_salient_points key=lambda p -> z default=none end if highest_point is none begin return none e...
def find_highest_point(self) -> Optional[Point]: if self.tags.get('kind', None) == 'box': # Boxes get special treatment. We ignore their sides. highest_point = self.position else: highest_point = max(self.shape.iter_salient_points(), key=lambda p: p.z, default=None) ...
Python
nomic_cornstack_python_v1
from collections import Counter set S = 0 with open string ./two_cities_ascii.txt as f begin set c = counter for line in f begin comment Counting the times each character Appears set c = c + counter line end end set c = dictionary c for i in c begin comment Summing all characters set S = S + c at i end comment Calculat...
from collections import Counter S = 0 with open("./two_cities_ascii.txt") as f: c = Counter() for line in f: c += Counter(line) # Counting the times each character Appears c = dict(c) for i in c: S = S+c[i] # Summing all characters c.update((x, round(y/S * 100)) for x, y in c.items(...
Python
zaydzuhri_stack_edu_python
function getGrades self student begin comment return copy of student's grades try begin comment return a copy, not the original so it can't be messed up return grades at call getIdNum at slice : : end except KeyError begin raise call ValueError string Student no in grade book end end function
def getGrades(self, student): try: #return copy of student's grades return self.grades[student.getIdNum()][:] #return a copy, not the original so it can't be messed up except KeyError: raise ValueError('Student no in grade book')
Python
nomic_cornstack_python_v1
function date self begin return call Date year month day end function
def date(self) -> Date: return Date(self.year, self.month, self.day)
Python
nomic_cornstack_python_v1
function test_getitem self begin set rp = call Reverse_Primer string AAGTCCG 0 assert true rp at 3 == string T end function
def test_getitem(self): rp = Reverse_Primer("AAGTCCG", 0) self.assertTrue(rp[3] == "T")
Python
nomic_cornstack_python_v1
from random import randint , random , uniform from MyGraph import Graph class Ant begin function __init__ self distanceGraph colony q0 begin comment colonia are: comment - matricea feromonului depus de furnici comment - metrica de distanta(inversul ei pentru a fi maxim) comment - coef. alpha si beta(A,B) set colony = c...
from random import randint,random,uniform from MyGraph import Graph class Ant: def __init__(self, distanceGraph:Graph, colony, q0): #colonia are: # - matricea feromonului depus de furnici # - metrica de distanta(inversul ei pentru a fi maxim) # - coef. alpha si beta(A,B) se...
Python
zaydzuhri_stack_edu_python
import torch import numpy as np import torch.nn as nn import torch.nn.functional as F from torch_geometric.nn import GCNConv , GATConv class Simple_GNN extends Module begin function __init__ self num_node_features hidden_size=10 begin call __init__ set conv1 = call GATConv num_node_features hidden_size set conv2 = call...
import torch import numpy as np import torch.nn as nn import torch.nn.functional as F from torch_geometric.nn import GCNConv, GATConv class Simple_GNN(torch.nn.Module): def __init__(self, num_node_features,hidden_size=10): super(Simple_GNN, self).__init__() self.conv1 = GATConv(num_node_features...
Python
zaydzuhri_stack_edu_python
function summon_cursor self begin set cursor = call cursor end function
def summon_cursor(self): self.cursor = self.connection.cursor()
Python
nomic_cornstack_python_v1
comment input from user height and weight comment calculating BMI comment bmi = (weight/(height*height))*10000 comment bmi <= 18.5 , Underweight comment bmi between 18.5 and 24.9 , Normal weight comment bmi between 25 and 29.9 , Overweight comment bmi 30 or more , Obesity
# input from user height and weight # calculating BMI # bmi = (weight/(height*height))*10000 # bmi <= 18.5 , Underweight # bmi between 18.5 and 24.9 , Normal weight # bmi between 25 and 29.9 , Overweight # bmi 30 or more , Obesity
Python
zaydzuhri_stack_edu_python
class A begin function keys self begin return tuple end function end class function a begin set x = 5 function b begin return x end function exec __code__ end function function c d begin pass end function try begin exec string 5 dict 5 assert false msg 0 end except TypeError begin try begin exec string 5 call A asser...
class A: def keys(self): return () def a(): x = 5 def b(): return x exec(b.__code__) def c(d): pass try: exec("5", {}, 5) assert False, 0 except TypeError: try: exec("5", A()) assert False, 1 except TypeError: try: a() assert False, 2 except TypeError: try: ...
Python
zaydzuhri_stack_edu_python
import sys comment Take input from stdin for string in stdin begin comment Check if input string contains any zeroes if string 0 in string begin print string Sorry, the inputs contained a zero end else begin comment Turn input into two separate string variables set answers = split string comment Reverse the two foremos...
import sys #Take input from stdin for string in sys.stdin: #Check if input string contains any zeroes if "0" in string: print("Sorry, the inputs contained a zero") else: #Turn input into two separate string variables answers = string.split() #Reverse the two foremost string...
Python
zaydzuhri_stack_edu_python
from __future__ import division import numpy from numpy import * comment import matplotlib.pyplot as plt import evaluation function predict train_dataSet train_labels test_dataSet test_labels w b begin string Predict training and test set set train_sample_num = length train_labels set train_feature_num = length train_d...
from __future__ import division import numpy from numpy import * #import matplotlib.pyplot as plt import evaluation def predict(train_dataSet, train_labels, test_dataSet, test_labels, w, b): """ Predict training and test set """ train_sample_num = len(train_labels) train_feature_num = len(train_dataSet[0]...
Python
zaydzuhri_stack_edu_python
comment class to solve the pricing problem for the multicommodity flow comment column generation framework import networkx as nx from copy import deepcopy class PricingSolver begin function __init__ self graph constraints findConstraints numberOfCommodities begin set graph = graph call __set_sources_sinks numberOfCommo...
# class to solve the pricing problem for the multicommodity flow # column generation framework import networkx as nx from copy import deepcopy class PricingSolver: def __init__(self,graph, constraints,findConstraints,numberOfCommodities): self.graph = graph self.__set_sources_sinks(numberOfCommodities) self....
Python
zaydzuhri_stack_edu_python
function calling_points self begin return _calling_points end function
def calling_points(self): return self._calling_points
Python
nomic_cornstack_python_v1
import face_recognition class FaceRecognitionModel begin set __DEFAULT_FACE_LABEL = string Unknown function __init__ self known_face_labels known_face_encodings begin set __known_face_labels = known_face_labels set __known_face_encodings = known_face_encodings end function function predictFaceLabel self image face_loca...
import face_recognition class FaceRecognitionModel: __DEFAULT_FACE_LABEL = "Unknown" def __init__(self, known_face_labels, known_face_encodings): self.__known_face_labels = known_face_labels self.__known_face_encodings = known_face_encodings def predictFaceLabel(self, image, face_locatio...
Python
zaydzuhri_stack_edu_python
function stop self begin info string Stopping Agatsuma... for extension in extensions begin call on_core_stop self end call _stop end function
def stop(self): self.logger.core.info("Stopping Agatsuma...") for extension in self.extensions: extension.on_core_stop(self) self._stop()
Python
nomic_cornstack_python_v1
function add_prefix self state_dict prefix begin print format string add prefix '{}' prefix comment 去除带有prefix的名字 set f = lambda x -> x + prefix return dictionary comprehension f dist key : value for tuple key value in items state_dict end function
def add_prefix(self, state_dict, prefix): print('add prefix \'{}\''.format(prefix)) f = lambda x: x + prefix # 去除带有prefix的名字 return {f(key): value for key, value in state_dict.items()}
Python
nomic_cornstack_python_v1
import random set HP_BASE = 100 set SP_BASE = 100 set MP_BASE = 100 set SPEED_BASE = 100 set INITIATIVE_BASE = 100 set ATTRIBUTES = list string name string status string klass string race class unit begin function __init__ self **feature begin set heals_point = HP_BASE set stamina_point = SP_BASE set mana_point = MP_BA...
import random HP_BASE = 100 SP_BASE = 100 MP_BASE = 100 SPEED_BASE = 100 INITIATIVE_BASE = 100 ATTRIBUTES = ['name', 'status', 'klass', 'race'] class unit(): def __init__(self, **feature): self.heals_point = HP_BASE self.stamina_point = SP_BASE self.mana_point = MP_BASE self.speed ...
Python
zaydzuhri_stack_edu_python
comment Accepts a large number and a small number. Then it tells the greatest range between prime numbers. set l = integer input string Enter lower limit : set h = integer input string Enter higher limit : comment Accepting values set c = 0 set pn = list set asc = list for i in range l h + 1 begin for j in range 1 i ...
#Accepts a large number and a small number. Then it tells the greatest range between prime numbers. l=int(input("Enter lower limit : ")) h=int(input("Enter higher limit :")) #Accepting values c=0 pn=[] asc=[] for i in range(l,h+1): for j in range(1,i+1): if i%j==0: c+=1 if c==2: ...
Python
zaydzuhri_stack_edu_python
comment Generates a properly signed URL for opening a twitter stream via curl comment To use, at the command prompt (or in bash) comment URL=$(python twitter_curl_url_builder.py) comment curl -get "$URL" import oauth2 as oauth import time comment Set the API endpoint set url = string https://stream.twitter.com/1.1/stat...
# Generates a properly signed URL for opening a twitter stream via curl # # To use, at the command prompt (or in bash) # URL=$(python twitter_curl_url_builder.py) # curl -get "$URL" # import oauth2 as oauth import time # Set the API endpoint url = 'https://stream.twitter.com/1.1/statuses/sample.json' # Set th...
Python
zaydzuhri_stack_edu_python
import collections import pandas as pd from pyalgotrade import plotter from pyalgotrade import strategy from pyalgotrade import technical from pyalgotrade.barfeed import yahoofeed from pyalgotrade.broker import backtesting from pyalgotrade.stratanalyzer import drawdown from pyalgotrade.stratanalyzer import returns from...
import collections import pandas as pd from pyalgotrade import plotter from pyalgotrade import strategy from pyalgotrade import technical from pyalgotrade.barfeed import yahoofeed from pyalgotrade.broker import backtesting from pyalgotrade.stratanalyzer import drawdown from pyalgotrade.stratanalyzer import re...
Python
zaydzuhri_stack_edu_python
comment encoding : utf-8 comment @File : Utilities.py comment @Author : AllenWoo comment @Date : 2018/1/30 9:01 comment @license : Copyright(C), all right reserved. comment @Contact : http://github.com/junbujianwpl comment @Desc : common utilities import os function get_file_size fname begin return get size path fname ...
# encoding : utf-8 # @File : Utilities.py # @Author : AllenWoo # @Date : 2018/1/30 9:01 # @license : Copyright(C), all right reserved. # @Contact : http://github.com/junbujianwpl # @Desc : common utilities import os def get_file_size(fname): return os.path.getsize(fname) def rename_file(old_name, ne...
Python
zaydzuhri_stack_edu_python
function directMessage self data who header=none begin set sentCount = 0 debug string broadcast - + string data + string - + string who comment Add newline if needed if data at - 1 != string begin set data = data + string end comment toDo: this should be a name search, instead of a number from 'who' if call isNum who...
def directMessage(self, data, who, header=None): sentCount = 0 logger.debug("broadcast - " + str(data) + " - " + str(who)) if data[-1] != "\n": # Add newline if needed data += "\n" # toDo: this should be a name search, instead of a number from 'who' if self.isNum(w...
Python
nomic_cornstack_python_v1
comment https://www.interviewbit.com/problems/prettyprint/ class Solution begin comment @param A : integer comment @return a list of list of integers function prettyPrint self A begin set cache = dict set center = A - 1 for i in range 2 * A - 1 begin for j in range 2 * A - 1 begin set cache at tuple i j = max absolute...
# https://www.interviewbit.com/problems/prettyprint/ class Solution: # @param A : integer # @return a list of list of integers def prettyPrint(self, A): cache = {} center = A - 1 for i in range(2*A - 1): for j in range(2*A - 1): cache[(i, j)] = max(abs(i-...
Python
zaydzuhri_stack_edu_python
function get_Plot self title=none text=none width=10 get_plt=false begin set width = width figure figsize=tuple width 10 set pTitle = if expression title is not none then string Diarization Performance on %s % title else string Diarization Performance call suptitle pTitle comment plot reference subplot 211 call plot_an...
def get_Plot(self, title=None, text=None, width=10, get_plt=False): notebook.width = width plt.figure(figsize=(notebook.width, 10)) pTitle = ('Diarization Performance on %s' % title) if title is not None else 'Diarization Performance' plt.suptitle(pTitle) # plot referen...
Python
nomic_cornstack_python_v1
import sys set input = readline set tuple n k = map int split input set graph = list comprehension list 0 * n for _ in range n for _ in range k begin set tuple a b = map int split input set graph at a - 1 at b - 1 = 1 end function floyd graph begin for x in range n begin for a in range n begin for b in range n begin if...
import sys input = sys.stdin.readline n, k = map(int, input().split()) graph = [[0]*n for _ in range(n)] for _ in range(k): a, b = map(int, input().split()) graph[a-1][b-1] = 1 def floyd(graph): for x in range(n): for a in range(n): for b in range(n): if graph[a][x] and graph[x][b]: ...
Python
zaydzuhri_stack_edu_python
function col x *number begin for y in number begin set x = x * y end return x end function print call col 5 6 7 8
def col(x,*number): for y in number: x=x*y return x print(col(5,6,7,8))
Python
zaydzuhri_stack_edu_python
comment if and elif comment zmienne set age = 17 set isDrunk = false set isRestrictedArea = false comment to jest trudne do zrozumienia, zagnieżdżona instrukcja warunkowa, ale można łatwiej if age < 18 begin print string za młody na alko end else if isDrunk begin print string jestes pijany? nie moge Ci sprzedac alkohol...
#if and elif #zmienne age = 17 isDrunk = False isRestrictedArea = False #to jest trudne do zrozumienia, zagnieżdżona instrukcja warunkowa, ale można łatwiej if age < 18: print('za młody na alko') else: if isDrunk: print('jestes pijany? nie moge Ci sprzedac alkoholu') else: if isRestrictedA...
Python
zaydzuhri_stack_edu_python
import torch import torch.nn.functional as F class KeypointEncoder extends object begin function encode self keypoints input_size stride hm_alpha hm_sigma begin string For each image, create heatmaps and visibility masks. For 224*224 image and 14 * 3 kps and 2 stride, return 112*112*14 heatmap Args: keypoints (tensor):...
import torch import torch.nn.functional as F class KeypointEncoder(object): def encode(self, keypoints, input_size, stride, hm_alpha, hm_sigma): ''' For each image, create heatmaps and visibility masks. For 224*224 image and 14 * 3 kps and 2 stride, return 112*112*14 heatmap ...
Python
zaydzuhri_stack_edu_python
class Solution begin function minSubArrayLen self s nums begin set res = decimal string inf set j = 0 set curr = 0 for tuple i c in enumerate nums begin set curr = curr + c while curr >= s begin set res = min res i - j + 1 set curr = curr - nums at j set j = j + 1 end end return if expression res < decimal string inf t...
class Solution: def minSubArrayLen(self, s: int, nums: List[int]) -> int: res = float('inf') j = 0 curr = 0 for i, c in enumerate(nums): curr += c while curr >= s: res = min(res, i - j + 1) curr -= nums[j] ...
Python
zaydzuhri_stack_edu_python
function f filename begin comment Note: this encoding could be wrong! set f = open filename string r encoding=string latin1 set all_data = read f close f print string all_data is all_data string comment just for fun return all_data at slice 42 : 43 : end function
def f(filename): f = open(filename,"r",encoding="latin1") # Note: this encoding could be wrong! all_data = f.read() f.close() print("\n\nall_data is", all_data, "\n\n") return all_data[42:43] # just for fun
Python
nomic_cornstack_python_v1
comment Exemplo basico socket (lado ativo) import socket comment maquina onde esta o par passivo set HOST = string localhost comment porta que o par passivo esta escutando set PORTA = 5000 comment cria socket comment default: socket.AF_INET, socket.SOCK_STREAM set sock = call socket comment conecta-se com o par passivo...
# Exemplo basico socket (lado ativo) import socket HOST = 'localhost' # maquina onde esta o par passivo PORTA = 5000 # porta que o par passivo esta escutando # cria socket sock = socket.socket() # default: socket.AF_INET, socket.SOCK_STREAM # conecta-se com o par passivo sock.connect((HOST, PORTA)) #faz a...
Python
zaydzuhri_stack_edu_python
function getParent self begin return parent end function
def getParent(self): return self.parent
Python
nomic_cornstack_python_v1
import msvcrt comment init keymap set keymap = dict tuple 8 none string backspace ; tuple 13 none string enter ; tuple 27 none string esc update keymap dictionary comprehension tuple i none : character i for i in range 32 127 update keymap dict tuple 224 72 string up ; tuple 224 80 string down ; tuple 224 75 string lef...
import msvcrt #init keymap keymap = {(8,None):'backspace',(13,None):'enter',(27,None):'esc'} keymap.update({(i,None):chr(i) for i in range(32,127)}) keymap.update({(224,72):'up',(224,80):'down',(224,75):'left',(224,77):'right'}) #end init,start function def keyboard(debug=False): ch = ord(msvcrt.getch()) ...
Python
zaydzuhri_stack_edu_python
comment coding=gbk import better_exceptions call hook import numpy as np import matplotlib.pyplot as plt set rcParams at string font.sans-serif = string SimHei set rcParams at string axes.unicode_minus = false set samples = call normal size=1000 set bins = array range - 4 5 set histogram = call histogram samples bins=b...
# coding=gbk import better_exceptions better_exceptions.hook() import numpy as np import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = 'SimHei' plt.rcParams['axes.unicode_minus'] = False samples = np.random.normal(size=1000) bins = np.arange(-4, 5) histogram = np.histogram(samples, bins=bins, normed=T...
Python
zaydzuhri_stack_edu_python
function parse_cores core_str begin set num_cores = cpu count set cores = list comment remove spaces replace core_str string string comment check if not a range if string - not in core_str begin set cores = list map int split strip core_str string , end else begin comment parse range e.g. 2-8 set core_str = split str...
def parse_cores(core_str): num_cores = os.cpu_count() cores = [] # remove spaces core_str.replace(" ", "") # check if not a range if '-' not in core_str: cores = list(map(int, core_str.strip().split(','))) else: # parse range e.g. 2-8 core_str = core_str.strip().spl...
Python
nomic_cornstack_python_v1
function get_by_id value id begin if value is none begin return none end for val in value begin if string id in keys val and val at string id == id begin return val end end return none end function
def get_by_id(value, id): if value is None: return None for val in value: if 'id' in val.keys() and val['id'] == id: return val return None
Python
nomic_cornstack_python_v1
function handle_extensions extensions=tuple string html begin set ext_list = list for ext in extensions begin extend ext_list split replace ext string string string , end for tuple i ext in enumerate ext_list begin if not starts with ext string . begin set ext_list at i = string .%s % ext_list at i end end comment we...
def handle_extensions(extensions=('html',)): ext_list = [] for ext in extensions: ext_list.extend(ext.replace(' ','').split(',')) for i, ext in enumerate(ext_list): if not ext.startswith('.'): ext_list[i] = '.%s' % ext_list[i] # we don't want *.py files here because ...
Python
nomic_cornstack_python_v1
function print_level self node depth begin if not node begin return end if depth == 1 begin set print_count = print_count + 1 print point print_count end else if depth > 1 begin call print_level left depth - 1 call print_level right depth - 1 end end function
def print_level(self, node, depth): if not node: return if depth == 1: self.print_count += 1 print(node.point, self.print_count) elif depth > 1: self.print_level(node.left, depth - 1) self.print_level(node.right, depth - 1)
Python
nomic_cornstack_python_v1
comment /usr/bin/env python3 comment 生成器函数(含有yield关键字) comment yield和return关键字不能同时存在 function generator begin print 1 set a = 123 yield string a print 2 end function set g = call generator comment print(g.__next__()) print next g
#/usr/bin/env python3 #生成器函数(含有yield关键字) #yield和return关键字不能同时存在 def generator(): print(1) a = 123 yield 'a' print(2) g = generator() #print(g.__next__()) print(next(g))
Python
zaydzuhri_stack_edu_python
function offset self begin if string offset in self begin return self at string offset end else begin return none end end function
def offset(self): if 'offset' in self: return self['offset'] else: return None
Python
nomic_cornstack_python_v1
class Stack begin function __init__ self begin set abi = list end function function is_empty self begin return abi == list end function function push self data begin append abi data end function function pop self begin return pop abi end function end class set pri = stack set barathi = input string for char in barath...
class Stack: def __init__(self): self.abi = [] def is_empty(self): return self.abi == [] def push(self, data): self.abi.append(data) def pop(self): return self.abi.pop() pri= Stack() barathi = input(' ') for char in barathi: pri.push(char) rev_text = '' while not pr...
Python
zaydzuhri_stack_edu_python
import os import re class CPSO4FF begin function getSOList self begin set pattern = compile string (\S+)\s=>\snot found set out = popen string ldd ffmpeg for line in out begin set find = search line if not find begin continue end set soName = call groups at 0 set findStr = string find . -name " + soName + string " end ...
import os import re class CPSO4FF: def getSOList(self): pattern = re.compile('(\S+)\s=>\snot found') out = os.popen('ldd ffmpeg') for line in out: find = pattern.search(line) if not find: continue soName = find.groups()[0] fin...
Python
zaydzuhri_stack_edu_python
function unpack_state state begin return reshape np state tuple shape at 0 1 end function
def unpack_state(state): return np.reshape(state, (state.shape[0], 1))
Python
nomic_cornstack_python_v1
comment [스택/큐 5번]탑 function solution heights begin set answer = list set index = 1 for i in heights begin set receive = heights at slice : index - 1 : reverse receive comment print(index,"번째 탑에서 송신,탑 높이: ",i,"수신 탑 높이list :",receive) if index == 1 begin append answer 0 end else begin set count = index for j in receiv...
# [스택/큐 5번]탑 def solution(heights): answer = [] index = 1 for i in heights: receive = heights[:index - 1] receive.reverse() # print(index,"번째 탑에서 송신,탑 높이: ",i,"수신 탑 높이list :",receive) if index == 1: answer.append(0) else: count = index ...
Python
zaydzuhri_stack_edu_python
import numpy as np import torch import random set dtype = float set device = device string cpu comment Times to run set epoch = 10000 comment There are 2 inputs set inputLayerSize = 2 comment NN nodes set hiddenLayerSize = 3 comment Only one output set outputLayerSize = 1 comment Learning rate set L = 0.1 comment There...
import numpy as np import torch import random dtype = torch.float device = torch.device('cpu') # Times to run epoch = 10000 # There are 2 inputs inputLayerSize = 2 # NN nodes hiddenLayerSize = 3 # Only one output outputLayerSize = 1 # Learning rate L = 0.1 # There are 2 inputs for XOR X = torch.tensor([[0, 0], [...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment Filename: calculateScore.py import os function calcScore fname score begin set f = call file string data/ + fname + string /final_result.txt set fw = call file string data/ + fname + string /score.txt string w while true begin set line = read line f if length line == 0 begin break end s...
#!/usr/bin/python # Filename: calculateScore.py import os def calcScore(fname,score): f = file("data/"+fname+"/final_result.txt") fw = file("data/"+fname+"/score.txt",'w') while True: line = f.readline() if len(line) == 0: break colonPos = line.find(":") startPos = line.find("[") endPos = line.fi...
Python
zaydzuhri_stack_edu_python
function load self filename **kwargs begin string Load stream and tag information from a file. set filename = filename try begin set tags = call _IFFID3 filename keyword kwargs end except ID3Error begin set tags = none end try begin set fileobj = open filename string rb set info = call AIFFInfo fileobj end finally begi...
def load(self, filename, **kwargs): """Load stream and tag information from a file.""" self.filename = filename try: self.tags = _IFFID3(filename, **kwargs) except ID3Error: self.tags = None try: fileobj = open(filename, "rb") sel...
Python
jtatman_500k
function to_path value begin set tokens = call to_path_tokens value if is instance tokens list begin set path = list comprehension if expression is instance token PathToken then key else token for token in call to_path_tokens value end else begin set path = list tokens end return path end function
def to_path(value): tokens = to_path_tokens(value) if isinstance(tokens, list): path = [token.key if isinstance(token, PathToken) else token for token in to_path_tokens(value)] else: path = [tokens] return path
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Sat Sep 11 21:00:38 2021 @author: Yang-Bin Fan import pandas as pd comment To make sure the first row is not thought of as the heading set dataset = read csv string ./Market_Basket_Optimisation.csv header=none shape comment Transforming the list into a list of lists, so t...
# -*- coding: utf-8 -*- """ Created on Sat Sep 11 21:00:38 2021 @author: Yang-Bin Fan """ import pandas as pd dataset = pd.read_csv('./Market_Basket_Optimisation.csv', header = None) #To make sure the first row is not thought of as the heading dataset.shape #Transforming the list into a list of lists, so that each...
Python
zaydzuhri_stack_edu_python
function calc_fs_int x R Z begin set R1 = R at tuple slice : : slice : - 1 : set R2 = call roll R at tuple slice : : slice : - 1 : - 1 axis=1 set Z1 = Z at tuple slice : : slice : - 1 : set Z2 = call roll Z at tuple slice : : slice : - 1 : - 1 axis=1 set x1 = x at tuple slice : : slice : - 1 : ...
def calc_fs_int(x, R, Z): R1 = R[:, :-1] R2 = np.roll(R[:, :-1], -1, axis=1) Z1 = Z[:, :-1] Z2 = np.roll(Z[:, :-1], -1, axis=1) x1 = x[:, :-1] x2 = np.roll(x[:, :-1], -1, axis=1) dl = np.sqrt((R2 - R1) ** 2 + (Z2 - Z1) ** 2) R_av = (R1 + R2)/2 dA = dl * (2 * pi * R_av) x_av =...
Python
nomic_cornstack_python_v1