code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function create_job_labels_report input_filepath
begin
set output_filepath = call _create_csv_filepath string jobs_qual_labels
to csv call parse_job_file input_filepath output_filepath
return output_filepath
end function | def create_job_labels_report(input_filepath: str) -> str:
output_filepath = _create_csv_filepath('jobs_qual_labels')
to_csv(parse_job_file(input_filepath), output_filepath)
return output_filepath | Python | nomic_cornstack_python_v1 |
function to_dataframe self count=none dtype=none drop_empty=true index_col=string Frame
begin
if has attribute self string ifp
begin
return call to_dataframe ifp interactions count=if expression count is none then count else count dtype=dtype drop_empty=drop_empty index_col=index_col
end
raise call AttributeError strin... | def to_dataframe(self, count=None, dtype=None, drop_empty=True, index_col="Frame"):
if hasattr(self, "ifp"):
return to_dataframe(
self.ifp,
self.interactions,
count=self.count if count is None else count,
dtype=dtype,
dr... | Python | nomic_cornstack_python_v1 |
set tuple a b v = map int split input
print v - a // a - b + if expression v - a % a - b != 0 then 2 else 1 | a, b, v = map(int, input().split())
print((v - a) // (a - b) + (2 if (v - a) % (a - b) != 0 else 1)) | Python | zaydzuhri_stack_edu_python |
function muc_set_affiliation self jid affiliation reason=none
begin
string Convenience wrapper around :meth:`.MUCClient.set_affiliation`. See there for details, and consider its `mucjid` argument to be set to :attr:`mucjid`.
return yield from call set_affiliation _mucjid jid affiliation reason=reason
end function | def muc_set_affiliation(self, jid, affiliation, *, reason=None):
"""
Convenience wrapper around :meth:`.MUCClient.set_affiliation`. See
there for details, and consider its `mucjid` argument to be set to
:attr:`mucjid`.
"""
return (yield from self.service.set_affiliation(
... | Python | jtatman_500k |
comment people=int(input("How many people ? \n"))
comment print("Insert time! ")
set people = integer input
set array = list map int split input
sort array
set min = 0
for i in range 0 people
begin
set min = min + people - i * array at i
end
print min | #people=int(input("How many people ? \n"))
#print("Insert time! ")
people=int(input())
array=list(map(int,input().split()))
array.sort()
min=0
for i in range(0,people):
min+=(people-i)*array[i]
print(min) | Python | zaydzuhri_stack_edu_python |
comment imports Modules
import pygame , sys , os
comment setup window
set mainClock = call Clock
from pygame.locals import *
call init
call set_caption string Adventure Game
set screen = call set_mode tuple 500 500 0 false
set rootDirectory = directory name path __file__
set imageDirectory = rootDirectory + string \img... | #imports Modules
import pygame, sys, os
#setup window
mainClock = pygame.time.Clock()
from pygame.locals import *
pygame.init()
pygame.display.set_caption("Adventure Game")
screen = pygame.display.set_mode((500,500),0,False)
rootDirectory = os.path.dirname(__file__)
imageDirectory = rootDirectory +'\\img'
textDirector... | Python | zaydzuhri_stack_edu_python |
function get_all_interfaces schema_obj
begin
set interfaces = list
for vendor in vendor_list
begin
for interface in interface_list
begin
append interfaces interface
end
end
return interfaces
end function | def get_all_interfaces(schema_obj):
interfaces = []
for vendor in schema_obj.vendor_list:
for interface in vendor.interface_list:
interfaces.append(interface)
return interfaces | Python | nomic_cornstack_python_v1 |
import sys
import yacc as hola
set tracebacklimit = 0
from MaquinaVitual import MaquinaVirtual
if length argv < 3
begin
print string ¡Bienvenido a Compy!. 🐬
print string Recuerda que el comando para ejecutar es:
print string Compy.py (Funcion:)Compilar o Ejecutar (Archivo:)Nombre.txt
end
if length argv == 3
begin
if s... | import sys
import yacc as hola
sys.tracebacklimit = 0
from MaquinaVitual import MaquinaVirtual
if(len(sys.argv) < 3):
print("¡Bienvenido a Compy!. 🐬")
print("Recuerda que el comando para ejecutar es:")
print("Compy.py (Funcion:)Compilar o Ejecutar (Archivo:)Nombre.txt")
if(len(sys.argv) == 3):
if(st... | Python | zaydzuhri_stack_edu_python |
function rot_axis_angle_to_ypr degrees q source
begin
set rotation_matrix = call get_rotmat call radians degrees q at 0 q at 1 q at 2
return call rotation_matrix_to_ypr matrix multiply rotation_matrix source
end function | def rot_axis_angle_to_ypr(degrees: float, q: Quaternion, source: np.ndarray) -> tuple:
rotation_matrix = get_rotmat(radians(degrees), q[0], q[1], q[2])
return rotation_matrix_to_ypr(np.matmul(rotation_matrix, source)) | Python | nomic_cornstack_python_v1 |
function keydown key
begin
if key == KEY_MAP at string up
begin
comment True for update logic to use image with flames
call thrusting true
end
else
if key == KEY_MAP at string left
begin
comment turn the ship counter-clockwise
call turn_ccw
end
else
if key == KEY_MAP at string right
begin
comment turn the ship counter-... | def keydown(key):
if key == simplegui.KEY_MAP["up"]:
# True for update logic to use image with flames
my_ship.thrusting(True)
elif key == simplegui.KEY_MAP["left"]:
# turn the ship counter-clockwise
my_ship.turn_ccw()
elif key == simplegui.KEY_MAP["right"]:
# turn ... | Python | nomic_cornstack_python_v1 |
function basicFeatureExtractorDigit datum
begin
set features = counter
for x in range DIGIT_DATUM_WIDTH
begin
for y in range DIGIT_DATUM_HEIGHT
begin
if call getPixel x y > 0
begin
set features at tuple x y = 1
end
else
begin
set features at tuple x y = 0
end
end
end
return features
end function | def basicFeatureExtractorDigit(datum):
features = util.Counter()
for x in range(DIGIT_DATUM_WIDTH):
for y in range(DIGIT_DATUM_HEIGHT):
if datum.getPixel(x, y) > 0:
features[(x,y)] = 1
else:
features[(x,y)] = 0
return features | Python | nomic_cornstack_python_v1 |
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn import svm , tree , linear_model , neighbors , naive_bayes , ensemble , discriminant_analysis , gaussian_process
from sklearn.metrics import accuracy_score
from sklearn.neural_network import MLPClassifier
from sklea... | import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn import svm, tree, linear_model, neighbors, naive_bayes, ensemble, discriminant_analysis, gaussian_process
from sklearn.metrics import accuracy_score
from sklearn.neural_network import MLPClassifier
from sklearn.ne... | Python | zaydzuhri_stack_edu_python |
function generate_orbit_chain orbiter
begin
if orbiter == string COM
begin
return list
end
set orbit_chain = list
set orbitee = string
while orbitee != string COM
begin
for orbit in orbits
begin
if orbit at 1 == orbiter
begin
set orbitee = orbit at 0
append orbit_chain orbitee
break
end
end
set orbiter = orbitee
end... | def generate_orbit_chain(orbiter):
if orbiter == "COM":
return []
orbit_chain = []
orbitee = ""
while orbitee != "COM":
for orbit in orbits:
if orbit[1] == orbiter:
orbitee = orbit[0]
orbit_chain.append(orbitee)
break
... | Python | zaydzuhri_stack_edu_python |
function value self
begin
comment pylint: disable=protected-access
return _val
end function | def value(self):
# pylint: disable=protected-access
return self.node.status._val | Python | nomic_cornstack_python_v1 |
import cv2 as cv
import sys
set img = call imread string /home/lajith/Downloads/ViratKohli.jpg
if img is none
begin
exit string Could not read the image
end
image show string Virat Kohli img
set k = call waitKey 0
if k == ordinal string s
begin
call imwrite string ViratKohli.jpg
end | import cv2 as cv
import sys
img = cv.imread("/home/lajith/Downloads/ViratKohli.jpg")
if img is None:
sys.exit("Could not read the image")
cv.imshow("Virat Kohli",img)
k=cv.waitKey(0)
if k==ord("s"):
cv.imwrite("ViratKohli.jpg") | Python | zaydzuhri_stack_edu_python |
function is_tree x_step y_step line y_pos stderr
begin
set debug = string { x_step } , { y_step }
if y_pos % y_step == 0
begin
set x_pos = integer y_pos / y_step * x_step % length strip line
if line at x_pos == string #
begin
write stderr debug + string %2d % x_pos + line at slice : x_pos : + string X + line at slice... | def is_tree(x_step, y_step, line, y_pos, stderr):
debug = f"{x_step},{y_step} "
if y_pos % y_step == 0:
x_pos = (int(y_pos / y_step) * x_step) % len(line.strip())
if line[x_pos] == "#":
stderr.write(debug + ("%2d " % x_pos)
+ line[:x_pos] + "X" + line[x_p... | Python | nomic_cornstack_python_v1 |
import numpy as np
import cv2
import time
comment 画图像包围框
function showbb img boundingbox
begin
comment img 是一种numpy格式的图像
set tuple x y w h = boundingbox
call rectangle img tuple integer x integer y tuple integer x + w integer y + h tuple 0 0 255
call showimg img
end function
comment 画图像
function showimg img
begin
image... | import numpy as np
import cv2
import time
# 画图像包围框
def showbb(img, boundingbox):
#img 是一种numpy格式的图像
x,y,w,h = boundingbox
cv2.rectangle(img, (int(x),int(y)),(int(x+w), int(y+h)), (0,0,255))
showimg(img)
# 画图像
def showimg(img):
cv2.imshow('image', img)
cv2.waitKey(0)
| Python | zaydzuhri_stack_edu_python |
function __init__ self
begin
set symbol_table_class = dict
set symbol_table_subroutine = dict
end function | def __init__(self):
self.symbol_table_class = {}
self.symbol_table_subroutine = {} | Python | nomic_cornstack_python_v1 |
comment target.py
comment by Josh Pedro
comment January 4th, 2019
import graphics
from graphics import *
function main
begin
set win = call GraphWin string snowman and Christmas tree 900 900
set torso = call Circle call Point 200 550 160
call setFill string White
call setOutline string black
call draw win
set body = ca... | #target.py
#by Josh Pedro
#January 4th, 2019
import graphics
from graphics import *
def main():
win = GraphWin("snowman and Christmas tree", 900,900)
torso = Circle(Point(200, 550), 160 )
torso.setFill("White")
torso.setOutline("black")
torso.draw(win)
body = Circle(Point(200, 350), 110)
bod... | Python | zaydzuhri_stack_edu_python |
function test_add_one_document_object_implicit_commit self
begin
set user_id = call get_rand_string
set data = call get_rand_string
set id = call get_rand_string
set doc = call Document
set doc at string user_id = user_id
set doc at string data = data
set doc at string id = id
comment Commit the changes
add conn true d... | def test_add_one_document_object_implicit_commit(self):
user_id = get_rand_string()
data = get_rand_string()
id = get_rand_string()
doc = Document()
doc["user_id"] = user_id
doc["data"] = data
doc["id"] = id
# Commit the changes
self.con... | Python | nomic_cornstack_python_v1 |
function to_datetime timestamp timezone=none
begin
try
begin
if is instance timestamp datetime
begin
return timestamp
end
try
begin
set timestamp = decimal timestamp
end
except Exception as e
begin
warning string Exception parsing { timestamp } to datetime: { e }
return call fromtimestamp 0
end
comment Really big Webki... | def to_datetime(timestamp, timezone=None):
try:
if isinstance(timestamp, datetime.datetime):
return timestamp
try:
timestamp = float(timestamp)
except Exception as e:
log.warning(f'Exception parsing {timestamp} to datetime: {e}')
return dateti... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Vector Class Note: we use deg rather than rad, for human @author: yl
from functools import wraps
import numpy as np
from numpy import pi
from tool import strnum
from ylcompat import py2
set rad2deg = lambda rad -> rad / pi * 180
set deg2rad = lambda deg -> deg / 180 * pi
comment TOD... | # -*- coding: utf-8 -*-
"""
Vector Class
Note:
we use deg rather than rad, for human
@author: yl
"""
from functools import wraps
import numpy as np
from numpy import pi
from ..tool import strnum
from ..ylcompat import py2
rad2deg = lambda rad: rad / pi * 180
deg2rad = lambda deg: deg / 180 * pi
# TODO mv to y... | Python | zaydzuhri_stack_edu_python |
function get_links url
begin
set browser = call Chrome string mysite/polls/tests/chromedriver/chromedriver.exe
get browser url
set elements = call find_elements_by_tag_name string a
set links = list comprehension call get_attribute string href for element in elements
close browser
return links
end function | def get_links(url):
browser = webdriver.Chrome('mysite/polls/tests/chromedriver/chromedriver.exe')
browser.get(url)
elements = browser.find_elements_by_tag_name('a')
links = [element.get_attribute('href') for element in elements]
browser.close()
return links | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Fri Jul 19 10:08:39 2019 @author: irinasm
import cv2
import numpy as np
function save path image jpg_quality=none png_compression=none
begin
string persist :image: object to disk. if path is given, load() first. jpg_quality: for jpeg only. 0 ... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 19 10:08:39 2019
@author: irinasm
"""
import cv2
import numpy as np
def save(path, image, jpg_quality=None, png_compression=None):
'''
persist :image: object to disk. if path is given, load() first.
jpg_quality: for jpeg only. 0 - 100... | Python | zaydzuhri_stack_edu_python |
function load_modules_from_yaml self
begin
set modules = dict
set yaml = call load_modules_file
comment pylint: disable=lost-exception
try
begin
set locations = yaml at string modules
set modules = locations at location
end
except KeyError
begin
info string configuration for location %s not found, using default locati... | def load_modules_from_yaml(self):
modules = {}
yaml = self.load_modules_file()
# pylint: disable=lost-exception
try:
locations = yaml['modules']
modules = locations[self.location]
except KeyError:
self.logger.info('configuration for location ... | Python | nomic_cornstack_python_v1 |
function test_create_empty_board_one_dimensional
begin
set board = call generate_board_from_moves one_dimensional=true
assert length board == ROWS * COLS
assert count board none == ROWS * COLS
end function | def test_create_empty_board_one_dimensional():
board = generate_board_from_moves(one_dimensional=True)
assert len(board) == ROWS * COLS
assert board.count(None) == ROWS * COLS | Python | nomic_cornstack_python_v1 |
function test_InputCurrent_Error_test self test_dict
begin
set output = call Output simu=test_dict at string test_obj
with assert raises InputError msg=string Expect: + test_dict at string exp as context
begin
call gen_input
end
assert equal test_dict at string exp string exception
end function | def test_InputCurrent_Error_test(self, test_dict):
output = Output(simu=test_dict["test_obj"])
with self.assertRaises(
InputError, msg="Expect: " + test_dict["exp"]
) as context:
output.simu.input.gen_input()
self.assertEqual(test_dict["exp"], str(context.exceptio... | Python | nomic_cornstack_python_v1 |
function my_dashboard request
begin
if not is_authenticated
begin
comment todo find a way to do this with permission class or fix on the front end, context:
comment options call is not sending the cookie after login so using IsAuthenticated returns a 403
comment and we get a CORS not happy with a non-ok status, but lat... | def my_dashboard(request):
if not request.user.is_authenticated:
# todo find a way to do this with permission class or fix on the front end, context:
# options call is not sending the cookie after login so using IsAuthenticated returns a 403
# and we get a CORS not happy with a non-ok status... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Thu Aug 19 11:36:31 2021 @author: franc
function directions ciudad barrio calle
begin
print string Su dirección de referencia es:
print string Su ciudad es: ciudad
print string el sector es: barrio
print string el sector es: calle
end function
set ci = input string Ingres... | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 19 11:36:31 2021
@author: franc
"""
def directions(ciudad, barrio, calle):
print("Su dirección de referencia es:")
print("Su ciudad es:", ciudad)
print("el sector es:", barrio)
print("el sector es:", calle)
ci=input("Ingrese la ciudad:")... | Python | zaydzuhri_stack_edu_python |
function delete_container self ContainerName
begin
pass
end function | def delete_container(self, ContainerName: str) -> Dict:
pass | Python | nomic_cornstack_python_v1 |
function operations_happening_at_same_time_as self scheduled_operation
begin
set overlaps = query self time=time duration=duration
return list comprehension e for e in overlaps if e != scheduled_operation
end function | def operations_happening_at_same_time_as(
self, scheduled_operation: ScheduledOperation
) -> List[ScheduledOperation]:
overlaps = self.query(
time=scheduled_operation.time,
duration=scheduled_operation.duration)
return [e for e in overlaps if e != scheduled_operation] | Python | nomic_cornstack_python_v1 |
import unittest
from getEmailByNonRegex import is_email , get_emails , get_accounts
class TestGetEmailByRegex extends TestCase
begin
function test_is_email self
begin
assert equal call is_email string abcd_aisu123@gmail.com true
end function
function test_get_emails self
begin
set paragraph = string ajskasjdkf asdfoig ... | import unittest
from getEmailByNonRegex import is_email, get_emails, get_accounts
class TestGetEmailByRegex(unittest.TestCase):
def test_is_email(self):
self.assertEqual(is_email("abcd_aisu123@gmail.com"), True)
def test_get_emails(self):
paragraph = "ajskasjdkf asdfoig asdf1234@kkbox.com and 395ajkd0@gmail.co... | Python | zaydzuhri_stack_edu_python |
import xlsxwriter
set workbook = call Workbook string demo2.xlsx
set work_sheet = call add_worksheet string 消费记录
comment 数据样式
comment 加粗 红色字体 字体大小20
set format_dic = dict string bold true ; string font_color string #DC143C ; string font_size 20
set text_format = call add_format format_dic
comment 数据写入
comment 头部写入
set ... | import xlsxwriter
workbook = xlsxwriter.Workbook("demo2.xlsx")
work_sheet = workbook.add_worksheet("消费记录")
##数据样式
#加粗 红色字体 字体大小20
format_dic = {
"bold":True,
"font_color":"#DC143C",
"font_size":20
}
text_format = workbook.add_format(format_dic)
##数据写入
#头部写入
header = ["门票总额","旅途总费用","购物消费","年消费总额"]
for co... | Python | zaydzuhri_stack_edu_python |
function calculate_log_latent corex X
begin
set Xm = call masked_equal X missing_values
set tuple n_samples n_visible = shape
set tuple n_hidden dim_hidden ram = tuple n_hidden dim_hidden ram
set log_p_y_given_x_unnorm = call empty tuple n_hidden n_samples dim_hidden
comment GB
set memory_size = decimal n_samples * n_v... | def calculate_log_latent(corex, X):
Xm = ma.masked_equal(X, corex.missing_values)
n_samples, n_visible = Xm.shape
n_hidden, dim_hidden, ram = corex.n_hidden, corex.dim_hidden, corex.ram
log_p_y_given_x_unnorm = np.empty((n_hidden, n_samples, dim_hidden))
memory_size = float(n_samples * n_visible * n... | Python | nomic_cornstack_python_v1 |
function _coerce_loc_index divisions o
begin
if divisions and is instance divisions at 0 datetime
begin
return timestamp pd o
end
if divisions and is instance divisions at 0 datetime64
begin
return as type call datetime64 o dtype
end
return o
end function | def _coerce_loc_index(divisions, o):
if divisions and isinstance(divisions[0], datetime):
return pd.Timestamp(o)
if divisions and isinstance(divisions[0], np.datetime64):
return np.datetime64(o).astype(divisions[0].dtype)
return o | Python | nomic_cornstack_python_v1 |
from werkzeug.exceptions import NotFound
from flask import Blueprint , render_template , redirect , url_for
from flask_login import current_user , login_user , logout_user
from logging import getLogger
from homework_06.views.auth_methods import *
comment Все страницы раздела auth (авторизация и содержание, доступное то... | from werkzeug.exceptions import NotFound
from flask import Blueprint, render_template, redirect, url_for
from flask_login import current_user, login_user, logout_user
from logging import getLogger
from homework_06.views.auth_methods import *
# Все страницы раздела auth (авторизация и содержание, доступное только авто... | Python | zaydzuhri_stack_edu_python |
function isValidLocation location
begin
if string .. in location
begin
return 1
end
else
if string / in location
begin
return 1
end
else
if length set location == 1 and location at 0 == string
begin
return 0
end
else
if length set location == 0
begin
return 0
end
end function | def isValidLocation(location):
if (".." in location):
return 1
elif ("/" in location):
return 1
elif (len(set(location))==1 and location[0]==' '):
return 0
elif (len(set(location))==0):
return 0 | Python | nomic_cornstack_python_v1 |
function _prepare_cookies self command url
begin
string Extract cookies from the requests session and add them to the command
set req = call Request
set method = string GET
set url = url
set cookie_values = call get_cookie_header cookies req
if cookie_values
begin
call _add_cookies command cookie_values
end
end functio... | def _prepare_cookies(self, command, url):
"""
Extract cookies from the requests session and add them to the command
"""
req = requests.models.Request()
req.method = 'GET'
req.url = url
cookie_values = requests.cookies.get_cookie_header(
self.session.... | Python | jtatman_500k |
comment !/usr/bin/env python
comment Sozi - A presentation tool using the SVG standard
comment Copyright (C) 2010-2012 Guillaume Savaton
comment This program is dual licensed under the terms of the MIT license
comment or the GNU General Public License (GPL) version 3.
comment A copy of both licenses is provided in the ... | #!/usr/bin/env python
# Sozi - A presentation tool using the SVG standard
#
# Copyright (C) 2010-2012 Guillaume Savaton
#
# This program is dual licensed under the terms of the MIT license
# or the GNU General Public License (GPL) version 3.
# A copy of both licenses is provided in the doc/ folder of the
# official re... | Python | zaydzuhri_stack_edu_python |
function delete connection redis_key
begin
delete redis_key
end function | def delete(connection, redis_key):
connection.delete(redis_key) | Python | nomic_cornstack_python_v1 |
from turtle import *
import turtle
setup turtle 650 350 200 200
call pu
call fd - 250
call pd
call pensize 5
call pencolor string black
call fd 500
call done | from turtle import *
import turtle
turtle.setup(650,350,200,200)
pu()
fd(-250)
pd()
pensize(5)
pencolor("black")
fd(500)
done() | Python | zaydzuhri_stack_edu_python |
function plotEmiss self tem_min=1000 tem_max=30000 ionic_abund=1.0 den=1000.0 style=string - legend_loc=4 temLog=false plot_total=false plot_only_total=false legend=true total_color=string black total_label=string TOTAL
begin
if not INSTALLED at string plt
begin
error string Matplotlib not available, no plot calling=ca... | def plotEmiss(self, tem_min=1000, tem_max=30000, ionic_abund=1.0, den=1e3, style='-',
legend_loc=4, temLog=False, plot_total=False, plot_only_total=False, legend=True,
total_color='black', total_label='TOTAL'):
if not pn.config.INSTALLED['plt']:
pn.log_.error('M... | Python | nomic_cornstack_python_v1 |
function perturb_action_for_exploration_purposes self action_info
begin
raise call ValueError string Must be implemented
end function | def perturb_action_for_exploration_purposes(self, action_info):
raise ValueError("Must be implemented") | Python | nomic_cornstack_python_v1 |
from lab1_proto import *
import lab1_tools as tools
import numpy as np
import matplotlib.pyplot as plt
from sklearn.mixture import GaussianMixture
from scipy.cluster import hierarchy
from random import randint
comment Load data (utterances of digits) and example
set data = load np string Labs/Lab1/lab1_data.npz allow_p... | from lab1_proto import *
import lab1_tools as tools
import numpy as np
import matplotlib.pyplot as plt
from sklearn.mixture import GaussianMixture
from scipy.cluster import hierarchy
from random import randint
# Load data (utterances of digits) and example
data = np.load('Labs/Lab1/lab1_data.npz', allow_pickle=True)['... | Python | zaydzuhri_stack_edu_python |
function get_noised_result self sample_state global_state add_noise=true
begin
comment print("Average Query get_noised_result")
set tuple noised_sum new_sum_global_state = call get_noised_result sample_state sum_state add_noise
set new_global_state = call _GlobalState new_sum_global_state denominator
function normalize... | def get_noised_result(self, sample_state, global_state, add_noise=True):
#print("Average Query get_noised_result")
noised_sum, new_sum_global_state = self._numerator.get_noised_result(
sample_state, global_state.sum_state, add_noise)
new_global_state = self._GlobalState(
new_sum_global_state... | Python | nomic_cornstack_python_v1 |
from typing import Dict , List
import pandas as pd
function get_dash_dropdown_options values labels
begin
return list comprehension dict string label label ; string value value for tuple value label in zip values labels
end function
function get_map_from_url_to_name df column
begin
set df_unique = call drop_duplicates
... | from typing import Dict, List
import pandas as pd
def get_dash_dropdown_options(values: List[str], labels: List[str]) -> List[Dict[str, str]]:
return [
{"label": label, "value": value} for value, label in zip(values, labels)
]
def get_map_from_url_to_name(df: pd.DataFrame, column: str) -> Dict[str... | Python | zaydzuhri_stack_edu_python |
function concat_immediate self other
begin
concat other
end function | def concat_immediate(self, other: "Linked[T]") -> None:
self.forward.concat(other) | Python | nomic_cornstack_python_v1 |
function check_close v1 v2 eps
begin
return norm v1 - v2 < eps or norm v1 + v2 < eps
end function | def check_close(v1, v2, eps):
return norm(v1-v2) < eps or norm(v1+v2) < eps | Python | nomic_cornstack_python_v1 |
function execute self cursor=none sql_executor=none **kwargs
begin
raise NotImplementedError
end function | def execute(self, cursor=None, sql_executor=None, **kwargs):
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
function get_keys self
begin
info ME + string .get_keys()
set tmp_primary_keys = list
set tmp_data_keys = list
try
begin
set tmp_primary_keys = split get config ME string primary_keys string ,
set tmp_data_keys = split get config ME string data_keys string ,
comment FIXME: this is bad
set index_key = get config ME st... | def get_keys(self):
self._logger.info(ME + '.get_keys()')
tmp_primary_keys = []
tmp_data_keys = []
try:
tmp_primary_keys = config.get(ME, 'primary_keys').split(',')
tmp_data_keys = config.get(ME, 'data_keys').split(',')
self.index_key = config.get(ME,... | Python | nomic_cornstack_python_v1 |
comment you can write to stdout for debugging purposes, e.g.
comment print "this is a debug message"
comment this solution can be done in O(1) space
comment my solution uses O(n) space since I chose
comment not to rotate the array in place
function solution A K
begin
set arrSz = length A
set answer = list
comment rota... | # you can write to stdout for debugging purposes, e.g.
# print "this is a debug message"
# this solution can be done in O(1) space
# my solution uses O(n) space since I chose
# not to rotate the array in place
def solution(A, K):
arrSz = len(A)
answer = []
# rotating the array K times in this
... | Python | zaydzuhri_stack_edu_python |
function pre_process_data_set df
begin
replace df list inf - inf nan
set df at df == inf = nan
set df = call remove_bad_columns df
set df = call fill_na df
set df = call convert_factorial_to_numerical df
comment Remove columns only containing 0
set df = df at any
return df
end function | def pre_process_data_set(df):
df.replace([np.inf, -np.inf], np.nan)
df[df == np.inf] = np.nan
df = remove_bad_columns(df)
df = fill_na(df)
df = convert_factorial_to_numerical(df)
# Remove columns only containing 0
df = df[(df.T != 0).any()]
return df | Python | nomic_cornstack_python_v1 |
import math
from FKLS import *
import matplotlib as mpl
import pylab as pl
import Image , ImageDraw | import math
from FKLS import *
import matplotlib as mpl
import pylab as pl
import Image,ImageDraw
| Python | zaydzuhri_stack_edu_python |
function metrics_roce cmd_ctx cpc **options
begin
call execute_cmd lambda -> call cmd_metrics_roce cmd_ctx cpc options
end function | def metrics_roce(cmd_ctx, cpc, **options):
cmd_ctx.execute_cmd(lambda: cmd_metrics_roce(cmd_ctx, cpc, options)) | Python | nomic_cornstack_python_v1 |
function double_check_attribute object setter backup_attribute custom_error_text=none
begin
string Check if a parameter to be used is None, if it is, then check the specified backup attribute and throw an error if it is also None. Args: object: The original object setter: Any input object backup_attribute (str): Attrib... | def double_check_attribute(object, setter, backup_attribute, custom_error_text=None):
"""Check if a parameter to be used is None, if it is, then check the specified backup attribute and throw
an error if it is also None.
Args:
object: The original object
setter: Any input object
bac... | Python | jtatman_500k |
function normalize v prefix=none
begin
set normalized = join _STREAM_SEP generator expression call normalize_segment seg prefix=prefix for seg in split v _STREAM_SEP
comment Validate the resulting string.
call validate_stream_name normalized
return normalized
end function | def normalize(v, prefix=None):
normalized = _STREAM_SEP.join(
normalize_segment(seg, prefix=prefix) for seg in v.split(_STREAM_SEP))
# Validate the resulting string.
validate_stream_name(normalized)
return normalized | Python | nomic_cornstack_python_v1 |
function get_current_lectures course_info username password instance_info=none save_lectures=none
begin
if instance_info is none
begin
set instance_info = call get_current_instance course_info
end
comment home_link looks like:
comment http://class.coursera.org/<short_name><suffix>
comment where the suffix indicates whi... | def get_current_lectures(course_info, username, password,
instance_info=None, save_lectures=None):
if instance_info is None:
instance_info = get_current_instance(course_info)
# home_link looks like:
# http://class.coursera.org/<short_name><suffix>
# where the suffix in... | Python | nomic_cornstack_python_v1 |
comment Definition for singly-linked list.
class ListNode extends object
begin
function __init__ self val=0 next=none
begin
set val = val
set next = next
end function
end class
class Solution extends object
begin
function summation self num1 num2
begin
return num1 + num2
end function
function convert_to_number self lis... | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def summation(self,num1, num2):
return num1+num2
def convert_to_number(self, list_val):
'''
:type list_... | Python | zaydzuhri_stack_edu_python |
function test_nested_three_ordered_max_unordered_max_block_max_no_bq1_with_li1
begin
comment Arrange
set source_markdown = string 1. + > list 1. item
set expected_tokens = list string [olist(1,4):.:1:9: ] string [ulist(1,10):+::14: ] string [block-quote(1,15): : > ] string [para(1,17):] string [text(1,17):list:] string... | def test_nested_three_ordered_max_unordered_max_block_max_no_bq1_with_li1():
# Arrange
source_markdown = """ 1. + > list
1. item"""
expected_tokens = [
"[olist(1,4):.:1:9: ]",
"[ulist(1,10):+::14: ]",
"[block-quote(1,15): : > ... | Python | nomic_cornstack_python_v1 |
import keras.backend as K
from keras.preprocessing import image
from config import *
import os
import numpy as np
import tensorflow as tf
import re
class load_data extends object
begin
function __init__ self mode
begin
string Initialize the load_data class Store the file_path, disparity_path and its mode ('train', 'tes... | import keras.backend as K
from keras.preprocessing import image
from config import *
import os
import numpy as np
import tensorflow as tf
import re
class load_data(object):
def __init__(self, mode):
"""
Initialize the load_data class
Store the file_path, disparity_path and its mode ('train... | Python | zaydzuhri_stack_edu_python |
function ADI file=string ./ADI_HPM.fits datafile=string /mnt/data0/isabel/mec/HD1160/data_HD1160.yml outfile=string /mnt/data0/isabel/mec/HD1160/out_HD1160.yml cfgfile=string /mnt/data0/isabel/mec/HD1160/pipe_HD1160.yml temporal_file_derot=string /mnt/data0/isabel/mec/HD1160/HD1160_temporal.fits temporal_file=string /m... | def ADI(file='./ADI_HPM.fits', datafile = '/mnt/data0/isabel/mec/HD1160/data_HD1160.yml', outfile = '/mnt/data0/isabel/mec/HD1160/out_HD1160.yml',
cfgfile = '/mnt/data0/isabel/mec/HD1160/pipe_HD1160.yml', temporal_file_derot='/mnt/data0/isabel/mec/HD1160/HD1160_temporal.fits',
temporal_file='/mnt/data0/... | Python | nomic_cornstack_python_v1 |
function clean_edges self
begin
for from_node in call all_nodes
begin
for to_node in call all_nodes
begin
if from_node == to_node
begin
continue
end
set dup = list filter lambda x -> from_node == from_node and to_node == to_node edges
if length dup > 1
begin
for d in dup at slice 1 : :
begin
remove edges d
end
end
en... | def clean_edges(self):
for from_node in self.all_nodes():
for to_node in self.all_nodes():
if from_node == to_node:
continue
dup = list(filter(lambda x: x.from_node == from_node and x.to_node == to_node, self.edges))
if len(dup) > 1... | Python | nomic_cornstack_python_v1 |
comment Haiku
import random
set wordList1 = list string Enchanting string Amazing string Colourful string Delightful string Delicate
set wordList2 = list string visions string distance string conscience string process string chaos
set wordList3 = list string superstitious string contrasting string graceful string invit... | #Haiku
import random
wordList1 = ["Enchanting", "Amazing", "Colourful", "Delightful", "Delicate"]
wordList2 = ["visions", "distance", "conscience", "process", "chaos"]
wordList3 = ["superstitious", "contrasting", "graceful", "inviting", "contradicting", "overwhelming"]
wordList4 = ["true", "dark", "cold", "warm", ... | Python | zaydzuhri_stack_edu_python |
function first_value self
begin
Ellipsis
end function | def first_value(self) -> Any:
... | Python | nomic_cornstack_python_v1 |
function cost_derivative self output_activations y
begin
return output_activations - y
end function | def cost_derivative(self, output_activations, y):
return (output_activations-y) | Python | nomic_cornstack_python_v1 |
comment Get a list of all transactions belong to the user
function get_all_transactions user start_date end_date
begin
set transactions = list
for card in cards
begin
for transaction in transactions
begin
set transaction_datetime = timestamp
if transaction_datetime >= start_date and transaction_datetime <= end_date
be... | # Get a list of all transactions belong to the user
def get_all_transactions(user, start_date, end_date):
transactions = []
for card in user.cards:
for transaction in card.transactions:
transaction_datetime = transaction.timestamp
if transaction_datetime >= start_date and transac... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python2
import sys
import struct
import datetime
comment You can use this method to exit on failure conditions.
function bork msg
begin
exit msg
end function
comment Some constants. You shouldn't need to change these.
set MAGIC = 2343432205
set VERSION = 1
set SECTION_ASCII = 1
set SECTION_UTF8 = ... | #!/usr/bin/env python2
import sys
import struct
import datetime
# You can use this method to exit on failure conditions.
def bork(msg):
sys.exit(msg)
# Some constants. You shouldn't need to change these.
MAGIC = 0x8BADF00D
VERSION = 1
SECTION_ASCII = 0x1
SECTION_UTF8 = 0x2
SECTION_WORDS = 0x3
SECTION_DWORDS =... | Python | zaydzuhri_stack_edu_python |
import sys
function versionCompare v1 v2
begin
comment Breakdown by version major, minor, and revision number
set ver1 = split v1 string .
set ver2 = split v2 string .
comment Initiator
set i = 0
while i < length ver1
begin
comment Version 2 is higher
if integer ver2 at i > integer ver1 at i
begin
return - 1
end
commen... | import sys
def versionCompare(v1, v2):
# Breakdown by version major, minor, and revision number
ver1 = v1.split(".")
ver2 = v2.split(".")
# Initiator
i = 0
while(i < len(ver1)):
# Version 2 is higher
if int(ver2[i]) > int(ver1[i]):
return -1
# ... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment coding: utf-8
comment In[16]:
from constants import *
import csv
import json as json
import pandas as pd
from IPython.display import display , HTML
set chiroptera_dataset_filepath = string ../data/note_chiroptera_database.csv
comment In[17]:
function read_data_file file_path
begin
s... | #!/usr/bin/env python
# coding: utf-8
# In[16]:
from constants import *
import csv
import json as json
import pandas as pd
from IPython.display import display, HTML
chiroptera_dataset_filepath = "../data/note_chiroptera_database.csv"
# In[17]:
def read_data_file(file_path):
dataset = []
with open(file_pat... | Python | zaydzuhri_stack_edu_python |
async function GET_AsyncInfo request
begin
call request request
set app = apps
set answer = dict
set answer at string bucket_stats = app at string bucket_stats
set resp = call json_response answer
call response request resp=resp
return resp
end function | async def GET_AsyncInfo(request):
log.request(request)
app = request.apps
answer = {}
answer["bucket_stats"] = app["bucket_stats"]
resp = json_response(answer)
log.response(request, resp=resp)
return resp | Python | nomic_cornstack_python_v1 |
function _get_authorization_header cosmos_client_connection verb path resource_id_or_fullname is_name_based resource_type headers
begin
comment In the AuthorizationToken generation logic, lower casing of ResourceID is required
comment as rest of the fields are lower cased. Lower casing should not be done for named
comm... | def _get_authorization_header(
cosmos_client_connection, verb, path, resource_id_or_fullname, is_name_based, resource_type, headers
):
# In the AuthorizationToken generation logic, lower casing of ResourceID is required
# as rest of the fields are lower cased. Lower casing should not be done for named
... | Python | nomic_cornstack_python_v1 |
comment #!/usr/bin/python
comment # -*- coding: utf-8 -*-
import math
from collections import namedtuple
import networkx as nx
import random
from functools import lru_cache
import math
import time
import random
import pdb
from datetime import datetime
from collections import namedtuple
from sklearn.metrics.pairwise imp... | # #!/usr/bin/python
# # -*- coding: utf-8 -*-
#
import math
from collections import namedtuple
import networkx as nx
import random
from functools import lru_cache
import math
import time
import random
import pdb
from datetime import datetime
from collections import namedtuple
from sklearn.metrics.pairwise import euclid... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Wed Jun 6 21:00:56 2018 @author: xinhui
comment class Solution:
comment def searchInsert(self, nums, target):
comment """
comment :type nums: List[int]
comment :type target: int
comment :rtype: int
comment """
comment try:
comment return nums... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 6 21:00:56 2018
@author: xinhui
"""
#class Solution:
# def searchInsert(self, nums, target):
# """
# :type nums: List[int]
# :type target: int
# :rtype: int
# """
# try:
# return nums.index(... | Python | zaydzuhri_stack_edu_python |
function get_expr_date self
begin
return date_added + time delta minutes=saleDuration
end function | def get_expr_date(self):
return self.date_added + dt.timedelta(minutes = self.saleDuration) | Python | nomic_cornstack_python_v1 |
function tags self
begin
return get pulumi self string tags
end function | def tags(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]:
return pulumi.get(self, "tags") | Python | nomic_cornstack_python_v1 |
comment https://www.acmicpc.net/problem/5988
comment 첫 번째 줄에 숫자의 개수 N을 입력합니다.
comment 1 <= N <= 100
set N = integer input
comment 숫자의 개수만큼 반복합니다.
for i in range N
begin
comment 홀수인지 짝수인지 확인할 정수 K를 입력합니다.
comment 1 <= K <= 10^60
set K = integer input
comment K를 2로 나누었을 때 나머지가 0이라면
if K % 2 == 0
begin
comment 짝수이므로 even을... | # https://www.acmicpc.net/problem/5988
# 첫 번째 줄에 숫자의 개수 N을 입력합니다.
# 1 <= N <= 100
N = int(input())
# 숫자의 개수만큼 반복합니다.
for i in range(N):
# 홀수인지 짝수인지 확인할 정수 K를 입력합니다.
# 1 <= K <= 10^60
K = int(input())
# K를 2로 나누었을 때 나머지가 0이라면
if K % 2 == 0:
# 짝수이므로 even을 출력합니다.
print("even")
# ... | Python | zaydzuhri_stack_edu_python |
function is_it_inside graph end start
begin
set stack = list start
set visited = list start
while stack
begin
set node = pop stack
if node == end
begin
return true
end
if node not in graph
begin
continue
end
for neighbors in graph at node
begin
if neighbors not in visited
begin
append stack neighbors
append visited nei... | def is_it_inside(graph, end, start):
stack = [start]
visited = [start]
while stack:
node = stack.pop()
if node == end:
return True
if node not in graph:
continue
for neighbors in graph[node]:
if neighbors not in visited:
stack.append(neighbors)
v... | Python | zaydzuhri_stack_edu_python |
function catalog_key catalog_name=DEFAULT_CATALOG_NAME
begin
return call Key string Catalog catalog_name
end function | def catalog_key(catalog_name=DEFAULT_CATALOG_NAME):
return ndb.Key('Catalog', catalog_name) | Python | nomic_cornstack_python_v1 |
if 0 < a and 0 < b
begin
print string Positive
end
else
if a <= 0 and 0 <= b or 0 <= a and b <= 0
begin
print string Zero
end
else
if b - a + 1 % 2 == 0
begin
print string Positive
end
else
begin
print string Negative
end | if 0 < a and 0 < b:
print('Positive')
elif a <= 0 and 0 <= b or 0 <= a and b <= 0:
print('Zero')
else:
if (b - a + 1) % 2 == 0:
print('Positive')
else:
print('Negative') | Python | zaydzuhri_stack_edu_python |
function setWeather self type turns=- 1 forever=true
begin
set weather = call buildWeatherFromType type self turns=turns forever=forever
set messages = call getStartMessage
return messages
end function | def setWeather(self, type, turns=-1, forever=True):
self.weather = WeatherFactory.buildWeatherFromType(type, self, turns=turns, forever=forever)
messages = self.weather.getStartMessage()
return messages | Python | nomic_cornstack_python_v1 |
function release self
begin
if locked == 0
begin
raise exception string this lock is not locked
end
call PyThread_release_lock lock
set locked = 0
end function | def release(self):
if self.locked == 0:
raise Exception('this lock is not locked')
PyThread_release_lock(self.lock)
self.locked = 0 | Python | nomic_cornstack_python_v1 |
function body_traces df frame=0
begin
set traces = list scatter go x=list loc at tuple frame string Nose_x loc at tuple frame string LeftEye_x loc at tuple frame string RightEye_x loc at tuple frame string Nose_x y=list loc at tuple frame string Nose_y loc at tuple frame string LeftEye_y loc at tuple frame string Right... | def body_traces(df, frame=0):
traces = [
# Head traces
go.Scatter(
x=[df.loc[frame, 'Nose_x'], df.loc[frame, 'LeftEye_x'], df.loc[frame, 'RightEye_x'], df.loc[frame, 'Nose_x']],
y=[df.loc[frame, 'Nose_y'], df.loc[frame, 'LeftEye_y'], df.loc[frame, 'RightEy... | Python | nomic_cornstack_python_v1 |
function maxIncreaseKeepingSkyline self grid
begin
string :type grid: List[List[int]] :rtype: int
set num = 0
for i in range 0 length grid
begin
for j in range 0 length grid
begin
set num = num + min max grid at i max list comprehension x at j for x in grid - grid at i at j
end
end
return num
end function
string Best S... | def maxIncreaseKeepingSkyline(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
num=0
for i in range(0,len(grid)):
for j in range(0,len(grid)):
num+=min(max(grid[i]),max([x[j] for x in grid]))-grid[i][j]
return num
'''
Best Solutions
1.
def maxIncreaseKeepingSkyline(self, grid):
row, c... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding:utf8 -*-
from bs4 import BeautifulSoup
from bs4 import UnicodeDammit
import re
import urllib2
import sys
import datetime
set _Done = 0
function chose_site choice
begin
if lower choice == string python
begin
return string http://wenda60.com/testdetail/leaderboard/tid-29
en... | #!/usr/bin/env python
#-*- coding:utf8 -*-
from bs4 import BeautifulSoup
from bs4 import UnicodeDammit
import re
import urllib2
import sys
import datetime
_Done = 0
def chose_site(choice):
if choice.lower() == "python":
return "http://wenda60.com/testdetail/leaderboard/tid-29"
if choice.lower() == "c+... | Python | zaydzuhri_stack_edu_python |
from itertools import permutations
function solve n m w_list lv_list
begin
set min_v = min list comprehension lv at 1 for lv in lv_list
set max_w = max w_list
if max_w > min_v
begin
return - 1
end
set w_dict = dictionary
comment pow
for i in range 1 2 ^ n
begin
set w = 0
for j in range n
begin
if i ? 2 ^ j
begin
set w ... | from itertools import permutations
def solve(n, m, w_list, lv_list):
min_v = min([lv[1] for lv in lv_list])
max_w = max(w_list)
if max_w > min_v:
return -1
w_dict = dict()
# pow
for i in range(1, 2 ** n):
w = 0
for j in range(n):
if i & (2 ** j):
... | Python | zaydzuhri_stack_edu_python |
comment Copyright © 2012-2013 BlackDragonHunt
comment This file is part of the Super Duper Script Editor.
comment The Super Duper Script Editor is free software: you can redistribute it
comment and/or modify it under the terms of the GNU General Public License as
comment published by the Free Software Foundation, eithe... | ### Copyright © 2012-2013 BlackDragonHunt
###
### This file is part of the Super Duper Script Editor.
###
### The Super Duper Script Editor is free software: you can redistribute it
### and/or modify it under the terms of the GNU General Public License as
### published by the Free Software Foundation, either version ... | Python | iamtarun_python_18k_alpaca |
class Solution
begin
function maxVowels self s k
begin
set vowels = string aeiou
set max_vowels = length list comprehension c for c in s at slice : k : if c in vowels
set curr = length list comprehension c for c in s at slice : k : if c in vowels
for tuple index c in enumerate s at slice k : : k
begin
if c in vow... | class Solution:
def maxVowels(self, s: str, k: int) -> int:
vowels = 'aeiou'
max_vowels = curr = len([c for c in s[:k] if c in vowels])
for index, c in enumerate(s[k:], k):
if c in vowels:
curr += 1
if s[index - k] in vowels:
curr -= 1
... | Python | zaydzuhri_stack_edu_python |
function changeXML request
begin
if call is_ajax
begin
set mod_xml = call change_XML get POST string origXML none get POST string refDict none
return call HttpResponse mod_xml
end
end function | def changeXML(request):
if request.is_ajax():
mod_xml = change_XML(request.POST.get("origXML", None), request.POST.get("refDict", None))
return HttpResponse(mod_xml) | Python | nomic_cornstack_python_v1 |
comment Input : My name is not Aman
comment Output : 4 (Size of Aman is 4)
set str1 = split input
set x = length str1
print length str1 at x - 1
comment Another method
print length split input at - 1 | #Input : My name is not Aman
#Output : 4 (Size of Aman is 4)
str1 = input().split()
x = len(str1)
print(len(str1[x-1]))
#Another method
print(len(input().split()[-1]))
| Python | zaydzuhri_stack_edu_python |
import time
import calendar
import pandas as pd
import numpy as np
from datetime import date
set CITY_DATA = dict string chicago string ./Project 2 - Bikeshare Data/chicago.csv ; string new york city string ./Project 2 - Bikeshare Data/new_york_city.csv ; string washington string ./Project 2 - Bikeshare Data/washington... | import time
import calendar
import pandas as pd
import numpy as np
from datetime import date
CITY_DATA = { 'chicago': './Project 2 - Bikeshare Data/chicago.csv',
'new york city': './Project 2 - Bikeshare Data/new_york_city.csv',
'washington': './Project 2 - Bikeshare Data/washington.csv' }... | Python | zaydzuhri_stack_edu_python |
function linucb self
begin
while true
begin
set context = yield
set context = call matrix context
set matrix_ainv_tmp = array list comprehension call get_model at string matrix_ainv at action for action in _actions
set theta_tmp = array list comprehension call get_model at string theta at action for action in _actions
... | def linucb(self):
while True:
context = yield
context = np.matrix(context)
matrix_ainv_tmp = np.array(
[self._modelstorage.get_model()['matrix_ainv'][action] for action in self._actions])
theta_tmp = np.array([self._modelstorage.get_model()['theta'... | Python | nomic_cornstack_python_v1 |
comment Reference - http://stackoverflow.com/questions/8548030/why-does-pip-install-inside-python-raise-a-syntaxerror
comment import pip
comment pip.main(['install','textblob'])
comment pip.main(['install','matplotlib'])
comment To do sentiment Analysis on the collected 10k tweets, plot histogram and calculate average ... | #Reference - http://stackoverflow.com/questions/8548030/why-does-pip-install-inside-python-raise-a-syntaxerror
#import pip
#pip.main(['install','textblob'])
#pip.main(['install','matplotlib'])
#To do sentiment Analysis on the collected 10k tweets, plot histogram and calculate average subjectivity and polarity
#Referen... | Python | zaydzuhri_stack_edu_python |
import pylab as pl
set X = range 10
set y = range 11 21
scatter pl X y c=string r
show
print | import pylab as pl
X = range(10)
y = range(11,21)
pl.scatter(X,y, c='r')
pl.show()
print
| Python | zaydzuhri_stack_edu_python |
comment User function Template for python3
function transpose matrix n
begin
comment code here
set tmp = 0
for i in range n
begin
for j in range i + 1 n
begin
set tmp = matrix at i at j
set matrix at i at j = matrix at j at i
set matrix at j at i = tmp
end
end
end function
comment {
comment Driver Code Starts
comment I... | #User function Template for python3
def transpose(matrix, n):
# code here
tmp = 0
for i in range(n):
for j in range(i+1,n):
tmp = matrix[i][j]
matrix[i][j] = matrix[j][i]
matrix[j][i] = tmp
#{
# Driver Code Starts
#Initial Template for Pyth... | Python | zaydzuhri_stack_edu_python |
function requestredirect function
begin
function wrapped self id *args
begin
try
begin
set server = call get_imaging_server id
end
except NotFound
begin
raise call notfound
end
if server != get config string server string fqdn
begin
raise call found string http://%s%s % tuple server path
end
return call function self i... | def requestredirect(function):
def wrapped(self, id, *args):
try:
server = self.db.requests.get_imaging_server(id)
except exceptions.NotFound:
raise web.notfound()
if server != config.get('server', 'fqdn'):
raise web.found("http://%s%s" % (server, web.ctx.... | Python | nomic_cornstack_python_v1 |
from django.db import models
comment Create your models here.
comment property type is choices so we have to create choices like this -- hitesh
set property_type = tuple tuple string Sale string sale tuple string Rent string rent
class Property extends Model
begin
set name = call CharField max_length=50
set property_ty... | from django.db import models
# Create your models here.
#property type is choices so we have to create choices like this -- hitesh
property_type = (
('Sale' , "sale"),
('Rent' , "rent")
)
class Property(models.Model):
name = models.CharField(max_length=50)
property_type = models.CharField(choices=pro... | Python | zaydzuhri_stack_edu_python |
function discover_satellite cli deploy=true timeout=5
begin
string Looks to make sure a satellite exists, returns endpoint First makes sure we have dotcloud account credentials. Then it looks up the environment for the satellite app. This will contain host and port to construct an endpoint. However, if app doesn't exis... | def discover_satellite(cli, deploy=True, timeout=5):
"""Looks to make sure a satellite exists, returns endpoint
First makes sure we have dotcloud account credentials. Then it looks
up the environment for the satellite app. This will contain host and
port to construct an endpoint. However, if app doesn'... | Python | jtatman_500k |
function config_is_reboot_required config_uuid
begin
return integer uuid config_uuid ? CONFIG_REBOOT_REQUIRED
end function | def config_is_reboot_required(config_uuid):
return int(uuid.UUID(config_uuid)) & constants.CONFIG_REBOOT_REQUIRED | Python | nomic_cornstack_python_v1 |
function __init__ self id_esquina x y latitud longitud
begin
set id_esquina = id_esquina
set x = x
set y = y
set latitud = latitud
set longitud = longitud
end function | def __init__ (self,id_esquina,x,y,latitud,longitud):
self.id_esquina = id_esquina
self.x = x
self.y = y
self.latitud = latitud
self.longitud = longitud | Python | nomic_cornstack_python_v1 |
string Project Euler Problem 7 Find the 10 001st prime number
from math import sqrt
function isPrime primeList num
begin
for prime in primeList
begin
if prime == 2
begin
continue
end
else
if prime > square root num
begin
break
end
else
if num % prime == 0
begin
return false
end
end
return true
end function
function mai... | '''Project Euler Problem 7
Find the 10 001st prime number'''
from math import sqrt
def isPrime(primeList, num):
for prime in primeList:
if prime == 2:
continue
elif(prime > sqrt(num)):
break
elif(num%prime==0):
return False
return True
def main():
prime = [2, ]
i = 1
while len(prime) < 10001:
... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.