code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment !/usr/bin/env python
import wiringpi as wpi
import datetime
comment Pins
comment BCM 22
set pCLK = 3
comment BCM 23
set pDT = 4
comment BCM 24
set pSW = 5
set pSideLight = 25
comment BCM 12
set pPWM = 26
set inputPins = list pCLK pDT pSW
comment Rotary Knob Vars
set flag = 0
set Last_DT_Status = 0
set Current_D... | #!/usr/bin/env python
import wiringpi as wpi
import datetime
# Pins
pCLK = 3 # BCM 22
pDT = 4 # BCM 23
pSW = 5 # BCM 24
pSideLight = 25
pPWM = 26 # BCM 12
inputPins = [pCLK, pDT, pSW]
# Rotary Knob Vars
flag = 0
Last_DT_Status = 0
Current_DT_Status = 0
LastClearTime = 0
# PWM Vars
pwmMinOn = 490
pwmLow = 520
pwm... | Python | zaydzuhri_stack_edu_python |
function generate_token configs=none
begin
if configs
begin
set dnac_username = configs at string username
set dnac_password = configs at string password
end
else
begin
call secho string [*] Please check DNA center configurations! fg=string blue
call secho string [x] Configs not found! fg=string red
exit 1
end
call div... | def generate_token(configs=None):
if configs:
dnac_username = configs["username"]
dnac_password = configs["password"]
else:
click.secho(f"[*] Please check DNA center configurations!", fg="blue")
click.secho(f"[x] Configs not found!", fg="red")
sys.exit(1)
divider("A... | Python | nomic_cornstack_python_v1 |
function number_of_pallets self
begin
return _number_of_pallets
end function | def number_of_pallets(self):
return self._number_of_pallets | Python | nomic_cornstack_python_v1 |
comment 7-21
function maximum_float
begin
return decimal string inf
end function
comment Step5. 7-31
function find_lowest_cost_node costs processed
begin
set lowest_cost = call maximum_float
set lowest_cost_node = none
for node in costs
begin
set cost = costs at node
if cost < lowest_cost and node not in processed
begi... | # 7-21
def maximum_float():
return float("inf")
# Step5. 7-31
def find_lowest_cost_node(costs, processed):
lowest_cost = maximum_float()
lowest_cost_node = None
for node in costs:
cost = costs[node]
if cost < lowest_cost and node not in processed:
lowest_cost = cost
... | Python | zaydzuhri_stack_edu_python |
function test_invalid_names
begin
for name in list string 1 string _ string 1a string _a string a a string string string a! string a@ string a# string a% string a^ string a& string a* string a( string a)
begin
with raises NoMatchError as excinfo
begin
set _ = call Name name
end
assert format string Name: '{0}' name i... | def test_invalid_names():
for name in [
"1",
"_",
"1a",
"_a",
"a a",
"",
" ",
"a!",
"a@",
"a#",
"a%",
"a^",
"a&",
"a*",
"a(",
"a)",
]:
with pytest.raises(NoMatchError) as excin... | Python | nomic_cornstack_python_v1 |
function create_network_add_weights network_input n_vocab wd
begin
set model = sequential
add model call Bidirectional lstm 512 return_sequences=true input_shape=tuple shape at 1 shape at 2
comment n_time_steps, n_features? Needed input_shape in first layer, which is Bid not LSTM
add model call SeqSelfAttention attenti... | def create_network_add_weights(network_input, n_vocab, wd):
model = Sequential()
model.add(Bidirectional(LSTM(512, return_sequences=True), input_shape=(network_input.shape[1], network_input.shape[
2]))) # n_time_steps, n_features? Needed input_shape in first layer, which is Bid not LSTM
model... | Python | nomic_cornstack_python_v1 |
function fibo l
begin
set a = 1
set b = 1
for n in range 0 l
begin
yield a
set tuple a b = tuple b a + b
end
end function
function even n
begin
return if expression n % 2 == 0 then n else 0
end function
set sum = 0
for i in call fibo 100
begin
if i > 4000000
begin
break
end
set sum = sum + call even i
end
print sum | def fibo(l):
a = b = 1
for n in range(0, l):
yield a
a, b = b, a + b
def even(n):
return n if n % 2 == 0 else 0
sum = 0
for i in fibo(100):
if i > 4000000:
break
sum += even(i)
print(sum)
| Python | zaydzuhri_stack_edu_python |
function true_entropy self params
begin
set mu = params at string mu
set Sigma = params at string Sigma
set dist = call multivariate_normal mean=mu cov=Sigma
set H_true = entropy
return H_true
end function | def true_entropy(self, params):
mu = params["mu"]
Sigma = params["Sigma"]
dist = scipy.stats.multivariate_normal(mean=mu, cov=Sigma)
H_true = dist.entropy()
return H_true | Python | nomic_cornstack_python_v1 |
function check_number list number
begin
if number in list
begin
return true
end
else
begin
return false
end
end function | def check_number(list, number):
if number in list:
return True
else:
return False
| Python | flytech_python_25k |
import string
set key = string goqibdwxystklmefacpvzurhjn
set base = ascii_lowercase
set d = dict
for i in range 26
begin
set d at key at i = base at i
end
set file = open string /Users/keltonz/Desktop/11411/hw01-handout/key.txt string w
for tuple key value in items d
begin
write file string %s %s % tuple key value
en... | import string
key = "goqibdwxystklmefacpvzurhjn"
base = string.ascii_lowercase
d = {}
for i in range(26):
d[key[i]] = base[i]
file = open("/Users/keltonz/Desktop/11411/hw01-handout/key.txt","w")
for key,value in d.items():
file.write("%s %s\n" % (key,value))
file.close()
| Python | zaydzuhri_stack_edu_python |
comment !/home/python/n/pyneng/bin/python
comment -*- coding: utf-8 -*-
string Задание 7.1 Аналогично заданию 4.6 обработать строки из файла ospf.txt и вывести информацию по каждой в таком виде: Protocol: OSPF Prefix: 10.0.24.0/24 AD/Metric: 110/41 Next-Hop: 10.0.13.3 Last update: 3d18h Outbound Interface: FastEthernet... | #!/home/python/n/pyneng/bin/python
# -*- coding: utf-8 -*-
'''
Задание 7.1
Аналогично заданию 4.6 обработать строки из файла ospf.txt
и вывести информацию по каждой в таком виде:
Protocol: OSPF
Prefix: 10.0.24.0/24
AD/Metric: 110/41
Next-Hop: 10.0.13.3
Last update: ... | Python | zaydzuhri_stack_edu_python |
function __init__ self learning_rate
begin
set learning_rate = learning_rate
end function | def __init__(self, learning_rate: float):
self.learning_rate = learning_rate | Python | nomic_cornstack_python_v1 |
from ImgBig import ImgBig , BBX
from os import listdir
import string
import random
import cv2
function resize_images crop pathto
begin
set width = 12
set height = 12
set dim = tuple width height
set resized = call resize crop dim interpolation=INTER_AREA
call imwrite pathto resized
end function
function crop_bdbox img ... | from ImgBig import ImgBig,BBX
from os import listdir
import string
import random
import cv2
def resize_images(crop, pathto):
width = 12
height = 12
dim = (width, height)
resized = cv2.resize(crop, dim, interpolation = cv2.INTER_AREA)
cv2.imwrite(pathto, resized)
def crop_bdbox(img, bb... | Python | zaydzuhri_stack_edu_python |
function validate_data self **kwargs
begin
comment lambda is a workaround to access the 'kwargs.keys()' scope.
if not all call
begin
return false
end
try
begin
set user_id = integer kwargs at string user
end
except ValueError
begin
return false
end
if user_id != id
begin
return false
end
return true
end function | def validate_data(self, **kwargs) -> bool:
# lambda is a workaround to access the 'kwargs.keys()' scope.
if not all((lambda keys=kwargs.keys():
[key in keys for key in ['checked', 'log', 'user']])()):
return False
try:
user_id = int(kwargs['user'])
... | Python | nomic_cornstack_python_v1 |
function SetTransformForward self _arg
begin
return call itkRegistrationParameterScalesFromPhysicalShiftEBPSTPSMPSUS3_Superclass_Superclass_SetTransformForward self _arg
end function | def SetTransformForward(self, _arg: 'bool const') -> "void":
return _itkExpectationBasedPointSetToPointSetMetricv4Python.itkRegistrationParameterScalesFromPhysicalShiftEBPSTPSMPSUS3_Superclass_Superclass_SetTransformForward(self, _arg) | Python | nomic_cornstack_python_v1 |
function get_hottest_SAD unique_SADs
begin
comment if len(unique_SADs) > 500:
comment unique_SADs = random.sample(unique_SADs,500)
set N = sum unique_SADs at 0
set S = length unique_SADs at 0
comment SAD mean
set a1 = 0
comment SAD variance
set v1 = 0
for rad in unique_SADs
begin
set in_common = list
set ct1 = 0
comme... | def get_hottest_SAD(unique_SADs):
#if len(unique_SADs) > 500:
#unique_SADs = random.sample(unique_SADs,500)
N = sum(unique_SADs[0])
S = len(unique_SADs[0])
a1 = 0 # SAD mean
v1 = 0 # SAD variance
for rad in unique_SADs:
in_common = []
ct1 = 0
for a in rad: # for... | Python | nomic_cornstack_python_v1 |
function test_getitem_returns_a_theme self
begin
set expected = themes at 0
set actual = tested at theme_names at 0
assert equal expected actual
end function | def test_getitem_returns_a_theme(self):
expected = self.themes[0]
actual = self.tested[self.theme_names[0]]
self.assertEqual(expected, actual) | Python | nomic_cornstack_python_v1 |
comment %% listeler
comment boş liste **
set l1 = list
comment boş liste
set l2 = list
set ogler = list string ahmet efe string zeynep string reyyan string yusuf string mert string kerem string tarık
set mix = list 1 2 32.0 string hasan true true false
print ogler
print mix
print ogler at 1
set ogler at 3 = string yus... | # %% listeler
l1 = [] # boş liste **
l2 = list() # boş liste
ogler = ["ahmet efe", "zeynep", "reyyan", "yusuf", "mert",
"kerem", "tarık"]
mix = [1, 2, 32.0, "hasan", True, True, False]
print(ogler)
print(mix)
print(ogler[1])
ogler[3] = "yusuf aras"
print(ogler)
for isim in ogler:
print(isim)
# %%
#k... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
import cgi
import sqlite3
set form = call FieldStorage
set html = string <!DOCTYPE html> <head> <title>Mon programme</title> </head> <body> <h1>Afficher le graphe de la luminescence de votre piece </h1> <img src="/img/peri.png" alt="logo" > <form action="/bd.py" method="post"> <input type="tex... | #!/usr/bin/python3
import cgi
import sqlite3
form = cgi.FieldStorage()
html = """<!DOCTYPE html>
<head>
<title>Mon programme</title>
</head>
<body>
<h1>Afficher le graphe de la luminescence de votre piece </h1>
<img src="/img/peri.png" alt="logo" >
<form action="/bd.py" method="post">
<input type="... | Python | zaydzuhri_stack_edu_python |
string 连接池的实现
from threading import Thread , Lock
from queue import Queue
from _queue import Empty
set pool = queue maxsize=5
class Conn
begin
function __init__ self
begin
pass
end function
function __enter__ self
begin
with lock as l
begin
try
begin
set result = get pool block=false timeout=1
return result
end
except ... | """连接池的实现"""
from threading import Thread, Lock
from queue import Queue
from _queue import Empty
pool = Queue(maxsize=5)
class Conn:
def __init__(self):
pass
def __enter__(self):
with Lock() as l:
try:
result = pool.get(block=False, timeout=1)
... | Python | zaydzuhri_stack_edu_python |
string This module provides Route Graph class, that allows to represent graph model(as an adjacency matrix), that's used to find optimal route among all the other possible.
import numpy as np
class RouteGraph
begin
comment refill - set of points (x,y), start(end) - set (x,y)
function __init__ self route vehicle scale=1... | """
This module provides Route Graph class, that
allows to represent graph model(as an adjacency matrix),
that's used to find optimal route among all the other possible.
"""
import numpy as np
class RouteGraph:
def __init__(self, route, vehicle, scale=1): # refill - set of points (x,y), start(end) - set (x,y)
... | Python | zaydzuhri_stack_edu_python |
function reset self
begin
set _timestep = array list 0
end function | def reset(self):
self._timestep = np.array([0]) | Python | nomic_cornstack_python_v1 |
import boto3
import sys
import os
import constants
import utils
import csv
import json
from botocore.exceptions import ClientError , NoCredentialsError , BotoCoreError
import logging
comment Constants
set INPUT_BUCKET_NAME = INPUT_BUCKET_NAME
set OUTPUT_BUCKET_NAME = OUTPUT_BUCKET_NAME
comment Bucket with CSV files to ... | import boto3
import sys
import os
import constants
import utils
import csv
import json
from botocore.exceptions import ClientError, NoCredentialsError, BotoCoreError
import logging
# Constants
INPUT_BUCKET_NAME = constants.INPUT_BUCKET_NAME
OUTPUT_BUCKET_NAME = constants.OUTPUT_BUCKET_NAME
# Bucket with CSV files to ... | Python | zaydzuhri_stack_edu_python |
function half_edge_graph g b=none B=none rec=none
begin
set E = call num_edges
set b_array = none
if b is none
begin
comment if no partition is given, obtain a random one.
set ba = random integer 0 B 2 * E
comment avoid empty blocks
set ba at slice : B : = array range B
if B < length ba
begin
shuffle random ba
end
se... | def half_edge_graph(g, b=None, B=None, rec=None):
E = g.num_edges()
b_array = None
if b is None:
# if no partition is given, obtain a random one.
ba = random.randint(0, B, 2 * E)
ba[:B] = arange(B) # avoid empty blocks
if B < len(ba):
random.shuffle(ba)
... | Python | nomic_cornstack_python_v1 |
function get self find_type find_key
begin
set methods = list string song_hash string artist string title string length string filename
set cache_handler = config at string cache_handler
comment find_type is ints from 1 - 5, list indices are ints from 0 - 4
set found = find cache_handler methods at find_type - 1 find_k... | def get(self, find_type, find_key):
methods = ['song_hash', 'artist', 'title', 'length', 'filename']
cache_handler = current_app.config['cache_handler']
# find_type is ints from 1 - 5, list indices are ints from 0 - 4
found = cache_handler.find(methods[find_type - 1], find_key)
i... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
from backend.models import Article , Flow , TagGroup
comment -----------------------------------------------------------------------------------
comment class
class Recoman extends object
begin
function __init__ self _postObj
begin
set postObj = _postObj
set tagsList = all
end function
fun... | # -*- coding: utf-8 -*-
from backend.models import Article, Flow, TagGroup
#-----------------------------------------------------------------------------------
#class
class Recoman(object):
def __init__(self, _postObj):
self.postObj = _postObj
self.tagsList = _postObj.tags.all()
def getTagCom... | Python | zaydzuhri_stack_edu_python |
import os , re , sys
from shutil import copy2
function Copy_Code_Files src dest
begin
set mNames = list directory src
set out = string Not Done
for mName in mNames
begin
if is directory path join path src mName and upper mName at slice 0 : 4 : == upper string eds_ and length mName == length string EDS_XX
begin
set code... | import os, re, sys
from shutil import copy2
def Copy_Code_Files(src,dest):
mNames = os.listdir(src)
out = 'Not Done'
for mName in mNames:
if (os.path.isdir(os.path.join(src,mName))) and (mName[0:4].upper() == 'eds_'.upper()) and (len(mName) == len('EDS_XX')):
codePath = os.path.join(src,mName,'matlab','tlcode'... | Python | zaydzuhri_stack_edu_python |
from typing import List
from randomList import randomList
function mergeSort iList
begin
if length iList <= 1
begin
return iList
end
set middle = length iList // 2
set tuple left right = tuple iList at slice 0 : middle : iList at slice middle : :
return merge call mergeSort left call mergeSort right
end function
fun... | from typing import List
from randomList import randomList
def mergeSort(iList: List[int]):
if len(iList) <= 1:
return iList
middle = len(iList) // 2
left, right = iList[0:middle], iList[middle:]
return merge(mergeSort(left), mergeSort(right))
def merge(left: List[int], right: List[int]):
... | Python | zaydzuhri_stack_edu_python |
function test_scalar_coord self
begin
call add_aux_coord call AuxCoord 1 long_name=string scalar_coord units=string no_unit
set coord = call coord string scalar_coord
set plugin = call NonLinearWeights 0.85
set result = process cube coord
call assertArrayAlmostEqual data array list 1.0
end function | def test_scalar_coord(self):
self.cube.add_aux_coord(AuxCoord(1, long_name="scalar_coord", units="no_unit"))
coord = self.cube.coord("scalar_coord")
plugin = NonLinearWeights(0.85)
result = plugin.process(self.cube, coord)
self.assertArrayAlmostEqual(result.data, np.array([1.0])) | Python | nomic_cornstack_python_v1 |
function create_proxy self kind target args kwargs name=none type_expr=none proxy_factory_fn=none
begin
function upwrapper obj
begin
while call _orig_isinstance obj ConcreteProxy
begin
set obj = value
end
return obj
end function
set args_unwrapped = call map_aggregate_not_proxy args upwrapper
set kwargs_unwrapped = cal... | def create_proxy(self, kind: str, target: Target, args: Tuple[Any, ...], kwargs: Dict[str, Any],
name: Optional[str] = None, type_expr: Optional[Any] = None,
proxy_factory_fn: Optional[Callable[[Node], Any]] = None):
def upwrapper(obj: Any):
while _orig_isinst... | Python | nomic_cornstack_python_v1 |
function encrypt self message
begin
set IV = read call new BLOCK_SIZE
set aes = call new key MODE_CBC IV
return base64 encode IV + call encrypt call _pad message
end function | def encrypt(self, message):
IV = Random.new().read(self.BLOCK_SIZE)
aes = AES.new(self.key, AES.MODE_CBC, IV)
return base64.b64encode(IV + aes.encrypt(self._pad(message))) | Python | nomic_cornstack_python_v1 |
function cancel
begin
if VERBOSE
begin
print string Cancelling PyCOMPSs interactive job...
end
comment Get command line arguments
set job_ids = argv at slice 1 : :
comment Load the Supercomputer configuration to get the appropriate cancel command
call setup_supercomputer_configuration
set success = true
comment There... | def cancel():
if VERBOSE:
print("Cancelling PyCOMPSs interactive job...")
# Get command line arguments
job_ids = sys.argv[1:]
# Load the Supercomputer configuration to get the appropriate cancel command
setup_supercomputer_configuration()
success = True
# There might be more than ... | Python | nomic_cornstack_python_v1 |
function winner self
begin
for winner in winning
begin
set players = list comprehension board at pos for pos in winner
set s_players = set players
if length s_players == 1 and blank not in s_players
begin
return players at 0
end
end
if blank not in set board
begin
return string Draw
end
end function | def winner(self):
for winner in self.winning:
players = [self.board[pos] for pos in winner]
s_players = set(players)
if len(s_players) == 1 and self.blank not in s_players:
return players[0]
if self.blank not in set(self.board):
re... | Python | nomic_cornstack_python_v1 |
function test_was_published_recently_with_recent_question self
begin
set recent_question = call create_question question_text=string past days=- 1
call assertIs call was_published_recently true
end function | def test_was_published_recently_with_recent_question(self):
recent_question = create_question(question_text="past", days=-1)
self.assertIs(recent_question.was_published_recently(), True) | Python | nomic_cornstack_python_v1 |
function set_words data_path
begin
comment file -i
set w_df = read csv data_path names=list string es string gn string syn1 string syn2 encoding=string iso-8859-1
set gn_df = call drop_duplicates
set gn_lst = call tolist + call tolist + call tolist
set cleanedList = list comprehension x for x in gn_lst if string x != s... | def set_words(data_path):
w_df = pd.read_csv(data_path, names=['es','gn','syn1','syn2'], encoding='iso-8859-1') # file -i
gn_df = w_df[['gn','syn1','syn2']].drop_duplicates()
gn_lst = gn_df['gn'].tolist()+gn_df['syn1'].tolist()+gn_df['syn2'].tolist()
cleanedList = [x for x in gn_lst if str(x) != 'nan' and len(x... | Python | nomic_cornstack_python_v1 |
function rotated_array_search input_list number
begin
string Find the index by searching in a rotated sorted array Args: input_list(list): Input array to search number(int): Target to search for Returns: int: Index or -1
return call binarysearch input_list number 0 length input_list - 1
end function
function binarysear... | def rotated_array_search(input_list , number ):
"""
Find the index by searching in a rotated sorted array
Args:
input_list(list): Input array to search
number(int): Target to search for
Returns:
int: Index or -1
"""
return binarysearch(input_list, number, 0, len(... | Python | zaydzuhri_stack_edu_python |
function test_mode device
begin
set air_purifier = air_purifiers at 0
assert mode == 1
end function | def test_mode(device):
air_purifier = device.air_purifier_control.air_purifiers[0]
assert air_purifier.mode == 1 | Python | nomic_cornstack_python_v1 |
function reverse_string_replace_vowels input_string replacement_vowels
begin
string This function takes a string and a list of replacement vowels as input. It reverses the string and replaces all vowels in the original string with the corresponding vowel from the list of replacements. The replacement is done in the ord... | def reverse_string_replace_vowels(input_string, replacement_vowels):
"""
This function takes a string and a list of replacement vowels as input. It reverses the string and replaces all vowels
in the original string with the corresponding vowel from the list of replacements. The replacement is done in the or... | Python | jtatman_500k |
function flags self flags
begin
set _flags = flags
end function | def flags(self, flags):
self._flags = flags | Python | nomic_cornstack_python_v1 |
function percentage_plot best_tags best_cash
begin
set plot_legend = subplot 313
x label string $/Hour Rate
y label string Percentage
plot range HOURLY_RATE_MAX + 1 best_tags at 2 color=string blue label=string Cheap Best Tags
plot range HOURLY_RATE_MAX + 1 best_tags at 0 color=string black label=string Fast Best Tags
... | def percentage_plot(best_tags, best_cash):
plot_legend = plt.subplot(313)
plt.xlabel("$/Hour Rate")
plt.ylabel("Percentage")
plt.plot(range(HOURLY_RATE_MAX+1), best_tags[2], color='blue', label='Cheap Best Tags')
plt.plot(range(HOURLY_RATE_MAX+1), best_tags[0], color='black', label='Fast Best Tags')... | Python | nomic_cornstack_python_v1 |
function get_celeba data_path test_on_dev=true orig_data=false
begin
set dev_name = string val
if not test_on_dev
begin
set dev_name = string test
end
set ds = call CelebA attribute=attribute
load ds
set ds_test = call CelebA attribute=attribute
load ds_test split=dev_name
set train_labels = labels
set test_labels = la... | def get_celeba(data_path, test_on_dev=True, orig_data=False):
dev_name = 'val'
if not test_on_dev:
dev_name = 'test'
ds = CelebA(attribute=FLAGS.attribute)
ds.load()
ds_test = CelebA(attribute=FLAGS.attribute)
ds_test.load(split=dev_name)
train_labels = ds.labels
test_labels = ds... | Python | nomic_cornstack_python_v1 |
import pandas as pd
import numpy as np
from scipy.sparse import csr_matrix
from sklearn.feature_extraction.text import CountVectorizer
class RobustOneHotSparse
begin
function __init__ self
begin
return
end function
function listify_df self df
begin
set df = call tolist
return df
end function
function stringify_columns ... | import pandas as pd
import numpy as np
from scipy.sparse import csr_matrix
from sklearn.feature_extraction.text import CountVectorizer
class RobustOneHotSparse:
def __init__(self):
return
def listify_df(self, df):
df = df.values.tolist()
return df
def stringify_columns(self, df, ... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment AUTHOR : Avi Mehenwal
comment DATED : 11th-Dec-2013
import csv
import os
set INPUT_DIR = string /home/avimehenwal/Documents/Projects/CompanyStock/CompanyStock2
set filename = string data.csv
set answer = list
function fetchShareValue companyIndex
begin
comment function to fetch Sha... | #!/usr/bin/env python
#AUTHOR : Avi Mehenwal
#DATED : 11th-Dec-2013
import csv
import os
INPUT_DIR = '/home/avimehenwal/Documents/Projects/CompanyStock/CompanyStock2'
filename = 'data.csv'
answer = []
def fetchShareValue(companyIndex):
#function to fetch Share value from answer data structure
retu... | Python | zaydzuhri_stack_edu_python |
comment 元组,当要求数据不可变时,可用元组
comment 单个元素时为int类型
set a = 1
print type a
comment 多个元素时为元组类型
set b = tuple 1 string a 2 string a
print type b
print count b string a
print index b string a | #元组,当要求数据不可变时,可用元组
a=(1)#单个元素时为int类型
print(type(a))
b=(1,'a',2,'a')#多个元素时为元组类型
print(type(b))
print(b.count('a'))
print(b.index('a'))
| Python | zaydzuhri_stack_edu_python |
comment Kata = https://www.codewars.com/kata/54da5a58ea159efa38000836
function find_it seq
begin
for i in seq
begin
set result = 0
for j in seq
begin
if i == j
begin
set result = result + 1
end
end
if result % 2 != 0
begin
return i
end
end
end function | # Kata = https://www.codewars.com/kata/54da5a58ea159efa38000836
def find_it(seq):
for i in seq:
result=0
for j in seq:
if i==j:
result+=1
if result %2 !=0:
return i | Python | zaydzuhri_stack_edu_python |
import torch
from torch import nn , einsum
import numpy as np
from einops import rearrange , repeat
from einops.layers.torch import Rearrange
function pair t
begin
return if expression is instance t tuple then t else tuple t t
end function
class AddPositionEmbs extends Module
begin
string 向输入中添加可学习的位置嵌入模块
function __in... | import torch
from torch import nn, einsum
import numpy as np
from einops import rearrange, repeat
from einops.layers.torch import Rearrange
def pair(t):
return t if isinstance(t, tuple) else (t, t)
class AddPositionEmbs(nn.Module):
"""向输入中添加可学习的位置嵌入模块 """
def __init__(self,inputs_positions=None):
... | Python | zaydzuhri_stack_edu_python |
function list_locations self ex_available=true
begin
set locations = list
set data = call request string /regions
for location in object at string regions
begin
if ex_available
begin
if get location string available
begin
append locations call _to_location location
end
end
else
begin
append locations call _to_location... | def list_locations(self, ex_available=True):
locations = []
data = self.connection.request("/regions")
for location in data.object["regions"]:
if ex_available:
if location.get("available"):
locations.append(self._to_location(location))
... | Python | nomic_cornstack_python_v1 |
function belongs_to_psm self diagnostics=none context=none
begin
raise call NotImplementedError string operation belongs_to_psm(...) not yet implemented
end function | def belongs_to_psm(self, diagnostics=None, context=None):
raise NotImplementedError(
'operation belongs_to_psm(...) not yet implemented') | Python | nomic_cornstack_python_v1 |
function depth_first_search graph start_node
begin
set visited = list
set stack = list start_node
while stack
begin
set node = pop stack
if node not in visited
begin
append visited node
set neighbors = graph at node
extend stack neighbors
end
end
return visited
end function
set graph = dict string A list string B stri... | def depth_first_search(graph, start_node):
visited = []
stack = [start_node]
while stack:
node = stack.pop()
if node not in visited:
visited.append(node)
neighbors = graph[node]
stack.extend(neighbors)
return visited
graph = {
'A': ['B'... | Python | jtatman_500k |
import math
import time
from multiprocessing.dummy import Lock as ThreadLock
class ProgressBar
begin
global charset
set charset = string ▏▎▍▌▋▊▉█
function __init__ self maxCount maxLength=50 printCount=true printPercentage=true printTime=false
begin
set lock = call ThreadLock
set maxCount = maxCount
set currentCount = ... | import math
import time
from multiprocessing.dummy import Lock as ThreadLock
class ProgressBar:
global charset
charset = "▏▎▍▌▋▊▉█"
def __init__(self, maxCount, maxLength=50, printCount=True, printPercentage=True, printTime=False):
self.lock = ThreadLock()
self.maxCount = maxCount
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
import socket
from sys import argv
set buff_size = 4096
set tuple host port = tuple string 127.0.0.1 8000
set backlog = 5
set s = call socket AF_INET SOCK_STREAM
call setsockopt SOL_SOCKET SO_REUSEADDR 1
call bind tuple host port
call listen backlog
while true
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
from sys import argv
buff_size = 4096
host, port = "127.0.0.1", 8000
backlog = 5
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind((host,port))
s.listen(backlog)
while True:
client_sock, clien... | Python | zaydzuhri_stack_edu_python |
function to_dict_index df
begin
return call to_dict string index
end function | def to_dict_index(df):
return df.to_dict('index') | Python | nomic_cornstack_python_v1 |
function check_if_elements_is_empty json_object
begin
try
begin
if length json_object > 0
begin
set is_empty = length json_object at string elements == 0
end
else
begin
set is_empty = true
end
end
except KeyError
begin
print string TypeError [ + string TypeError + string ]
return true
end
return is_empty
end function | def check_if_elements_is_empty(json_object):
try:
if len(json_object) > 0:
is_empty = len(json_object['elements']) == 0
else:
is_empty = True
except KeyError:
print("TypeError [" + str(TypeError) + " ]")
return True
return is_empty | Python | nomic_cornstack_python_v1 |
function extract_roi_fft data4D pixel_spacing minradius_mm=15 maxradius_mm=45 kernel_width=5 center_margin=8 num_peaks=10 num_circles=20 radstep=2
begin
comment Data shape:
comment radius of the smallest and largest circles in mm estimated from the train set
comment convert to pixel counts
set tuple pixel_spacing_X pix... | def extract_roi_fft(data4D, pixel_spacing, minradius_mm=15, maxradius_mm=45, kernel_width=5,
center_margin=8, num_peaks=10, num_circles=20, radstep=2):
# Data shape:
# radius of the smallest and largest circles in mm estimated from the train set
# convert to pixel counts
pixel_spacing... | Python | nomic_cornstack_python_v1 |
set my_dic = dict string name string dhmodh ; string age 19
set person_name = get my_dic string name
print person_name
set person_age = get my_dic string age
print person_age | my_dic = {'name' : 'dhmodh', 'age' : 19}
person_name = my_dic.get('name')
print(person_name)
person_age = my_dic.get('age')
print(person_age) | Python | zaydzuhri_stack_edu_python |
for t in range 1 T + 1
begin
set N = input
for i in range 1 10
begin
if N at slice : i : == N at slice i : i * 2 :
begin
print string # { t } { i }
break
end
end
end | for t in range(1, T + 1):
N = input()
for i in range(1, 10):
if N[:i] == N[i: i * 2]:
print(f'#{t} {i}')
break | Python | zaydzuhri_stack_edu_python |
import sys
import time
from parser import parse
from greedy_sol import GreedySol
from dinamico import dinamico
if __name__ == string __main__
begin
if length argv < 2
begin
print string Uso: run.py archivo.dat <algoritmo> Algoritmos disponibles: greedy/dinamico, por defecto: greedy
end
else
begin
set tuple codigos caja... | import sys
import time
from parser import parse
from greedy_sol import GreedySol
from dinamico import dinamico
if __name__ == '__main__':
if len(sys.argv) < 2:
print(('Uso: run.py archivo.dat <algoritmo>\n\n'
'Algoritmos disponibles: greedy/dinamico, por defecto: greedy'))
else:
... | Python | zaydzuhri_stack_edu_python |
function initializePage self
begin
call initialize self
call use call QVBoxLayout
set exp = call give_exp string pressure
set grps = call find_groups call give_field string mesh
set dims = list tuple string Pressure 1.0
set tit = string Adding pressure on meshes groups
comment The last groups should be seen first
rever... | def initializePage(self):
WC.WizardPage.initialize(self)
self.page.use(qt.QVBoxLayout())
exp = self.give_field("exp-store").give_exp("pressure")
grps = exp.find_groups(self.give_field("mesh"))
dims = [(u"Pressure", 1.)]
tit = u"Adding pressure on meshes groups"
# ... | Python | nomic_cornstack_python_v1 |
function get_neighbors self vertex_id
begin
if vertex_id in vertices
begin
return vertices at vertex_id
end
else
begin
return none
end
end function | def get_neighbors(self, vertex_id):
if vertex_id in self.vertices:
return self.vertices[vertex_id]
else:
return None | Python | nomic_cornstack_python_v1 |
function hlf state r
begin
set state at r = state at r / 2
end function
function tpl state r
begin
set state at r = state at r * 3
end function
function inc state r
begin
set state at r = state at r + 1
end function
function jmp state r
begin
set state at string pc = state at string pc + integer r - 1
end function
func... | def hlf(state, r):
state[r] = state[r]/2
def tpl(state, r):
state[r] = state[r]*3
def inc(state, r):
state[r] = state[r]+1
def jmp(state, r):
state['pc'] = state['pc'] + (int(r)-1)
def jie(state, r, c):
if not state[r]%2:
state['pc'] = state['pc'] + (int(c)-1)
def jio(state, r, c):
if state[r]==1:
state[... | Python | zaydzuhri_stack_edu_python |
function _setup_fill_and_save_dates self
begin
if count gapfill_manager
begin
call setEnabled true
call setEnabled true
set mindate = min
set maxdate = max
set qdatemin = call QDate year month day
set qdatemax = call QDate year month day
call blockSignals true
call setDate qdatemin
call setMinimumDate qdatemin
call set... | def _setup_fill_and_save_dates(self):
if self.gapfill_manager.count():
self.date_start_widget.setEnabled(True)
self.date_end_widget.setEnabled(True)
mindate = (
self.gapfill_manager.worker()
.wxdatasets.metadata['first_date'].min())
... | Python | nomic_cornstack_python_v1 |
function has_cached_data_for_year self year
begin
if conn
begin
set temps = call get_temperature_table
set s = where extract string year dt == year
set result = execute conn s
set n_results = length call fetchall
return n_results > 1000
end
return false
end function | def has_cached_data_for_year(self,year):
if self.conn:
temps = self.get_temperature_table()
s = select([temps.c.dt]).where(extract('year', temps.c.dt) == year)
result = self.conn.execute(s)
n_results = len(result.fetchall())
return n_results > 1000
... | Python | nomic_cornstack_python_v1 |
function log self msg *args
begin
if args
begin
set msg = msg % args
end
call echo msg file=stderr
end function | def log(self, msg, *args):
if args:
msg %= args
click.echo(msg, file=sys.stderr) | Python | nomic_cornstack_python_v1 |
import requests
import json
set room_db = dict string rm-a dict string room_id string rm-a ; string room_name string Room A ; string time_available string Mondays-Sundays ; string location string First Floor ; string description string Accomodates 25 people. ; string rm-b dict string room_id string rm-b ; string room_n... | import requests
import json
room_db = {"rm-a" : {"room_id" : "rm-a", "room_name" : "Room A", "time_available" : "Mondays-Sundays", "location" : "First Floor", "description" : "Accomodates 25 people."},
"rm-b" : {"room_id" : "rm-b", "room_name" : "Room B", "time_available" : "Mondays-Sundays", "location" : "First F... | Python | zaydzuhri_stack_edu_python |
comment Assignment One
comment October 9th, 2018
string Develop an algorithm to calculate the average of a list elements. Implement your algorithm in Python as a function. • Develop a program that gets a list of values from the user, call the l’algorithm/function to calculate the average and print the results.
function... | #Assignment One
#October 9th, 2018
''' Develop an algorithm to calculate the
average of a list elements. Implement your
algorithm in Python as a function.
• Develop a program that gets a list of values
from the user, call the l’algorithm/function
to calculate the average and print the
results.'''
def averagecalc(listo... | Python | zaydzuhri_stack_edu_python |
function _click_on_popup_msg self text btn
begin
if not call get_top_bar_text == text
begin
error string The screen text should be " { text } ", but it was " { call get_top_bar_text } "
warning string Some part of your configuration is not valid
return false
end
else
if not call click_toolbar btn
begin
error string Una... | def _click_on_popup_msg(self, text, btn):
if not mws.get_top_bar_text() == text:
self.log.error(f"The screen text should be \"{text}\", but it was \"{mws.get_top_bar_text()}\"")
self.log.warning("Some part of your configuration is not valid")
return False
else:
... | Python | nomic_cornstack_python_v1 |
function _baseline_sam preds target reduction=string elementwise_mean
begin
set reduction_options = tuple string elementwise_mean string sum string none
if reduction not in reduction_options
begin
raise call ValueError string reduction has to be one of { reduction_options } , got: { reduction } .
end
set similarity = c... | def _baseline_sam(
preds: Tensor,
target: Tensor,
reduction: str = "elementwise_mean",
) -> Tensor:
reduction_options = ("elementwise_mean", "sum", "none")
if reduction not in reduction_options:
raise ValueError(f"reduction has to be one of {reduction_options}, got: {reduction}.")
simila... | Python | nomic_cornstack_python_v1 |
from fractions import Fraction
class Assessment
begin
function __init__ self t
begin
set t = t
set total = decimal length t * length terms
set correct = list 0 0 0 0 0
set incor = list 0 0 0 0 0
set tot_correct = decimal sum correct
call assess
set tot_ret = total - correct at 0 - incor at 0
set cor_ret = tot_correct -... | from fractions import Fraction
class Assessment:
def __init__(self,t):
self.t = t
self.total = float(len(self.t)*len(self.t.terms))
self.correct = [0,0,0,0,0]
self.incor = [0,0,0,0,0]
self.tot_correct = float(sum(self.correct))
self.assess()
self.tot_ret = s... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import matplotlib.pyplot as plt
import mplcursors
from bs4 import BeautifulSoup
import requests
set domain = string https://www.imdb.com
set top250 = string /chart/top/?ref_=nv_mv_250
set url = domain + top250
set page = get requests url
set soup = call BeautifulSoup content string html.parser
set l... | import pandas as pd
import matplotlib.pyplot as plt
import mplcursors
from bs4 import BeautifulSoup
import requests
domain = "https://www.imdb.com"
top250 = "/chart/top/?ref_=nv_mv_250"
url = domain + top250
page = requests.get(url)
soup = BeautifulSoup(page.content,"html.parser")
lister = soup.find(class_="lister... | Python | zaydzuhri_stack_edu_python |
function updateLineEditLabels self x_label=none y_label=none title=none
begin
if x_label is not none
begin
call setText x_label
end
if y_label is not none
begin
call setText y_label
end
if title is not none
begin
call setText title
end
end function | def updateLineEditLabels(self, x_label=None, y_label=None, title=None):
if x_label is not None:
self.ui.lineEditXLabel.setText(x_label)
if y_label is not None:
self.ui.lineEditYLabel.setText(y_label)
if title is not None:
self.ui.lineEditTitle.setText(title) | Python | nomic_cornstack_python_v1 |
function showoff_databases
begin
set log = call configure_logger string default string ../logs/nosql_dev.log
info string Mongodb example to use data from Furniture module, so get it
set furniture = call get_furniture_data
set roygbiv = list string Red string Orange string Yellow string Green string Blue string Indigo s... | def showoff_databases():
log = utilities.configure_logger('default', '../logs/nosql_dev.log')
log.info("Mongodb example to use data from Furniture module, so get it")
furniture = learn_data.get_furniture_data()
roygbiv = ["Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet"]
for it... | Python | nomic_cornstack_python_v1 |
function _unpack b data_type
begin
if data_type == long
begin
return call unpack string >q b at 0
end
else
if data_type == int
begin
return call unpack string >i b at 0
end
else
if data_type == str
begin
return call unpack string >%ds % length b b at 0
end
else
if data_type == unicode
begin
set unic = call unpack strin... | def _unpack(b, data_type):
if data_type == long:
return struct.unpack('>q', b)[0]
elif data_type == int:
return struct.unpack('>i', b)[0]
elif data_type == str:
return struct.unpack('>%ds' % len(b), b)[0]
elif data_type == unicode:
unic = struct.unpack('>%ds' % len(b), b... | Python | nomic_cornstack_python_v1 |
function removeFromDownloadQueue self _src
begin
for dl in downloadQueue
begin
if _src in dl at string src
begin
pop downloadQueue index downloadQueue dl
return
end
end
end function | def removeFromDownloadQueue(self, _src):
for dl in self.downloadQueue:
if _src in dl['src']:
self.downloadQueue.pop(self.downloadQueue.index(dl))
return | Python | nomic_cornstack_python_v1 |
function create_acc_loss_graph file_path device save_graph_path
begin
set state_dict = call load_metrics file_path device
set fig = figure
set ax1 = call subplot2grid tuple 2 1 tuple 0 0
set ax2 = call subplot2grid tuple 2 1 tuple 1 0 sharex=ax1
plot state_dict at string epoch_list state_dict at string train_loss_list ... | def create_acc_loss_graph(file_path, device, save_graph_path):
state_dict = load_metrics(file_path, device)
fig = plt.figure()
ax1 = plt.subplot2grid((2, 1), (0, 0))
ax2 = plt.subplot2grid((2, 1), (1, 0), sharex=ax1)
ax1.plot(
state_dict["epoch_list"], state_dict["train_loss_list"], label... | Python | nomic_cornstack_python_v1 |
comment -*- coding : utf-8 -*-
class Solution extends object
begin
function maxDepth self root
begin
string :param root: :return:
comment 1. 递归结束条件,越过叶子节点
if not root
begin
return 0
end
comment 2. 递归操作
comment 分别看左右子树的深度
set depthLeft = call maxDepth left
set depthRight = call maxDepth right
return if expression depthL... | # -*- coding : utf-8 -*-
class Solution(object):
def maxDepth(self, root):
"""
:param root:
:return:
"""
# 1. 递归结束条件,越过叶子节点
if not root:
return 0
# 2. 递归操作
# 分别看左右子树的深度
depthLeft = self.maxDepth(root.left)
depthRight = s... | Python | zaydzuhri_stack_edu_python |
function home
begin
return string Avaiable Routes:<br/>/api/v1.0/precipitation<br/>/api/v1.0/stations<br/>/api/v1.0/tobs<br/>/api/v1.0/<start><br/>/api/v1.0/<start>/<end><br/>
end function | def home():
return (
f'Avaiable Routes:<br/>'
f'/api/v1.0/precipitation<br/>'
f'/api/v1.0/stations<br/>'
f'/api/v1.0/tobs<br/>'
f'/api/v1.0/<start><br/>'
f'/api/v1.0/<start>/<end><br/>'
) | Python | nomic_cornstack_python_v1 |
import math
import os
import random
import re
import sys
function getRank scoreSet score
begin
if score in scoreSet
begin
return index scoreSet score + 1
end
else
begin
for x in range length scoreSet
begin
if score > scoreSet at x
begin
insert scoreSet x score
return x + 1
end
end
append scoreSet score
return length sc... | import math
import os
import random
import re
import sys
def getRank(scoreSet, score):
if score in scoreSet:
return scoreSet.index(score) + 1
else:
for x in range(len(scoreSet)):
if score > scoreSet[x]:
scoreSet.insert(x,score)
return x+1
scor... | Python | zaydzuhri_stack_edu_python |
function test_incorrect_content_type self
begin
set response = post string /logout
assert equal status_code UNSUPPORTED_MEDIA_TYPE
end function | def test_incorrect_content_type(self):
response = self.app.post('/logout')
self.assertEqual(response.status_code, codes.UNSUPPORTED_MEDIA_TYPE) | Python | nomic_cornstack_python_v1 |
function print_condition_suggestion_and_die missing_promise_description promise_description
begin
write stderr string Conditions in techniques not specified in + string condition vocabulary
set output_list = list
for missing in missing_promise_description
begin
set possible_match = list
for cond in promise_descriptio... | def print_condition_suggestion_and_die(missing_promise_description: Set[Text],
promise_description: Set[Text]) -> None:
sys.stderr.write("Conditions in techniques not specified in " +
"condition vocabulary\n")
output_list = []
for missing in missi... | Python | nomic_cornstack_python_v1 |
function fov_theta_rad self
begin
set fov_theta_rad = 2 * call arctan 0.5 * width_px / fx_px
return decimal fov_theta_rad
end function | def fov_theta_rad(self) -> float:
fov_theta_rad = 2 * np.arctan(0.5 * self.width_px / self.intrinsics.fx_px)
return float(fov_theta_rad) | Python | nomic_cornstack_python_v1 |
comment encoding: utf-8
comment Created by David Rideout <drideout@safaribooksonline.com> on 2/7/14 5:01 PM
comment Copyright (c) 2013 Safari Books Online, LLC. All rights reserved.
from django.test import TestCase
from lxml import etree
from storage.models import Book , Alias
import storage.tools
class TestTools exten... | # encoding: utf-8
# Created by David Rideout <drideout@safaribooksonline.com> on 2/7/14 5:01 PM
# Copyright (c) 2013 Safari Books Online, LLC. All rights reserved.
from django.test import TestCase
from lxml import etree
from storage.models import Book, Alias
import storage.tools
class TestTools(TestCase):
def se... | Python | zaydzuhri_stack_edu_python |
function color_temp self
begin
return color_temp
end function | def color_temp(self) -> int | None:
return self._device.color_temp | Python | nomic_cornstack_python_v1 |
function test_3
begin
set d = 3
set x = zeros d
assert call zakharov_func x d == 0
assert all call zakharov_grad x d == zeros d
end function | def test_3():
d = 3
x = np.zeros((d))
assert(mt_obj.zakharov_func(x, d) == 0)
assert(np.all(mt_obj.zakharov_grad(x, d) == np.zeros((d)))) | Python | nomic_cornstack_python_v1 |
function _lineIs3D linehandle
begin
return is instance linehandle Line3D
end function | def _lineIs3D(linehandle):
return isinstance(linehandle, mpl_toolkits.mplot3d.art3d.Line3D) | Python | nomic_cornstack_python_v1 |
function update_metadata ctx archive_name
begin
string Update an archive's metadata
call _generate_api ctx
set tuple args kwargs = call _parse_args_and_kwargs args
assert length args == 0 msg format string Unrecognized arguments: "{}" args
set var = call get_archive archive_name
call update_metadata metadata=kwargs
end... | def update_metadata(ctx, archive_name):
'''
Update an archive's metadata
'''
_generate_api(ctx)
args, kwargs = _parse_args_and_kwargs(ctx.args)
assert len(args) == 0, 'Unrecognized arguments: "{}"'.format(args)
var = ctx.obj.api.get_archive(archive_name)
var.update_metadata(metadata=k... | Python | jtatman_500k |
function remove_duplicates arr
begin
set seen = set
for elem in arr
begin
if elem not in seen
begin
add seen elem
end
end
return list seen
end function | def remove_duplicates(arr):
seen = set()
for elem in arr:
if elem not in seen:
seen.add(elem)
return list(seen)
| Python | flytech_python_25k |
from collections import deque
class Graph
begin
set vertices = dict
function __init__ self vertices=dict
begin
if not boolean vertices
begin
set vertices = vertices
end
end function
function add_vertex self vertex_name
begin
if vertex_name not in vertices
begin
set vertices at vertex_name = list
end
end function
func... | from collections import deque
class Graph:
vertices = {}
def __init__(self, vertices=dict):
if not bool(self.vertices):
self.vertices = vertices
def add_vertex(self, vertex_name):
if vertex_name not in self.vertices:
self.vertices[vertex_name] = []
def add_ed... | Python | zaydzuhri_stack_edu_python |
function offset self
begin
return _offset
end function | def offset(self):
return self._offset | Python | nomic_cornstack_python_v1 |
function hard_classification predicted_distribution
begin
set tuple class_ind confidence = call tensor_argmax predicted_distribution
return tuple class_ind confidence
end function | def hard_classification(predicted_distribution):
class_ind, confidence = tensor_argmax(predicted_distribution)
return class_ind, confidence | Python | nomic_cornstack_python_v1 |
function download_artifact_bundle self id_or_uri file_path
begin
string Download the Artifact Bundle. Args: id_or_uri: ID or URI of the Artifact Bundle. file_path(str): Destination file path. Returns: bool: Successfully downloaded.
set uri = DOWNLOAD_PATH + string / + call extract_id_from_uri id_or_uri
return call down... | def download_artifact_bundle(self, id_or_uri, file_path):
"""
Download the Artifact Bundle.
Args:
id_or_uri: ID or URI of the Artifact Bundle.
file_path(str): Destination file path.
Returns:
bool: Successfully downloaded.
"""
uri = se... | Python | jtatman_500k |
import pandas as pd
set users = call read_table string https://raw.githubusercontent.com/justmarkham/DAT8/master/data/u.user sep=string | index_col=string user_id
print head users 25
print string
print tail users 10
comment Numeros de datos
print string
print shape at 0
comment Numeros de columnas
print string
print sh... | import pandas as pd
users = pd.read_table('https://raw.githubusercontent.com/justmarkham/DAT8/master/data/u.user', sep='|', index_col='user_id')
print(users.head(25))
print(" ")
print(users.tail(10))
# Numeros de datos
print(" ")
print(users.shape[0])
# Numeros de columnas
print(" ")
print(users.shape[1])
# Impr... | Python | zaydzuhri_stack_edu_python |
function inner x y
begin
set n = length x
assert length y == n
set val = 0
for i in range 0 n
begin
set val = val + x at i * y at i
end
return val
end function | def inner(x, y):
n = len(x)
assert len(y) == n
val = 0
for i in range(0, n):
val = val + x[i]*y[i]
return val | Python | nomic_cornstack_python_v1 |
import random
import functools
import simpy
from SimComponents import PacketGenerator , PacketSink , SwitchPort , RandomBrancher , Packet
from Node import NetworkNode
if __name__ == string __main__
begin
set env = call Environment
comment in bytes
set mean_pkt_size = 100.0
set port_rate = 2.2 * 8 * mean_pkt_size
set ad... | import random
import functools
import simpy
from SimComponents import PacketGenerator, PacketSink, SwitchPort, RandomBrancher, Packet
from Node import NetworkNode
if __name__ == '__main__':
env = simpy.Environment()
mean_pkt_size = 100.0 # in bytes
port_rate = 2.2 * 8 * mean_pkt_size
adist1 = functo... | Python | zaydzuhri_stack_edu_python |
import random
set random_num = uniform - 1 1
print random_num | import random
random_num = random.uniform(-1,1)
print(random_num) | Python | jtatman_500k |
function safe_pawns pawns
begin
set pawns = list pawns
set count = 0
for i in pawns
begin
set ad1 = character ordinal i at 0 - 1 + string integer i at 1 - 1
set ad2 = character ordinal i at 0 + 1 + string integer i at 1 - 1
if ad1 in pawns or ad2 in pawns
begin
set count = count + 1
end
end
return count
end function
pr... | def safe_pawns(pawns):
pawns = list(pawns)
count = 0
for i in pawns:
ad1 = chr(ord(i[0])-1) + str(int(i[1])-1)
ad2 = chr(ord(i[0])+1) + str(int(i[1])-1)
if ad1 in pawns or ad2 in pawns:
count += 1
return count
print(safe_pawns({"b4", "d4", "f4", "c3", "e3",... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Fri Oct 28 19:06:28 2016 @author: root
function loadDigits fileName
begin
import numpy as np
import os
set files = list directory fileName
set samples = list
set labels = list
for eachFile in files
begin
set data = call loadtxt fileName + string / + eachFile dtype=str
c... | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 28 19:06:28 2016
@author: root
"""
def loadDigits(fileName):
import numpy as np
import os
files = os.listdir(fileName)
samples = []
labels = []
for eachFile in files:
data = np.loadtxt(fileName + "/" + eachFile, dtype=str)
#py3
# ... | Python | zaydzuhri_stack_edu_python |
function test_get_all_books_with_pagination self
begin
comment create book
set add_book = dict string title string Hello Books ; string isbn string 5698745124
set login_data = call login_test_user
set token = login_data at string auth_token
set res = post string { URL_BOOKS } headers=dictionary Authorization=string Bea... | def test_get_all_books_with_pagination(self):
# create book
add_book = {
'title': 'Hello Books',
'isbn': '5698745124'
}
login_data = self.login_test_user()
token = login_data['auth_token']
res = self.client.post(
f'{URL_BOOKS}',
headers=dict(Authorization=f'Bearer {token}'),
content_type='a... | Python | nomic_cornstack_python_v1 |
comment Copyright (C) 2012-2013 Benjamin Kehlet
comment This file is part of DOLFIN.
comment DOLFIN is free software: you can redistribute it and/or modify
comment it under the terms of the GNU Lesser General Public License as published by
comment the Free Software Foundation, either version 3 of the License, or
commen... | # Copyright (C) 2012-2013 Benjamin Kehlet
#
# This file is part of DOLFIN.
#
# DOLFIN is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later ver... | Python | zaydzuhri_stack_edu_python |
from sklearn.datasets import fetch_20newsgroups
from sklearn.naive_bayes import MultinomialNB
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer , HashingVectorizer , CountVectorizer
from sklearn.pipeline import Pipeline
from sklearn.model_selection import cross_val_score , KFold
from scipy.... | from sklearn.datasets import fetch_20newsgroups
from sklearn.naive_bayes import MultinomialNB
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer, HashingVectorizer, CountVectorizer
from sklearn.pipeline import Pipeline
from sklearn.model_selection import cross_val_score, KFold
from scipy.sta... | Python | zaydzuhri_stack_edu_python |
function grep_count word input_file
begin
set grep_process = popen list string grep string -c word input_file stdout=PIPE stderr=PIPE universal_newlines=true
set word_count = communicate grep_process
if word_count
begin
return strip word_count at 0
end
return none
end function | def grep_count(word, input_file):
grep_process = subprocess.Popen(["grep", "-c", word, input_file], \
stdout=subprocess.PIPE, \
stderr=subprocess.PIPE, \
unive... | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.