code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function from_name cls name begin string Create a new Language instance from a name as string :param name: name as string :return: Language instance with instance.name() == name if name is valid else instance of UnknownLanguage set name = lower string name if name is string unknown or name is call _ string unknown begi...
def from_name(cls, name): """ Create a new Language instance from a name as string :param name: name as string :return: Language instance with instance.name() == name if name is valid else instance of UnknownLanguage """ name = str(name).lower() if name is 'unknow...
Python
jtatman_500k
comment -*- coding: utf-8 -*- comment 姓名:zry comment @time: 2021/2/21 22:44 comment @File: 3_6_0class.py comment 类是对象的抽象集合,对象是类的具体表现 comment 类class是描述具有相同属性和方法的对象的集合,它定义了该集合中每个对象所共有的属性和方法 comment 数据成员(属性):类的不同属性数据,所有类中的变量称为属性 comment 对象:对象是类的实例 comment 方法:类中定义的函数,实现相关的功能 class Student begin comment 类属性或类变量,所有类的实例化对象都同时...
# -*- coding: utf-8 -*- # 姓名:zry # @time: 2021/2/21 22:44 # @File: 3_6_0class.py # 类是对象的抽象集合,对象是类的具体表现 # 类class是描述具有相同属性和方法的对象的集合,它定义了该集合中每个对象所共有的属性和方法 # 数据成员(属性):类的不同属性数据,所有类中的变量称为属性 # 对象:对象是类的实例 # 方法:类中定义的函数,实现相关的功能 class Student(): name = 'yourname' # 类属性或类变量,所有类的实例化对象都同时共享类变量 color = 'yellow' def __i...
Python
zaydzuhri_stack_edu_python
function plot_I1 i1Grid axes vmin=3.0 vmax=3.05 cmap=string PuBuGn begin image show i1Grid interpolation=string bicubic extent=tuple 0 1 1 0 cmap=cmap aspect=7.0 / 8.0 vmin=vmin vmax=vmax set interp_scale = 8 set Z = call zoom i1Grid interp_scale set xi = linear space 0.0 1.0 8 * interp_scale set yi = linear space 0.0 ...
def plot_I1(i1Grid, axes, vmin=3.0, vmax=3.05, cmap='PuBuGn'): axes.imshow(i1Grid, interpolation='bicubic', extent=(0, 1, 1, 0), cmap=cmap, aspect=(7.0/8.0), vmin=vmin, vmax=vmax) interp_scale = 8 Z = zoom(i1Grid, interp_scale) xi = linspace(0.0, 1.0, 8 * interp_scale) yi = linspace(0.0, 1.0...
Python
nomic_cornstack_python_v1
function encode_capped_sample_pair vocab text cap=512 begin set enc = lambda x -> call sample_encode_as_ids x - 1 0.5 comment first try set tuple src tgt = tuple call enc text call enc text if length src <= cap and length tgt <= cap begin return tuple src tgt end comment sentence split and guess the number of sentences...
def encode_capped_sample_pair(vocab, text, cap= 512): enc = lambda x: vocab.sample_encode_as_ids(x, -1, 0.5) # first try src, tgt = enc(text), enc(text) if len(src) <= cap and len(tgt) <= cap: return src, tgt # sentence split and guess the number of sentences that fit sents = sent_tokenize(text)...
Python
nomic_cornstack_python_v1
comment WRITE YOUR CODE IN THIS FILE comment define function comment add parameters function countA x begin set x = lower x set z = 0 for i in range 0 length x begin if x at i == string a begin set z = z + 1 end end return z end function comment run function print call countA string apple
#WRITE YOUR CODE IN THIS FILE #define function #add parameters def countA(x): x = x.lower() z = 0 for i in range (0, len(x)): if x[i] == 'a': z = z + 1 return z #run function print(countA("apple"))
Python
zaydzuhri_stack_edu_python
from sys import argv function main begin comment TODO set file_name = string set max_arguments = 2 if length argv is not max_arguments begin print string Usage: python bleep.py dictionary exit 1 end else begin set file_name = argv at 1 end set message = split input string What message would you like to censor? set dic...
from sys import argv def main(): # TODO file_name = "" max_arguments = 2 if len(argv) is not max_arguments: print("Usage: python bleep.py dictionary") exit(1) else: file_name = argv[1] message = input("What message would you like to censor?\n").split() dict_file...
Python
zaydzuhri_stack_edu_python
function test_view_profile self begin call login username=string username3 password=string password set interviewee = first filter username=string username3 set view_profile = get client reverse string main:view_profile assert equal status_code 200 call assertContains view_profile string First Name call assertContains ...
def test_view_profile(self): self.client.login(username='username3', password='password') interviewee = User.objects.filter(username= 'username3').first() view_profile = self.client.get(reverse('main:view_profile')) self.assertEqual(view_profile.status_code, 200) self.assertConta...
Python
nomic_cornstack_python_v1
set string = string Hello, World! print string
string = "Hello, World!" print (string)
Python
zaydzuhri_stack_edu_python
function grid_shape config begin set size = call grid_size config return tuple size size size call num_channels config end function
def grid_shape(config): size = grid_size(config) return (size, size, size, num_channels(config))
Python
nomic_cornstack_python_v1
import os import csv import re function write_csv data file_name begin set fieldnames = list string post with open file_name string a newline=string encoding=string utf-8-sig as f begin comment print(data) set writer = dict writer f fieldnames=fieldnames for note in data begin comment print(note) write row writer note...
import os import csv import re def write_csv(data, file_name): fieldnames = ['post'] with open(file_name, 'a', newline='', encoding='utf-8-sig') as f: #print(data) writer = csv.DictWriter(f, fieldnames=fieldnames) for note in data: #print(note) writer.writerow(note) def csv_dict_reader(data_set): arr=...
Python
zaydzuhri_stack_edu_python
function delete_subscription self request=none subscription=none retry=DEFAULT timeout=none metadata=tuple begin comment Create or coerce a protobuf request object. comment Sanity check: If we got a request object, we should *not* have comment gotten any keyword arguments that map to the request. if request is not none...
def delete_subscription(self, request: pubsub.DeleteSubscriptionRequest = None, *, subscription: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: ...
Python
nomic_cornstack_python_v1
function validate_format self begin return all list call validate_header_keyword call validate_type_keyword call validate_type_annotations call validate_unique_header call validate_against_header_count end function
def validate_format(self): return all( [ self.validate_header_keyword(), self.validate_type_keyword(), self.validate_type_annotations(), self.validate_unique_header(), self.validate_against_header_count(), ] ...
Python
nomic_cornstack_python_v1
function geopotential_at_model_levels dlnp Tv Z0 alpha levs z_axis=1 t_axis=0 begin comment Move z_axis to front set _dlnp = call moveaxis dlnp z_axis 0 set _Tv = call moveaxis Tv z_axis 0 set _alpha = call moveaxis alpha z_axis 0 set t_axis = if expression t_axis < z_axis then t_axis + 1 else t_axis comment Geopotenti...
def geopotential_at_model_levels(dlnp, Tv, Z0, alpha, levs, z_axis=1, t_axis=0): # Move z_axis to front _dlnp = np.moveaxis(dlnp, z_axis, 0) _Tv = np.moveaxis(Tv, z_axis, 0) _alpha = np.moveaxis(alpha, z_axis, 0) t_axis = t_axis+1 if t_axis < z_axis else t_axis # Geopotential jump over...
Python
nomic_cornstack_python_v1
function get_cleaned_fully_merged_messages strip_html_content=true resolve_fb_id=false begin if not _messages_file begin print string Please initialize the facebook_connector module. return end set chats = none with open _messages_file mode=string rt encoding=string utf-8 as handle begin set chats = parse parser handle...
def get_cleaned_fully_merged_messages(strip_html_content=True, resolve_fb_id=False): if not _messages_file: print("Please initialize the facebook_connector module.") return chats = None with io.open(_messages_file, mode="rt", encoding="utf-8") as handle:...
Python
nomic_cornstack_python_v1
import math import numpy as np class Diagnostic_assessment begin string Расчет оценки достоверности диагностики. Вычисляются оценки первого и второго рода. Для этого вычисляются: расстояние Махаланобиса, стандартное отклонение 1, 2 и функции от них, а именно экспонента и интеграл Лапласа function __init__ self a1 a2 in...
import math import numpy as np class Diagnostic_assessment: ''' Расчет оценки достоверности диагностики. Вычисляются оценки первого и второго рода. Для этого вычисляются: расстояние Махаланобиса, стандартное отклонение 1, 2 и функции от них, а именно экспонента и интеграл Лапласа ''' def __init__(s...
Python
zaydzuhri_stack_edu_python
function send cls nid data timestamp=none begin if call has_key nid begin if data begin for tuple val typ in zip data nodes at nid at string data begin call _output nid val typ timestamp end end end end function
def send(cls, nid, data, timestamp=None): if nodes.has_key(nid): if data: for val, typ in zip(data, nodes[nid]['data']): cls._output(nid, val, typ, timestamp)
Python
nomic_cornstack_python_v1
function update_archive self population offsprings generation begin comment Get list of ordered indexes according to selection strategy if selection_operator == string random begin set idx = list range size shuffle random idx end else if selection_operator == string best begin set performances = offsprings at update_cr...
def update_archive(self, population, offsprings, generation): # Get list of ordered indexes according to selection strategy if self.params.selection_operator == 'random': idx = list(range(offsprings.size)) np.random.shuffle(idx) elif self.params.selection_operator == 'best': performances =...
Python
nomic_cornstack_python_v1
import matplotlib.pyplot as plt function chart_learning_rate x training_accuracy test_accuracy begin string Author: Mike Allen :param: x, training_accuracy, test_accuracy :return: figure comment x = results['n'] comment results['training_accuracy'] set y1 = training_accuracy comment results['test_accuracy'] set y2 = te...
import matplotlib.pyplot as plt def chart_learning_rate(x, training_accuracy, test_accuracy): """ Author: Mike Allen :param: x, training_accuracy, test_accuracy :return: figure """ # x = results['n'] y1 = training_accuracy # results['training_accuracy'] y2 = test_accuracy ...
Python
zaydzuhri_stack_edu_python
function az_stone_policy_head input normalization nonl boardsize actionsize begin set net = call nonl call normalization conv 2d input filters=2 kernel_size=list 1 1 padding=string same set logits = dense reshape tf net list - 1 boardsize * boardsize * 2 actionsize return logits end function
def az_stone_policy_head(input, normalization, nonl, boardsize, actionsize): net = nonl((normalization(tf.layers.conv2d(input, filters=2, kernel_size=[1, 1], padding="same")))) logits = tf.layers.dense(tf.reshape(net, [-1, boardsize * boardsize * 2]), actionsize) return logits
Python
nomic_cornstack_python_v1
comment ---------------------------------------------------------------------- comment centralities comment Computes centralities of graphs comment Author: Emanuele Pesce comment ---------------------------------------------------------------------- import networkx as nx import csv import fnmatch import os function app...
#---------------------------------------------------------------------- # centralities # # Computes centralities of graphs # # Author: Emanuele Pesce #---------------------------------------------------------------------- import networkx as nx import csv import fnmatch import os def applyAnalysis(pathIn, filename = ...
Python
zaydzuhri_stack_edu_python
import numpy as np from osgeo import gdal , ogr from qgis.core import * from qgis.PyQt.QtCore import QVariant from datetime import datetime function extract_arrays layer excludeNone begin string Function to extract numpy arrays from a QgsVectorLayer for analysis Parameters ---------- vectorlayer : qgis._core.QgsVectorL...
import numpy as np from osgeo import gdal, ogr from qgis.core import * from qgis.PyQt.QtCore import QVariant from datetime import datetime def extract_arrays(layer, excludeNone): '''Function to extract numpy arrays from a QgsVectorLayer for analysis Parameters ---------- vectorlayer : ...
Python
zaydzuhri_stack_edu_python
function name self begin if _actuator_type == string INFINITY_OUTPUT_MODULE begin return string { service_location_name } - Output module - { _actuator_name } - { _actuator_state_option } end comment Switch or comfort plug return string { service_location_name } - { title _actuator_type } - { _actuator_name } end funct...
def name(self): if self._actuator_type == "INFINITY_OUTPUT_MODULE": return ( f"{self._service_location.service_location_name} - " f"Output module - {self._actuator_name} - {self._actuator_state_option}" ) # Switch or comfort plug return ( ...
Python
nomic_cornstack_python_v1
import sys set case = integer input set result = list set sum = list set percent = list for i in range 0 case begin set score = call rsplit append result score append sum 0 append percent 0 end set i = 0 while i < case begin for j in range 0 integer result at i at 0 begin for k in range 1 integer result at i at 0 + 1 b...
import sys case = int(input()) result = list() sum = list() percent = list() for i in range(0,case) : score = sys.stdin.readline().strip().rsplit() result.append(score) sum.append(0) percent.append(0) i = 0 while i < case : for j in range(0, int(result[i][0])) : for k in range(1, int(r...
Python
zaydzuhri_stack_edu_python
function circ_seg x1 y1 x2 y2 r begin set x = call euclidean x1 y1 x2 y2 / 2 set y = square root r ^ 2 - x ^ 2 set ATriangles = x * y comment angle of sector (radians) set theta = 2 * call arcsin x / r comment area of whole circle set ACircle = pi * r ^ 2 comment area of sector set ASector = ACircle * theta / 2 * pi co...
def circ_seg(x1, y1, x2, y2, r): x = euclidean(x1,y1,x2,y2) / 2 y = np.sqrt(r**2 - x**2) ATriangles = x*y theta = 2*(np.arcsin(x/r)) #angle of sector (radians) ACircle = np.pi*(r**2) #area of whole circle ASector = ACircle * (theta/(2*np.pi)) #area of sector A = ASector - ATriangles #fin...
Python
nomic_cornstack_python_v1
function save_buffer self begin print string Saving replay buffer ... set start = last_saved_at % maxlen set end = number_of_samples_seen % maxlen if start >= end begin set start = start - end set end = maxlen end set data = buf at slice start : end : set data_list_of_tuples = map tuple call tolist call executemany st...
def save_buffer(self): print("\nSaving replay buffer ...") start = self.last_saved_at % self.maxlen end = self.number_of_samples_seen % self.maxlen if start >= end: start = start - end end = self.maxlen data = self.buf[start:end] data_list_of_tuple...
Python
nomic_cornstack_python_v1
function perform_search search_operator return_type=ENTRY request_options=none return_with_scores=false return_raw_json_dict=false verbosity=true begin return call perform_search_with_graph query_object=search_operator return_type=return_type request_options=request_options return_with_scores=return_with_scores return_...
def perform_search( search_operator: SearchOperator, return_type: ReturnType = ReturnType.ENTRY, request_options: Optional[RequestOptions] = None, return_with_scores: bool = False, return_raw_json_dict: bool = False, verbosity: bool = True, ) -> Union[List[str], List[ScoredResult], RawJSONDictRe...
Python
nomic_cornstack_python_v1
string PROJET L3 INFO 20-21 Vincent + Francesco Bataille navale string PARTIE 1 import numpy as np import matplotlib.pyplot as plt import random as r comment nomBateau(id)=taille comment porteAvion(1)=5 comment croiseur(2)=4 comment contreTorpilleur(3)=3 comment sousMarin(4)=3 comment torpilleur(5)=2 set grille = zeros...
""" PROJET L3 INFO 20-21 Vincent + Francesco Bataille navale """ """ PARTIE 1 """ import numpy as np import matplotlib.pyplot as plt import random as r # nomBateau(id)=taille # porteAvion(1)=5 # croiseur(2)=4 # contreTorpilleur(3)=3 # sousMarin(4)=3 # torpilleur(5)=2 grille=np.zeros((1...
Python
zaydzuhri_stack_edu_python
string Handles data objects from mechanalyzer import par set THY_PROPS = list PROGRAM METHOD BASIS ORB_RESTRICT comment Constructors function from_data program method basis orb_restrict begin string thy info data structure from necessary data comment assert to put in a data for a real species return tuple program metho...
""" Handles data objects """ from mechanalyzer import par THY_PROPS = [ par.THY.PROGRAM, par.THY.METHOD, par.THY.BASIS, par.THY.ORB_RESTRICT ] # Constructors def from_data(program, method, basis, orb_restrict): """ thy info data structure from necessary data """ # assert to put in a ...
Python
zaydzuhri_stack_edu_python
function _get_source_sum source_hash file_path saltenv begin string Extract the hash sum, whether it is in a remote hash file, or just a string. set ret = dictionary set schemes = tuple string salt string http string https string ftp string swift string s3 string file set invalid_hash_msg = format string Source hash '{...
def _get_source_sum(source_hash, file_path, saltenv): ''' Extract the hash sum, whether it is in a remote hash file, or just a string. ''' ret = dict() schemes = ('salt', 'http', 'https', 'ftp', 'swift', 's3', 'file') invalid_hash_msg = ("Source hash '{0}' format is invalid. It must be in " ...
Python
jtatman_500k
comment This is module for file 45 and 46 comment ============== FOR FILE 45 ============== function add a b begin return a + b end function function sub a b begin return a - b end function function mul a b begin return a * b end function function div a b begin return a / b end function comment ============== FOR FILE ...
# This is module for file 45 and 46 # ============== FOR FILE 45 ============== def add(a,b): return a+b def sub(a,b): return a-b def mul(a,b): return a*b def div(a,b): return a/b # ============== FOR FILE 46 ============== def myFunction(): print('the value of __name__ is' + __name__) if...
Python
zaydzuhri_stack_edu_python
function input_fn params begin set batch_size = params at string batch_size set output_buffer_size = batch_size * 1000 function extract_fn data_record begin set features = dict string query_ids call FixedLenSequenceFeature list int64 allow_missing=true ; string doc_ids call FixedLenSequenceFeature list int64 allow_mi...
def input_fn(params): batch_size = params["batch_size"] output_buffer_size = batch_size * 1000 def extract_fn(data_record): features = { "query_ids": tf.FixedLenSequenceFeature( [], tf.int64, allow_missing=True), "doc_ids": tf.FixedLenSequenceFeature( ...
Python
nomic_cornstack_python_v1
function test_new_board begin set rows = 8 set cols = 8 set board = call Board id=string uuid 4 rows=rows cols=cols for row in slots begin for slot in row begin assert available is true assert mine is false end end end function
def test_new_board(): rows = cols = 8 board = Board(id=str(uuid4()), rows=rows, cols=cols) for row in board.slots: for slot in row: assert slot.available is True assert slot.mine is False
Python
nomic_cornstack_python_v1
import itertools import numpy as np from collections import defaultdict class Learner extends object begin set grid_mesh_count = 5 set epsilon = 0.0001 function __init__ self simulator alpha gamma exploration_param decay_param local_approx=false begin string Learns a policy using Sarsa-Lambda given a State instance. Pa...
import itertools import numpy as np from collections import defaultdict class Learner(object): grid_mesh_count = 5 epsilon = 1e-4 def __init__(self, simulator, alpha, gamma, exploration_param, decay_param, local_approx=False): """ Learns a policy using Sarsa-Lambda given a State instance. ...
Python
zaydzuhri_stack_edu_python
function setImage self *args **kwargs begin call setImage *args keyword kwargs call disableAutoRange axis=0 call enableAutoRange axis=1 end function
def setImage(self, *args, **kwargs): super().setImage(*args, **kwargs) self.view.disableAutoRange(axis = 0) self.view.enableAutoRange(axis = 1)
Python
nomic_cornstack_python_v1
function get_formatted_name city country population=string begin if population begin set full_message = city + string + country + string + string population end else begin set gull_message = city + string + country end return title full_message end function
def get_formatted_name(city,country,population=''): if population: full_message=city+' '+country+' '+str(population) else: gull_message=city+' '+country return full_message.title()
Python
zaydzuhri_stack_edu_python
function interwiki_removals cls begin return call frozenset removed_wikis + closed_wikis end function
def interwiki_removals(cls) -> FrozenSet[str]: return frozenset(cls.removed_wikis + cls.closed_wikis)
Python
nomic_cornstack_python_v1
function create_backup self begin return _create_backup end function
def create_backup(self): return self._create_backup
Python
nomic_cornstack_python_v1
function UserMessage self begin return _usermessage end function
def UserMessage(self): return self._usermessage
Python
nomic_cornstack_python_v1
function user_dict self begin return dict string user_id user_id ; string firstname firstname ; string lastname lastname ; string othernames othernames ; string username username ; string email email ; string phonenumber phonenumber ; string is_admin is_admin ; string password password ; string registered_on registered...
def user_dict(self): return { "user_id": self.user_id, "firstname": self.firstname, "lastname": self.lastname, "othernames": self.othernames, "username": self.username, "email": self.email, "phonenumber": self.phonenumber, ...
Python
nomic_cornstack_python_v1
function duration_seconds_sum self duration_seconds_sum begin set _duration_seconds_sum = duration_seconds_sum end function
def duration_seconds_sum(self, duration_seconds_sum): self._duration_seconds_sum = duration_seconds_sum
Python
nomic_cornstack_python_v1
comment %% set idx = 0 set visited = set set count = 0 set flag = false for i in range n begin set next_idx = A at idx set next_idx = next_idx - 1 add visited idx if idx == 1 begin set flag = true break end else if next_idx in visited begin break end set count = count + 1 set idx = next_idx end if flag begin print coun...
#%% idx = 0 visited = set() count = 0 flag = False for i in range(n): next_idx = A[idx] next_idx -= 1 visited.add(idx) if idx == 1: flag = True break elif next_idx in visited: break count += 1 idx = next_idx if flag: print(count) else: print(-1)
Python
zaydzuhri_stack_edu_python
function save_intermediate_results self begin set is_intermediate_results_saves = true end function
def save_intermediate_results(self): self._technical_vision_system.is_intermediate_results_saves = True
Python
nomic_cornstack_python_v1
function auth_login request user begin set ri = call rest_interface opensso_url=OPEN_AM_SERVER_URL set token_logged_in = call do_login get REQUEST string username get REQUEST string password if call isErrorable token_logged_in begin if call has_key OPENAM_COOKIE_NAME_FOR_TOKEN begin del COOKIES at OPENAM_COOKIE_NAME_FO...
def auth_login(request, user): ri = rest_interface(opensso_url=OPEN_AM_SERVER_URL) token_logged_in = ri.do_login(request.REQUEST.get('username'),request.REQUEST.get('password')) if (ri.isErrorable(token_logged_in)): if request.COOKIES.has_key(OPENAM_COOKIE_NAME_FOR_TOKEN): del request...
Python
nomic_cornstack_python_v1
comment Example 1 function first_and_last message begin if message == string begin return true end else if message at 0 == message at length message - 1 begin return true end return false end function print call first_and_last string else print call first_and_last string tree print call first_and_last string comment E...
# Example 1 def first_and_last(message): if(message == ""): return True elif(message[0] == message[len(message) - 1]): return True return False print(first_and_last("else")) print(first_and_last("tree")) print(first_and_last("")) # Example 2 str = "Ada adad" print(str[len(str) - 1]) # Exa...
Python
zaydzuhri_stack_edu_python
function plot_waveforms self sorting=string compwise_loss tmin=0 class_names=none begin if not has attribute self string lat_tcs begin call compute_patterns dataset end if not has attribute self string uorder begin set tuple order _ = call _sorting sorting set uorder = call ravel end comment self.uorder = np.squeeze(or...
def plot_waveforms(self, sorting='compwise_loss', tmin=0, class_names=None): if not hasattr(self, 'lat_tcs'): self.compute_patterns(self.dataset) if not hasattr(self, 'uorder'): order, _ = self._sorting(sorting) self.uorder = order.ravel() #self.uorder = ...
Python
nomic_cornstack_python_v1
from my_opengl import * function draw_line start_axis end_axis step fix horientation begin if horientation == string h begin while start_axis < end_axis begin set start_axis = start_axis + step call glVertex start_axis fix end end else begin while start_axis < end_axis begin set start_axis = start_axis + step call glVe...
from my_opengl import * def draw_line(start_axis, end_axis, step, fix, horientation): if horientation == "h": while start_axis < end_axis: start_axis = start_axis + step glVertex(start_axis, fix) else: while start_axis < end_axis: start_axis = start_axis + st...
Python
zaydzuhri_stack_edu_python
function forward self x begin with call variable_scope string discriminator as scope begin comment Reuse variables when graph is applied again if graph_created begin call reuse_variables end set graph_created = true comment Image dimensions are fixed to the training size because of the FC layer call set_shape list none...
def forward(self, x): with tf.variable_scope('discriminator') as scope: # Reuse variables when graph is applied again if self.graph_created: scope.reuse_variables() self.graph_created = True # Image dimensions are fixed to the training size becaus...
Python
nomic_cornstack_python_v1
function create_lb_policy self lb_name policy_name policy_type policy_attributes begin set params = dict string LoadBalancerName lb_name ; string PolicyName policy_name ; string PolicyTypeName policy_type for tuple index tuple name value in enumerate call iteritems policy_attributes 1 begin set params at string PolicyA...
def create_lb_policy(self, lb_name, policy_name, policy_type, policy_attributes): params = {'LoadBalancerName': lb_name, 'PolicyName': policy_name, 'PolicyTypeName': policy_type} for index, (name, value) in enumerate(six.iteritems(policy_attri...
Python
nomic_cornstack_python_v1
function make_2d_array_fill dim1 dim2 init_fun begin set result = list for i in range dim1 begin set result = result + list call make_vector_fill dim2 lambda j -> call init_fun i j end return result end function
def make_2d_array_fill(dim1, dim2, init_fun): result = [] for i in range(dim1): result = result + [make_vector_fill(dim2, lambda j: init_fun(i, j))] return result
Python
nomic_cornstack_python_v1
function parse_stdout self filelike begin string Parse the formulae from the content written by the script to standard out. :param filelike: filelike object of stdout :returns: an exit code in case of an error, None otherwise from aiida.orm import Dict set formulae = dict set content = strip read filelike if not conte...
def parse_stdout(self, filelike): """Parse the formulae from the content written by the script to standard out. :param filelike: filelike object of stdout :returns: an exit code in case of an error, None otherwise """ from aiida.orm import Dict formulae = {} con...
Python
jtatman_500k
import numpy as np from sklearn.datasets import fetch_lfw_people from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt from sklearn.svm import SVC from sklearn.metrics import accuracy_score set lfw_people = call fetch_lfw_people min_faces_per_person=70 resize=0.4 print target_names set X ...
import numpy as np from sklearn.datasets import fetch_lfw_people from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt from sklearn.svm import SVC from sklearn.metrics import accuracy_score lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4) print(lfw_people.target_names) ...
Python
zaydzuhri_stack_edu_python
function on key begin global keys esc_count REPEAT_NUMBER csv_name comment caps, shift, etc. aren't automatically registered as strings if type key == Key begin append keys at esc_count tuple string key performance counter string pressed end else begin append keys at esc_count tuple key performance counter string press...
def on(key): global keys, esc_count, REPEAT_NUMBER, csv_name # caps, shift, etc. aren't automatically registered as strings if type(key) == Key: keys[esc_count].append((str(key), time.perf_counter(), "pressed")) else: keys[esc_count].append((key, time.perf_counter(), "pressed")) i...
Python
nomic_cornstack_python_v1
function SetAutodetectLCD lcd begin set DeviceList at string spi_lcd = lcd set DeviceList at string i2c_lcd = lcd end function
def SetAutodetectLCD(lcd): SPI.DeviceList["spi_lcd"]= lcd I2C.DeviceList["i2c_lcd"]= lcd
Python
nomic_cornstack_python_v1
function search_ontology request ontology_name term_query begin set tuple logger user upload_folder process_folder = call get_user_and_folders_plus_logger request info string Searching ontology %s for term: %s tuple ontology_name term_query set response_code = 200 set response = dict set index_dir = join path INDEX_BA...
def search_ontology(request, ontology_name, term_query): logger, user, upload_folder, process_folder = get_user_and_folders_plus_logger(request) logger.info("Searching ontology %s for term: %s", (ontology_name, term_query)) response_code = 200 response = {} index_dir = os.path.join(settings.INDEX_...
Python
nomic_cornstack_python_v1
function get_field self field_db_name begin for field in fields begin if db_name == field_db_name begin return field end end return none end function
def get_field(self, field_db_name): for field in self.fields: if field.db_name == field_db_name: return field return None
Python
nomic_cornstack_python_v1
function _convert_base value begin if is instance value int begin return call _encode_int value end else if is instance value bytes begin return call _encode_string value end else begin raise call ValueError format string Value must be str or int but {} was passed string type value end end function
def _convert_base(value): if isinstance(value, int): return Encoder._encode_int(value) elif isinstance(value, bytes): return Encoder._encode_string(value) else: raise ValueError("Value must be str or int but {} was passed".format(str(type(value))))
Python
nomic_cornstack_python_v1
from human_player import HumanPlayer function test_set_symbol begin set human = call HumanPlayer symbol=string - call set_symbol string X set actual = symbol set expected = string X assert actual == expected msg string set symbol should set the symbol end function
from human_player import HumanPlayer def test_set_symbol(): human = HumanPlayer(symbol='-') human.set_symbol('X') actual = human.symbol expected = 'X' assert actual == expected, "set symbol should set the symbol"
Python
zaydzuhri_stack_edu_python
comment Quiz) 당신은 Cocoa 서비스를 이용하는 택시기사 comment 50명의 승객과 매칭 기회가 있을 때, 총 탑승 승객 수를 구하는 프로그램 comment 조건1 : 승객별 운행 소요 시간은 5분~50분 사이의 난수 comment 조건2 : 당신은 소요 시간 5분 ~15분 사이의 승객만 매칭 comment (출력문 예제) comment [0] 1번째 손님 (소요시간 : 15분) comment [ ] 2번째 손님 (소요시간 : 50분) comment [0] 3번째 손님 (소요시간 : 5분) comment ... comment [ ] 50번째 손님 (소...
# Quiz) 당신은 Cocoa 서비스를 이용하는 택시기사 # 50명의 승객과 매칭 기회가 있을 때, 총 탑승 승객 수를 구하는 프로그램 # 조건1 : 승객별 운행 소요 시간은 5분~50분 사이의 난수 # 조건2 : 당신은 소요 시간 5분 ~15분 사이의 승객만 매칭 # (출력문 예제) # [0] 1번째 손님 (소요시간 : 15분) # [ ] 2번째 손님 (소요시간 : 50분) # [0] 3번째 손님 (소요시간 : 5분) # ... # [ ] 50번째 손님 (소요시간 :16분) # 총 탑승 승객 : 2 분 #----------------...
Python
zaydzuhri_stack_edu_python
function Deserializer object_list **options begin set db = pop options string database DEFAULT_DB_ALIAS set ignore = pop options string ignorenonexistent false set val_names_cache = dict set model_name = get options string model if is instance model_name str begin set Model = apps at model_name end else begin set Mode...
def Deserializer(object_list, **options): db = options.pop('database', DEFAULT_DB_ALIAS) ignore = options.pop('ignorenonexistent', False) val_names_cache = {} model_name = options.get('model') if isinstance(model_name, str): Model = apps[model_name] else: Model = model_name O...
Python
nomic_cornstack_python_v1
string Given a collection of intervals, merge all overlapping intervals. Example 1: Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. Example 2: Input: [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are ...
""" Given a collection of intervals, merge all overlapping intervals. Example 1: Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. Example 2: Input: [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are...
Python
zaydzuhri_stack_edu_python
string Flask Documentation: http://flask.pocoo.org/docs/ Jinja2 Documentation: http://jinja.pocoo.org/2/documentation/ Werkzeug Documentation: http://werkzeug.pocoo.org/documentation/ This file creates your application. from app import app from flask import render_template , request , redirect , url_for , jsonify from ...
""" Flask Documentation: http://flask.pocoo.org/docs/ Jinja2 Documentation: http://jinja.pocoo.org/2/documentation/ Werkzeug Documentation: http://werkzeug.pocoo.org/documentation/ This file creates your application. """ from app import app from flask import render_template, request, redirect, url_for, jsonify...
Python
zaydzuhri_stack_edu_python
function convert_to_rgb img begin string Convert an image to RGB if it isn't already RGB or grayscale if mode == string CMYK and HAS_PROFILE_TO_PROFILE begin set profile_dir = join path directory name path __file__ string profiles set input_profile = join path profile_dir string USWebUncoated.icc set output_profile = j...
def convert_to_rgb(img): """ Convert an image to RGB if it isn't already RGB or grayscale """ if img.mode == 'CMYK' and HAS_PROFILE_TO_PROFILE: profile_dir = os.path.join(os.path.dirname(__file__), 'profiles') input_profile = os.path.join(profile_dir, "USWebUncoated.icc") output_...
Python
jtatman_500k
comment ------------------------------------------------------------------------------- comment Base class for all door sensors import iofun import message from device import Device from querier import Querier from querier import MsgHandler from dbbuilder import GenericDBBuilder from linkdb import LightDBRecordFormatte...
#------------------------------------------------------------------------------- # # Base class for all door sensors # import iofun import message from device import Device from querier import Querier from querier import MsgHandler from dbbuilder import GenericDBBuilder from linkdb import LightDBRecordFormatter from us...
Python
jtatman_500k
from reading import * from database import * comment Below, write: comment *The cartesian_product function comment *All other functions and helper functions comment *Main code that obtains queries from the keyboard, comment processes them, and uses the below function to output csv results comment Below are the indexes ...
from reading import * from database import * # Below, write: # *The cartesian_product function # *All other functions and helper functions # *Main code that obtains queries from the keyboard, # processes them, and uses the below function to output csv results # Below are the indexes which each token of the qu...
Python
zaydzuhri_stack_edu_python
function build_minimum_request_body begin return dict string intent string AUTHORIZE ; string application_context dict string return_url string https://www.example.com ; string cancel_url string https://www.example.com ; string purchase_units list dict string amount dict string currency_code string USD ; string value s...
def build_minimum_request_body(): return \ { "intent": "AUTHORIZE", "application_context": { "return_url": "https://www.example.com", "cancel_url": "https://www.example.com" }, "purchase_units": [...
Python
nomic_cornstack_python_v1
function download_arcrest begin string downloads arcrest to disk set arcrest_name = string arcrest.zip set arcresthelper_name = string arcresthelper.zip set url = string https://github.com/Esri/ArcREST/archive/master.zip set file_name = join path scratchFolder base name path url set scratch_folder = join path scratchFo...
def download_arcrest(): """downloads arcrest to disk""" arcrest_name = "arcrest.zip" arcresthelper_name = "arcresthelper.zip" url = "https://github.com/Esri/ArcREST/archive/master.zip" file_name = os.path.join(arcpy.env.scratchFolder, os.path.basename(url)) scratch_folder = os.path.join(arcpy.e...
Python
jtatman_500k
function ordering self begin set aliases = dict for bound_column in columns begin set aliases at order_by_alias = order_by end try begin return next call segment order_by aliases end except StopIteration begin pass end end function
def ordering(self): aliases = {} for bound_column in self.table.columns: aliases[bound_column.order_by_alias] = bound_column.order_by try: return next(segment(self.data.query.order_by, aliases)) except StopIteration: pass
Python
nomic_cornstack_python_v1
function _init_services self begin pass end function
def _init_services(self) -> None: pass
Python
nomic_cornstack_python_v1
function change_punc df cols_to_change begin for col in cols_to_change begin if dtype == string object begin set df at col = apply df at col lambda x -> decimal replace x string , string end end return df end function
def change_punc(df, cols_to_change): for col in cols_to_change: if df[col].dtype == "object": df[col] = df[col].apply(lambda x: float(x.replace(",", ""))) return df
Python
nomic_cornstack_python_v1
from tweet_analysis.analysis import * from tweet_text2.sentiment_analysis import * import seaborn as sns import matplotlib.pyplot as plt function tweet_polarity begin string :return: the graphs of the percentage of positive, negative and neutral tweets set style=string white context=string talk set tuple f ax1 = call s...
from tweet_analysis.analysis import * from tweet_text2.sentiment_analysis import * import seaborn as sns import matplotlib.pyplot as plt def tweet_polarity(): ''' :return: the graphs of the percentage of positive, negative and neutral tweets ''' sns.set(style="white", context="talk") f, (ax1) = plt...
Python
zaydzuhri_stack_edu_python
function score_choice begin set score_choice_input = call raw_input string How would you like to score this turn? set score_choice_input_lower = lower score_choice_input set scoring_option_words = list string ones string twos string threes string fours string fives string sixes string 3 of a kind string three of a kind...
def score_choice(): score_choice_input = raw_input("How would you like to score this turn? ") score_choice_input_lower = score_choice_input.lower() scoring_option_words = ['ones','twos','threes','fours','fives','sixes', '3 of a kind','three of a kind','4 of a kind','four of a kind','full house','small straight...
Python
zaydzuhri_stack_edu_python
comment coding=utf-8 set M = 8 import math from Table import Luminance_Quantization_Matrix , Chroma_Quantization_Matrix function Luminance_Quantization matrix M begin set temp = list for i in range 0 M * M begin append temp integer round 1.0 * matrix at i / Luminance_Quantization_Matrix at i end return temp end functi...
# coding=utf-8 M = 8 import math from .Table import Luminance_Quantization_Matrix, Chroma_Quantization_Matrix def Luminance_Quantization(matrix, M): temp = [] for i in range(0, M*M): temp.append(int(round(1.0 * matrix[i] / Luminance_Quantization_Matrix[i]))) return temp def De_Luminance_Quantiza...
Python
zaydzuhri_stack_edu_python
with open string input.txt string r as f begin set x = list eval read line f end print string Lista initiala= x set y = sorted x print string ord . crescator= y set i = sorted x reverse=true print string ord. descresctor= i print string lungimea listei= length x print string MAX listei= max x print string MIN listei= m...
with open ('input.txt','r') as f: x=list(eval(f.readline())) print('Lista initiala=',x) y=sorted(x) print('ord . crescator=',y) i=sorted(x,reverse=True) print('ord. descresctor=',i) print('lungimea listei=',len(x)) print('MAX listei=',max(x)) print('MIN listei=',min(x)) print('lista.4=',x+[111]) x.inser...
Python
zaydzuhri_stack_edu_python
function remove_from_feed self fg begin if _feed_entry is not none begin call remove_entry _feed_entry set _feed_entry = none end else begin raise call RuntimeError string This episode is not yet added to any FeedGenerator end end function
def remove_from_feed(self, fg: FeedGenerator) -> None: if self._feed_entry is not None: fg.remove_entry(self._feed_entry) self._feed_entry = None else: raise RuntimeError("This episode is not yet added to any FeedGenerator")
Python
nomic_cornstack_python_v1
function update self user data begin if user is none or is_active is false begin raise call ValueError string {"detail":" + string call _ string In order to perform this operation, your account must be active + string "} end set validator = call ProfileUserValidate data if call validate is false begin set errors = call...
def update(self, user: accounts_models.User, data: dict)-> accounts_models.User: if user is None or user.is_active is False: raise ValueError('{"detail":"' + str(_("In order to perform this operation, your account must be active")) + '"}') validator = accounts_va...
Python
nomic_cornstack_python_v1
string Skills 2: oo.py Summary. comment Design a Bicycle Class class Bicycle begin string A bicycle. end class comment TODO: replace this with your code comment Define a Method for Processing Password Changes class User begin string A user who can log in to a website. function __init__ self username password begin stri...
"""Skills 2: oo.py Summary. """ ## # Design a Bicycle Class class Bicycle: """A bicycle.""" # TODO: replace this with your code ## # Define a Method for Processing Password Changes class User: """A user who can log in to a website.""" def __init__(self, username, password): """Create a...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment Program Name: HyperTyper # comment Version: 2.4.0 # comment Author: Ethan Hicks # comment Published: 2/17/2016 # try begin comment for Python2 import TKinter from Tkinter import * end except ImportError begin comment for Python3 import tkinter from tkinter import * from tkinter imp...
#!/usr/bin/env python3 ################################## # Program Name: HyperTyper # # Version: 2.4.0 # # Author: Ethan Hicks # # Published: 2/17/2016 # ################################## try: # for Python2 import TKinter from Tkinter import * except ImportE...
Python
zaydzuhri_stack_edu_python
class Food extends object begin function __init__ self name food_type heal begin set __name = name set __food_type = food_type set __heal = heal end function function get_name self begin return __name end function function get_food_type self begin return __food_type end function function get_heal_value self begin retur...
class Food(object): def __init__(self, name: str, food_type: str, heal: int): self.__name = name self.__food_type = food_type self.__heal = heal def get_name(self): return self.__name def get_food_type(self): return self.__food_type def get_heal_value(self): ...
Python
zaydzuhri_stack_edu_python
function OnPressEnter self event begin set get entryUserVariable + string You pressed Enter! call focus_set call selection_range 0 END end function
def OnPressEnter(self, event): self.labelVariable2.set(self.entryUserVariable.get() + " You pressed Enter!") self.Entry1.focus_set() self.Entry1.selection_range(0, Tkinter.END)
Python
nomic_cornstack_python_v1
function addition num1 num2 begin set num1 = num1 + num2 return num1 end function function subtraction num1 num2 begin set num1 = num1 - num2 return num1 end function function mul num1 num2 begin set num1 = num1 * num2 return num1 end function function division num1 num2 begin set num1 = num1 / num2 return num1 end fun...
def addition(num1, num2): num1 += num2 return num1 def subtraction(num1, num2): num1 -= num2 return num1 def mul(num1, num2): num1 *= num2 return num1 def division(num1, num2): num1 /= num2 return num1 def module(num1, num2): num1 %= num2 return num1 def default(num1, num2): return...
Python
zaydzuhri_stack_edu_python
function add4 a b begin return list a at 0 + b at 0 a at 1 + b at 1 a at 2 + b at 2 a at 3 + b at 3 end function
def add4(a,b): return [a[0]+b[0],a[1]+b[1],a[2]+b[2],a[3]+b[3]]
Python
nomic_cornstack_python_v1
class Solution begin function removeDuplicates self nums begin if not nums begin return none end set tuple last next_ind = tuple nums at 0 1 for i in range 1 length nums begin if nums at i > last begin set last = nums at i set tuple nums at next_ind nums at i = tuple nums at i nums at next_ind set next_ind = next_ind +...
class Solution: def removeDuplicates(self, nums: List[int]) -> List[int]: if not nums: return None last, next_ind = nums[0], 1 for i in range(1, len(nums)): if nums[i] > last: last = nums[i] nums[next_ind], nums[i] = nums[i], nums[next...
Python
zaydzuhri_stack_edu_python
import sys from game import Game if length argv != 3 begin print string Usage: python3 solver.py <filename> <mode> exit end set filename = argv at 1 set mode = argv at 2 try begin set game_object = call Game filename end except FileNotFoundError as e begin print e exit end call set_start_pos grid function add_walk node...
import sys from game import Game if len(sys.argv) != 3: print("Usage: python3 solver.py <filename> <mode>") sys.exit() filename = sys.argv[1] mode = sys.argv[2] try: game_object = Game(filename) except FileNotFoundError as e: print(e) sys.exit() game_object.player.set_start_pos(game_object.grid)...
Python
zaydzuhri_stack_edu_python
comment smtplib_verify.py import smtplib set server = call SMTP string mail comment mostra la comunicazione con il server call set_debuglevel true try begin set dhellmann_result = call verify string dhellmann set notthere_result = call verify string notthere end finally begin call quit end print string dhellmann: dhell...
# smtplib_verify.py import smtplib server = smtplib.SMTP('mail') server.set_debuglevel(True) # mostra la comunicazione con il server try: dhellmann_result = server.verify('dhellmann') notthere_result = server.verify('notthere') finally: server.quit() print('dhellmann:', dhellmann_result) print('notthere...
Python
zaydzuhri_stack_edu_python
function get_vars begin return list string A:0 string A:1 string A:3 string U:0 string U:1 string Gradients A:0 string Gradients A:1 string Gradients A:3 string Gradients A:4 string Gradients A:9 string Gradients A:10 string Gradients U:0 string Gradients U:1 string Gradients U:3 string Gradients U:4 end function
def get_vars(): return [ "A:0", "A:1", "A:3", "U:0", "U:1", "Gradients A:0", "Gradients A:1", "Gradients A:3", "Gradients A:4", "Gradients A:9", "Gradients A:10", "Gradients U:0", "Gradients U:1", "Gradie...
Python
nomic_cornstack_python_v1
function to_tensor image begin if ndim == 2 begin print string The number image dimensions is 2! return image at tuple newaxis Ellipsis newaxis end else if ndim == 3 begin print string The number of image dimensions is 3! return call moveaxis image 2 0 at tuple Ellipsis newaxis end end function
def to_tensor(image): if image.ndim == 2: print('The number image dimensions is 2!') return image[np.newaxis, ..., np.newaxis] elif image.ndim == 3: print('The number of image dimensions is 3!') return np.moveaxis(image, 2, 0)[..., np.newaxis]
Python
nomic_cornstack_python_v1
string Module with tests related to `repositories_app.views`. from unittest import mock , TestCase from repositories_app.app import create_app from repositories_app.exceptions import UserNotFoundServiceException , BadCredentialsServiceException , ApiRateLimitExceededServiceException , UnprocessableEntityServiceExceptio...
""" Module with tests related to `repositories_app.views`. """ from unittest import mock, TestCase from repositories_app.app import create_app from repositories_app.exceptions import ( UserNotFoundServiceException, BadCredentialsServiceException, ApiRateLimitExceededServiceException, UnprocessableEnti...
Python
zaydzuhri_stack_edu_python
function get_tips self begin try begin set res = call get_tips end except Exception as e begin warning string Failed to get tips e set res = none end return res end function
def get_tips(self) -> dict: try: res = self.iota_api.get_tips() except Exception as e: logging.warning("Failed to get tips", e) res = None return res
Python
nomic_cornstack_python_v1
class Difference begin function __init__ self a begin set __elements = a end function end class
class Difference: def __init__(self, a): self.__elements = a
Python
zaydzuhri_stack_edu_python
function tearDown self begin del ocb_key pysat_key notes lwarn lout del added_keys pysat_keys test_inst ocb del test_file log_capture cust_kwargs pysat_var2 del del_time pysat_lat return end function
def tearDown(self): del self.ocb_key, self.pysat_key, self.notes, self.lwarn, self.lout del self.added_keys, self.pysat_keys, self.test_inst, self.ocb del self.test_file, self.log_capture, self.cust_kwargs, self.pysat_var2 del self.del_time, self.pysat_lat return
Python
nomic_cornstack_python_v1
function home begin set locationList = all return call render_template string index.html title=string Start Select locs=locationList year=year end function
def home(): locationList = location.query.all() return render_template( 'index.html', title='Start Select', locs = locationList, year=datetime.now().year )
Python
nomic_cornstack_python_v1
function min self begin return __min end function
def min(self) -> float: return self.__min
Python
nomic_cornstack_python_v1
comment Написать программу, доказывающую или проверяющую, comment что для множества натуральных чисел выполняется равенство: comment 1+2+...+n = n(n+1)/2, где n — любое натуральное число. set n = integer input set s = 0 for i in range 1 n + 1 begin set s = s + i end set m = n * n + 1 // 2 print s print m
#Написать программу, доказывающую или проверяющую, #что для множества натуральных чисел выполняется равенство: #1+2+...+n = n(n+1)/2, где n — любое натуральное число. n = int(input()) s = 0 for i in range(1,n+1): s += i m = n * (n + 1) // 2 print(s) print(m)
Python
zaydzuhri_stack_edu_python
function fromString cls string begin set parts = split re string \s*=\s* string set name = strip parts at 0 if not parts at slice 1 : 2 : begin return call cls name none end return call cls name strip parts at 1 end function
def fromString(cls, string): parts = re.split("\s*=\s*", string) name = parts[0].strip() if not parts[1:2]: return cls(name, None) return cls(name, parts[1].strip())
Python
nomic_cornstack_python_v1
comment Chris Gala 64338761 and Eui Seon Chi 83682606. ICS 31 Lab 6 Sec 11, Lab asst 6 comment C1 print string -------------------C1------------------------ function contains string string2 begin return string2 in string end function assert call contains string banana string ana == true assert not call contains string ...
#Chris Gala 64338761 and Eui Seon Chi 83682606. ICS 31 Lab 6 Sec 11, Lab asst 6 #C1 print('-------------------C1------------------------') def contains(string: str, string2: str) -> bool: return string2 in string assert contains('banana', 'ana') == True assert not contains('racecar', 'ck') == True #C2 ...
Python
zaydzuhri_stack_edu_python
set num1 = decimal input string Entre com o primeiro número: set num2 = decimal input string Entre com o segundo número: set total = num1 * num2 print string Resultado: total
num1 = float(input("Entre com o primeiro número:")) num2 = float(input("Entre com o segundo número:")) total = num1 * num2 print("Resultado: ",total)
Python
zaydzuhri_stack_edu_python
function load_from_file cls begin set fname = __name__ + string .json try begin with open fname encoding=string utf8 as jfile begin set content = call from_json_string read jfile end end except any begin return list end set instances = list for instance in content begin set temp = call create keyword instance append ...
def load_from_file(cls): fname = cls.__name__ + ".json" try: with open(fname, encoding='utf8') as jfile: content = cls.from_json_string(jfile.read()) except: return [] instances = [] for instance in content: temp = cls.create...
Python
nomic_cornstack_python_v1
for rounds in range 0 6 1 begin set a = list set xp_field = 0 set val_field = 0 set xp_disc = 0 set val_disc = 0 set xp_spec = 0 set val_spec = 0 set val = 0 set val_per_spec = 0 set xp = 0 set val_attrib = 0 if rounds < 3 begin set num_disc = 1 set num_spec_disc_1 = rounds + 1 end else begin set num_disc = 2 set num_...
for rounds in range (0, 6, 1): a = [] xp_field = 0 val_field = 0 xp_disc = 0 val_disc = 0 xp_spec = 0 val_spec = 0 val = 0 val_per_spec = 0 xp = 0 val_attrib = 0 if (rounds<3): num_disc = 1 num_spec_disc_1 = rounds + 1 else: ...
Python
zaydzuhri_stack_edu_python
function GetMoves self x y begin set moves_x = list x set moves_y = list y set moves = list if x != 0 begin append moves_x x - 1 end if x != M - 1 begin append moves_x x + 1 end if y != 0 begin append moves_y y - 1 end if y != N - 1 begin append moves_y y + 1 end for m_x in moves_x begin for m_y in moves_y begin appen...
def GetMoves(self, x : int, y : int): moves_x = [x] moves_y = [y] moves = [] if x != 0: moves_x.append(x - 1) if x != self.M - 1: moves_x.append(x + 1) if y != 0: moves_y.append(y - 1) if y != self.N - 1: moves_y.app...
Python
nomic_cornstack_python_v1
function masked_softmax vector mask dim=- 1 memory_efficient=false mask_fill_value=- 1e+32 begin if mask is none begin set result = softmax vector dim=dim end else begin set mask = decimal while dim mask < dim vector begin set mask = unsqueeze mask 1 end if not memory_efficient begin comment To limit numerical errors f...
def masked_softmax(vector, mask, dim= -1, memory_efficient= False, mask_fill_value= -1e32): if mask is None: result = torch.nn.functional.softmax(vector, dim=dim) else: mask = mask.float() while mask.dim() < vect...
Python
nomic_cornstack_python_v1