code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function rebin_data_log x y f y_err=none dx=none begin set dx_init = call apply_function_if_none dx diff np x median set x = call asarray x set y = call asarray y set y_err = call asarray call apply_function_if_none y_err y zeros_like if shape at 0 != shape at 0 begin raise call ValueError string x and y must be of the...
def rebin_data_log(x, y, f, y_err=None, dx=None): dx_init = apply_function_if_none(dx, np.diff(x), np.median) x = np.asarray(x) y = np.asarray(y) y_err = np.asarray(apply_function_if_none(y_err, y, np.zeros_like)) if x.shape[0] != y.shape[0]: raise ValueError("x and y must be of the same l...
Python
nomic_cornstack_python_v1
comment I don't think this works at all -__-... This is a mix of a few codes i found online becuase I am trying to figure out sqlalchemy still (githubs cited at the bottom) from flask import Flask , render_template , redirect , jsonify comment dependencies import sqlalchemy from sqlalchemy.ext.automap import automap_ba...
###I don't think this works at all -__-... This is a mix of a few codes i found online becuase I am trying to figure out sqlalchemy still (githubs cited at the bottom) from flask import Flask, render_template, redirect, jsonify # dependencies import sqlalchemy from sqlalchemy.ext.automap import automap_base from sql...
Python
zaydzuhri_stack_edu_python
string CSci5512 Spring'12 Homework 4 login: sharm163@umn.edu date: 4/30/2012 name: Mohit Sharma id: 4465482 algorithm: dtree4 from Example import Example , Attribute from TreeNode import TreeNode import math import sys comment check if all examples have same class function checkIfSameClass examples begin set firstLabel...
""" CSci5512 Spring'12 Homework 4 login: sharm163@umn.edu date: 4/30/2012 name: Mohit Sharma id: 4465482 algorithm: dtree4 """ from Example import Example, Attribute from TreeNode import TreeNode import math import sys #check if all examples have same class def checkIfSameClass(examples): firstL...
Python
zaydzuhri_stack_edu_python
from list import * function testCreate begin global resp comment xml = List('Markham temp list', 'Wouldn\'t it be lovely?') set xml = list string Markham temp list end function
from list import * def testCreate(): global resp #xml = List('Markham temp list', 'Wouldn\'t it be lovely?') xml = List('Markham temp list')
Python
zaydzuhri_stack_edu_python
import cec import speech_recognition as sr set TURN_TV_ON = string turn tv on set TURN_TV_OFF = string turn tv off set CLOSE_PROGRAM = string close program function main begin comment Create cec control call init comment Ceate speech recognizer object set r = call Recognizer comment Create infinite loop while true begi...
import cec import speech_recognition as sr TURN_TV_ON = "turn tv on" TURN_TV_OFF = "turn tv off" CLOSE_PROGRAM = "close program" def main(): # Create cec control cec.init() # Ceate speech recognizer object r = sr.Recognizer() # Create infinite loop while True: # Record sound ...
Python
zaydzuhri_stack_edu_python
function bbox self begin set abbox = call empty for normsubpath in normsubpaths begin set abbox = abbox + call bbox end return abbox end function
def bbox(self): abbox = bboxmodule.empty() for normsubpath in self.normsubpaths: abbox += normsubpath.bbox() return abbox
Python
nomic_cornstack_python_v1
function rotate self begin call command string rotate SERVICE_NAME end function
def rotate(self): Wrapper.command("rotate", self.SERVICE_NAME)
Python
nomic_cornstack_python_v1
function euclides a b begin string Calcula o mdc(a,b), com a,b naturais e b>0, pelo algoritmo de Euclides set tuple dividendo divisor = tuple a b comment resto da divisao de dividendo por divisor set resto = dividendo % divisor comment print(dividendo, divisor, resto) while resto != 0 begin set tuple dividendo divisor ...
def euclides(a, b): """Calcula o mdc(a,b), com a,b naturais e b>0, pelo algoritmo de Euclides""" dividendo, divisor = a, b resto = dividendo % divisor # resto da divisao de dividendo por divisor #print(dividendo, divisor, resto) while resto != 0: dividendo, divisor = divisor, resto resto = dividendo ...
Python
zaydzuhri_stack_edu_python
for i in range 1 n + 1 begin for j in a begin if i - match at j < 0 begin continue end if dp at i - match at j == - 1 begin continue end set dp at i = max dp at i dp at i - match at j * 10 + j end end comment print(dp) print dp at n
for i in range(1,n+1): for j in a: if i - match[j] < 0: continue if dp[i-match[j]] == -1: continue dp[i] = max(dp[i], dp[i-match[j]]*10+j) # print(dp) print(dp[n])
Python
zaydzuhri_stack_edu_python
function calculate_visibility qv qc qr qi qs T p begin set Rd = 287.0 set COEFLC = 144.7 set COEFLP = 2.24 set COEFFC = 327.8 set COEFFP = 10.36 set EXPLC = 0.88 set EXPLP = 0.75 set EXPFC = 1.0 set EXPFP = 0.7776 comment Virtual temperature set Tv = T * 1 + 0.61 * qv comment Air density [kg m^-3] set rhoa = p / Rd * T...
def calculate_visibility(qv,qc,qr,qi,qs,T,p): Rd = 287. COEFLC = 144.7 COEFLP = 2.24 COEFFC = 327.8 COEFFP = 10.36 EXPLC = 0.88 EXPLP = 0.75 EXPFC = 1. EXPFP = 0.7776 Tv = T * (1+0.61*qv) # Virtual temperature rhoa = p/(Rd*Tv) # Air density [kg m^-3] rhow = 1e3 ...
Python
nomic_cornstack_python_v1
import xml.dom.pulldom as pulldom comment from http://code.google.com/p/py-dom-xpath/ import xpath import wikitextparser as wtp import re import pickle from collections import defaultdict import nltk set x = 0 set NLWIKI_FILE = string data/nlwiki-latest-pages-articles.xml set sep_list = list string is een string is de ...
import xml.dom.pulldom as pulldom import xpath # from http://code.google.com/p/py-dom-xpath/ import wikitextparser as wtp import re import pickle from collections import defaultdict import nltk x=0 NLWIKI_FILE = 'data/nlwiki-latest-pages-articles.xml' sep_list = ["is een", "is de", "was een", "was de", "waren een", "...
Python
zaydzuhri_stack_edu_python
class Utility begin decorator staticmethod function sort_together to_sort other begin set sorted_to_sort = sorted to_sort set sorted_other = list comprehension x for tuple _ x in sorted zip to_sort other return tuple sorted_to_sort sorted_other end function end class
class Utility(): @staticmethod def sort_together(to_sort, other): sorted_to_sort = sorted(to_sort) sorted_other = [x for _,x in sorted(zip(to_sort, other))] return sorted_to_sort, sorted_other
Python
zaydzuhri_stack_edu_python
comment 두 개의 문자열 str1과 str2가 주어진다. 문자열 str2 안에 str1과 일치하는 부분이 있는지 찾는 프로그램을 만드시오. comment 예를 들어 두 개의 문자열이 다음과 같이 주어질 때, 첫 문자열이 두번째에 존재하면 1, 존재하지 않으면 0을 출력한다. comment ABC comment ZZZZZABCZZZZZ comment 두번째 문자열에 첫번째 문자열과 일치하는 부분이 있으므로 1을 출력. comment ABC comment ZZZZAZBCZZZZZ comment 문자열이 일치하지 않으므로 0을 출력. comment [입력] comme...
# 두 개의 문자열 str1과 str2가 주어진다. 문자열 str2 안에 str1과 일치하는 부분이 있는지 찾는 프로그램을 만드시오. # 예를 들어 두 개의 문자열이 다음과 같이 주어질 때, 첫 문자열이 두번째에 존재하면 1, 존재하지 않으면 0을 출력한다. # ABC # ZZZZZABCZZZZZ # 두번째 문자열에 첫번째 문자열과 일치하는 부분이 있으므로 1을 출력. # ABC # ZZZZAZBCZZZZZ # 문자열이 일치하지 않으므로 0을 출력. # [입력] # 첫 줄에 테스트 케이스 개수 T가 주어진다. (1≤T≤50) # 다음 줄부터 ...
Python
zaydzuhri_stack_edu_python
import os from matplotlib.image import imread import numpy as np class PreProcessing begin set images_train = array list set images_test = array list set labels_train = array list set labels_test = array list set unique_train_label = array list set map_train_label_indices = dictionary function __init__ self data_src da...
import os from matplotlib.image import imread import numpy as np class PreProcessing: images_train = np.array([]) images_test = np.array([]) labels_train = np.array([]) labels_test = np.array([]) unique_train_label = np.array([]) map_train_label_indices = dict() def __init__(self,data_sr...
Python
zaydzuhri_stack_edu_python
import pandas as pd import numpy as np from sklearn.feature_extraction.text import CountVectorizer from sklearn.model_selection import train_test_split from sklearn.naive_bayes import MultinomialNB set data = read csv string reviews.csv set texts = data at string Text set labels = data at string Label comment Create a ...
import pandas as pd import numpy as np from sklearn.feature_extraction.text import CountVectorizer from sklearn.model_selection import train_test_split from sklearn.naive_bayes import MultinomialNB data = pd.read_csv("reviews.csv") texts = data['Text'] labels = data['Label'] # Create a vectorizer and expand the rev...
Python
iamtarun_python_18k_alpaca
import requests from bs4 import BeautifulSoup comment 방법 1 comment webpage = requests.get("https://www.hanbit.co.kr/store/books/full_book_list.html") comment # print(webpage.text) comment soup = BeautifulSoup(webpage.content, "html.parser") comment # print(soup) comment for a in soup.find_all('a'): comment print(a.get(...
import requests from bs4 import BeautifulSoup # 방법 1 # webpage = requests.get("https://www.hanbit.co.kr/store/books/full_book_list.html") # # print(webpage.text) # soup = BeautifulSoup(webpage.content, "html.parser") # # print(soup) # for a in soup.find_all('a'): # print(a.get('href'), a.text) # # 방법 2 // 문제발생 # #...
Python
zaydzuhri_stack_edu_python
function UpdateCalendarSessionToken request begin set redirect_path = reverse urlresolvers StoreCalendarSessionToken return call UpdateCalendarSessionToken request redirect_path end function
def UpdateCalendarSessionToken(request): redirect_path = urlresolvers.reverse(StoreCalendarSessionToken) return views_impl.UpdateCalendarSessionToken(request, redirect_path)
Python
nomic_cornstack_python_v1
function order x begin set L = length x set rangeL = range L set z = call izip x rangeL comment avoid problems with duplicates. set z = call izip z rangeL set D = sorted z return list comprehension d at 1 for d in D end function
def order(x): L = len(x) rangeL = range(L) z = izip(x, rangeL) z = izip(z, rangeL) # avoid problems with duplicates. D = sorted(z) return [d[1] for d in D]
Python
nomic_cornstack_python_v1
function layout_waveguide cell layer points_list width smooth=false begin set dbu = dbu set dpolygon = call waveguide_dpolygon points_list width dbu smooth=smooth compress true call layout cell layer return dpolygon end function
def layout_waveguide(cell, layer, points_list, width, smooth=False): dbu = cell.layout().dbu dpolygon = waveguide_dpolygon(points_list, width, dbu, smooth=smooth) dpolygon.compress(True) dpolygon.layout(cell, layer) return dpolygon
Python
nomic_cornstack_python_v1
function audio d sr=none ext=string .mp3 begin if nussl_available begin if type d is AudioSignal begin set sr = sample_rate set d = audio_data end else if sr is none begin raise call ValueError string Sample rate must be provided when d is not an AudioSignal object! end end set tmp_wav = named temporary file mode=strin...
def audio(d, sr=None, ext = '.mp3'): if nussl_available: if type(d) is AudioSignal: sr = d.sample_rate d = d.audio_data elif sr is None: raise ValueError('Sample rate must be provided when d is not an AudioSignal object!') tmp_wav = NamedTemporaryFile(mode='w...
Python
nomic_cornstack_python_v1
function push list x begin append list x end function function pop list begin set x = list at - 1 del list at - 1 return x end function set list = list call push list 1
def push(list,x): list.append(x) def pop(list): x=list[-1] del list[-1] return x list=[] push(list,1)
Python
zaydzuhri_stack_edu_python
function get_sample_name self begin if have_metadata is false begin call _get_metadata set have_metadata = true end end function
def get_sample_name(self): if self.have_metadata is False: self._get_metadata() self.have_metadata = True
Python
nomic_cornstack_python_v1
function from_service_account_info cls info *args **kwargs begin comment type: ignore return call __func__ AdaptationAsyncClient info *args keyword kwargs end function
def from_service_account_info(cls, info: dict, *args, **kwargs): return AdaptationClient.from_service_account_info.__func__(AdaptationAsyncClient, info, *args, **kwargs) # type: ignore
Python
nomic_cornstack_python_v1
for contador in range 0 length listagem begin if contador % 2 == 0 begin print string { listagem at contador } end=string end if contador % 2 == 1 begin print string R$ { listagem at contador } end end print string =- * 22
for contador in range(0, len(listagem)): if contador % 2 == 0: print(f'{listagem[contador]:.<28}', end='') if contador % 2 == 1: print(f'R$ {listagem[contador]:>7.2f}') print('=-'*22)
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Fri Dec 27 08:41:39 2019 @author: Osheen comment Chapter 6 ################## print string 6.1 set information = dict string first_name string neha ; string last_name string mishra ; string city string dubai print information print information at string first_name print i...
# -*- coding: utf-8 -*- """ Created on Fri Dec 27 08:41:39 2019 @author: Osheen """ ############Chapter 6 ################## print("6.1") information ={'first_name' : 'neha', 'last_name': 'mishra' , 'city' : 'dubai'} print(information) print(information['first_name']) print(information['last_name']) print(informatio...
Python
zaydzuhri_stack_edu_python
function __init__ __self__ field_mappings begin set __self__ string field_mappings field_mappings end function
def __init__(__self__, *, field_mappings: Sequence['outputs.RelationshipTypeFieldMappingResponse']): pulumi.set(__self__, "field_mappings", field_mappings)
Python
nomic_cornstack_python_v1
function setup_ax ax=none wcs=none begin if not ax begin set fig = figure if wcs is not none begin set ax = call add_subplot 111 projection=get attribute wcs string low_level_wcs wcs end else begin set ax = call add_subplot 111 end end return ax end function
def setup_ax(ax=None, wcs=None): if not ax: fig = plt.figure() if wcs is not None: ax = fig.add_subplot(111, projection=getattr(wcs, "low_level_wcs", wcs)) else: ax = fig.add_subplot(111) return ax
Python
nomic_cornstack_python_v1
function one_stack_port_up self dpid dp_name port begin call set_port_up port dpid wait=false call wait_for_stack_port_status dpid dp_name port 3 end function
def one_stack_port_up(self, dpid, dp_name, port): self.set_port_up(port, dpid, wait=False) self.wait_for_stack_port_status(dpid, dp_name, port, 3)
Python
nomic_cornstack_python_v1
for i in range 1 11 begin print string 4 x i string = 4 * i end
for i in range(1, 11): print("4 x", i, "=", 4*i)
Python
jtatman_500k
function linear_activation_forward_test_case begin seed 2 set A_prev = randn 3 2 set W = randn 1 3 set b = randn 1 1 return tuple A_prev W b end function
def linear_activation_forward_test_case(): np.random.seed(2) A_prev = np.random.randn(3,2) W = np.random.randn(1,3) b = np.random.randn(1,1) return A_prev, W, b
Python
nomic_cornstack_python_v1
from itertools import product import time set start = time function pattern n begin set l = list comprehension x for x in string n at slice : : 2 if all generator expression integer l at x - 1 == x for x in range 1 10 begin return true end return false end function comment sqrt(19293949596979899) set start = 13890266...
from itertools import product import time start = time.time() def pattern(n): l = [x for x in str(n)][::2] if all(int(l[x-1]) == x for x in range(1,10)): return True return False start = 138902663 # sqrt(19293949596979899) while not pattern(start**2): start -= 1 elapsed = time.time() - s...
Python
zaydzuhri_stack_edu_python
comment first_session_only_tensorflow.py import tensorflow as tf set x = call constant 1 name=string x set y = call Variable x + 9 name=string y comment model = tf.initialize_all_variables() set model = call global_variables_initializer with call Session as session begin comment session.extend would be used to extend e...
#first_session_only_tensorflow.py import tensorflow as tf x = tf.constant(1, name='x') y = tf.Variable(x + 9, name='y') # model = tf.initialize_all_variables() model =tf.global_variables_initializer() with tf.Session() as session: # session.extend would be used to extend execution graph wihle calculating # ...
Python
zaydzuhri_stack_edu_python
function fromstring text schema=none begin if schema begin set parser = call makeparser schema=schema return call fromstring text parser=parser end else begin return call fromstring text end end function
def fromstring(text, schema=None): if schema: parser = objectify.makeparser(schema=schema.schema) return objectify.fromstring(text, parser=parser) else: return objectify.fromstring(text)
Python
nomic_cornstack_python_v1
function _upload_post self begin comment Fetch the user's identifier from the request, which comment contains the oauth2 creds. try begin set token = headers at string X-IDTOKEN end except Exception as e begin return call Response string Missing credential token header 405 end try begin set idinfo = call verify_id_toke...
def _upload_post(self): # Fetch the user's identifier from the request, which # contains the oauth2 creds. try: token = flask.request.headers['X-IDTOKEN'] except Exception as e: return flask.Response('Missing credential token header', 405) try: ...
Python
nomic_cornstack_python_v1
string Last edited: Vivien Tsao 9/19/18 import pickle as pkl import numpy as np import os set root = strip get current directory string itin_gen string SHARED CLASSES string This sets up all the classes used by the final model(s). comment user_preferences = pkl.load(open('austin.pkl', 'rb')) set start = string St. Regi...
'''Last edited: Vivien Tsao 9/19/18''' import pickle as pkl import numpy as np import os root=os.getcwd().strip('itin_gen') '''SHARED CLASSES''' '''This sets up all the classes used by the final model(s).''' # user_preferences = pkl.load(open('austin.pkl', 'rb')) start = 'St. Regis' stop = 'Hotel Vitale' '''Trave...
Python
zaydzuhri_stack_edu_python
comment entrada de dados set numero = integer input string Digite um valor: comment Verifica se o valor inserido pode ser calculado while numero == 0 or numero < 1 begin print string valor incorreto! set numero = integer input string Digite um valor: end comment Processamento de impressao for n in range 11 begin print ...
#entrada de dados numero = int(input("Digite um valor: ")) #Verifica se o valor inserido pode ser calculado while(numero == 0 or numero < 1): print("valor incorreto!") numero = int(input("Digite um valor: ")) #Processamento de impressao for n in range(11): print(numero," X ",n," = ",numero *...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import requests import re import subprocess set HOST = string 2018shell3.picoctf.com set PORT = string 52168 set USERNAME = string random_user set PASSWORD = string make_up_some_crap comment Sometimes the requests return some invalid crap and the code doesn't know how to deal with it commen...
#!/usr/bin/env python import requests import re import subprocess HOST = "2018shell3.picoctf.com" PORT = "52168" USERNAME = 'random_user' PASSWORD = 'make_up_some_crap' # Sometimes the requests return some invalid crap and the code doesn't know how to deal with it # So the requests just retry until they succeed... ...
Python
zaydzuhri_stack_edu_python
comment Video Refrence:- https://www.youtube.com/watch?v=FsAPt_9Bf3U string #revision of closure and function def outer_function(msg): message = msg def inner_function(): print(message) return inner_function hi_func = outer_function('hi') my_func = outer_function('bye') hi_func() my_func() string # Decorator :- A decor...
#Video Refrence:- https://www.youtube.com/watch?v=FsAPt_9Bf3U ''' #revision of closure and function def outer_function(msg): message = msg def inner_function(): print(message) return inner_function hi_func = outer_function('hi') my_func = outer_function('bye') hi_func() my_func() ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment python executables import yaml import json from array import * from Tkinter import * function func value begin print value end function set root = call Tk set options = list string 1 string 2 string 3 set var = call StringVar set drop = call OptionMenu root var *options command=func cal...
#!/usr/bin/python # python executables import yaml import json from array import * from Tkinter import * def func(value): print(value) root = Tk() options = ["1", "2", "3"] var = StringVar() drop = OptionMenu(root, var, *options, command=func) drop.place(x=10, y=10) #import networkx as nx #G = nx.Graph() b=...
Python
zaydzuhri_stack_edu_python
async function set_lock self resource lock_identifier lock_timeout begin string Lock this instance and set lock expiration time to lock_timeout :param resource: redis key to set :param lock_identifier: uniquie id of lock :param lock_timeout: timeout for lock in seconds :raises: LockError if lock is not acquired set loc...
async def set_lock(self, resource, lock_identifier, lock_timeout): """ Lock this instance and set lock expiration time to lock_timeout :param resource: redis key to set :param lock_identifier: uniquie id of lock :param lock_timeout: timeout for lock in seconds :raises: Lo...
Python
jtatman_500k
from tkinter import * import math comment ---------------------------- CONSTANTS ------------------------------- # set PINK = string #e2979c set RED = string #e7305b set GREEN = string #9bdeac set YELLOW = string #f7f5dd set FONT_NAME = string Courier set WORK_MIN = 25 set SHORT_BREAK_MIN = 5 set LONG_BREAK_MIN = 20 se...
from tkinter import * import math # ---------------------------- CONSTANTS ------------------------------- # PINK = "#e2979c" RED = "#e7305b" GREEN = "#9bdeac" YELLOW = "#f7f5dd" FONT_NAME = "Courier" WORK_MIN = 25 SHORT_BREAK_MIN = 5 LONG_BREAK_MIN = 20 REPS = 0 TIMER = None # ---------------------------- TIMER RES...
Python
zaydzuhri_stack_edu_python
import os import csv import threading import webbrowser import subprocess import time import signal from texttable import Texttable set filename = string interface/cap.csv set url = string http://localhost:3000 set install_cmd = string cd interface && npm install set command = string cd interface && npm run start funct...
import os import csv import threading import webbrowser import subprocess import time import signal from texttable import Texttable filename = "interface/cap.csv" url = "http://localhost:3000" install_cmd = "cd interface && npm install" command = "cd interface && npm run start" def clearFile(): fd = open(filename...
Python
zaydzuhri_stack_edu_python
function update_port_dhcp_opts self port_id dhcp_options token=none begin set port_req_body = dict string port dict string extra_dhcp_opts dhcp_options try begin call update_port port_id port_req_body end except NeutronClientException begin exception call _LE string Failed to update Neutron port %s. port_id raise call ...
def update_port_dhcp_opts(self, port_id, dhcp_options, token=None): port_req_body = {'port': {'extra_dhcp_opts': dhcp_options}} try: _build_client(token).update_port(port_id, port_req_body) except neutron_client_exc.NeutronClientException: LOG.exception(_LE("Failed to upd...
Python
nomic_cornstack_python_v1
function nanmae pred target begin set cnt = sum dtype=dtype set mae = call nansum absolute pred - target dim=- 1 return sum / cnt end function
def nanmae( pred: Tensor, target: Tensor) -> Tensor: cnt = torch.any(torch.isfinite(target), dim=-1).sum(dtype=target.dtype) mae = torch.nansum(torch.abs(pred-target), dim=-1) return mae.sum() / cnt
Python
nomic_cornstack_python_v1
function __init__ self outer_diameter=- 1 wall_thickness=- 1 material=string default begin set _diameter_outer = outer_diameter set _wall_thickness = wall_thickness set _material_name = material set _materials = call Materials set _coatings_material = string none set _coatings_thickness = 0.0 set _coatings_density = 0....
def __init__(self, outer_diameter=-1, wall_thickness=-1, material='default'): self._diameter_outer = outer_diameter self._wall_thickness = wall_thickness self._material_name = material # self._materials = Materials() # self._coatings_material = 'none' ...
Python
nomic_cornstack_python_v1
import html5lib import requests from bs4 import BeautifulSoup import csv import pandas as pd import copy import urllib print string Initializing... function connect host=string http://google.com begin try begin url open host return true end except any begin return false end end function comment test if call connect beg...
import html5lib import requests from bs4 import BeautifulSoup import csv import pandas as pd import copy import urllib print("Initializing...") def connect(host='http://google.com'): try: urllib.request.urlopen(host) return True except: return False # test if(connect()): print("Ne...
Python
zaydzuhri_stack_edu_python
function factorial n begin if n == 0 begin return 1 end else begin return n * call factorial n - 1 end end function set num = 5 print string The factorial of num string is call factorial num
def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) num = 5 print("The factorial of", num, "is", factorial(num))
Python
jtatman_500k
class Solution begin function subsets self nums begin string Example: Input: nums = [1,2,3] Output: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ] :type nums: List[int] :rtype: List[List[int]] We can view the problem of forming subsets as successively adding items to a list. Let's clarify. For a given n, there are...
class Solution: def subsets(self, nums): """ Example: Input: nums = [1,2,3] Output: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ] :type nums: List[int] :rtype: List[List[int]] We can view the problem of forming subsets a...
Python
zaydzuhri_stack_edu_python
while dreams begin set who_are_you = string Please enter your name: set name = input who_are_you set destination_promot = string { title name } , if you could visit only one place, where would you go? set destination = input destination_promot set dream_vacation at name = destination set repeat = input string Would som...
while dreams: who_are_you = 'Please enter your name: ' name = input(who_are_you) destination_promot = f'{name.title()}, if you could visit only one place, where would you go? ' destination = input(destination_promot) dream_vacation[name] = destination repeat = input("Would someone else like to...
Python
zaydzuhri_stack_edu_python
function generate_IMU_data path_root_IMU_data IMU_ID dict_all_data verbose=1 begin if verbose > 0 begin call printi string generate IMU data for IMU ID: + IMU_ID end set total_path = path_root_IMU_data + IMU_ID + string / set list_all_files = list directory total_path if string B in dict_all_data at IMU_ID begin pass e...
def generate_IMU_data(path_root_IMU_data, IMU_ID, dict_all_data, verbose=1): if verbose > 0: printi("generate IMU data for IMU ID: " + IMU_ID) total_path = path_root_IMU_data + IMU_ID + '/' list_all_files = os.listdir(total_path) if 'B' in dict_all_data[IMU_ID]: pass else: ...
Python
nomic_cornstack_python_v1
import unittest from gaphas.item import Line from gaphas.canvas import Canvas from gaphas import state set undo_list = list set redo_list = list function undo_handler event begin append undo_list event end function function undo begin set apply_me = list undo_list del undo_list at slice : : reverse apply_me for e ...
import unittest from gaphas.item import Line from gaphas.canvas import Canvas from gaphas import state undo_list = [] redo_list = [] def undo_handler(event): undo_list.append(event) def undo(): apply_me = list(undo_list) del undo_list[:] apply_me.reverse() for e in apply_me: ...
Python
zaydzuhri_stack_edu_python
string Для чисел, що вводяться користувачем, визначити відсоток додатних та від’ємних чисел. При введенні числа 0 закінчити роботу. set amountNumbers = 0 set negative = 0 set pozitive = 0 function check begin while true begin try begin set num = integer input string Input your number: return num end except any begin pr...
'''Для чисел, що вводяться користувачем, визначити відсоток додатних та від’ємних чисел. При введенні числа 0 закінчити роботу. ''' amountNumbers = 0 negative = 0 pozitive = 0 def check(): while True: try: num = int(input('Input your number: ')) return num exc...
Python
zaydzuhri_stack_edu_python
comment Найдите сумму 1+1/2+1/3+…+1/n. from fractions import Fraction set n = integer input string n: set summ = 0 set i = 1 while i <= n begin set summ = summ + call Fraction 1 i set i = i + 1 end print summ
#Найдите сумму 1+1/2+1/3+…+1/n. from fractions import Fraction n = int(input("n:")) summ = 0 i = 1 while i <= n: summ += Fraction(1, i) i+=1 print(summ)
Python
zaydzuhri_stack_edu_python
function find_path tree x begin if call label tree == x begin return list call label tree end for b in call branches tree begin set path = call find_path b x if path begin return list call label tree + path end end end function
def find_path(tree, x): if label(tree) == x: return [label(tree)] for b in branches(tree): path = find_path(b, x) if path: return [label(tree)] + path
Python
nomic_cornstack_python_v1
import math import sys set p = 14461 set p = 2161 set m = 17 set d = 8 function h x a b begin return x * a + b % p % m end function set cnt = 0 set same_cnt = 0 for b in range p begin for a in range p begin set same = call h 0 a b == call h 1 a b and call h 0 a b == call h d a b set collide = true set y = call h 0 a b ...
import math import sys p = 14461 p = 2161 m = 17 d = 8 def h(x, a, b): return (x * a + b) % p % m cnt = 0 same_cnt = 0 for b in range(p): for a in range(p): same = (h(0, a, b) == h(1, a, b) and h(0, a, b) == h(d, a, b)) collide = True y = h(0, a, b) for x in range(d + 1): ...
Python
zaydzuhri_stack_edu_python
function get_optimizer model args begin comment Define optimizers and loss function comment If you are using PyTorch 0.4.0 you need this weird filter comment https://github.com/pytorch/pytorch/issues/679 comment no longer needed in 1.0.0 if optim_type == string Adam begin set optimizer = adam parameters model lr=optim_...
def get_optimizer(model, args): # Define optimizers and loss function # If you are using PyTorch 0.4.0 you need this weird filter # https://github.com/pytorch/pytorch/issues/679 # no longer needed in 1.0.0 if args.optim_type == 'Adam': optimizer = torch.optim.Adam(model.parameters(), ...
Python
nomic_cornstack_python_v1
function index_rtypes self begin set metric = index_metric set out = dict for fnode in values nodes begin comment only consider outgoing relationships because looping over comment all object anyways, so will cover everything for tuple rtype dest in outgoing_relations begin set dnode = nodes at dest comment merge outgo...
def index_rtypes(self): metric = self.index_metric out = {} for fnode in self.nodes.values(): # only consider outgoing relationships because looping over # all object anyways, so will cover everything for (rtype, dest) in fnode.outgoing_relations: ...
Python
nomic_cornstack_python_v1
comment ! /usr/bin/env python3 comment import rospy import rospy comment import service message from std_srvs.srv import Empty , EmptyResponse comment import twist from geometry_msgs.msg import Twist comment definisikan fungsi my_callback function my_callback request begin comment menset loginfo "service bb8_move_in_ci...
#! /usr/bin/env python3 import rospy #import rospy from std_srvs.srv import Empty, EmptyResponse #import service message from geometry_msgs.msg import Twist #import twist def my_callback(request): #definisikan fungsi my_callback rospy.loginfo("service bb8_move_in_circle telah dipanggil") # menset loginfo "service...
Python
zaydzuhri_stack_edu_python
import io import tensorflow as tf import numpy as np set iris_train = list set iris_target = list set iris_target_dict = dict string setosa 0 ; string versicolor 1 ; string virginica 2 set iris = open string ./iris.csv set i = 0 for line in iris begin set tmp_ls = list comprehension 0 for i in range 4 set tmp_dict = ...
import io import tensorflow as tf import numpy as np iris_train = [] iris_target = [] iris_target_dict = {'setosa':0,'versicolor':1,'virginica':2} iris = io.open("./iris.csv") i = 0 for line in iris : tmp_ls = [0 for i in range(4)] tmp_dict = [0,0,0] line = line.replace("\n","") tmp_ls[0],tmp_ls[1],tm...
Python
zaydzuhri_stack_edu_python
function clearNextLayer self begin set nextLayer = list end function
def clearNextLayer(self): self.nextLayer = []
Python
nomic_cornstack_python_v1
string Created on 2017年4月6日 @author: test class goNews begin comment 验证图片是否显示,输入XPath,输出结果 function pPlayed self driver1 inputXpath begin set driver = driver1 set inputXpath1 = inputXpath set p1 = call find_element_by_xpath inputXpath1 assert call is_displayed return string 图片展示 Verified OK end function function quitPa...
''' Created on 2017年4月6日 @author: test ''' class goNews(): #验证图片是否显示,输入XPath,输出结果 def pPlayed(self,driver1,inputXpath): driver = driver1 inputXpath1=inputXpath p1 =driver.find_element_by_xpath(inputXpath1) assert p1.is_displayed() return (" 图片展示 Verified OK") def q...
Python
zaydzuhri_stack_edu_python
function override_serializer format_output dimension base_serializer_class begin if format_output == string geojson begin if dimension == string 3 begin class GeneratedGeo3DSerializer extends Base3DSerializer BaseGeoJSONSerializer base_serializer_class begin class Meta extends Meta Meta begin pass end class end class s...
def override_serializer(format_output, dimension, base_serializer_class): if format_output == 'geojson': if dimension == '3': class GeneratedGeo3DSerializer(Base3DSerializer, BaseGeoJSONSerializer, base_seriali...
Python
nomic_cornstack_python_v1
function neg_test self begin set z = linear space 0 1 100 set b = - linear 0 1 assert call allclose call b z - z end function
def neg_test(self): z = np.linspace(0, 1, 100) b = -ph.motion.Linear(0,1) assert(np.allclose(b(z),-z))
Python
nomic_cornstack_python_v1
import csv class Node begin function __init__ self *args begin set tuple Index CutPredictor CutPoint IsBranchNode NodeClass Parent ChildL ChildR = args at 0 set index = Index set cutPredictor = CutPredictor set cutPoint = decimal CutPoint set isBranch = IsBranchNode set nodeClass = if expression NodeClass == string 0 t...
import csv class Node(): def __init__(self, *args): Index,CutPredictor,CutPoint,IsBranchNode,NodeClass,Parent,ChildL,ChildR = args[0] self.index = Index self.cutPredictor = CutPredictor self.cutPoint = float(CutPoint) self.isBranch = IsBranchNode self.nodeClass = "N...
Python
zaydzuhri_stack_edu_python
function build_model self inputs begin info string start building model set tuple cls_outputs box_outputs = call build_model model_name inputs keyword model_config comment Write to tfevent for tensorboard. set train_writer = call FileWriter logdir call add_graph call get_default_graph flush train_writer set all_outputs...
def build_model(self, inputs: tf.Tensor) -> List[tf.Tensor]: logging.info('start building model') cls_outputs, box_outputs = inference.build_model( self.model_name, inputs, **self.model_config) # Write to tfevent for tensorboard. train_writer = tf.summary.FileWriter(self.logdir)...
Python
nomic_cornstack_python_v1
import types import typing import abc class Strategy begin function __init__ self name=string Strategy Example 0 func=none begin set name = name if func begin set execute = call MethodType func self end end function function execute self begin print name end function end class function execute_replacement1 self begin p...
import types import typing import abc class Strategy: def __init__(self, name='Strategy Example 0', func=None): self.name = name if func: self.execute = types.MethodType(func, self) def execute(self): print (self.name) def execute_replacement1(self): print(self.name...
Python
zaydzuhri_stack_edu_python
function fieldhelp2 self fieldid begin set txt = list set dd_desc = Globals at string ^DD at fileid at fieldid at 21 for tuple k v in call keys_with_decendants begin append txt value end return join string txt end function
def fieldhelp2(self, fieldid): txt = [] dd_desc = M.Globals["^DD"][self.fileid][fieldid][21] for k,v in dd_desc.keys_with_decendants(): txt.append(dd_desc[k][0].value) return '\n'.join(txt)
Python
nomic_cornstack_python_v1
import tensorflow as tf import os import pandas as pd from PIL import Image import dataset_util import sys if length argv == 2 begin set set = argv at 1 end else begin set set = string train end set output_record_path = format string ../data/{}.record set set images_path = format string ../data/{}/resized_images set se...
import tensorflow as tf import os import pandas as pd from PIL import Image import dataset_util import sys if len(sys.argv) == 2: set = sys.argv[1] else: set = 'train' output_record_path = '../data/{}.record'.format(set) images_path = '../data/{}/resized_images'.format(set) pdts_path = '../data/products.csv'...
Python
zaydzuhri_stack_edu_python
import pyflight import pickle from results_printer import print_results from secrets import API_KEY comment seting our QPX api key - from Google APIs console call set_api_key API_KEY comment pyflight.set_queries_per_day(50) comment define our trip comment slice is a one way route - from where - to where you want to fly...
import pyflight import pickle from results_printer import print_results from secrets import API_KEY # seting our QPX api key - from Google APIs console pyflight.set_api_key(API_KEY) # pyflight.set_queries_per_day(50) # define our trip # slice is a one way route - from where - to where you want to fly stage1 = pyfligh...
Python
zaydzuhri_stack_edu_python
function CreateFromDocument xml_text default_namespace=none location_base=none begin if XMLStyle_saxer != _XMLStyle begin set dom = call StringToDOM xml_text return call CreateFromDOM documentElement default_namespace=default_namespace end if default_namespace is none begin set default_namespace = call fallbackNamespac...
def CreateFromDocument (xml_text, default_namespace=None, location_base=None): if pyxb.XMLStyle_saxer != pyxb._XMLStyle: dom = pyxb.utils.domutils.StringToDOM(xml_text) return CreateFromDOM(dom.documentElement, default_namespace=default_namespace) if default_namespace is None: default_n...
Python
nomic_cornstack_python_v1
function __get_rule_items self law rules **kwargs begin info string Collecting report data for "%s" string law set items : List at RuleItem = list for rule in rules begin set items = items + tuple call __get_rule_item_from_rule law rule keyword kwargs end return items end function
def __get_rule_items( self, law: Law, rules: Iterable[Rule], **kwargs ) -> List[RuleItem]: logging.info('Collecting report data for "%s"', str(law)) items: List[RuleItem] = list() for rule in rules: items += (self.__get_rule_item_from_rule(law, rule, **kwargs),) ...
Python
nomic_cornstack_python_v1
function relationships self r_type=none n_ids=tuple begin if r_type is none begin set r_sets = list end else begin set r_sets = list get _relationships_by_type r_type call frozenset end if not n_ids or has attribute n_ids string __iter__ and all generator expression n_id is none for n_id in n_ids begin pass end else i...
def relationships(self, r_type=None, n_ids=()): if r_type is None: r_sets = [] else: r_sets = [self._relationships_by_type.get(r_type, frozenset())] if not n_ids or (hasattr(n_ids, "__iter__") and all(n_id is None for n_id in n_ids)): pass elif isinsta...
Python
nomic_cornstack_python_v1
function scrape_sport sport url favorite_list begin if not url begin return list end set matchups = list for favorite in favorite_list begin set matchups = matchups + call scrape_sport_favorite sport url favorite end return matchups end function
def scrape_sport(sport, url, favorite_list): if not url: return [] matchups = [] for favorite in favorite_list: matchups += scrape_sport_favorite(sport, url, favorite) return matchups
Python
nomic_cornstack_python_v1
string Created on wed Sept 26 9:32 2018 Author : Han Yue South East University Automation College, 211hna189 Nanjing China import numpy as np from poseevaluation.mpii import * import poseevaluation string metrics: 1.pcp(percentage of correct parts) 2.pckh(percentage of correct keypoints) string The canonical part stick...
''' Created on wed Sept 26 9:32 2018 Author : Han Yue South East University Automation College, 211hna189 Nanjing China ''' import numpy as np from poseevaluation.mpii import * import poseevaluation """ metrics: 1.pcp(percentage of correct parts) 2.pckh(percentage of correct keypoints) """ "...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python from __future__ import print_function import sys import traceback import signal import curses import atexit import life function main *args begin set std_scr = call initscr set iter_max = none global resizing set resizing = false function resize *args begin global resizing set resizing = tr...
#!/usr/bin/env python from __future__ import print_function import sys import traceback import signal import curses import atexit import life def main(*args): std_scr = curses.initscr() iter_max = None global resizing resizing = False def resize(*args): global resizing resizing = True ...
Python
zaydzuhri_stack_edu_python
function img_to_array_raw img data_format=string channels_last dtype=string float32 begin if data_format not in set literal string channels_first string channels_last begin raise call ValueError string Unknown data_format: %s % data_format end comment Numpy array x has format (height, width, channel) comment or (channe...
def img_to_array_raw(img, data_format='channels_last', dtype='float32'): if data_format not in {'channels_first', 'channels_last'}: raise ValueError('Unknown data_format: %s' % data_format) # Numpy array x has format (height, width, channel) # or (channel, height, width) # but original PIL image...
Python
nomic_cornstack_python_v1
class Point begin function __init__ self x y begin set x = x set y = y end function end class class Rectangle begin function __init__ self ux uy lx ly begin comment upper left(u) to lower right(l) set ux = ux set uy = uy set lx = lx set ly = ly end function function is_present self item begin comment the origin is at t...
class Point: def __init__(self,x,y): self.x=x self.y=y class Rectangle: def __init__(self,ux,uy,lx,ly): #upper left(u) to lower right(l) self.ux=ux self.uy=uy self.lx=lx self.ly=ly def is_present(self,item): #the origin is at the bottom left if (type(item)==Point): if (self.ux<=item.x<=self....
Python
zaydzuhri_stack_edu_python
function _represent self allele begin if is instance allele MouseAllele begin return string %s-%s%s%s % tuple organism locus upper supertype subtype end else begin return string %s-%s%s%s % tuple organism locus supertype subtype end end function
def _represent(self, allele): if isinstance(allele, MouseAllele): return "%s-%s%s%s" % (allele.organism, allele.locus, allele.supertype.upper(), allele.subtype) else: return "%s-%s%s%s" % (allele.organism, allele.locus, allele.supertype, allele.subtype)
Python
nomic_cornstack_python_v1
comment this returns a file object set f = open string pythonFile.txt string r comment read() method is for reading the content of the file print string The content of the file: read f comment close the file when you are finish with it close f
# this returns a file object f=open("pythonFile.txt","r") #read() method is for reading the content of the file print("The content of the file:",f.read()) #close the file when you are finish with it f.close()
Python
zaydzuhri_stack_edu_python
function enviar_contacto request begin set formulario = call ContactoForm if method == string POST begin set formulario = call ContactoForm POST if call is_valid begin set mail = call EmailMessage subject=string HPC Contacto from_email=cleaned_data at string email to=EMAIL_TO set body = string El usuario %s ha comentad...
def enviar_contacto(request): formulario = ContactoForm() if request.method == 'POST': formulario = ContactoForm(request.POST) if formulario.is_valid(): mail = EmailMessage(subject='HPC Contacto', from_email=formulario.cleaned_data['email'], ...
Python
nomic_cornstack_python_v1
comment FUNCTION function imprimir_matriz matriz begin set a = string for k in range 3 begin for j in range 3 begin comment print(m[k][j]) set a = a + string matriz at k at j + string end print a set a = string end end function function cambio_optimo cambio_total begin comment Array de monedas que tenemos que combin...
# FUNCTION def imprimir_matriz(matriz): a = "" for k in range(3): for j in range(3): # print(m[k][j]) a += str(matriz[k][j])+'\t' print(a) a = "" def cambio_optimo(cambio_total): # Array de monedas que tenemos que combinar posibles_monedas...
Python
zaydzuhri_stack_edu_python
comment Adds List Element as value of List. set List = list string Mathematics string chemistry 1997 2000 comment List.append(10087) insert List 2 1204 print List
# Adds List Element as value of List. List = ['Mathematics', 'chemistry', 1997, 2000] #List.append(10087) List.insert(2,1204) print(List)
Python
zaydzuhri_stack_edu_python
from collections import defaultdict import numpy as np function count_valid file begin string Counts number of valid passphrases in input file. Each passphrase (line) must not contain repeated words. Tests: ok: aa bb cc dd ee not ok: aa bb cc dd aa ok: aa bb cc dd aaa set count = 0 with open file string r as fin begin ...
from collections import defaultdict import numpy as np def count_valid(file): """ Counts number of valid passphrases in input file. Each passphrase (line) must not contain repeated words. Tests: ok: aa bb cc dd ee not ok: aa bb cc dd aa ok: aa bb cc dd aaa """ count = 0...
Python
zaydzuhri_stack_edu_python
function stationary_distribution self begin set Q = generator_matrix set n = shape at 0 set A = vertical stack tuple Q ones tuple 1 n set B = zeros tuple n + 1 1 set B at - 1 = 1 set stationary_distribution = call _solve_least_squares A B return stationary_distribution end function
def stationary_distribution(self): Q = self.generator_matrix n = Q.shape[0] A = np.vstack((Q, np.ones((1, n)))) B = np.zeros((n + 1, 1)) B[-1] = 1 stationary_distribution = _solve_least_squares(A, B) return stationary_distribution
Python
nomic_cornstack_python_v1
function plot_temp begin set work_book = call open_workbook string Temp.xls set sheet1 = call sheet_by_name string Temperature set time_x = call col_values 1 set temp_y = call col_values 0 title plt string Time x label string Time y label string Temperature plot time_x temp_y show end function
def plot_temp(): work_book = xlrd.open_workbook("Temp.xls") sheet1 = work_book.sheet_by_name("Temperature") time_x = sheet1.col_values(1) temp_y = sheet1.col_values(0) plt.title("Time") plt.xlabel("Time") plt.ylabel("Temperature") plt.plot(time_x, temp_y) plt.show()
Python
nomic_cornstack_python_v1
function move_forward self begin comment moves position forward in the doubly linked list if _curr is none begin raise call EmptyListError string Cannot move forward because the doubly linked list is empty end else if _curr == _tail or next is none begin raise call IndexError string Cannot go past the end of the doubly...
def move_forward(self): # moves position forward in the doubly linked list if self._curr is None: raise DoublyLinkedList.EmptyListError('Cannot move forward because the doubly linked list is empty') elif (self._curr == self._tail) or (self._curr.next is None): raise Index...
Python
nomic_cornstack_python_v1
function Run self args begin set impersonate_service_account = get impersonate_service_account if impersonate_service_account begin warning format string Impersonate service account '{}' is detected. This command cannot be used to print the access token for an impersonate account. The token below is still the applicati...
def Run(self, args): impersonate_service_account = ( properties.VALUES.auth.impersonate_service_account.Get()) if impersonate_service_account: log.warning( "Impersonate service account '{}' is detected. This command cannot be" ' used to print the access token for an impersonate...
Python
nomic_cornstack_python_v1
function make_new_folder folder begin if is directory path folder begin pass end else begin make directory os folder end end function
def make_new_folder(folder): if os.path.isdir(folder): pass else: os.mkdir(folder)
Python
nomic_cornstack_python_v1
function delete self evt=none begin for link in copy next_links begin delete end end function
def delete(self, evt=None): for link in self.next_links.copy(): link.delete()
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment -*- coding: utf-8 -*- import sqlite3 import sys import os set db_filename = string zone1db.db set schema_filename = string zoneDBSchema.sql set db_is_new = not exists path db_filename with call connect db_filename as conn begin if db_is_new begin print string Creating schema with open s...
#!/usr/bin/python # -*- coding: utf-8 -*- import sqlite3 import sys import os db_filename = 'zone1db.db' schema_filename = 'zoneDBSchema.sql' db_is_new = not os.path.exists(db_filename) with sqlite3.connect(db_filename) as conn: if db_is_new: print ('Creating schema') with open(schema_filename...
Python
zaydzuhri_stack_edu_python
function auto_color stream=stdin begin set term_name = lower get environ string TERM string if call isatty and term_name in KNOWN_TERMINAL_TYPES or string xterm in term_name begin return call VtColor end return call NoColor end function
def auto_color(stream=sys.stdin): term_name = os.environ.get("TERM", "").lower() if (stream.isatty() and (term_name in KNOWN_TERMINAL_TYPES or "xterm" in term_name)): return VtColor() return NoColor()
Python
nomic_cornstack_python_v1
function cardholder_signature self cardholder_signature begin set _cardholder_signature = cardholder_signature end function
def cardholder_signature(self, cardholder_signature): self._cardholder_signature = cardholder_signature
Python
nomic_cornstack_python_v1
function scale self scalar begin string Multiply a polynomial with a scalar return call __class__ list comprehension coefficients at i * scalar for i in call _range length self end function
def scale(self, scalar): '''Multiply a polynomial with a scalar''' return self.__class__([self.coefficients[i] * scalar for i in _range(len(self))])
Python
jtatman_500k
function test_entropy_bounds_hold self begin print string print string L1 = % 7.5f % L1 print string L1_lb2 = % 7.5f % L1_lb2 print string L1_lb = % 7.5f % L1_lb assert L1 > L1_lb assert L1 > L1_lb2 print string print string L2 = % 7.5f % L2 print string L2_lb2 = % 7.5f % L2_lb2 print string L2_lb = % 7.5f % L2_lb asse...
def test_entropy_bounds_hold(self): print('') print('L1 = % 7.5f' % (self.L1)) print('L1_lb2 = % 7.5f' % (self.L1_lb2)) print('L1_lb = % 7.5f' % (self.L1_lb)) assert self.L1 > self.L1_lb assert self.L1 > self.L1_lb2 print('') print('L2 = % 7.5f'...
Python
nomic_cornstack_python_v1
comment coding: utf-8 set __author__ = string Jux.Liu class BinaryNode extends object begin function __init__ self data=none left_child=none right_child=none parent=none begin set data = data set left_child = left_child set right_child = right_child if left_child begin set parent = self end if right_child begin set par...
# coding: utf-8 __author__ = 'Jux.Liu' class BinaryNode(object): def __init__(self, data=None, left_child=None, right_child=None, parent=None): self.data = data self.left_child = left_child self.right_child = right_child if left_child: self.left_child.parent = self ...
Python
zaydzuhri_stack_edu_python
import logging import numpy as np from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error , mean_absolute_error from helpers.datasets import load_training_test_datasets from helpers import constants set FORMAT = string %(asctime)-15s %(message)s call basicConfig level=DEBUG form...
import logging import numpy as np from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error, mean_absolute_error from helpers.datasets import load_training_test_datasets from helpers import constants FORMAT = '%(asctime)-15s %(message)s' logging.basicConfig(level=logging.DEBUG,...
Python
zaydzuhri_stack_edu_python
async function search_wikipedia term begin set url = string http://en.wikipedia.org/w/api.php set params = dict string action string opensearch ; string search term ; string format string json async_with call ClientSession as session begin async_with get session url params=params as resp begin set json_response = await...
async def search_wikipedia(term: str) -> rx.AsyncObservable[str]: url = "http://en.wikipedia.org/w/api.php" params = {"action": "opensearch", "search": term, "format": "json"} async with aiohttp.ClientSession() as session: async with session.get(url, params=params) as resp: json_respon...
Python
nomic_cornstack_python_v1
comment Natural Langauge Processing comment Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd comment importing the dataset comment quoting for ignor set dataset = read csv string Restaurant_Reviews.tsv delimiter=string quoting=3 comment cleaning the text import re import n...
#Natural Langauge Processing # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd #importing the dataset dataset= pd.read_csv('Restaurant_Reviews.tsv', delimiter='\t', quoting=3 )#quoting for ignor #cleaning the text import re import nltk from nltk.corpus imp...
Python
zaydzuhri_stack_edu_python
comment python b6-comment.py from bs4 import BeautifulSoup with open string example.html string r as l begin set soup = call BeautifulSoup l string lxml end set comment = string print comment print type comment print call prettify
# python b6-comment.py from bs4 import BeautifulSoup with open("example.html" ,"r") as l: soup = BeautifulSoup(l ,"lxml") comment = soup.p.string print(comment) print(type(comment)) print(soup.p.prettify())
Python
zaydzuhri_stack_edu_python
class Solution extends object begin function getRow self rowIndex begin string :type rowIndex: int :rtype: List[int] if rowIndex == 0 begin return list 1 end set re = list list 1 for i in range 1 rowIndex + 1 begin set x1 = list 0 + re at - 1 set x2 = re at - 1 + list 0 set new = list for j in range length x1 begin ap...
class Solution(object): def getRow(self, rowIndex): """ :type rowIndex: int :rtype: List[int] """ if rowIndex == 0: return [1] re = [[1]] for i in range(1, rowIndex+1): x1 = [0]+re[-1] x2 = re[-1]+[0] new = [] ...
Python
zaydzuhri_stack_edu_python