code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function __repr__ self
begin
return string <Cat id= { cat_id } name= { name }
end function | def __repr__(self):
return f"<Cat id={self.cat_id} name={self.name}" | Python | nomic_cornstack_python_v1 |
function after_deliver analysis_request
begin
call reindexObject idxs=list string getDateReceived
end function | def after_deliver(analysis_request):
analysis_request.reindexObject(idxs=["getDateReceived", ]) | Python | nomic_cornstack_python_v1 |
from flask import Flask , render_template , redirect , request
from flask_mail import Mail , Message
set app = call Flask __name__
set mail_settings = dict string MAIL_SERVER string smtp.gmail.com ; string MAIL_PORT 465 ; string MAIL_USE_TLS false ; string MAIL_USE_SSL true ; string MAIL_USERNAME string contato.port21@... | from flask import Flask, render_template, redirect, request
from flask_mail import Mail, Message
app = Flask(__name__)
mail_settings = {
"MAIL_SERVER": 'smtp.gmail.com',
"MAIL_PORT": 465,
"MAIL_USE_TLS": False,
"MAIL_USE_SSL": True,
"MAIL_USERNAME": 'contato.port21@gmail.com',
"MAIL_PASSWORD"... | Python | zaydzuhri_stack_edu_python |
function compute_ap recall precision
begin
comment recall和precision两边填两个值
set mrec = concatenate tuple list 0.0 recall list 1.0
set mpre = concatenate tuple list 0.0 precision list 0.0
comment 精确率的值从后往前循环
comment 循环下来除了最开始的值以外,后面的值都是从高到低的形成阶梯下降
for i in range size - 1 0 - 1
begin
comment 留下大的值
set mpre at i - 1 = call ... | def compute_ap(recall, precision):
# recall和precision两边填两个值
mrec = np.concatenate(([0.], recall, [1.]))
mpre = np.concatenate(([0.], precision, [0.]))
# 精确率的值从后往前循环
# 循环下来除了最开始的值以外,后面的值都是从高到低的形成阶梯下降
for i in range(mpre.size - 1, 0, -1):
# 留下大的值
mpre[i - 1] = np.maximum(mpre[i - ... | Python | nomic_cornstack_python_v1 |
function get_query_specs self *args **keyword_args
begin
set sandbox_query_dict = dict QUERY call render project=project_id sandbox_dataset=sandbox_dataset_id sandbox_table=call sandbox_table_for OBSERVATION dataset=dataset_id
set update_query_dict = dict QUERY call render project=project_id sandbox_dataset=sandbox_dat... | def get_query_specs(self, *args, **keyword_args) -> query_spec_list:
sandbox_query_dict = {
cdr_consts.QUERY:
SANDBOX_FIX_UNMAPPED_SURVEY_ANSWERS_QUERY.render(
project=self.project_id,
sandbox_dataset=self.sandbox_dataset_id,
... | Python | nomic_cornstack_python_v1 |
function main
begin
set text = string See you at Garage Trip 2.0!
set ascii_codes = generator expression ordinal i for i in text
set shift = - 42
set shifted = generator expression i + shift for i in ascii_codes
set hexed = generator expression replace hexadecimal i string 0x string for i in shifted
print join string ... | def main():
text = "See you at Garage Trip 2.0!"
ascii_codes = (ord(i) for i in text)
shift = -42
shifted = (i + shift for i in ascii_codes)
hexed = (hex(i).replace("0x", "") for i in shifted)
print(' '.join(hexed))
if __name__ == '__main__':
main()
| Python | zaydzuhri_stack_edu_python |
function map_amoi self variant status=none outside=false
begin
if not _quiet
begin
write stderr format string status: {}; outside: {} status outside
end
comment Make sure the input data is correctly formatted and complete
call __validate_variant_dict variant
set result = string
if variant at string type == string snvs... | def map_amoi(self, variant, status=None, outside=False):
if not self._quiet:
sys.stderr.write('status: {}; outside: {}\n'.format(status, outside))
# Make sure the input data is correctly formatted and complete
self.__validate_variant_dict(variant)
result = ''
if var... | Python | nomic_cornstack_python_v1 |
comment contains the forms used in the app
from wtforms import Form , StringField , validators
class PlacSettingsForm extends Form
begin
set ip_addr_regex = string ^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4... | # contains the forms used in the app
from wtforms import Form, StringField, validators
class PlacSettingsForm(Form):
ip_addr_regex = '^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9... | Python | zaydzuhri_stack_edu_python |
function ActiveHlt2Lines self
begin
set lines = list string Hlt2B2HH string Hlt2B2PiPi string Hlt2B2KPi string Hlt2B2KK string Hlt2Lb2PK string Hlt2Lb2PPi
return lines
end function | def ActiveHlt2Lines(self) :
lines = [
'Hlt2B2HH',
'Hlt2B2PiPi',
'Hlt2B2KPi',
'Hlt2B2KK',
'Hlt2Lb2PK',
'Hlt2Lb2PPi'
]
return lines | Python | nomic_cornstack_python_v1 |
import requests
import json
import time
set yucom_uri = string http://yucomtrack.co.id/track-api/unit/read.php?po=qlue
set traccar_uri = string http://traccar.qlue.id:5055
set device_id = 313484
set delay = 5
function getData
begin
try
begin
set r = get requests url=yucom_uri timeout=5
end
except Timeout
begin
print st... | import requests
import json
import time
yucom_uri = 'http://yucomtrack.co.id/track-api/unit/read.php?po=qlue'
traccar_uri = 'http://traccar.qlue.id:5055'
device_id = 313484
delay = 5
def getData():
try:
r = requests.get(url = yucom_uri,timeout=5)
except requests.exceptions.Timeout:
print('timeout error')
r... | Python | zaydzuhri_stack_edu_python |
function task1 text
begin
set result = string
set in_garbage = false
set need_ignore = false
set group_level = 0
set counter = 0
for i in range length text
begin
set actual_char = text at i
if in_garbage and actual_char != garbage_end and not need_ignore and actual_char != ignore
begin
set result = result + actual_cha... | def task1(text):
result = ""
in_garbage = False
need_ignore = False
group_level = 0
counter = 0
for i in range(len(text)):
actual_char = text[i]
if in_garbage and actual_char != garbage_end and not need_ignore and actual_char != ignore:
result = result + actual_ch... | Python | zaydzuhri_stack_edu_python |
import serial
import serial.tools.list_ports
comment Configurations used for serial communication with Nucleo. #
set BAUDRATE = 9600
comment Packet configs.
set BYTESIZE = EIGHTBITS
set PARITY = PARITY_NONE
set STOPBITS = STOPBITS_ONE
comment Helper functions. #
function add_config serial
begin
string Configures the gi... | import serial
import serial.tools.list_ports
#############################################################
# Configurations used for serial communication with Nucleo. #
#############################################################
BAUDRATE = 9600
# Packet configs.
BYTESIZE = serial.EIGHTBITS
PARITY = serial.PARITY_N... | Python | zaydzuhri_stack_edu_python |
set t = tuple 1 2 3 4
set tuple x y z a = t
print string your list t
print x
print y
print z
print a | t=(1,2,3,4)
x,y,z,a=t
print('your list',t)
print(x)
print(y)
print(z)
print(a)
| Python | zaydzuhri_stack_edu_python |
string P-121 - Best Time to Buy and Sell Stock Say you have an array for which theithelement is the price of a given stock on dayi. If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. Tags: Array, Dynamic Programmi... | '''
P-121 - Best Time to Buy and Sell Stock
Say you have an array for which theithelement is the price of a given
stock on dayi. If you were only permitted to complete at most one
transaction (ie, buy one and sell one share of the stock), design an
algorithm to find the maximum profit.
Tags: Array, Dynamic Programmin... | Python | zaydzuhri_stack_edu_python |
import time as t
import RPi.GPIO as rp
import smtplib as s
call setmode BOARD
call setwarnings false
set l = list 11 13 21 31 33 35 37
function distance
begin
call output 21 1
sleep 0.001
call output 21 0
while input 19 == 0
begin
pass
end
set st = time
while input 19 == 1
begin
pass
end
set stopt = time
set tt = stopt... | import time as t
import RPi.GPIO as rp
import smtplib as s
rp.setmode(rp.BOARD)
rp.setwarnings(False)
l=[11,13,21,31,33,35,37]
def distance():
rp.output(21,1)
t.sleep(0.001)
rp.output(21,0)
while(rp.input(19)==0):
pass
st=t.time()
while(rp.input(19)==1):
pass
stopt=t... | Python | zaydzuhri_stack_edu_python |
function search_by_product self **query
begin
for tuple product datasets in call _do_search_by_product query
begin
yield tuple product call _make_many datasets product
end
end function | def search_by_product(self, **query):
for product, datasets in self._do_search_by_product(query):
yield product, self._make_many(datasets, product) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
import json
from flask import jsonify
from util.common_module import print_stdout
function get_request_param req
begin
if method == string GET
begin
set result = args
end
else
begin
set result = json
end
call print_stdout string ---------------START------------... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from flask import jsonify
from util.common_module import print_stdout
def get_request_param(req):
if req.method == "GET":
result = req.args
else:
result = req.json
print_stdout("---------------START---------------")
... | Python | zaydzuhri_stack_edu_python |
function is_armstrong_number n
begin
set num_str = string n
set num_digits = length num_str
set sum_cubes = 0
for i in range num_digits
begin
set digit = integer num_str at i
set sum_cubes = sum_cubes + digit ^ num_digits
end
if sum_cubes == n
begin
return true
end
else
begin
return false
end
end function | def is_armstrong_number(n):
num_str = str(n)
num_digits = len(num_str)
sum_cubes = 0
for i in range(num_digits):
digit = int(num_str[i])
sum_cubes += digit**num_digits
if sum_cubes == n:
return True
else:
return False
| Python | jtatman_500k |
comment Python 2.7
comment Original author: Nicole JS Gaynor (nschiff2 [at] illinois [dot] edu)
comment Created for: Illinois State Water Survey
comment Date: February 2016
comment This program takes data from the HEC-RAS model and compares the max stage and hourly stage to the bank station
comment elevations to determ... | # Python 2.7
# Original author: Nicole JS Gaynor (nschiff2 [at] illinois [dot] edu)
# Created for: Illinois State Water Survey
# Date: February 2016
# This program takes data from the HEC-RAS model and compares the max stage and hourly stage to the bank station
# elevations to determine how far out of banks the water ... | Python | zaydzuhri_stack_edu_python |
function test_find_bridges_04 self json_mock poll_mock xml_mock
begin
set known_bridges = list string deadbeef string 0017884e7dad
set found_bridges = call find_bridges known_bridges
assert is instance found_bridges dict
assert equal length found_bridges 1
assert in string 0017884e7dad found_bridges
assert equal length... | def test_find_bridges_04(self, json_mock, poll_mock, xml_mock):
known_bridges = ['deadbeef', '0017884e7dad']
found_bridges = find_bridges(known_bridges)
self.assertIsInstance(found_bridges, dict)
self.assertEqual(len(found_bridges), 1)
self.assertIn('0017884e7dad', found_bridges)... | Python | nomic_cornstack_python_v1 |
function newEpisode self
begin
set explmatrix = call normal 0.0 call expln sigma shape
end function | def newEpisode(self):
self.explmatrix = random.normal(0., expln(self.sigma), self.explmatrix.shape) | Python | nomic_cornstack_python_v1 |
function parse_args
begin
if __name__ == string __main__
begin
set parser = call ArgumentParser description=string Do the thing!
call add_argument string json help=string Specify the path to an actions.json file to ingest. action=string store
set args = call parse_args
set path_json = json
return path_json
end
end func... | def parse_args():
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="""Do the thing!""")
parser.add_argument('json', help="Specify the path to an actions.json file to ingest.",
action="store")
args = parser.parse_args()
path_json = a... | Python | nomic_cornstack_python_v1 |
for a in range n
begin
set num = integer input
if num == 0
begin
del allNums at - 1
end
else
begin
append allNums num
end
end
print sum allNums | for a in range(n):
num = int(input())
if (num == 0):
del allNums[-1]
else:
allNums.append(num)
print(sum(allNums)) | Python | zaydzuhri_stack_edu_python |
function _Clamp n low high
begin
return min high max low n
end function | def _Clamp(n, low, high):
return min(high, max(low, n)) | Python | nomic_cornstack_python_v1 |
function stepen a n
begin
return a ^ n
end function
set a = integer input
set b = integer input
print call stepen a b | def stepen(a,n):
return a**n
a=int(input())
b=int(input())
print(stepen(a,b)) | Python | zaydzuhri_stack_edu_python |
function hz_to_midi self
begin
return call _compute_unary_op self HZ_TO_MIDI
end function | def hz_to_midi(self) -> "UGenMethodMixin":
return self._compute_unary_op(self, UnaryOperator.HZ_TO_MIDI) | Python | nomic_cornstack_python_v1 |
comment no need to define the data type for a variables
comment Indentation is important, wrong indent may lead to error
comment It has inbuilt naming conventions/rules or standards (A-Z, a-z, 0-9)
comment Single value can be assigned to multiple variables
comment we can use comma separator to print multiple value in s... | # no need to define the data type for a variables
# Indentation is important, wrong indent may lead to error
# It has inbuilt naming conventions/rules or standards (A-Z, a-z, 0-9)
# Single value can be assigned to multiple variables
# we can use comma separator to print multiple value in single print statement
# existi... | Python | zaydzuhri_stack_edu_python |
import pygame , sys , math , random
call init
set WINDOWSIZE = tuple 1000 600
set tuple WINDOWWIDTH WINDOWHEIGHT = tuple 1000 600
set SCREEN = call set_mode WINDOWSIZE
call set_caption string Aim Pong
set comicSansMs = call SysFont string comicsansms 45
comment Constantes de coleur
set BLACK = tuple 0 0 0
set BLUE = tu... | import pygame, sys, math, random
pygame.init()
WINDOWSIZE = WINDOWWIDTH, WINDOWHEIGHT = 1000, 600
SCREEN = pygame.display.set_mode(WINDOWSIZE)
pygame.display.set_caption("Aim Pong")
comicSansMs = pygame.font.SysFont("comicsansms", 45)
#Constantes de coleur
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
WHITE = (255,... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import numpy as np
import torch
from PIL import Image
from scipy.misc import imread , imsave , imresize
import os
import numpy as np
from torchvision import transforms
comment For custom datasets
from torch.utils.data.dataset import Dataset
class PetsVectorDataset extends Dataset
begin
function __in... | import pandas as pd
import numpy as np
import torch
from PIL import Image
from scipy.misc import imread, imsave, imresize
import os
import numpy as np
from torchvision import transforms
from torch.utils.data.dataset import Dataset # For custom datasets
class PetsVectorDataset(Dataset):
def __init__(self, train_... | Python | zaydzuhri_stack_edu_python |
comment nhap vao ho ten day du
print string My fullname is:
set name = input
comment in ra man hinh cau chao Xin--chao!--Toi--ten--la--{ten nhap vao}
print string Xin string chao! string Toi string ten string la string name sep=string -- | #nhap vao ho ten day du
print("My fullname is:")
name=input()
#in ra man hinh cau chao Xin--chao!--Toi--ten--la--{ten nhap vao}
print("Xin","chao!","Toi","ten","la",str(name),sep="--") | Python | zaydzuhri_stack_edu_python |
comment create a set of elements in list1
set s1 = set list1
comment create a set of elements in list2
set s2 = set list2
comment find the intersection
set intersection = intersection s1 s2
comment print the intersection
print intersection
comment prints {3, 4} | # create a set of elements in list1
s1 = set(list1)
# create a set of elements in list2
s2 = set(list2)
# find the intersection
intersection = s1.intersection(s2)
# print the intersection
print(intersection)
# prints {3, 4} | Python | jtatman_500k |
string Design a HashSet without using any built-in hash table libraries. Implement MyHashSet class: void add(key) Inserts the value key into the HashSet. bool contains(key) Returns whether the value key exists in the HashSet or not. void remove(key) Removes the value key in the HashSet. If key does not exist in the Has... | '''
Design a HashSet without using any built-in hash table libraries.
Implement MyHashSet class:
void add(key) Inserts the value key into the HashSet.
bool contains(key) Returns whether the value key exists in the HashSet or not.
void remove(key) Removes the value key in the HashSet. If key does not exist in the Hash... | Python | zaydzuhri_stack_edu_python |
function _create_user cls auth_ids **user_values
begin
if not is instance auth_ids list
begin
set auth_ids = list auth_ids
end
set user_values at string auth_ids = auth_ids
for auth_id in user_values at string auth_ids
begin
if call get_by_auth_id auth_id
begin
raise call DuplicatePropertyError value=list string auth_i... | def _create_user(cls, auth_ids, **user_values):
if not isinstance(auth_ids, list):
auth_ids = [auth_ids]
user_values['auth_ids'] = auth_ids
for auth_id in user_values['auth_ids']:
if cls.get_by_auth_id(auth_id):
raise DuplicatePropertyError(value=['auth_i... | Python | nomic_cornstack_python_v1 |
import os
comment 1. 해당 파일들이 있는 위치로 이동
change directory string C:\Users\student\Desktop\TIL\00_startcamp\02_day\change_filenames
comment 2. 현재 폴더 안에 모든 파일 이름을 수집
set filenames = list directory string .
comment 3. 각각의 파일명을 돌면서 수정한다.
for filename in filenames
begin
rename filename string SAMSUNG_ { filename }
end | import os
# 1. 해당 파일들이 있는 위치로 이동
os.chdir(r'C:\Users\student\Desktop\TIL\00_startcamp\02_day\change_filenames')
# 2. 현재 폴더 안에 모든 파일 이름을 수집
filenames = os.listdir('.')
# 3. 각각의 파일명을 돌면서 수정한다.
for filename in filenames:
os.rename(filename, f'SAMSUNG_{filename}') | Python | zaydzuhri_stack_edu_python |
function collectSignatures values arr
begin
set tempArr = arr
set coordinate = list
while length tempArr != 0
begin
set comparingValue = tempArr at 0
set capturedNum = none
remove tempArr comparingValue
for i in range integer comparingValue at 1 integer comparingValue at 0 - 1 - 1
begin
for ranges in tempArr
begin
if ... | def collectSignatures(values, arr):
tempArr = arr
coordinate = []
while len(tempArr) != 0:
comparingValue = tempArr[0]
capturedNum = None
tempArr.remove(comparingValue)
for i in range(int(comparingValue[1]), int(comparingValue[0])-1, -1):
for ranges in tempAr... | Python | zaydzuhri_stack_edu_python |
import turtle as tr
call shape string turtle
function flower n
begin
for i in range 1 n + 1 1
begin
call circle 50
call left 360 / n
end
end function
call flower 6 | import turtle as tr
tr.shape('turtle')
def flower(n):
for i in range(1,n+1,1):
tr.circle(50)
tr.left(360/n)
flower(6)
| Python | zaydzuhri_stack_edu_python |
import urllib.request
import urllib.parse
from bs4 import BeautifulSoup
set plusUrl = call quote_plus input string 검색어를 입력하세요:
set pageNum = 1
set count = 1
set page = input string 크롤링할 페이지를 입력하세요:
print
set lastPage = integer page * 10 - 9
while pageNum < lastPage + 1
begin
set url = string https://search.naver.com/se... | import urllib.request
import urllib.parse
from bs4 import BeautifulSoup
plusUrl = urllib.parse.quote_plus(input('검색어를 입력하세요: '))
pageNum = 1
count = 1
page = input("크롤링할 페이지를 입력하세요: ")
print()
lastPage = int(page) * 10 - 9
while pageNum < lastPage + 1:
url = f'https://search.naver.com/search.naver?date_from=&date... | Python | zaydzuhri_stack_edu_python |
function multiply x n
begin
if n == 0
begin
return 1
end
else
begin
return x * call multiply x n - 1
end
end function
set x = 4
set n = 3
set result = call multiply x n
print result | def multiply(x, n):
if n == 0:
return 1
else:
return x * multiply(x, n-1)
x = 4
n = 3
result = multiply(x, n)
print(result)
| Python | jtatman_500k |
function description self
begin
return get pulumi self string description
end function | def description(self) -> pulumi.Output[Optional[str]]:
return pulumi.get(self, "description") | Python | nomic_cornstack_python_v1 |
comment 2021/1/11 弃用
comment 图片下载模块
comment 图片下载到“下载”文件夹,按照数字顺序重命名
from selenium import webdriver
from time import sleep
from selenium.webdriver import ActionChains
from TOOLS.mongosave import MongoDB
import os
from pykeyboard import *
from pymouse import *
comment 固定代码
set k = call PyKeyboard
set m = call PyMouse
set ... | #2021/1/11 弃用
# 图片下载模块
#图片下载到“下载”文件夹,按照数字顺序重命名
from selenium import webdriver
from time import sleep
from selenium.webdriver import ActionChains
from TOOLS.mongosave import MongoDB
import os
from pykeyboard import *
from pymouse import *
###固定代码
k = PyKeyboard()
m = PyMouse()
db = MongoDB('mongodb://localhost', 'c... | Python | zaydzuhri_stack_edu_python |
function getOrder self
begin
return order
end function | def getOrder(self):
return self.order | Python | nomic_cornstack_python_v1 |
class CountLogger extends object
begin
function __init__ self logger countable
begin
set _logger = logger
set _total = length countable
set _count = 0
set _width = length string _total
end function
function count_string self msg=none
begin
return format string {count:0{width}d}/{total} {msg} count=_count width=_width t... | class CountLogger(object):
def __init__(self, logger, countable):
self._logger = logger
self._total = len(countable)
self._count = 0
self._width = len(str(self._total))
def count_string(self, msg=None):
return u'{count:0{width}d}/{total} {msg}'.format(
cou... | Python | zaydzuhri_stack_edu_python |
function is_fully_connected self
begin
if _protocol is none
begin
return false
end
return call is_fully_connected
end function | def is_fully_connected(self) -> bool:
if self._protocol is None:
return False
return self._protocol.is_fully_connected() | Python | nomic_cornstack_python_v1 |
function search self prefix tolerance=2 tree=none root=none matches=none
begin
comment TODO: Number of arguments can be reduced by defining BKTree
comment recursively (i.e. root and tree args shouldn't be necessary).
if root is none
begin
set root = root
end
if tree is none
begin
set tree = tree at root
end
if matches ... | def search(self, prefix, tolerance=2, tree=None, root=None, matches=None):
# TODO: Number of arguments can be reduced by defining BKTree
# recursively (i.e. root and tree args shouldn't be necessary).
if root is None:
root = self.root
if tree is None:
tree = self.... | Python | nomic_cornstack_python_v1 |
import numpy as np
from fractions import Fraction
function find_tangent_angles
begin
comment Initialize list for storing valid angles
set valid_angles = list
comment Loop through possible k values
comment k = 0, 1, 2, 3
for k in range 4
begin
set x = k + 0.5 * pi / 4
comment Add valid angles to the list
append valid_a... | import numpy as np
from fractions import Fraction
def find_tangent_angles():
# Initialize list for storing valid angles
valid_angles = []
# Loop through possible k values
for k in range(4): # k = 0, 1, 2, 3
x = ((k + 0.5) * np.pi) / 4
# Add valid angles to the list
... | Python | dbands_pythonMath |
string keras_to_tfl.py converts a keras model into tensorflow lite format, and also optimizes the model to have a smaller memory footprint and lower latency. see: https://www.tensorflow.org/lite/performance/model_optimization
comment Standard Library imports:
import argparse
from pathlib import Path
comment 3rd Party i... | """
keras_to_tfl.py converts a keras model into tensorflow lite format, and also optimizes the model
to have a smaller memory footprint and lower latency.
see: https://www.tensorflow.org/lite/performance/model_optimization
"""
# Standard Library imports:
import argparse
from pathlib import Path
# 3rd Party imports:
... | Python | zaydzuhri_stack_edu_python |
function step self closure=none
begin
set loss = none
if closure is not none
begin
set loss = call closure
end
for group in param_groups
begin
for p in group at string params
begin
if grad is none
begin
continue
end
set grad = data
if is_sparse
begin
raise call RuntimeError string Adam does not support sparse gradients... | def step(self, closure=None):
loss = None
if closure is not None:
loss = closure()
for group in self.param_groups:
for p in group["params"]:
if p.grad is None:
continue
grad = p.grad.data
if grad.is_spar... | Python | nomic_cornstack_python_v1 |
function split_data self
begin
set tuple train val test_x test_y = tuple list list list list
set train_size = horizon
comment This assumes all countries have the same length.
comment The minus two gives space for the validation and test sets as they will overshoot.
set k_folds = length data // horizon - 2
for _ in ... | def split_data(self):
self.train, self.val, self.test_x, self.test_y = [], [], [], []
train_size = self.horizon
# This assumes all countries have the same length.
# The minus two gives space for the validation and test sets as they will overshoot.
k_folds = len(self.countries[0].... | Python | nomic_cornstack_python_v1 |
function test_connected_app_client_credentials_login_success self
begin
set login_args = dict string consumer_key string 12345.abcde ; string consumer_secret string 12345.abcde ; string domain split hostname string .salesforce.com at 0
call _test_login_success compile string ^ { INSTANCE_URL } /.*$ login_args response_... | def test_connected_app_client_credentials_login_success(self):
login_args = {
'consumer_key': '12345.abcde',
'consumer_secret': '12345.abcde',
'domain': urlparse(tests.INSTANCE_URL).hostname.split(
'.salesforce.com')[0],
}
self._test_login_... | Python | nomic_cornstack_python_v1 |
function detail_rec array level first_stage=DEFAULT_FIRST_STAGE wavelet=DEFAULT_CMP_WAV axis=- 1
begin
set coeffs = call dualtree data=array first_stage=first_stage wavelet=wavelet level=level mode=DEFAULT_MODE axis=axis
set app_coeffs = zeros like coeffs at 0 dtype=complex
set reconstructed = call idualtree coeffs=lis... | def detail_rec(array, level, first_stage = DEFAULT_FIRST_STAGE, wavelet = DEFAULT_CMP_WAV, axis = -1):
coeffs = dualtree(data = array, first_stage = first_stage, wavelet = wavelet, level = level, mode = DEFAULT_MODE, axis = axis)
app_coeffs = n.zeros_like(coeffs[0], dtype = n.complex)
reconstructed = idual... | Python | nomic_cornstack_python_v1 |
class Solution extends object
begin
function lengthOfLongestSubstring self s
begin
set i = 0
set j = 0
set ans = 0
set length = length s
set hash_map = dictionary
while j < length
begin
if call has_key s at j
begin
set i = max i hash_map at s at j
end
set ans = max ans j - i + 1
set hash_map at s at j = j + 1
set j = j... | class Solution(object):
def lengthOfLongestSubstring(self, s):
i=0
j=0
ans=0
length = len(s)
hash_map = dict()
while j<length:
if hash_map.has_key(s[j]):
i = max(i,hash_map[s[j]])
ans = max(ans,j-i+1)
hash_map[s[j]]=j+1
j+=1
return ans
if __name__ == "__main__":
s = "abcaefghijklmnopq"
... | Python | zaydzuhri_stack_edu_python |
function calc_netSuns self
begin
if aMode == string GEN
begin
set netSuns = raw at string ref / refCal - e * W * dndt / jsc
end
else
if aMode == string QSS
begin
set netSuns = raw at string ref / refCal
end
return netSuns
end function | def calc_netSuns(self):
if self.aMode == "GEN":
netSuns = self.raw['ref'] / self.refCal - C.e * self.W * self.dndt / self.jsc
elif self.aMode == "QSS":
netSuns = self.raw['ref'] / self.refCal
return netSuns | Python | nomic_cornstack_python_v1 |
comment Este é o codigo completo criado para rodar o jogo de Bacará
comment As 9 primeiras linhas mostram algumas definições de bibliotecas e classes que usamos para aperfeiçoar tanto a performance quanto a estética do código
class cor
begin
set vermelho = string [91m
set azul = string [94m
set verde = string [92m
s... | #Este é o codigo completo criado para rodar o jogo de Bacará
#As 9 primeiras linhas mostram algumas definições de bibliotecas e classes que usamos para aperfeiçoar tanto a performance quanto a estética do código
class cor:
vermelho="\033[91m"
azul="\033[94m"
verde="\033[92m"
negrito="\033[1m"
... | Python | zaydzuhri_stack_edu_python |
function find_node self address
begin
if is instance address str
begin
set addr_arr = split address __sep
end
else
begin
set addr_arr = list address
end
return call __find_node addr_arr __root 0
end function | def find_node(self, address):
if isinstance(address, str):
addr_arr = address.split(self.__sep)
else:
addr_arr = list(address)
return self.__find_node(addr_arr, self.__root, 0) | Python | nomic_cornstack_python_v1 |
function test_01_create self namespace=none name=none contact_user=none
begin
call direct_login_user_1
set data = dict
if namespace
begin
set data at string namespace = namespace
end
if name
begin
set data at string name = name
end
if contact_user
begin
set data at string contact_user = contact_user
end
set new_applic... | def test_01_create(self, namespace=None, name=None, contact_user=None):
self.direct_login_user_1()
data = {}
if namespace:
data['namespace'] = namespace
if name:
data['name'] = name
if contact_user:
data['contact_user'] = contact_user
... | Python | nomic_cornstack_python_v1 |
comment _*_ coding:utf-8 _*_
import sys
from time import sleep
import demo
class Init
begin
function getBrowser self
begin
set browser = driver
return browser
end function
end class
class help
begin
function addCookie self name value
begin
call add_cookie dict string name name ; string value value
sleep 1
end function
... | # _*_ coding:utf-8 _*_
import sys
from time import sleep
import demo
class Init():
def getBrowser(self):
browser = demo.driver
return browser
class help():
def addCookie(self, name, value):
Init().getBrowser().add_cookie({'name': name, 'value': value})
sleep(1)
def get... | Python | zaydzuhri_stack_edu_python |
function get_custom_dmx self
begin
if string custom-dmx in keys config at string dmx
begin
return config at string dmx at string custom-dmx
end
return none
end function | def get_custom_dmx(self):
if "custom-dmx" in self.config["dmx"].keys():
return self.config["dmx"]["custom-dmx"]
return None | Python | nomic_cornstack_python_v1 |
import plotly.graph_objects as go
comment Create figure
set fig = figure
comment Add trace
call add_trace scatter go x=list 0 0.5 1 2 2.2 y=list 1.23 2.5 0.42 3 1
comment Add images
call update_layout images=list call Image source=string https://images.plot.ly/language-icons/api-home/python-logo.png xref=string x yref=... | import plotly.graph_objects as go
# Create figure
fig = go.Figure()
# Add trace
fig.add_trace(
go.Scatter(x=[0, 0.5, 1, 2, 2.2], y=[1.23, 2.5, 0.42, 3, 1])
)
# Add images
fig.update_layout(
images=[
go.layout.Image(
source="https://images.plot.ly/language-icons/api-home/python-logo.png",
... | Python | zaydzuhri_stack_edu_python |
function logout self
begin
set logged_in = false
set first_name = none
set last_name = none
set token = none
return true
end function | def logout(self):
self.logged_in = False
self.first_name = None
self.last_name = None
self.token = None
return True | Python | nomic_cornstack_python_v1 |
comment get guestlist , input list, print the guest list
import csv
set filename = string guestlist.csv
set read = string r
set write = string w
set accessmode = string r+
comment input guest name from user
set guestname = list
set guestage = list
set name = string
set age = integer 10000
while upper name != string ... | #get guestlist , input list, print the guest list
import csv
filename="guestlist.csv"
read="r"
write="w"
accessmode="r+"
#input guest name from user
guestname=[]
guestage=[]
name=""
age=int(10000)
while name.upper() != "DONE":
name=input("pleases enter name of the guest(once completed enter name of ... | Python | zaydzuhri_stack_edu_python |
comment @lc app=leetcode.cn id=134 lang=python
comment [134] 加油站
comment @lc code=start
class Solution extends object
begin
function canCompleteCircuit self gas cost
begin
string :type gas: List[int] :type cost: List[int] :rtype: int
set cur = 0
set total = 0
set start = 0
for i in range length gas
begin
set cur = cur ... | #
# @lc app=leetcode.cn id=134 lang=python
#
# [134] 加油站
#
# @lc code=start
class Solution(object):
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
cur = 0
total = 0
start = 0
for i in ra... | Python | zaydzuhri_stack_edu_python |
class Tile
begin
function __init__ self data
begin
set data = split data
set id = integer data at 1 at slice : - 1 :
set data = list comprehension list line for line in data at slice 2 : :
set size = length data
set borders = call get_borders
set calibrated = false
end function
function rotate self
begin
for x in ra... | class Tile:
def __init__(self, data):
data = data.split()
self.id = int(data[1][:-1])
self.data = [list(line) for line in data[2:]]
self.size = len(self.data)
self.borders = self.get_borders()
self.calibrated = False
def rotate(self):
for x in range(self.size // 2):
for y in range(x, se... | Python | zaydzuhri_stack_edu_python |
class tabuleiro
begin
function __init__ self
begin
set tab = list list - 1 - 1 - 1 list - 1 - 1 - 1 list - 1 - 1 - 1
set vitoria = - 1
set jogadas = 0
end function
function getVitoria self
begin
return vitoria
end function
function marcarPosicao self id coordenadas
begin
if call posicaoMarcada coordenadas
begin
return ... | class tabuleiro:
def __init__(self):
self.tab = [[-1, -1, -1], [-1, -1, -1], [-1, -1, -1]]
self.vitoria = -1
self.jogadas = 0
def getVitoria(self):
return self.vitoria
def marcarPosicao(self, id, coordenadas):
if self.posicaoMarcada(coordenadas):
return... | Python | zaydzuhri_stack_edu_python |
from sklearn.metrics import classification_report
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
import sklearn.linear_model as lm
set model = logistic regression
class LogisticRegression
begin
f... | from sklearn.metrics import classification_report
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
import sklearn.linear_model as lm
model = lm.LogisticRegression()
class LogisticRegr... | Python | zaydzuhri_stack_edu_python |
function longestPalindrome s
begin
if length s < 2
begin
return s
end
set start = 0
set maxLength = 0
for center in range 1 length s - 1
begin
set left = center
set right = center
while left >= 0 and right < length s and s at left == s at right
begin
set left = left - 1
set right = right + 1
end
set length = right - le... | def longestPalindrome(s):
if len(s) < 2:
return s
start = 0
maxLength = 0
for center in range(1, len(s) - 1):
left = right = center
while left >= 0 and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
length ... | Python | jtatman_500k |
class Employee
begin
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
print string Total Employee %d % empCount
end function
function displayEmployee self
begin
print string Name: name string Salary: s... | class Employee:
empCount=0
def __init__(self,name,salary):
self.name=name
self.salary=salary
Employee.empCount+=1
def displayCount(self):
print("Total Employee %d"%Employee.empCount)
def displayEmployee(self):
print("Name:",self.name, "Salary:",self.salar... | Python | zaydzuhri_stack_edu_python |
import matplotlib.pyplot as plt
import numpy.random as random
from multiprocessing import Pool
function test_plt a b number
begin
set fig_loc = figure num=number + 1
scatter plt a b
save figure string %043d.jpg % tuple number + 1
close plt
end function
function do_plot number
begin
set fig = figure number
set a = rando... | import matplotlib.pyplot as plt
import numpy.random as random
from multiprocessing import Pool
def test_plt(a,b,number):
fig_loc = plt.figure(num = number + 1, )
plt.scatter(a,b )
plt.savefig("%043d.jpg" % (number + 1,))
plt.close()
def do_plot(number):
fig = plt.figure(number)
a = random.sa... | Python | zaydzuhri_stack_edu_python |
function labels self labels
begin
set _labels = labels
end function | def labels(self, labels):
self._labels = labels | Python | nomic_cornstack_python_v1 |
class PlasoGeneralEvent extends object
begin
string plaso general parser "TIMEZONE = parser.PARSE_TIMEZONE
function __init__ self data_type=none
begin
set data_type = data_type
set display_name = none
set offset = none
set parser = none
set hash = none
set time_stamp = none
set time_dsec = none
end function
function Se... | class PlasoGeneralEvent(object):
"""plaso general parser
"TIMEZONE = parser.PARSE_TIMEZONE"""
def __init__(self, data_type=None):
self.data_type = data_type
self.display_name = None
self.offset = None
self.parser = None
self.hash = None
self.time_stamp = None... | Python | zaydzuhri_stack_edu_python |
comment Задание 3
set n = input string Введите число от 1 до 9:
print integer n + integer n + n + integer n + n + n | # Задание 3
n = input ("Введите число от 1 до 9: ")
print (int (n) + int (n + n) + int(n + n + n)) | Python | zaydzuhri_stack_edu_python |
function set_mode_targeted_by_label self quiet=false
begin
call _set_mode_targeted string targeted(label) quiet
set _target_map_function = string function is a string
end function | def set_mode_targeted_by_label(self, quiet=False):
self._set_mode_targeted('targeted(label)', quiet)
self._target_map_function = 'function is a string' | Python | nomic_cornstack_python_v1 |
function __extractFileName self line
begin
set f = split line none 1 at 1
set f = call rsplit none 2 at 0
return f
end function | def __extractFileName(self, line):
f = line.split(None, 1)[1]
f = f.rsplit(None, 2)[0]
return f | Python | nomic_cornstack_python_v1 |
from elftools.elf.elffile import ELFFile
import os
import struct
class codeobject
begin
set CC = string ../resource/riscvgnutools/bin/riscv-none-embed-gcc
set AS = string ../resource/riscvgnutools/bin/riscv-none-embed-as
set LD = string ../resource/riscvgnutools/bin/riscv-none-embed-ld
function __init__ self ctype=stri... | from elftools.elf.elffile import ELFFile
import os
import struct
class codeobject:
CC = '../resource/riscvgnutools/bin/riscv-none-embed-gcc'
AS = '../resource/riscvgnutools/bin/riscv-none-embed-as'
LD = '../resource/riscvgnutools/bin/riscv-none-embed-ld'
def __init__(self, ctype = 'assembly'):
... | Python | zaydzuhri_stack_edu_python |
string Defines the form objects to be used for the booking aspects of the app Includes a form to search available dates
from django import forms
from django_countries.fields import CountryField
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout , Field , Fieldset , Div , HTML , Hidden
fro... | """
Defines the form objects to be used for the booking aspects of the app
Includes a form to search available dates
"""
from django import forms
from django_countries.fields import CountryField
from crispy_forms.helper import FormHelper
from crispy_forms.layout import (
Layout,
Field,
Fieldset,
Div,
... | Python | zaydzuhri_stack_edu_python |
function running_mean_after_pybites sequence
begin
for tuple count accumulated_sum in enumerate accumulate sequence start=1
begin
yield round accumulated_sum / count ndigits=2
end
end function | def running_mean_after_pybites(sequence):
for count, accumulated_sum in enumerate(itertools.accumulate(sequence), start=1):
yield round(accumulated_sum / count, ndigits=2) | Python | nomic_cornstack_python_v1 |
function accept self item
begin
return 1
end function | def accept (self, item):
return 1 | Python | nomic_cornstack_python_v1 |
comment 13
comment 1 2 1 3 2 4 3 5 3 6 4 7 5 8 5 9 6 10 6 11 7 12 11 13
comment 입력은 위와같이 받음.
comment 노드 개수 받기
set N = integer input
set info = list map int split input
comment 노드의 개수보다 크게 설정.
set tree = list 0 * 100
for i in range 0 length info 2
begin
set p = info at i
set c = info at i + 1
comment 초기 설정.
if p not in ... | # 13
# 1 2 1 3 2 4 3 5 3 6 4 7 5 8 5 9 6 10 6 11 7 12 11 13
# 입력은 위와같이 받음.
N = int(input()) # 노드 개수 받기
info = list(map(int, input().split()))
tree = [0] * 100 # 노드의 개수보다 크게 설정.
for i in range(0, len(info), 2):
p = info[i]
c = info[i + 1]
# 초기 설정.
if p not in tree:
idx = -1
else:
... | Python | zaydzuhri_stack_edu_python |
comment Autoencoder
comment Imports
from warnings import warn
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import norm
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Input , Dense , Lambda , Layer , Add , Multiply , Conv2D , MaxPooling2D , UpSamp... | # Autoencoder
# Imports
from warnings import warn
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import norm
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Input, Dense, Lambda, Layer, Add, Multiply, Conv2D, MaxPooling2D, UpSampling2D, Flatten, Re... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
import socket , select , string , sys , json , datetime , os , argparse , time
import threading
comment Introducir la ruta de favicon.ico y de index
set path_favicon = string /images/icon.ico
set path_index = string ./
comment Tiempo en segundos para el mensaje... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket, select, string, sys, json, datetime, os, argparse, time
import threading
#Introducir la ruta de favicon.ico y de index
path_favicon = '/images/icon.ico'
path_index = './'
#Tiempo en segundos para el mensaje de timeout
TIMEOUT = 300
#Definiciones de códigos... | Python | zaydzuhri_stack_edu_python |
function bases self
begin
_revision_map
return bases
end function | def bases(self):
self._revision_map
return self.bases | Python | nomic_cornstack_python_v1 |
comment menghitung volume tabung
set radius = decimal input string Radius >
set tinggi = decimal input string Tinggi >
set radius2 = radius ^ 2
set phi = 22 / 7
set v = phi * radius2 * tinggi
print string Volume nya > integer v | # menghitung volume tabung
radius = float(input("Radius > "))
tinggi = float(input("Tinggi > "))
radius2 = radius ** 2
phi = 22/7
v = phi * radius2 * tinggi
print("Volume nya > ",int(v)) | Python | zaydzuhri_stack_edu_python |
import tkinter as tk
set root = call Tk
title root string Sum Application
set num1 = call StringVar
set num2 = call StringVar
function calculate
begin
try
begin
set result = integer get num1 + integer get num2
call configure text=string The sum is %d % result
end
except ValueError
begin
call configure text=string Pleas... | import tkinter as tk
root = tk.Tk()
root.title('Sum Application')
num1 = tk.StringVar()
num2 = tk.StringVar()
def calculate():
try:
result = int(num1.get()) + int(num2.get())
sumLabel.configure(text="The sum is %d" % result)
except ValueError:
sumLabel.configure(text="Please enter num... | Python | iamtarun_python_18k_alpaca |
from pymongo import MongoClient
import datetime
class MongoStore extends object
begin
function __init__ self connectionStr
begin
set client = call MongoClient connectionStr
set db = client at string PyMongoDB
set collection = db at string test
end function
function insert self obj
begin
return inserted_id
end function
... | from pymongo import MongoClient
import datetime
class MongoStore(object):
def __init__(self,connectionStr):
self.client=MongoClient(connectionStr)
self.db=self.client['PyMongoDB']
self.collection=self.db['test']
def insert(self,obj):
return self.collection.insert_one(obj).i... | Python | zaydzuhri_stack_edu_python |
function addHandler name basepath=none baseurl=none allowDownscale=false
begin
string Add an event handler with given name.
if basepath is none
begin
set basepath = string .
end
append _handlers call basepath baseurl allowDownscale
end function | def addHandler(name, basepath=None, baseurl=None, allowDownscale=False):
"""Add an event handler with given name."""
if basepath is None:
basepath = '.'
_handlers.append(_handler_classes[name](basepath, baseurl, allowDownscale)) | Python | jtatman_500k |
function set_value self value
begin
if call _is_string value
begin
set value = split value string ,
for item in value
begin
append _value call _type item
end
end
else
if call _is_list value
begin
set _value = list
for item in value
begin
if not call _is_primitive item
begin
return MODEL_ANALYZER_FAILURE
end
append _va... | def set_value(self, value):
if self._is_string(value):
value = value.split(',')
for item in value:
self._value.append(self._type(item))
elif self._is_list(value):
self._value = []
for item in value:
if not self._is_primitiv... | Python | nomic_cornstack_python_v1 |
function _execute_bwd params tapes device execute_fn gradient_fn gradient_kwargs _n=1 max_diff=2
begin
comment pylint: disable=unused-variable
comment Copy a given tape with operations and set parameters
set new_device_interface = is instance device Device
decorator custom_jvp
function execute_wrapper params
begin
set ... | def _execute_bwd(
params,
tapes,
device,
execute_fn,
gradient_fn,
gradient_kwargs,
_n=1,
max_diff=2,
):
# pylint: disable=unused-variable
# Copy a given tape with operations and set parameters
new_device_interface = isinstance(device, qml.devices.experimental.Device)
@... | Python | nomic_cornstack_python_v1 |
function send s data verbose=false
begin
comment Ensure to terminate with desired newline
if is instance data bytes
begin
set data = call b2str data
end
set lines = split data string
for line in lines
begin
set line = line + string
set size = length line
set line = encode line
set send = 0
comment Loop until all bytes... | def send(s, data, verbose=False):
# Ensure to terminate with desired newline
if isinstance(data, bytes):
data = b2str(data)
lines = data.split("\n")
for line in lines:
line += "\n"
size = len(line)
line = line.encode()
send = 0
# Loop until all bytes ha... | Python | nomic_cornstack_python_v1 |
function calculate_angles_to_rotate_vector self *args **kwargs
begin
comment The parent class does the work
set best_angles = call calculate_angles_to_rotate_vector self *args keyword kwargs
if best_angles is none
begin
return none
end
else
begin
set tuple phi chi omega = best_angles
comment Chi needs to be 45 degrees!... | def calculate_angles_to_rotate_vector(self, *args, **kwargs):
#The parent class does the work
best_angles = LimitedGoniometer.calculate_angles_to_rotate_vector(self, *args, **kwargs)
if best_angles is None:
return None
else:
(phi, chi, omega) = best_angles
... | Python | nomic_cornstack_python_v1 |
set t = tuple 1
print string 要素が1だけのタプル : { t }
print string 型 : { type t } | t = (1, )
print(f'要素が1だけのタプル : {t}')
print(f'型 : {type(t)}') | Python | zaydzuhri_stack_edu_python |
from xlrd import open_workbook
import string
set tweets = call open_workbook string Final_Tweet_Table_simulation.xlsx
for s in call sheets
begin
set numb_row = nrows
set numb_col = ncols
set time_vector = list
set user_vector = list
set unigrams_vector = list
set bigrams_vector = list
set trigrams_vector = list
se... | from xlrd import open_workbook
import string
tweets = open_workbook('Final_Tweet_Table_simulation.xlsx')
for s in tweets.sheets():
numb_row = s.nrows
numb_col = s.ncols
time_vector = []
user_vector = []
unigrams_vector = []
bigrams_vector = []
trigrams_vector = []
ngra... | Python | zaydzuhri_stack_edu_python |
function __init__ self *args **kwargs
begin
if length kwargs == 1 and string handle in kwargs
begin
set handle = kwargs at string handle
call IncRef handle
end
else
if length args == 1 and is instance args at 0 GoClass
begin
set handle = handle
call IncRef handle
end
else
if length args == 1 and is instance args at 0 i... | def __init__(self, *args, **kwargs):
if len(kwargs) == 1 and 'handle' in kwargs:
self.handle = kwargs['handle']
_test.IncRef(self.handle)
elif len(args) == 1 and isinstance(args[0], GoClass):
self.handle = args[0].handle
_test.IncRef(self.handle)
elif len(args) == 1 and isinstance(args[0], int):
se... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Sun Oct 21 08:15:51 2018 @author: bjohau
import numpy as np
import sys
function gauss_points iRule
begin
string Returns gauss coordinates and weight given integration number Parameters: iRule = number of integration points Returns: gp : row-vector containing gauss coordin... | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 21 08:15:51 2018
@author: bjohau
"""
import numpy as np
import sys
def gauss_points(iRule):
"""
Returns gauss coordinates and weight given integration number
Parameters:
iRule = number of integration points
Returns:
gp... | Python | zaydzuhri_stack_edu_python |
from sha1 import sha1 , Sha1Hash
from time import sleep , time
from statistics import median
set blocksize = 64
function xor ma mb
begin
return bytes list comprehension a ? b for tuple a b in zip ma mb
end function
function sha1bytes message
begin
return call digest
end function
function hmac key message
begin
if lengt... | from sha1 import sha1, Sha1Hash
from time import sleep, time
from statistics import median
blocksize = 64
def xor(ma, mb):
return bytes([a ^ b for a, b in zip(ma, mb)])
def sha1bytes(message):
return Sha1Hash().update(message).digest()
def hmac(key, message):
if len(key) > blocksize:
key = sha... | Python | zaydzuhri_stack_edu_python |
comment coding=utf8
import sublime_plugin , sublime , re
comment to transfer cleaned data to sublime text
function clean_paste data
begin
comment Standard stuff like apostrophes
set data = replace data string " string ”
set data = replace data string ” string ”
set data = replace data string “ string &ldquo... | # coding=utf8
import sublime_plugin, sublime, re
# to transfer cleaned data to sublime text
def clean_paste(data):
#Standard stuff like apostrophes
data = data.replace(u'\"', '”')
data = data.replace(u'”', '”')
data = data.replace(u'“', '“')
data = data.replace(u'\'', '’')... | Python | zaydzuhri_stack_edu_python |
function checkScene doc_id
begin
if call objExists string root
begin
call setText string You shouldn't have any named 'root' node in your scene
return false
end
return true
end function | def checkScene ( doc_id ):
if cmds.objExists ( "root" ) :
self.labelStatus.setText ( "You shouldn't have any named 'root' node in your scene" )
return False
return True | Python | nomic_cornstack_python_v1 |
function cluster_version self
begin
return get pulumi self string cluster_version
end function | def cluster_version(self) -> Optional[str]:
return pulumi.get(self, "cluster_version") | Python | nomic_cornstack_python_v1 |
function subnet_id self
begin
return get pulumi self string subnet_id
end function | def subnet_id(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "subnet_id") | Python | nomic_cornstack_python_v1 |
function _process proc_data
begin
return proc_data
end function | def _process(proc_data: Dict) -> Dict:
return proc_data | Python | nomic_cornstack_python_v1 |
function native_unit_of_measurement self
begin
if has attribute self string _attr_native_unit_of_measurement
begin
return _attr_native_unit_of_measurement
end
if has attribute self string entity_description
begin
return native_unit_of_measurement
end
return none
end function | def native_unit_of_measurement(self) -> str | None:
if hasattr(self, "_attr_native_unit_of_measurement"):
return self._attr_native_unit_of_measurement
if hasattr(self, "entity_description"):
return self.entity_description.native_unit_of_measurement
return None | Python | nomic_cornstack_python_v1 |
function load_reportlab finder module
begin
call IncludeModule string reportlab.rl_settings
end function | def load_reportlab(finder, module):
finder.IncludeModule("reportlab.rl_settings") | 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.