code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function append self name value
begin
string Appends the string ``value`` to the value at ``key``. If ``key`` doesn't already exist, create it with a value of ``value``. Returns the new length of the value at ``key``. :param name: str the name of the redis key :param value: str :return: Future()
with pipe as pipe
begin... | def append(self, name, value):
"""
Appends the string ``value`` to the value at ``key``. If ``key``
doesn't already exist, create it with a value of ``value``.
Returns the new length of the value at ``key``.
:param name: str the name of the redis key
:param value: st... | Python | jtatman_500k |
import sys
import requests
from requests.api import head
from bs4 import BeautifulSoup
import pandas as pd
import xlsxwriter
from datetime import datetime
set companies = list
set base_url = string https://www.finanzen.net/bilanz_guv/
set user_agent = dict string User-Agent string Mozilla/5.0 (Windows NT 10.0; Win64; ... | import sys
import requests
from requests.api import head
from bs4 import BeautifulSoup
import pandas as pd
import xlsxwriter
from datetime import datetime
companies = []
base_url = "https://www.finanzen.net/bilanz_guv/"
user_agent = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, l... | Python | zaydzuhri_stack_edu_python |
string Request库基本使用
import requests
string requests是python实现的最简单易用的HTTP库,建议爬虫使用requests库
comment response = requests.get("https://www.baidu.com")
comment print(type(response))
comment print(response.status_code)
comment print(type(response.text))
comment #print(response.text)
comment print(response.cookies)
comment pri... | '''Request库基本使用'''
import requests
'''requests是python实现的最简单易用的HTTP库,建议爬虫使用requests库'''
# response = requests.get("https://www.baidu.com")
# print(type(response))
# print(response.status_code)
# print(type(response.text))
# #print(response.text)
# print(response.cookies)
# print(response.content)
# print('='*100)
# prin... | Python | zaydzuhri_stack_edu_python |
function isothermal_depth_wyrtki1964_gradient da_PT
begin
comment make land mask based on surface layer
set da_mask = call isel z=0 * 0.0 + 1.0
comment calculate drho/dz
comment kg/m^4
set da_PT_dz = call differentiate string z
comment interpolate to finer vertical resolution (2.5m)
set da_interp = call interp z=array ... | def isothermal_depth_wyrtki1964_gradient(da_PT):
# make land mask based on surface layer
da_mask = da_PT.isel(z=0)*0.+1.
# calculate drho/dz
da_PT_dz = da_PT.differentiate('z') # kg/m^4
# interpolate to finer vertical resolution (2.5m)
da_interp = da_PT_dz.interp(z=np.arange(0,da_PT_dz.z.max(... | Python | nomic_cornstack_python_v1 |
function lexer self
begin
return call get_lexer self
end function | def lexer(self) -> Lexer:
return get_lexer(self) | Python | nomic_cornstack_python_v1 |
function mean_absolute_percentage_error y_true y_pred
begin
set tuple y_true y_pred = tuple array y_true array y_pred
return mean np absolute y_true - y_pred / y_true * 100
end function | def mean_absolute_percentage_error(y_true, y_pred):
y_true, y_pred = np.array(y_true), np.array(y_pred)
return np.mean(np.abs((y_true - y_pred) / y_true)) * 100 | Python | nomic_cornstack_python_v1 |
from unittest import TestCase
class FileSearchTest extends TestCase
begin
function test_it self
begin
import os
import shutil
import tempfile
from utils import search_file
from compat import makedirs
set path = make dir temp
try
begin
set work_dir = join path path string a/b/c/d
make directories work_dir exist_ok=true
... | from unittest import TestCase
class FileSearchTest(TestCase):
def test_it(self):
import os
import shutil
import tempfile
from ..utils import search_file
from ..compat import makedirs
path = tempfile.mkdtemp()
try:
work_dir = os.path.join(path, '... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Tue Sep 28 11:26:26 2021 @author: tepha Code1. 5.11 parillisten summa
set summa = 0
for i in range 0 1000 2
begin
set summa = summa + i
end
print summa | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 28 11:26:26 2021
@author: tepha
Code1. 5.11 parillisten summa
"""
summa = 0
for i in range(0,1000,2):
summa +=i
print(summa)
| Python | zaydzuhri_stack_edu_python |
function altaz_to_offset obj_azimuth obj_altitude azimuth altitude
begin
set daz = obj_azimuth - azimuth
set coa = cos obj_altitude
set xp0 = - cos daz * coa
set yp0 = sin daz * coa
set zp0 = sin obj_altitude
set cx = sin altitude
set sx = cos altitude
set xp1 = cx * xp0 + sx * zp0
set yp1 = yp0
set zp1 = - sx * xp0 + ... | def altaz_to_offset(obj_azimuth,obj_altitude,azimuth,altitude):
daz = obj_azimuth - azimuth
coa = cos(obj_altitude)
xp0 = -cos(daz) * coa
yp0 = sin(daz) * coa
zp0 = sin(obj_altitude)
cx = sin(altitude)
sx = cos(altitude)
xp1 = cx*xp0 + sx*zp0
yp1 = yp0
zp1 = -sx*xp0 + cx*zp0
... | Python | nomic_cornstack_python_v1 |
from airflow.hooks.postgres_hook import PostgresHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
from airflow.contrib.hooks.aws_hook import AwsHook
class StageToRedshiftOperator extends BaseOperator
begin
set ui_color = string #358140
set copy_sql = string COPY {} FROM '{... | from airflow.hooks.postgres_hook import PostgresHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
from airflow.contrib.hooks.aws_hook import AwsHook
class StageToRedshiftOperator(BaseOperator):
ui_color = '#358140'
copy_sql = """
COPY {}
FROM ... | Python | zaydzuhri_stack_edu_python |
function iter_selected_events_stations self
begin
set events = list call iter_selected_events
comment Look for any event-based distance filter
set distance_range = call get_event_distances
if distance_range
begin
comment Event locations by id
set event_locations = dictionary call iter_selected_event_locations
end
else
... | def iter_selected_events_stations(self):
events = list(self.iter_selected_events())
# Look for any event-based distance filter
distance_range = self.station_options.get_event_distances()
if distance_range:
# Event locations by id
event_locations = dict(self.iter... | Python | nomic_cornstack_python_v1 |
function longest_common_substring str1 str2
begin
comment Strip leading and trailing whitespace
set str1 = strip str1
set str2 = strip str2
comment Get the lengths of the input strings
set len1 = length str1
set len2 = length str2
comment Create a matrix to store the lengths of common substrings
set matrix = list compr... | def longest_common_substring(str1, str2):
# Strip leading and trailing whitespace
str1 = str1.strip()
str2 = str2.strip()
# Get the lengths of the input strings
len1 = len(str1)
len2 = len(str2)
# Create a matrix to store the lengths of common substrings
matrix = [[0] * (len2 +... | Python | greatdarklord_python_dataset |
function __repr__ self
begin
return format string <Genome(id='{}',desc='{}')> genome_id description
end function | def __repr__(self) -> str:
return "<Genome(id='{}',desc='{}')>".format(self.genome_id, self.description) | Python | nomic_cornstack_python_v1 |
function updateUserPage self user
begin
try
begin
set tuple iList sList = userDict at user
end
except Exception as _exc
begin
return string
end
set page = string
set style = string
for idx in call xrange 0 length iList
begin
set lfn = iList at idx
end
end function | def updateUserPage(self, user):
try:
iList, sList = self.userDict[user]
except Exception as _exc:
return ""
page = ""
style = ""
for idx in xrange(0, len(iList)):
lfn = iList[idx] | Python | nomic_cornstack_python_v1 |
function get_by_id cm_id caller_id news_id
begin
return dict
end function | def get_by_id(cm_id, caller_id, news_id):
return News.get(news_id).dict | Python | nomic_cornstack_python_v1 |
import sys
import json
import unicodedata
comment Global Data
set sentDict = dict
set tags = dict
set sent_file = open argv at 1
set tweet_file = open argv at 2
set statesent = dict | import sys
import json
import unicodedata
# Global Data
sentDict = {}
tags = {}
sent_file = open(sys.argv[1])
tweet_file = open(sys.argv[2])
statesent = {}
| Python | zaydzuhri_stack_edu_python |
string Open file
set filename = string input.txt
with open filename as f
begin
set content = read lines f
end
set valid_counter = 0
for line in content
begin
set list min_max target_char_dirty password = split line string
set min_num = integer split min_max string - at 0
set max_num = integer split min_max string - at ... | ''' Open file '''
filename = 'input.txt'
with open(filename) as f:
content = f.readlines()
valid_counter = 0
for line in content:
[min_max, target_char_dirty, password] = line.split(" ")
min_num = int(min_max.split("-")[0])
max_num = int(min_max.split("-")[1])
target_char = target_char_dirty[:-1]
... | Python | zaydzuhri_stack_edu_python |
function training_mlp_any_layers_with_number_iterations self X Y number_iterations=100000 learning_rate=0.1 epsilon=1e-05 log_mse=false
begin
set epochs = list
set mse = list
set current_mse_cost = 0
comment Loop
for i in range number_iterations
begin
comment MSE of the last epoch
set previous_mse_cost = current_mse_... | def training_mlp_any_layers_with_number_iterations(self, X, Y, number_iterations=100000, learning_rate=0.1, epsilon=1e-5, log_mse=False):
epochs = []
mse = []
current_mse_cost = 0
# Loop
for i in range(number_iterations):
# MSE of the last epoc... | Python | nomic_cornstack_python_v1 |
function label self newLabel
begin
call SetLabel newLabel
end function | def label(self, newLabel):
self.staticpanel.SetLabel(newLabel) | Python | nomic_cornstack_python_v1 |
function ids cls values itype=none
begin
string http://www.elasticsearch.org/guide/reference/query-dsl/ids-filter.html Filters documents that only have the provided ids. Note, this filter does not require the _id field to be indexed since it works using the _uid field.
set instance = call cls ids=dict string values val... | def ids(cls, values, itype=None):
'''
http://www.elasticsearch.org/guide/reference/query-dsl/ids-filter.html
Filters documents that only have the provided ids. Note, this filter does not require the _id field to be indexed since it works using the _uid field.
'''
instance = cls(ids={'va... | Python | jtatman_500k |
function delAttribute self key setNone=true
begin
if call hasAttribute key
begin
if setNone
begin
set dict at key = none
end
else
begin
del dict at key
end
end
end function | def delAttribute(self, key:str, setNone:bool = True) -> None:
if self.hasAttribute(key):
if setNone:
self.dict[key] = None
else:
del self.dict[key] | Python | nomic_cornstack_python_v1 |
import time
import random
import typer
from pathlib import Path
from aiohttp.client import ClientSession
from bs4 import BeautifulSoup
from libgen_dl.domain.book import Book
from libgen_dl.config import socks_names , user_agents
from aiohttp_socks import ProxyConnector
import pylibgen
class BookDownloader extends objec... | import time
import random
import typer
from pathlib import Path
from aiohttp.client import ClientSession
from bs4 import BeautifulSoup
from libgen_dl.domain.book import Book
from libgen_dl.config import socks_names, user_agents
from aiohttp_socks import ProxyConnector
import pylibgen
class BookDownloader(object):
... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import matplotlib.pyplot as plt
from math import floor
import taichi as ti
call init arch=gpu
decorator kernel
function foo
begin
set a = call Vector list 0 2
set b = call Vector list 1 0
set c = call cols list a b
set area = absolute call cross b * 0.5
set B = call inverse
set aa = call Vector list ... | import numpy as np
import matplotlib.pyplot as plt
from math import floor
import taichi as ti
ti.init(arch=ti.gpu)
@ti.kernel
def foo():
a = ti.Vector([0, 2])
b = ti.Vector([1, 0])
c = ti.Matrix.cols([a, b])
area = abs(a.cross(b))*0.5
B = c.inverse()
aa = ti.Vector([0.1, 2])
bb = ti.Vecto... | Python | zaydzuhri_stack_edu_python |
from collections import namedtuple
from datetime import date
import pandas as pd
set DATA_FILE = string weather-ann-arbor.csv
set STATION = named tuple string Station string ID Date Value
function high_low_record_breakers_for_2015
begin
string Extract the high and low record breaking temperatures for 2015 The expected ... | from collections import namedtuple
from datetime import date
import pandas as pd
DATA_FILE = "weather-ann-arbor.csv"
STATION = namedtuple("Station", "ID Date Value")
def high_low_record_breakers_for_2015():
"""Extract the high and low record breaking temperatures for 2015
The expected value will be a tuple... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import numpy as np
set features = list string event string trackster string x string y string z string r string layer string E string nHits string phi string eta
function read_dataset_by_event filepath
begin
set data = call read_hdf filepath
comment data = data.head(1000)
comment filter out all dang... | import pandas as pd
import numpy as np
features = ['event', 'trackster', 'x', 'y', 'z', 'r', 'layer', 'E', 'nHits', 'phi', 'eta' ]
def read_dataset_by_event( filepath ):
data = pd.read_hdf( filepath )
#data = data.head(1000)
data = data.loc[ data['trackster'] != 0.0 ] # filter out all dangling layer clus... | Python | zaydzuhri_stack_edu_python |
async function _receive_loop self
begin
string Receive the response to a request made to the Watchman service. Note that when trying to receive a PDU from the Watchman service, we might get a unilateral response to a subscription or log, so these are processed and queued up for later retrieval. This function only retur... | async def _receive_loop(self):
"""Receive the response to a request made to the Watchman service.
Note that when trying to receive a PDU from the Watchman service,
we might get a unilateral response to a subscription or log, so these
are processed and queued up for later retrieval. This... | Python | jtatman_500k |
function btw n
begin
set binary = list string .
set count = 0
while n != 0
begin
if n >= 2 ^ - count + 1
begin
append binary string 1
set n = n - 2 ^ - count + 1
end
else
begin
append binary string 0
end
set count = count + 1
if count == 33
begin
return string ERROR
end
end
return join string binary
end function | def btw(n):
binary = ['.']
count = 0
while n != 0:
if n >= 2 ** -(count+1):
binary.append('1')
n -= 2 ** -(count+1)
else:
binary.append('0')
count += 1
if count == 33:
return "ERROR"
return ''.join(binary)
| Python | zaydzuhri_stack_edu_python |
function calcBMI
begin
set h = decimal input string 你的身高(cm):
set w = decimal input string 你的體重(kg):
set bmi = w / h / 100 ^ 2
set result = if expression 18 < bmi <= 23 then string 正常 else if expression bmi > 23 then string 過高 else string 過低
print string 身高: %.1f cm 體重: %.1f kg BMI: %.2f (%s) % tuple h w bmi result
end... | def calcBMI():
h = float(input("你的身高(cm): "))
w = float(input("你的體重(kg): "))
bmi = w / ((h/100)**2)
result = "正常" if 18 < bmi <= 23 else "過高" if bmi > 23 else "過低"
print("身高: %.1f cm 體重: %.1f kg BMI: %.2f (%s)" % (h, w, bmi,result))
def menu():
print("BMI計算系統")
print("----------")
pri... | Python | zaydzuhri_stack_edu_python |
from run import main , parse
class TestParsing
begin
function test_valid_place_cmd self
begin
set tuple cmd args = parse string PLACE 1,2,NORTH
assert cmd == string PLACE
assert args at string x == 1
assert args at string y == 2
assert args at string f == string NORTH
end function
function test_valid_move_cmd self
begi... | from run import main, parse
class TestParsing:
def test_valid_place_cmd(self):
(cmd, args) = parse('PLACE 1,2,NORTH\n')
assert cmd == 'PLACE'
assert args['x'] == 1
assert args['y'] == 2
assert args['f'] == 'NORTH'
def test_valid_move_cmd(self):
(cmd, args) = pa... | Python | zaydzuhri_stack_edu_python |
import requests
import json
import PyICU
function translate2thai txt
begin
set english2thai = call createInstance string English-Thai
return call transliterate txt
end function
function isThai chr
begin
set cVal = ordinal chr
if cVal >= 3584 and cVal <= 3711
begin
return true
end
return false
end function
function warp... | import requests
import json
import PyICU
def translate2thai(txt):
english2thai = PyICU.Transliterator.createInstance('English-Thai')
return english2thai.transliterate(txt)
def isThai(chr):
cVal = ord(chr)
if(cVal >= 3584 and cVal <= 3711):
return True
return False
def warp(txt):
#p... | Python | zaydzuhri_stack_edu_python |
from flask.views import MethodView
from models import Goods , Category
from flask import jsonify , request
from schemas import ShopSchema
from marshmallow import ValidationError
import re
import json
class ShopResource extends MethodView
begin
decorator staticmethod
function get id_key=none
begin
if id_key
begin
try
be... | from flask.views import MethodView
from models import Goods, Category
from flask import jsonify, request
from schemas import ShopSchema
from marshmallow import ValidationError
import re
import json
class ShopResource(MethodView):
@staticmethod
def get(id_key=None):
if id_key:
try:
... | Python | zaydzuhri_stack_edu_python |
import re
function validate_pin str
begin
if match string ^[0-9]{4}$ str or match string ^[0-9]{6}$ str
begin
return true
end
else
begin
return false
end
end function
set p = call validate_pin string a234 | import re
def validate_pin(str):
if re.match('^[0-9]{4}$', str) or re.match('^[0-9]{6}$', str):
return True
else:
return False
p = validate_pin("a234") | Python | zaydzuhri_stack_edu_python |
function get_substring_index string substring
begin
if substring not in string
begin
return - 1
end
else
begin
return index string substring
end
end function
set string = string hello
set sub = string ello
print call get_substring_index string sub
set string = string hello
set sub = string llo
print call get_substring_... | def get_substring_index(string, substring):
if substring not in string:
return -1
else:
return string.index(substring)
string = "hello"
sub = "ello"
print(get_substring_index(string, sub))
string = "hello"
sub = "llo"
print(get_substring_index(string, sub))
string = "hello"
sub = "o"
print(get... | Python | zaydzuhri_stack_edu_python |
comment Enoncé : Votre programme demande à l'utilisateur d'entrer un chiffre, ce chiffre représentera le sexe la personne (1:femme 2:homme 3:autre)
comment En fonction de l'entrée donnée, le programme donnera un résultat différent, le programme saluera la personne en prenant en compte son sexe,
comment (Boujour Madame/... | # Enoncé : Votre programme demande à l'utilisateur d'entrer un chiffre, ce chiffre représentera le sexe la personne (1:femme 2:homme 3:autre)
# En fonction de l'entrée donnée, le programme donnera un résultat différent, le programme saluera la personne en prenant en compte son sexe,
# (Boujour Madame/Boujour Monsieur/... | Python | zaydzuhri_stack_edu_python |
import numpy as np
set nx = 1000
set ny = 1000
set factor = 10
set x = reshape linear space 0 1 nx / factor * ny / factor nx / factor ny / factor
for i in range nx / 3 * factor 2 * nx / 3 * factor
begin
for j in range ny / 3 * factor 2 * ny / 3 * factor
begin
set x at i at j = 1
end
end | import numpy as np
nx = 1000
ny = 1000
factor = 10
x = np.linspace(0,1,(nx/factor)*(ny/factor)).reshape(nx/factor,ny/factor)
for i in range(nx/(3*factor),2*nx/(3*factor)):
for j in range(ny/(3*factor),2*ny/(3*factor)):
x[i][j] = 1 | Python | zaydzuhri_stack_edu_python |
function face_location self image position
begin
set point1 = tuple 500 600
set point2 = tuple 500 200
set point3 = tuple 700 600
set point4 = tuple 700 200
set p = tuple 0 0
set face_cascade = call CascadeClassifier string Data/haarcascade_frontalface_default.xml
set image = array image
comment Convert RGB to BGR
set ... | def face_location(self, image, position):
point1 = (500, 600)
point2 = (500, 200)
point3 = (700, 600)
point4 = (700, 200)
p = (0, 0)
face_cascade = cv2.CascadeClassifier('Data/haarcascade_frontalface_default.xml')
image = np.array(image)
# Convert RGB to B... | Python | nomic_cornstack_python_v1 |
import time
class Core
begin
set puzzle_input_dir = string ../puzzle_input/
function __init__ self day
begin
set day = day
set start_time = 0
end function
function get_input_filename self extension=string .txt
begin
return puzzle_input_dir + string day + extension
end function
function get_invalid_input_filename self e... | import time
class Core:
puzzle_input_dir = "../puzzle_input/"
def __init__(self, day):
self.day = day
self.start_time = 0
def get_input_filename(self, extension=".txt"):
return self.puzzle_input_dir + str(self.day) + extension
def get_invalid_input_filename(self, extension="... | Python | zaydzuhri_stack_edu_python |
function get_model self
begin
return copy R_hat
end function | def get_model(self):
return self.R_hat.copy() | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Thu Apr 30 18:13:50 2020 @author: santi
set lista = list
set numerador = 1
set denominador = 1
for a in range 1 10
begin
for b in range 1 10
begin
for c in range 1 10
begin
if 10 * b + a / 10 * a + c == b / c != 1
begin
set numerador = numerador * b
set denominador = den... | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 30 18:13:50 2020
@author: santi
"""
lista = []
numerador = 1
denominador = 1
for a in range(1,10):
for b in range (1,10):
for c in range(1,10):
if (10*b+a)/(10*a+c) == b/c != 1:
numerador *= b
denominador... | Python | zaydzuhri_stack_edu_python |
function download self
begin
comment check timestamp
set label_url = url
info string Downloading %s. % label_url
call url_retrieve label_url local_label_path
info string Downloading %s. table_url
call url_retrieve table_url local_table_path
print string Downloaded { local_label_path } and { local_table_path }
if key ==... | def download(self:Index):
# check timestamp
label_url = self.url
logger.info("Downloading %s." % label_url)
utils.url_retrieve(label_url, self.local_label_path)
logger.info("Downloading %s.", self.table_url)
utils.url_retrieve(self.table_url, self.local_table_path)
print(f"Downloaded {self.l... | Python | nomic_cornstack_python_v1 |
comment author: Ziming Guo
comment time: 2020/2/7
string 作业3: 连续获取字符,生成列表,以空字符串为结束 计算列表中最小值(不使用min)
set list01 = list
while true
begin
set str01 = input string 请输入一个数字:
if str01 == string
begin
break
end
append list01 str01
end
comment 将所有获取的字符放入列表
set min_list01 = list01 at 0
for i in range 1 length list01
begin
com... | # author: Ziming Guo
# time: 2020/2/7
'''
作业3:
连续获取字符,生成列表,以空字符串为结束
计算列表中最小值(不使用min)
'''
list01 = []
while True:
str01 = input("请输入一个数字:")
if str01 == "":
break
list01.append(str01)
# 将所有获取的字符放入列表
min_list01 = list01[0]
for i in range(1, len(list01)):
if int(min_list01) > int(list01[i])... | Python | zaydzuhri_stack_edu_python |
function get_resul self
begin
return dict string W W
end function | def get_resul(self):
return {'W': self.W} | Python | nomic_cornstack_python_v1 |
function get_editable_fields self
begin
for fieldName in schema
begin
if call has_field_permission fieldName string edit
begin
yield left strip fieldName string _
end
end
end function | def get_editable_fields(self):
for fieldName in self.schema:
if self.has_field_permission(fieldName, 'edit'):
yield fieldName.lstrip('_') | Python | nomic_cornstack_python_v1 |
comment Hello World program in Python
set x = - 1234
set negFlag = 0
set num = x
if x < 0
begin
set num = - x
set negFlag = 1
print negFlag
end
set ctr = 0
set digits = list
set ln = length string num
set retNum = 0
while ctr < ln
begin
set divr = 10 ^ ctr
set temp = num / divr % 10
set retNum = retNum + temp * 10 ^ l... | # Hello World program in Python
x = -1234
negFlag = 0
num = x
if x < 0:
num = -x
negFlag = 1
print (negFlag)
ctr = 0
digits = []
ln = len(str(num))
retNum=0
while (ctr < ln ):
divr = 10**ctr
temp = (num/divr )%10
retNum += temp * (10**(ln-ctr-1))
ctr += 1
if negFlag:
... | Python | zaydzuhri_stack_edu_python |
string The file is full of a bunch of commands i was experimenting with analyzing text i pulled off linkedin. It will NOT run as a complete program.
comment pylint: skip-file
comment setup NLP env
import nltk
from nltk.tokenize import word_tokenize , sent_tokenize
from nltk.corpus import stopwords
from string import pu... | """
The file is full of a bunch of commands i was experimenting with analyzing text
i pulled off linkedin. It will NOT run as a complete program.
"""
# pylint: skip-file
# setup NLP env
import nltk
from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.corpus import stopwords
from string import punctuatio... | Python | zaydzuhri_stack_edu_python |
function insert self jobModels
begin
assert cursor is not none
set jobModelDicts : List at Dict at tuple str str = list comprehension call toDict for jobModel in jobModels
call executemany INSERT_JOBS jobModelDicts
commit self
return rowcount
end function | def insert(self, jobModels: List[JobModel]) -> Any:
assert(self.cursor is not None)
jobModelDicts: List[Dict[str, str]] = [jobModel.toDict()
for jobModel in jobModels]
self.cursor.executemany(INSERT_JOBS, jobModelDicts)
self.commit()
... | Python | nomic_cornstack_python_v1 |
function test_perfect_horizontal_line
begin
set X = array range 100 at tuple slice : : none
set y = zeros tuple 100
set estimator = linear regression
set ransac_estimator = call RANSACRegressor estimator random_state=0
fit ransac_estimator X y
call assert_allclose coef_ 0.0
call assert_allclose intercept_ 0.0
end fu... | def test_perfect_horizontal_line():
X = np.arange(100)[:, None]
y = np.zeros((100,))
estimator = LinearRegression()
ransac_estimator = RANSACRegressor(estimator, random_state=0)
ransac_estimator.fit(X, y)
assert_allclose(ransac_estimator.estimator_.coef_, 0.0)
assert_allclose(ransac_estima... | Python | nomic_cornstack_python_v1 |
for n in filter lambda n -> n % 2 == 0 nums
begin
print n
end
for n in filter lambda n -> n > 25 nums
begin
print n
end | for n in filter(lambda n : n % 2 == 0,nums):
print(n)
for n in filter(lambda n : n > 25 ,nums):
print(n)
| Python | zaydzuhri_stack_edu_python |
function normal_input user_input
begin
set user_input = call no_punct user_input
set user_input = call no_whitespace user_input
set normal_lst = split user_input
set filtered = call refine_words normal_lst
return filtered
end function | def normal_input(user_input):
user_input = no_punct(user_input)
user_input = no_whitespace(user_input)
normal_lst = user_input.split()
filtered = refine_words(normal_lst)
return filtered | Python | nomic_cornstack_python_v1 |
import pandas as pd
import time
from query.knowledge_graph import Knowledge_Graph , Namespaces , get_text_prefix , replace_prefix
set output_location = string ./query/output/
string Query: What are the top 5 vehicle types that were involved in the most accidents in Manhattan due to ice? Developer: Andreas Saplacan
func... | import pandas as pd
import time
from query.knowledge_graph import Knowledge_Graph, Namespaces, get_text_prefix, replace_prefix
output_location = "./query/output/"
"""
Query: What are the top 5 vehicle types that were involved in the most accidents in Manhattan due to ice?
Developer: Andreas Saplacan
"""
def start():
... | Python | zaydzuhri_stack_edu_python |
comment this is a code for making a chatbot. import the "time" module to have pauses.
import time
print string hello there ! my name is Uoxo123, and i want to have a little chat with you.
set name = input string what is your name?:
comment time for user to read full thing
sleep 3
print string ah, name string is a very ... | # this is a code for making a chatbot. import the "time" module to have pauses.
import time
print('hello there ! my name is Uoxo123, and i want to have a little chat with you.')
name = input('what is your name?: ')
time.sleep(3) # time for user to read full thing
print('ah,', name, ' is a very nice name.')
# talk abo... | Python | zaydzuhri_stack_edu_python |
function query self
begin
if DEBUG > 0
begin
print string >query
end
if not valid_login
begin
if DEBUG > 0
begin
print string >query() = False
end
return false
end
set query_headers = dictionary common_headers keyword query_headers
set baseurl = BASEURL + string /Device/CheckDataSession/ + string deviceid + string ?_= ... | def query(self):
if self.DEBUG > 0:
print (">query")
if not self.valid_login:
if self.DEBUG > 0:
print (">query() = False")
return False
query_headers = dict(self.common_headers, **self.query_headers)
baseurl = self.BASEURL + '/Device... | Python | nomic_cornstack_python_v1 |
function issuer_mode self
begin
return get pulumi self string issuer_mode
end function | def issuer_mode(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "issuer_mode") | Python | nomic_cornstack_python_v1 |
string Download notMNIST and generate a pickle file Author: Rowel Atienza Project: https://github.com/roatienza/Deep-Learning-Experiments
comment On command line: python3 mnist_a2j_2pickle.py
comment Prerequisite: tensorflow (see tensorflow.org)
comment from __future__ import print_function
comment import numpy as np
i... | """
Download notMNIST and generate a pickle file
Author: Rowel Atienza
Project: https://github.com/roatienza/Deep-Learning-Experiments
"""
# On command line: python3 mnist_a2j_2pickle.py
# Prerequisite: tensorflow (see tensorflow.org)
# from __future__ import print_function
# import numpy as np
import pickle
import n... | Python | zaydzuhri_stack_edu_python |
import re
set fd1 = open string authors string r
set reg = string [a-я|А-Я|ё| ]*
set pat = compile reg
set reg2 = string [^ ].*[^ ]
set pat2 = compile reg2
for line in fd1
begin
comment print(line)
set z = find all line
end | import re
fd1=open('authors', 'r')
reg=r'[a-я|А-Я|ё| ]*'
pat=re.compile(reg)
reg2=r'[^ ].*[^ ]'
pat2=re.compile(reg2)
for line in fd1:
#print(line)
z=pat.findall(line) | Python | zaydzuhri_stack_edu_python |
function add_namespaces specification
begin
for ns in specification at string namespaces
begin
set specification at string namespaces at ns at string list = list
set specification at string namespaces at ns at string list_long = list
set specification at string namespaces at ns at string list_short = list
set specif... | def add_namespaces(specification):
for ns in specification["namespaces"]:
specification["namespaces"][ns]["list"] = []
specification["namespaces"][ns]["list_long"] = []
specification["namespaces"][ns]["list_short"] = []
specification["namespaces"][ns]["to_short"] = {}
speci... | Python | nomic_cornstack_python_v1 |
function test_upload_collection_instrument_failure self
begin
with call RequestsMock as rsps
begin
add rsps POST ci_upload_url status=500 json=dict string errors list string Failed to publish upload message
with call app_context
begin
set file = call create_test_file
set tuple upload_success error_text = call upload_co... | def test_upload_collection_instrument_failure(self):
with responses.RequestsMock() as rsps:
rsps.add(rsps.POST, ci_upload_url, status=500, json={"errors": ["Failed to publish upload message"]})
with self.app.app_context():
file = self.create_test_file()
up... | Python | nomic_cornstack_python_v1 |
function readWrite self
begin
call _rwFileID
call _rw1DRecord
call _rw2DRecord
end function | def readWrite(self):
self._rwFileID()
self._rw1DRecord()
self._rw2DRecord() | Python | nomic_cornstack_python_v1 |
from repo import FileRepo
from controller import Service
from entities import Address
import unittest
class TestExam extends TestCase
begin
function setUp self
begin
setup TestCase self
end function
function tearDown self
begin
teardown TestCase self
end function
function testGetNearAdr self
begin
set repo = call FileR... | from repo import FileRepo
from controller import Service
from entities import Address
import unittest
class TestExam(unittest.TestCase):
def setUp(self):
unittest.TestCase.setUp(self)
def tearDown(self):
unittest.TestCase.tearDown(self)
def testGetNearAdr(self):
repo = FileRepo("t... | Python | zaydzuhri_stack_edu_python |
function kde_gauss data_a data_b sigma
begin
set m = length data_b
set log_likelihood = 0.0
comment get the log-probability of each sample in data_b
for i in call prange m
begin
set log_likelihood_i = call compute_log_prob x=data_b at i mu=data_a sigma=sigma
set log_likelihood = log_likelihood + log_likelihood_i
end
se... | def kde_gauss(data_a: np.ndarray, data_b: np.ndarray, sigma: float) -> float:
m = len(data_b)
log_likelihood = 0.
# get the log-probability of each sample in data_b
for i in prange(m):
log_likelihood_i = compute_log_prob(x=data_b[i], mu=data_a, sigma=sigma)
log_likelihood += log_likelih... | Python | nomic_cornstack_python_v1 |
function init_host self host
begin
if _drv_nodes is none
begin
call set_nodes list host
end
set args = tuple tenant_id client_id client_secret subscription_id
set compute_client = call get_compute_client *args
set resource_client = call get_resource_client *args
set network_client = call get_network_client *args
set is... | def init_host(self, host):
if self._drv_nodes is None:
self.set_nodes([nova_conf.host])
args = (drv_conf.tenant_id, drv_conf.client_id, drv_conf.client_secret,
drv_conf.subscription_id)
self.compute_client = utils.get_compute_client(*args)
self.resource_clien... | Python | nomic_cornstack_python_v1 |
import tweepy
import wikipedia
from datetime import datetime as dt
import time
import twitterkeys as tk
import requests
import random
comment constructs the URL that is to be posted
function urlConstruction topic
begin
set temp = replace topic string string _
set fin = string https://en.wikipedia.org/wiki/ + temp
retu... | import tweepy
import wikipedia
from datetime import datetime as dt
import time
import twitterkeys as tk
import requests
import random
#constructs the URL that is to be posted
def urlConstruction(topic):
temp = topic.replace(' ','_')
fin = "https://en.wikipedia.org/wiki/"+temp
return fin
#post the tweet
de... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function restoreIpAddresses self s
begin
return call traverse s 3
end function
function traverse self s points
begin
if points == 0
begin
if call isValid s
begin
return list s
end
else
begin
return list none
end
end
set ans = list
for i in range 3
begin
if call isValid s at slice - i - 1 : :
begi... | class Solution:
def restoreIpAddresses(self, s):
return self.traverse(s, 3)
def traverse(self, s, points):
if points == 0:
if self.isValid(s):
return [s]
else:
return [None]
ans = []
for i in range(3):
if self.i... | Python | zaydzuhri_stack_edu_python |
function to_dict self
begin
set result = dict
for tuple attr _ in call iteritems swagger_types
begin
set value = get attribute self attr
if is instance value list
begin
set result at attr = list map lambda x -> if expression has attribute x string to_dict then call to_dict else x value
end
else
if has attribute value ... | def to_dict(self):
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
... | Python | nomic_cornstack_python_v1 |
comment ! /usr/bin/env python
import sys
import json
import csv
function load_file fn
begin
with open fn string r as f
begin
return loads read f
end
end function
function analyze j
begin
print length j
set out_rows = list
for info in j
begin
set instance_type = info at string instance_type
try
begin
set on_demand = in... | #! /usr/bin/env python
import sys
import json
import csv
def load_file(fn):
with open(fn, 'r') as f:
return json.loads(f.read())
def analyze(j):
print(len(j))
out_rows = []
for info in j:
instance_type = info['instance_type']
try:
on_demand = info['pricing']['us-e... | Python | zaydzuhri_stack_edu_python |
from models.system import System
from database.area_repo import get_one_area
function get_one_system code_system
begin
set system = get objects code=code_system
return system
end function
function get_all_systems
begin
set systems = call objects
return systems
end function
function insert_one_system area_code system
be... | from models.system import System
from database.area_repo import get_one_area
def get_one_system(code_system):
system = System.objects.get(code=code_system)
return system
def get_all_systems():
systems = System.objects()
return systems
def insert_one_system(area_code, system):
area = get_one_ar... | Python | zaydzuhri_stack_edu_python |
from gandalf_vs_saruman import gandalf_vs_saruman
function test_no_winner
begin
set gandalf_spells = list 2 3 4 5 6 2 2
set saruman_spells = list 3 4 3 2 7 5 1
assert call gandalf_vs_saruman gandalf_spells saruman_spells == string NO WINNER
end function
function test_saruman_wins
begin
set gandalf_spells = list 2 3 4 5... | from gandalf_vs_saruman import gandalf_vs_saruman
def test_no_winner():
gandalf_spells = [2, 3, 4, 5, 6, 2, 2]
saruman_spells = [3, 4, 3, 2, 7, 5, 1]
assert gandalf_vs_saruman(gandalf_spells, saruman_spells) == "NO WINNER"
def test_saruman_wins():
gandalf_spells = [2, 3, 4, 5, 6, 2, 2]
saruman_s... | Python | zaydzuhri_stack_edu_python |
function __setitem__ self key value
begin
set data at string key = value
end function | def __setitem__(self, key, value):
self.data[str(key)] = value | Python | nomic_cornstack_python_v1 |
function test_PingUnexistingHost self
begin
set p = call Pinger string 1.0.1.0
assert false call ping
end function | def test_PingUnexistingHost(self):
p = Pinger("1.0.1.0")
self.assertFalse( p.ping() ) | Python | nomic_cornstack_python_v1 |
function status self
begin
return get pulumi self string status
end function | def status(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "status") | Python | nomic_cornstack_python_v1 |
comment 1.
import math
import numpy
function func_fm x
begin
set C = 50
set H = 30
set Q = list comprehension square root 2 * C * D / H for D in x
print Q
end function
call func_fm list 20 30
comment 2.
class Shape extends object
begin
function __init__ self
begin
pass
end function
function func_area self
begin
return ... | #1.
import math
import numpy
def func_fm(x):
C=50
H=30
Q=[ math.sqrt((2*C*D)/H) for D in x ]
print(Q)
func_fm([20,30])
#2.
class Shape(object):
def __init__(self):
pass
def func_area(self):
return 0
class Square (Shape):
def __init__(self,l):
self.length = l
... | Python | zaydzuhri_stack_edu_python |
function get_personality_name self
begin
return __personality_name
end function | def get_personality_name(self):
return self.__personality_name | Python | nomic_cornstack_python_v1 |
import numpy as np
class Detector extends object
begin
function __init__ self width height pixel_size=2e-05
begin
set width = width
set height = height
set pixelSize = pixel_size
end function
comment self.resPixPerMM = 1.0/(1e-3*pixelSize)
function setFilter self
begin
pass
end function
function getMeshRep self
begin
s... | import numpy as np
class Detector(object):
def __init__(self, width, height, pixel_size=20e-6):
self.width=width
self.height=height
self.pixelSize = pixel_size
#self.resPixPerMM = 1.0/(1e-3*pixelSize)
def setFilter(self):
pass
def getMesh... | Python | zaydzuhri_stack_edu_python |
import attr
from typing import List , Optional , Dict
from collections import defaultdict
from enum import Enum
from IPython.display import HTML , display
decorator s
class BookSection
begin
comment TODO somehow these can be float??
set page_number_begin : int = call ib
set page_number_end : int = call ib
set image_num... | import attr
from typing import List, Optional, Dict
from collections import defaultdict
from enum import Enum
from IPython.display import HTML, display
@attr.s
class BookSection:
# TODO somehow these can be float??
page_number_begin: int = attr.ib()
page_number_end: int = attr.ib()
image_number_begin:... | Python | zaydzuhri_stack_edu_python |
import pygame
class Peca extends Sprite
begin
function __init__ self cor pos
begin
call __init__
set promoted = false
set cor = cor
set pos = pos
set image = call getImg
set rect = call get_rect
set center = pos
end function
function getImg self
begin
if cor == string preta
begin
set img = load image string img/black.p... | import pygame
class Peca(pygame.sprite.Sprite):
def __init__(self, cor, pos):
super().__init__()
self.promoted = False
self.cor = cor
self.pos = pos
self.image = self.getImg()
self.rect = self.image.get_rect()
self.rect.center = pos
def getImg(self):
... | Python | zaydzuhri_stack_edu_python |
function _fcn_add_score_row self
begin
comment Increase length :
call setRowCount call rowCount + 1
end function | def _fcn_add_score_row(self):
# Increase length :
self._scoreTable.setRowCount(self._scoreTable.rowCount() + 1) | Python | nomic_cornstack_python_v1 |
comment Databricks notebook source exported at Wed, 15 Jun 2016 17:01:17 UTC
comment MAGIC %md
comment MAGIC <a rel="license" href="http://creativecommons.org/licenses/by-nc-nd/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-nc-nd/4.0/88x31.png" /></a><br />This ... | # Databricks notebook source exported at Wed, 15 Jun 2016 17:01:17 UTC
# MAGIC %md
# MAGIC <a rel="license" href="http://creativecommons.org/licenses/by-nc-nd/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-nc-nd/4.0/88x31.png" /></a><br />This work is licensed ... | Python | zaydzuhri_stack_edu_python |
function _validate_params self request_set target_set=none context=none
begin
comment Perform first-pass validation in Function.__init__():
comment - returns full set of params based on subclass paramClassDefaults
call _validate_params request_set target_set context
set params = target_set
comment region VALIDATE TIME ... | def _validate_params(self, request_set, target_set=None, context=None):
# Perform first-pass validation in Function.__init__():
# - returns full set of params based on subclass paramClassDefaults
super(Mechanism, self)._validate_params(request_set,target_set,context)
params = target_se... | Python | nomic_cornstack_python_v1 |
import numpy as np
from pynput import keyboard
import time
from pyautogui import press , typewrite , hotkey
import tkinter as tk
import numpy as np
import cv2
from mss import mss
from PIL import Image
import threading
from mss.tools import to_png
from pywinauto.findwindows import find_window
from pywinauto.win32functio... | import numpy as np
from pynput import keyboard
import time
from pyautogui import press, typewrite, hotkey
import tkinter as tk
import numpy as np
import cv2
from mss import mss
from PIL import Image
import threading
from mss.tools import to_png
from pywinauto.findwindows import find_window
from pywinauto.win32funct... | Python | zaydzuhri_stack_edu_python |
function test_models_product_target_course_runs_property self
begin
set list course1 course2 = call create_batch 2
set list cr1 cr2 = call create_batch 2 course=course1
set list cr3 _ = call create_batch 2 course=course2
set product = call ProductFactory target_courses=list course1 course2
comment - Link cr3 to the pro... | def test_models_product_target_course_runs_property(self):
[course1, course2] = factories.CourseFactory.create_batch(2)
[cr1, cr2] = factories.CourseRunFactory.create_batch(2, course=course1)
[cr3, _] = factories.CourseRunFactory.create_batch(2, course=course2)
product = factories.Produc... | Python | nomic_cornstack_python_v1 |
function count_mine y x
begin
set cnt = 0
for dir in range 8
begin
set ny = y + dy at dir
set nx = x + dx at dir
if ny < 0 or ny >= n or nx < 0 or nx >= n
begin
continue
end
if map_mine at ny at nx == string *
begin
set cnt = cnt + 1
end
end
if cnt == 0
begin
for dir in range 8
begin
set ny = y + dy at dir
set nx = x +... | def count_mine(y, x):
cnt = 0
for dir in range(8):
ny = y + dy[dir]
nx = x + dx[dir]
if ny < 0 or ny >= n or nx < 0 or nx >= n:
continue
if map_mine[ny][nx] == '*':
cnt += 1
if cnt == 0:
for dir in range(8):
ny = y + dy[dir]
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment coding: utf-8
from __future__ import division
from __future__ import print_function
import igraph
import price
comment Define variables
comment starting vertices
set sv = 3
comment attractivity
set at = 0.8
comment network size
set ns = 20
string Create a graph, and print out its pr... | #!/usr/bin/env python
# coding: utf-8
from __future__ import division
from __future__ import print_function
import igraph
import price
# Define variables
sv = 3 # starting vertices
at = .8 # attractivity
ns = 20 # network size
""" Create a graph, and print out its properties
"""
p = price.price(sv, at,... | Python | zaydzuhri_stack_edu_python |
function _freespace_matrix distance
begin
return array list list 1.0 distance list 0.0 1.0
end function | def _freespace_matrix(distance):
return np.array([[1., distance], [0., 1.]]) | Python | nomic_cornstack_python_v1 |
function euler_from_quaternion x y z w
begin
set t0 = + 2.0 * w * x + y * z
set t1 = + 1.0 - 2.0 * x * x + y * y
set roll_x = call atan2 t0 t1
set t2 = + 2.0 * w * y - z * x
set t2 = if expression t2 > + 1.0 then + 1.0 else t2
set t2 = if expression t2 < - 1.0 then - 1.0 else t2
set pitch_y = call asin t2
set t3 = + 2.... | def euler_from_quaternion(x, y, z, w):
t0 = +2.0 * (w * x + y * z)
t1 = +1.0 - 2.0 * (x * x + y * y)
roll_x = math.atan2(t0, t1)
t2 = +2.0 * (w * y - z * x)
t2 = +1.0 if t2 > +1.0 else t2
t2 = -1.0 if t2 < -1.0 else t2
pitch_y = math.asin(t2)
t3 = +2.0 * (w * z + x * y)
t4 = +1.0 -... | Python | nomic_cornstack_python_v1 |
function __str__ self
begin
return name
end function | def __str__(self):
return self.name | Python | nomic_cornstack_python_v1 |
function set_SSE self ssep ssed sse
begin
if save_trace
begin
comment save the ret codes from the last iter
append ssep ssep
append ssed ssed
append sse sse
end
else
begin
set ssep = list ssep
set ssed = list ssed
set sse = list sse
end
end function | def set_SSE(self,ssep,ssed,sse) :
if self.save_trace :
# save the ret codes from the last iter
self.ssep.append(ssep)
self.ssed.append(ssed)
self.sse.append(sse)
else :
self.ssep = [ssep]
self.ssed = [ssed]
self.sse = [sse] | Python | nomic_cornstack_python_v1 |
string ============================ Author:柠檬班-木森 Time:2020/2/6 20:21 E-mail:3247119728@qq.com Company:湖南零檬信息技术有限公司 ============================
string python中的 运算符 1、算术运算符:+、 -、 *、 /、 //、 %、 ** # 整数和整数进行除法运算(/)的时候,得到的结果是浮点数 2、比较预算符:< 、 > 、 <=、 >=、 ==、 != 3、赋值运算符:= 、+=、-=、/= 、 *= 4、逻辑运算符:and(与)、or(或)、not(非) 5、身份运算符(后面学... | """
============================
Author:柠檬班-木森
Time:2020/2/6 20:21
E-mail:3247119728@qq.com
Company:湖南零檬信息技术有限公司
============================
"""
"""
python中的 运算符
1、算术运算符:+、 -、 *、 /、 //、 %、 **
# 整数和整数进行除法运算(/)的时候,得到的结果是浮点数
2、比较预算符:< 、 > 、 <=、 >=、 ==、 !=
3、赋值运算符:= 、+=、-=、/= 、 *=
4、逻辑运算符:and(与)、or(或)、not(非)
5、身... | Python | zaydzuhri_stack_edu_python |
function sis3305_mode self
begin
return _sis3305_mode
end function | def sis3305_mode(self):
return self._faux._sis3305_mode | Python | nomic_cornstack_python_v1 |
function interpolateCubicPeriodic
begin
set S = list
comment for all parameters
for i in range 11
begin
set y = list
comment get i-th parameter
for k in range length keyframe
begin
append y keyframe at k at i
end
set interpolants = call interpolatePeriodicSpline keytime y
append S interpolants
end
return S
end functi... | def interpolateCubicPeriodic() :
S = []
# for all parameters
for i in range(11):
y = []
# get i-th parameter
for k in range(len(keyframe)):
y.append(keyframe[k][i])
interpolants = interpolatePeriodicSpline(keytime, y)
S.append(interpolants)
return S | Python | nomic_cornstack_python_v1 |
import os
import os.path
import torch.utils.data as data
import torch
class APPRENTICE extends Dataset
begin
function __init__ self root transform=none target_transform=none
begin
set DATA_FILE_NAME = string mnist_apprentice_split.data
set root = root
set transform = transform
set target_transform = target_transform
se... | import os
import os.path
import torch.utils.data as data
import torch
class APPRENTICE(data.Dataset):
def __init__(self, root, transform=None, target_transform=None):
DATA_FILE_NAME = "mnist_apprentice_split.data"
self.root = root
self.transform = transform
self.target_transform = t... | Python | zaydzuhri_stack_edu_python |
from trainingTweets import parse_csv , splitTrainingTweets
from analyzer import get_words_in_tweets , get_word_features , analyze , set_training_set
import pickle
import nltk
comment Get Training Tweets
print string [1;33;40m Obtaining training data... [0m
set training_tweets = call parse_csv string TrainingDataset.c... | from trainingTweets import parse_csv, splitTrainingTweets
from analyzer import get_words_in_tweets, get_word_features, analyze, set_training_set
import pickle
import nltk
# Get Training Tweets
print("\033[1;33;40m Obtaining training data... \033[0m")
training_tweets = parse_csv("TrainingDataset.csv")
training_tweets ... | Python | zaydzuhri_stack_edu_python |
function num_available self
begin
return length self
end function | def num_available(self) -> int:
return len(self) | Python | nomic_cornstack_python_v1 |
function edit_product_info self user_id shop_id product_id product_name description price quantity categories purchase_types
begin
raise call NotImplementedError
end function | def edit_product_info(
self, user_id: int, shop_id: int, product_id: int,
product_name: str, description: str, price: float,
quantity: int, categories: List[str], purchase_types: list
) -> bool:
raise NotImplementedError() | Python | nomic_cornstack_python_v1 |
function installed_apps_list self
begin
return split installed_apps_text string
end function | def installed_apps_list(self):
return self.installed_apps_text.split("\n") | Python | nomic_cornstack_python_v1 |
comment EXPERIMENT FOR JUSTIN'S BIG IMPROVEMENT
comment Default Libraries
import math
import inspect
import itertools
comment Data Science Libraries
import numpy as np
import pandas as pd
import sklearn_pandas
comment sklearn Library (https://scikit-learn.org)
import sklearn.model_selection
import sklearn.linear_model
... | # EXPERIMENT FOR JUSTIN'S BIG IMPROVEMENT
# Default Libraries
import math
import inspect
import itertools
# Data Science Libraries
import numpy as np
import pandas as pd
import sklearn_pandas
# sklearn Library (https://scikit-learn.org)
import sklearn.model_selection
import sklearn.linear_model
import sklearn.neigh... | Python | zaydzuhri_stack_edu_python |
function get_series_factor k lamada sequence phyche_value
begin
set theta = list
set l_seq = length sequence
set temp_values = list values phyche_value
set max_big_lamada = length temp_values at 0
for small_lamada in range 1 lamada + 1
begin
for big_lamada in range max_big_lamada
begin
set temp_sum = 0.0
for i in rang... | def get_series_factor(k, lamada, sequence, phyche_value):
theta = []
l_seq = len(sequence)
temp_values = list(phyche_value.values())
max_big_lamada = len(temp_values[0])
for small_lamada in range(1, lamada + 1):
for big_lamada in range(max_big_lamada):
temp_sum = 0.0
... | Python | nomic_cornstack_python_v1 |
async function add_animal request animal
begin
await execute string set string animals:item: { animal } body
return call text format string Added {0} to the farm animal status=201
end function | async def add_animal(request, animal):
await execute('set', f'animals:item:{animal}', request.body)
return text('Added {0} to the farm'.format(animal), status=201) | Python | nomic_cornstack_python_v1 |
function get_app workdir
begin
comment configure the core package
import rnaseqlyze
call configure workdir
comment default configuraion file name
import os.path
set web_ini = join path workdir string web.ini
comment configure logging
import logging.config
call fileConfig web_ini dictionary here=workdir
comment create t... | def get_app(workdir):
# configure the core package
import rnaseqlyze
rnaseqlyze.configure(workdir)
# default configuraion file name
import os.path
web_ini = os.path.join(workdir, 'web.ini')
# configure logging
import logging.config
logging.config.fileConfig(web_ini, dict(here=work... | Python | nomic_cornstack_python_v1 |
function customer self id
begin
return call Customer self id
end function | def customer(self, id):
return Customer(self, id) | Python | nomic_cornstack_python_v1 |
import subprocess
set completed = run list string ls string -l
print string return code returncode
comment shell=true causes subprocess to spawn an intermediate shell process which then runs the command
set compl = run string echo $HOME shell=true
print string return code returncode
comment error handling
try
begin
run... | import subprocess
completed= subprocess.run(['ls','-l'])
print('return code',completed.returncode)
# shell=true causes subprocess to spawn an intermediate shell process which then runs the command
compl=subprocess.run('echo $HOME',shell=True)
print('return code',compl.returncode)
#error handling
try:
subproces... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.