code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function select_expand self
begin
set path_len = 0
set curr_node = root_node
while true
begin
if is_terminal
begin
break
end
if is_fully_expanded
begin
set tuple _ curr_node = call _get_best_node curr_node
set path_len = path_len + 1
end
else
begin
set tuple _ node = call _expand curr_node
if node is not none
begin
set... | def select_expand(self):
path_len = 0
curr_node = self.root_node
while True:
if curr_node.is_terminal:
break
if curr_node.is_fully_expanded:
_, curr_node = self._get_best_node(curr_node)
path_len += 1
else:
... | Python | nomic_cornstack_python_v1 |
import unittest
from str_calculator import str_calculator
class TestSringCalculator extends TestCase
begin
function test_concat self
begin
set r = call str_calculator string a string b string concat
assert equal r string ab
end function
function test_contain_when_true self
begin
set r = call str_calculator string ala s... | import unittest
from str_calculator import str_calculator
class TestSringCalculator(unittest.TestCase):
def test_concat(self):
r = str_calculator("a", "b", 'concat')
self.assertEqual(r, 'ab')
def test_contain_when_true(self):
r = str_calculator("ala", "ala ma kota", 'contains')
... | Python | zaydzuhri_stack_edu_python |
function _apply_to_services self function services=list
begin
set services_iterable = if expression services then services else services_with_code
comment type: ignore
for service in services_iterable
begin
if not call function service
begin
comment Fail fast to optimize the CI/CD pipeline
return false
end
end
return t... | def _apply_to_services(self, function: Callable[[str], bool], services: List[str] = []) -> bool:
services_iterable = services if services else self.config.services_with_code
for service in services_iterable: # type: ignore
if not function(service):
return False # Fail fas... | Python | nomic_cornstack_python_v1 |
set floatNumber = decimal input
print string %f % floatNumber | floatNumber = float(input())
print("%f" % floatNumber) | Python | zaydzuhri_stack_edu_python |
from base_backend import BaseBackend
class Backend extends BaseBackend
begin
function __init__ self db *args **kwargs
begin
set db = db
call __init__ *args keyword kwargs
end function
function find_one self **filters
begin
set sql = call select_sql users_table filters
return call fetch_one sql filters
end function
asyn... | from .base_backend import BaseBackend
class Backend(BaseBackend):
def __init__(self, db, *args, **kwargs):
self.db = db
super().__init__(*args, **kwargs)
def find_one(self, **filters):
sql = select_sql(self.users_table, filters)
return self.db.fetch_one(sql, filters)
asyn... | Python | zaydzuhri_stack_edu_python |
import random
class Maso extends object
begin
function __init__ self crear_cartas=true
begin
set cartas = list
if crear_cartas
begin
for palo in PALOS
begin
extend cartas list comprehension call Carta numero palo for numero in NUMEROS
end
end
end function
function barajar self
begin
comment for i in range(0, 3):
commen... | import random
class Maso(object):
def __init__(self, crear_cartas=True):
self.cartas = list()
if crear_cartas:
for palo in Carta.PALOS:
self.cartas.extend([Carta(numero, palo) for numero in Carta.NUMEROS])
def barajar(self):
# for i in range(0, 3... | Python | zaydzuhri_stack_edu_python |
import torch
import torch.nn as nn
class NRMSModel extends Module
begin
function __init__ self hparams vocab
begin
call __init__
set name = hparams at string name
set cdd_size = if expression hparams at string npratio > 0 then hparams at string npratio + 1 else 1
set device = device hparams at string device
if hparams ... | import torch
import torch.nn as nn
class NRMSModel(nn.Module):
def __init__(self,hparams,vocab):
super().__init__()
self.name = hparams['name']
self.cdd_size = (hparams['npratio'] + 1) if hparams['npratio'] > 0 else 1
self.device = torch.device(hparams['device'])
i... | Python | zaydzuhri_stack_edu_python |
function min_time self min_time
begin
set _min_time = min_time
end function | def min_time(self, min_time: str):
self._min_time = min_time | Python | nomic_cornstack_python_v1 |
function get_verified_password self
begin
raise call NotImplementedError string get_verified_password
end function | def get_verified_password(self):
raise NotImplementedError('get_verified_password') | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
import sys
class Datensatz
begin
set data = dict
function add self column value
begin
update data dict column value
end function
function __init__ self column value
begin
add self column value
end function
function drop self
begin
clear data
end function
end ... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
class Datensatz:
data = {}
def add(self, column, value):
self.data.update({column:value})
def __init__(self, column, value):
self.add(column,value)
def drop(self):
self.data.clear()
| Python | zaydzuhri_stack_edu_python |
function level_33
begin
print string [31mLevel 33[0m
from PIL import Image
import numpy as np
set im = open string source/beer2.png
set data_list = list call getdata
set data_set = set data_list
while data_set
begin
set c0 = max data_set
remove data_set c0
set c1 = max data_set
remove data_set c1
set tuple c0 c1 = tu... | def level_33() -> None:
print(f"\033[31mLevel 33\033[0m")
from PIL import Image
import numpy as np
im = Image.open("source/beer2.png")
data_list = list(im.getdata())
data_set = set(data_list)
while data_set:
c0 = max(data_set)
data_set.remove(c0)
c1 = max(data_set)
... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
set inputNumber = decimal input string 변환할 화씨온도(℉를) 입력하십시오:
print string %0.2f℉는 %0.2f℃입니다. % tuple inputNumber inputNumber - 32 * 5 / 9
comment 1. #-*- coding: utf-8 -*-은 python2.x버전에서 인코딩을 알려주는 규약입니다.
comment python3에서는 사용하지 않으셔되 됩니다.
comment 2. 1번 줄에서의 빨간 줄은 # 뒤에 공백이 없어서 발생합니다.
comment ... | #-*- coding: utf-8 -*-
inputNumber=float(input("변환할 화씨온도(℉를) 입력하십시오: "))
print("%0.2f℉는 %0.2f℃입니다." %(inputNumber, (inputNumber-32)*5/9))
# 1. #-*- coding: utf-8 -*-은 python2.x버전에서 인코딩을 알려주는 규약입니다.
# python3에서는 사용하지 않으셔되 됩니다.
# 2. 1번 줄에서의 빨간 줄은 # 뒤에 공백이 없어서 발생합니다.
# 3. 2번 줄에서의 빨간 줄은 '=' 연산자 주변에 공백이 없어서 그렇습니다.
# 4. 3번 ... | Python | zaydzuhri_stack_edu_python |
import datetime
import hashlib
import json
class Block
begin
function __init__ self timestamp nonce data hash previous_hash
begin
set timestamp = timestamp
set nonce = nonce
set data = data
set curhash = hash
set previous_hash = previous_hash
end function
function hash self
begin
print dumps data
return hex digest sha2... | import datetime
import hashlib
import json
class Block:
def __init__(self , timestamp, nonce , data , hash , previous_hash):
self.timestamp = timestamp
self.nonce = nonce
self.data = data
self.curhash = hash
self.previous_hash = previous_hash
def hash(self):
pr... | Python | zaydzuhri_stack_edu_python |
function set_flash_mode self mode
begin
call setFlashMode call get_enum_value mode
end function | def set_flash_mode(self, mode: FlashModeStr | multimedia.QCamera.FlashMode):
self.setFlashMode(FLASH_MODE.get_enum_value(mode)) | Python | nomic_cornstack_python_v1 |
comment simply use dictionary for adj list
comment for topological sort when a node is finished add to a list.
comment at the end of the DFS print the list in reverse.
class Graph
begin
function __init__ self nodes
begin
set V = nodes
set adj_list = dictionary
set adj_list = dictionary comprehension i : list for i in r... | # simply use dictionary for adj list
# for topological sort when a node is finished add to a list.
# at the end of the DFS print the list in reverse.
class Graph:
def __init__(self, nodes):
self.V = nodes
self.adj_list = dict()
self.adj_list = {i: list() for i in range(self.V)}
self... | Python | zaydzuhri_stack_edu_python |
function test_arithmatex_generic self
begin
call check_markdown string ```math E(\mathbf{v}, \mathbf{h}) = -\sum_{i,j}w_{ij}v_i h_j - \sum_i b_i v_i - \sum_j c_j h_j ``` string <div class="arithmatex">\[ E(\mathbf{v}, \mathbf{h}) = -\sum_{i,j}w_{ij}v_i h_j - \sum_i b_i v_i - \sum_j c_j h_j \]</div> true
end function | def test_arithmatex_generic(self):
self.check_markdown(
r'''
```math
E(\mathbf{v}, \mathbf{h}) = -\sum_{i,j}w_{ij}v_i h_j - \sum_i b_i v_i - \sum_j c_j h_j
```
''',
r'''
<div class="arithmatex">\[
E(\mathbf{v}, \mat... | Python | nomic_cornstack_python_v1 |
from code_challenges.left_join.left_join import left_join
from code_challenges.left_join.hashtable import Hashtable
import pytest
function test_join_left_all_the_same hash
begin
set actual = call left_join hash at 0 hash at 1
set expected = list list string fond string enamored string averse list string wrath string an... | from code_challenges.left_join.left_join import left_join
from code_challenges.left_join.hashtable import Hashtable
import pytest
def test_join_left_all_the_same(hash):
actual = left_join(hash[0], hash[1])
expected = [
["fond", "enamored", "averse"],
["wrath", "anger", "delight"],
["di... | Python | zaydzuhri_stack_edu_python |
function on_test_end self logs=none
begin
call on_test_end logs
end function | def on_test_end(self, logs=None):
self.tf_callback.on_test_end(logs) | Python | nomic_cornstack_python_v1 |
from pyparsing import Word , Optional , LineStart , LineEnd , SkipTo
import re
from regs import search
import string
function find_next_section_offsets text part
begin
string Find the start/end of the next section
end function | from pyparsing import Word, Optional, LineStart, LineEnd, SkipTo
import re
from regs import search
import string
def find_next_section_offsets(text, part):
"""Find the start/end of the next section""" | Python | zaydzuhri_stack_edu_python |
from thefuck.types import Command
set RE_AUTH_TEXT = string To re-authenticate, please run:
function match command
begin
return RE_AUTH_TEXT in output
end function
function get_new_command command
begin
set re_auth_index = find output RE_AUTH_TEXT
set command_start_index = re_auth_index + length RE_AUTH_TEXT
set comman... | from thefuck.types import Command
RE_AUTH_TEXT = "To re-authenticate, please run:\n"
def match(command: Command):
return RE_AUTH_TEXT in command.output
def get_new_command(command: Command):
re_auth_index = command.output.find(RE_AUTH_TEXT)
command_start_index = re_auth_index + len(RE_AUTH_TEXT)
co... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Spyder Editor This is a temporary script file.
set annual_salary = decimal input string Enter your annual salary:
set portion_saved = decimal input string Enter the percnet of your salary to save, as a decimal:
set total_cost = decimal input string Enter the cost of your dream home:... | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
annual_salary= float(input('Enter your annual salary: '))
portion_saved= float(input('Enter the percnet of your salary to save, as a decimal: '))
total_cost= float(input('Enter the cost of your dream home: '))
semi_annual_raise= fl... | Python | zaydzuhri_stack_edu_python |
function categorize_y self labels class_dict
begin
set labels = list comprehension class_dict at i for i in labels
return call to_categorical labels length class_dict
end function | def categorize_y(self, labels, class_dict):
labels = [class_dict[i] for i in labels]
return keras.utils.to_categorical(labels, len(class_dict)) | Python | nomic_cornstack_python_v1 |
comment ON START SERVER SHOULD BE SUPPLIED WITH CONTROL PORT NUMBER
from socket import *
from threading import Thread
import sys
import os
import shutil
import json
import getpass
import glob
global pam_import
try
begin
import pam
set pam_import = 0
end
except ImportError
begin
set pam_import = 1
end
global control_por... | #ON START SERVER SHOULD BE SUPPLIED WITH CONTROL PORT NUMBER
from socket import *
from threading import Thread
import sys
import os
import shutil
import json
import getpass
import glob
global pam_import
try:
import pam
pam_import = 0
except ImportError:
pam_import = 1
global control_port
class State:
'... | Python | zaydzuhri_stack_edu_python |
function split_data self X_vector y_vector test_size=0.2
begin
print string * * 50 string Start train_test_split string * * 50
set start_time = time
set tuple X_train X_val y_train y_val = train test split X_vector y_vector test_size=test_size random_state=1024
comment X_train, X_val, y_train, y_val = train_test_split(... | def split_data(self, X_vector, y_vector, test_size=0.2):
print("*" * 50, "Start train_test_split", "*" * 50)
start_time = time()
X_train, X_val, y_train, y_val = train_test_split(X_vector, y_vector, test_size=test_size,
random_state=1024)... | Python | nomic_cornstack_python_v1 |
function get_symbols self by=none val=none
begin
assert by in tuple none string sector string industry string year_added string year_founded
if by == none
begin
return symbols
end
if by == string sector
begin
if val
begin
return call to_dict
end
else
begin
set dct = call to_dict orient=string index
for tuple k v in ite... | def get_symbols(self, by=None, val=None):
assert by in (None, "sector", "industry", "year_added", "year_founded")
if by==None:
return self.symbols
if by=='sector':
if val:
return self.raw[self.raw['GICS Sector']==val]['Security'].to_dict()
else... | Python | nomic_cornstack_python_v1 |
comment !/bin/python3
string Input: 10 161 182 161 154 176 170 167 171 170 174 Output: 169.375
function average array
begin
set result = 0
set set_array = set array
set result = sum set_array / length set_array
return result
end function
if __name__ == string __main__
begin
set n = integer input
set arr = list map int ... | #!/bin/python3
"""
Input:
10
161 182 161 154 176 170 167 171 170 174
Output:
169.375
"""
def average(array):
result = 0
set_array = set(array)
result = sum(set_array)/len(set_array)
return result
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().split()))
result = ... | Python | zaydzuhri_stack_edu_python |
function get_info node
begin
set info = dict string parser_style string _ ; string parser_lang none ; string parser_defaults none ; string convert_style string _ ; string convert_from none ; string convert_to string html ; string convert_defaults none ; string adopt true ; string convert string true
for att in node
beg... | def get_info(node):
info = {
'parser_style': '_',
'parser_lang': None,
'parser_defaults': None,
'convert_style': '_',
'convert_from': None,
'convert_to': 'html',
'convert_defaults': None,
'adopt': True,
'... | Python | nomic_cornstack_python_v1 |
function test_clean_up_global_blacklist self
begin
comment Test that a reproducible leak is not cleared from blacklist cleanup.
set testcase = call _add_dummy_leak_testcase
set blacklist_item = call add_crash_to_global_blacklist_if_needed testcase
call cleanup_global_blacklist
assert true get key
comment Test that an u... | def test_clean_up_global_blacklist(self):
# Test that a reproducible leak is not cleared from blacklist cleanup.
testcase = self._add_dummy_leak_testcase()
blacklist_item = leak_blacklist.add_crash_to_global_blacklist_if_needed(
testcase)
leak_blacklist.cleanup_global_blacklist()
self.assert... | Python | nomic_cornstack_python_v1 |
comment gui program calculates gas mileage
comment needs entry widgets that let user enter gallons of gas car holds
comment and number of miles it can be driven on a full tank
comment when calculate mpg button is clicked
comment should display the mpg
comment mpg is miles/gallons
import tkinter
import tkinter.messagebo... | #gui program calculates gas mileage
#needs entry widgets that let user enter gallons of gas car holds
#and number of miles it can be driven on a full tank
#when calculate mpg button is clicked
#should display the mpg
#mpg is miles/gallons
import tkinter
import tkinter.messagebox
class MpgGUI:
def __i... | Python | zaydzuhri_stack_edu_python |
function basic_propagate
begin
global assignments trail STATS
comment propagate until a conflict is derived or we have no unit clauses left
while unit_clauses := call basic_get_unit_clauses
begin
set unit_clause = unit_clauses at 0
comment figure out the only unassigned literal in the unit clause
set unit = none
for li... | def basic_propagate() -> Optional[Clause]:
global assignments, trail, STATS
# propagate until a conflict is derived or we have no unit clauses left
while unit_clauses := basic_get_unit_clauses():
unit_clause = unit_clauses[0]
# figure out the only unassigned literal in the unit clause
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
comment -*- coding: utf-8 -*-
string PROGRAM : compile_seeding_set.py AUTHOR : Eliza Harrison Retrieves and compiles a seeding set of subreddits known to relate to the discussion of health topics and which can be used to identify clusters of similarly health-related subreddits.
import re
import... | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
PROGRAM : compile_seeding_set.py
AUTHOR : Eliza Harrison
Retrieves and compiles a seeding set of subreddits known to relate to the
discussion of health topics and which can be used to identify clusters of similarly
health-related subreddits.
"""
import re
import pandas... | Python | zaydzuhri_stack_edu_python |
function get_tx_history account_id total
begin
set query = query iroha string GetTransactions account_id=account_id page_size=total
call sign_query query user_private_key
set response = call send_query query
set data = call MessageToDict response
call pprint data indent=2
end function | def get_tx_history(account_id, total):
query = iroha.query("GetTransactions", account_id=account_id, page_size=total)
ic.sign_query(query, user_private_key)
response = net.send_query(query)
data = MessageToDict(response)
pprint(data, indent=2) | Python | nomic_cornstack_python_v1 |
import scrapy
import sys
append path string ../../../../fastfood/
from fastfood.extractor.items import ReceitasRapidasItem
from fastfood.extractor.utils import strip_tags
string first version of the first crawler. I'm learning how to use scrapy, so this may be extremely poor coded. the target website didn't help as wel... | import scrapy
import sys
sys.path.append("../../../../fastfood/")
from fastfood.extractor.items import ReceitasRapidasItem
from fastfood.extractor.utils import strip_tags
"""
first version of the first crawler.
I'm learning how to use scrapy, so
this may be extremely poor coded.
the target website didn't help as wel... | Python | zaydzuhri_stack_edu_python |
comment import binascii
comment import socket
comment import struct
comment import sys
comment # Create a TCP/IP socket
comment sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
comment server_address = ('localhost', 1234)
comment sock.bind(server_address)
comment sock.listen(1)
comment while True:
comment MESSA... | # import binascii
# import socket
# import struct
# import sys
#
# # Create a TCP/IP socket
# sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# server_address = ('localhost', 1234)
# sock.bind(server_address)
# sock.listen(1)
#
# while True:
# MESSAGE = b'\x09\x00\x09'
# sock.send(MESSAGE)
# print ... | Python | zaydzuhri_stack_edu_python |
function createUTF8ColumnFamily sys_manager keyspace tablename ts_table=false
begin
comment Default options for the tree-storage tables
set kw_options = dict string super false ; string comparator_type call UTF8Type ; string key_validation_class call UTF8Type ; string default_validation_class call UTF8Type
comment A ts... | def createUTF8ColumnFamily(sys_manager, keyspace, tablename, ts_table=False):
# Default options for the tree-storage tables
kw_options = {'super': False, 'comparator_type': pycassa_types.UTF8Type(),
'key_validation_class': pycassa_types.UTF8Type(),
'default_validation_class': pycass... | Python | nomic_cornstack_python_v1 |
function _async_raise tid exctype
begin
set tid = call c_long tid
if not call isclass exctype
begin
set exctype = type exctype
end
set res = call PyThreadState_SetAsyncExc tid call py_object exctype
if res == 0
begin
raise call ValueError string invalid thread id
end
else
if res != 1
begin
comment """if it returns a nu... | def _async_raise(tid, exctype):
tid = ctypes.c_long(tid)
if not inspect.isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
# """if it retu... | Python | nomic_cornstack_python_v1 |
import csv
function get_new_weight _weights _inputs output
begin
return list map lambda xi wi -> decimal wi + decimal xi * decimal output _inputs _weights
end function
function get_new_bias old_bias output
begin
return decimal old_bias + decimal output
end function
function main
begin
set weights = list 0 0
set bias = ... | import csv
def get_new_weight(_weights, _inputs, output):
return list(map(lambda xi, wi: float(wi) + float(xi) * float(output), _inputs, _weights))
def get_new_bias(old_bias, output):
return float(old_bias) + float(output)
def main():
weights = [0, 0]
bias = 0
file_path = 'truth_table.csv'
... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import matplotlib.pyplot as plt
import itertools
from matplotlib.lines import Line2D
function read_data n
begin
string Finds the results for a run with N agents and returns a pandas dataframe
return read json string N_ { n } _output.json
end function
function redefine_rounds old_rounds
begin
string ... | import pandas as pd
import matplotlib.pyplot as plt
import itertools
from matplotlib.lines import Line2D
def read_data(n):
"""Finds the results for a run with N agents and returns a pandas dataframe"""
return pd.read_json(f"N_{n}_output.json")
def redefine_rounds(old_rounds):
"""Redefines the bit intege... | Python | zaydzuhri_stack_edu_python |
function do_kcsd ele_pos pots **params
begin
set num_ele = length ele_pos
set pots = reshape pots num_ele 1
set k = call KCSD1D ele_pos pots keyword params
comment k.cross_validate(Rs=np.arange(0.01,0.2,0.01), lambdas= np.logspace(15,-25,25))
cross validate Rs=array list 0.275 lambdas=call logspace 15 - 25 35
set est_c... | def do_kcsd(ele_pos, pots, **params):
num_ele = len(ele_pos)
pots = pots.reshape(num_ele, 1)
k = KCSD1D(ele_pos, pots, **params)
#k.cross_validate(Rs=np.arange(0.01,0.2,0.01), lambdas= np.logspace(15,-25,25))
k.cross_validate(Rs=np.array([0.275]), lambdas=np.logspace(15,-25, 35))
est_csd = k.val... | Python | nomic_cornstack_python_v1 |
comment Set of functions used to perform and test the Weighted Alternating
comment Least Squares algorithm.
import numpy as np
import numpy.linalg as lin
import pandas as pd
comment Define functions to compute approximated ratings and error.
function predict X Y
begin
string Computes the dot product between X and Y.T, ... | # Set of functions used to perform and test the Weighted Alternating
# Least Squares algorithm.
import numpy as np
import numpy.linalg as lin
import pandas as pd
# Define functions to compute approximated ratings and error.
def predict(X, Y):
"""
Computes the dot product between X and Y.T, producing a predi... | Python | zaydzuhri_stack_edu_python |
function testCheckSha256Signature_FailBadHash self
begin
set sig_data = call ljust 256
set expected_signed_hash = call digest
set returned_signed_hash = call digest
call DoCheckSha256SignatureTest false true sig_data SIG_ASN1_HEADER expected_signed_hash returned_signed_hash
end function | def testCheckSha256Signature_FailBadHash(self):
sig_data = 'fake-signature'.ljust(256)
expected_signed_hash = hashlib.sha256('fake-data').digest()
returned_signed_hash = hashlib.sha256('bad-fake-data').digest()
self.DoCheckSha256SignatureTest(False, True, sig_data,
co... | Python | nomic_cornstack_python_v1 |
string This Python script defines a function named add that takes in two arguments, x and y, and returns their sum. The time complexity of this function is O(1) as it performs a single operation, the addition of x and y. The space complexity is also O(1) as the function does not use any additional memory. The function ... | """
This Python script defines a function named add that takes in two arguments, x and y, and returns their sum. The time complexity of this function is O(1) as it performs a single operation, the addition of x and y. The space complexity is also O(1) as the function does not use any additional memory.
The function sh... | Python | jtatman_500k |
function load_storage
begin
make directories STORAGE_DIR mode=448 exist_ok=true
try
begin
with open STORAGE_FILE encoding=string utf-8 as fp
begin
set serializable_seen_app_dict = load json fp
return dictionary comprehension app_filename : call date for tuple app_filename serialized_first_seen_date in items serializabl... | def load_storage():
os.makedirs(STORAGE_DIR, mode=0o700, exist_ok=True)
try:
with open(STORAGE_FILE, encoding="utf-8") as fp:
serializable_seen_app_dict = json.load(fp)
return {app_filename: arrow.get(serialized_first_seen_date).date()
for app_filename, serial... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment coding:utf-8
comment 循环和操作符
comment a = raw_input(unicode('请输入5个数字:','utf-8').encode('gbk'))
comment alist = [1,2,3,4,5]
set b = 0
set i = 0
while i < 5
begin
set b = b + integer call raw_input encode call unicode string 请输入1个数字: string utf-8 string gbk
set i = i + 1
end | #!/usr/bin/env python
#coding:utf-8
#循环和操作符
# a = raw_input(unicode('请输入5个数字:','utf-8').encode('gbk'))
# alist = [1,2,3,4,5]
b=0
i=0
while i < 5:
b += int(raw_input(unicode('请输入1个数字:','utf-8').encode('gbk')))
i += 1 | Python | zaydzuhri_stack_edu_python |
import random
class ArrayStack
begin
function __init__ self
begin
set revdata = list
set data = list
end function
function __len__ self
begin
comment 221910307033 ( Likith Narukurhti)
return length data
end function
function is_empty self
begin
return length data == 0
end function
function push self ele
begin
append ... | import random
class ArrayStack:
def __init__(self):
self.revdata = []
self.data = []
def __len__(self):
return len(self.data) # 221910307033 ( Likith Narukurhti)
def is_empty(self):
return len(self.data) == 0
def push(self, ele):
... | Python | zaydzuhri_stack_edu_python |
comment -*- coding=utf-8 -*-
import requests
from concurrent.futures import ThreadPoolExecutor , wait , ALL_COMPLETED
import os
import sys
import time
class PiecesDownLoadFile
begin
function __init__ self file_name url max_workers
begin
set file_name = file_name
set url = url
set max_workers = max_workers
set total_pie... | # -*- coding=utf-8 -*-
import requests
from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED
import os
import sys
import time
class PiecesDownLoadFile():
def __init__(self, file_name, url, max_workers):
self.file_name = file_name
self.url = url
self.max_workers = max_worke... | Python | zaydzuhri_stack_edu_python |
comment copy and paste this code into the first line of main.py, before all the other code there (if there is any).
import RPSelements
import random
import click
function clrscr
begin
comment Clear screen using click.clear() function
clear click
end function
print welcome
set play = string Y
while play == string Y or p... | # copy and paste this code into the first line of main.py, before all the other code there (if there is any).
import RPSelements
import random
import click
def clrscr():
# Clear screen using click.clear() function
click.clear()
print(RPSelements.welcome)
play="Y"
while play=="Y" or play=="y":
choice=int(input... | Python | zaydzuhri_stack_edu_python |
function get_query_result self query
begin
set sp_ = hex
execute cursor format string SAVEPOINT "{}" sp_
try
begin
execute cursor query
set rows = call fetchall
end
except Exception
begin
execute cursor format string ROLLBACK TO SAVEPOINT "{}" sp_
raise
end
try else
begin
execute cursor format string RELEASE SAVEPOINT ... | def get_query_result(self, query):
sp_ = uuid.uuid1().hex
self.cursor.execute('SAVEPOINT "{}"'.format(sp_))
try:
self.cursor.execute(query)
rows = self.cursor.fetchall()
except Exception:
self.cursor.execute('ROLLBACK TO SAVEPOINT "{}"'.format(sp_))
raise
else:
self.cur... | Python | nomic_cornstack_python_v1 |
function iterchunks self chunklen stepsize=none startindex=none endindex=none include_remainder=true accessmode=none
begin
with call _open_array accessmode=accessmode as tuple ar _
begin
for tuple framestart frameend in call iterindices chunklen stepsize=stepsize startindex=startindex endindex=endindex include_remainde... | def iterchunks(self, chunklen, stepsize=None, startindex=None,
endindex=None, include_remainder=True, accessmode=None):
with self._open_array(accessmode=accessmode) as (ar, _):
for framestart, frameend in \
self.iterindices(chunklen, stepsize=stepsize,
... | Python | nomic_cornstack_python_v1 |
function database
begin
set db = call Database
yield db
close db
end function | def database():
db = Database()
yield db
db.close() | Python | nomic_cornstack_python_v1 |
for i in range 0 length list1
begin
for j in range i length list1
begin
comment it is compulsory to write here otherwise sum will added up.
set current_sum = 0
for k in range i j + 1
begin
set current_sum = current_sum + list1 at k
end
comment printing all subarray
comment print(current_sum)
if current_sum >= maxsum
be... | for i in range(0,len(list1)):
for j in range(i,len(list1)):
current_sum=0 #it is compulsory to write here otherwise sum will added up.
for k in range(i,j+1):
current_sum+=list1[k]
# printing all subarray
#print(current_sum)
if current_... | Python | zaydzuhri_stack_edu_python |
function test_svc_acct_command_support_05
begin
comment "op item get" is supported but requires a "--vault" argument
comment when used with service accounts
set item_get_argv = list string op string --format string json string item string get string example item
set reg = call OPSvcAcctSupportRegistry
set support = cal... | def test_svc_acct_command_support_05():
# "op item get" is supported but requires a "--vault" argument
# when used with service accounts
item_get_argv = ['op', '--format', 'json', 'item', 'get', 'example item']
reg = OPSvcAcctSupportRegistry()
support = reg.command_supported(item_get_argv)
asse... | Python | nomic_cornstack_python_v1 |
from urllib.request import urlopen
from bs4 import BeautifulSoup
comment 더 페이보릿 : 여왕의 여자 네티즌 리뷰 크롤링
set url = string https://movie.daum.net/moviedb/grade?movieId=119036&type=netizen&page=1
set webpage = url open url
set source = call BeautifulSoup webpage string html.parser from_encoding=string utf-8
set netizen_review... | from urllib.request import urlopen
from bs4 import BeautifulSoup
# 더 페이보릿 : 여왕의 여자 네티즌 리뷰 크롤링
url = 'https://movie.daum.net/moviedb/grade?movieId=119036&type=netizen&page=1'
webpage = urlopen(url)
source = BeautifulSoup(webpage, 'html.parser', from_encoding='utf-8')
netizen_reviews = source.findAll('p', {'class': 'de... | Python | zaydzuhri_stack_edu_python |
function run_plugin self plugin_name file_id forge_file_name=none datafile_id=none
begin
run plugin_name file_id forge_file_name datafile_id
end function | def run_plugin(self, plugin_name: str, file_id: Union[str, int], forge_file_name: Union[None, str] = None, datafile_id: Union[None, int] = None) -> None:
self.pyUbiForge.right_click_plugins.run(plugin_name, file_id, forge_file_name, datafile_id) | Python | nomic_cornstack_python_v1 |
function grid_search train_labels test_labels output res=tuple 120 160 lazy=true batch_size=16 epochs=20
begin
comment Data
print string => Loading data.
set train = call FLIRDataset train_labels res=res batch_size=batch_size
set test = call FLIRDataset test_labels res=res batch_size=batch_size
comment In eager loading... | def grid_search(train_labels: str,
test_labels: str,
output:str,
res:tuple=(120, 160),
lazy:bool=True,
batch_size:int=16,
epochs:int=20):
# Data
print("=> Loading data.")
train = FLIRDataset(train_labels, ... | Python | nomic_cornstack_python_v1 |
comment coding:utf-8
comment 两层简单的神经网络(全连接)
import tensorflow as tf
comment 定义输入和参数
set x = call constant list list 0.7 0.5
set w1 = call Variable call random_normal list 2 3 stddev=1 seed=1
set w2 = call Variable call random_normal list 3 1 stddev=1 seed=1
comment 定义向前传播过程
set a = matrix multiply x w1
set y = matrix m... | #coding:utf-8
#两层简单的神经网络(全连接)
import tensorflow as tf
#定义输入和参数
x=tf.constant([[0.7,0.5]])
w1=tf.Variable(tf.random_normal([2,3],stddev=1,seed=1))
w2=tf.Variable(tf.random_normal([3,1],stddev=1,seed=1))
#定义向前传播过程
a=tf.matmul(x,w1)
y=tf.matmul(a,w2)
#用会话计算结果
with tf.Session() as sess:
init_op=tf.global_variables_init... | Python | zaydzuhri_stack_edu_python |
comment RUN THE PROGRAM TO SEE THE PATTERN OF NUMBERS
set a = integer input string enter:
set d = a
set rows = 7
set k = 0
set l = 1
print a
for i in range rows - 1
begin
if i % 2 != 0
begin
set a = a * 3
set k = k + 3
for j in range k
begin
print a + 2 * j end=string
end
print
end
else
begin
set d = d * 2
set l = l * ... | # RUN THE PROGRAM TO SEE THE PATTERN OF NUMBERS
a=int(input("enter: "))
d=a
rows=7
k=0
l=1
print(a)
for i in range(rows-1):
if (i%2!=0):
a=a*3
k+=3
for j in range(k):
print(a+(2*j), end=" ")
print()
else:
d*=2
l*=2
for j in ran... | Python | zaydzuhri_stack_edu_python |
from models.dish import Dish
from enums.type_of_menu import TypeOfMenu
from enums.temperature import Temperature
from enums.level_of_spicy import LevelOfSpicy
class Drinks extends Dish
begin
function __init__ self type_of_menu=STANDARD_MENU currency=string price=0 name=string temperature=NORMAL weigh=0 level_of_spicy... | from models.dish import Dish
from enums.type_of_menu import TypeOfMenu
from enums.temperature import Temperature
from enums.level_of_spicy import LevelOfSpicy
class Drinks(Dish):
def __init__(self, type_of_menu=TypeOfMenu.STANDARD_MENU, currency="", price=0, name="",
temperature=Temperature.NORM... | Python | zaydzuhri_stack_edu_python |
function filter_unique_peptides peptides score ns
begin
string Filters unique peptides from multiple Percolator output XML files. Takes a dir with a set of XMLs, a score to filter on and a namespace. Outputs an ElementTree.
set scores = dict string q string q_value ; string pep string pep ; string p string p_value ; st... | def filter_unique_peptides(peptides, score, ns):
""" Filters unique peptides from multiple Percolator output XML files.
Takes a dir with a set of XMLs, a score to filter on and a namespace.
Outputs an ElementTree.
"""
scores = {'q': 'q_value',
'pep': 'pep',
'p': '... | Python | jtatman_500k |
from dotenv import load_dotenv , find_dotenv
from src.home_made.data.Scrapper import Scrapper
from src.home_made.dictionary import Dictionary
from src.home_made.networks.networks import ChatBot
import pandas as pd
import getopt
import sys
from nltk.corpus import brown
import torch
import torch.nn as nn
import time
impo... | from dotenv import load_dotenv, find_dotenv
from src.home_made.data.Scrapper import Scrapper
from src.home_made.dictionary import Dictionary
from src.home_made.networks.networks import ChatBot
import pandas as pd
import getopt
import sys
from nltk.corpus import brown
import torch
import torch.nn as nn
import time
impor... | Python | zaydzuhri_stack_edu_python |
set num_one = integer input
set num_two = integer input
set num_three = integer input
print num_one < num_two < num_three | num_one = int(input())
num_two = int(input())
num_three = int(input())
print(num_one < num_two < num_three)
| Python | zaydzuhri_stack_edu_python |
comment singleton.py
class Singleton
begin
set __instance = none
decorator staticmethod
function get_instance
begin
if __instance == none
begin
call Singleton
end
return __instance
end function
function __init__ self
begin
if __instance != none
begin
raise exception string Class is singleton
end
else
begin
set __instan... | # singleton.py
class Singleton:
__instance = None
@staticmethod
def get_instance():
if Singleton.__instance == None:
Singleton()
return Singleton.__instance
def __init__(self):
if Singleton.__instance != None:
raise Exception("Class is singleton")
... | Python | zaydzuhri_stack_edu_python |
function test_analytics_endpoints_canonical_get self mock_resp resp_obj mock_dict
begin
set status_code = 200
set match = string 420aa27ce815499c85ec0301aff61ec4
set value = get state match
call assert_called_with string https://foo.uri/v1/analytics/match/420aa27ce815499c85ec0301aff61ec4/state params=dict string app_id... | def test_analytics_endpoints_canonical_get(self, mock_resp, resp_obj, mock_dict):
mock_resp.get.return_value.status_code = 200
match = "420aa27ce815499c85ec0301aff61ec4"
value = self.client.analytics.state.get(match)
mock_resp.get.assert_called_with(
'https://foo.uri/v1/an... | Python | nomic_cornstack_python_v1 |
string Built-in mite jinja filters.
import logging
import os
import pprint
from mite import color
function module_url root extension urls
begin
string Creates a url filter that gets the absolute url from a module-relative url. The urls set should contain the site-relative (final) urls. Example: {{ "some/path"|mymodule ... | """Built-in mite jinja filters."""
import logging
import os
import pprint
from mite import color
def module_url(root, extension, urls):
"""
Creates a url filter that gets the absolute url from a module-relative url.
The urls set should contain the site-relative (final) urls.
Example:
{{ "some/path"|mymodule }}... | Python | zaydzuhri_stack_edu_python |
function libvlc_media_duplicate p_md
begin
string Duplicate a media descriptor object. @param p_md: a media descriptor object.
set f = get _Cfunctions string libvlc_media_duplicate none or call _Cfunction string libvlc_media_duplicate tuple tuple 1 call class_result Media c_void_p Media
return f dist p_md
end function | def libvlc_media_duplicate(p_md):
'''Duplicate a media descriptor object.
@param p_md: a media descriptor object.
'''
f = _Cfunctions.get('libvlc_media_duplicate', None) or \
_Cfunction('libvlc_media_duplicate', ((1,),), class_result(Media),
ctypes.c_void_p, Media)
return... | Python | jtatman_500k |
from bisect import bisect_right
from PyQt5.QtCore import Qt , pyqtSignal
from PyQt5.QtWidgets import QTableWidget , QLabel , QHeaderView , QPushButton
from Internal.Util import makeTableWidgetItem
class GameTableWidget extends QTableWidget
begin
set playLocally = call pyqtSignal str
set hostGame = call pyqtSignal str
f... | from bisect import bisect_right
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtWidgets import QTableWidget, QLabel, QHeaderView, QPushButton
from Internal.Util import makeTableWidgetItem
class GameTableWidget(QTableWidget):
playLocally = pyqtSignal(str)
hostGame = pyqtSignal(str)
def __init__(sel... | Python | zaydzuhri_stack_edu_python |
function test_fma_invalid_param_str_intnum_intnum_none_1405 self
begin
comment This version is expected to pass.
call fma floatarrayx floatnumy floatnumz
comment This is the actual test.
with assert raises TypeError
begin
call fma strx intnumy intnumz
end
end function | def test_fma_invalid_param_str_intnum_intnum_none_1405(self):
# This version is expected to pass.
arrayfunc.fma(self.floatarrayx, self.floatnumy, self.floatnumz)
# This is the actual test.
with self.assertRaises(TypeError):
arrayfunc.fma(self.strx, self.intnumy, self.intnumz) | Python | nomic_cornstack_python_v1 |
function customwordcheck word
begin
set result = true
if length word >= 3 and length word <= 15
begin
set result = true
end
else
begin
return false
end
set word = lower word
for letter in word
begin
if letter not in string abcdefghijklmnopqrstuvwxyz
begin
return false
end
end
for else
begin
set result = true
end
return... | def customwordcheck(word):
result = True
if len(word) >= 3 and len(word) <= 15:
result = True
else:
return False
word = word.lower()
for letter in word:
if letter not in "abcdefghijklmnopqrstuvwxyz":
return False
else:
result = True
ret... | Python | nomic_cornstack_python_v1 |
from cardlib import *
import pytest
function test_cards
begin
string The test checks that the get_values function returns the correct value of the cards, that only integers between 2-10 can be entered for the numbered cards and that only correct suits can be entered at Suit.
set card_list_spades = list call AceCard Spa... | from cardlib import *
import pytest
def test_cards():
"""
The test checks that the get_values function returns the correct value of the cards, that only integers between 2-10
can be entered for the numbered cards and that only correct suits can be entered at Suit.
"""
card_list_spades = [AceCard(S... | Python | zaydzuhri_stack_edu_python |
function __call__ self *args **kwargs
begin
raise NotImplementedError
end function | def __call__(self, *args, **kwargs):
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
function is_on self
begin
comment type: ignore[no-any-return]
return get data string status == string enabled
end function | def is_on(self) -> bool:
return self.api.data.get("status") == "enabled" # type: ignore[no-any-return] | Python | nomic_cornstack_python_v1 |
import numpy as np
import tensorflow as tf
function merge images size
begin
if ndim == 4
begin
set tuple h w d = tuple shape at 1 shape at 2 shape at 3
set img = zeros tuple h * size at 0 w * size at 1 shape at 3
end
else
begin
set tuple h w = tuple shape at 1 shape at 2
set img = zeros tuple h * size at 0 w * size at ... | import numpy as np
import tensorflow as tf
def merge(images, size):
if images.ndim == 4:
h, w, d = images.shape[1], images.shape[2], images.shape[3]
img = np.zeros((h * size[0], w * size[1], images.shape[3]))
else:
h, w = images.shape[1], images.shape[2]
img = np.zeros((h * size... | Python | zaydzuhri_stack_edu_python |
function email self
begin
set billing_contact = user
return email
end function | def email(self):
billing_contact = self.owner.organization_user.user
return billing_contact.email | Python | nomic_cornstack_python_v1 |
from import dtw
import pandas
import numpy as np
class detector
begin
function __init__ self values predictions
begin
set values = values
set predictions = predictions
end function
function calculate_distances self comparision_window_size
begin
set comparision_window_size = comparision_window_size
set distances = call... | from . import dtw
import pandas
import numpy as np
class detector:
def __init__(self, values, predictions):
self.values = values
self.predictions = predictions
def calculate_distances(self, comparision_window_size):
self.comparision_window_size = comparision_window_size
... | Python | zaydzuhri_stack_edu_python |
function get_30_days_distance **kwargs
begin
set s = call Schema dict call Required string df DataFrame ; call Required string row_id int
try
begin
call s kwargs
set df = kwargs at string df
set n = 30
set row_id = kwargs at string row_id
set price = decimal call get_price_in_dollar df row_id
set average = call get_30_... | def get_30_days_distance(**kwargs):
s = Schema({
Required('df'): pd.DataFrame,
Required('row_id'): int
})
try:
s(kwargs)
df = kwargs['df']
n = 30
row_id = kwargs['row_id']
price = float(get_price_in_dollar(df, row_id))
average = get_... | Python | nomic_cornstack_python_v1 |
set s = string 10
set n = integer s 8
print n | s = '10'
n = int(s,8)
print(n) | Python | zaydzuhri_stack_edu_python |
import numpy as np
from random import shuffle
import operator
import csv
import cPickle as pickle
from collections import defaultdict
from sklearn.cross_validation import StratifiedKFold
set VOCABULARY_SIZE = 150000
function build_dataset train_filepath test_filepath
begin
set vocab = default dictionary int
set reader ... | import numpy as np
from random import shuffle
import operator
import csv
import cPickle as pickle
from collections import defaultdict
from sklearn.cross_validation import StratifiedKFold
VOCABULARY_SIZE=150000
def build_dataset(train_filepath,test_filepath):
vocab=defaultdict(int)
reader=csv.reader(open(trai... | Python | zaydzuhri_stack_edu_python |
string @author:Administrator @file:main.py @time:2020/05/09
import sys
from PyQt5.QtCore import QFileInfo
from PyQt5.QtWidgets import QApplication , QWidget , QMessageBox , QFileDialog
from PyQt5.QtGui import QIcon
comment main界面
from Win_Ui import Ui_Form
comment 爬虫
from Spider import SpiderPdd
comment 文本处理
import loa... | """
@author:Administrator
@file:main.py
@time:2020/05/09
"""
import sys
from PyQt5.QtCore import QFileInfo
from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox, QFileDialog
from PyQt5.QtGui import QIcon
from Win_Ui import Ui_Form # main界面
from Spider import SpiderPdd # 爬虫
import load_excel # 文本处理
impo... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
import argparse
function hello_base source output command
begin
with open output string w as out
begin
write out string === Source content:
with open source string r as s
begin
write out read s + string
end
write out string === is compiled by:
write out join string command
end
end functio... | #!/usr/bin/env python3
import argparse
def hello_base(source, output, command):
with open(output, 'w') as out:
out.write("=== Source content:\n")
with open(source, 'r') as s:
out.write(s.read() + '\n')
out.write("=== is compiled by:\n")
out.write(' '.join(command))
i... | Python | zaydzuhri_stack_edu_python |
import RPi.GPIO as GPIO
import time
call setmode BOARD
setup GPIO 11 IN pull_up_down=PUD_DOWN
setup GPIO 7 OUT
call output 7 0
set millisOn = 0
set millisOff = 0
set millis = 0
set userInput = list
set userChars = list
set userOutput = string
set temporalString = string
set morse = set literal set literal string A ... | import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(7, GPIO.OUT)
GPIO.output(7, 0)
millisOn = 0
millisOff = 0
millis = 0
userInput = []
userChars = []
userOutput = ""
temporalString = ""
morse = {{"A", ".-"},{"B", "-..."},{"C", "-.-."},{"D", "-.... | Python | zaydzuhri_stack_edu_python |
function check
begin
from funcwin import check_icon
from pyquickhelper.loghelper import check_log
call check_icon
call check_log
return true
end function | def check():
from .funcwin import check_icon
from pyquickhelper.loghelper import check_log
check_icon()
check_log()
return True | Python | nomic_cornstack_python_v1 |
import re
from stemming.porter2 import stem
from question_model import QuestionModel
class InformationalModel extends QuestionModel
begin
string A model matching questions asking for basic information. These questions are very simple and are asking for vague information about a concept. For example, "what is a vector?"... | import re
from stemming.porter2 import stem
from question_model import QuestionModel
class InformationalModel(QuestionModel):
"""A model matching questions asking for basic information.
These questions are very simple and are asking for vague information about
a concept. For example, "what is a vector?"... | Python | zaydzuhri_stack_edu_python |
import time
from threading import RLock
import sys
from collections import OrderedDict
class LRU extends OrderedDict
begin
function __init__ self max_len max_age_seconds
begin
assert max_age_seconds >= 0
assert max_len >= 1
call __init__ self
set max_len = max_len
set max_age = max_age_seconds
set lock = r lock
set _sa... | import time
from threading import RLock
import sys
from collections import OrderedDict
class LRU(OrderedDict):
def __init__(self, max_len, max_age_seconds):
assert max_age_seconds >= 0
assert max_len >= 1
OrderedDict.__init__(self)
self.max_len = max_len
self.max_ag... | Python | zaydzuhri_stack_edu_python |
import Read_file
import PARAMETER
import math
set all_train_document = all_train_document
function create_model
begin
set token_dict = dict
for tuple key value in items all_train_document
begin
set class_type = split key string - at 0
for term in value
begin
if term
begin
if term not in token_dict
begin
set token_dict... | import Read_file
import PARAMETER
import math
all_train_document = Read_file.all_train_document
def create_model():
token_dict = {}
for (key, value) in all_train_document.items():
class_type = key.split("-")[0]
for term in value:
if term:
if term not in token_dict:... | Python | zaydzuhri_stack_edu_python |
function read_snps snp_list
begin
set snps = read csv snp_list header=none names=list string chr string pos
return snps
end function | def read_snps(snp_list):
snps = pd.read_csv(snp_list, header=None, names=['chr', 'pos'])
return snps | Python | nomic_cornstack_python_v1 |
function setWidthLeft self val=string True **kwargs
begin
pass
end function | def setWidthLeft(self, val='True', **kwargs):
pass | Python | nomic_cornstack_python_v1 |
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
import cv2
import glob
import time
import pickle
from sklearn.svm import LinearSVC
from sklearn.preprocessing import StandardScaler
from skimage.feature import hog
from sklearn.model_selection import train_test_split
comment Loading + t... | import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
import cv2
import glob
import time
import pickle
from sklearn.svm import LinearSVC
from sklearn.preprocessing import StandardScaler
from skimage.feature import hog
from sklearn.model_selection import train_test_split
# Loading + train... | Python | zaydzuhri_stack_edu_python |
function run self
begin
set snippets = list
for filepath in call find_resources string *.javatar-snippet
begin
call add_action string javatar.core.snippets_loader_thread.analyse_snippet string Analyse snippet [file= + filepath + string ]
set snippet = call analyse_snippet filepath
if snippet
begin
call add_action stri... | def run(self):
snippets = []
for filepath in sublime.find_resources("*.javatar-snippet"):
ActionHistory().add_action(
"javatar.core.snippets_loader_thread.analyse_snippet",
"Analyse snippet [file=" + filepath + "]"
)
snippet = self.ana... | Python | nomic_cornstack_python_v1 |
function username_not_contains self username_not_contains
begin
set _username_not_contains = username_not_contains
end function | def username_not_contains(self, username_not_contains):
self._username_not_contains = username_not_contains | Python | nomic_cornstack_python_v1 |
import scipy as np
import matplotlib.pyplot as plt
from numpy.linalg import linalg as lin
from numpy import abs
class DSolve
begin
function __init__ self
begin
set boundaryCondition = list
set initialCondition = list
set h = 0.1
set DX = tuple - 10 10
end function
function setStep self h
begin
set h = h
end function
... | import scipy as np
import matplotlib.pyplot as plt
from numpy.linalg import linalg as lin
from numpy import abs
class DSolve:
def __init__(self):
self.boundaryCondition = []
self.initialCondition = []
self.h = 0.1
self.DX = (-10,10)
def setStep(self,h):
self.h = h
def Runge_Kutta(self,sys,i... | Python | zaydzuhri_stack_edu_python |
function convert_tokens_to_string self tokens
begin
set text = join string tokens
set text = decode bytearray list comprehension byte_decoder at c for c in text string utf-8 errors=string ignore
return text
end function | def convert_tokens_to_string(self, tokens):
text = "".join(tokens)
text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors="ignore")
return text | Python | nomic_cornstack_python_v1 |
function testDrawHMMCluster fileLocation limit=100 cColor=tuple 255 255 255
begin
set oData = call loadData fileLocation
set assignedData = list sData
for i in range length assignedData
begin
set v = length assignedData at i
if v > limit
begin
set v = limit
end
set ns = assignedData at i at slice 0 : v :
set tmp = lis... | def testDrawHMMCluster(fileLocation, limit = 100, cColor = (255, 255, 255)):
oData = dataio.loadData(fileLocation)
oData.assignedData = [oData.sData]
for i in range(len(oData.assignedData)):
v = len(oData.assignedData[i])
if v > limit:
v = limit
ns = oData.assignedData... | Python | nomic_cornstack_python_v1 |
function save_csv X y path
begin
string Save data as a CSV file. Args: X (numpy or scipy sparse matrix): Data matrix y (numpy array): Target vector. path (str): Path to the CSV file to save data.
if call issparse X
begin
set X = call todense
end
call savetxt path horizontal stack tuple reshape y tuple - 1 1 X delimiter... | def save_csv(X, y, path):
"""Save data as a CSV file.
Args:
X (numpy or scipy sparse matrix): Data matrix
y (numpy array): Target vector.
path (str): Path to the CSV file to save data.
"""
if sparse.issparse(X):
X = X.todense()
np.savetxt(path, np.hstack((y.reshape... | Python | jtatman_500k |
import math
for i in range 0 999
begin
for x in range 0 999
begin
if i + x < 1000
begin
set d = 1000 - x - i
if i < x and x < d
begin
set a = i ^ 2
set b = x ^ 2
set c = d ^ 2
if a + b == c
begin
set p = square root a * square root b * square root c
end
end
end
end
end | import math
for i in range (0,999):
for x in range (0,999):
if (i+x)<1000:
d=1000-x-i
if i<x and x<d:
a=i**2
b=x**2
c=d**2
if a+b==c:
p=math.sqrt(a) * math.sqrt(b)* math.sqrt(c) | Python | zaydzuhri_stack_edu_python |
function getFirstLabelmapNode
begin
set nodes = call GetNodesByClass string vtkMRMLLabelMapVolumeNode
call UnRegister nodes
if call GetNumberOfItems > 0
begin
return call GetItemAsObject 0
end
return none
end function | def getFirstLabelmapNode():
nodes = slicer.mrmlScene.GetNodesByClass("vtkMRMLLabelMapVolumeNode")
nodes.UnRegister(nodes)
if nodes.GetNumberOfItems() > 0:
return nodes.GetItemAsObject(0)
return None | Python | nomic_cornstack_python_v1 |
function preorder self root
begin
set res = list
if root
begin
append res data
set res = res + call preorder left
set res = res + call preorder right
end
return res
end function | def preorder(self,root)->list:
res=[]
if root:
res.append(root.data)
res=res+self.preorder(root.left)
res=res+self.preorder(root.right)
return res | Python | nomic_cornstack_python_v1 |
from bs4 import BeautifulSoup
import requests
import spotipy
from spotipy.oauth2 import SpotifyOAuth
comment website url
set URL = string https://www.billboard.com/charts/hot-100/
comment Spotify Authentication
set CLIENT_ID = string b6a721c6a21b46f9bc8a626e6ce1c5e7
set CLIENT_SECRET = string 6d46d4728d92451da5a284d339... | from bs4 import BeautifulSoup
import requests
import spotipy
from spotipy.oauth2 import SpotifyOAuth
#website url
URL = "https://www.billboard.com/charts/hot-100/"
#Spotify Authentication
CLIENT_ID ="b6a721c6a21b46f9bc8a626e6ce1c5e7"
CLIENT_SECRET="6d46d4728d92451da5a284d339768563"
REDIRECT_URL="http://example.com"
... | Python | zaydzuhri_stack_edu_python |
while i < length a
begin
if a at i == user
begin
print b at i
end
set i = i + 1
end
comment if user will give q op- [1,2,3,4]
comment if usr will give r op-
list 9 10 11 12 | while i<len(a):
if a[i]==user:
print(b[i])
i=i+1
# if user will give q op- [1,2,3,4]
# if usr will give r op-
[9,10,11,12] | Python | zaydzuhri_stack_edu_python |
function _apply_descrambler stream_data key
begin
if key == string url_encoded_fmt_stream_map and not get stream_data string url_encoded_fmt_stream_map
begin
set formats = loads stream_data at string player_response at string streamingData at string formats
extend formats loads stream_data at string player_response at ... | def _apply_descrambler(stream_data, key):
if key == "url_encoded_fmt_stream_map" and not stream_data.get(
"url_encoded_fmt_stream_map"
):
formats = json.loads(stream_data["player_response"])["streamingData"]["formats"]
formats.extend(
json.loads(stream_data["player_response"]... | Python | nomic_cornstack_python_v1 |
import OpenGL
import random
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
from transformation import *
set is2D = false
set is3D = false
set window_name = string cartesian
set currentCommand = string
set moveX = 0.1
set moveY = 0.1
set moveZ = 0.1
set eyeX = 0
set eyeY = 0
set eyeZ = 0
set... | import OpenGL
import random
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
from transformation import *
is2D = False
is3D = False
window_name = 'cartesian'
currentCommand = ""
moveX = 0.1
moveY = 0.1
moveZ = 0.1
eyeX = 0
eyeY = 0
eyeZ = 0
isEnd = False
q = []
verticies3d = Matriks([
([... | 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.