code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function __could_edit self slug
begin
string Test if the user could edit the page.
set page_rec = call get_by_uid slug
if not page_rec
begin
return false
end
if call check_post_role at string EDIT
begin
return true
end
else
if user_name == user_name
begin
return true
end
else
begin
return false
end
end function | def __could_edit(self, slug):
'''
Test if the user could edit the page.
'''
page_rec = MWiki.get_by_uid(slug)
if not page_rec:
return False
if self.check_post_role()['EDIT']:
return True
elif page_rec.user_name == self.userinfo.user_name:
... | Python | jtatman_500k |
function fprop self inputs
begin
return call fprop call fprop inputs
end function | def fprop(self, inputs):
return self.nonlinearity.fprop(self.convolution.fprop(inputs)) | Python | nomic_cornstack_python_v1 |
function load_key bl_cmd key_size key_file_path ser
begin
comment open file to read it as a string
set key_file = open key_file_path string r
set key_hex_str_size = key_size * 2
comment verify key file contains a hex string with length that matches expected key length
set file_content = read key_file
if length file_con... | def load_key(bl_cmd, key_size, key_file_path, ser):
# open file to read it as a string
key_file = open(key_file_path, 'r')
key_hex_str_size = key_size * 2
# verify key file contains a hex string with length that matches expected key length
file_content = key_file.read()
if len(file_content) ... | Python | nomic_cornstack_python_v1 |
function insert cls available_parking_space
begin
call validate
set redis = call StrictRedis connection_pool=redis_pool
call hmset AVAILABLE_PARKING + plate call to_record entity=available_parking_space
info dict string message string new parking space has been put into pool ; string parking_space available_parking_spa... | def insert(cls, available_parking_space):
available_parking_space.validate()
redis = _redis.StrictRedis(connection_pool=redis_pool)
redis.hmset(
AVAILABLE_PARKING + available_parking_space.plate,
AvailableParkingSpaceMapper.to_record(entity=available_parking_space)
... | Python | nomic_cornstack_python_v1 |
function delete_configuration_handler event context
begin
call configure_logging
call configure_dynamodb
end function | def delete_configuration_handler(event, context):
configure_logging()
configure_dynamodb()
| Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Mon Feb 1 17:09:00 2016 @author: 3200404
from soccersimulator import SoccerAction
from soccersimulator import Vector2D
from soccersimulator import settings
import math
import random
comment miroir position
function miroir_p p
begin
return call Vector2D GAME_WIDTH - x y
en... | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 1 17:09:00 2016
@author: 3200404
"""
from soccersimulator import SoccerAction
from soccersimulator import Vector2D
from soccersimulator import settings
import math
import random
def miroir_p(p): # miroir position
return Vector2D( settings.GAME_WIDTH - p.x,p... | Python | zaydzuhri_stack_edu_python |
function canny_detection_of_edges image_filename plot=true
begin
set current_image = call imread DS_PATH + image_filename
set edges = call canny current_image
comment plotting the edges of canny algorithm
if plot
begin
set tuple figure tuple ax1 ax2 = call subplots 1 2
call suptitle string Canny edge detector fontsize=... | def canny_detection_of_edges(image_filename, plot=True):
current_image = plt.imread(DS_PATH + image_filename)
edges = skimage.feature.canny(current_image)
# plotting the edges of canny algorithm
if plot:
figure, (ax1, ax2) = plt.subplots(1, 2)
figure.suptitle("Canny edge detector", font... | Python | nomic_cornstack_python_v1 |
function list self
begin
set response = get requests base_url
if not ok
begin
raise call ServerException format string {}: {} status_code text
end
return dictionary comprehension get host string name : list comprehension get log string key for log in get host string logs for host in get json response string list
end fu... | def list(self):
response = requests.get(self.base_url)
if not response.ok:
raise ServerException(
'{}: {}'.format(response.status_code, response.text))
return {
host.get('name'): [
log.get('key')
for log
in... | Python | nomic_cornstack_python_v1 |
function is_any_item_moving items
begin
for tuple _ bbox in items items
begin
if status == string move
begin
return true
end
end
return false
end function | def is_any_item_moving(items):
for _, bbox in items.items():
if bbox.status == 'move':
return True
return False | Python | nomic_cornstack_python_v1 |
set s = decimal input string Qual o salário do funcionário? R$
set a = decimal input string Qual o aumento percentual? %
set sca = s + s * a / 100
print format string O valor do salário após o aumento de {}% será de R${} a sca | s = float(input('Qual o salário do funcionário? R$'))
a = float(input('Qual o aumento percentual? %'))
sca = s + (s * (a/100))
print('O valor do salário após o aumento de {}% será de R${}'.format(a,sca))
| Python | zaydzuhri_stack_edu_python |
function _get_model_type self model_descr
begin
set tuple app_label model = split lower model_descr string .
return get objects app_label=app_label model=model
end function | def _get_model_type(self, model_descr):
app_label, model = model_descr.lower().split(".")
return ContentType.objects.get(app_label=app_label, model=model) | Python | nomic_cornstack_python_v1 |
function best_classifier df output vectorizer_factory classifier_factories
begin
set accuracies = list comprehension list for _ in classifier_factories
set N_SPLITS = 5
set kf = call KFold n_splits=N_SPLITS shuffle=true
for tuple fold tuple train_indices test_indices in enumerate split kf df
begin
print string Started... | def best_classifier(df, output, vectorizer_factory, classifier_factories):
accuracies = [[] for _ in classifier_factories]
N_SPLITS = 5
kf = KFold(n_splits=N_SPLITS, shuffle=True)
for fold, (train_indices, test_indices) in enumerate(kf.split(df)):
print(f"Started evaluating fold {fold + 1... | Python | nomic_cornstack_python_v1 |
comment cmd .\.venvs\lpthw\Scripts\activate 转到虚拟空间
comment cmd cd 到存放文件目录
comment python hello_name.py
comment 浏览器打开 http://127.0.0.1:5000/hello
comment 把Zhang改成任意就可以看见对你的输入进行hello
comment 打开http://127.0.0.1:5000/hello?name=Zhang
from flask import Flask
from flask import render_template
from flask import request
commen... | # cmd .\.venvs\lpthw\Scripts\activate 转到虚拟空间
# cmd cd 到存放文件目录
# python hello_name.py
# 浏览器打开 http://127.0.0.1:5000/hello
# 把Zhang改成任意就可以看见对你的输入进行hello
# 打开http://127.0.0.1:5000/hello?name=Zhang
from flask import Flask
from flask import render_template
from flask import request
# 这个函数知道如何去template/目录加载模板.html文件,这是flask... | Python | zaydzuhri_stack_edu_python |
from math import factorial
set tuple w h = map int split input
set mod = 10 ^ 9 + 7
function calc n r
begin
set tuple x y = tuple 1 1
for i in range r
begin
set x = x * n - i % mod
set y = y * i + 1 % mod
end
return x * power y mod - 2 mod % mod
end function
print call calc w + h - 2 w - 1 | from math import factorial
w, h = map(int, input().split())
mod = 10 ** 9 + 7
def calc(n, r):
x, y = 1, 1
for i in range(r):
x = x * (n - i) % mod
y = y * (i + 1) % mod
return x * pow(y, mod - 2, mod) % mod
print(calc(w + h - 2, w - 1)) | Python | zaydzuhri_stack_edu_python |
function T_bright2RJ nu T
begin
comment nu [GHz] ; t [#K]
set x = h_over_k * nu / T
set g = x / call expm1 x
return g * T
end function | def T_bright2RJ(nu, T):
x = h_over_k * nu / T # nu [GHz] ; t [#K]
g = x / np.expm1(x)
return g * T | Python | nomic_cornstack_python_v1 |
from Crypto.Cipher import AES
comment Este es el vector de inicialización, debe ser el mismo para encriptar y desencriptar
set iv = string IVV's12345667890
function encrypt key message iv
begin
string Función para cifrar con una llave de 16, 32 o 64 bytes
set encryptionSuite = call new key MODE_CFB iv
set encryptedMess... | from Crypto.Cipher import AES
#Este es el vector de inicialización, debe ser el mismo para encriptar y desencriptar
iv="IVV's12345667890"
def encrypt(key,message,iv):
'''Función para cifrar con una llave de 16, 32 o 64 bytes'''
encryptionSuite=AES.new(key, AES.MODE_CFB, iv)
encryptedMessage=encryptionSuite.encrypt... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
comment @File : LeetCode100.py
comment @Author : Runpeng Zhang
comment @Date : 2020/2/19
comment @Desc : 判断两颗二叉树是否相同
from collections import deque
comment Definition for a binary tree node.
class TreeNode
begin
function __init__ self x
begin
set val = x
set left = none
set right = none
end... | # -*- coding: utf-8 -*-
# @File : LeetCode100.py
# @Author : Runpeng Zhang
# @Date : 2020/2/19
# @Desc : 判断两颗二叉树是否相同
from collections import deque
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Sol... | Python | zaydzuhri_stack_edu_python |
function addPrice item_price
begin
set item_price = item_price + 25
print string Item price inside function : item_price
end function
set item_price = 10
print string Item Price Before calling method : item_price
call addPrice item_price
print string Item Price After calling method : item_price | def addPrice(item_price):
item_price += 25
print("Item price inside function : ",item_price)
item_price = 10
print("Item Price Before calling method : ",item_price)
addPrice(item_price)
print("Item Price After calling method : ",item_price) | Python | zaydzuhri_stack_edu_python |
comment Engineers: Sean Duback, Robert Geoffrion
comment School: Weber State University
comment Project: Motion Tracking
comment Year: 2019 Academic Year
comment Engineer: Michael Lewson
comment School: Chapman University
comment Year: 2021
comment Converts .png image into excel file
comment filename is for the name of... | #Engineers: Sean Duback, Robert Geoffrion
#School: Weber State University
#Project: Motion Tracking
#Year: 2019 Academic Year
#Engineer: Michael Lewson
#School: Chapman University
#Year: 2021
#Converts .png image into excel file
#filename is for the name of the picture
#fillEmptyWithZeros determines whether the white... | Python | zaydzuhri_stack_edu_python |
function to_text self p
begin
set rs = call xpath string .//w:t
return join string list comprehension text for r in rs
end function | def to_text(self, p):
rs = p._element.xpath('.//w:t')
return u" ".join([r.text for r in rs]) | Python | nomic_cornstack_python_v1 |
function plot_graph_route G route bbox=none fig_height=6 fig_width=none margin=0.02 bgcolor=string w axis_off=true show=true save=false close=true file_format=string png filename=string temp dpi=300 annotate=false node_color=string #999999 node_size=15 node_alpha=1 node_edgecolor=string none node_zorder=1 edge_color=st... | def plot_graph_route(
G,
route,
bbox=None,
fig_height=6,
fig_width=None,
margin=0.02,
bgcolor="w",
axis_off=True,
show=True,
save=False,
close=True,
file_format="png",
filename="temp",
dpi=300,
annotate=False,
node_color="#999999",
node_size=15,
no... | Python | nomic_cornstack_python_v1 |
comment Day 36 of 100 days of code
comment Random Algorithm
comment Function to check prime
function checkPrime num
begin
if num == 1
begin
return true
end
else
if num == 0
begin
return false
end
else
begin
for x in range 2 num
begin
if num % x == 0
begin
return false
end
end
end
return true
end function
comment Functi... | ## Day 36 of 100 days of code
#Random Algorithm
#Function to check prime
def checkPrime(num):
if num == 1 :
return True
elif num == 0:
return False
else:
for x in range(2,num):
if num%x ==0:
return False
return True
#Function to check prime in... | Python | zaydzuhri_stack_edu_python |
function test_1 self num
begin
set test_list = list
for r in range num
begin
append test_list tuple integer random integer 0 64 size=1 integer random integer 0 128 size=1
end
set RST = 24
comment 128x64 display with hardware I2C:
set disp = call SSD1306_128_64 rst=RST
comment Initialize library.
call begin
comment Cle... | def test_1(self, num):
test_list = []
for r in range(num):
test_list.append((int(np.random.randint(0, 64, size=1)), int(np.random.randint(0, 128, size=1))))
RST = 24
# 128x64 display with hardware I2C:
disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)
... | Python | nomic_cornstack_python_v1 |
function test_abl1_query query_handler num_sources normalized_abl1
begin
comment Search
set resp = search string ncbigene:25 keyed=true
set matches = resp at string source_matches
assert length matches == num_sources
assert matches at string HGNC at string match_type == XREF
assert matches at string Ensembl at string m... | def test_abl1_query(query_handler, num_sources, normalized_abl1):
# Search
resp = query_handler.search('ncbigene:25', keyed=True)
matches = resp['source_matches']
assert len(matches) == num_sources
assert matches['HGNC']['match_type'] == MatchType.XREF
assert matches['Ensembl']['match_type'] == ... | Python | nomic_cornstack_python_v1 |
function test_classify_cuisine self
begin
pass
end function | def test_classify_cuisine(self):
pass | Python | nomic_cornstack_python_v1 |
string a piece of code to iterate over classifiers
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import BernoulliNB
from sklearn.naive_bayes import Gaussia... | ''' a piece of code to iterate over classifiers '''
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import BernoulliNB
from sklearn.naive_bayes import Gauss... | Python | zaydzuhri_stack_edu_python |
async function add self ctx target
begin
if length mentions > 0
begin
set messages = await flatten call history limit=123
set user = mentions at 0
if author == user
begin
await call send string What kind of sad person would quote themself?
return
end
set lastmsg = get utils messages channel=channel author=user
if lastm... | async def add(self,ctx,target):
if len(ctx.message.mentions) > 0:
messages = await ctx.history(limit=123).flatten()
user = ctx.message.mentions[0]
if ctx.message.author == user:
await ctx.send("What kind of sad person would quote themself?")
return
lastmsg = discord.utils.get(messages,chann... | Python | nomic_cornstack_python_v1 |
function get_date
begin
set latest_known_show_date = EPOCH
try
begin
with open string date.txt string r as f
begin
set str_file_time = read f
set file_date = string parse time strip str_file_time string %d/%m/%Y
set latest_known_show_date = if expression file_date > latest_known_show_date then file_date else latest_kno... | def get_date():
latest_known_show_date = EPOCH
try:
with open("date.txt", "r") as f:
str_file_time = f.read()
file_date = datetime.strptime(str_file_time.strip(), '%d/%m/%Y')
latest_known_show_date = file_date if file_date > latest_known_show_date else latest_known_sh... | Python | nomic_cornstack_python_v1 |
function convert_to_numeric str_value
begin
try
begin
return integer str_value
end
except ValueError
begin
try
begin
return decimal str_value
end
except ValueError
begin
pass
end
end
return str_value
end function | def convert_to_numeric(str_value):
try:
return int(str_value)
except ValueError:
try:
return float(str_value)
except ValueError:
pass
return str_value | Python | nomic_cornstack_python_v1 |
import sys
set s = set list comprehension split x at 0 + string for x in read lines stdin
print length s
print join string sorted list s | import sys
s = set([x.split()[0] + "\n" for x in sys.stdin.readlines()])
print(len(s))
print("".join(sorted(list(s))))
| Python | zaydzuhri_stack_edu_python |
from apps.highschools import controllers
import settings
import pandas as pds
function test_csv_loading
begin
set data = call read_highschools_csv_data highschools_csv_path
assert data at string Etablissement at 0 == string LYCEE PIERRE-GILLES DE GENNES
assert length data == 16210
end function
function test_columns_ext... | from apps.highschools import controllers
import settings
import pandas as pds
def test_csv_loading():
data = controllers.read_highschools_csv_data(settings.highschools_csv_path)
assert (data['Etablissement'][0]) == "LYCEE PIERRE-GILLES DE GENNES"
assert len(data) == 16210
def test_columns_extraction():
... | Python | zaydzuhri_stack_edu_python |
while n % 2 == 0
begin
set n = n / 2
set answer = answer + 1
end
set f = open string cultout.txt string w
write f string integer n + string + string answer
close f | while n%2 == 0:
n /= 2
answer += 1
f = open('cultout.txt', 'w')
f.write(str(int(n)) + " " + str(answer))
f.close()
| Python | zaydzuhri_stack_edu_python |
function dec self string
begin
return call make_str string
end function | def dec(self, string):
return click.utils.make_str(string) | Python | nomic_cornstack_python_v1 |
function _get_next_occurrence haystack offset needles
begin
string Find next occurence of one of the needles in the haystack :return: tuple of (index, needle found) or: None if no needle was found
comment make map of first char to full needle (only works if all needles
comment have different first characters)
set first... | def _get_next_occurrence(haystack, offset, needles):
"""
Find next occurence of one of the needles in the haystack
:return: tuple of (index, needle found)
or: None if no needle was found"""
# make map of first char to full needle (only works if all needles
# have di... | Python | jtatman_500k |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Tue Dec 4 17:25:24 2018 @author: labfluidos
function product x
begin
set total = 1
for i in x
begin
set total = total * i
end
print total
return total
end function
product list 4 5 5 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 4 17:25:24 2018
@author: labfluidos
"""
def product(x):
total = 1
for i in x:
total = total*i
print(total)
return total
product([4, 5, 5]) | Python | zaydzuhri_stack_edu_python |
function display self
begin
print
print
for tuple j h in enumerate horizontals
begin
set line = string
for tuple i area in enumerate areas
begin
if not is instance area int
begin
set value = v
end
if value == 0
begin
set line = line + string + string -
end
else
if is_fix
begin
set line = line + string + string value... | def display(self):
print()
print()
for j, h in enumerate(self.horizontals):
line = '\t\t\t'
for i, area in enumerate(h.areas):
if not isinstance(area, int):
value = area.v
if value == 0:
line += ' ' +... | Python | nomic_cornstack_python_v1 |
function setAutoGainControlLevel self channel group threshold target attack gain unitCode=0
begin
set threshold = if expression convertDb then call linear2db threshold else threshold
set target = if expression convertDb then call linear2db target else target
set gain = if expression convertDb then call linear2db gain e... | def setAutoGainControlLevel(self, channel, group, threshold, target, attack, gain, unitCode=0):
threshold = linear2db(threshold) if self.convertDb else threshold
target = linear2db(target) if self.convertDb else target
gain = linear2db(gain) if self.convertDb else gain
resp = self.XAPCom... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Thu Dec 13 12:50:16 2018 @author: Casper
comment def gcd(a,b):
comment if a>=b:
comment temp=b
comment else:
comment temp=a
comment while True:
comment if a>=b:
comment if a % temp ==0 and b % temp==0:
comment return temp
comment else:
comment if temp>1:
comment temp-=1
c... | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 13 12:50:16 2018
@author: Casper
"""
#def gcd(a,b):
# if a>=b:
# temp=b
# else:
# temp=a
# while True:
#
# if a>=b:
# if a % temp ==0 and b % temp==0:
# return temp
# else:
# ... | Python | zaydzuhri_stack_edu_python |
comment noqa:DAR101,DAR201
function reference prefix identifier
begin
return call jsonify call _get_identifier prefix identifier
end function | def reference(prefix: str, identifier: str): # noqa:DAR101,DAR201
return jsonify(_get_identifier(prefix, identifier)) | Python | nomic_cornstack_python_v1 |
import os
import sys
set args = argv
set my_file = args at 1
set model_file = args at 2
function parse_file file_name
begin
set f = open file_name
set table = list
for line in f
begin
set row = split line string ,
if strip row at 0 == string
begin
continue
end
append table row
end
close f
return table
end function
se... | import os
import sys
args = sys.argv
my_file = args[1]
model_file = args[2]
def parse_file(file_name):
f = open(file_name)
table = []
for line in f:
row = line.split(',')
if row[0].strip() == '':
continue
table.append(row)
f.close()
return table
my_table = parse_file(my_file)
model_table = parse_f... | Python | zaydzuhri_stack_edu_python |
function createInvFileHash invFileHash docList
begin
set id = docList at string id
for term in docList at string terms
begin
if term
begin
if term at 0 in invFileHash
begin
set invFileHash at term at 0 at 0 = invFileHash at term at 0 at 0 + 1
append invFileHash at term at 0 at 1 list id term at 1
end
else
begin
set inv... | def createInvFileHash(invFileHash, docList):
id = docList['id']
for term in docList['terms']:
if (term):
if (term[0] in invFileHash):
invFileHash[term[0]][0] += 1
invFileHash[term[0]][1].append([id, term[1]])
else:
invFileHash[term[... | Python | nomic_cornstack_python_v1 |
function svd matrix rank=none
begin
if ndim != 2
begin
raise call ValueError format string Input should be a two-dimensional array. matrix.ndim is {} != 2 ndim
end
set tuple dim_1 dim_2 = shape
if dim_1 <= dim_2
begin
set min_dim = dim_1
end
else
begin
set min_dim = dim_2
end
if rank is none or rank >= min_dim
begin
co... | def svd(matrix, rank=None):
if matrix.ndim != 2:
raise ValueError('Input should be a two-dimensional array. matrix.ndim is {} != 2'.format(matrix.ndim))
dim_1, dim_2 = matrix.shape
if dim_1 <= dim_2:
min_dim = dim_1
else:
min_dim = dim_2
if rank is None or rank >= min_dim:
... | Python | nomic_cornstack_python_v1 |
set strings = list string BaNaNa string OrAnGe string ChOcOlAtE string ApPlE string MaNgO string StRaWbErRy string KiWi string BlUeBeRrY string Pineapple string Lemonade
set sorted_array = sorted strings reverse=true
print sorted_array at 1
print sorted_array at - 2 | strings = ['BaNaNa', 'OrAnGe', 'ChOcOlAtE', 'ApPlE', 'MaNgO', 'StRaWbErRy', 'KiWi', 'BlUeBeRrY', 'Pineapple', 'Lemonade']
sorted_array = sorted(strings, reverse=True)
print(sorted_array[1])
print(sorted_array[-2])
| Python | jtatman_500k |
comment !/usr/bin/env python
import optparse
import sys
import copy
from collections import defaultdict
import nltk
import numpy as np
import cPickle
import itertools
import pdb
import time
set ZERO_THRESH = 1e-12
set RENORMALIZATION_THRESH = 1e-06
call seterr divide=string ignore
set f_data = string data/hansards.f
se... | #!/usr/bin/env python
import optparse
import sys
import copy
from collections import defaultdict
import nltk
import numpy as np
import cPickle
import itertools
import pdb
import time
ZERO_THRESH = 1e-12
RENORMALIZATION_THRESH = 1e-6
np.seterr(divide = 'ignore')
f_data = "data/hansards.f"
e_data = "data/hansards.e"
bi... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding:utf-8 -*-
import requests
import time
function main
begin
set url = string http://www.wandoujia.com
set headers_dict = dict string connection string Keep-Alive
set r = get requests url headers=headers_dict
comment print r.status_code
comment print r.content
comment print ... | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import requests
import time
def main():
url = "http://www.wandoujia.com"
headers_dict = {"connection": "Keep-Alive"}
r = requests.get(url, headers=headers_dict)
# print r.status_code
# print r.content
# print r.encoding
# print r.text
# r... | Python | zaydzuhri_stack_edu_python |
comment 활용3-1. How to handle scroll
from selenium import webdriver
set browser = call Chrome
comment browser.maximize_window()
comment < page movement >
set url = string https://play.google.com/store/movies/top
get browser url
comment < Scroll down to the designated location[coordinates] >
comment browser.execute_scrip... | # 활용3-1. How to handle scroll
from selenium import webdriver
browser = webdriver.Chrome()
# browser.maximize_window()
# < page movement >
url = "https://play.google.com/store/movies/top"
browser.get(url)
# < Scroll down to the designated location[coordinates] >
# browser.execute_script("window.scrollTo(0,... | Python | zaydzuhri_stack_edu_python |
import socket
comment basic socket-to-file server
comment waits to be connected to, then dumps everything coming over
comment the socket into a file
comment empherial port
set DEFAULT_PORT = 9877
set BUFFER_SIZE = 1024 * 8
set fileName = string example
comment addr = IP of host
comment fileout = file to dump data to
co... | import socket
# basic socket-to-file server
#
# waits to be connected to, then dumps everything coming over
# the socket into a file
DEFAULT_PORT = 9877 # empherial port
BUFFER_SIZE = 1024 * 8
fileName = "example"
# addr = IP of host
# fileout = file to dump data to
# port = port part of TCP address
def datadump(a... | Python | zaydzuhri_stack_edu_python |
function set_data self data type_check
begin
if not type_check
begin
call _set_data data
end
else
begin
call _set_data_after_check data
end
end function | def set_data(self, data, type_check):
if not type_check:
self._set_data(data)
else:
self._set_data_after_check(data) | Python | nomic_cornstack_python_v1 |
function input_fn params
begin
set batch_size = params at string batch_size
comment For training, we want a lot of parallel reading and shuffling.
comment For eval, we want no shuffling and parallel reading doesn't matter.
set d = call TFRecordDataset input_file
if is_training
begin
set d = repeat
set d = shuffle d buf... | def input_fn(params):
batch_size = params["batch_size"]
# For training, we want a lot of parallel reading and shuffling.
# For eval, we want no shuffling and parallel reading doesn't matter.
d = tf.data.TFRecordDataset(input_file)
if is_training:
d = d.repeat()
d = d.shuff... | Python | nomic_cornstack_python_v1 |
from sklearn import preprocessing
import numpy as np
from sklearn.preprocessing import LabelEncoder , OneHotEncoder
comment X_str = [ 'media_attached', 'mature', 'mature_image', 'mature_video','image']
comment X_str.append('test')
set X_str = list list string media_attached list string mature list string mature_image l... | from sklearn import preprocessing
import numpy as np
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
# X_str = [ 'media_attached', 'mature', 'mature_image', 'mature_video','image']
# X_str.append('test')
X_str = ([[ 'media_attached'], ['mature'], ['mature_image'], ['mature_video'],['image']])
X_str.appen... | Python | zaydzuhri_stack_edu_python |
from rest_framework import serializers
from blog.models import article , author , category
class DynamicFieldsModelSerializer extends ModelSerializer
begin
string A ModelSerializer that takes an additional `fields` argument that controls which fields should be displayed.
function __init__ self *args **kwargs
begin
comm... | from rest_framework import serializers
from blog.models import article , author, category
class DynamicFieldsModelSerializer(serializers.ModelSerializer):
"""
A ModelSerializer that takes an additional `fields` argument that
controls which fields should be displayed.
"""
def __init__(self, *args, ... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import matplotlib.pyplot as plt
import csv
set df = read csv string all_data.csv
set topics = unique
set df at string publishedAt = call to_datetime df at string publishedAt
set table = dict
for topic in topics
begin
set creative = loc at df at string videoLicense == string creativeCommon ? df at s... | import pandas as pd
import matplotlib.pyplot as plt
import csv
df = pd.read_csv('all_data.csv')
topics = df['topic'].unique()
df['publishedAt'] = pd.to_datetime(df['publishedAt'])
table = {}
for topic in topics:
creative = df.loc[(df['videoLicense'] == 'creativeCommon') & (df['topic'] == topic)]
youtube =... | Python | zaydzuhri_stack_edu_python |
import requests
import bs4
set page = get requests string https://referensi.data.kemdikbud.go.id/index11.php?kode=010101&level=3
set soup = call BeautifulSoup text string lxml
set table = find soup string table id=string example
set headers = list comprehension text for heading in find all table string th
set table_row... | import requests
import bs4
page = requests.get(
'https://referensi.data.kemdikbud.go.id/index11.php?kode=010101&level=3')
soup = bs4.BeautifulSoup(page.text, 'lxml')
table = soup.find('table', id="example")
headers = [heading.text for heading in table.find_all('th')]
table_rows = [row for row in table.find_all... | Python | zaydzuhri_stack_edu_python |
function eh_primo num
begin
set nao_primo = true
set t = 2
if num == 2
begin
return true
end
if num % t != 0 and num != 1
begin
set t = t + 1
while t < num
begin
if num % t != 0
begin
set t = t + 2
end
else
begin
return false
end
end
return true
set nao_primo = false
end
else
begin
return false
end
end function
functio... | def eh_primo(num):
nao_primo = True
t = 2
if num == 2:
return True
if num % t != 0 and num != 1:
t += 1
while t < num:
if num % t != 0:
t += 2
else:
return False
return True
nao_primo = Fals... | Python | zaydzuhri_stack_edu_python |
string 7.取近似值 接受一个正浮点数 输出该数值的近似整数值 如果小数点后数值大于等于5,向上取整;小于5,则向下取整 | """
7.取近似值
接受一个正浮点数
输出该数值的近似整数值
如果小数点后数值大于等于5,向上取整;小于5,则向下取整
""" | Python | zaydzuhri_stack_edu_python |
comment IMPORTS
import numpy
from sklearn import ensemble
import sklearn
from sklearn.preprocessing import Imputer
import matplotlib.pyplot as plt
comment CONSTANTS
set N_TREES = 5
comment FUNCTIONS I NEED ####################################################################################
function return_real_data
beg... | # IMPORTS
import numpy
from sklearn import ensemble
import sklearn
from sklearn.preprocessing import Imputer
import matplotlib.pyplot as plt
# CONSTANTS
N_TREES = 5
################# FUNCTIONS I NEED ####################################################################################
def return_real_data():
"""
Th... | Python | zaydzuhri_stack_edu_python |
from math import sqrt
set x = 5
set vals = list
set m = tuple 0 0
for D in range 1 1001
begin
if not call is_integer square root D
begin
set x = 2
while not call is_integer square root x ^ 2.0 - 1 / D
begin
set x = x + 1
end
if x > m at 1
begin
set m = tuple D x
end
end
end | from math import sqrt
x = 5
vals = []
m = (0,0)
for D in range(1,1001):
if not float.is_integer(sqrt(D)):
x = 2
while not float.is_integer(sqrt((x**2.0-1)/D)):
x += 1
if x > m[1]:
m = (D, x) | Python | zaydzuhri_stack_edu_python |
function updateData self item
begin
set item = item
call setText item at string title
call setHtml item at string summary
call setOpenLinks false
call setReadOnly true
call connect openWebPage
end function | def updateData(self, item):
self.item = item
self.labelFeed.setText(item['title'])
self.textBrowser.setHtml(item['summary'])
self.textBrowser.setOpenLinks(False)
self.textBrowser.setReadOnly(True)
self.textBrowser.anchorClicked.connect(self.openWebPage) | Python | nomic_cornstack_python_v1 |
for line in file
begin
print line
end | for line in file:
print(line)
| Python | zaydzuhri_stack_edu_python |
function load_table_files table_filenames
begin
set dfs = list
for v in call tqdm values table_filenames
begin
append dfs read csv v low_memory=false
end
return dfs
end function | def load_table_files(table_filenames: Dict):
dfs = []
for v in tqdm(table_filenames.values()):
dfs.append(pd.read_csv(v, low_memory=False))
return dfs | Python | nomic_cornstack_python_v1 |
function test_atomic_byte_min_inclusive_nistxml_sv_iv_atomic_byte_min_inclusive_1_1 mode save_output output_format
begin
call assert_bindings schema=string nistData/atomic/byte/Schema+Instance/NISTSchema-SV-IV-atomic-byte-minInclusive-1.xsd instance=string nistData/atomic/byte/Schema+Instance/NISTXML-SV-IV-atomic-byte-... | def test_atomic_byte_min_inclusive_nistxml_sv_iv_atomic_byte_min_inclusive_1_1(mode, save_output, output_format):
assert_bindings(
schema="nistData/atomic/byte/Schema+Instance/NISTSchema-SV-IV-atomic-byte-minInclusive-1.xsd",
instance="nistData/atomic/byte/Schema+Instance/NISTXML-SV-IV-atomic-byte-m... | Python | nomic_cornstack_python_v1 |
import numpy , pandas , root_numpy
from sklearn.cross_validation import train_test_split
import gc , os
import sys
function get_number_particles files_http particles_pdg selection log_file_name=string get_number_particles.log
begin
string Returns number of particles of each type in each data file. Parameters ----------... | import numpy, pandas, root_numpy
from sklearn.cross_validation import train_test_split
import gc, os
import sys
def get_number_particles(files_http, particles_pdg, selection, log_file_name='get_number_particles.log'):
"""
Returns number of particles of each type in each data file.
Parameters
---------... | Python | zaydzuhri_stack_edu_python |
for char in string Hello World
begin
print char string : count string Hello World char
end | for char in "Hello World":
print(char, ":", "Hello World".count(char)) | Python | jtatman_500k |
function release filePtr
begin
set _release = NET_DVR_Cleanup
set restype = BOOL
if call _release
begin
print string now + string |INFO|SDK released successfully file=filePtr
end
else
begin
set _m = string now + string |ERROR|SDK release failed. Error message: + call getErrorMsg call getLastError
print _m file=filePtr
... | def release(filePtr):
_release = HC.NET_DVR_Cleanup
_release.restype = BOOL
if _release():
print(str(datetime.now())+"|INFO|SDK released successfully",file=filePtr)
else :
_m=str(datetime.now())+"|ERROR|SDK release failed. Error message: "+getErrorMsg(getLastError())
print(_m,fil... | Python | nomic_cornstack_python_v1 |
function test_amin_nonfinite_nan_01 self
begin
set result = call amin data_nan nosimd=true
set result2 = min data_nan
end function
comment We don't actually test the result as there is no meaningful order
comment comparison with NaN. | def test_amin_nonfinite_nan_01(self):
result = arrayfunc.amin(self.data_nan , nosimd=True)
result2 = min(self.data_nan)
# We don't actually test the result as there is no meaningful order
# comparison with NaN. | Python | nomic_cornstack_python_v1 |
function test_result_pass_started self
begin
set envs = call create_full_set dict string OS list string OS X ; string Language list string English
set run = call create environments=envs
set rcv = call create run=run
set u = call create
start rcv envs at 0 user=u
call result_pass envs at 0 user=u
set r = get results en... | def test_result_pass_started(self):
envs = self.F.EnvironmentFactory.create_full_set(
{"OS": ["OS X"], "Language": ["English"]})
run = self.F.RunFactory.create(environments=envs)
rcv = self.F.RunCaseVersionFactory.create(run=run)
u = self.F.UserFactory.create()
... | Python | nomic_cornstack_python_v1 |
from sqlite3 import connect
set DATABASE = string test.db
function create_table
begin
set sql_request = string CREATE TABLE Stocks(ID INTEGER PRIMARY KEY AUTOINCREMENT, Open Decimal(15,15), Date DATE, Close Decimal(15,15), Low Decimal(15,15), Symbol VARCHAR(5), Adj_Close Decimal(15,15), Volume Integer, High Decimal(15,... | from sqlite3 import connect
DATABASE = 'test.db'
def create_table():
sql_request = 'CREATE TABLE Stocks(ID INTEGER PRIMARY KEY AUTOINCREMENT, Open Decimal(15,15), Date DATE, Close Decimal(15,15), Low Decimal(15,15), Symbol VARCHAR(5), Adj_Close Decimal(15,15), Volume Integer, High Decimal(15,15))'
execute_sql(... | Python | zaydzuhri_stack_edu_python |
import itertools
import sys
insert path 0 string ./lesson01
from rank_hands import hand_rank
function best_hand hand
begin
return max call combinations hand 5 key=hand_rank
end function
function test_best_hand
begin
assert sorted call best_hand split string 6C 7C 8C 9C TC 5C JS == list string 6C string 7C string 8C str... | import itertools
import sys
sys.path.insert(0, "./lesson01")
from rank_hands import hand_rank
def best_hand(hand):
return max(itertools.combinations(hand, 5), key=hand_rank)
def test_best_hand():
assert (sorted(best_hand("6C 7C 8C 9C TC 5C JS".split()))
== ['6C', '7C', '8C', '9C', 'TC'])
asser... | Python | zaydzuhri_stack_edu_python |
function test_linear_inequality_to_penalty3 self
begin
set op = call QuadraticProgram
set lip = call LinearInequalityToPenalty
call binary_var_list 5
comment Linear constraints
set n = 5
call linear_constraint list 1 1 1 1 1 GE n - 1 string
comment Test with no max/min
with call subTest string No max/min
begin
assert e... | def test_linear_inequality_to_penalty3(self):
op = QuadraticProgram()
lip = LinearInequalityToPenalty()
op.binary_var_list(5)
# Linear constraints
n = 5
op.linear_constraint([1, 1, 1, 1, 1], Constraint.Sense.GE, n - 1, "")
# Test with no max/min
with se... | Python | nomic_cornstack_python_v1 |
import time
function foo
begin
print string in foo()
end function
comment 定义一个计时器,传入一个,并返回另一个附加了计时器功能的方法
function timeit func
begin
comment 定义一个内嵌的包装函数,给传入的函数加上计时功能的包装
function wrapper
begin
set start = call clock
call func
set end = call clock
print string used: end - start
end function
return wrapper
end function
set... | import time
def foo():
print('in foo()')
#定义一个计时器,传入一个,并返回另一个附加了计时器功能的方法
def timeit(func):
#定义一个内嵌的包装函数,给传入的函数加上计时功能的包装
def wrapper():
start = time.clock()
func()
end = time.clock()
print('used:',end-start)
return wrapper
foo = timeit(foo)
foo() | Python | zaydzuhri_stack_edu_python |
function load_data file_loc
begin
call load_data file_loc
end function | def load_data(file_loc):
scripts.load_data(file_loc) | Python | nomic_cornstack_python_v1 |
comment find number of digits in array
set leng = length numStr
set totalSymmetry = 0
if leng % 2 > 0
begin
set totalSymmetry = totalSymmetry + 1
end
comment get fist part of number(str)
set firsPart = numStr at slice : leng // 2 :
comment get fist part of number(str), below if for odd and even count of digits
if len... | # find number of digits in array
leng = len(numStr)
totalSymmetry = 0
if leng % 2 > 0:
totalSymmetry+=1
# get fist part of number(str)
firsPart = numStr[:leng//2]
# get fist part of number(str), below if for odd and even count of digits
if leng % 2 > 0:
secondPart = numStr[leng//2+1:]
else:
secondPa... | Python | zaydzuhri_stack_edu_python |
function powerSetHelper inputL marker
begin
set res = list
set indx = 0
while marker > 0
begin
if marker ? 1 == 1
begin
append res inputL at indx
end
set indx = indx + 1
set marker = marker ? 1
end
return res
end function
function powerset inputL
begin
set allSets = list
for i in call xrange 2 ^ length inputL
begin
s... | def powerSetHelper(inputL, marker):
res = []
indx = 0
while marker > 0:
if marker & 1 == 1:
res.append(inputL[indx])
indx += 1
marker >>= 1
return res
def powerset(inputL):
allSets = []
for i in xrange(2**(len(inputL))):
ss = powerSetHelper(inputL, i)
allSets.append(ss)
return... | Python | zaydzuhri_stack_edu_python |
function repositionImage self event
begin
set new_x = width / 2
set new_y = height / 2
delete string all
call create_image new_x new_y image=img
end function | def repositionImage(self, event):
new_x = event.width/2
new_y = event.height/2
self.canvas.delete('all')
self.canvas.create_image(new_x, new_y, image=self.img) | Python | nomic_cornstack_python_v1 |
async function read_until_eof self
begin
set chunks = list
while true
begin
set chunk = await read self _read_size
if not chunk
begin
break
end
append chunks chunk
end
return join b'' chunks
end function | async def read_until_eof(self):
chunks = []
while True:
chunk = await self.read(self._read_size)
if not chunk:
break
chunks.append(chunk)
return b''.join(chunks) | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
import numpy as np
from scipy.misc import imread as imread , imsave as imsave
from skimage import img_as_float
from skimage.color import rgb2gray
set BINS = 256
set RGB_CODE = 2
set GRAY_SCALE_CODE = 1
function read_image filename representation
begin
string The function receives a file ... | import matplotlib.pyplot as plt
import numpy as np
from scipy.misc import imread as imread, imsave as imsave
from skimage import img_as_float
from skimage.color import rgb2gray
BINS = 256
RGB_CODE = 2
GRAY_SCALE_CODE = 1
def read_image(filename, representation):
"""
The function receives a file path and open... | Python | zaydzuhri_stack_edu_python |
import cv2
import matplotlib.pyplot as plt
import numpy as np
import os
import glob
class HomographyMatrixFinder
begin
function __init__ self
begin
set dirName = string PictureGroup
set imgNames = list
set imgFiles = list
set sticher = call create
set panoLeft = none
set panoRight = none
set pano = none
end function
... | import cv2
import matplotlib.pyplot as plt
import numpy as np
import os
import glob
class HomographyMatrixFinder:
def __init__(self):
self.dirName = "PictureGroup"
self.imgNames = []
self.imgFiles = []
self.sticher = cv2.Stitcher.create()
self.panoLeft = None
self.p... | Python | zaydzuhri_stack_edu_python |
function tear_down exception
begin
close storage
end function | def tear_down(exception):
storage.close() | Python | nomic_cornstack_python_v1 |
function singleDriverTrainer file_to_classify training_files in_model1 in_model2 weight_1=0.5 file_subset_size=200
begin
comment first, grab the target data
set tuple x_target y_target id_target = call extractCSV file_to_classify target=1
comment remove na's
set x_target = call nan_to_num x_target
set y_target = call n... | def singleDriverTrainer(file_to_classify, training_files, in_model1, in_model2,
weight_1 = 0.5, file_subset_size = 200):
# first, grab the target data
x_target, y_target, id_target = extractCSV(file_to_classify, target = 1)
# remove na's
x_target = np.nan_to_num(x_target)
y_t... | Python | nomic_cornstack_python_v1 |
function fitness self tree
begin
set key = dump tree
if key in fitness_cache
begin
return fitness_cache at key
end
comment Save defs
set original_defs = dict
for name in call toplevel_defs tree
begin
if name in globals
begin
set original_defs at name = globals at name
end
else
begin
warn string Couldn't find definitio... | def fitness(self, tree):
key = ast.dump(tree)
if key in self.fitness_cache:
return self.fitness_cache[key]
# Save defs
original_defs = {}
for name in self.toplevel_defs(tree):
if name in self.globals:
original_defs[name] = self.globals[nam... | Python | nomic_cornstack_python_v1 |
import json
from pprint import pprint
import os
from ebaysdk.trading import Connection as Trading
set credentials = dictionary zip tuple string appid string devid string certid string token split environ at string EBAY_PARAMS string ;
set api = call Trading config_file=none keyword credentials
set response = execute ap... | import json
from pprint import pprint
import os
from ebaysdk.trading import Connection as Trading
credentials = dict(zip(('appid', 'devid', 'certid', 'token'), os.environ['EBAY_PARAMS'].split(';')))
api = Trading(config_file=None, **credentials)
response = api.execute('GetMyeBaySelling', {
'ActiveList': {
... | Python | zaydzuhri_stack_edu_python |
function predict self boards **kwargs
begin
return predict model boards keyword kwargs
end function | def predict(self, boards, **kwargs):
return self.model.predict(boards, **kwargs) | Python | nomic_cornstack_python_v1 |
set usf = input string Ingrese el numero de piso US:
set wf = integer usf - 1
print string Numero de piso NO-US es wf | usf = input('Ingrese el numero de piso US: ')
wf = int(usf)-1
print('Numero de piso NO-US es ', wf) | Python | zaydzuhri_stack_edu_python |
function resolve_by_auth0_id args info auth0_user_id
begin
comment Cleanup the Auth0 user ID.
set auth0_user_id = call clean_auth0_user_id auth0_user_id=string auth0_user_id
comment Check that the requesting user is authorized to retrieve the user with
comment the given Auth0 ID.
call check_auth info=info auth0_user_id... | def resolve_by_auth0_id(
args: dict,
info: graphene.ResolveInfo,
auth0_user_id: str,
) -> List[ModelUser]:
# Cleanup the Auth0 user ID.
auth0_user_id = clean_auth0_user_id(auth0_user_id=str(auth0_user_id))
# Check that the requesting user is authorized to retrieve t... | Python | nomic_cornstack_python_v1 |
comment Writing Employee idno, name and salary into a file
import pickle
comment int type
set idno = 1212
comment str type
set name = string Ravi Kumar
comment float type
set salary = 185000.25
set file = open string employee.txt string wb
dump idno file
dump name file
dump salary file
close file
print string Data Writ... | # Writing Employee idno, name and salary into a file
import pickle
idno = 1212# int type
name = 'Ravi Kumar' # str type
salary = 185000.25 # float type
file = open("employee.txt","wb")
pickle.dump(idno,file)
pickle.dump(name,file)
pickle.dump(salary,file)
file.close()
print("Data Written to File") | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
comment coding:utf8
comment http://projecteuler.net/problem=63
comment PROBLEM CONTENT:
comment The 5-digit number, 16807=7^5, is also a fifth power. Similarly, the 9-digit
comment number, 134217728=8^9, is a ninth power.
comment How many n-digit positive integers exist which are also an nth p... | #!/usr/bin/python3
# coding:utf8
# http://projecteuler.net/problem=63
#
# PROBLEM CONTENT:
# The 5-digit number, 16807=7^5, is also a fifth power. Similarly, the 9-digit
# number, 134217728=8^9, is a ninth power.
#
# How many n-digit positive integers exist which are also an nth power?
#
#
# EXPLANATION:
# We are look... | Python | zaydzuhri_stack_edu_python |
function _run_ssh_cmd argv
begin
set process = popen argv stderr=PIPE
set line = read line stderr
while line
begin
call echo line nl=false err=true
if b'Permission denied' in line and b'rsync: send_files failed to open' not in line
begin
call echo PERMISSION_DENIED_MESSAGE err=true
end
set line = read line stderr
end
r... | def _run_ssh_cmd(argv):
process = subprocess.Popen(argv, stderr=subprocess.PIPE)
line = process.stderr.readline()
while line:
click.echo(line, nl=False, err=True)
if (
b"Permission denied" in line
and b"rsync: send_files failed to open" not in line
):
... | Python | nomic_cornstack_python_v1 |
import pygame
from platform import Platform
comment global constants
string Colors
set BLACK = tuple 0 0 0
set WHITE = tuple 255 255 255
set GREEN = tuple 0 255 0
set RED = tuple 255 0 0
set BLUE = tuple 0 0 255
string Screen Dimensions
set SCREEN_WIDTH = 800
set SCREEN_HEIGHT = 600
class Wall extends Sprite
begin
stri... | import pygame
from platform import Platform
#global constants
''' Colors '''
BLACK = (0,0,0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
''' Screen Dimensions'''
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
class Wall(pygame.sprite.Sprite):
'''walls to keep player in world'''
de... | Python | zaydzuhri_stack_edu_python |
function register self wool
begin
set wools at package = wool
info format string Registered {!r} wool
end function | def register(self, wool):
self.wools[wool.package] = wool
LOGGER.info("Registered {!r}".format(wool)) | Python | nomic_cornstack_python_v1 |
function standard_dev dataset
begin
set mean = call average dataset
set deviations = list comprehension data - mean ^ 2 for data in dataset
set variance = sum deviations / length dataset
return variance ^ 0.5
end function
function average dataset
begin
return sum dataset / length dataset
end function
set listA = list 4... | def standard_dev(dataset):
mean = average(dataset)
deviations = [(data - mean)**2 for data in dataset]
variance = sum(deviations)/len(dataset)
return variance**0.5
def average(dataset):
return sum(dataset) / len(dataset)
listA = [4, 6, 9, 2, 7, 6]
listB = [12, 63, 92, 36, 74]
list... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
string This module holds a function that calls the dir function
function lookup obj
begin
string Returns a lists of all the attributes and methods Args: obj (object): Holds the object Returns: list: A list of attributes and methods
return directory obj
end function | #!/usr/bin/python3
"""This module holds a function that calls the dir function
"""
def lookup(obj):
"""Returns a lists of all the attributes and methods
Args:
obj (object): Holds the object
Returns:
list: A list of attributes and methods
"""
return dir(obj)
| Python | zaydzuhri_stack_edu_python |
import pandas as pd
comment Create a sample DataFrame
set data = dict string Name list string John string Emily string Michael string Jessica string William ; string Age list 25 28 30 24 32 ; string City list string New York string Los Angeles string Chicago string San Francisco string Seattle ; string Salary list 5000... | import pandas as pd
# Create a sample DataFrame
data = {'Name': ['John', 'Emily', 'Michael', 'Jessica', 'William'],
'Age': [25, 28, 30, 24, 32],
'City': ['New York', 'Los Angeles', 'Chicago', 'San Francisco', 'Seattle'],
'Salary': [50000, 60000, 55000, 45000, 65000]}
df = pd.DataFrame(data)
#... | Python | jtatman_500k |
import json
from pprint import pprint
set data = dict string name string 中文 ; string shares 100 ; string price 542.23
comment Python数据结构转换为JSON
set json_str = encode dumps data
print json_str
print string ***
comment JSON数据转字典
print loads decode json_str string utf8 | import json
from pprint import pprint
data = {
'name' : '中文',
'shares' : 100,
'price' : 542.23
}
# Python数据结构转换为JSON
json_str = json.dumps(data).encode()
print(json_str)
print('***')
# JSON数据转字典
print(json.loads(json_str.decode('utf8'))) | Python | zaydzuhri_stack_edu_python |
function send_handle_delete_request self **args
begin
string Send a HTTP DELETE request to the handle server to delete either an entire handle or to some specified values from a handle record, using the requests module. :param handle: The handle. :param indices: Optional. A list of indices to delete. Defaults to None (... | def send_handle_delete_request(self, **args):
'''
Send a HTTP DELETE request to the handle server to delete either an
entire handle or to some specified values from a handle record,
using the requests module.
:param handle: The handle.
:param indices: Optional. A... | Python | jtatman_500k |
function train_with_corpus corpus
begin
call set_trainer string chatterbot.trainers.ChatterBotCorpusTrainer
train chatbot corpus
end function | def train_with_corpus(corpus):
chatbot.set_trainer("chatterbot.trainers.ChatterBotCorpusTrainer")
chatbot.train(corpus) | Python | nomic_cornstack_python_v1 |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import warnings
from scipy import signal
from scipy.signal import blackman
import sys
set freq = 4000
function read_and_plot column=string x block=false
begin
if length argv > 1
begin
set path = string data/ + argv at 1 + string .csv
end
else
begin
... | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import warnings
from scipy import signal
from scipy.signal import blackman
import sys
freq = 4000
def read_and_plot(column = 'x', block = False):
if len(sys.argv) > 1:
path = 'data/' + sys.argv[1] + '.csv'
else:
print("File no... | Python | zaydzuhri_stack_edu_python |
function handle_no_permission self
begin
if not is_authenticated
begin
return call redirect string { LOGIN_URL } ?next= { path }
end
return call redirect string access-denied
end function | def handle_no_permission(self):
if not self.request.user.is_authenticated:
return redirect(f"{settings.LOGIN_URL}?next={self.request.path}")
return redirect("access-denied") | Python | nomic_cornstack_python_v1 |
comment Пользователь вводит число N.
comment Напишите программу, которая выводит такую “лесенку” из чисел:
comment Введите число: 5
comment 1
comment 2 2
comment 3 3 3
comment 4 4 4 4
comment 5 5 5 5 5
set number = integer input string Введите номер:
for row in range 1 number + 1
begin
for col in range row
begin
print ... | # Пользователь вводит число N.
# Напишите программу, которая выводит такую “лесенку” из чисел:
# Введите число: 5
# 1
# 2 2
# 3 3 3
# 4 4 4 4
# 5 5 5 5 5
number = int(input("Введите номер: "))
for row in range(1, number + 1):
for col in range(row):
print(row, end = " ")
print() | Python | zaydzuhri_stack_edu_python |
string Date: Monday, 24 July 2017 File name: Version: 1 Author: Abderrazak DERDOURI Subject: CQF Final Project Description: Notes: Revision History:
import pandas as pd
from unittest import TestCase
import sys
import math
import numpy as np
import matplotlib.pyplot as plt
import LiteLibrary
from math import log , sqrt ... | """
Date: Monday, 24 July 2017
File name:
Version: 1
Author: Abderrazak DERDOURI
Subject: CQF Final Project
Description:
Notes:
Revision History:
"""
import pandas as pd
from unittest import TestCase
import sys
import math
import numpy as np
import matplotlib.pyplot as plt
import LiteLibrary
f... | Python | zaydzuhri_stack_edu_python |
import subprocess
run list string wuauclt.exe string /detectnow | import subprocess
subprocess.run(['wuauclt.exe', '/detectnow'])
| Python | flytech_python_25k |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.