code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment 判断 [101,200] 有多少个素数,并输出所有素数 comment 素数:只能被 1 和它本身整除的正整数(1不是素数) set counter = 0 for i in range 101 201 begin comment 因为1 不是素数,所以从2 开始 for j in range 2 i begin if i % j == 0 begin break end end for else begin print i comment Python 中没有自增自减 ++ -- set counter = counter + 1 end end print string 质数的个数为: counter
# 判断 [101,200] 有多少个素数,并输出所有素数 # 素数:只能被 1 和它本身整除的正整数(1不是素数) counter = 0 for i in range(101 , 201): for j in range(2, i): # 因为1 不是素数,所以从2 开始 if i % j == 0: break else: print(i) counter = counter + 1 # Python 中没有自增自减 ++ -- print('质数的个数为:',counter)
Python
zaydzuhri_stack_edu_python
comment Step 4 : Data Exploaration comment These codes serve for a multitude of reasons but the one most impotant is quantifing initial statistics for you data. comment You want to be able to draw samples, get accurate graphs, sort the data. etc... comment You have no real mission for this step, it's the only step that...
#Step 4 : Data Exploaration ##These codes serve for a multitude of reasons but the one most impotant is quantifing initial statistics for you data. ##You want to be able to draw samples, get accurate graphs, sort the data. etc... ##You have no real mission for this step, it's the only step that really doesn't have an a...
Python
zaydzuhri_stack_edu_python
from django import template set register = call Library decorator filter function grade value begin return call gradelogic value end function decorator filter function mean value begin set avg = integer value / 5 return call gradelogic avg end function decorator filter function score_remarks value begin return call rem...
from django import template register = template.Library() @register.filter def grade(value): return gradelogic(value) @register.filter def mean(value): avg = int(value/5) return gradelogic(avg) @register.filter def score_remarks(value): return remarkslogic(value) @register.filter def mean_remar...
Python
zaydzuhri_stack_edu_python
comment Only one argument. function inthuong value begin return lower value end function
def inthuong(value): # Only one argument. return value.lower()
Python
nomic_cornstack_python_v1
function __init__ self size begin comment Best to have size be primary number to ensure efficiency set size = size set slots = list none * size set data = list none * size end function
def __init__(self, size): self.size = size #Best to have size be primary number to ensure efficiency self.slots = [None] * self.size self.data = [None] * self.size
Python
nomic_cornstack_python_v1
import os import nltk import re from PATH_CONSTANTS import * function getNumberOfLocation extendedNERAnalyzedParse begin set locationList = list set locationCode = dict set fl = 0 set locStr = string set normStr = string for tuple key tokenInfoDict in call iteritems begin if tokenInfoDict at string NER == string LO...
import os import nltk import re from PATH_CONSTANTS import * def getNumberOfLocation(extendedNERAnalyzedParse): locationList = [] locationCode = {} fl = 0 locStr = "" normStr = "" for key,tokenInfoDict in extendedNERAnalyzedParse.iteritems(): if(tokenInfoDict["NER"] == "LOCATION" and fl == 0): fl = 1 loc...
Python
zaydzuhri_stack_edu_python
comment ! /usr/bin/env python function old_child str_arg begin call world str_arg print string public_way end function function world str_arg begin print str_arg end function if __name__ == string __main__ begin call old_child string come_own_year_of_hand end
#! /usr/bin/env python def old_child(str_arg): world(str_arg) print('public_way') def world(str_arg): print(str_arg) if __name__ == '__main__': old_child('come_own_year_of_hand')
Python
zaydzuhri_stack_edu_python
import json from urllib.request import urlopen function main begin set conn = url open string https://api.thingspeak.com/channels/921887/feeds.json?api_key=TFOKGAJVCBP8CZTL&results=2 set response = read conn print format string http status code= {} call getcode set data = loads response print data at string channel at ...
import json from urllib.request import urlopen def main(): conn = urlopen("https://api.thingspeak.com/channels/921887/feeds.json?api_key=TFOKGAJVCBP8CZTL&results=2") response = conn.read() print ("http status code= {}" .format(conn.getcode())) data=json.loads(response) print (data['channel']['crea...
Python
zaydzuhri_stack_edu_python
import json import requests import datetime function get_trending_repositories top_size days_ago begin set trending_repositories = list set request_url = string https://api.github.com/search/repositories set today = today set past_date = today - time delta days=days_ago set search_params = dict string q format string ...
import json import requests import datetime def get_trending_repositories(top_size, days_ago): trending_repositories = [] request_url = "https://api.github.com/search/repositories" today = datetime.datetime.today() past_date = today - datetime.timedelta(days=days_ago) search_params = {"q": " creat...
Python
zaydzuhri_stack_edu_python
function isLeapYear year begin if year % 4 == 0 and year % 100 != 0 begin return true end return year % 400 == 0 end function comment TESTS## function test_simple_leapYear begin assert call isLeapYear 1996 end function function test_simple_not_leapYear begin assert not call isLeapYear 2001 end function function test_di...
def isLeapYear(year): if(year % 4 == 0 and year % 100 != 0): return True return year % 400 == 0 ##TESTS## def test_simple_leapYear(): assert isLeapYear(1996) def test_simple_not_leapYear(): assert not isLeapYear(2001) def test_different_leapYear(): assert isLeapYear(2000) def test_different_not_leapYear()...
Python
zaydzuhri_stack_edu_python
function bfsSearchGraph graph=none start=none end=none begin if not graph or not start begin return false end set queue = list start set visited = list start while queue begin set node = pop queue 0 if node == end begin return true end for adjacent in list comprehension x for x in graph at node if x not in visited begi...
def bfsSearchGraph(graph=None, start=None, end=None): if not graph or not start: return False queue = [start] visited = [start] while queue: node = queue.pop(0) if node == end: return True for adjacent in [x for x in graph[node] if x not in visited]: ...
Python
nomic_cornstack_python_v1
string Module to enable quadratic sorting of long dictionaries. Functions: insertion_sort(a_list_dict, key): Insertion sorts list of dictionaries, a_list_dict, in ascending order by the values of key, key. bubble_sort(a_list_dict, key): Bubble sorts list of dictionaries, a_list_dict, in ascending order by the values of...
""" Module to enable quadratic sorting of long dictionaries. Functions: insertion_sort(a_list_dict, key): Insertion sorts list of dictionaries, a_list_dict, in ascending order by the values of key, key. bubble_sort(a_list_dict, key): Bubble sorts list of dictionaries, a_list_dict, in ascending order by the va...
Python
zaydzuhri_stack_edu_python
comment 图像的空域平滑、锐化 import cv2 import numpy as np import matplotlib.pyplot as plt import random comment 求均值 function get_average img x y step begin set ans = 0 for i in range x - integer step / 2 x + integer step / 2 + 1 begin for j in range y - integer step / 2 y + integer step / 2 + 1 begin comment 求像素周围像素的均值 set ans ...
#图像的空域平滑、锐化 import cv2 import numpy as np import matplotlib.pyplot as plt import random #求均值 def get_average(img,x,y,step): ans=0 for i in range(x-int(step/2),x+int(step/2)+1): for j in range(y-int(step/2),y+int(step/2)+1): ans+=img[i][j] #求像素周围像素的均值 return int(an...
Python
zaydzuhri_stack_edu_python
comment import the necessary packages from skimage.segmentation import slic from skimage.segmentation import mark_boundaries from skimage.util import img_as_float import matplotlib.pyplot as plt import numpy as np import argparse import cv2 import glob as glob call set_printoptions threshold=inf comment construct the a...
# import the necessary packages from skimage.segmentation import slic from skimage.segmentation import mark_boundaries from skimage.util import img_as_float import matplotlib.pyplot as plt import numpy as np import argparse import cv2 import glob as glob np.set_printoptions(threshold=np.inf) # construct the argument p...
Python
zaydzuhri_stack_edu_python
function getJSON self begin set out = dict string xCoord x ; string yCoord y ; string orientation orient if ship_type is not string M begin set out at string type = ship_type end return out end function
def getJSON(self): out = {'xCoord': self.x, 'yCoord': self.y, 'orientation': self.orient} if self.ship_type is not "M": out['type'] = self.ship_type return out
Python
nomic_cornstack_python_v1
function writeArray file vector format fontSize sep=string & linesep=string \\ suppress_entry=none begin comment TODO (see CAVE above): I think the written numbers are only correct, if comment the input format specifies two numbers of precision. Otherwise the comment rounding procedure is wrong. comment handle input ar...
def writeArray(file, vector, format, fontSize, sep=' & ', linesep='\\\\ \n', suppress_entry=None): # TODO (see CAVE above): I think the written numbers are only correct, if # the input format specifies two numbers of precision. Otherwise the # rounding procedure is wrong. # handle input...
Python
nomic_cornstack_python_v1
function degree self v outgoing=true begin set adj = if expression outgoing then _outgoing else _incoming return length adj at v end function
def degree(self,v,outgoing=True): adj = self._outgoing if outgoing else self._incoming return len(adj[v])
Python
nomic_cornstack_python_v1
comment coding: utf-8 comment In[1]: import time import csv import requests comment 使用selenium webdriver進行抓取 from selenium import webdriver set chromedriver = string D:\chromedriver_win32/chromedriver set driver = call Chrome chromedriver comment 獲取要爬取的網頁 get driver string http://www.tse.com.tw/zh/page/trading/fund/TWT...
# coding: utf-8 # In[1]: import time import csv import requests #使用selenium webdriver進行抓取 from selenium import webdriver chromedriver="D:\chromedriver_win32/chromedriver" driver=webdriver.Chrome(chromedriver) #獲取要爬取的網頁 driver.get("http://www.tse.com.tw/zh/page/trading/fund/TWT38U.html") #之後要儲存檔案的路徑,output.csv是要寫入...
Python
zaydzuhri_stack_edu_python
function assert_merge_headers self locale begin set path = join path call get_messages_dir locale string django.po set pof = call pofile path set pattern = compile string ^#-#-#-#-# M set match = find all header assert length match == 3 msg string Found { length match } (should be 3) merge comments in the header for { ...
def assert_merge_headers(self, locale): path = os.path.join(self.configuration.get_messages_dir(locale), 'django.po') pof = pofile(path) pattern = re.compile('^#-#-#-#-#', re.M) match = pattern.findall(pof.header) assert len(match) == 3, (f'Found {len(match)} (should be 3) merge ...
Python
nomic_cornstack_python_v1
comment coding:utf-8 from ConfigurationFolder.ReadConfig import ReadConfig import requests class Access begin string 1、调用requests库get、post方法访问,并返回dict数据类型。 function __init__ self url **kwargs begin string :param url: config.ini --> "SetFollow" :param kwargs: 接口参数 set url = call get_url url set kwargs = kwargs end funct...
# coding:utf-8 from ConfigurationFolder.ReadConfig import ReadConfig import requests class Access: """ 1、调用requests库get、post方法访问,并返回dict数据类型。 """ def __init__(self, url, **kwargs): """ :param url: config.ini --> "SetFollow" :param kwargs: 接口参数 """ self.url = Re...
Python
zaydzuhri_stack_edu_python
import random import math function Nim begin set size = call randrange 10 101 print format string The size of the pile is {} marbles. size if call randrange 0 2 == 0 begin set first = string computer set nextt = string human print string The computer will go first. end else begin set first = string human set second = s...
import random import math def Nim(): size = random.randrange(10, 101) print ("The size of the pile is {} marbles.".format(size)) if random.randrange(0, 2) == 0: first = "computer" nextt = "human" print ("The computer will go first.") else: first = "human" second...
Python
zaydzuhri_stack_edu_python
function loadCheckpoint self begin raise call NotImplementedError string loadCheckpoint must be implemented by sub-class end function
def loadCheckpoint(self): raise NotImplementedError( "loadCheckpoint must be implemented by sub-class")
Python
nomic_cornstack_python_v1
function dap_reset_ext self extend=false begin debug string dap_reset_ext set cmd = bytearray 7 set cmd at 0 = ID_DAP_SWJ_Pins comment Reset LOW, TCK LOW set cmd at 1 = 0 set cmd at 2 = DAP_SWJ_nRESET if extend begin set cmd at 2 = cmd at 2 ? DAP_SWJ_SWCLK_TCK end set cmd at 3 = 0 set cmd at 4 = 0 set cmd at 5 = 0 set ...
def dap_reset_ext(self, extend=False): self.logger.debug("dap_reset_ext") cmd = bytearray(7) cmd[0] = self.ID_DAP_SWJ_Pins cmd[1] = 0 # Reset LOW, TCK LOW cmd[2] = self.DAP_SWJ_nRESET if extend: cmd[2] |= self.DAP_SWJ_SWCLK_TCK cmd[3] = 0 cmd[...
Python
nomic_cornstack_python_v1
function cli input_directory output_directory=string docs style=string md begin set input_path = call Path input_directory set output_path = call Path output_directory set parsed_modules = call find_and_extract input_path set builder = call MarkdownBuilder call setting call build parsed_modules save output_path end fun...
def cli(input_directory: str, output_directory: str = 'docs', style: str = 'md'): input_path = Path(input_directory) output_path = Path(output_directory) parsed_modules = find_and_extract(input_path) builder = MarkdownBuilder() builder.setting() builder.build(parsed_modules) builder....
Python
nomic_cornstack_python_v1
for tuple k v in sorted items result begin print string { k } : { v } time/s end
for k, v in sorted(result.items()): print(f"{k}: {v} time/s")
Python
zaydzuhri_stack_edu_python
from unittest import TestCase from unittest.mock import patch from character import combat_to_death import unittest.mock import io import random class TestCombat_to_death extends TestCase begin decorator patch string sys.stdout new_callable=StringIO decorator patch string character.roll_die side_effect=list 2 2 8 funct...
from unittest import TestCase from unittest.mock import patch from character import combat_to_death import unittest.mock import io import random class TestCombat_to_death(TestCase): @unittest.mock.patch('sys.stdout', new_callable=io.StringIO) @patch('character.roll_die', side_effect=[2, 2, 8]) ...
Python
zaydzuhri_stack_edu_python
function greet name=call Option string friend string --name string -n count=call Option 1 string --count string -c begin comment name: str = typer.Option(...), # required for _ in range count begin call echo string Hello { name } ! end end function
def greet( # name: str = typer.Option(...), # required name: str = typer.Option("friend", "--name", "-n"), count: int = typer.Option(1, "--count", "-c") ) -> None: for _ in range(count): typer.echo(f"Hello {name}!")
Python
nomic_cornstack_python_v1
if lower user_input at 0 in string aeiou begin print user_input + string way end else begin print user_input at slice 1 : : + user_input at 0 + string ay end
if user_input[0].lower() in ("aeiou"): print (user_input + "way") else: print (user_input[1:] + user_input[0] + "ay")
Python
zaydzuhri_stack_edu_python
function mirrorReflection p q begin from math import gcd set m = p // call gcd p q if m % 2 == 0 begin return 2 end if q // call gcd p q % 2 == 0 begin return 0 end return 1 end function
def mirrorReflection(p, q): from math import gcd m = p // gcd(p, q) if m % 2 == 0: return 2 if (q // gcd(p, q)) % 2 == 0: return 0 return 1
Python
jtatman_500k
function capacity_fit swap_houses_1 swap_houses_2 swap_battery_1 swap_battery_2 begin set output_1 = 0 set output_2 = 0 for house in swap_houses_1 begin set output_1 = output_1 + output end for house in swap_houses_2 begin set output_2 = output_2 + output end set capacity_1 = call capacity_used - output_1 + output_2 se...
def capacity_fit(swap_houses_1, swap_houses_2, swap_battery_1, swap_battery_2): output_1 = 0 output_2 = 0 for house in swap_houses_1: output_1 += house.output for house in swap_houses_2: output_2 += house.output capacity_1 = swap_battery_1.capacity_used() - output_1 + output_2 ...
Python
nomic_cornstack_python_v1
string 1161. Maximum Level Sum of a Binary Tree Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on. Return the smallest level X such that the sum of all the values of nodes at level X is maximal. Input: [1,7,0,7,-8,null,null] Output: 2 Explanation: Level 1 sum = 1. Le...
""" 1161. Maximum Level Sum of a Binary Tree Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on. Return the smallest level X such that the sum of all the values of nodes at level X is maximal. Input: [1,7,0,7,-8,null,null] Output: 2 Explanation: Level 1 ...
Python
zaydzuhri_stack_edu_python
for x in range 0 test_cases begin set data = split input set coord = list map int data set slope = coord at 3 - coord at 1 / coord at 2 - coord at 0 set answers = answers + string ( + string slope + string + string coord at 1 - slope * coord at 0 + string ) end print answers
for x in range(0, test_cases): data = input().split() coord = list(map(int, data)) slope = (coord[3]-coord[1])/(coord[2]-coord[0]) answers += '(' + str(slope) + ' ' + str(coord[1]-slope*coord[0]) + ') ' print(answers)
Python
zaydzuhri_stack_edu_python
function intersect_sgrna_copynumber self begin comment Build copy-number and sgRNAs data frames set df_cn = call get_df_copy_number set df_sg = call get_df_library comment Build beds set bed_cn = sort call BedTool call to_string index=false header=false from_string=true set bed_sg = sort call BedTool call to_string ind...
def intersect_sgrna_copynumber(self): # Build copy-number and sgRNAs data frames df_cn = self.get_df_copy_number() df_sg = self.get_df_library() # Build beds bed_cn = BedTool(df_cn.to_string(index=False, header=False), from_string=True).sort() bed_sg = BedTool(df_sg.to_s...
Python
nomic_cornstack_python_v1
function get_trigrams text begin set lista = list call ngrams split text 2 return lista end function
def get_trigrams(text): lista = list(nltk.ngrams(text.split(), 2)) return lista
Python
nomic_cornstack_python_v1
import os set premier = string premier.txt set path_track1 = join path string C:\ string Users string yannt string Desktop string PYTHON string Practice_Python premier set happy = string happy.txt set path_track2 = join path string C:\ string Users string yannt string Desktop string PYTHON string Practice_Python happy ...
import os premier = "premier.txt" path_track1 = os.path.join("C:\\","Users","yannt","Desktop","PYTHON","Practice_Python",premier) happy = "happy.txt" path_track2 = os.path.join("C:\\","Users","yannt","Desktop","PYTHON","Practice_Python",happy) premier_liste = [] happy_liste = [] with open(path_track1) as f: ...
Python
zaydzuhri_stack_edu_python
function get_USD_BTC_price_bittrex begin set price = call get_ticker string USD-BTC assert price at string success return price at string result at string Last end function
def get_USD_BTC_price_bittrex(): price = BITTREX.get_ticker("USD-BTC") assert price["success"] return price["result"]["Last"]
Python
nomic_cornstack_python_v1
if age >= 0 begin if age < 3 begin print string 無料です end else if age < 13 begin print string 半額です end else if age < 65 begin print string 通常料金です end else begin print string 無料です end end else begin print string 正の整数を入力してください end
if age >= 0: if age < 3: print("無料です") elif age < 13: print("半額です") elif age < 65: print("通常料金です") else: print("無料です") else: print("正の整数を入力してください")
Python
zaydzuhri_stack_edu_python
function pc_noutput_items_var self begin return call dll_cc_sptr_pc_noutput_items_var self end function
def pc_noutput_items_var(self): return _ccsds_swig.dll_cc_sptr_pc_noutput_items_var(self)
Python
nomic_cornstack_python_v1
async function get_content_count self source begin string Return file listing for source. set params = dict string uri source ; string type none ; string target string all ; string view string flat return call make keyword await call params end function
async def get_content_count(self, source: str): """Return file listing for source.""" params = {"uri": source, "type": None, "target": "all", "view": "flat"} return ContentInfo.make( **await self.services["avContent"]["getContentCount"](params) )
Python
jtatman_500k
comment !/usr/bin/env python comment This does not work with Python 3.8 comment Works with Python3.6 import yfinance as yf , argparse , sys import time from yaspin import yaspin from yaspin.spinners import Spinners from util import str2bool from findance import FinDance comment Yahoo finance datetimes are received as U...
#!/usr/bin/env python # This does not work with Python 3.8 # Works with Python3.6 import yfinance as yf,argparse,sys import time from yaspin import yaspin from yaspin.spinners import Spinners from util import str2bool from findance import FinDance # Yahoo finance datetimes are received as UTC # Use Ticker module ...
Python
zaydzuhri_stack_edu_python
comment Compute the standard deviations set control_sd = cont_var ^ 0.5 set test_sd = test_var ^ 0.5 comment Create the range of x values set control_line = linear space cont_conv - 3 * control_sd cont_conv + 3 * control_sd 100 set test_line = linear space test_conv - 3 * test_sd test_conv + 3 * test_sd 100 comment Plo...
# Compute the standard deviations control_sd = cont_var**0.5 test_sd = test_var**0.5 # Create the range of x values control_line = np.linspace( cont_conv - 3 * control_sd, cont_conv + 3 * control_sd , 100) test_line = np.linspace( test_conv - 3 * test_sd, test_conv + 3 * test_sd , 100) # Plot the distribution plt....
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Thu Aug 26 10:58:02 2021 @author: dharmendar comment Arithmetic Operators (+,-,*,/) comment Addition operator (+) print 10 * string - + string Addition + 10 * string - function add begin set num1 = integer input string Enter First Number: set num2 = integer input string E...
# -*- coding: utf-8 -*- """ Created on Thu Aug 26 10:58:02 2021 @author: dharmendar """ # Arithmetic Operators (+,-,*,/) # Addition operator (+) print(10*'-'+'Addition'+10*'-') def add(): num1 = int(input('Enter First Number: ')) num2 = int(input('Enter Second Number: ')) addition = num1+num2 p...
Python
zaydzuhri_stack_edu_python
function setWriteComment *args begin return call XMLOutputStream_setWriteComment *args end function
def setWriteComment(*args): return _libsbml.XMLOutputStream_setWriteComment(*args)
Python
nomic_cornstack_python_v1
comment Importa a biblioteca do MySQL import MySQLdb comment Define a classe class ConectaBanco begin comment init é o metodo inicializador da classe function __init__ self begin comment Cria a variavel de conexão vazia set con = string end function comment Método para conectar no banco function conecta self begin com...
import MySQLdb # Importa a biblioteca do MySQL class ConectaBanco: # Define a classe def __init__(self): # init é o metodo inicializador da classe self.con = "" # Cria a variavel de conexão vazia def conecta(self): # Método para conectar no banco host = "localhost" # Nome utilizado no ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 comment coding=UTF-8 string Created on 07 декабря 2019 г. построение 2D-image функций z=f(x,y) в прямоугольной области import os , sys import math import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import numpy.ma as ma comment from cycler import cycler if __name__ == ...
#!/usr/bin/python3 # coding=UTF-8 ''' Created on 07 декабря 2019 г. построение 2D-image функций z=f(x,y) в прямоугольной области ''' import os, sys import math import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import numpy.ma as ma #from cycler import cycler if...
Python
zaydzuhri_stack_edu_python
comment coding=utf-8 import logging import tensorflow as tf import layers.tf_layers as layers from utils.utility import seq_length class LSTM extends object begin string mlp cnn init function function __init__ self config begin set vocab_size = integer config at string vocabulary_size set emb_size = integer config at s...
#coding=utf-8 import logging import tensorflow as tf import layers.tf_layers as layers from utils.utility import seq_length class LSTM(object): """ mlp cnn init function """ def __init__(self, config): self.vocab_size = int(config['vocabulary_size']) self.emb_size = int(config['embe...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Fri May 28 02:53:58 2021 @author: Andy, Ananya, Tiana import networkx as nx function set_opinion_attrs G nodes begin string Sets the opinion attribute of a network G comment creating attribute dictionary set opinion_dict = dict for i in rang...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri May 28 02:53:58 2021 @author: Andy, Ananya, Tiana """ import networkx as nx def set_opinion_attrs(G, nodes): ''' Sets the opinion attribute of a network G ''' #creating attribute dictionary opinion_dict = {} for i in range(len(n...
Python
zaydzuhri_stack_edu_python
function match_skip self begin return length small_l_prime - small_l_prime at 1 end function
def match_skip(self): return len(self.small_l_prime) - self.small_l_prime[1]
Python
nomic_cornstack_python_v1
from sklearn.ensemble import GradientBoostingClassifier from sklearn.datasets import make_hastie_10_2 set tuple X y = call make_hastie_10_2 n_samples=10000 comment shallow trees, multiple steps set est = gradient boosting classifier n_estimators=200 max_depth=3 fit est X y set pred = predict est X
from sklearn.ensemble import GradientBoostingClassifier from sklearn.datasets import make_hastie_10_2 X, y = make_hastie_10_2(n_samples=10000) est = GradientBoostingClassifier(n_estimators=200, max_depth=3) # shallow trees, multiple steps est.fit(X, y) pred = est.predict(X)
Python
zaydzuhri_stack_edu_python
import pygame import random call init set progress = 0 set into = true set black = list 0 0 0 set white = list 255 255 255 set intoWhite = list 249 244 244 set green = list 0 255 0 set screenWidth = 600 set screenHeigth = 450 set size = list screenWidth screenHeigth set font = call SysFont string Comic Sans MS 25 set i...
import pygame import random pygame.init() progress = 0 into = True black = [0, 0, 0] white = [255, 255, 255] intoWhite = [249, 244, 244] green = [0, 255, 0] screenWidth = 600 screenHeigth = 450 size = [screenWidth, screenHeigth] font = pygame.font.SysFont("Comic Sans MS", 25) intoPic = pygame...
Python
zaydzuhri_stack_edu_python
function zfill a width begin set a_arr = call asarray a set width_arr = call asarray width set size = integer max flat return call _vec_string a_arr call type dtype size string zfill tuple width_arr end function
def zfill(a, width): a_arr = numpy.asarray(a) width_arr = numpy.asarray(width) size = int(numpy.max(width_arr.flat)) return _vec_string( a_arr, type(a_arr.dtype)(size), 'zfill', (width_arr,))
Python
nomic_cornstack_python_v1
function _run_custom_commands self environment directory branch key begin set commands = call config key list if not commands begin info string Skipped %s % key return true end info string Running %s % key for command in commands begin set command = replace command string {{environment}} environment set command = repla...
def _run_custom_commands(self, environment, directory, branch, key): commands = self.config(key, []) if not commands: self.output.info('Skipped %s' % key) return True self.output.info('Running %s' % key) for command in commands: command = command.rep...
Python
nomic_cornstack_python_v1
import os set path = string F:\CSE\Python programs\text.txt comment path = "F:\\CSE\\Python programs" if exists path path begin print string That's location exists if is file path path begin print string That's a file end else if is directory path path begin print string That's a directory end end else begin print stri...
import os path = "F:\\CSE\\Python programs\\text.txt" #path = "F:\\CSE\\Python programs" if os.path.exists(path): print("That's location exists") if os.path.isfile(path): print("That's a file") elif os.path.isdir(path): print("That's a directory") else: print("That's loca...
Python
zaydzuhri_stack_edu_python
comment 2.已知仓库中有若干商品,以及相应库存,类似: comment 袜子,10,鞋子,20,拖鞋,30,项链,40 comment 要求随机返回一种商品,要求商品被返回的概率与其库存成正比。请描述实现的思路或者直接写一个实现的函数 lam
#2.已知仓库中有若干商品,以及相应库存,类似: #袜子,10,鞋子,20,拖鞋,30,项链,40 #要求随机返回一种商品,要求商品被返回的概率与其库存成正比。请描述实现的思路或者直接写一个实现的函数 lam
Python
zaydzuhri_stack_edu_python
function track depth score path begin global max_score if depth == 11 begin comment print(path, score) if score > max_score begin set max_score = score end return end for i in range 11 begin if used at i begin continue end if graph at depth at i == 0 begin continue end set used at i = 1 append path i call track depth +...
def track(depth, score, path): global max_score if depth == 11: # print(path, score) if score > max_score: max_score = score return for i in range(11): if used[i]: continue if graph[depth][i] == 0: continue used[i] = 1 ...
Python
zaydzuhri_stack_edu_python
import tensorflow as tf import numpy as np import collections import random import math import logging import zipfile import os import string from nltk.corpus import stopwords import pickle call basicConfig level=INFO set logger = call getLogger __name__ comment to-do: add dictionary class Word2Vec begin function __ini...
import tensorflow as tf import numpy as np import collections import random import math import logging import zipfile import os import string from nltk.corpus import stopwords import pickle logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # to-do: add dictionary class Word2Vec: def __i...
Python
zaydzuhri_stack_edu_python
function fitfunc_3G1Ysq a_x a_p1 a_p2 a_p3 a_p4 a_p5 a_p6 a_p7 a_p8 a_p9 begin comment if (a_x != 0.0): if true begin return a_p1 * exp - power a_x / a_p2 2 + a_p3 * exp - power a_x / a_p4 2 + a_p5 * exp - power a_x / a_p6 2 + a_p7 * 1.0 - exp - a_p8 * a_x ^ 2 ^ 2 * exp - 2.0 * a_p9 * a_x / a_x ^ 2 end else begin retur...
def fitfunc_3G1Ysq(a_x, a_p1, a_p2, a_p3, a_p4, a_p5, a_p6, a_p7, a_p8, a_p9): # if (a_x != 0.0): if (True): return (a_p1 * exp(-pow(a_x/a_p2, 2)) + a_p3 * exp(-pow(a_x/a_p4, 2)) + a_p5 * exp(-pow(a_x/a_p6, 2)) + a_p7 * (1.0 - exp(-a_p8 * a_x**2))**2 * exp(-2.0 * a_p9...
Python
nomic_cornstack_python_v1
function rawDataReceived self data begin raise NotImplementedError end function
def rawDataReceived(self, data): raise NotImplementedError
Python
nomic_cornstack_python_v1
while c != a begin if second == 60 begin set minute = minute + 1 set second = 0 end else if second != 60 begin pass end set second = second + 1 set c = c + 1 end if minute != 1 begin set min_print = string minutes end else if minute == 1 or minute == 0 begin set min_print = string minute end if second != 1 begin set se...
while c!=a: if second==60: minute+=1 second=0 elif second!=60: pass second+=1 c+=1 if minute!=1: min_print = "minutes" elif minute==1 or minute==0 : min_print = "minute" if second!=1: sec_print = "seconds" elif second==1 or second==0 : sec_print = "second" print(f...
Python
zaydzuhri_stack_edu_python
function name self begin return get pulumi self string name end function
def name(self) -> pulumi.Output[str]: return pulumi.get(self, "name")
Python
nomic_cornstack_python_v1
function is_business_day self input_date begin set input_date = call parse_date input_date if call is_holiday input_date begin return false end else if input_date in extra_working_dates begin return true end else begin return call is_working_day input_date end end function
def is_business_day(self, input_date: INPUT_TYPES) -> bool: input_date = self.parse_date(input_date) if self.is_holiday(input_date): return False elif input_date in self.extra_working_dates: return True else: return self.is_working_day(input_date)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Sun Oct 6 20:28:07 2019 @author: whistler comment import data and split to variables and target import pandas as pd import numpy as np set df = read csv string /Users/whistler/Desktop/MachineLearning/ccdefault.csv header=0 set X = iloc at tup...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Oct 6 20:28:07 2019 @author: whistler """ #import data and split to variables and target import pandas as pd import numpy as np df = pd.read_csv('/Users/whistler/Desktop/MachineLearning/ccdefault.csv', header=0) X = df.iloc[:, 1:24] y = df.iloc[:, 24]...
Python
zaydzuhri_stack_edu_python
print string Olá! set peso = 60 set altura = 1.7 ^ 2 set imc = peso / altura print string O resultado do IMC com os dados sugeridos é: imc print string Obrigado. Volte sempre!
print("Olá!") peso = 60 altura = 1.70**2 imc = (peso/altura) print("O resultado do IMC com os dados sugeridos é: ", imc) print("Obrigado. Volte sempre!")
Python
zaydzuhri_stack_edu_python
function call self *args **kwargs begin return call _thing *args keyword kwargs end function
def call(self, *args, **kwargs): return self._thing(*args, **kwargs)
Python
nomic_cornstack_python_v1
function volume_detach name profile=none timeout=300 **kwargs begin string Attach a block storage volume name Name of the new volume to attach server_name Name of the server to detach from profile Profile to build on CLI Example: .. code-block:: bash salt '*' nova.volume_detach myblock profile=openstack set conn = call...
def volume_detach(name, profile=None, timeout=300, **kwargs): ''' Attach a block storage volume name Name of the new volume to attach server_name Name of the server to detach from profile Profile to build on CLI Example: .. code-block:: bash salt '*' nov...
Python
jtatman_500k
import re from collections import Counter function count_domain begin set log = open string access_log set regex_domain_list = list set line = read lines log comment Get domain from log for x in range length line begin append regex_domain_list string find all string "(?:http|https)://(.+?)(?:/|").+?" line at x at slic...
import re from collections import Counter def count_domain(): log = open('access_log') regex_domain_list = [] line = log.readlines() # Get domain from log for x in range(len(line)): regex_domain_list.append(str((re.findall(r'"(?:http|https)://(.+?)(?:/|").+?"', line[x])))[2:-2]) temp_...
Python
zaydzuhri_stack_edu_python
function clean sent begin set p1 = compile string \W set p2 = compile string \s+ set sent = sub string http\S+ string sent set sent = call ReplaceThreeOrMore sent set sent = call remove_unicode_diac sent set sent = replace sent string _ string set sent = sub string [A-Za-z0-9] string sent set sent = sub p1 string se...
def clean(sent): p1 = re.compile('\W') p2 = re.compile('\s+') sent = re.sub(r"http\S+", "", sent) sent = ReplaceThreeOrMore(sent) sent = remove_unicode_diac(sent) sent = sent.replace('_', ' ') sent = re.sub(r'[A-Za-z0-9]', r'', sent) sent = re.sub(p1, ' ', sent) sent = re.sub(p2, ' '...
Python
nomic_cornstack_python_v1
function nextPermutation self nums begin set i = length nums - 2 comment find first element that is less than next element. while i >= 0 and nums at i >= nums at i + 1 begin set i = i - 1 end set j = length nums - 1 comment find second element that is greater than first element. if i >= 0 begin while j >= 0 and nums at...
def nextPermutation(self, nums: List[int]) -> None: i = len(nums) - 2 # find first element that is less than next element. while i >= 0 and nums[i] >= nums[i + 1]: i -= 1 j = len(nums) - 1 # find second element that is greater than first element. if...
Python
nomic_cornstack_python_v1
function test_name_test_queries self begin delete comment Create 10 source traits from the same dataset, with non-deprecated ssv of version 2. set source_traits = list for name in TEST_NAMES begin append source_traits call create source_dataset=source_dataset i_trait_name=name end call refresh_from_db set url = call g...
def test_name_test_queries(self): models.SourceTrait.objects.all().delete() # Create 10 source traits from the same dataset, with non-deprecated ssv of version 2. self.source_traits = [] for name in TEST_NAMES: self.source_traits.append(factories.SourceTraitFactory.create( ...
Python
nomic_cornstack_python_v1
from django.http import HttpResponse , JsonResponse from django.shortcuts import render import json import numpy as np import math import time import random import itertools import queue import pandas as pd import seaborn as sns function createRandomPop Npop numberOfJobs begin set pop = list for i in range Npop begin ...
from django.http import HttpResponse, JsonResponse from django.shortcuts import render import json import numpy as np import math import time import random import itertools import queue import pandas as pd import seaborn as sns def createRandomPop(Npop, numberOfJobs): pop = [] for i in range(Npop): p ...
Python
zaydzuhri_stack_edu_python
comment need a clear function each time a bid is created import art print logo print string Welcome to the secret auction program. function ask_questions begin set name = input string What is your name?: set bid = input string What is your bid?: $ set keep_running = input string Are there any other bidders? Type 'yes' ...
# need a clear function each time a bid is created import art print(art.logo) print("Welcome to the secret auction program.") def ask_questions(): name = input("What is your name?: ") bid = input("What is your bid?: $") keep_running = input("Are there any other bidders? Type 'yes' or 'no'. ") return [name, bi...
Python
zaydzuhri_stack_edu_python
function getShardName self shardId begin assert call debugStateCall self string loginFSM string gameFSM try begin return name end except any begin return none end end function
def getShardName(self, shardId): assert self.notify.debugStateCall(self, 'loginFSM', 'gameFSM') try: return self.activeDistrictMap[shardId].name except: return None
Python
nomic_cornstack_python_v1
comment Lab 9 Errors, Testing and Logging; useFib.py comment This program prompts the user to input a number and outputs the Fibonacci sequence comment Author: Ross Downey import myFunctions set nTimes = integer input string how many: print call fibonacci nTimes
# Lab 9 Errors, Testing and Logging; useFib.py # This program prompts the user to input a number and outputs the Fibonacci sequence # Author: Ross Downey import myFunctions nTimes = int(input('how many:')) print (myFunctions.fibonacci(nTimes))
Python
zaydzuhri_stack_edu_python
import csv import pandas as pd import string import re import nltk from nltk.probability import FreqDist import matplotlib.pyplot as plt from nltk.corpus import stopwords from nltk.stem import PorterStemmer from nltk.stem.cistem import Cistem from nltk.tokenize import RegexpTokenizer from nltk.stem import SnowballStemm...
import csv import pandas as pd import string import re import nltk from nltk.probability import FreqDist import matplotlib.pyplot as plt from nltk.corpus import stopwords from nltk.stem import PorterStemmer from nltk.stem.cistem import Cistem from nltk.tokenize import RegexpTokenizer from nltk.stem import Sn...
Python
zaydzuhri_stack_edu_python
import pandas as pd import seaborn as sns import numpy as np comment Read the dataset set sheets = call read_excel string KPMG_VI_New_raw_data_update_final.xlsx engine=string openpyxl sheet_name=list string Transactions string NewCustomerList string CustomerDemographic string CustomerAddress set df_Transactions = sheet...
import pandas as pd import seaborn as sns import numpy as np #Read the dataset sheets = pd.read_excel('KPMG_VI_New_raw_data_update_final.xlsx', engine='openpyxl', sheet_name = ['Transactions', 'NewCustomerList', 'CustomerDemographic', 'CustomerAddress']) df_Transactions = sheets['Transactions'...
Python
zaydzuhri_stack_edu_python
string This is an older version based on Brahaym's derivations, not complete import numpy as np import scipy.linalg as scl from crocoddyl import SolverAbstract set VERBOSE = false function rev_enumerate l begin return reversed list enumerate l end function function raiseIfNan A error=none begin if error is none begin s...
""" This is an older version based on Brahaym's derivations, not complete """ import numpy as np import scipy.linalg as scl from crocoddyl import SolverAbstract VERBOSE = False def rev_enumerate(l): return reversed(list(enumerate(l))) def raiseIfNan(A, error=None): if error is None: error = scl....
Python
zaydzuhri_stack_edu_python
function search_specific_tags package tag_search begin return call search_tags package_name=package tag_search=tag_search end function
def search_specific_tags(package, tag_search): return search_tags( package_name=package, tag_search=tag_search )
Python
nomic_cornstack_python_v1
function modulo self x a begin return call fmod x + call sign x * a / 2 a - call sign x * a / 2 end function
def modulo(self, x, a): return torch.fmod(x + torch.sign(x) * a / 2, a) - torch.sign(x) * a / 2
Python
nomic_cornstack_python_v1
import tweepy comment Create variables for each key, secret, token set consumer_key = string hrABYWoeNcdDgyMYUPqlcITNi set consumer_secret = string 8KkiJEgeJySQ8ZFDA2ywHPx2cagifHqiXS7jxcsCWDtLPGV59K set access_token = string 838796084038230016-L8xC5JUjkDxUvfNJR4iZACE5QIKlXMG set access_token_secret = string jhQC3kWgc8S...
import tweepy #Create variables for each key, secret, token consumer_key = 'hrABYWoeNcdDgyMYUPqlcITNi' consumer_secret = '8KkiJEgeJySQ8ZFDA2ywHPx2cagifHqiXS7jxcsCWDtLPGV59K' access_token = '838796084038230016-L8xC5JUjkDxUvfNJR4iZACE5QIKlXMG' access_token_secret = 'jhQC3kWgc8SbkmlMnJ5965UDddeV61EbGbqcUnfzI3DuQ' #Set u...
Python
zaydzuhri_stack_edu_python
function amount_paid self begin return __amount_paid end function
def amount_paid(self): return self.__amount_paid
Python
nomic_cornstack_python_v1
import os from helper import get_postgres_host import os import psycopg2 class Database begin set USER_NAME = environ at string POSTGRES_USER set USER_PASSWORD = environ at string POSTGRES_PASSWORD set DB_NAME = environ at string POSTGRES_DB set DB_HOST = call get_postgres_host decorator staticmethod function get_conne...
import os from helper import get_postgres_host import os import psycopg2 class Database: USER_NAME = os.environ["POSTGRES_USER"] USER_PASSWORD = os.environ["POSTGRES_PASSWORD"] DB_NAME = os.environ["POSTGRES_DB"] DB_HOST = get_postgres_host() @staticmethod def get_connection(): tr...
Python
zaydzuhri_stack_edu_python
function __get_write_concern self begin comment To support dict style access we have to return the actual comment WriteConcern here, not a copy. return __write_concern end function
def __get_write_concern(self): # To support dict style access we have to return the actual # WriteConcern here, not a copy. return self.__write_concern
Python
nomic_cornstack_python_v1
function precipitation_df self begin return loc at reading_type == string PRCP end function
def precipitation_df(self): return self.weather_df.loc[ self.weather_df.reading_type == 'PRCP' ]
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python string Pure Python code for doing ADMM in 3D. minimize 1/2*|| Ax - b ||_2^2 + \lambda || x ||_1 As described in: Boyd et al., "Distributed Optimization and Statistical Learning via the Alternating Direction Method of Multipliers", Foundations and Trends in Machine Learning, 2010. Hazen 11/1...
#!/usr/bin/env python """ Pure Python code for doing ADMM in 3D. minimize 1/2*|| Ax - b ||_2^2 + \lambda || x ||_1 As described in: Boyd et al., "Distributed Optimization and Statistical Learning via the Alternating Direction Method of Multipliers", Foundations and Trends in Machine Learning, 2010. Hazen 11/19 """ ...
Python
zaydzuhri_stack_edu_python
function setUp self begin pass end function
def setUp(self): pass
Python
nomic_cornstack_python_v1
from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * import math from gl_frame import Frame from gl_vec3 import * class Rectangle extends object begin string @author Preetham Chalasani @brief Create a Rectangle function __init__ self x y z w h begin string Initializes rectangle paramets according ...
from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * import math from .gl_frame import Frame from .gl_vec3 import * class Rectangle(object): """ @author Preetham Chalasani @brief Create a Rectangle""" def __init__(self, x, y, z, w, h): """Initializes rectangle paramets according to the in...
Python
zaydzuhri_stack_edu_python
import numpy as np from SSplines import SimplexSpline function test_evaluation_coordinates_single begin set triangle = array list list 0 0 list 1 0 list 0 1 set knot_multiplicities = list 3 1 1 0 0 0 0 0 0 0 set s = call SimplexSpline triangle knot_multiplicities set x = array list 0.5 0.5 set b = array list 0 0.5 0.5 ...
import numpy as np from SSplines import SimplexSpline def test_evaluation_coordinates_single(): triangle = np.array([ [0, 0], [1, 0], [0, 1] ]) knot_multiplicities = [3, 1, 1, 0, 0, 0, 0, 0, 0, 0] s = SimplexSpline(triangle, knot_multiplicities) x = np.array([0.5, 0.5]) ...
Python
zaydzuhri_stack_edu_python
function runner fun *args begin if version_info >= tuple 3 7 begin if name == string nt and version_info < tuple 3 8 begin call set_event_loop_policy call WindowsProactorEventLoopPolicy end return run call fun *args end if name == string nt begin set loop = call ProactorEventLoop end else begin set loop = call new_even...
def runner(fun, *args): if sys.version_info >= (3, 7): if os.name == "nt" and sys.version_info < (3, 8): asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) return asyncio.run(fun(*args)) if os.name == "nt": loop = asyncio.ProactorEventLoop() else: ...
Python
nomic_cornstack_python_v1
function coerce_str value strip=true none=string trim=none trim_lines=false trim_msg=TRIM_MSG begin set value = call bytes_to_str value=value if value is none begin set value = none end if not is instance value str begin set value = string value end if strip begin set value = call strip_str value=value end set value =...
def coerce_str( value: t.Any, strip: bool = True, none: t.Any = "", trim: t.Optional[int] = None, trim_lines: bool = False, trim_msg: str = TRIM_MSG, ) -> t.Union[str, t.Any]: value = bytes_to_str(value=value) if value is None: value = none if not isinstance(value, str): ...
Python
nomic_cornstack_python_v1
function sequence_del my_str begin set new = string set l = length my_str for i in range l - 1 begin comment for j in range(1,len(my_str)): if my_str at i == my_str at i + 1 begin continue end set new = new + my_str at i end set new = new + my_str at i print new end function
def sequence_del(my_str): new = '' l = len(my_str) for i in range(l -1): # for j in range(1,len(my_str)): if my_str[i] == my_str[i+1]: continue new += my_str[i] new += my_str[i] print(new)
Python
nomic_cornstack_python_v1
import math function calc el begin return floor el / 3 - 2 end function function star1 inputArr begin set res = 0 for el in inputArr begin set res = res + call calc integer el end return res end function function star2 inputArr begin set modulesArr = list set index = 0 for el in inputArr begin append modulesArr call c...
import math def calc(el): return math.floor(el/3) - 2; def star1(inputArr): res = 0; for el in inputArr: res += calc(int(el)); return res def star2(inputArr): modulesArr = [] index = 0; for el in inputArr: modulesArr.append(calcFuel(int(el))) print(modulesArr); res = 0; for module in modulesArr: res...
Python
zaydzuhri_stack_edu_python
set num = decimal input string Enter a number: comment Check if the number is divisible by 4 if num % 4 == 0 begin comment Check if the number is greater than 100 if num > 100 begin comment Convert the number to positive if negative if num < 0 begin set num = absolute num end comment Check if the sum of its digits is d...
num = float(input("Enter a number: ")) # Check if the number is divisible by 4 if num % 4 == 0: # Check if the number is greater than 100 if num > 100: # Convert the number to positive if negative if num < 0: num = abs(num) # Check if the sum of its digits is divisible by 4 ...
Python
jtatman_500k
import requests import os from statistics import mean import json set api_key = call getenv string API_KEY set players = dict string alex string 80034246 ; string dan string 77947110 ; string elly string 91301985 ; string justin string 121774797 ; string kellen string 60514922 function get_dota_mmr user_id begin set na...
import requests import os from statistics import mean import json api_key = os.getenv('API_KEY') players = { "alex": "80034246", "dan": "77947110", "elly": "91301985", "justin": "121774797", "kellen": "60514922", } def get_dota_mmr(user_id): name = user_id.lower() if name in players: ...
Python
zaydzuhri_stack_edu_python
function changeOwnership self user recursive=0 begin set new = call ownerInfo user if new is none begin comment Special user! return end set old = call getOwnerTuple if not recursive begin if old == new or old is UnownableOwner begin return end end if recursive begin set children = call get attribute call aq_base self ...
def changeOwnership(self, user, recursive=0): new = ownerInfo(user) if new is None: return # Special user! old = self.getOwnerTuple() if not recursive: if old == new or old is UnownableOwner: return if recursive: children = g...
Python
nomic_cornstack_python_v1
function __init__ self filename bucket=none client=none version_id=none begin set _filename : str = filename set _seen_so_far : float = 0 set _lock = lock set _size : float = 0 if bucket and client begin if not version_id begin set _size = get call head_object Bucket=bucket Key=filename string ContentLength end else be...
def __init__( self, filename: str, bucket: str = None, client=None, version_id: str = None, ) -> None: self._filename: str = filename self._seen_so_far: float = 0 self._lock = threading.Lock() self._size: float = 0 if bucket and client:...
Python
nomic_cornstack_python_v1
function Subclasses cls sort_by=none reverse=false begin string Get all nested Constant class and it's name pair. :param sort_by: the attribute name used for sorting. :param reverse: if True, return in descend order. :returns: [(attr, value),...] pairs. :: >>> class MyClass(Constant): ... a = 1 # non-class attributre ....
def Subclasses(cls, sort_by=None, reverse=False): """Get all nested Constant class and it's name pair. :param sort_by: the attribute name used for sorting. :param reverse: if True, return in descend order. :returns: [(attr, value),...] pairs. :: >>> class MyClass(Const...
Python
jtatman_500k
string Day 7: The Sum of Its Parts import copy class VertexMapper begin function __init__ self begin set mapper = list end function function getNum self symbol begin if symbol in mapper begin return index mapper symbol end append mapper symbol return length mapper - 1 end function function getSymbol self num begin ret...
""" Day 7: The Sum of Its Parts """ import copy class VertexMapper: def __init__(self): self.mapper = [] def getNum(self, symbol): if symbol in self.mapper: return self.mapper.index(symbol) self.mapper.append(symbol) return len(self.mapper) - 1 def getSymbol(...
Python
zaydzuhri_stack_edu_python
function name_to_hex name spec=string css3 begin string Convert a color name to a normalized hexadecimal color value. The optional keyword argument ``spec`` determines which specification's list of color names will be used; valid values are ``html4``, ``css2``, ``css21`` and ``css3``, and the default is ``css3``. When ...
def name_to_hex(name, spec=u'css3'): """ Convert a color name to a normalized hexadecimal color value. The optional keyword argument ``spec`` determines which specification's list of color names will be used; valid values are ``html4``, ``css2``, ``css21`` and ``css3``, and the default is ``css...
Python
jtatman_500k
print string Operand 1:3, Operand 2:2 comment Addition print string Addition 3+2: 3 + 2 comment Subtraction print string Subtraction 3-2: 3 - 2 comment Multiplication print string Multiplication 3*2: 3 * 2 comment Division ->Gives the floating value (quotient) print string Division ->Gives the floating value (quotient)...
print('Operand 1:3, Operand 2:2') print('Addition 3+2: ',3+2) #Addition print('Subtraction 3-2: ',3-2) #Subtraction print('Multiplication 3*2: ',3*2) #Multiplication print('Division ->Gives the floating value (quotient) 3/2: ',3/2) #Division ->Gives the floating value (quotient) print('Modular Division ->Gives the rem...
Python
zaydzuhri_stack_edu_python
import smtplib function sendEmail begin set server = call SMTP string smtp.gmail.com 587 call ehlo call starttls comment Next, log in to the server call login string email string pass comment Send the mail comment The /n separates the message from the headers set msg = string Hello! call sendmail string jake.happersett...
import smtplib def sendEmail(): server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() #Next, log in to the server server.login("email", "pass") #Send the mail msg = "Hello!" # The /n separates the message from the headers server.sendmail("jake.happersett@gmail.com", "8042100901@msg.fi.g...
Python
zaydzuhri_stack_edu_python