code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function __unicode__ self
begin
return call self
end function | def __unicode__(self):
return self() | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
comment Imports the Google Cloud client library
from google.cloud import language
from google.cloud.language import enums
from google.cloud.language import types
import six
string Detects syntax in the text.
set client = call LanguageServiceClient
set searchTrigger = string find jobs
set searc... | #!/usr/bin/python3
# Imports the Google Cloud client library
from google.cloud import language
from google.cloud.language import enums
from google.cloud.language import types
import six
"""Detects syntax in the text."""
client = language.LanguageServiceClient()
searchTrigger = 'find jobs'
searchKeyword = 'web design... | Python | zaydzuhri_stack_edu_python |
import py5
import cv2 as cv
set tuple WIDTH HEIGHT = tuple 1280 720
function setup
begin
size py5 WIDTH HEIGHT
call rect_mode CENTER
global webcam
comment Hopefully we can just hard-code this - for now, my built-in webcam is device 0, and a USB webcam is device 1
comment But we might be able to build in something to en... | import py5
import cv2 as cv
WIDTH, HEIGHT = 1280, 720
def setup():
py5.size(WIDTH, HEIGHT)
py5.rect_mode(py5.CENTER)
global webcam
# Hopefully we can just hard-code this - for now, my built-in webcam is device 0, and a USB webcam is device 1
# But we might be able to build in something... | Python | zaydzuhri_stack_edu_python |
if B - A % 2 == 0
begin
print B - A // 2
end
else
begin
set straight = min B - 1 N - A
set wrap = 1 + min A - 1 N - B + B - A // 2
print min straight wrap
end | if (B-A) % 2 == 0:
print((B-A) // 2)
else:
straight = min(B - 1, N - A)
wrap = 1 + min(A - 1, N - B) + (B - A) // 2
print(min(straight, wrap)) | Python | zaydzuhri_stack_edu_python |
from __future__ import unicode_literals
from django.db import models
from datetime import datetime , timedelta
import bcrypt
import re
set EMAIL_REGEX = compile string ^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$
class UserManager extends Manager
begin
function registration_validator self postData
begin
set errors = d... | from __future__ import unicode_literals
from django.db import models
from datetime import datetime, timedelta
import bcrypt
import re
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
class UserManager(models.Manager):
def registration_validator(self, postData):
errors = {}
... | Python | zaydzuhri_stack_edu_python |
function biphenyl_workflow target
begin
set mol = call from_file call get_data string biphenyl.sdf string sdf
set workflow = call WorkflowFactory
comment turn off bespoke terms we want fast fitting
set generate_bespoke_terms = false
set expand_torsion_terms = false
set fb = call ForceBalanceOptimizer
set target = call ... | def biphenyl_workflow(target) -> OptimizationSchema:
mol = Molecule.from_file(get_data("biphenyl.sdf"), "sdf")
workflow = WorkflowFactory()
# turn off bespoke terms we want fast fitting
workflow.generate_bespoke_terms = False
workflow.expand_torsion_terms = False
fb = ForceBalanceOptimizer()
... | Python | nomic_cornstack_python_v1 |
comment 从精灵模块导入所有命令
from sprites import *
import random
comment 新建屏幕
set screen = call Screen
comment 设置屏幕宽高
setup screen 800 600
comment 设置背景图
call bgpic string sea2.png
comment 关闭标题栏
call titlebar false
comment 设置按中键可拖动窗口
call draggable
comment 设置窗口透明度为0.9
call wm_attributes string -alpha 0.9
set fish1 = call Sprite ... | from sprites import * # 从精灵模块导入所有命令
import random
screen = Screen() # 新建屏幕
screen.setup(800, 600) # 设置屏幕宽高
screen.bgpic('sea2.png') # 设置背景图
screen.titlebar(False) # 关闭标题栏
screen.draggable() # 设置按中键可拖动窗口
screen._root.wm_attributes('-alpha', 0.9) # 设置窗口透明度为0.9
fish1 = Sprite('fish')
fish = Sprite('dog') # 新建小鱼... | Python | zaydzuhri_stack_edu_python |
function _split_into_batches self dataset bsz shuffle=true device=none name=string unknown
begin
if shuffle
begin
shuffle random dataset
end
comment sort by dialog length and pad
sort dataset key=lambda x -> length x at 1
set pad = call get_idx string <pad>
set batches = list
set stats = dict string n 0 ; string nonpa... | def _split_into_batches(self, dataset, bsz, shuffle=True, device=None, name="unknown"):
if shuffle:
random.shuffle(dataset)
# sort by dialog length and pad
dataset.sort(key=lambda x: len(x[1]))
pad = self.word_dict.get_idx('<pad>')
batches = []
stats = {
... | Python | nomic_cornstack_python_v1 |
function assert_team_exists self team_id
begin
set result = call fetchone
if result is none
begin
raise call UnknownTeamError team_id
end
end function | def assert_team_exists(self, team_id):
result = self.con.execute(
'SELECT id FROM team WHERE id = ?', (team_id,)
).fetchone()
if result is None:
raise err.UnknownTeamError(team_id) | Python | nomic_cornstack_python_v1 |
comment def print_name():
comment age = 41
comment first_name = "stussy"
comment print(first_name + ' is ' + str(age))
comment print_name()
set value = 1
while value >= 0
begin
print value
set value = value - 1
set people = list string sts string stussy string shanna string shanna t doolittle string mrs doolittle
set i... | # def print_name():
# age = 41
# first_name = "stussy"
# print(first_name + ' is ' + str(age))
#
# print_name()
value = 1
while value >= 0:
print(value)
value -= 1
people = ["sts ","stussy","shanna","shanna t doolittle","mrs doolittle"]
index = 0
found = False
while not found:
... | Python | zaydzuhri_stack_edu_python |
function mergeKArrays arrays
begin
string This function will merge k sorted arrays in to one sorted array.
comment initialize the resulting array
set result = list
comment loop through all the arrays
for array in arrays
begin
comment merge this array with existing result
set result = call mergeTwoArrays result array
e... | def mergeKArrays(arrays):
'''
This function will merge k sorted
arrays in to one sorted array.
'''
# initialize the resulting array
result = []
# loop through all the arrays
for array in arrays:
# merge this array with existing result
result = mergeTwoArrays(result, array)... | Python | iamtarun_python_18k_alpaca |
function check_add_registrants_permission self
begin
set sm = call getSecurityManager
return call checkPermission ADD_PERMISSIONS at string SignupSheet context
end function | def check_add_registrants_permission(self):
sm = getSecurityManager()
return sm.checkPermission(config.ADD_PERMISSIONS['SignupSheet'], self.context) | Python | nomic_cornstack_python_v1 |
import unittest
from reportsystembot.command import Command
from reportsystembot.report import FormatText
from reportsystembot.report import ReportSO
class TesteRportSO extends TestCase
begin
string Classe para teste do Report de Comandos.
function test_get_return_command_teste self
begin
string Testa a execução do com... | import unittest
from reportsystembot.command import Command
from reportsystembot.report import FormatText
from reportsystembot.report import ReportSO
class TesteRportSO(unittest.TestCase):
"""
Classe para teste do Report de Comandos.
"""
def test_get_return_command_teste(self):
"""
Te... | Python | zaydzuhri_stack_edu_python |
function normalise_bytes value
begin
if value is none
begin
return none
end
if not is instance value integer_types
begin
set parts = none
if PY3 and is instance value str
begin
set value = bytes value string latin
end
comment Check for IPv6 note this can match the naive MAC
comment The smallest IPv6 is '::'
if length s... | def normalise_bytes(value):
if value is None:
return None
if not isinstance(value, six.integer_types):
parts = None
if six.PY3 and isinstance(value, str):
value = bytes(value, 'latin')
# Check for IPv6 note this can match the naive MAC
# The smallest IPv6 is '... | Python | nomic_cornstack_python_v1 |
from problems.longest_palindromic_substring import Solution
set subject = call Solution
function test_1
begin
set s1 = string babad
set result = call longestPalindrome s1
assert result == string aba or result == string bab
end function
function test_2
begin
set input = string cbbd
set result = call longestPalindrome in... | from problems.longest_palindromic_substring import Solution
subject = Solution()
def test_1():
s1 = "babad"
result = subject.longestPalindrome(s1)
assert (result == 'aba') or (result == "bab")
def test_2():
input = "cbbd"
result = subject.longestPalindrome(input)
assert result == "bb"
def t... | Python | zaydzuhri_stack_edu_python |
function test_insertion_sort create_list
begin
from insertion_sort import insertion_sort
assert call insertion_sort create_list at string list == create_list at string sorted_list
end function | def test_insertion_sort(create_list):
from ..insertion_sort import insertion_sort
assert insertion_sort(create_list["list"]) == create_list["sorted_list"] | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
comment ======================================
comment @File : 713.py
comment @Time : 2020/12/23 2:05 下午
comment @Author : Rivarrl
comment ======================================
from algorithm_utils import *
class Solution
begin
string [713. 乘积小于K的子数组](https://leetcode-cn.com/problems/suba... | # -*- coding: utf-8 -*-
# ======================================
# @File : 713.py
# @Time : 2020/12/23 2:05 下午
# @Author : Rivarrl
# ======================================
from algorithm_utils import *
class Solution:
"""
[713. 乘积小于K的子数组](https://leetcode-cn.com/problems/subarray-product-less-than-k/)
... | Python | zaydzuhri_stack_edu_python |
function get_app_option_list self option_key
begin
return call get_list app_section option_key
end function | def get_app_option_list(self, option_key):
return self.get_list(self.app_section, option_key) | Python | nomic_cornstack_python_v1 |
function _encode_context self context context_length
begin
with call variable_scope string context_sentence
begin
comment reshape it so that the first dimension combines batch_size and context_size
set encoded_context = reshape tf context list - 1 call shape context at 2
comment transform the sentence to embeddings
set... | def _encode_context(self, context, context_length):
with tf.variable_scope("context_sentence"):
# reshape it so that the first dimension combines batch_size and context_size
encoded_context = tf.reshape(context, [-1, tf.shape(context)[2]])
# transform the sentence to embed... | Python | nomic_cornstack_python_v1 |
async function prepare_async_request cls httpx_request **kwargs
begin
set tuple httpx_request kwargs = await call prepare_async_request httpx_request keyword kwargs
set stream = stream
return tuple httpx_request kwargs
end function | async def prepare_async_request(cls, httpx_request, **kwargs):
httpx_request, kwargs = await super().prepare_async_request(
httpx_request, **kwargs
)
kwargs["request"].stream = httpx_request.stream
return httpx_request, kwargs | Python | nomic_cornstack_python_v1 |
comment (TAB)
function complete self e
begin
set completions = call _get_completions
if completions
begin
set cprefix = call commonprefix completions
if length cprefix > 0
begin
set rep = list comprehension c for c in cprefix
set point = point
set l_buffer at slice begidx : endidx : = rep
set point = point + length re... | def complete(self, e): # (TAB)
completions = self._get_completions()
if completions:
cprefix = commonprefix(completions)
if len(cprefix) > 0:
rep = [ c for c in cprefix ]
point=self.l_buffer.point
self.l_buffer[self.begidx:self.endi... | Python | nomic_cornstack_python_v1 |
from utils import *
from character import Character
from controllers.campController import CampController
from controllers.exploreController import ExploreController
from bonuses.bonus import *
from items.item import *
class GameController
begin
function __init__ self
begin
comment , bonuses = [HealingAmulet()])
set ch... | from utils import *
from character import Character
from controllers.campController import CampController
from controllers.exploreController import ExploreController
from bonuses.bonus import *
from items.item import *
class GameController:
def __init__(self):
self.character = Character("The hero", 15, 15,... | Python | zaydzuhri_stack_edu_python |
function get_host self
begin
return string python in executable
end function | def get_host(self):
return 'python' in sys.executable | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
import numpy as np
import re
from tqdm import tqdm
from operator import itemgetter
import seaborn as sns
import portfolio
set algorithms = call getAlgorithms
set timePoints = call getTimePoints
set n = size
set names = call getNames
function generatePortfolio portfolioName
begin
class Da... | import matplotlib.pyplot as plt
import numpy as np
import re
from tqdm import tqdm
from operator import itemgetter
import seaborn as sns
import portfolio
algorithms = portfolio.getAlgorithms()
timePoints = portfolio.getTimePoints()
n = timePoints.size
names = portfolio.getNames()
def generatePortfolio(portfolioName):... | Python | zaydzuhri_stack_edu_python |
function frechet_classifier_distance_from_activations real_activations generated_activations
begin
assert length shape == length shape == 2
set activations_dtype = dtype
if activations_dtype != float64
begin
set real_activations = as type real_activations float64
set generated_activations = as type generated_activation... | def frechet_classifier_distance_from_activations(real_activations,
generated_activations):
assert len(real_activations.shape) == len(generated_activations.shape) == 2
activations_dtype = real_activations.dtype
if activations_dtype != np.float64:
real_activatio... | Python | nomic_cornstack_python_v1 |
from __future__ import division
comment import libraries
from datetime import date
import pandas as pd
comment do not show warnings
import warnings
from models.classification.feature_engineering import feature_engineering
filter warnings string ignore
function prepare_data data
begin
set train_date_before = reset index... | from __future__ import division
# import libraries
from datetime import date
import pandas as pd
# do not show warnings
import warnings
from models.classification.feature_engineering import feature_engineering
warnings.filterwarnings("ignore")
def prepare_data(data):
train_date_before = data[data['InvoiceDate... | Python | zaydzuhri_stack_edu_python |
string 非极大值抑制的相关脚本
import numpy as np
import cupy as cp
function non_maximum_suppression bbox thresh score=none limit=none
begin
string 非极大值抑制
set bbox_y1 = bbox at tuple slice : : 0
set bbox_x1 = bbox at tuple slice : : 1
set bbox_y2 = bbox at tuple slice : : 2
set bbox_x2 = bbox at tuple slice : : 3
set a... | """
非极大值抑制的相关脚本
"""
import numpy as np
import cupy as cp
def non_maximum_suppression(bbox, thresh, score=None, limit=None):
"""非极大值抑制"""
bbox_y1 = bbox[:, 0]
bbox_x1 = bbox[:, 1]
bbox_y2 = bbox[:, 2]
bbox_x2 = bbox[:, 3]
area = (bbox_x2 - bbox_x1 + 1) * (bbox_y2 - bbox_y1 + 1)
n_bbox = bb... | Python | zaydzuhri_stack_edu_python |
class Employee
begin
comment 'Common base class for all employees'
set empCount = 0
function __init__ self name salary
begin
set name = name
set salary = salary
set empCount = empCount + 1
end function
function displayCount self
begin
return string Total Employee %d % empCount
end function
function displayEmployee self... | class Employee:
# 'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
return "Total Employee %d" % Employee.empCount
def displayEmployee(self):
retur... | Python | zaydzuhri_stack_edu_python |
import os
import random
import string
import db
import json
set FILENAME_LENGTH = 20
set db = call Database
function generate_student_sheet login
begin
set latex_template = string \documentclass{article} \usepackage[T2A]{fontenc} \usepackage[utf8]{inputenc} \usepackage[russian]{babel} \begin{document} \section*{Задачи}... | import os
import random
import string
import db
import json
FILENAME_LENGTH = 20
db = db.Database()
def generate_student_sheet(login):
latex_template = "\documentclass{article} \n" \
"\\usepackage[T2A]{fontenc} \n" \
"\\usepackage[utf8]{inputenc} \n" \
... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Tue Aug 14 11:28:02 2018 @author: Administrator
import logging
import sys
comment 获取logger的实例
set logger = call getLogger string testLogger
comment 指定当前日志格式
set formatter = call Formatter string %(asctime)s %(levelname)s %(message)s
comment 创建日志对象的Handler
comment 文件日志
set... | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 14 11:28:02 2018
@author: Administrator
"""
import logging
import sys
# 获取logger的实例
logger = logging.getLogger('testLogger')
# 指定当前日志格式
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
# 创建日志对象的Handler
# 文件日志
file_handler = logg... | Python | zaydzuhri_stack_edu_python |
function get_new_energies event_voxels verbosity=false
begin
comment Identify voxels with low energy
set negl_voxels = event_voxels at negli == true
set negl_neig_pairs = list
set neig_index = list
for i in index
begin
set negl_voxel = loc at i
comment looking the closest neighbour of every negligible voxel
set min_d... | def get_new_energies(event_voxels, verbosity=False):
# Identify voxels with low energy
negl_voxels = event_voxels[event_voxels.negli == True]
negl_neig_pairs = []
neig_index = []
for i in negl_voxels.index:
negl_voxel = event_voxels.loc[i]
# looking the closest neighbour of eve... | Python | nomic_cornstack_python_v1 |
function get_fees self
begin
return call _send_get string fees
end function | def get_fees(self):
return self._send_get('fees') | Python | nomic_cornstack_python_v1 |
function setZeroes self matrix
begin
set saved_row = set
set saved_col = set
for tuple i r in enumerate matrix
begin
for tuple j c in enumerate r
begin
if c == 0
begin
add saved_row i
add saved_col j
end
end
end
for tuple i r in enumerate matrix
begin
for tuple j c in enumerate r
begin
if i in saved_row or j in saved_c... | def setZeroes(self, matrix: List[List[int]]) -> None:
saved_row = set()
saved_col = set()
for i, r in enumerate(matrix):
for j, c in enumerate(r):
if c == 0:
saved_row.add(i)
saved_col.add(j)
for i, r in enumera... | Python | nomic_cornstack_python_v1 |
from math_dict import tagMap , mtMap
set words = split string 小明 有 5 個 蘋果 , 給 了 小華 3 個 蘋果 , 請問 他 還 剩 幾 個 蘋果 ? string
print string 中文: words
set wi = 0
set mtWords = list
function mt w
begin
if get mtMap w == none
begin
return w
end
else
begin
return mtMap at w
end
end function
function isTag tag
begin
set tagWords = t... | from math_dict import tagMap, mtMap
words="小明 有 5 個 蘋果 , 給 了 小華 3 個 蘋果 , 請問 他 還 剩 幾 個 蘋果 ?".split(" ")
print('中文:', words)
wi = 0
mtWords=[]
def mt(w):
if mtMap.get(w) == None:
return w
else:
return mtMap[w]
def isTag(tag):
tagWords=tagMap[tag]
if tagWords == None:
return Fal... | Python | zaydzuhri_stack_edu_python |
function precondition amp
begin
set n = length amp
set mean = mean np amp at slice : n / 5 :
return - amp - mean
end function | def precondition(amp):
n = len(amp)
mean = np.mean(amp[:n/5])
return -(amp-mean) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import xlwt
import os
import StringIO
function write excel_name header data
begin
string 不落磁盘下载 :param excel_name: :param header: :param data: :return:
set write_workbook = call Workbook encoding=string utf-8
set write_sheet = call add_sheet string Sheet 1 cell_overwrite_ok=true
for i in r... | # -*- coding: utf-8 -*-
import xlwt
import os
import StringIO
def write(excel_name, header, data):
'''
不落磁盘下载
:param excel_name:
:param header:
:param data:
:return:
'''
write_workbook = xlwt.Workbook(encoding='utf-8')
write_sheet = write_workbook.add_sheet('Sheet 1', cell_overwrit... | Python | zaydzuhri_stack_edu_python |
function request_token user
begin
try
begin
call request_access_token
call log_action request_token
set email_subject = string [ { REANA_HOSTNAME } ] Token request ( { email } )
set fields = list string id_ string email string full_name string username string access_token string access_token_status
set user_data = join... | def request_token(user):
try:
user.request_access_token()
user.log_action(AuditLogAction.request_token)
email_subject = f"[{REANA_HOSTNAME}] Token request ({user.email})"
fields = [
"id_",
"email",
"full_name",
"username",
"... | Python | nomic_cornstack_python_v1 |
function get_employees_in_department department_name
begin
comment Return the employees in the department.
comment Each "row" has: [ empid, name ]
comment employees = [
comment [15905, 'Rea Fibbings'],
comment [9438, 'Julia Norville'],
comment [36020, 'Adora Lansdowne'],
comment [98809, 'Nathanial Farfoot'],
comment [5... | def get_employees_in_department(department_name: str) -> list:
# Return the employees in the department.
# Each "row" has: [ empid, name ]
#employees = [
#[15905, 'Rea Fibbings'],
#[9438, 'Julia Norville'],
#[36020, 'Adora Lansdowne'],
#[98809, 'Nathanial Farfoot'],
... | Python | nomic_cornstack_python_v1 |
import torch
import numpy as np
from nltk.translate import bleu_score
class Utility
begin
decorator staticmethod
function tensorize sequences dtype device
begin
string Converts an array of sequences to an array of tensors
return list comprehension to tensor sequence dtype=dtype device for sequence in sequences
end func... | import torch
import numpy as np
from nltk.translate import bleu_score
class Utility:
@staticmethod
def tensorize(sequences, dtype, device):
"""Converts an array of sequences to an array of tensors"""
return [torch.tensor(sequence, dtype=dtype).to(device) for sequence in sequences]
@stati... | Python | zaydzuhri_stack_edu_python |
function getUrl self
begin
set cmdId = call executeCommand GET_CURRENT_URL
return cmdId
end function | def getUrl(self):
cmdId = self.executeCommand(Command.GET_CURRENT_URL)
return cmdId | Python | nomic_cornstack_python_v1 |
function flipAndInvertImage A
begin
if length A == 0
begin
return
end
for num in A
begin
set low = 0
set high = length num - 1
while low < high
begin
set tuple num at low num at high = tuple num at high num at low
set low = low + 1
set high = high - 1
end
for i in range length num
begin
if num at i == 1
begin
set num a... | def flipAndInvertImage(A):
if len(A) == 0:
return
for num in A:
low = 0
high = len(num) - 1
while low < high:
num[low], num[high] = num[high], num[low]
low +=1
high -=1
for i in range(len(num)):
if num[i] == 1:
... | Python | zaydzuhri_stack_edu_python |
function install_mu_no_ha_base self
begin
call check_run string install_mu_no_ha_base
call show_step 1
call revert_snapshot string prepare_for_install_mu_non_ha_cluster
set cluster_id = call get_last_created_cluster
call show_step 2
call _check_for_potential_updates cluster_id
call show_step 3
call _install_mu cluster_... | def install_mu_no_ha_base(self):
self.check_run("install_mu_no_ha_base")
self.show_step(1)
self.env.revert_snapshot("prepare_for_install_mu_non_ha_cluster")
cluster_id = self.fuel_web.get_last_created_cluster()
self.show_step(2)
self._check_for_potential_updates(clus... | Python | nomic_cornstack_python_v1 |
function set_ref_traj self ref_traj
begin
set ref_traj = ref_traj
call postprocess_ref_traj
if is instance subfeatures dict
begin
set sfs = list values subfeatures
end
else
begin
set sfs = subfeatures
end
for sf in sfs
begin
call propagate_verbosity sf
update super_pars pars
update super_results results
call set_ref_tr... | def set_ref_traj(self, ref_traj):
self.ref_traj = ref_traj
self.postprocess_ref_traj()
if isinstance(self.subfeatures, dict):
sfs = list(self.subfeatures.values())
else:
sfs = self.subfeatures
for sf in sfs:
self.propagate_verbosity(sf)
... | Python | nomic_cornstack_python_v1 |
function setAxisName name axes=string XYZ
begin
call name name axes
end function | def setAxisName(name, axes='XYZ'):
dislin.name(name, axes) | Python | nomic_cornstack_python_v1 |
function mostcommon self iterable n=none
begin
comment http://code.activestate.com/recipes/347615/ (Raymond
comment Hettinger)
set bag = dict
set bag_get = get
for elem in iterable
begin
set bag at elem = call bag_get elem 0 + 1
end
if n is none
begin
return sorted call iteritems key=call itemgetter 1 reverse=true
end... | def mostcommon(self, iterable, n=None):
# http://code.activestate.com/recipes/347615/ (Raymond
# Hettinger)
bag = {}
bag_get = bag.get
for elem in iterable:
bag[elem] = bag_get(elem, 0) + 1
if n is None:
return sorted(bag.iteritems(), key... | Python | nomic_cornstack_python_v1 |
function test_kathy_hit_thirtyone_still_has_cards self
begin
set fake_redis = call FakeRedis
set game_dict = dict string cards CARDS ; string hands dict string kathy list string 5e1e7e60ab ; string tom list string 95f92b2f0c ; string pegging dict string cards list string 75e734d054 string 60575e1068 string 1d5eb77128 ;... | def test_kathy_hit_thirtyone_still_has_cards(self):
fake_redis = fakeredis.FakeRedis()
game_dict = {
'cards': CARDS,
'hands': {'kathy': ['5e1e7e60ab'], 'tom': ['95f92b2f0c']},
'pegging': {
'cards': ['75e734d054', '60575e1068', '1d5eb77128'],
... | Python | nomic_cornstack_python_v1 |
function append self forms lemmas cpostags postags feats heads deprels
begin
call __init__ _forms + list forms _lemmas + list lemmas _cpostags + list cpostags _postags + list postags _feats + list feats _heads + list heads _deprels + list deprels
end function | def append(self, forms, lemmas, cpostags, postags, feats, heads, deprels):
self.__init__(
self._forms + list(forms),
self._lemmas + list(lemmas),
self._cpostags + list(cpostags),
self._postags + list(postags),
self._feats + list(feats),
sel... | Python | nomic_cornstack_python_v1 |
function _vis_minibatch_box im_blob gt_boxes
begin
import matplotlib.pyplot as plt
for i in call xrange shape at 0
begin
set fig = figure
comment show image
set im = copy im_blob at tuple i slice : : slice : : slice : :
set im = im + PIXEL_MEANS
set im = im at tuple slice : : slice : : tuple 2 1 0
set im ... | def _vis_minibatch_box(im_blob, gt_boxes):
import matplotlib.pyplot as plt
for i in xrange(im_blob.shape[0]):
fig = plt.figure()
# show image
im = im_blob[i, :, :, :].copy()
im += cfg.PIXEL_MEANS
im = im[:, :, (2, 1, 0)]
im = im.astype(np.uint8)
ax = fig.... | Python | nomic_cornstack_python_v1 |
function create_keypair address_type addresses_path address_prefix name
begin
set vkey_file = call get_vkey_file addresses_path address_prefix name
set skey_file = call get_skey_file addresses_path address_prefix name
if exists path vkey_file
begin
print address_prefix string key pair already exists for name
return
end... | def create_keypair(address_type, addresses_path, address_prefix, name):
vkey_file = get_vkey_file(addresses_path, address_prefix, name)
skey_file = get_skey_file(addresses_path, address_prefix, name)
if(path.exists(vkey_file)) :
print(address_prefix, "key pair already exists for", name)
return
maked... | Python | nomic_cornstack_python_v1 |
import selenium
from bs4 import BeautifulSoup as soup
import pandas as pd
import sys
import os
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
set Postcode_Details = read csv string NSW-Postcodes.csv
from Postcodes_NSW import Suburbs_And_Postcodes
set Company_Names = lis... | import selenium
from bs4 import BeautifulSoup as soup
import pandas as pd
import sys
import os
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
Postcode_Details = pd.read_csv("NSW-Postcodes.csv")
from Postcodes_NSW import Suburbs_And_Postcodes
Company_Names = []
Emails = ... | Python | zaydzuhri_stack_edu_python |
function formatUptime uptime
begin
if uptime >= 0.9
begin
return format string [1mUptime: [92m{:.2%}[0m uptime
end
else
if uptime >= 0.8
begin
return format string [1mUptime: [93m{:.2%}[0m uptime
end
else
begin
return format string [1mUptime: [91m{:.2%}[0m uptime
end
end function | def formatUptime(uptime):
if uptime >= 0.9:
return '\n\t\033[1mUptime: \033[92m{:.2%}\033[0m'.format(uptime)
elif uptime >= 0.8:
return '\n\t\033[1mUptime: \033[93m{:.2%}\033[0m'.format(uptime)
else:
return '\n\t\033[1mUptime: \033[91m{:.2%}\033[0m'.format(uptime) | Python | nomic_cornstack_python_v1 |
function computeMin initalMoteSize motes index
begin
if length motes == 0 or index == length motes
begin
return 0
end
else
if initalMoteSize == 1
begin
return length motes - index
end
else
if initalMoteSize <= motes at index
begin
return min 1 + call computeMin 2 * initalMoteSize - 1 motes index length motes - index
en... | def computeMin(initalMoteSize, motes, index):
if len(motes) == 0 or index == len(motes):
return 0
elif initalMoteSize == 1:
return len(motes) - index
elif initalMoteSize <= motes[index]:
return min(1 + computeMin(2*initalMoteSize - 1, motes, index), len(motes) - index)
else:
return min(computeMin(initalMote... | Python | zaydzuhri_stack_edu_python |
comment Print student and course information
comment nathanLanLab1.py
comment 6.17.2020
print string Hello World!
comment assign information to variables
set last_name = string Lan
set g_number = string G01246656
set syl_1 = string Assesments are due Tuesday at 11:59
set syl_2 = string Assignments are worth 50% of your... | ###########################################################
# Print student and course information
# nathanLanLab1.py
# 6.17.2020
###########################################################
print("Hello World!")
#assign information to variables
last_name = "Lan"
g_number = "G01246656"
syl_1 = "Assesments are due Tuesd... | Python | zaydzuhri_stack_edu_python |
function get_none_part l
begin
return count l string - / length l
end function | def get_none_part(l: List) -> float:
return (l.count("-")) / len(l) | Python | nomic_cornstack_python_v1 |
import numpy as np
import pandas as pd
import matplotlib.pyplot as mpl
from sklearn.preprocessing import scale
from matplotlib.figure import Figure
from TFANN import ANNR
import yfinance as yf
class Predict extends object
begin
function __init__ self name interval hidden iterations tolerance
begin
set name = name
comme... | import numpy as np
import pandas as pd
import matplotlib.pyplot as mpl
from sklearn.preprocessing import scale
from matplotlib.figure import Figure
from TFANN import ANNR
import yfinance as yf
class Predict(object):
def __init__(self, name, interval, hidden, iterations, tolerance):
self.name = name
... | Python | zaydzuhri_stack_edu_python |
comment Uses python3
string 6. Maximum salary Introduction: At the end of a successful interview, your boss gives you a few pieces of paper with numbers on it and asks you to compose a larger number from these numbers. The resulting number is going to be your salary, so you are very interested in maximizing this number... | # Uses python3
"""
6. Maximum salary
Introduction: At the end of a successful interview, your boss gives you a few pieces of paper with numbers on it
and asks you to compose a larger number from these numbers. The resulting number is going to be your salary,
so you are very interested in maximizing this numbe... | Python | zaydzuhri_stack_edu_python |
import library as lib
import groups
import sqlite3
set conn = call connect string bptournament.db
set c = call cursor
function createdb
begin
execute c string DROP TABLE groupgames
execute c string DROP TABLE player_stats
execute c string DROP TABLE tournament
execute c string DROP TABLE advancers
execute c string CREA... | import library as lib
import groups
import sqlite3
conn = sqlite3.connect("bptournament.db")
c = conn.cursor()
def createdb():
c.execute('''DROP TABLE groupgames''')
c.execute('''DROP TABLE player_stats''')
c.execute('''DROP TABLE tournament''')
c.execute('''DROP TABLE advancers''')
c.... | Python | zaydzuhri_stack_edu_python |
comment 변수를 선언합니다.
set list_input_a = list 1 2 3 4 5
comment map() 함수를 사용합니다.
set output_a = map lambda x -> x * x list_input_a
print string # map() 함수의 실행 결과
print string map(power, list_input_a): output_a
print string map(power, list_input_a): list output_a
print
comment filter() 함수를 사용합니다.
set output_b = filter lamb... | # 변수를 선언합니다.
list_input_a = [1, 2, 3, 4, 5]
# map() 함수를 사용합니다.
output_a = map(lambda x: x * x, list_input_a)
print("# map() 함수의 실행 결과")
print("map(power, list_input_a):", output_a)
print("map(power, list_input_a):", list(output_a))
print()
# filter() 함수를 사용합니다.
output_b = filter(lambda x: x < 3, list_input_a)
print("... | Python | zaydzuhri_stack_edu_python |
function _set_counters self v load=false
begin
if has attribute v string _utype
begin
set v = call _utype v
end
try
begin
set t = call YANGDynClass v base=yc_counters_openconfig_interfaces__interfaces_interface_subinterfaces_subinterface_state_counters is_container=string container yang_name=string counters parent=self... | def _set_counters(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_counters_openconfig_interfaces__interfaces_interface_subinterfaces_subinterface_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper,... | Python | nomic_cornstack_python_v1 |
import math
from abc import abstractclassmethod , ABC
class FlagsRegister
begin
function __init__ self
begin
set carry = false
set auxiliary = false
set parity = false
set zero = false
set sign = false
set overflow = false
end function
end class
class MPRegister extends ABC
begin
function __init__ self limitInBits
begi... | import math
from abc import abstractclassmethod, ABC
class FlagsRegister:
def __init__(self):
self.carry = False
self.auxiliary = False
self.parity = False
self.zero = False
self.sign = False
self.overflow = False
class MPRegister(ABC):
def __init__(self, limitI... | Python | zaydzuhri_stack_edu_python |
function leave self expected_state=none timeout=none
begin
call call_operation string leave expected_state timeout
end function | def leave(self, expected_state=None, timeout=None):
super(IxnPimV4JoinPruneListEmulation, self).call_operation('leave', expected_state, timeout) | Python | nomic_cornstack_python_v1 |
comment this script modifies every json generated to contain the a new field that holds the url of the html file.
comment the url is made available as the first string in the content field, right up to the first end line character
import json
import pprint
set count = 0
comment for all jsons
for i in range 1 235
begin
... | #this script modifies every json generated to contain the a new field that holds the url of the html file.
# the url is made available as the first string in the content field, right up to the first end line character
import json
import pprint
count = 0
#for all jsons
for i in range(1,235):
path = "D:\\irdm scrape\\se... | Python | zaydzuhri_stack_edu_python |
function select_thread *args
begin
return call select_thread *args
end function | def select_thread(*args):
return _idaapi.select_thread(*args) | Python | nomic_cornstack_python_v1 |
function hash_value d
begin
return call hash_value d
end function | def hash_value(d):
return _eveusb.hash_value(d) | Python | nomic_cornstack_python_v1 |
function generate_candidates thetas proposal_stdev
begin
set thetas_proposed = zeros tuple 2 1
set thetas_proposed at tuple 0 0 = gaussian thetas at 0 at 0 proposal_stdev at 0 at 0
set thetas_proposed at tuple 1 0 = gaussian thetas at 1 at 0 proposal_stdev at 1 at 0
return thetas_proposed
end function | def generate_candidates(thetas, proposal_stdev):
thetas_proposed = np.zeros((2, 1))
thetas_proposed[0, 0] = random.gauss(thetas[0][0], proposal_stdev[0][0])
thetas_proposed[1, 0] = random.gauss(thetas[1][0], proposal_stdev[1][0])
return thetas_proposed | Python | nomic_cornstack_python_v1 |
for _ in range n
begin
append l list map int split input
end
for i in range 1 length l
begin
set m = 0
for j in range 2
begin
if j == 0
begin
set a = 0
end
else
begin
set a = l at i at j + l at i - 1 at 0
end
if j == 1
begin
set b = 0
end
else
begin
set b = l at i at j + l at i - 1 at 1
end
if j == 2
begin
set c = 0
en... | for _ in range(n):
l.append(list(map(int,input().split())))
for i in range(1,len(l)):
m=0
for j in range(2):
if j==0:
a=0
else:
a=l[i][j]+l[i-1][0]
if j==1:
b=0
else:
b=l[i][j]+l[i-1][1]
if j==2:
... | Python | zaydzuhri_stack_edu_python |
function gen_grid f mins maxes ncoarse=10 nfine=30
begin
set tuple xmin ymin zmin = mins
set tuple xmax ymax zmax = maxes
set xcoarse = linear space xmin xmax ncoarse
set ycoarse = linear space ymin ymax ncoarse
set zcoarse = linear space zmin zmax ncoarse
set xfine = linear space xmin xmax nfine
set yfine = linear spa... | def gen_grid(f, mins, maxes, ncoarse=10, nfine=30):
xmin, ymin, zmin = mins
xmax, ymax, zmax = maxes
xcoarse = np.linspace(xmin, xmax, ncoarse)
ycoarse = np.linspace(ymin, ymax, ncoarse)
zcoarse = np.linspace(zmin, zmax, ncoarse)
xfine = np.linspace(xmin, xmax, nfine)
yfine = np.linspa... | Python | nomic_cornstack_python_v1 |
comment -*- encoding: utf-8 -*-
string 2.1.6十组最常用的内置函数
set data = list list 0.468 0.975 0.446 list 0.718 0.826 0.359
comment 写csv文件
with open string ..\res\csv_data.csv string w as fp
begin
for line in data
begin
set ok = write fp string %s % join string , list comprehension string item for item in line
end
end
set res... | # -*- encoding: utf-8 -*-
"""
2.1.6十组最常用的内置函数
"""
data = [[0.468,0.975,0.446],[0.718,0.826,0.359]]
with open(r'..\res\csv_data.csv', 'w') as fp: # 写csv文件
for line in data:
ok = fp.write('%s\n'%','.join([str(item) for item in line]))
result = list()
with open(r'..\res\csv_data.csv', 'r') as fp: # 读csv文件... | Python | zaydzuhri_stack_edu_python |
function target_class_tensor self target_class outputs original_labels
begin
if target_class == - 1
begin
set predicted_classes = max data 1 at 1
set predicting_correct_class = predicted_classes == original_labels
set second_best_class = call topk outputs 2 1 at 1 at tuple slice : : 1
comment For each label in outpu... | def target_class_tensor(self, target_class, outputs, original_labels):
if target_class == -1:
predicted_classes = torch.max(outputs.data, 1)[1]
predicting_correct_class = predicted_classes == original_labels
second_best_class = torch.topk(outputs, 2, 1)[1][:, 1]
# For each label in outputs ... | Python | nomic_cornstack_python_v1 |
string By Paweł A. Pierzchlewicz ========================= A library that has all the required functions for signal analysis =================================================================
string ========================== Imports ==========================
import numpy as np
import matplotlib.pyplot as plt
import wa... | '''
By Paweł A. Pierzchlewicz
=========================
A library that has all the required functions for signal analysis
=================================================================
'''
'''
==========================
Imports
==========================
'''
import numpy as np
import matplotlib.pyplot as plt
imp... | Python | zaydzuhri_stack_edu_python |
function transform self data_frame
begin
return as type transform vectorizer call __preprocess_input data_frame float32
end function | def transform(self, data_frame: pd.DataFrame) -> np.array:
return self.vectorizer.transform(self.__preprocess_input(data_frame)).astype(np.float32) | Python | nomic_cornstack_python_v1 |
comment My Code
comment stages.sort() 후 N 순서대로 카운팅한 개수를 분자, 전체 길이를 분모로 넣고 실패율 계산, "1: 실패율" 의 형태로 dict에 넣는다
comment 다음번 분모 계산 시에는 전체 길이에서 이전 분자를 빼준다.
comment dict 내 key를 실패율 높은 순서대로 result list에 append
function solution N stages
begin
set numerator = 0
set denominator = length stages
set result_dict = dict
set result_l... | # My Code
# stages.sort() 후 N 순서대로 카운팅한 개수를 분자, 전체 길이를 분모로 넣고 실패율 계산, "1: 실패율" 의 형태로 dict에 넣는다
# 다음번 분모 계산 시에는 전체 길이에서 이전 분자를 빼준다.
# dict 내 key를 실패율 높은 순서대로 result list에 append
def solution(N, stages):
numerator = 0
denominator = len(stages)
result_dict = {}
result_list = []
for i in range(1,... | Python | zaydzuhri_stack_edu_python |
comment Double linked list - pairs with sum e.g. 2 + 3 = 5 and 4 + 1 = 5
class Node
begin
function __init__ self data
begin
set data = data
comment intially equals to None
set next = none
set prev = none
end function
end class
class DoubleLinkedList
begin
function __init__ self
begin
set head = none
end function
functi... | # Double linked list - pairs with sum e.g. 2 + 3 = 5 and 4 + 1 = 5
class Node:
def __init__(self, data):
self.data = data
self.next = None # intially equals to None
self.prev = None
class DoubleLinkedList:
def __init__(self):
self.head = None
def print_list(self):
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
from Adafruit_PWM_Servo_Driver import PWM
import time
import helpers
import stairvalues
set chips = list call PWM 64 call PWM 65 call PWM 66
set stairs = stairs
comment transition()
comment args:
comment stair: 1-16, bottom step is 1, top step is 16
comment rgb1: 3-ple of red, green, blue value... | #!/usr/bin/python
from Adafruit_PWM_Servo_Driver import PWM
import time
import helpers
import stairvalues
chips = [PWM(0x40), PWM(0x41), PWM(0x42)]
stairs = stairvalues.stairs
# transition()
# args:
# stair: 1-16, bottom step is 1, top step is 16
# rgb1: 3-ple of red, green, blue value for initial color
# rgb2: ... | Python | zaydzuhri_stack_edu_python |
import time
import xlwt
import re
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
comment 这个是一个用来控制chrome以无界面模式打开的浏览器
comment 创建一个参数对象,用来控制chrome以无界面的方式打开
set chrome_options = options
comment 后面的两个是固定写法 必须这么写,如果不是这样写,就是自动化
call add_argument string --headless
call add_argument string... | import time
import xlwt
import re
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
#这个是一个用来控制chrome以无界面模式打开的浏览器
#创建一个参数对象,用来控制chrome以无界面的方式打开
chrome_options = Options()
#后面的两个是固定写法 必须这么写,如果不是这样写,就是自动化
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-g... | Python | zaydzuhri_stack_edu_python |
function get_location bs array
begin
try
begin
set location = find all bs string div dict string class string event-details__data
set content = find all location at length location - 1 string p
if length content < 2
begin
set content = find all location at length location - 2 string p
end
set location_info = string
en... | def get_location(bs, array):
try:
location = bs.find_all("div", {"class": "event-details__data"})
content = location[len(location) - 1].find_all("p")
if len(content) < 2:
content = location[len(location) - 2].find_all("p")
location_info = ""
except Exception:
... | Python | zaydzuhri_stack_edu_python |
function serve self
begin
try
begin
set httpd = call _LimitedHTTPServer server_address _LimitedHTTPRequestHandler files_to_serve=files_to_serve docroot=docroot
end
except Exception as e
begin
call LOG_WARN string There was an error creating the HTTP server: %s % string e
raise
end
set pid = call fork
if pid
begin
close... | def serve(self):
try:
self.httpd=_LimitedHTTPServer(self.server_address,
_LimitedHTTPRequestHandler,
files_to_serve=self.files_to_serve,
docroot=self.docroot)
except Exc... | Python | nomic_cornstack_python_v1 |
function regress_residuals x y
begin
set tuple slope intercept = call regress x y
set coords = zip x y
set residuals = list
for tuple x y in coords
begin
set e = y - slope * x - intercept
append residuals e
end
return residuals
end function | def regress_residuals(x, y):
slope, intercept = regress(x, y)
coords = zip(x, y)
residuals = []
for x, y in coords:
e = y - (slope * x) - intercept
residuals.append(e)
return residuals | Python | nomic_cornstack_python_v1 |
function getpointy self cursor=true end=false prompt=false
begin
set tuple line index = call getCursorPosition
if end
begin
set tuple line index = call get_end_pos
end
else
if prompt
begin
set index = 0
end
set pos = call position_from_lineindex line index
return call SendScintilla SCI_POINTYFROMPOSITION 0 pos
end func... | def getpointy(self, cursor=True, end=False, prompt=False):
line, index = self.getCursorPosition()
if end:
line, index = self.get_end_pos()
elif prompt:
index = 0
pos = self.position_from_lineindex(line, index)
return self.SendScintilla(QsciScintilla... | Python | nomic_cornstack_python_v1 |
function New *args **kargs
begin
set obj = call __New_orig__
import itkTemplate
call New obj *args keyword kargs
return obj
end function | def New(*args, **kargs):
obj = itkVectorIndexSelectionCastImageFilterIRGBAUS2IUS2.__New_orig__()
import itkTemplate
itkTemplate.New(obj, *args, **kargs)
return obj | Python | nomic_cornstack_python_v1 |
function get_uid self
begin
if UID not in fields
begin
return none
end
if _ids is none
begin
call __load_ids
end
if not _uids
begin
return none
end
else
if length _uids == 1
begin
return _uids at 0
end
else
begin
return _uids
end
end function | def get_uid(self):
if current.xml.UID not in self.table.fields:
return None
if self._ids is None:
self.__load_ids()
if not self._uids:
return None
elif len(self._uids) == 1:
return self._uids[0]
else:
return self._uids | Python | nomic_cornstack_python_v1 |
function GetNextSubFeature self
begin
set ret = call InvokeTypes 22 LCID 1 tuple 9 0 tuple
if ret is not none
begin
set ret = call Dispatch ret string GetNextSubFeature none
end
return ret
end function | def GetNextSubFeature(self):
ret = self._oleobj_.InvokeTypes(22, LCID, 1, (9, 0), (),)
if ret is not None:
ret = Dispatch(ret, u'GetNextSubFeature', None)
return ret | Python | nomic_cornstack_python_v1 |
function _doAddUser self name password roles domains **kw
begin
raise NotImplementedError
end function | def _doAddUser(self, name, password, roles, domains, **kw):
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
comment Notes: Adding Fare to the logistic regression did not help
comment Version 1.2 - Changed how names were processed
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_t... | #Notes: Adding Fare to the logistic regression did not help
#Version 1.2 - Changed how names were processed
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
f... | Python | zaydzuhri_stack_edu_python |
import sys
import heapq
function solution
begin
set get_input = readline
set tuple n k = list map int split strip call get_input
set jewels = list
for i in range n
begin
append jewels list map int split strip call get_input
end
set bags = list
for i in range k
begin
append bags integer strip call get_input
end
sort j... | import sys
import heapq
def solution():
get_input = sys.stdin.readline
n, k = list(map(int, get_input().strip().split()))
jewels = []
for i in range(n):
jewels.append(list(map(int, get_input().strip().split())))
bags = []
for i in range(k):
bags.append(int(get_input().strip())... | Python | zaydzuhri_stack_edu_python |
function dfs v
begin
set visited at v = true
for v2 in range n
begin
if graph at v at v2 == false
begin
continue
end
if visited at v2 == true
begin
continue
end
call dfs v2
end
end function
set tuple n m = map int split input
set alis = list
set blis = list
set graph = list comprehension list false * n for i in range... | def dfs(v):
visited[v]=True
for v2 in range(n):
if graph[v][v2]==False:
continue
if visited[v2]==True:
continue
dfs(v2)
n, m = map(int, input().split())
alis=[]
blis=[]
graph=[[False] * n for i in range(n)]
#隣接行列のセット
for i in range(m):
a, b = map(int, input... | Python | zaydzuhri_stack_edu_python |
function select_foreign_edges self transaction_id key=none
begin
return list select self transaction_id string foreign_edges key
end function | def select_foreign_edges(self, transaction_id, key=None):
return [self.select(transaction_id, "foreign_edges", key)] | Python | nomic_cornstack_python_v1 |
comment 2.24.2019 - shashi
comment Comprised of a team of five incredibly brilliant women, "The ladies of ENIAC" were the first “computors” working at the
comment University of Pennsylvania’s Moore School of Engineering (1945). Through their contributions, we gained the first software
comment application and the first ... | #2.24.2019 - shashi
#Comprised of a team of five incredibly brilliant women, "The ladies of ENIAC" were the first “computors” working at the
#University of Pennsylvania’s Moore School of Engineering (1945). Through their contributions, we gained the first software
#application and the first programming classes! The l... | Python | zaydzuhri_stack_edu_python |
function _remove_last_stream_calendar_entries client_id match_id now
begin
comment Remove every CalendarEntry for this match.
set result = execute session where match_id == match_id
end function | def _remove_last_stream_calendar_entries(client_id, match_id, now):
# Remove every CalendarEntry for this match.
result = session.execute(
CalendarEntries.delete().where(CalendarEntry.match_id == match_id)) | Python | nomic_cornstack_python_v1 |
string SVM for email spam classification
import numpy as np
from sklearn import svm
import re
from nltk.stem import PorterStemmer
comment LOAD DATA
comment needed to load data (as np arrays), puts data into numpy column vectors, shape == (length, 1)
from scipy.io import loadmat
set spam_train = call loadmat string spam... | """ SVM for email spam classification """
import numpy as np
from sklearn import svm
import re
from nltk.stem import PorterStemmer
##########################################################################################################
# LOAD DATA
###################################################################... | Python | zaydzuhri_stack_edu_python |
comment Scentence corrector
import requests
set word = input string Enter sentence:
comment x=len(word.split())
set urls = string https://www.google.com/search?q= + word + string &oq= + word + string &aqs=chrome..69i57j46i10j0i10l7.3288j0j9&sourceid=chrome&ie=UTF-8
set x = get requests urls
set zz = string content
set ... | ## Scentence corrector
import requests
word=input("Enter sentence: ")
#x=len(word.split())
urls="https://www.google.com/search?q="+word+"&oq="+word+"&aqs=chrome..69i57j46i10j0i10l7.3288j0j9&sourceid=chrome&ie=UTF-8"
x=requests.get(urls)
zz=str(x.content)
ss='''href="/search?ie'''
y=zz.find(ss)
ls1=zz[y:].split... | Python | zaydzuhri_stack_edu_python |
string Program: a2.py Name: Date: Desc:
comment Initialize the database of student grades
set database = list list string ICS4U string Assignment 1 string Luke Skywalker string 3+ list string ICS4U string Assignment 1 string Han Solo string 4- list string SPH3U string Unit 1 Test string Leia Organa string 4 list string... | '''
Program: a2.py
Name:
Date:
Desc:
'''
# Initialize the database of student grades
database = [
['ICS4U', 'Assignment 1', 'Luke Skywalker', '3+'],
['ICS4U', 'Assignment 1', 'Han Solo', '4-'],
['SPH3U', 'Unit 1 Test', 'Leia Organa', '4'],
['SPH3U', 'Unit 1 Test', 'Luke Skywalker', '3-'],
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
import sys
from optparse import OptionParser
comment A typical usage function
function usage msg retval
begin
write stderr string Error: + msg + string
exit retval
end function
comment The option parser will accept short and long arguments. eg.
comment ./opt.py -f /etc/passwd -c ./conf.txt
comm... | #!/usr/bin/python
import sys
from optparse import OptionParser
# A typical usage function
def usage(msg, retval):
sys.stderr.write("Error: " + msg + "\n")
sys.exit(retval)
# The option parser will accept short and long arguments. eg.
# ./opt.py -f /etc/passwd -c ./conf.txt
# or
# ./opt.py --file /etc/passwd --c... | Python | zaydzuhri_stack_edu_python |
function proxy_results id
begin
comment We need the server io for the decryption of the results
set client : NodeClient = get config string SERVER_IO
if not client
begin
return tuple dict string msg string Proxy server not initialized properly INTERNAL_SERVER_ERROR
end
comment Make the proxied request
try
begin
set res... | def proxy_results(id: int) -> Response:
# We need the server io for the decryption of the results
client: NodeClient = app.config.get("SERVER_IO")
if not client:
return {'msg': 'Proxy server not initialized properly'},\
HTTPStatus.INTERNAL_SERVER_ERROR
# Make the proxied request
... | Python | nomic_cornstack_python_v1 |
function receptor_type self
begin
return __receptor_type
end function | def receptor_type(self):
return self.__receptor_type | Python | nomic_cornstack_python_v1 |
function do_ask self s
begin
if PY2
begin
call main self
end
else
begin
call print_say string Feature currently not available in Python 3 self RED
end
end function | def do_ask(self, s):
if six.PY2:
chat.main(self)
else:
print_say("Feature currently not available in Python 3", self, Fore.RED) | Python | nomic_cornstack_python_v1 |
import json
comment Import the stop word list
from nltk.corpus import stopwords
import re
from urlparse import urlparse
from nltk import *
from nltk.stem.wordnet import *
function histogram words freq
begin
for w in words
begin
if call has_key w
begin
set freq at w = freq at w + 1
end
else
begin
set freq at w = 1
end
e... | import json
from nltk.corpus import stopwords # Import the stop word list
import re
from urlparse import urlparse
from nltk import *
from nltk.stem.wordnet import *
def histogram(words, freq):
for w in words:
if freq.has_key(w):
freq[w] = freq[w] + 1
else:
freq[w] = 1
re... | Python | zaydzuhri_stack_edu_python |
function countActiveSensors ringOfSensors
begin
set count = 0
for i in range length ringOfSensors
begin
set left_neighbor = ringOfSensors at i - 1 + length ringOfSensors % length ringOfSensors
set right_neighbor = ringOfSensors at i + 1 % length ringOfSensors
if left_neighbor == 1 and right_neighbor == 1
begin
set coun... | def countActiveSensors(ringOfSensors):
count = 0
for i in range(len(ringOfSensors)):
left_neighbor = ringOfSensors[(i - 1 + len(ringOfSensors)) % len(ringOfSensors)]
right_neighbor = ringOfSensors[(i + 1) % len(ringOfSensors)]
if left_neighbor == 1 and right_neighbor == 1:
co... | Python | flytech_python_25k |
function addExtra self opaqueobject
begin
append _extra opaqueobject
end function | def addExtra(self, opaqueobject):
doc._extra.append(opaqueobject) | Python | nomic_cornstack_python_v1 |
function get_input_fn filename
begin
function input_fn params
begin
string Generates an input function for training or evaluation. This uses the input pipeline based approach using file name queue to read data so that entire data is not loaded in memory. Args: params (dict): Dictionary of additional params like batch_s... | def get_input_fn(filename):
def input_fn(params):
"""Generates an input function for training or evaluation.
This uses the input pipeline based approach using file name queue
to read data so that entire data is not loaded in memory.
Args:
params (dict): Dictionary of additional params like bat... | 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.