code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment !/usr/bin string The target is put through an embedding which is summed with the positional encoding. The output of this summation is the input to the decoder layers. The output of the decoder is the input to the final linear layer. function decoder vocab_size num_layers units d_model num_heads dropout name=str...
#!/usr/bin """ The target is put through an embedding which is summed with the positional encoding. The output of this summation is the input to the decoder layers. The output of the decoder is the input to the final linear layer. """ def decoder(vocab_size, num_layers, units, d_model, num_heads, dropout, name='decoder...
Python
zaydzuhri_stack_edu_python
function additional_derivatives self increment_filter k begin comment derivatives for specified energy-group paremeters if is_set begin set f = energy_func set jacobian at tuple k 0 0 = val_SI - val_SI if not increment_filter at tuple 0 1 begin set jacobian at tuple k 0 1 = call numeric_deriv f string p 0 end if not in...
def additional_derivatives(self, increment_filter, k): ###################################################################### # derivatives for specified energy-group paremeters if self.energy_group.is_set: f = self.energy_func self.jacobian[k, 0, 0] = ( s...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding=utf-8 import smtplib set mail_server = string smtp.qq.com set mail_server_port = 25 set from_addr = string 1161938@qq.com set to_addr = string applelyh@qq.com comment 要发送的头部格式 set from_header = string From:%s % from_addr set to_header = string To:%s % to_addr comment 要发送的标题 s...
#!/usr/bin/env python #coding=utf-8 import smtplib mail_server = 'smtp.qq.com' mail_server_port = 25 from_addr = '1161938@qq.com' to_addr = 'applelyh@qq.com' #要发送的头部格式 from_header = 'From:%s\r\n' % from_addr to_header = 'To:%s\r\n\r\n' % to_addr #要发送的标题 subject_header = 'Subject:Test SMTP' content =...
Python
zaydzuhri_stack_edu_python
function first_baron self first_baron begin set _first_baron = first_baron end function
def first_baron(self, first_baron): self._first_baron = first_baron
Python
nomic_cornstack_python_v1
import argparse from preprocess import Preprocess from data_parser import Parser import pickle if __name__ == string __main__ begin set parser = call ArgumentParser description=string Prepare data with features and labels call add_argument string -i type=str help=string data file to prepare call add_argument string -o ...
import argparse from preprocess import Preprocess from data_parser import Parser import pickle if __name__ == '__main__': parser = argparse.ArgumentParser(description='Prepare data with features and labels') parser.add_argument('-i', type=str, help='data file to prepare') parser.add_argument('-o', type=s...
Python
zaydzuhri_stack_edu_python
comment Famous Quote set famous_person = string Albert Einstein set message = string "A person who never made a mistake never tried anything new." print famous_person + string + message comment My Favorite Number set Fav = string string 7 set massage = string My favorite number is print massage + Fav
# Famous Quote famous_person = "Albert Einstein" message = '"A person who never made a mistake never tried anything new."' print(famous_person + " " + message) # My Favorite Number Fav = str('7') massage = 'My favorite number is ' print(massage + Fav)
Python
zaydzuhri_stack_edu_python
function version_constraint version_range begin return string >= { version_range at 0 } ,< { version_range at 1 } end function
def version_constraint(version_range): return f">={version_range[0]},<{version_range[1]}"
Python
nomic_cornstack_python_v1
function test_find_config_directories begin set dirs = call config_directories string test call eq_ length dirs 3 end function
def test_find_config_directories(): dirs = find.config_directories('test') nt.eq_(len(dirs), 3)
Python
nomic_cornstack_python_v1
string Author @ Mihir_Srivastava Dated - 20-05-2020 File - Visualizing_K_means_clustering Aim - To visualize how k means clustering (flat clustering) actually works. comment import necessary libraries import matplotlib.pyplot as plt import numpy as np from matplotlib import style from sklearn.cluster import KMeans call...
""" Author @ Mihir_Srivastava Dated - 20-05-2020 File - Visualizing_K_means_clustering Aim - To visualize how k means clustering (flat clustering) actually works. """ # import necessary libraries import matplotlib.pyplot as plt import numpy as np from matplotlib import style from sklearn.cluster import KMea...
Python
zaydzuhri_stack_edu_python
function line_alpha self *args **kwargs begin return call freq_sink_f_line_alpha self *args keyword kwargs end function
def line_alpha(self, *args, **kwargs): return _qtgui_swig.freq_sink_f_line_alpha(self, *args, **kwargs)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment Now suppose I roll the die again and get an 8. comment We can update the Suite again with the new data. comment Now the 6-sided die has been eliminated, the 8-sided die is most likely, comment and there is less than a 10% chance that I am rolling a 20-sided die. call bayesian_update...
#!/usr/bin/env python # Now suppose I roll the die again and get an 8. # We can update the Suite again with the new data. # Now the 6-sided die has been eliminated, the 8-sided die is most likely, # and there is less than a 10% chance that I am rolling a 20-sided die. dice_suite.bayesian_update(8) for die, prob i...
Python
zaydzuhri_stack_edu_python
comment Welcome to Learn Python created by Kyle Martin | https://github.com/Thesnowmanndev | This repository is mainly for my comment notes while learning how to program in python. Feel free to read over the files in this repository and learn what comment you can. I will try to leave as detailed notes in a comment form...
# Welcome to Learn Python created by Kyle Martin | https://github.com/Thesnowmanndev | This repository is mainly for my # notes while learning how to program in python. Feel free to read over the files in this repository and learn what # you can. I will try to leave as detailed notes in a comment form as I can but if y...
Python
zaydzuhri_stack_edu_python
from math import atan2 from random import randint set points : list at tuple at tuple int int = list for i in range 10 begin set point = tuple random integer - 100 100 random integer - 100 100 append points point end set phi = lambda x y -> call atan2 x y set sortedByPhi = sorted points key=lambda p -> call phi p at 0...
from math import atan2 from random import randint points: list[tuple[int, int]] = [] for i in range(10): point = randint(-100, 100), randint(-100, 100) points.append(point) phi = lambda x, y: atan2(x, y) sortedByPhi = sorted(points, key=lambda p: phi(p[0], p[1])) print(sortedByPhi)
Python
zaydzuhri_stack_edu_python
while count > 0 begin set passwardin = input string input the passward: if passwardin == passward begin print string great!!~~~~~~~~~~~ break end else if string * in passwardin begin print string there is '*' ,input again %d times left % count continue end else begin print string input is wrong,%d times left % count - ...
while count>0: passwardin=input("input the passward:") if passwardin==passward: print("great!!~~~~~~~~~~~") break elif '*' in passwardin: print("there is '*' ,input again \n %d times left"%count) continue else: print("input is wrong,%d times left"%(count-1)) ...
Python
zaydzuhri_stack_edu_python
string 元组的定义和使用 Version: 0.1 Author: 骆昊 Date: 2018-03-06 function main begin set t = tuple string 骆昊 38 true string 四川成都 print t print t at 0 print t at 1 print t at 2 print t at 3 for member in t begin print member end comment t[0]='王大富' set t = tuple string 王大锤 20 true string 云南昆明 print t set person = list t print pe...
""" 元组的定义和使用 Version: 0.1 Author: 骆昊 Date: 2018-03-06 """ def main(): t = ('骆昊', 38, True, '四川成都') print(t) print(t[0]) print(t[1]) print(t[2]) print(t[3]) for member in t: print(member) # t[0]='王大富' t = ('王大锤', 20, True, '云南昆明') print(t) person = list(t) print(pe...
Python
zaydzuhri_stack_edu_python
import os import exifread import re import json import requests function getExif path filename begin set old_full_file_name = join path imgpath filename set FIELD = string EXIF DateTimeOriginal set fd = open old_full_file_name string rb set tags = call process_file fd close fd comment 显示图片所有的exif信息 print string showing...
import os import exifread import re import json import requests def getExif(path, filename): old_full_file_name = os.path.join(imgpath, filename) FIELD = 'EXIF DateTimeOriginal' fd = open(old_full_file_name, 'rb') tags = exifread.process_file(fd) fd.close() # 显示图片所有的exif信息 print("showing r...
Python
zaydzuhri_stack_edu_python
function L_Layers_backword_model AL train_y internal_params begin set grads = dict set L = integer length internal_params / 2 comment nb = AL.shape[1] print shape set train_y = reshape train_y shape set dAL = call compute_error_cross_dataset AL train_y set curr_params = internal_params at L - 1 set tuple grads at stri...
def L_Layers_backword_model(AL, train_y, internal_params): grads = {} L = int(len(internal_params)/2) # nb = AL.shape[1] print(AL.shape) train_y = train_y.reshape(AL.shape) dAL = compute_error_cross_dataset(AL, train_y) curr_params = internal_params[L - 1] grads["dA" + str(L)], grads["dW...
Python
nomic_cornstack_python_v1
function get_random_female begin set last = count objects - 1 set randomIndex = random integer 0 last return all at randomIndex end function
def get_random_female(): last = Female.objects.count() - 1 randomIndex = random.randint(0, last) return Female.objects.all()[randomIndex]
Python
nomic_cornstack_python_v1
string pokemon.py fully depends on the _pokemon_database for its query results the PokemonController initially loads all of the data (type, weaknesses, strengths, etc) from files once all of the data is loaded in, our server fully relies on the stored data to fill queries comment movies.py import cherrypy import json f...
''' pokemon.py fully depends on the _pokemon_database for its query results the PokemonController initially loads all of the data (type, weaknesses, strengths, etc) from files once all of the data is loaded in, our server fully relies on the stored data to fill queries ''' #movies.py import cherrypy import json from ...
Python
zaydzuhri_stack_edu_python
comment Import dataframe and functions comment from Helper import * from main import * comment Import packages import base64 import pandas as pd import numpy as np import dash import dash_table import dash_core_components as dcc import dash_html_components as html import dash_bootstrap_components as dbc import plotly.g...
# Import dataframe and functions # from Helper import * from main import * # Import packages import base64 import pandas as pd import numpy as np import dash import dash_table import dash_core_components as dcc import dash_html_components as html import dash_bootstrap_components as dbc import plotly.graph...
Python
zaydzuhri_stack_edu_python
import cv2 import os import matplotlib call use string Agg import matplotlib.pyplot as plt import numpy as np import matplotlib.image as mpimg from undistort import undistort from transformPerspective import transformPerspective , inverseTransformPerspective from imageFilters import threshold , sobelX , sobelY , sobelD...
import cv2 import os import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np import matplotlib.image as mpimg from undistort import undistort from transformPerspective import transformPerspective, inverseTransformPerspective from imageFilters import threshold, sobelX, sobelY, sobel...
Python
zaydzuhri_stack_edu_python
function __rmul__ self integrand begin comment Avoid circular imports from ufl.integral import Integral from ufl.form import Form comment Allow python literals: 1*dx and 1.0*dx if is instance integrand tuple int float begin set integrand = call as_ufl integrand end comment Let other types implement multiplication with ...
def __rmul__(self, integrand): # Avoid circular imports from ufl.integral import Integral from ufl.form import Form # Allow python literals: 1*dx and 1.0*dx if isinstance(integrand, (int, float)): integrand = as_ufl(integrand) # Let other types implement mul...
Python
nomic_cornstack_python_v1
function _bin self X begin set H = linear space 0 1 Nbin return call maximum 1 - absolute X at tuple Ellipsis none - H / H at 1 - H at 0 0 end function
def _bin(self, X): H = np.linspace(0, 1, self.Nbin) return np.maximum(1 - (abs(X[..., None] - H)) / (H[1] - H[0]) , 0)
Python
nomic_cornstack_python_v1
if K * 500 >= X begin print string Yes end else begin print string No end
if K * 500 >= X: print("Yes") else: print("No")
Python
zaydzuhri_stack_edu_python
function __hash__ self begin set hashvalue = call hash __name__ for tuple i c in self begin set hashvalue = hashvalue ? call hash i ? call hash c end return hashvalue ? 2147483647 end function
def __hash__(self): hashvalue = hash(self.__class__.__name__) for i, c in self: hashvalue = hashvalue ^ (hash(i) | hash(c)) return hashvalue & 0x7fffffff
Python
nomic_cornstack_python_v1
function packSimulationCommand self lstCommand begin set szCommand = string set szCommand = call pack string 16si lstCommand at 0 lstCommand at 1 set szCommand = szCommand + call pack string i length lstCommand at slice 2 : : for i in lstCommand at slice 2 : : begin set szCommand = szCommand + call pack string 16s ...
def packSimulationCommand(self, lstCommand): szCommand = "" szCommand = struct.pack('16si', lstCommand[0], lstCommand[1]) szCommand += struct.pack('i', len(lstCommand[2:])) for i in lstCommand[2:]: szCommand += struct.pack('16s', i[0]) szCommand += struct.pack('i', len(i[1:])) for j in...
Python
nomic_cornstack_python_v1
function logLayerInfo self msg=none begin if msg begin log msg end debug string Layers: for id in layer_z_order begin set layer = layer_mapping at id debug string %s % string layer end end function
def logLayerInfo(self, msg=None): if msg: log(msg) log.debug('Layers:') for id in self.layer_z_order: layer = self.layer_mapping[id] log.debug(' %s' % str(layer))
Python
nomic_cornstack_python_v1
class Solution extends object begin function verticalTraversal self root begin string :type root: TreeNode :rtype: List[List[int]] set maxHd = 0 set minHd = 0 set cache = dict comment Map binary tree into cache call dfs root 0 0 comment Remap cache into result list set res = list for key in range minHd maxHd + 1 begi...
class Solution(object): def verticalTraversal(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ self.maxHd = 0 self.minHd = 0 self.cache = {} # Map binary tree into cache self.dfs(root, 0, 0) # Remap cache into result li...
Python
zaydzuhri_stack_edu_python
string 22 (Population projection) Rewrite Exercise 1.11 to prompt the user to enter the number of years and displays the population after that many years. Here is a sample run of the program: Enter the number of years: The population in 5 years is 325932970 set birth = 7 set death = 13 set NI = 45 set CP = 312032486 se...
''' 22 (Population projection) Rewrite Exercise 1.11 to prompt the user to enter the number of years and displays the population after that many years. Here is a sample run of the program: Enter the number of years: The population in 5 years is 325932970 ''' birth =7 death = 13 NI = 45 CP = 312032486 YIS =...
Python
zaydzuhri_stack_edu_python
function get_iso_gradients dv_dict begin set p at string oas_scaneagle.wing.twist_cp = dv_dict at string twist_cp set p at string oas_scaneagle.wing.thickness_cp = dv_dict at string thickness_cp set p at string oas_scaneagle.wing.sweep = dv_dict at string sweep set p at string oas_scaneagle.alpha = dv_dict at string al...
def get_iso_gradients(dv_dict): UQObj.QoI.p['oas_scaneagle.wing.twist_cp'] = dv_dict['twist_cp'] UQObj.QoI.p['oas_scaneagle.wing.thickness_cp'] = dv_dict['thickness_cp'] UQObj.QoI.p['oas_scaneagle.wing.sweep'] = dv_dict['sweep'] UQObj.QoI.p['oas_scaneagle.alpha'] = dv_dict['alpha'] mu_val = cp.E(UQ...
Python
nomic_cornstack_python_v1
string grouper.py EXIF 기반 파일 분류(동영상 파일도 가능한지 확인요망) 필수 설정 변수 _path_dir # 작업 경로 _is_year_path_dir # _path_dir가 연도폴더인지 아닌지 _fr_year # 생성할 폴더 시작년도 _to_year # 생성할 폴더 종료년도 하기 EXIF 기준으로 파일을 분류하며 순서는 다음과 같다. BASE EXIF 1. DateTimeOriginal 2. DateTimeDigitized 3. DateTime 확장자 필터 - jpg/jpeg/png/gif 등 - mp4/mov/mkv/avi 등 작업흐름 # 연도...
"""grouper.py EXIF 기반 파일 분류(동영상 파일도 가능한지 확인요망) 필수 설정 변수 _path_dir # 작업 경로 _is_year_path_dir # _path_dir가 연도폴더인지 아닌지 _fr_year # 생성할 폴더 시작년도 _to_year # 생성할 폴더 종료년도 하기 EXIF 기준으로 파일을 분류하며 순서는 다음과 같다. BASE EXIF 1. DateTimeOriginal 2. DateTimeDigitized 3. DateTime ...
Python
zaydzuhri_stack_edu_python
function query_roles self parameters=none **kwargs begin comment [GET] https://assets.falcon.crowdstrike.com/support/api/swagger.html#/mssp/queryRoles return call process_service_request calling_object=self endpoints=Endpoints operation_id=string queryRoles keywords=kwargs params=parameters end function
def query_roles(self: object, parameters: dict = None, **kwargs) -> dict: # [GET] https://assets.falcon.crowdstrike.com/support/api/swagger.html#/mssp/queryRoles return process_service_request( calling_object=self, endpoints=Endpoints, operation_id="queryRoles", ...
Python
nomic_cornstack_python_v1
class MNIST_data begin function __init__ self image label begin set image = image set label = label end function end class function load_mnist_dataset begin from mnist import MNIST set mn_data = call MNIST string ./mnist set tuple images labels = call load_training print string loading mnist dataset complete. return tu...
class MNIST_data : def __init__(self, image, label) : self.image = image self.label = label def load_mnist_dataset() : from mnist import MNIST mn_data = MNIST('./mnist') images, labels = mn_data.load_training() print('loading mnist dataset complete.') return images, labels def...
Python
zaydzuhri_stack_edu_python
comment JWT --> Json Web Token from werkzeug.security import safe_str_cmp from models.user import UserModel function authenticate username password begin comment user = username_mapping.get(username,None) set user = call find_by_username username print string * * 10 print user print string * * 10 if user and password =...
# JWT --> Json Web Token from werkzeug.security import safe_str_cmp from models.user import UserModel def authenticate(username, password): # user = username_mapping.get(username,None) user = UserModel.find_by_username(username) print("*"*10) print(user) print("*"*10) if user and user.password...
Python
zaydzuhri_stack_edu_python
comment # Python Fundamentals comment # Neil Denning comment # These are lessons examples comment # Code BLock Key Words -below comment # def (functions) comment # if, elif, else (conditional statements) comment # for, while (loops) comment # Class (classes) comment # ---------------------------------------------------...
# # Python Fundamentals # # Neil Denning # # These are lessons examples # # Code BLock Key Words -below # # def (functions) # # if, elif, else (conditional statements) # # for, while (loops) # # Class (classes) # # --------------------------------------------------------------| # x = 10 # if x > 50: # print("bi...
Python
zaydzuhri_stack_edu_python
comment 11779 - 최소비용 구하기 2 from heapq import heappop , heappush from sys import stdin set input = readline function dijkstra start begin set distance = list 1000000000.0 * 1001 set distance at start = 0 set q = list call heappush q list 0 start while q begin set tuple dist now = call heappop q if now == end begin retu...
# 11779 - 최소비용 구하기 2 from heapq import heappop, heappush from sys import stdin input = stdin.readline def dijkstra(start): distance = [1e9]*1001 distance[start] = 0 q = [] heappush(q,[0,start]) while q: dist, now = heappop(q) if now == end: return dist for nex...
Python
zaydzuhri_stack_edu_python
function handle_history self begin set choices = call get_previous_choices if choices at slice : - 1 : is not list begin set step = call get_current_step set choices = list update step choices=list end else begin raise call ModelError string Previous choice does not exist end return step end function
def handle_history(self): choices = self.get_previous_choices() if choices[:-1] is not []: step = self.get_current_step() step.choices = [] step.update(choices=[]) else: raise ModelError("Previous choice does not exist") return step
Python
nomic_cornstack_python_v1
function test_project_fork default_domino_client begin set forked_project_name = string forked-project- { string uuid 4 } set response = call fork_project forked_project_name assert status_code == 200 msg string { status_code } : { reason } set project_list = call projects_list assert any generator expression p at stri...
def test_project_fork(default_domino_client): forked_project_name = f"forked-project-{str(uuid.uuid4())}" response = default_domino_client.fork_project(forked_project_name) assert response.status_code == 200, f"{response.status_code}: {response.reason}" project_list = default_domino_client.projects_lis...
Python
nomic_cornstack_python_v1
function test_append_slash_opt_out self begin set request = get rf string /sensitive_fbv assert equal status_code 404 set request = get rf string /sensitive_cbv assert equal status_code 404 end function
def test_append_slash_opt_out(self): request = self.rf.get("/sensitive_fbv") self.assertEqual(CommonMiddleware(get_response_404)(request).status_code, 404) request = self.rf.get("/sensitive_cbv") self.assertEqual(CommonMiddleware(get_response_404)(request).status_code, 404)
Python
nomic_cornstack_python_v1
function test_single_image_no_train_id self client begin set params = dictionary tag=string tag_name_0/image step=1 set url = call get_url BASE_URL params set response = get client url assert status_code == 400 set response = call get_json assert response at string error_code == string 50540003 assert response at strin...
def test_single_image_no_train_id(self, client): params = dict(tag="tag_name_0/image", step=1) url = get_url(BASE_URL, params) response = client.get(url) assert response.status_code == 400 response = response.get_json() assert response['error_code'] == '50540003' ...
Python
nomic_cornstack_python_v1
comment Complete the compareTriplets function below. function compareTriplets begin set tuple a b = tuple 0 0 comment contestants=['alice','bob'] comment for i in contestants: comment print(i) set alice = list set tuple x y z = map int split input string Enter 3 scores given by judges extend alice list x y z print ali...
# Complete the compareTriplets function below. def compareTriplets(): a,b=0,0 # contestants=['alice','bob'] # for i in contestants: # print(i) alice=[] x,y,z=map(int, input("Enter 3 scores given by judges").split()) alice.extend([x,y,z]) print(alice) bob=[] x,y,z=map(int, in...
Python
zaydzuhri_stack_edu_python
import os from PIL import Image set l1 = list directory get current directory set p = list for ele in l1 begin if starts with ele string $ and ends with ele string .jpg begin append p ele end end for path in p begin set img = open path set img = call resize tuple 28 28 BILINEAR save path end
import os from PIL import Image l1=os.listdir(os.getcwd()) p=[] for ele in l1: if ele.startswith('$') and ele.endswith('.jpg'): p.append(ele) for path in p: img = Image.open(path) img = img.resize((28, 28), Image.BILINEAR) img.save(path)
Python
zaydzuhri_stack_edu_python
function testDrawEdge self begin set tuple w h = get size im8_1 for thick in range 10 begin call reset call drawEdge im8_1 thick call fill 255 call drawSquare im8_3 tuple thick thick w - 1 - thick h - 1 - thick 0 set tuple x y = call compare im8_1 im8_3 im8_2 assert true x < 0 end end function
def testDrawEdge(self): (w,h) = self.im8_1.getSize() for thick in range(10): self.im8_1.reset() drawEdge(self.im8_1, thick) self.im8_3.fill(255) drawSquare(self.im8_3, (thick, thick, w-1-thick, h-1-thick), 0) (x,y) = compare(self.im8_1...
Python
nomic_cornstack_python_v1
comment Question: comment Define a class named American which has a static method called printNationality. comment Hints: comment Use @staticmethod decorator to define class static method. comment class American: comment @staticmethod comment def printNationality(self): comment self.nationality = "American" comment Imm...
# Question: # Define a class named American which has a static method called printNationality. # # Hints: # # Use @staticmethod decorator to define class static method. # # class American: # @staticmethod # def printNationality(self): # self.nationality = "American" # Imma be honest, I ha...
Python
zaydzuhri_stack_edu_python
comment -*- coding:utf-8 -*- string 线性分类器(分类)实践之良/恶性乳腺癌肿瘤预测 import pandas as pd import numpy as np comment 指定数据列名 set col_name = list string code number string clump thickness string size string shape string adhesion string single size string nuclei string chromatin string nucleoli string mitoses string class comment 读...
# -*- coding:utf-8 -*- """ 线性分类器(分类)实践之良/恶性乳腺癌肿瘤预测 """ import pandas as pd import numpy as np #指定数据列名 col_name=['code number','clump thickness','size','shape','adhesion','single size','nuclei','chromatin','nucleoli','mitoses','class'] # 读取数据 data=pd.read_csv('良恶性乳腺癌肿瘤预测.txt',sep=',',header=None,names=col_name) # 查看数据 #...
Python
zaydzuhri_stack_edu_python
comment directory listing import glob comment sha1 import hashlib import json from collections import defaultdict set customSongsDir = string C:/Program Files (x86)/Steam/steamapps/common/Beat Saber/Beat Saber_Data/CustomLevels/ set songsDict = default dictionary set folders = list comprehension f for f in glob glob st...
import glob # directory listing import hashlib # sha1 import json from collections import defaultdict customSongsDir = 'C:/Program Files (x86)/Steam/steamapps/common/Beat Saber/Beat Saber_Data/CustomLevels/' songsDict = defaultdict() folders = [f for f in glob.glob(f"{customSongsDir}*/")] for folder in folders:...
Python
zaydzuhri_stack_edu_python
function test_project_ds_tree self begin call project_ds_tier inst1 call project_ds_tier inst2 end function
def test_project_ds_tree(self): project_ds_tier(self.inst1) project_ds_tier(self.inst2)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- encoding: utf-8 -*- string @File : theturtle.py @Time : 2019/06/26 22:20:56 @Author : 王翔 @Version : 1.0 @Contact : muumuu123@126.com @License : (C)Copyright 2018-2019, 王翔 @Desc : None comment here put the import lib from turtle import * comment 设置笔刷宽度: call width 4 comment 前进: c...
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @File : theturtle.py @Time : 2019/06/26 22:20:56 @Author : 王翔 @Version : 1.0 @Contact : muumuu123@126.com @License : (C)Copyright 2018-2019, 王翔 @Desc : None ''' # here put the import lib from turtle import * # 设置笔刷宽度: width(4) # 前进: forward...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 import abc import cv2 import numpy as np from math import sqrt comment Board dimensions, in millimeters as well as pixels set BOARD_H = 300 set BOARD_W = 400 comment Board Obstacles set quads = list list 36.53 124.38 48 108 170.87 194.04 159.4 210.42 list 200 280 200 230 210 230 210 280 li...
#!/usr/bin/env python3 import abc import cv2 import numpy as np from math import sqrt # Board dimensions, in millimeters as well as pixels BOARD_H = 300 BOARD_W = 400 # Board Obstacles quads = [[36.53, 124.38, 48, 108, 170.87, 194.04, 159.40, 210.42], [200,280,200,230,210,230,210,280], [210,280,210...
Python
zaydzuhri_stack_edu_python
function disable_logo plot element begin set logo = none end function
def disable_logo(plot, element): plot.state.toolbar.logo = None
Python
nomic_cornstack_python_v1
function is_json self begin string Check if the mimetype indicates JSON data, either :mimetype:`application/json` or :mimetype:`application/*+json`. set mt = mimetype return mt == string application/json or starts with mt string application/ and ends with mt string +json end function
def is_json(self): """Check if the mimetype indicates JSON data, either :mimetype:`application/json` or :mimetype:`application/*+json`. """ mt = self.mimetype return ( mt == "application/json" or mt.startswith("application/") and mt.endswith("+...
Python
jtatman_500k
comment !/usr/bin/env python comment -*- coding: utf-8 -*- string PoleXML - Operações com XML em Python Arquivo: PoleXML.py Versão.: 0.1.0 Autor..: Claudio Polegato Junior Data...: 25 Mar 2011 Copyright © 2011 - Claudio Polegato Junior <junior@juniorpolegato.com.br> Todos os direitos reservados comment Módulo para vali...
#!/usr/bin/env python # -*- coding: utf-8 -*- """PoleXML - Operações com XML em Python Arquivo: PoleXML.py Versão.: 0.1.0 Autor..: Claudio Polegato Junior Data...: 25 Mar 2011 Copyright © 2011 - Claudio Polegato Junior <junior@juniorpolegato.com.br> Todos os direitos reservados """ # Módulo para validação de XML e ...
Python
zaydzuhri_stack_edu_python
function compose2 f g begin return lambda x -> f dist call g x end function function double x begin return x * 2 end function function inc x begin return x + 1 end function set inc_and_double = call compose2 double inc
def compose2(f,g): return lambda x:f(g(x)) def double(x): return x*2 def inc(x): return x+1 inc_and_double=compose2(double,inc)
Python
zaydzuhri_stack_edu_python
function pp arg lexer=__PP_LEXER_PYTHON formatter=__PP_FORMATTER outfile=stdout begin set arg = call pformat arg set close = false try begin if is instance outfile string_types begin set close = true set outfile = open outfile string w end call highlight arg lexer formatter outfile end finally begin if close begin clos...
def pp(arg, lexer=__PP_LEXER_PYTHON, formatter=__PP_FORMATTER, outfile=sys.stdout): arg = pformat(arg) close = False try: if isinstance(outfile, six.string_types): close = True outfile = open(outfile, 'w') pygments.highlight(arg, lexer, formatter, outfile) final...
Python
nomic_cornstack_python_v1
function basis_representation self matrix_representation begin raise call NotImplementedError string basis_representation not implemented. end function
def basis_representation(self, matrix_representation): raise NotImplementedError("basis_representation not implemented.")
Python
nomic_cornstack_python_v1
import sys import re from functools import partial set CLASSES = list string 0 string 4 function init_arff f begin string Initialize the .arff file f. That is, write the relation name and enumerate the attributes. write f format string @relation {} RELATION_NAME for feature in FEATURES begin write f format string @attr...
import sys import re from functools import partial CLASSES = ['0', '4'] def init_arff(f): ''' Initialize the .arff file f. That is, write the relation name and enumerate the attributes. ''' f.write('@relation {}\n\n'.format(RELATION_NAME)) for feature in FEATURES: f.write('@attribute {...
Python
zaydzuhri_stack_edu_python
function test_with_legacy_custom_evolutions self begin with call warns RemovedInDjangoEvolution30Warning as record begin set custom_evolutions = dict string my_app list string evolution1 string evolution2 with call override_settings CUSTOM_EVOLUTIONS=custom_evolutions begin assert equal CUSTOM_EVOLUTIONS dict string my...
def test_with_legacy_custom_evolutions(self): with pytest.warns(RemovedInDjangoEvolution30Warning) as record: custom_evolutions = { 'my_app': ['evolution1', 'evolution2'], } with override_settings(CUSTOM_EVOLUTIONS=custom_evolutions): self.ass...
Python
nomic_cornstack_python_v1
function pressed_key self key dt begin if key == LEFT begin set rotation = rotation - call spaceship_rotation dt end if key == RIGHT begin set rotation = rotation + call spaceship_rotation dt end if key == DOWN begin set x_speed = x_speed - call spaceship_acceleration_x dt rotation set y_speed = y_speed - call spaceshi...
def pressed_key(self, key, dt): if key == LEFT: self.rotation -= spaceship_rotation(dt) if key == RIGHT: self.rotation += spaceship_rotation(dt) if key == DOWN: self.x_speed -= spaceship_acceleration_x(dt, self.rotation) self.y_speed -= spaceship_a...
Python
nomic_cornstack_python_v1
function rss_items_to_list list_of_items begin set result = list for item in list_of_items begin set parsed_item = call item_to_dict item append result parsed_item end return result end function
def rss_items_to_list(list_of_items): result = [] for item in list_of_items: parsed_item = item_to_dict(item) result.append(parsed_item) return result
Python
nomic_cornstack_python_v1
comment coding=utf-8 comment Copyright 2018 The DisentanglementLib Authors. All rights reserved. comment Licensed under the Apache License, Version 2.0 (the "License"); comment you may not use this file except in compliance with the License. comment You may obtain a copy of the License at comment http://www.apache.org/...
# coding=utf-8 # Copyright 2018 The DisentanglementLib Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Un...
Python
zaydzuhri_stack_edu_python
function diag_values self begin return _hdiag end function
def diag_values(self) -> np.ndarray: return self._hdiag
Python
nomic_cornstack_python_v1
import requests import pandas as pd from py2neo import Graph , Node comment 最终挖掘到的字段名,分别为房间图片链接,房间街区名称,房间结构,到地铁站的距离,价格,房间细节,其他标签,房间的经纬度坐标 set colu_name = list string picture_link string title string subTitle string location string showPrice string detailDesc string 标签1 string 标签2 string 纬度 string 经度 comment 抓取到的蘑菇租房的ap...
import requests import pandas as pd from py2neo import Graph, Node # 最终挖掘到的字段名,分别为房间图片链接,房间街区名称,房间结构,到地铁站的距离,价格,房间细节,其他标签,房间的经纬度坐标 colu_name = ['picture_link', 'title', 'subTitle', 'location', 'showPrice', 'detailDesc', '标签1', '标签2', '纬度', '经度'] # 抓取到的蘑菇租房的api接口 url = 'https://api.mgzf.com/ro...
Python
zaydzuhri_stack_edu_python
function scrape_features features begin for feature in features begin set node = call get_or_create_vertex string FEATURE name=name description=description call get_or_create_edge node string CITATION tuple string FILE dict string name filename line=line call scrape_scenarios call walk_scenarios node if background is n...
def scrape_features(features): for feature in features: node = GRAPH.get_or_create_vertex( "FEATURE", name=feature.name, description=feature.description, ) GRAPH.get_or_create_edge( node, "CITATION", ( "...
Python
nomic_cornstack_python_v1
from fractions import Fraction from peluche_scratch import dummy_rectangle from production import cg class Matcher begin string Helper class used for evaluation optimization. An approximator recieves a polygon list and a matcher list before evaluation. The polygon numbers are 0-based indices in the initial polygon list...
from fractions import Fraction from peluche_scratch import dummy_rectangle from production import cg class Matcher: """ Helper class used for evaluation optimization. An approximator recieves a polygon list and a matcher list before evaluation. The polygon numbers are 0-based indices in the initial p...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 function make_album artist album tracks=string begin string Describes a music album. set retval = dict string artist artist ; string album album if tracks begin set retval at string tracks = tracks end return retval end function while true begin set artist = input string Enter the artist's...
#!/usr/bin/env python3 def make_album(artist, album, tracks=""): """Describes a music album.""" retval = {'artist': artist, 'album': album} if tracks: retval['tracks'] = tracks return retval while True: artist = input("\nEnter the artist's name (or enter 'q' to quit): ") if artist == ...
Python
zaydzuhri_stack_edu_python
from html.parser import HTMLParser class HTMLData extends HTMLParser begin function handle_comment self data begin call print_data string comment call getpos data end function function handle_starttag self tag attrs begin call print_data tag call getpos attrs end function function handle_endtag self tag begin call prin...
from html.parser import HTMLParser class HTMLData(HTMLParser): def handle_comment(self, data: str) -> None: self.print_data('comment', self.getpos(), data) def handle_starttag(self, tag: str, attrs): self.print_data(tag, self.getpos(), attrs) def handle_endtag(self, tag: str) -> None: ...
Python
zaydzuhri_stack_edu_python
string __author__=桃花寓酒寓美人 comment 1.类中的方法 string 类中的方法有3中:对象方法、类方法、静态方法 1)对象方法 a.怎么声明:直接生命在类中的函数 b.怎么调用:通过对象来调用 c.特点:自带一个参数self;self在调用的时候不用传参,指向当前对象 self -> 当前对象 d.什么时候用:如果实现函数的功能需要用到对象属性,这个函数就声明成对象方法 2)类方法 a.怎么声明:在函数声明前加@classmethod b.怎么调用:通过类来调用 c.特点:自带一个参数cls;cls在调用的时候不用传参,系统会自动将当前类传给cls cls -> 当前类(当前类能做的事情cls都可以做 ...
"""__author__=桃花寓酒寓美人""" # 1.类中的方法 """ 类中的方法有3中:对象方法、类方法、静态方法 1)对象方法 a.怎么声明:直接生命在类中的函数 b.怎么调用:通过对象来调用 c.特点:自带一个参数self;self在调用的时候不用传参,指向当前对象 self -> 当前对象 d.什么时候用:如果实现函数的功能需要用到对象属性,这个函数就声明成对象方法 2)类方法 a.怎么声明:在函数声明前加@classmethod b.怎么调用:通过类来调用 c.特点:自带一个参数cls;cls在调用的时候不用传参,系统会自动将当前类传给cls cls -> 当前类(当前类能做的事...
Python
zaydzuhri_stack_edu_python
function add_sales_per_customer historical test begin comment load historical - use this in data.py comment historical = pd.read_csv('./data/raw/train.csv') set data = mean group by historical string Store set loc at tuple slice : : string sales-per-customer = loc at tuple slice : : string Sales / loc at tuple sl...
def add_sales_per_customer(historical, test): # load historical - use this in data.py # historical = pd.read_csv('./data/raw/train.csv') data = historical.groupby('Store').mean() data.loc[:, 'sales-per-customer'] = data.loc[:, 'Sales'] / data.loc[:, 'Customers'] data = data.loc[:, ['Customers', 's...
Python
nomic_cornstack_python_v1
import sys import os import re import logging import traceback import csv from urllib.parse import urlparse import requests from bs4 import BeautifulSoup comment Logging call basicConfig level=INFO filename=join path directory name path __file__ string crawler.log format=string %(asctime)s::%(levelname)s::%(message)s c...
import sys import os import re import logging import traceback import csv from urllib.parse import urlparse import requests from bs4 import BeautifulSoup # Logging logging.basicConfig(level=logging.INFO, filename=os.path.join(os.path.dirname(__file__), 'crawler.log'), format='%(asctime)s::%(levelna...
Python
zaydzuhri_stack_edu_python
function test_complex_url self begin set url = string slug/42/foo/bar/ call create set request = call MagicMock set handle_path = string conman.routes.models.Route.handle with patch handle_path as handle begin set response = call route_router request url end call assert_called_with request string / + url assert equal r...
def test_complex_url(self): url = 'slug/42/foo/bar/' factories.RouteFactory.create() request = mock.MagicMock() handle_path = 'conman.routes.models.Route.handle' with mock.patch(handle_path) as handle: response = views.route_router(request, url) handle.assert...
Python
nomic_cornstack_python_v1
function insert self v p begin set root = call _insert root v p end function
def insert(self, v, p): self.root = self._insert(self.root, v, p)
Python
nomic_cornstack_python_v1
function binCoeffRec n k begin if k == 0 or n == k begin return 1 end return call binCoeffRec n - 1 k - 1 + call binCoeffRec n - 1 k end function function binCoeff n k begin set coeff = list comprehension list 0 * k + 1 for _ in call xrange n + 1 for i in call xrange n + 1 begin for j in call xrange min i k + 1 begin i...
def binCoeffRec(n, k): if k == 0 or n == k: return 1 return binCoeffRec(n-1, k-1) + binCoeffRec(n-1, k) def binCoeff(n, k): coeff = [[0]*(k+1) for _ in xrange(n+1)] for i in xrange(n+1): for j in xrange(min(i,k)+1): if j == 0 or j == i: ...
Python
zaydzuhri_stack_edu_python
for i in range length timetable begin append crew integer timetable at i at slice : 2 : * 60 + integer timetable at i at slice 3 : : end for times in range n begin comment 막차 if times == n - 1 begin if m <= length crew begin if final_bus < crew at 0 begin set con_time = final_bus end else begin set con_time = crew at...
for i in range(len(timetable)): crew.append(int(timetable[i][:2]) * 60 + int(timetable[i][3:])) for times in range(n): if times == (n-1): # 막차 if m <= len(crew): if final_bus < crew[0]: con_time = final_bus else: con_time = crew[m-1] - 1 ...
Python
zaydzuhri_stack_edu_python
function __init__ self glyphSet begin call __init__ set glyphSet = glyphSet end function
def __init__(self, glyphSet): super(DecomposingPen, self).__init__() self.glyphSet = glyphSet
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib.pyplot as plt import seaborn set col = array list 50 100 150 200 250 set transformations = array list 3438 14284 32110 56412 87163 plot col transformations x label string Dimensionality y label string Number of transformations show
import numpy as np import matplotlib.pyplot as plt import seaborn col = np.array([50,100,150,200,250]) transformations = np.array([3438,14284,32110,56412,87163]) plt.plot(col,transformations) plt.xlabel("Dimensionality") plt.ylabel("Number of transformations") plt.show()
Python
zaydzuhri_stack_edu_python
function event_m50_37_x92 z223=_ z222=_ begin string State 0,2: Host? if call IsGuest != 1 begin pass end else begin call Goto string L0 end string State 1: Is it already released? if call GetEventFlag z223 != 0 begin string State 3: Delete character call DeleteEnemyByGenerator z222 0 string State 5: Released return 1 ...
def event_m50_37_x92(z223=_, z222=_): """State 0,2: Host?""" if IsGuest() != 1: pass else: Goto('L0') """State 1: Is it already released?""" if GetEventFlag(z223) != 0: """State 3: Delete character""" DeleteEnemyByGenerator(z222, 0) """State 5: Released""" ...
Python
nomic_cornstack_python_v1
import chess import chess.pgn import time comment file where processed information goes set SAVE_FILE = string board_scores.txt set pgn = open string lichess/lichess_db_standard_rated_2019-08.pgn set run_time = integer input string Run for how long? (seconds) comment positions are stored in an array of dictionaries set...
import chess import chess.pgn import time #file where processed information goes SAVE_FILE = "board_scores.txt" pgn = open("lichess/lichess_db_standard_rated_2019-08.pgn") run_time = int(input("Run for how long? (seconds)")) positions = [] #positions are stored in an array of dictionaries #the FEN ...
Python
zaydzuhri_stack_edu_python
function concat_data_scale raw_dir all_files begin set isFirst = 1 for file in sorted all_files begin if isFirst == 1 begin comment read to a np arrau set concat_data = array values end else begin comment read to a np arrau set another_data = array values set concat_data = append np concat_data another_data axis=0 end ...
def concat_data_scale(raw_dir, all_files): isFirst = 1 for file in sorted(all_files): if isFirst == 1: concat_data = np.array(pd.read_csv(raw_dir + file, sep=',', header=None).values) # read to a np arrau else: another_data = np.array(pd.read_csv(raw_dir + file, sep=',',...
Python
nomic_cornstack_python_v1
from flask import Flask , Blueprint from flask_restful import Resource , Api , reqparse from repositories import user_repository as repository set user_blueprint = call Blueprint string user_api __name__ set user_api = call Api user_blueprint class UserCollection extends Resource begin function get self begin return ca...
from flask import Flask, Blueprint from flask_restful import Resource, Api, reqparse from repositories import user_repository as repository user_blueprint = Blueprint('user_api', __name__) user_api = Api(user_blueprint) class UserCollection(Resource): def get(self): return repository.get_users() user_api...
Python
zaydzuhri_stack_edu_python
string Refactoring exercises from email.parser import Parser try begin comment Some versions of Anaconda are missing IMAP4_SSL from imaplib import IMAP4_SSL end except ImportError begin pass end class Weekday begin string Class with attributes representing weekdays. end class class NextDate begin string Answers questio...
"""Refactoring exercises""" from email.parser import Parser try: # Some versions of Anaconda are missing IMAP4_SSL from imaplib import IMAP4_SSL except ImportError: pass class Weekday: """Class with attributes representing weekdays.""" class NextDate: """Answers questions about the next Monday/T...
Python
zaydzuhri_stack_edu_python
comment Write your code here :-) set a = true set b = false set c = false comment ✅ if a begin print string a is true end comment ❌ if a and b begin print string a and b are both true end comment ✅ if a or b begin print string a or b might be true end comment ❌ if b or c begin print string b and c are true end
# Write your code here :-) a = True b = False c = False #✅ if a: print('a is true') #❌ if a and b: print('a and b are both true') #✅ if a or b: print('a or b might be true') #❌ if b or c: print("b and c are true")
Python
zaydzuhri_stack_edu_python
function __init__ self begin if not call is_installed begin call install end else begin call load_users end end function
def __init__(self): if not self.is_installed(): self.install() else: self.load_users()
Python
nomic_cornstack_python_v1
function test_rshift_num_array_none_c1 self begin set inpvalue = inparray1a at 0 comment This version is expected to pass. call rshift inpvalue inparray2a maxlen=testmaxlen comment This is the actual test. with assert raises TypeError begin call rshift inpvalue inparray2b maxlen=string a end end function
def test_rshift_num_array_none_c1(self): inpvalue = self.inparray1a[0] # This version is expected to pass. arrayfunc.rshift(inpvalue, self.inparray2a, maxlen=self.testmaxlen) # This is the actual test. with self.assertRaises(TypeError): arrayfunc.rshift(inpvalue, self.inparray2b, maxlen='a')
Python
nomic_cornstack_python_v1
class LineBrain begin function __init__ self begin set new_horizontal_value = 0 set new_vertical_value = 0 end function function updating self new_x_value new_y_value begin try begin if new_x_value != new_vertical_value or new_y_value != new_horizontal_value begin set last__horizontalvalue = new_y_value set last_vertic...
class LineBrain(): def __init__(self): self.new_horizontal_value = 0 self.new_vertical_value = 0 def updating(self, new_x_value, new_y_value): try: if new_x_value != self.new_vertical_value or new_y_value != self.new_horizontal_value: self.last__horizontalva...
Python
zaydzuhri_stack_edu_python
function _get_config self begin return __config end function
def _get_config(self): return self.__config
Python
nomic_cornstack_python_v1
function trigger_next_execution message delay queue_name contextid begin set sqs = call resource string sqs try begin set queue = queue environ at queue_name comment Fifo messages can't be delayed arbitrarily, only its preset amount. if queue_name != string IGNITION_QUEUE_NAME begin call next_execution message=message ...
def trigger_next_execution(message: dict, delay: int, queue_name: str, contextid: str) -> None: sqs = boto3.resource('sqs') try: queue = sqs.Queue(os.environ[queue_name]) #Fifo messages can't be delayed arbitrarily, only its preset amount. if queue_name != 'IGNITION_QUEUE_NAME': ...
Python
nomic_cornstack_python_v1
function get_ssclient config begin return call Smartsheet config at string ss_access_token end function
def get_ssclient(config): return smartsheet.Smartsheet(config["ss_access_token"])
Python
nomic_cornstack_python_v1
set a = string input set a1 = upper a print a1
a=str(input()) a1=a.upper() print(a1)
Python
zaydzuhri_stack_edu_python
function ReleaseCapturePorts self *args **kwargs begin comment type: (*Any, **Any) -> None set payload = dict string Arg1 self for i in range length args begin set payload at string Arg%s % i + 2 = args at i end for item in items kwargs begin set payload at item at 0 = item at 1 end return call _execute string releaseC...
def ReleaseCapturePorts(self, *args, **kwargs): # type: (*Any, **Any) -> None payload = { "Arg1": self } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('releaseCapturePorts', payload=payl...
Python
nomic_cornstack_python_v1
function SingleQubitIRB_AC qubit seqFile begin comment Original: comment # Setup a pulse library comment pulseLib = [AC(qubit, cliffNum) for cliffNum in range(24)] comment pulseLib.append(pulseLib[0]) comment measBlock = MEAS(qubit) comment with open(seqFile,'r') as FID: comment fileReader = reader(FID) comment seqs = ...
def SingleQubitIRB_AC(qubit: qreg, seqFile): # Original: # # Setup a pulse library # pulseLib = [AC(qubit, cliffNum) for cliffNum in range(24)] # pulseLib.append(pulseLib[0]) # measBlock = MEAS(qubit) # with open(seqFile,'r') as FID: # fileReader = reader(FID) # seqs = [] #...
Python
nomic_cornstack_python_v1
function getBypass self begin return bypass end function
def getBypass(self): return self.bypass
Python
nomic_cornstack_python_v1
string links.py Illustrates finding embedded links. Uses regular expressions. Output: ====== $ python3 links2.py "http://chuckallison.com/cs1410/inx.html" Link: https://uvu.edu $ python3 links2.py "http://freshsources.com/page1.html" Link: http://freshsources.com/page2.html Link: http://freshsources.com/page5.html impo...
''' links.py Illustrates finding embedded links. Uses regular expressions. Output: ====== $ python3 links2.py "http://chuckallison.com/cs1410/inx.html" Link: https://uvu.edu $ python3 links2.py "http://freshsources.com/page1.html" Link: http://freshsources.com/page2.html Link: http://freshsources.com/page5.html ...
Python
zaydzuhri_stack_edu_python
string 1.9 Training Logistic Classifier Define the function softmax to compute the softmax probability values softmax(x) function should return a NumPy array of the same shape as x. import numpy as np set scores = list 3.0 1.0 0.2 function softmax x begin return exp x / sum exp x axis=0 end function
''' 1.9 Training Logistic Classifier Define the function softmax to compute the softmax probability values softmax(x) function should return a NumPy array of the same shape as x. ''' import numpy as np scores = [3.0, 1.0, 0.2] def softmax(x): return np.exp(x) / np.sum(np.exp(x), axis = 0)
Python
zaydzuhri_stack_edu_python
function get_general_info self begin set template_attrs = attrs set channel_id_attrs = attrs return call _create_Fast5Info template_attrs channel_id_attrs end function
def get_general_info(self): template_attrs = self._key_dict_flat['BaseCalled_template'].attrs channel_id_attrs = self._key_dict_flat['channel_id'].attrs return ResquiggledFAST5._create_Fast5Info(template_attrs, channel_id_attrs)
Python
nomic_cornstack_python_v1
comment 先用keys()方法把key值取出(成list形式), comment 然后在用','.join()方法转换成字符串输出。
# 先用keys()方法把key值取出(成list形式), # 然后在用','.join()方法转换成字符串输出。
Python
zaydzuhri_stack_edu_python
function get_players_names nb_player begin set name_list = list string Bobby string Johny string Suzan string Karen string Lauren string Anthony string Isa string Matthew string Pablo string Sofia if nb_player > length name_list begin print format string To many players not enough names, please choose a number of playe...
def get_players_names(nb_player): name_list = [ "Bobby", "Johny", "Suzan", "Karen", "Lauren", "Anthony", "Isa", "Matthew", "Pablo", "Sofia", ] if nb_player > len(name_list): print( "To many players not enough...
Python
nomic_cornstack_python_v1
function __init__ self num_nodes=6 params=list begin set nodes = list if num_nodes > 0 begin comment Offset the nodes so they don't start at 0. set offset = 360.0 / num_nodes / 2.0 for i in range num_nodes begin set deg = i * 360.0 / num_nodes + offset if params begin append nodes call MNode deg=deg params=params at i...
def __init__(self, num_nodes=6, params=[]): self.nodes = [] if(num_nodes > 0): offset = 360./num_nodes/2. # Offset the nodes so they don't start at 0. for i in range(num_nodes): deg = i*(360./num_nodes)+offset if params: ...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- from IPy import IP set ip = call IP string 192.168.0.1
# -*- coding: utf-8 -*- from IPy import IP ip = IP('192.168.0.1')
Python
zaydzuhri_stack_edu_python
function test_netcdf_write_names_keyword_as_str tmpdir begin set field = call RasterModelGrid tuple 4 3 call add_field string topographic__elevation array range 12.0 at=string node call add_field string uplift_rate array range 12.0 at=string node with call as_cwd begin call write_netcdf string test.nc field names=strin...
def test_netcdf_write_names_keyword_as_str(tmpdir): field = RasterModelGrid((4, 3)) field.add_field("topographic__elevation", np.arange(12.0), at="node") field.add_field("uplift_rate", np.arange(12.0), at="node") with tmpdir.as_cwd(): write_netcdf("test.nc", field, names="uplift_rate", format="...
Python
nomic_cornstack_python_v1
comment 데이터 로드와 사전처리 데이터 : TF. 텍스트 comment TensorFlow Text는 TensorFlow 2.0에서 사용할 준비가 된 텍스트 관련 클래스 및 작업 모음을 제공 comment 기반 모델에 필요한 사전 처리를 정기적으로 수행 할 수 있으며 comment 핵심 TensorFlow에서 제공하지 않는 시퀀스 모델링에 유용한 기타 기능을 포함 comment 목차 comment 1. 열렬한 실행 comment 2. 유니코드 comment 3. 토큰화 comment 4. 기타 텍스트 작업 comment 1. 열렬한 실행 comment Tenso...
# 데이터 로드와 사전처리 데이터 : TF. 텍스트 # TensorFlow Text는 TensorFlow 2.0에서 사용할 준비가 된 텍스트 관련 클래스 및 작업 모음을 제공 # 기반 모델에 필요한 사전 처리를 정기적으로 수행 할 수 있으며 # 핵심 TensorFlow에서 제공하지 않는 시퀀스 모델링에 유용한 기타 기능을 포함 # 목차 # 1. 열렬한 실행 # 2. 유니코드 # 3. 토큰화 # 4. 기타 텍스트 작업 # 1. 열렬한 실행 # TensorFlow Text에는 TensorFlow 2.0이 필요하며 eager 모드 및 그래프 모드와 완벽하게 호환됩 i...
Python
zaydzuhri_stack_edu_python