code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function add_class self label=none definition=none synonyms=tuple comment=none cid=none subClassOf=none predicates=none begin return call add_entity type=string term label=label definition=definition synonyms=synonyms comment=comment cid=cid subThingOf=subClassOf predicates=predicates end function
def add_class(self, label: str = None, definition: str = None, synonyms: tuple = tuple(), comment: str = None, cid: Union[str, int] = None, subClassOf: str = None, predicates: dict = None) -> Qu...
Python
nomic_cornstack_python_v1
function p_funct self yi p t begin global Cg set Cg = absolute yi at 0 global Ch set Ch = absolute yi at 1 global tin_g set tin_g = absolute yi at 2 global tin_h set tin_h = absolute yi at 3 set y = call state_at t set risk = 1 - y at - 1 at 0 + y at - 1 at 3 / sum y at - 1 return absolute risk - p end function
def p_funct(self, yi, p, t): global Cg Cg = abs(yi[0]) global Ch Ch = abs(yi[1]) global tin_g tin_g = abs(yi[2]) global tin_h tin_h = abs(yi[3]) y = state_at(t) risk = 1 - (y[-1][0] + y[-1][3]) / sum(y[-1]) return abs(risk - p)
Python
nomic_cornstack_python_v1
import math import numpy import random import typing import equipment import simulation class SmartSimulation extends simulation begin decorator staticmethod function weightedDistribution additional initialBuckets weights begin string Metaphorically speaking, we have a list of buckets that each contains some quantity o...
import math import numpy import random import typing import equipment import simulation class SmartSimulation(simulation.simulation): @staticmethod def weightedDistribution(additional: float, initialBuckets: typing.List[float], weights: typing.List[float]) -> typing.List[float]: """Metaphorically spea...
Python
zaydzuhri_stack_edu_python
function get_parent_images namespace_name repository_name image_obj begin set parents = ancestors comment Ancestors are in the format /<root>/<intermediate>/.../<parent>/, with each path section comment containing the database Id of the image row. set parent_db_ids = split strip parents string / string / if parent_db_i...
def get_parent_images(namespace_name, repository_name, image_obj): parents = image_obj.ancestors # Ancestors are in the format /<root>/<intermediate>/.../<parent>/, with each path section # containing the database Id of the image row. parent_db_ids = parents.strip("/").split("/") if parent_db_ids =...
Python
nomic_cornstack_python_v1
import numpy as np import pickle import pandas as pd from sklearn.decomposition import PCA from sklearn.cluster import KMeans set df_std = load pickle open string ./model/scaled_data.pkl string rb set names = load pickle open string ./model/names.pkl string rb set pca_flask = principal component analysis n_components=1...
import numpy as np import pickle import pandas as pd from sklearn.decomposition import PCA from sklearn.cluster import KMeans df_std= pickle.load(open('./model/scaled_data.pkl', 'rb')) names = pickle.load(open('./model/names.pkl', 'rb')) pca_flask = PCA(n_components=100) data_flask=pca_flask.fit_transform(df_std) k...
Python
zaydzuhri_stack_edu_python
comment CALCULATING POWER OF MATRIX using Numpy import numpy as np from numpy.linalg import matrix_power from numpy.linalg import multi_dot from numpy import * comment --------------------------------------------------------------------------EXAMPLE 1 (2*2 matrix) print string -----EXAMPLE 1----- set A = random integer...
#CALCULATING POWER OF MATRIX using Numpy import numpy as np from numpy.linalg import matrix_power from numpy.linalg import multi_dot from numpy import * #--------------------------------------------------------------------------EXAMPLE 1 (2*2 matrix) print("-----EXAMPLE 1-----") A=np.random.randint(10,size=(2,2)) answe...
Python
zaydzuhri_stack_edu_python
function from_dict cls dikt begin return call deserialize_model dikt cls end function
def from_dict(cls, dikt) -> 'SecurityNotification': return util.deserialize_model(dikt, cls)
Python
nomic_cornstack_python_v1
import sys append path argv at 0 at slice : - 6 : + string VF2/ import itertools as it import matplotlib.cbook import networkx as nx import time import warnings from vf import Vf filter warnings string ignore category=mplDeprecation comment Все возможные сочетания узлов list_nodes размера k function gen_combinations ...
import sys sys.path.append(sys.argv[0][:-6] + 'VF2/') import itertools as it import matplotlib.cbook import networkx as nx import time import warnings from vf import Vf warnings.filterwarnings("ignore", category=matplotlib.cbook.mplDeprecation) # Все возможные сочетания узлов list_nodes размера k def gen_combinati...
Python
zaydzuhri_stack_edu_python
function create path value=string acls=none ephemeral=false sequence=false makepath=false profile=none hosts=none scheme=none username=none password=none default_acl=none begin string Create Znode path path of znode to create value value to assign to znode (Default: '') acls list of acl dictionaries to be assigned (De...
def create(path, value='', acls=None, ephemeral=False, sequence=False, makepath=False, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Create Znode path path of znode to create value value to assign to znode (Default: '') acls...
Python
jtatman_500k
function extract_features self begin set feature_paths = dictionary for feat_type in outlier_feat_types begin try begin print format string Extracting feature type: {} feat_type set feature_paths at feat_type = call feature_extractor self feat_type end except any begin call print_exc print format string Unable to extra...
def extract_features(self): self.feature_paths = dict() for feat_type in self.outlier_feat_types: try: print('Extracting feature type: {}'.format(feat_type)) self.feature_paths[feat_type] = self.feature_extractor(self, feat_type) except: ...
Python
nomic_cornstack_python_v1
function _predict_lane self begin set binary_warped = call get_image set out_img = call dstack tuple binary_warped binary_warped binary_warped * 255 set nonzero = call nonzero set nonzeroy = array nonzero at 0 set nonzerox = array nonzero at 1 set margin = 100 set left_lane_indexes = nonzerox > _left_fit at 0 * nonzero...
def _predict_lane(self): binary_warped = self.binary_output.get_image() out_img = np.dstack((binary_warped, binary_warped, binary_warped))*255 nonzero = binary_warped.nonzero() nonzeroy = np.array(nonzero[0]) nonzerox = np.array(nonzero[1]) margin = 100 left_lane...
Python
nomic_cornstack_python_v1
function DefinePosition1 self begin comment if self.matchedword.dbid == 166728: comment import ipdb; ipdb.set_trace() if call DefinePositionMatch begin comment list the words dependents call ListDependentsRecursive matchedsentence comment For the source segment if call IsThisClauseInitial positionmatchword matchedsente...
def DefinePosition1(self): #if self.matchedword.dbid == 166728: #import ipdb; ipdb.set_trace() if self.DefinePositionMatch(): #list the words dependents self.positionmatchword.ListDependentsRecursive(self.matchedsentence) #For the source segment ...
Python
nomic_cornstack_python_v1
comment def game(n): comment global win comment if len(n) == 1: comment return win comment else: comment win *= -1 comment a = n[-1] + n[-2] comment if a < 10: comment n.pop(-1) comment n.pop(-1) comment n.append(a) comment elif a >= 10: comment n.pop(-1) comment n.pop(-1) comment n.append(a // 10) comment n.append(a %...
# def game(n): # global win # if len(n) == 1: # return win # else: # win *= -1 # a = n[-1] + n[-2] # if a < 10: # n.pop(-1) # n.pop(-1) # n.append(a) # elif a >= 10: # n.pop(-1) # n.pop(-1) # n.ap...
Python
zaydzuhri_stack_edu_python
function deutsch_algorithm oracle begin yield call X q1 yield tuple call H q0 call H q1 yield oracle yield call H q0 yield call measure q0 end function
def deutsch_algorithm(oracle): yield cirq.X(q1) yield cirq.H(q0), cirq.H(q1) yield oracle yield cirq.H(q0) yield cirq.measure(q0)
Python
nomic_cornstack_python_v1
function setup_mlflow run_name begin call set_tracking_uri string http://beetle.mlflow.kplabs.pl call set_experiment string cloud_detection call start_run run_name=run_name end function
def setup_mlflow(run_name: str): mlflow.set_tracking_uri("http://beetle.mlflow.kplabs.pl") mlflow.set_experiment("cloud_detection") mlflow.start_run(run_name=run_name)
Python
nomic_cornstack_python_v1
function setSymbol self *args begin return call InitialAssignment_setSymbol self *args end function
def setSymbol(self, *args): return _libsbml.InitialAssignment_setSymbol(self, *args)
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Wed Jun 17 23:59:51 2020 @author: Renan import os import math import matplotlib.pyplot as plt import matplotlib.ticker as tck import scipy.interpolate import numpy as np set f = 60 set vp = 5 set t = 0 comment ------ set w = 2 * pi * f set exp = 18 set bits = 2 ^ exp set ...
# -*- coding: utf-8 -*- """ Created on Wed Jun 17 23:59:51 2020 @author: Renan """ import os import math import matplotlib.pyplot as plt import matplotlib.ticker as tck import scipy.interpolate import numpy as np f=60 vp=5 t=0 #------ w=2*np.pi*f exp=18 bits=2**exp tempo=[] n=1 dt=(n/bits) #phi=-w*t fonte_tensao=...
Python
zaydzuhri_stack_edu_python
function _create_es_client self begin from elasticsearch._async.client import AsyncElasticsearch set use_basic_auth = _username is not none and _password is not none set serializer = call get_serializer if use_basic_auth begin set auth = tuple _username _password return call AsyncElasticsearch list _url http_auth=auth ...
def _create_es_client(self): from elasticsearch._async.client import AsyncElasticsearch use_basic_auth = self._username is not None and self._password is not None serializer = get_serializer() if use_basic_auth: auth = (self._username, self._password) return As...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding: utf-8 comment In[1]: comment pip install yfinance comment pip install PyPortfolioOpt comment pip install pulp comment In[94]: import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns call use string fivethirtyeight from datetime import dat...
#!/usr/bin/env python # coding: utf-8 # In[1]: #pip install yfinance #pip install PyPortfolioOpt #pip install pulp # In[94]: import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns plt.style.use('fivethirtyeight') from datetime import datetime import yfinance as yf # In[95...
Python
zaydzuhri_stack_edu_python
function is_good_response resp begin set content_type = lower headers at string Content-Type return status_code == 200 and content_type is not none and find content_type string html > - 1 end function
def is_good_response(resp): content_type = resp.headers['Content-Type'].lower() return (resp.status_code == 200 and content_type is not None and content_type.find('html') > -1)
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Wed Mar 11 12:50:33 2020 @author: cheerag.verma function spiralPrinting arr begin set rowStart = 0 set rowEnd = n set colStart = 0 set colEnd = m while rowStart < rowEnd and colStart < colEnd begin for j in range colStart colEnd begin print arr at rowStart at j end=string...
# -*- coding: utf-8 -*- """ Created on Wed Mar 11 12:50:33 2020 @author: cheerag.verma """ def spiralPrinting(arr): rowStart = 0 rowEnd = n colStart = 0 colEnd = m while rowStart<rowEnd and colStart<colEnd: for j in range(colStart,colEnd): print(ar...
Python
zaydzuhri_stack_edu_python
function update_time_dependent self dt begin if index == 7 begin return none end set current_time = current_time + dt if current_time >= animation_time begin set current_time = 0 set index = index + 1 % length images set image = images at index end end function
def update_time_dependent(self, dt): if self.index == 7: return None self.current_time += dt if self.current_time >= self.animation_time: self.current_time = 0 self.index = (self.index + 1) % len(self.images) self.image = self.images[self.index]
Python
nomic_cornstack_python_v1
function homeassistant_image self begin return environ at string HOMEASSISTANT_REPOSITORY end function
def homeassistant_image(self): return os.environ['HOMEASSISTANT_REPOSITORY']
Python
nomic_cornstack_python_v1
function act self states timestep add_noise=true begin return list comprehension call act call expand_dims state axis=0 timestep for tuple agent state in zip agents states end function
def act(self, states, timestep, add_noise=True): return [agent.act(np.expand_dims(state, axis=0), timestep) for agent, state in zip(self.agents, states)]
Python
nomic_cornstack_python_v1
function walk2 self **kwargs begin comment type: (str) -> Generator if not _initialized begin raise call PyCdlibInvalidInput string This object is not initialized; call either open() or new() to create an ISO end set num_paths = 0 for tuple key value in items kwargs begin if key in tuple string joliet_path string rr_pa...
def walk2(self, **kwargs): # type: (str) -> Generator if not self._initialized: raise pycdlibexception.PyCdlibInvalidInput('This object is not initialized; call either open() or new() to create an ISO') num_paths = 0 for key, value in kwargs.items(): if key in ('joliet_path'...
Python
nomic_cornstack_python_v1
string Coq files dependencies analysis. ..todo: Generalize multiprocessing to the whole pipeline. import copy import itertools import pandas as pd import networkx as nx import networkx.algorithms as al from os import path from functools import reduce , partial from concurrent.futures import ProcessPoolExecutor function...
"""Coq files dependencies analysis. ..todo: Generalize multiprocessing to the whole pipeline. """ import copy import itertools import pandas as pd import networkx as nx import networkx.algorithms as al from os import path from functools import reduce, partial from concurrent.futures import ProcessPoolExecutor def...
Python
zaydzuhri_stack_edu_python
function exec self **kwargs begin pass end function
def exec(self,**kwargs): pass
Python
nomic_cornstack_python_v1
comment _________________________SET UP_______________________________________________________ comment iterating over all other lines set w_index = 0 set h_index = 0 for i in range n_categories begin comment line is current ith line of input set line = list map int split input set k at i = line at 0 del line at 0 comme...
#_________________________SET UP_______________________________________________________ # iterating over all other lines w_index = 0 h_index = 0 for i in range(n_categories): line = list(map(int, input().split())) #line is current ith line of input k[i] = line[0] del line[0] # now working with only th...
Python
zaydzuhri_stack_edu_python
function validate_character_for_story_element sender instance action reverse pk_set *args **kwargs begin string Validates that character is from the same outline as the story node. if action == string pre_add begin if reverse begin for spk in pk_set begin set story_node = get objects pk=spk if outline != outline begin ...
def validate_character_for_story_element(sender, instance, action, reverse, pk_set, *args, **kwargs): ''' Validates that character is from the same outline as the story node. ''' if action == 'pre_add': if reverse: for spk in pk_set: story_node = StoryElementNode.obje...
Python
jtatman_500k
from itertools import permutations from collections import deque function init begin with open string input.txt string r as f begin set program = list comprehension integer c for c in split read f string , end return program end function function compute prog io output begin set i = 0 set op = list comprehension 0 for ...
from itertools import permutations from collections import deque def init(): with open("input.txt","r") as f: program = [int(c) for c in f.read().split(',')] return program def compute(prog,io,output): i = 0 op = [0 for n in range(2)] while i < len(prog): instr = prog[i] # ...
Python
zaydzuhri_stack_edu_python
function _make_file_path self classes_name sub_str sample_name subsub_str=none begin set mini_batch_dir = string pplp/data/mini_batches/iou_2d/panoptic/train/lidar if sample_name begin if subsub_str begin return mini_batch_dir + string / + classes_name + string [ + sub_str + string ]/ + subsub_str + string / + sample_n...
def _make_file_path(self, classes_name, sub_str, sample_name, subsub_str=None): mini_batch_dir = 'pplp/data/mini_batches/iou_2d/panoptic/train/lidar' if sample_name: if subsub_str: return mini_batch_dir + '/' + classes_name + \ '[' + sub_str + ']/' + \ ...
Python
nomic_cornstack_python_v1
function _build_G self begin call build_inputs call build_seq_embeddings call build_model call setup_global_step comment [batch_size, max_seq_len_this_batch, vocab_size] comment shp = tf.shape(self.logits) comment [batch_size, max_seq_len_this_batch] set caption_embedding_ids = call arg_max logits dimension=2 comment c...
def _build_G(self): self.build_inputs() self.build_seq_embeddings() self.build_model() self.setup_global_step() # [batch_size, max_seq_len_this_batch, vocab_size] # shp = tf.shape(self.logits) # [batch_size, max_seq_len_this_batch] self.caption_embedding...
Python
nomic_cornstack_python_v1
function GetTextHeightAtIndex self Index=defaultNamedNotOptArg begin return call InvokeTypes 5 LCID 1 tuple 5 0 tuple tuple 3 1 Index end function
def GetTextHeightAtIndex(self, Index=defaultNamedNotOptArg): return self._oleobj_.InvokeTypes(5, LCID, 1, (5, 0), ((3, 1),),Index )
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 string learning about NEO from NASA | chris.marquardt2@vzw.com import requests from pprint import pprint from datetime import datetime comment define api_key (read in from file) with open string neo.key as neokey begin set api_key = read neokey end comment lookup nasa api comment GET https...
#!/usr/bin/env python3 """learning about NEO from NASA | chris.marquardt2@vzw.com""" import requests from pprint import pprint from datetime import datetime ## define api_key (read in from file) with open("neo.key") as neokey: api_key = neokey.read() ## lookup nasa api ## GET https://api.nasa.gov/neo/rest/v1/fe...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt import math function plot_distribution_comparison histograms legend title begin string Plots a list of histograms with matching list of descriptions as the legend. :param histograms: list of histograms :param legend: list of matching histogram names :param title: plot title comment TODO:...
import matplotlib.pyplot as plt import math def plot_distribution_comparison(histograms, legend, title): """ Plots a list of histograms with matching list of descriptions as the legend. :param histograms: list of histograms :param legend: list of matching histogram names :param title: plot title ...
Python
zaydzuhri_stack_edu_python
function commit_message_from_addendum added_text begin comment TODO: use a grammar to parse the added_text, and therefore comment get a way better commit messaging. set COMMIT_MESSAGE_TEMPLATE = strip string {pioneer} discovered {name} at {date} Location: {location} set run_regex = lambda reg -> call groups 0 at 0 retu...
def commit_message_from_addendum(added_text:str) -> str: # TODO: use a grammar to parse the added_text, and therefore # get a way better commit messaging. COMMIT_MESSAGE_TEMPLATE = """ {pioneer} discovered {name} at {date} Location: {location} """.strip() run_regex = lambda reg: reg.search(added_t...
Python
nomic_cornstack_python_v1
function test_sync_no_archives_failure self begin set support = call SaltSupportModule set archives = call MagicMock return_value=list with raises SaltInvocationError as err begin call sync string group-name end assert string No archives found to transfer in string err end function
def test_sync_no_archives_failure(self): support = saltsupport.SaltSupportModule() support.archives = MagicMock(return_value=[]) with pytest.raises(salt.exceptions.SaltInvocationError) as err: support.sync("group-name") assert "No archives found to transfer" in str(err)
Python
nomic_cornstack_python_v1
function layer_sensitivity_profiling model val_dataloader cali_dataloader val_func criterion target_metric sensitivity_type qconfig metric_big_best backend args begin set t_model = deep copy model eval call distributed_model_not_ddp t_model args set device = device print string layer_sensitivity_profiling use device: {...
def layer_sensitivity_profiling(model: Module, val_dataloader: DataLoader, cali_dataloader: DataLoader, val_func, criterion: _Loss, target_metric: float, sensitivity_type: int, qconfig: QConfig, metric_big_best: bool, backend: str, args): t_model = cop...
Python
nomic_cornstack_python_v1
function fit_text self font_family=string Calibri max_size=18 bold=false italic=false font_file=none begin string Fit text-frame text entirely within bounds of its shape. Make the text in this text frame fit entirely within the bounds of its shape by setting word wrap on and applying the "best-fit" font size to all the...
def fit_text(self, font_family='Calibri', max_size=18, bold=False, italic=False, font_file=None): """Fit text-frame text entirely within bounds of its shape. Make the text in this text frame fit entirely within the bounds of its shape by setting word wrap on and applying the "b...
Python
jtatman_500k
function include self photo begin if photo in file begin return true end return false end function
def include(self, photo): if photo in self.file: return True return False
Python
nomic_cornstack_python_v1
import pandas as pd comment Field Names set fields = list string Symbol string Volume string Tweets comment Read in Ticker data set ticker_df = read csv string data/nyse_081821.csv comment Setup Filter for 2M in Volume set is_2M = ticker_df at string Volume >= 2000000 comment Apply Filter to capture symbols with at lea...
import pandas as pd #Field Names fields = ["Symbol", "Volume", "Tweets"] #Read in Ticker data ticker_df = pd.read_csv("data/nyse_081821.csv") #Setup Filter for 2M in Volume is_2M = ticker_df["Volume"] >= 2000000 #Apply Filter to capture symbols with at least 2M in Volume output = ticker_df[is_2M] final = output.sor...
Python
zaydzuhri_stack_edu_python
import os import json from flask import Flask , jsonify , request , g import flasgger import zmq import base64 set app = call Flask __name__ set swagger = call Swagger app comment connexion serveur zmq (service tokendealer port 7000) set context = call Context set socket = call socket REQ call connect string tcp://toke...
import os import json from flask import(Flask, jsonify, request, g) import flasgger import zmq import base64 app = Flask(__name__) swagger = flasgger.Swagger(app) # connexion serveur zmq (service tokendealer port 7000) context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect("tcp://tokendealer:7000") ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python import sys set oldKey = none set nodes = list set occurrences = 0 for line in stdin begin set data_mapped = split strip line string if length data_mapped != 2 begin comment Something has gone wrong. Skip this line. continue end set tuple thisKey node = data_mapped if oldKey and oldKey != thisK...
#!/usr/bin/python import sys oldKey = None nodes = [] occurrences = 0 for line in sys.stdin: data_mapped = line.strip().split("\t") if len(data_mapped) != 2: # Something has gone wrong. Skip this line. continue thisKey, node = data_mapped if oldKey and oldKey != thisKey: nod...
Python
zaydzuhri_stack_edu_python
string Get all the post paths import pathlib from bs4 import BeautifulSoup set here = call resolve set site = here / string site set sitemap = site / string sitemap.xml with open sitemap string r as file_ begin set contents = read file_ set soup = call BeautifulSoup contents string xml set locations = find all soup str...
''' Get all the post paths ''' import pathlib from bs4 import BeautifulSoup here = pathlib.Path(__file__).parent.resolve() site = here / 'site' sitemap = site / 'sitemap.xml' with open(sitemap, 'r') as file_: contents = file_.read() soup = BeautifulSoup(contents, "xml") locations = soup.find_all('loc') ...
Python
zaydzuhri_stack_edu_python
function check_valid_training_input self training_config begin for channel in training_config at string InputDataConfig begin call check_for_url channel at string DataSource at string S3DataSource at string S3Uri end end function
def check_valid_training_input(self, training_config): for channel in training_config['InputDataConfig']: self.check_for_url(channel['DataSource'] ['S3DataSource']['S3Uri'])
Python
nomic_cornstack_python_v1
function get_cache_prefix self prefix=string begin string Hook for any extra data you would like to prepend to your cache key. The default implementation ensures that ajax not non ajax requests are cached separately. This can easily be extended to differentiate on other criteria like mobile os' for example. if CACHE_MI...
def get_cache_prefix(self, prefix=''): """ Hook for any extra data you would like to prepend to your cache key. The default implementation ensures that ajax not non ajax requests are cached separately. This can easily be extended to differentiate on other criteria ...
Python
jtatman_500k
function navigation self begin set tuple text_from_xml ids eng_list = call get_text_from_xml string_xml string Navigation string trans-unit strip selected_language set xpath = call read_xpath_list_from_xml object_repo string Navigation my_object set lenth = length xpath set text_index = 0 set loop_index = 0 while loop_...
def navigation(self): text_from_xml, ids, eng_list = self.util.get_text_from_xml(self.string_xml, "Navigation", "trans-unit", Config.selected_language.strip()) xpath = self.util.read_xpath_list_from_xml(self.object_repo, "Navigation",...
Python
nomic_cornstack_python_v1
import re import collections import operator function open_file begin with open string mystem.xml encoding=string utf-8 as f begin set text = read f end return text end function function count_symbols text begin set n = 0 for line in text begin if string <w> or string <se> or string /se in line begin for symbol in line...
import re import collections import operator def open_file(): with open('mystem.xml', encoding='utf-8') as f: text = f.read() return text def count_symbols(text): n = 0 for line in text: if '<w>' or '<se>' or '/se' in line: for symbol in line: ...
Python
zaydzuhri_stack_edu_python
import sys function bitFlip c begin return if expression c == string 0 then string 1 else string 0 end function function flip s begin return join string list comprehension call bitFlip c for c in s end function function reverse s begin return join string list reversed s end function function getOp before after begin ...
import sys def bitFlip(c): return '1' if c == '0' else '0' def flip(s): return ''.join([bitFlip(c) for c in s]) def reverse(s): return ''.join(list(reversed(s))) def getOp(before, after): flipped = flip(before) rev = reverse(before) if before == after: return 'none' if after == r...
Python
zaydzuhri_stack_edu_python
class Solution begin function minMoves nums begin sort nums set mid = integer length nums / 2 set moves = 0 for i in range length nums begin set moves = moves + absolute nums at mid - nums at i end return moves end function end class
class Solution: def minMoves(nums): nums.sort() mid = int(len(nums)/2) moves = 0 for i in range(len(nums)): moves = moves + abs(nums[mid] - nums[i]) return(moves)
Python
zaydzuhri_stack_edu_python
from CpuScheduler import printOutput comment # # Sample input comment processList = [{"processId": 0, "arrivalTime": 0, "BurstTime": 3}, comment {"processId": 1, "arrivalTime": 2, "BurstTime": 6}, comment {"processId": 2, "arrivalTime": 4, "BurstTime": 4}, comment {"processId": 3, "arrivalTime": 6, "BurstTime": 5}, com...
from CpuScheduler import printOutput # # # Sample input # processList = [{"processId": 0, "arrivalTime": 0, "BurstTime": 3}, # {"processId": 1, "arrivalTime": 2, "BurstTime": 6}, # {"processId": 2, "arrivalTime": 4, "BurstTime": 4}, # {"processId": 3, "arrivalTime": 6, "...
Python
zaydzuhri_stack_edu_python
function test_read_python35_package begin set t = string Package: python3 Version: 3.5 Vim-Version: 35 Install: x86 C:\Python35 x64 C:\Python35 set f = call StringIO t set pkgs = read Package f call eq_ length pkgs 1 call eq_ name string python3 call eq_ version string 3.5 call eq_ vim_version string 35 set paths = cal...
def test_read_python35_package(): t = """ Package: python3 Version: 3.5 Vim-Version: 35 Install: x86 C:\Python35 x64 C:\Python35 """ f = StringIO(t) pkgs = Package.read(f) eq_(len(pkgs), 1) eq_(pkgs[0].name, 'python3') eq_(pkgs[0].version, '3.5') eq_(pkgs[0].vim_version, '35') paths = ...
Python
nomic_cornstack_python_v1
function prepare_surrogates self pool=none begin if pool == none begin set map_func = map end else begin set map_func = map end comment burst the time series set num_lats = length lats set num_lons = length lons set num_tm = length tm comment run the job in parallel set job_data = list comprehension tuple i j order_ran...
def prepare_surrogates(self, pool = None): if pool == None: map_func = map else: map_func = pool.map # burst the time series num_lats = len(self.lats) num_lons = len(self.lons) num_tm = len(self.tm) # run the job in paral...
Python
nomic_cornstack_python_v1
import json import os import re from datetime import datetime from pandas import ExcelWriter from pandas.io.json import json_normalize import scripts.logger_util as Logger from scripts.utils import get_configuration set logger = call get_logger __name__ set config = call get_configuration function write_to_file market_...
import json import os import re from datetime import datetime from pandas import ExcelWriter from pandas.io.json import json_normalize import scripts.logger_util as Logger from scripts.utils import get_configuration logger = Logger.get_logger(__name__) config = get_configuration() def write_to_file(market_type, ca...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- import os.path as path import sys from orcreader import OrcReader
#!/usr/bin/env python # -*- coding: utf-8 -*- import os.path as path import sys from orcreader import OrcReader
Python
zaydzuhri_stack_edu_python
function RemoveVirtualLayersFromWebkitLayoutTestName test_name begin set match = match test_name if match begin return call group 1 end return test_name end function
def RemoveVirtualLayersFromWebkitLayoutTestName(test_name): match = _VIRTUAL_LAYOUT_TEST_NAME_PATTERN.match(test_name) if match: return match.group(1) return test_name
Python
nomic_cornstack_python_v1
function relevant_complaints complaints complaints_accused t1 t2 begin set complaints at string incident_date = call to_datetime complaints at string incident_date set complaints_t1 = complaints at year >= t1 at 0 ? year <= t1 at 1 set complaints_t2 = complaints at year >= t2 at 0 ? year <= t2 at 1 set complaints_t1_fu...
def relevant_complaints(complaints, complaints_accused, t1, t2): complaints["incident_date"] = pd.to_datetime(complaints["incident_date"]) complaints_t1 = complaints[(complaints["incident_date"].dt.year >= t1[0]) & (complaints["incident_date"].dt.year <= t1[1])] complaints_t2 ...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string 62. KVS内の反復処理 60で構築したデータベースを用い,活動場所が「Japan」となっているアーティスト数を求めよ. import sys import plyvel function main db_source begin set n = 0 set artist_db = call DB db_source for tuple name area in artist_db begin if area == string Japan begin set n = n + 1 end end close artist_db end function
# -*- coding: utf-8 -*- """ 62. KVS内の反復処理 60で構築したデータベースを用い,活動場所が「Japan」となっているアーティスト数を求めよ. """ import sys import plyvel def main(db_source): n = 0 artist_db = plyvel.DB(db_source) for name,area in artist_db: if area == "Japan": n += 1 artist_db.close()
Python
zaydzuhri_stack_edu_python
class reader_writer begin function write_solution self file_path dict_result score begin set file = open file_path string w write file string length dict_result + string for library_id in keys dict_result begin set lib_num = string library_id set lib_books = dict_result at library_id set size = length lib_books set siz...
class reader_writer(): def write_solution(self, file_path, dict_result, score): file = open(file_path, "w") file.write(str(len(dict_result)) + '\n') for library_id in dict_result.keys(): lib_num = str(library_id) lib_books = dict_result[library_id] size =...
Python
zaydzuhri_stack_edu_python
function dataset_parameters self begin return get pulumi self string dataset_parameters end function
def dataset_parameters(self) -> Optional[str]: return pulumi.get(self, "dataset_parameters")
Python
nomic_cornstack_python_v1
function convertDnaListToString lst begin comment PUT YOUR IMPLEMENTATION HERE set curr = head set s = string while curr != none begin set s = s + string data set curr = next end return s end function
def convertDnaListToString(lst): # PUT YOUR IMPLEMENTATION HERE curr = lst.head s = '' while curr != None: s += str(curr.data) curr = curr.next return s
Python
nomic_cornstack_python_v1
comment print 1 to 50(normal method) comment lst=[] comment for i in range(1,51): comment lst.append(i) comment print(lst) comment using list comprehension set lst = list comprehension i for i in range 1 51 print lst
#print 1 to 50(normal method) # lst=[] # for i in range(1,51): # lst.append(i) # print(lst) #using list comprehension lst=[i for i in range(1,51)] print(lst)
Python
zaydzuhri_stack_edu_python
function from_name cls symb begin if is instance symb cls begin return symb end try begin set cache = __dict__ at string _str_to_op end except KeyError begin set _str_to_op = dict set cache = dict end try begin return cache at symb end except KeyError begin pass end for op in cls begin if value == symb begin set cach...
def from_name(cls, symb: Union[str, "Op"]) -> "Op": if isinstance(symb, cls): return symb try: cache = cls.__dict__["_str_to_op"] except KeyError: cls._str_to_op = cache = {} try: return cache[symb] except KeyError: pa...
Python
nomic_cornstack_python_v1
import re set regex = compile string pattern print start search string searching pattern in text..
import re regex = re.compile("pattern") print(regex.search("searching pattern in text..").start())
Python
zaydzuhri_stack_edu_python
import cv2 import math import numpy as np import tkinter comment Prevents root window from opening after file is selected from tkinter import Tk set root = call Tk call withdraw comment Select image to remove blemish from tkinter.filedialog import askopenfilename set filename = call askopenfilename set image = call imr...
import cv2 import math import numpy as np import tkinter # Prevents root window from opening after file is selected from tkinter import Tk root = Tk() root.withdraw() # Select image to remove blemish from tkinter.filedialog import askopenfilename filename = askopenfilename() image = cv2.imread(filename) output = ima...
Python
zaydzuhri_stack_edu_python
function setup cls client_id client_secret begin string Configure client in session set client_id = client_id set client_secret = client_secret end function
def setup(cls, client_id, client_secret): """Configure client in session """ cls.client_id = client_id cls.client_secret = client_secret
Python
jtatman_500k
function get_predominant_language from_lang=string txt=string to_lang=string begin set response = text return loads response at string translation at string from end function
def get_predominant_language(from_lang='', txt='', to_lang=''): response = requests.get((HOST + ENDPOINTTRANSLATE) % (from_lang, to_lang, txt[:500].replace('\r\n', ' '))).text return json.loads(response)['translation']['from']
Python
nomic_cornstack_python_v1
function get_weekly_track_chart self from_date=none to_date=none begin return call retrieve bind=Track flatten=string track params=dict string method string user.getWeeklyTrackChart ; string user name ; string from from_date ; string to to_date end function
def get_weekly_track_chart( self, from_date: str = None, to_date: str = None ) -> ListModel[Track]: return self.retrieve( bind=Track, flatten="track", params={ "method": "user.getWeeklyTrackChart", "user": self.name, ...
Python
nomic_cornstack_python_v1
async function export_to_prometheus matcher=query string * begin return call StreamingResponse call prometheus_export matcher media_type=string plain/text end function
async def export_to_prometheus(matcher: str = Query("*")) -> StreamingResponse: return StreamingResponse(prometheus_export(matcher), media_type="plain/text")
Python
nomic_cornstack_python_v1
function num1 begin set num_of_play = 1 set computer_point = 0 set human_point = 0 print string Welcome to the Snake, Water, Gun Game print string 3 times is more then enough to find who is best while num_of_play <= 3 begin set play_num = integer input string type 1 for Snake type 2 for Water type 3 for Gun if play_num...
def num1(): num_of_play = 1 computer_point = 0 human_point = 0 print("Welcome to the Snake, Water, Gun Game\n") print("3 times is more then enough to find who is best\n") while (num_of_play <= 3): play_num = int(input(" type 1 for Snake \n type 2 for Water \n type 3 for Gun \n")) ...
Python
zaydzuhri_stack_edu_python
function serialize path corpus begin info string Writing txt= { path } with open path string w+ as f_out begin for line in corpus begin write f_out line end end end function
def serialize(path: str, corpus: iCorpus): log.info(f'Writing txt={path}') with open(path, 'w+') as f_out: for line in corpus: f_out.write(line)
Python
nomic_cornstack_python_v1
function push self task backends_ctx begin raise call NotImplementedError end function
def push(self, task, backends_ctx): raise NotImplementedError()
Python
nomic_cornstack_python_v1
import os import shutil set path = string /home/python/ set names = list directory path set folder_name = list string music string video string file string picture for x in range 0 4 begin if not exists path path + folder_name at x begin make directories path + folder_name at x end end for files in names begin if strin...
import os import shutil path = "/home/python/" names = os.listdir(path) folder_name = ['music','video','file','picture'] for x in range(0,4): if not os.path.exists(path+folder_name[x]): os.makedirs(path+folder_name[x]) for files in names: if ".mp3" in files and not os.path.exists(path+'music/'+files): ...
Python
zaydzuhri_stack_edu_python
function finder files queries begin set store = dict for directory in files begin set dir_splitted = split directory string / for i in range length dir_splitted begin if dir_splitted at i != string begin if dir_splitted at i in store begin set store at dir_splitted at i = store at dir_splitted at i + list join string...
def finder(files, queries): store = {} for directory in files: dir_splitted = directory.split('/') for i in range(len(dir_splitted)): if dir_splitted[i] != '': if dir_splitted[i] in store: store[dir_splitted[i]] += ['/'.join(dir_splitted[:i+1])] ...
Python
zaydzuhri_stack_edu_python
function job_flows_to_stats job_flows now=none begin comment stats for all job flows set s = dict set s at string flows = list comprehension call job_flow_to_full_summary job_flow now=now for job_flow in job_flows comment total usage for nih_type in tuple string nih_billed string nih_used string nih_bbnu begin set s a...
def job_flows_to_stats(job_flows, now=None): s = {} # stats for all job flows s['flows'] = [job_flow_to_full_summary(job_flow, now=now) for job_flow in job_flows] # total usage for nih_type in ('nih_billed', 'nih_used', 'nih_bbnu'): s[nih_type] = float(sum(jf[nih_typ...
Python
nomic_cornstack_python_v1
function test_get self begin call _test_pre_redirect set response = get client login_begin_url query_string=REQUEST_DATA call _test_redirect response end function
def test_get(self): self._test_pre_redirect() response = self.client.get(self.login_begin_url, query_string=REQUEST_DATA) self._test_redirect(response)
Python
nomic_cornstack_python_v1
function __init__ self begin set DIMENSION = 0 set TOTAL_GRIDS = 1 set dense_threshold = 3.0 set sparse_threshold = 0.8 set time_gap = 0 set decay_factor = 0.998 set correlation_threshold = 0.0 set latestCluster = 0 end function
def __init__(self): self.DIMENSION = 0 self.TOTAL_GRIDS = 1 self.dense_threshold = 3.0 self.sparse_threshold = 0.8 self.time_gap = 0 self.decay_factor = 0.998 self.correlation_threshold = 0.0 self.latestCluster = 0
Python
nomic_cornstack_python_v1
comment 18.6 - Control Layout With Geometry Managers comment Review Exercise #2 comment NOTE: The first exercise in this section is instructional and does comment not require a solution to be shown here. For this reason, only the comment solution to the second exercise is presented. import tkinter as tk comment Create ...
# 18.6 - Control Layout With Geometry Managers # Review Exercise #2 # NOTE: The first exercise in this section is instructional and does # not require a solution to be shown here. For this reason, only the # solution to the second exercise is presented. import tkinter as tk # Create a new window with the title "Add...
Python
zaydzuhri_stack_edu_python
function _load_namespace filename begin set data = load yaml call read_text set namespace = data at string regionMap set df = call from_dict namespace orient=string index set name = string standardCode set df at string namespace = data at string name return df end function
def _load_namespace(filename: Path) -> pandas.DataFrame: data = yaml.load(filename.read_text()) namespace = data['regionMap'] df = pandas.DataFrame.from_dict(namespace, orient = 'index') df.index.name = 'standardCode' df['namespace'] = data['name'] return df
Python
nomic_cornstack_python_v1
function __call__ self max_iter=20000 spread=0.0001 start_samples=list begin set nsteps = 1000 comment Start walkers in a tight random ball if length start_samples == 0 begin comment Do this in the case of KDE set pos = array list comprehension start + randn ndim * spread for i in range nwalkers end else begin comment ...
def __call__(self, max_iter=20000, spread=1e-4, start_samples=[]): nsteps = 1000 # Start walkers in a tight random ball if len(start_samples) == 0: # Do this in the case of KDE pos = np.array([self.start + (np.random.randn(self.ndim) * spread) for i in range(sel...
Python
nomic_cornstack_python_v1
function Flush *args **kwargs begin return call GraphicsContext_Flush *args keyword kwargs end function
def Flush(*args, **kwargs): return _gdi_.GraphicsContext_Flush(*args, **kwargs)
Python
nomic_cornstack_python_v1
function Add self failureSimulationKey failureSimulationFile=string failureSimulationPort=string begin set callResult = call _Call string Add failureSimulationKey failureSimulationFile failureSimulationPort if callResult is none begin return none end set objId = callResult set classInstance = FailureSimulation return ...
def Add(self, failureSimulationKey, failureSimulationFile='', failureSimulationPort=''): callResult = self._Call("Add", failureSimulationKey, failureSimulationFile, failureSimulationPort) if callResult is None: return None objId = callResult classInstance = FailureSimulati...
Python
nomic_cornstack_python_v1
function set_output_file self outputPath begin set output_file = outputPath end function
def set_output_file(self, outputPath): self.output_file = outputPath
Python
nomic_cornstack_python_v1
from question_model import Question from data import question_data from quiz_brain import QuizBrain set question_bank = list for question in question_data begin set question_text = question at string text set question_answer = question at string answer set new_question = call Question question_text question_answer app...
from question_model import Question from data import question_data from quiz_brain import QuizBrain question_bank = [] for question in question_data: question_text = question["text"] question_answer = question["answer"] new_question = Question(question_text, question_answer) question_bank.appe...
Python
zaydzuhri_stack_edu_python
function dump_graph self writer begin writer string digraph %s_dfa { % name for tuple i state in enumerate states begin writer string %d [label="State %d %s"]; % tuple i i is_final and string (final) or string for tuple label next in sorted items arcs begin writer string %d -> %d [label=%s]; % tuple i index states next...
def dump_graph(self, writer): writer('digraph %s_dfa {\n' % self.name) for i, state in enumerate(self.states): writer(' %d [label="State %d %s"];\n' % (i, i, state.is_final and "(final)" or "")) for label, next in sorted(state.arcs.items()): writer(" %d -> %d [lab...
Python
nomic_cornstack_python_v1
comment !/bin/python3 import sys function marsExploration s begin comment Complete this function if length s % 3 != 0 begin return none end set n_msg = length s / 3 set cntr = 0 for i in range 0 length s 3 begin set tmp = s at slice i : i + 3 : if tmp at 0 != string S begin set cntr = cntr + 1 end if tmp at 1 != strin...
#!/bin/python3 import sys def marsExploration(s): # Complete this function if len(s) % 3 != 0: return None n_msg = len(s) / 3 cntr = 0 for i in range(0, len(s), 3): tmp = s[i:i + 3] if tmp[0] != 'S': cntr += 1 if tmp[1] != 'O': cntr += 1 ...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt import numpy as np import scipy from scipy.interpolate import griddata from mpi4py import MPI set comm = COMM_WORLD set size = call Get_size set rank = call Get_rank class SolverWrapper begin string Additional functionality to the C++ Python binding. The C++ class derived from SolverBase...
import matplotlib.pyplot as plt import numpy as np import scipy from scipy.interpolate import griddata from mpi4py import MPI; comm = MPI.COMM_WORLD; size = comm.Get_size(); rank = comm.Get_rank() class SolverWrapper(): """ Additional functionality to the C++ Python binding. The C++ class derived fr...
Python
zaydzuhri_stack_edu_python
function _ event begin call insert_text string end function
def _(event: E) -> None: event.app.current_buffer.insert_text(" ")
Python
nomic_cornstack_python_v1
function __call__ self example begin return call test example end function
def __call__(self, example): return self.test(example)
Python
nomic_cornstack_python_v1
function from_pascal_case name begin return lower sub string \1_\2 name end function
def from_pascal_case(name): return CAP_RE.sub(r"\1_\2", name).lower()
Python
nomic_cornstack_python_v1
import heapq set tuple n k = map int split input set dp = list 10 ^ 9 * n + 1 set dp at 1 = 0 set que = list 1 call heapify que while length que begin set cur = call heappop que if cur * 2 <= n and dp at cur + 1 < dp at cur * 2 begin set dp at cur * 2 = dp at cur + 1 call heappush que cur * 2 end if cur + 3 <= n and dp...
import heapq n, k = map(int, input().split()) dp = [10 ** 9] * (n + 1) dp[1] = 0 que = [1] heapq.heapify(que) while len(que): cur = heapq.heappop(que) if cur * 2 <= n and dp[cur] + 1 < dp[cur * 2]: dp[cur * 2] = dp[cur] + 1 heapq.heappush(que, cur * 2) if cur + 3 <= n and dp[cur] + 1 < dp[...
Python
zaydzuhri_stack_edu_python
function __init__ self batery_size=75 begin set batery_size = batery_size end function
def __init__(self,batery_size = 75): self.batery_size = batery_size
Python
nomic_cornstack_python_v1
comment Gaussian distribution function randsteps n begin import random return sum list comprehension random choice tuple - 1 0 1 for i in range n end function comment Final counting with orinting. "n" for number of random steps, "m" for number of overall repiting function distrib n m begin comment randsteps(n) from abo...
# Gaussian distribution def randsteps(n): import random return sum([random.choice((-1,0,1)) for i in range(n)]) # Final counting with orinting. "n" for number of random steps, "m" for number of overall repiting def distrib(n,m): allr = [randsteps(n) for i in range(m)] #randsteps(n) from above for i in r...
Python
zaydzuhri_stack_edu_python
function setValue self value begin set exact_value = value comment If a new min/max is necessary: Set it to twice the value, to give user leeway if value > _max_value begin comment If the slider range is fixed: Set it to the maximum possible value if fixed_range begin set value = call maximum end else comment In the od...
def setValue(self, value): self.exact_value = value # If a new min/max is necessary: Set it to twice the value, to give user leeway if value > self._max_value: # If the slider range is fixed: Set it to the maximum possible value if self.fixed_range: value ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import rospy from geometry_msgs.msg import Twist import keyboard set spd = 0.5 set trn = 0.3 set mov = call Twist set msg = string Segue a linha de jogos de computador, em tese: Movimentos direcionais: w: vai para frente s: para tras a: esquerda d: direita space_bar: sobe ctrl: desce Movime...
#!/usr/bin/env python import rospy from geometry_msgs.msg import Twist import keyboard spd = 0.5 trn = 0.3 mov = Twist() msg=""" Segue a linha de jogos de computador, em tese: Movimentos direcionais: w: vai para frente s: para tras a: esquerda d: direita space_bar: sobe...
Python
zaydzuhri_stack_edu_python
import logging set logger = call getLogger string Training call setLevel INFO call basicConfig format=string %(levelname)s %(asctime)s : %(message)s level=INFO import ipdb as pdb from ipdb import slaunch_ipdb_on_exception import pandas as pd import numpy as np from rouge import Rouge from text_encoders import NNLM , Wo...
import logging logger = logging.getLogger("Training") logger.setLevel(logging.INFO) logging.basicConfig(format='%(levelname)s %(asctime)s : %(message)s', level=logging.INFO) import ipdb as pdb from ipdb import slaunch_ipdb_on_exception import pandas as pd import numpy as np from rouge import Rouge from text_encoders im...
Python
zaydzuhri_stack_edu_python
function _has_vowel self word begin set vowel_pattern = compile string [aeiouR] return boolean search call _capitalize_syllabic_r word end function
def _has_vowel(self, word): vowel_pattern = re.compile('[aeiouR]') return bool(vowel_pattern.search(self._capitalize_syllabic_r(word)))
Python
nomic_cornstack_python_v1
from set1.fixed_xor import fixed_xor function test_challenge_should_match begin comment GIVEN set hex_str_1 = string 1c0111001f010100061a024b53535009181c set hex_str_2 = string 686974207468652062756c6c277320657965 comment WHEN set actual = call fixed_xor hex_str_1 hex_str_2 comment THEN assert actual == string 74686520...
from set1.fixed_xor import fixed_xor def test_challenge_should_match(): # GIVEN hex_str_1 = '1c0111001f010100061a024b53535009181c' hex_str_2 = '686974207468652062756c6c277320657965' # WHEN actual = fixed_xor(hex_str_1, hex_str_2) # THEN assert actual == '746865206b696420646f6e277420706c6...
Python
zaydzuhri_stack_edu_python
from graphics import * from a_star import * function paint matriz inicio final bloques begin set win = call GraphWin string Floor 500 500 call setCoords 0.0 0.0 length matriz length matriz call setBackground string white comment pinta un grid inicial for x in range length matriz begin for y in range length matriz at 0 ...
from graphics import * from a_star import * def paint(matriz, inicio, final,bloques): win = GraphWin('Floor', 500, 500) win.setCoords(0.0, 0.0, len(matriz), len(matriz)) win.setBackground("white") #pinta un grid inicial for x in range(len(matriz)): for y in range(len(matriz[0])): square = Rectangle(Poi...
Python
zaydzuhri_stack_edu_python
comment -*- coding:utf-8 -*- import json from datetime import date from marshmallow import fields , ValidationError from werkzeug import datastructures class FormDict extends Field begin function _deserialize self value attr data begin string 從 Form 的 location 反序列化 json 格式的資料為字典 if value is none begin return none end i...
# -*- coding:utf-8 -*- import json from datetime import date from marshmallow import fields, ValidationError from werkzeug import datastructures class FormDict(fields.Field): def _deserialize(self, value, attr, data): """ 從 Form 的 location 反序列化 json 格式的資料為字典 """ if value is None: ...
Python
zaydzuhri_stack_edu_python