code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment !/usr/bin/env python import rospy import roslib import time from std_msgs.msg import Float32 , Int32 from geometry_msgs.msg import Twist from dual_mc33926_rpi import motors , MAX_SPEED from simple_pid import PID class MotorEncoder begin function __init__ self enc_topic_name velo_topic_name pos_topic_name begin ...
#!/usr/bin/env python import rospy import roslib import time from std_msgs.msg import Float32, Int32 from geometry_msgs.msg import Twist from dual_mc33926_rpi import motors, MAX_SPEED from simple_pid import PID class MotorEncoder(): def __init__(self, enc_topic_name, velo_topic_name, pos_topic_name): ros...
Python
zaydzuhri_stack_edu_python
comment 2. Пользователь вводит время в секундах. Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс. Используйте форматирование строк. print string task_2 set time = integer input string Enter time in seconds: set time_h = time // 3600 set time_m = time - time_h * 3600 // 60 set time_s = time - tim...
#2. Пользователь вводит время в секундах. Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс. Используйте форматирование строк. print("\ntask_2\n") time = int(input("Enter time in seconds: ")) time_h = time//3600 time_m = (time - time_h * 3600)//60 time_s = time - time_h * 3600 - time_m * 60 print...
Python
zaydzuhri_stack_edu_python
comment File holding all voice commands for assistant comment Initialize the commands comment Hash table with the keyword as a value so we can reduce overall runtime set all_commands = dict function add_to_commands function keywords begin for keyword in keywords begin update all_commands dict keyword function end end ...
# File holding all voice commands for assistant # Initialize the commands # Hash table with the keyword as a value so we can reduce overall runtime all_commands = {} def add_to_commands(function, keywords): for keyword in keywords: all_commands.update({keyword:function}) # Add the Youtube keywords to the...
Python
zaydzuhri_stack_edu_python
function variables self begin return call pack_if_not _args at 0 end function
def variables(self): return pack_if_not(self._args[0])
Python
nomic_cornstack_python_v1
function set_acls self path acls version=- 1 begin debug string set_acls(%r, %r, %r) path acls version set request = call SetACLRequest call _prefix_root chroot path acls version set response = call SetACLResponse none call _call request response return stat end function
def set_acls(self, path, acls, version=-1): LOGGER.debug('set_acls(%r, %r, %r)', path, acls, version) request = SetACLRequest(_prefix_root(self.chroot, path), acls, version) response = SetACLResponse(None) self._call(request, response) return response.stat
Python
nomic_cornstack_python_v1
comment -*- mode: python; coding: utf-8; -*- import re from django import template function tag_parse contents param_re begin string Templatetags parameters parsing helper. Require two arguments: - ``contents``: ``token.contents`` - ``param_re``: regexp to parse ``contents`` with. Example:: obj, var = tag_parse(token.c...
# -*- mode: python; coding: utf-8; -*- import re from django import template def tag_parse(contents, param_re): """Templatetags parameters parsing helper. Require two arguments: - ``contents``: ``token.contents`` - ``param_re``: regexp to parse ``contents`` with. Example:: obj, var ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment -*- coding: utf-8 -*- import sqlite3 as lite import sys set f = open string ../hashtags/1000seg.txt string r set con = call connect string hashtags.db with con and f begin set cur = call cursor set count = 0 end
#!/usr/bin/python # -*- coding: utf-8 -*- import sqlite3 as lite import sys f = open ('../hashtags/1000seg.txt','r') con = lite.connect('hashtags.db') with con and f: cur = con.cursor() count = 0
Python
zaydzuhri_stack_edu_python
function release_stream_buffer self begin return call ps3000_release_stream_buffer _handle end function
def release_stream_buffer(self): return self.sdk.ps3000_release_stream_buffer(self._handle)
Python
nomic_cornstack_python_v1
function add_segment self pt begin if call is_venv begin set prompt_ipster_main = prompt_virtualenv + pt end else begin comment prompt_ipster_main = pt set prompt_ipster_main = list tuple Prompt string + pt end return prompt_ipster_main end function
def add_segment(self, pt): if self.is_venv(): prompt_ipster_main = self.prompt_virtualenv + pt else: # prompt_ipster_main = pt prompt_ipster_main = [(Token.Prompt, ' '), ] + pt return prompt_ipster_main
Python
nomic_cornstack_python_v1
from flask import Flask set app = call Flask __name__ comment global vars set equips = list string Cornellà string Sant Boi string Despí decorator call route string / comment entry points function hello_world begin set html = string for equip in equips begin set html = html + equip + string <br> end return string Hell...
from flask import Flask app = Flask(__name__) # global vars equips = [ "Cornellà", "Sant Boi", "Despí" ] # entry points @app.route('/') def hello_world(): html = "" for equip in equips: html += equip + "<br>" return 'Hello, World!<br><br>' + html + "<a href='/afegir_equip'>Afegir equip</a>" @app.route('/afe...
Python
zaydzuhri_stack_edu_python
function test_it_rejects_annotations_to_other_groups self data effective_principals ok authn_policy begin set return_value = effective_principals set request = call mock_request set schema = call LegacyCreateAnnotationSchema request if ok begin set result = call validate data assert get result string group == get data ...
def test_it_rejects_annotations_to_other_groups(self, data, effective_principals, ok, authn_policy): aut...
Python
nomic_cornstack_python_v1
class Test extends object begin function __init__ self begin set __num = 100 end function end class set t = call Test comment 报错 __num 私有属性 print __num comment 前置单下滑线 表示 只能在当前模块使用,import ,from无法导入 set _num = 100
class Test(object): def __init__(self): self.__num = 100 t = Test() print(t.__num) #报错 __num 私有属性 #前置单下滑线 表示 只能在当前模块使用,import ,from无法导入 _num = 100
Python
zaydzuhri_stack_edu_python
import data_io import doc_preprocessing as dpp import math , operator , itertools , os from terminaltables import AsciiTable class Search begin function __init__ self begin comment dictionary and posting list set dl_and_pl = call deserialize_object DICTIONARY_AND_POSTING_LIST_FILE set _pre_processor = call PreProcessor...
import data_io import doc_preprocessing as dpp import math, operator, itertools, os from terminaltables import AsciiTable class Search: def __init__(self): self.dl_and_pl = data_io.DataIO().deserialize_object(data_io.DICTIONARY_AND_POSTING_LIST_FILE) #dictionary and posting list self._pre_processor = dpp.PreProce...
Python
zaydzuhri_stack_edu_python
async function decoder queue consumer begin info string decoder: starting try begin async_for msg in consumer begin if value == EOT begin info string decoder: EOT received break end info string consumed: %s %s %s %s %s %s topic partition offset key value timestamp set bpayload : bytes = value set payload : ConsumerPayl...
async def decoder( queue: asyncio.Queue[ConsumerPayload], consumer: AIOKafkaConsumer, ) -> int: log.info("decoder: starting") try: async for msg in consumer: if msg.value == EOT: log.info("decoder: EOT received") break log.info( ...
Python
nomic_cornstack_python_v1
function test_blank_arrangement self begin comment Display full-length failure info set maxDiff = none set LINE = string | { string - * 32 } set ONE_BAR = LINE + string | * 6 + string set TWO_BAR = LINE * 2 + string | * 6 + string for i in range 1 5 begin with call subTest i=i + 1 begin set TAB = TWO_BAR * i + 1 // 2...
def test_blank_arrangement(self): self.maxDiff = None # Display full-length failure info LINE = f"|{'-' * 32}" ONE_BAR = (LINE + '|\n') * 6 + '\n' TWO_BAR = (LINE * 2 + '|\n') * 6 + '\n' for i in range(1, 5): with self.subTest(i=i+1): TAB = TWO_BAR * ...
Python
nomic_cornstack_python_v1
from datetime import date from core import db comment Association table enables many-to-many relation set groups_users = call Table string groups_users call Column string user_id call Integer call ForeignKey string user.id call Column string group_id call Integer call ForeignKey string group.id class User extends Model...
from datetime import date from .core import db # Association table enables many-to-many relation groups_users = db.Table('groups_users', db.Column('user_id', db.Integer(), db.ForeignKey('user.id')), db.Column('group_id', db.Integer(), db.ForeignKey('group.id'))) clas...
Python
zaydzuhri_stack_edu_python
string You are given some integer as input, (i.e. ... -3, -2, -1, 0, 1, 2, 3 ...) Convert the integer you are given to a string. Do not make use of the built-in "str" function. Examples: Input: 123 Output: "123" Input: -123 Output: "-123" comment a = 123 comment a = print(type(a)) # class int comment a = str(123) # bui...
""" You are given some integer as input, (i.e. ... -3, -2, -1, 0, 1, 2, 3 ...) Convert the integer you are given to a string. Do not make use of the built-in "str" function. Examples: Input: 123 Output: "123" Input: -123 Output: "-123" """ # a = 123 # a = print(type(a)) # class int # a = str(123) # bu...
Python
zaydzuhri_stack_edu_python
function _remove_listener self begin if _listener begin call remove_listener EVENT_TIME_CHANGED _listener set _listener = none end end function
def _remove_listener(self): if self._listener: self.hass.bus.remove_listener(EVENT_TIME_CHANGED, self._listener) self._listener = None
Python
nomic_cornstack_python_v1
import torch function print_fn grad begin print grad end function function double_fn grad begin set grad = grad * 2 print grad return grad end function set x = call requires_grad_ call register_hook double_fn set y = x * x set dx = grad autograd outputs=list y inputs=list x create_graph=false retain_graph=true at 0 set...
import torch def print_fn(grad): print(grad) def double_fn(grad): grad = grad * 2 print(grad) return grad x = torch.ones([1], dtype=torch.float32).requires_grad_() x.register_hook(double_fn) y = x * x dx = torch.autograd.grad( outputs=[y], inputs=[x], create_graph=False, retain_grap...
Python
zaydzuhri_stack_edu_python
function sum_dup lst begin set s = 0 for x in lst begin set s = s + x end return s end function
def sum_dup(lst): s = 0 for x in lst: s += x return s
Python
nomic_cornstack_python_v1
function getAction self gameState begin comment Collect legal moves and successor states set legalMoves = call getLegalActions comment Choose one of the best actions set scores = list comprehension call evaluationFunction gameState action for action in legalMoves set bestScore = max scores set bestIndices = list compre...
def getAction(self, gameState): # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [inde...
Python
nomic_cornstack_python_v1
for line in read lines fileIn begin set dataLine = split line string , if length dataLine == 5 begin append tags pop dataLine at slice 0 : - 1 : append data join string dataLine end end close fileIn set fileOut = open string iris.data.txt string w for ele in data begin write fileOut ele + string end close fileOut set ...
for line in fileIn.readlines(): dataLine = line.split(',') if len(dataLine) == 5: tags.append(dataLine.pop()[0:-1]) data.append(' '.join(dataLine)) fileIn.close() fileOut = open('iris.data.txt', 'w') for ele in data: fileOut.write(ele + '\n') fileOut.close() fileOut = open('iris.data.tags....
Python
zaydzuhri_stack_edu_python
function api_mapping_id self begin set result = get _values string api_mapping_id assert result is not none msg string Required property 'api_mapping_id' is missing return result end function
def api_mapping_id(self) -> builtins.str: result = self._values.get("api_mapping_id") assert result is not None, "Required property 'api_mapping_id' is missing" return result
Python
nomic_cornstack_python_v1
function user_id self user_id begin set _user_id = user_id end function
def user_id(self, user_id): self._user_id = user_id
Python
nomic_cornstack_python_v1
comment numeric types of datatype comment it is of 3 types comment int comment float comment complex comment int set a = 10 print a comment <class 'int'> print type a comment when we supposed to get the type of a variable then we can do it by using type() function comment binary, hexadecimal, octadecimal representation...
# numeric types of datatype # it is of 3 types # int # float # complex # int a=10 print(a) print(type(a)) # <class 'int'> # when we supposed to get the type of a variable then we can do it by using type() function # binary, hexadecimal, octadecimal representation of int # always integer type of variables are conv...
Python
zaydzuhri_stack_edu_python
import sys from terminal import * function main begin set tuple width height = call get_term_size set grid = list comprehension width - 5 * list 0 for i in range height - 5 call update_screen grid call read_initial_conf grid set prompt = string ITER %d: Type anything to continue, the number of steps to + string perform...
import sys from terminal import * def main(): (width, height) = get_term_size() grid = [(width-5)*[0] for i in range(height-5)] update_screen(grid) read_initial_conf(grid) prompt = ('ITER %d: Type anything to continue, the number of steps to ' + 'perform (or quit to exit): ') ...
Python
zaydzuhri_stack_edu_python
function setRobotDirection self direction begin set d = direction end function
def setRobotDirection(self, direction): self.d = direction
Python
nomic_cornstack_python_v1
function random_list request begin if method == string GET begin set snippets = all set serializer = call RandomSerializer snippets many=true return call JsonResponse data safe=false end else if method == string POST begin set data = parse call JSONParser request set serializer = call RandomSerializer data=data if call...
def random_list(request): if request.method == 'GET': snippets = RandomApi.objects.all() serializer = RandomSerializer(snippets, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = Ran...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Sun Jun 16 16:39:30 2019 @author: Hacker set x1 = integer input string Enter value of x1: set y1 = integer input string Enter value of y1: set x2 = integer input string Enter value of x2: set y2 = integer input string Enter value of y2: set e = x2 - x1 ^ 2 + y2 - y1 ^ 2 ^...
# -*- coding: utf-8 -*- """ Created on Sun Jun 16 16:39:30 2019 @author: Hacker """ x1 = int(input("Enter value of x1: ")) y1 = int(input("Enter value of y1: ")) x2 = int(input("Enter value of x2: ")) y2 = int(input("Enter value of y2: ")) e = ((x2 - x1)**2 + (y2 - y1)**2)**0.5 print('The distance between two points ...
Python
zaydzuhri_stack_edu_python
import sys set nombreCas = integer read line stdin set resultat = 0 for i in range 0 nombreCas begin set entree = integer read line stdin set nombre = entree // 10 set exposant = entree % 10 set resultat = resultat + nombre ^ exposant end print resultat * resultat
import sys nombreCas = int(sys.stdin.readline()) resultat = 0 for i in range(0,nombreCas): entree = int(sys.stdin.readline()) nombre = entree // 10 exposant = entree % 10 resultat = resultat + nombre**exposant print(resultat*resultat)
Python
zaydzuhri_stack_edu_python
function delMessage self begin if not isClosed begin if __message != string begin set __message = string end else begin raise call HDDOPermissionException string Tried to remove non-existing message from a HealthDominoDataObject. end end else begin raise call HDDOPermissionException string Tried to remove message fro...
def delMessage(self): if not self.isClosed: if self.__message != '': self.__message = '' else: raise HDDOPermissionException('Tried to remove non-existing message from a HealthDominoDataObject.') else: raise HDDOPermissionExcep...
Python
nomic_cornstack_python_v1
function hexdump buf syscall begin print format string {:30} ---=== {} ===--- string upper syscall set hexbuffer = decode call hexlify buf set hexstrings = call wrap hexbuffer 32 for tuple offset hexstring in enumerate hexstrings begin set ascii_string = string set hexb = string for pos in range 0 length hexstring -...
def hexdump(buf, syscall): print("{:30} ---=== {} ===---".format(" ", syscall.upper())) hexbuffer = hexlify(buf).decode() hexstrings = wrap(hexbuffer, 32) for offset, hexstring in enumerate(hexstrings): ascii_string = "" hexb = "" for pos in range(0, len(hexstring) - 1, 2): ...
Python
nomic_cornstack_python_v1
import cv2 import numpy as np comment BASIC FUNCTIONS set img = call imread string Resources/lena.png set kernel = ones tuple 5 5 uint8 comment GRAYSCALE set imgGray = call cvtColor img COLOR_BGR2GRAY comment BLUR set imgBlur = call GaussianBlur imgGray tuple 7 7 0 comment CANNY EDGES set imgCanny = call Canny img 150 ...
import cv2 import numpy as np # BASIC FUNCTIONS img = cv2.imread("Resources/lena.png") kernel = np.ones((5, 5), np.uint8) imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # GRAYSCALE imgBlur = cv2.GaussianBlur(imgGray, (7, 7), 0) # BLUR imgCanny = cv2.Canny(img, 150, 200) # CANNY EDGES imgDilation = cv2.dila...
Python
zaydzuhri_stack_edu_python
function on_connection_close self *args **kwargs begin append errors MESSAGES at string INTERRUPTED teardown self end function
def on_connection_close(self, *args, **kwargs): self.errors.append(MESSAGES['INTERRUPTED']) self.teardown()
Python
nomic_cornstack_python_v1
async function generate_bytes_img url **kwargs begin set params = call _parse_parameters keyword kwargs set browser = await call get_browser set page = await call _page_manager browser url params set element = await call _selector_manager page params set image = await call screenshot options=get params string screensho...
async def generate_bytes_img(url: str, **kwargs) -> bytes: params = _parse_parameters(**kwargs) browser = await get_browser() page = await _page_manager(browser, url, params) element = await _selector_manager(page, params) image = await element.screenshot(options=params.get("screenshot_options")...
Python
nomic_cornstack_python_v1
function valid_output_name filename path extension=none begin set path = call file_exists path directory name real path __file__ if extension begin set base_filepath = join path filename + format string .{} extension end else begin set base_filepath = join path filename end set output_filepath = base_filepath set idx =...
def valid_output_name(filename: str, path: str, extension=None) -> str: path = file_exists(path, dirname(realpath(__file__))) if extension: base_filepath = join(path, filename) + '.{}'.format(extension) else: base_filepath = join(path, filename) output_filepath = base_filepath idx = ...
Python
nomic_cornstack_python_v1
import numpy as np from physics_sim import PhysicsSim class Task begin string Task (environment) that defines the goal and provides feedback to the agent. function __init__ self init_pose=array list 0.0 0.0 0.0 0.0 0.0 0.0 init_velocities=none init_angle_velocities=none runtime=5.0 target_pos=none action_repeat=none be...
import numpy as np from physics_sim import PhysicsSim class Task(): """Task (environment) that defines the goal and provides feedback to the agent.""" def __init__(self, init_pose=np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0]), init_velocities=None, init_angle_velocities=None, runtime=5., target_pos=None, ac...
Python
zaydzuhri_stack_edu_python
function wait_for_event self event timeout=10000 begin set _vbox_wait_events at event = false function on_property_change _event begin debug string event: %s %s %s name value flags set _vbox_wait_events at event = true end function set callback_id = call register_callback on_property_change event comment wait for some ...
def wait_for_event(self, event, timeout=10000): self._vbox_wait_events[event] = False def on_property_change(_event): logger.debug('event: %s %s %s', _event.name, _event.value, _event.flags) self._vbox_wait_events[event] = True callback_id = self._vbox.event_source.regi...
Python
nomic_cornstack_python_v1
import numpy as np class Node begin function __init__ self word begin set left = none set right = none set word = word set rating = none end function function __repr__ self begin if left is not none and right is not none begin return string word + string - + string word end else begin return string word end end functio...
import numpy as np class Node(): def __init__(self, word): self.left = None; self.right = None self.word = word self.rating = None; def __repr__(self): if (self.left is not None and self.right is not None): return str(self.left.word) + "-" + str(self.right....
Python
zaydzuhri_stack_edu_python
function countPerms n begin set tmp = list 1 1 1 1 1 for _ in range n - 1 begin comment a = e + i + u set a = tmp at 1 + tmp at 2 + tmp at 4 comment e = a + i set e = tmp at 0 + tmp at 2 comment i = a + e + o + u set i = tmp at 1 + tmp at 3 comment o = i set o = tmp at 2 comment u = i + o set u = tmp at 2 + tmp at 3 se...
def countPerms(n): tmp = [1,1,1,1,1] for _ in range(n - 1): # a = e + i + u a = tmp[1] + tmp[2] + tmp[4] # e = a + i e = tmp[0] + tmp[2] # i = a + e + o + u i = tmp[1] + tmp[3] # o = i o = tmp[2] # u = i + o u = tmp[2] + tmp[3] ...
Python
zaydzuhri_stack_edu_python
function begin_step self begin if stepid is none begin set stepid = 0 end else begin set stepid = stepid + 1 end return call Message Transition idnum call Transition BeginStep stepid end function
def begin_step(self): if self.stepid is None: self.stepid = 0 else: self.stepid += 1 return Message(MsgTypes.Transition, self.idnum, Transition(Transitions.BeginStep, self.stepid))
Python
nomic_cornstack_python_v1
function valid_connection graph next_ver curr_ind path begin comment 1. Validate that path exists between current and next vertices if graph at path at curr_ind - 1 at next_ver == 0 begin return false end comment 2. Validate that next vertex is not already in path return not any generator expression vertex == next_ver ...
def valid_connection( graph: list[list[int]], next_ver: int, curr_ind: int, path: list[int] ) -> bool: # 1. Validate that path exists between current and next vertices if graph[path[curr_ind - 1]][next_ver] == 0: return False # 2. Validate that next vertex is not already in path return not...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt comment 定义等高线高度函数 function f x y begin return 1 - x / 2 + x ^ 5 + y ^ 3 * exp - x ^ 2 - y ^ 2 end function comment data number set n = 666 comment define x y set x = linear space - 3 3 n set y = linear space - 3 3 n comment to make grid se...
# -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt #定义等高线高度函数 def f(x,y): return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2) #data number n=666 #define x y x=np.linspace(-3,3,n) y=np.linspace(-3,3,n) #to make grid X,Y=np.meshgrid(x,y) # 填充等高线的颜色, 8是等高线分为几部分 plt.contourf(X, Y, f(X, Y), 8, alpha =...
Python
zaydzuhri_stack_edu_python
while true begin set index = find s string bob start if index == - 1 begin break end else begin set count = count + 1 set start = index + 1 set index = - 1 continue end end
while True: index=s.find('bob',start) if(index==-1): break else: count+=1 start = index+1 index=-1 continue
Python
zaydzuhri_stack_edu_python
function slew_to_zero self begin call slew_to_home end function
def slew_to_zero(self): self.slew_to_home()
Python
nomic_cornstack_python_v1
string [문제 설명] 카카오에 신입 개발자로 입사한 콘은 선배 개발자로부터 개발역량 강화를 위해 다른 개발자가 작성한 소스 코드를 분석하여 문제점을 발견하고 수정하라는 업무 과제를 받았습니다. 소스를 컴파일하여 로그를 보니 대부분 소스 코드 내 작성된 괄호가 개수는 맞지만 짝이 맞지 않은 형태로 작성되어 오류가 나는 것을 알게 되었습니다. 수정해야 할 소스 파일이 너무 많아서 고민하던 콘은 소스 코드에 작성된 모든 괄호를 뽑아서 올바른 순서대로 배치된 괄호 문자열을 알려주는 프로그램을 다음과 같이 개발하려고 합니다. 용어의 정의 '(' 와 ')' 로만 이루어진 ...
''' [문제 설명] 카카오에 신입 개발자로 입사한 콘은 선배 개발자로부터 개발역량 강화를 위해 다른 개발자가 작성한 소스 코드를 분석하여 문제점을 발견하고 수정하라는 업무 과제를 받았습니다. 소스를 컴파일하여 로그를 보니 대부분 소스 코드 내 작성된 괄호가 개수는 맞지만 짝이 맞지 않은 형태로 작성되어 오류가 나는 것을 알게 되었습니다. 수정해야 할 소스 파일이 너무 많아서 고민하던 콘은 소스 코드에 작성된 모든 괄호를 뽑아서 올바른 순서대로 배치된 괄호 문자열을 알려주는 프로그램을 다음과 같이 개발하려고 합니다. 용어의 정의 '(' 와 ')' 로만 이루어진 문...
Python
zaydzuhri_stack_edu_python
function getFeatureDistribution self fIndex vIndices=none begin call checkIndex fIndex 0 call getNumFeatures if vIndices == none begin set tuple freqs items = call histogram V at tuple slice : : fIndex end else begin set tuple freqs items = call histogram V at tuple vIndices fIndex end return tuple freqs items end f...
def getFeatureDistribution(self, fIndex, vIndices=None): Parameter.checkIndex(fIndex, 0, self.getNumFeatures()) if vIndices == None: (freqs, items) = Util.histogram(self.V[:, fIndex]) else: (freqs, items) = Util.histogram(self.V[vIndices, fIndex]) ...
Python
nomic_cornstack_python_v1
function test_new_endpoints_generation self begin set probabilities_for_cdf = array list list 0.05 0.7 0.95 set threshold_points = array list - 50 10 60 set plugin = call Plugin ecc_bounds_warning=true set result = call _add_bounds_to_thresholds_and_probabilities threshold_points probabilities_for_cdf bounds_pairing as...
def test_new_endpoints_generation(self): probabilities_for_cdf = np.array([[0.05, 0.7, 0.95]]) threshold_points = np.array([-50, 10, 60]) plugin = Plugin(ecc_bounds_warning=True) result = plugin._add_bounds_to_thresholds_and_probabilities( threshold_points, probabilities_for_...
Python
nomic_cornstack_python_v1
function list2 self filenames=none path=none digest=none begin call assert_none_or_list_of_strings filenames string filenames string filename try begin return call ttbd_iface_call string store string list2 path=path digest=digest filenames=filenames method=string GET end except exception as e begin if string list2: uns...
def list2(self, filenames = None, path = None, digest = None): commonl.assert_none_or_list_of_strings(filenames, "filenames", "filename") try: return self.target.ttbd_iface_call( "store", "list2", path = path, digest = digest, filenames = filenames, method = "...
Python
nomic_cornstack_python_v1
for i in range length mount begin if ma < mount at i begin set ma = mount at i append kill cnt set cnt = 0 end else begin set cnt = cnt + 1 end end if ma > mount at n - 1 begin append kill cnt end print max kill
for i in range(len(mount)): if ma < mount[i]: ma = mount[i] kill.append(cnt) cnt = 0 else: cnt += 1 if ma > mount[n - 1]: kill.append(cnt) print(max(kill))
Python
zaydzuhri_stack_edu_python
from common import utility as u class writer begin function __init__ self rel_path generate_header=true comment_prefix=string // using_tab=false begin set path = rel_path set indent = 0 set content = list set using_tab = using_tab if generate_header begin call wl comment_prefix + string THIS FILE IS AUTOMATIC GENERATE...
from common import utility as u class writer: def __init__(self, rel_path, generate_header=True, comment_prefix='//', using_tab=False): self.path = rel_path self.indent = 0 self.content = [] self.using_tab = using_tab if generate_header: self.wl(comment_prefix ...
Python
zaydzuhri_stack_edu_python
comment -*- coding:utf-8 -*- import sys class Solution begin function VerifySquenceOfBST self sequence begin comment write code here print sequence if length sequence < 1 begin return false end set left = 0 for i in range length sequence - 1 begin if sequence at i > sequence at - 1 begin set left = i break end else beg...
# -*- coding:utf-8 -*- import sys class Solution: def VerifySquenceOfBST(self, sequence): # write code here print(sequence) if len(sequence) < 1: return False left = 0 for i in range(len(sequence) - 1): if sequence[i] > sequence[-1]: le...
Python
zaydzuhri_stack_edu_python
function loss self top_out targets weights_fn=none begin set logits = top_out if weights_fn is none begin set weights_fn = targets_weights_fn end return call padded_cross_entropy logits targets label_smoothing weights_fn=weights_fn end function
def loss(self, top_out, targets, weights_fn=None): logits = top_out if weights_fn is None: weights_fn = self.targets_weights_fn return common_layers.padded_cross_entropy( logits, targets, self._model_hparams.label_smoothing, weights_fn=weights_fn)
Python
nomic_cornstack_python_v1
function delete_entity sender instance **kwargs begin string Delete Entity when last Data object is deleted. comment 1 means that the last Data object is going to be deleted. delete end function
def delete_entity(sender, instance, **kwargs): """Delete Entity when last Data object is deleted.""" # 1 means that the last Data object is going to be deleted. Entity.objects.annotate(num_data=Count('data')).filter(data=instance, num_data=1).delete()
Python
jtatman_500k
function powerSumsOrder self begin return 2 * order end function
def powerSumsOrder(self): return 2*self.order
Python
nomic_cornstack_python_v1
function set_photo_title photo filepath relative_filepath title_template exiftool_path verbose begin set title_text = call render_photo_template filepath relative_filepath title_template exiftool_path if length title_text > 1 begin call echo string photo can have only a single title: ' { title_template } ' = { title_te...
def set_photo_title( photo: Photo, filepath: Path, relative_filepath: Path, title_template: str, exiftool_path: str, verbose: Callable[..., None], ) -> str: title_text = render_photo_template( filepath, relative_filepath, title_template, exiftool_path ) if len(title_text) > 1...
Python
nomic_cornstack_python_v1
comment python 的面向对象 set a = string aaa type a comment 类的定义 class Animal begin comment pass string animal class comment 类属性 set eye = 2 set leg = list comment __init__类的初始化 最先执行 self 默认不带参数 function __init__ self name food color=string yellow begin set name = name comment self.food = food set _food = food comment self...
#python 的面向对象 a = 'aaa' type(a) #类的定义 class Animal: #pass '''animal class ''' eye = 2 #类属性 leg = [] def __init__(self,name,food,color = 'yellow'): #__init__类的初始化 最先执行 self 默认不带参数 self.name = name #self.food = food self._food = food #self.color = color ...
Python
zaydzuhri_stack_edu_python
class Edge begin function __init__ self source target weight begin set source = source set target = target set weight = weight end function end class comment def dfs(s, d): comment visited[s] = True comment if s == d: comment return True comment for edge in graph: comment u = edge.source comment v = edge.target comment...
class Edge: def __init__(self, source, target, weight): self.source = source self.target = target self.weight = weight # def dfs(s, d): # visited[s] = True # if s == d: # return True # for edge in graph: # u = edge.source # v = edge.target # ...
Python
zaydzuhri_stack_edu_python
set count = count sentence word print count
count = sentence.count(word) print(count)
Python
jtatman_500k
function __lt__ self other begin return string self < string other end function
def __lt__(self, other: Any) -> bool: return str(self) < str(other)
Python
nomic_cornstack_python_v1
string Made and written by: Julie Lizardo import pygame as pg , sys import random as r from pygame.locals import * comment display box import tkinter from tkinter import messagebox comment hide main window set root = call Tk call withdraw comment start pygame call init call init call init set myfont = call SysFont stri...
""" Made and written by: Julie Lizardo """ import pygame as pg,sys import random as r from pygame.locals import * # display box import tkinter from tkinter import messagebox #hide main window root = tkinter.Tk() root.withdraw() # start pygame pg.init() pg.font.init() pg.mixer.init() myfont = pg.font.SysFont('Verda...
Python
zaydzuhri_stack_edu_python
function main_game_loop begin set board = call SetupBoard call draw_board end function
def main_game_loop(): board = SetupBoard() board.draw_board()
Python
nomic_cornstack_python_v1
function sort_ascending nums begin return sorted nums end function
def sort_ascending(nums): return sorted(nums)
Python
flytech_python_25k
function transform self X y=none begin string :param X: list of dict which contains metabolic measurements. return call call Parallel n_jobs=n_jobs generator expression call call delayed _transform x for x in X end function
def transform(self, X, y=None): ''' :param X: list of dict which contains metabolic measurements. ''' return Parallel(n_jobs=self.n_jobs)(delayed(self._transform)(x) for x in X)
Python
jtatman_500k
string Module with epigenomic training sequence for the MLP. import pandas as pd import numpy as np from keras_mixed_sequence import MixedSequence , VectorSequence function get_mlp_training_sequence X y batch_size random_state begin string Return training sequence for MLP. Parameters -------------------- X: np.ndarray,...
"""Module with epigenomic training sequence for the MLP.""" import pandas as pd import numpy as np from keras_mixed_sequence import MixedSequence, VectorSequence def get_mlp_training_sequence( X: np.ndarray, y: pd.DataFrame, batch_size: int, random_state: int ) -> MixedSequence: """Return training...
Python
zaydzuhri_stack_edu_python
import json import math import os import re import sys from datetime import datetime from treelib import Node , Tree try begin insert path 0 real path path environ at string INTEREST_ENGINE_PATH end except KeyError begin write stderr string Application Root environmental variable 'INTEREST_ENGINE_PATH' not set exit 1 e...
import json import math import os import re import sys from datetime import datetime from treelib import Node, Tree try: sys.path.insert(0, os.path.realpath(os.environ['INTEREST_ENGINE_PATH'])) except KeyError: sys.stderr.write("Application Root environmental variable 'INTEREST_ENGINE_PATH' not set\n") sy...
Python
zaydzuhri_stack_edu_python
string script to extract CSS values given a list of CSS properties and their location in the specification. FIXME: ouput data into a suitable JSON format FIXME: create a config file FIXME: check if the cache directory exists and create it if not from bs4 import BeautifulSoup import urllib2 import urlparse import loggin...
""" script to extract CSS values given a list of CSS properties and their location in the specification. FIXME: ouput data into a suitable JSON format FIXME: create a config file FIXME: check if the cache directory exists and create it if not """ from bs4 import BeautifulSoup import urllib2 import urlparse import logg...
Python
zaydzuhri_stack_edu_python
comment Write a script that detects and prints out your monitor resolution. comment Mac import AppKit print list comprehension tuple width height for screen in call screens comment Windows comment from screeninfo import get_monitors comment w = get_monitors()[0].width comment h = get_monitors()[0].height comment print ...
# Write a script that detects and prints out your monitor resolution. # Mac import AppKit print [(screen.frame().size.width, screen.frame().size.height) for screen in AppKit.NSScreen.screens()] # Windows # from screeninfo import get_monitors # w = get_monitors()[0].width # h = get_monitors()[0]....
Python
zaydzuhri_stack_edu_python
function hello request begin comment html_content = render_to_string("dash/task_tables/coord_you.html", query_dictionary, RequestContext(request)) return dumps dict string message string hello end function
def hello(request): #html_content = render_to_string("dash/task_tables/coord_you.html", query_dictionary, RequestContext(request)) return simplejson.dumps({'message': 'hello'})
Python
nomic_cornstack_python_v1
function test_string_format begin set tree = parse call dedent string import logging logging.info("Hello {}".format("World!")) set visitor = call LoggingVisitor call visit tree call assert_that violations call has_length 1 call assert_that violations at 0 at 1 call is_ call equal_to STRING_FORMAT_VIOLATION end function
def test_string_format(): tree = parse(dedent("""\ import logging logging.info("Hello {}".format("World!")) """)) visitor = LoggingVisitor() visitor.visit(tree) assert_that(visitor.violations, has_length(1)) assert_that(visitor.violations[0][1], is_(equal_to(STRING_FORMAT_VIOLA...
Python
nomic_cornstack_python_v1
function compute_cost X groups K_clusters begin set m = shape at 0 set dis = call empty m for i in range m begin set dis at i = call compute_distance reshape X at tuple i slice : : 1 shape at 1 reshape K_clusters at tuple groups at i slice : : 1 shape at 1 set cost = 1 / m * sum dis end return cost end function
def compute_cost(X, groups, K_clusters): m = X.shape[0] dis = np.empty(m) for i in range(m): dis[i] = compute_distance(X[i,:].reshape(1,X.shape[1]), K_clusters[groups[i],:].reshape(1,X.shape[1])) cost = (1/m)*np.sum(dis) return cost
Python
nomic_cornstack_python_v1
comment encoding=utf8 string Author: 'jdwang' Date: 'create date: 2016-06-23' Email: '383287471@qq.com' Describe: CNN base class 提供一些公共的函数 import logging import numpy as np from sklearn.metrics import f1_score import pickle as pickle from base.common_model_class import CommonModel import sys call setrecursionlimit 1500...
#encoding=utf8 """ Author: 'jdwang' Date: 'create date: 2016-06-23' Email: '383287471@qq.com' Describe: CNN base class 提供一些公共的函数 """ import logging import numpy as np from sklearn.metrics import f1_score import pickle as pickle from base.common_model_class import CommonModel impo...
Python
zaydzuhri_stack_edu_python
import base64 function hexToBase64 s begin set decodedString = call fromhex s print string Plain text is = decodedString set base64EncodedString = base64 encode decodedString return decode base64EncodedString end function if __name__ == string __main__ begin set s = input string Enter string to be converted set cyphert...
import base64 def hexToBase64(s): decodedString = bytes.fromhex(s) print("Plain text is = ",decodedString) base64EncodedString = base64.b64encode(decodedString) return base64EncodedString.decode() if __name__ == "__main__": s = input("Enter string to be converted\n") cyphertext = hexToBase6...
Python
zaydzuhri_stack_edu_python
from ipywidgets import IntProgress from IPython.display import display , clear_output from copy import deepcopy from collections.abc import Iterator class ProgressBar begin string .. codeauthor:: Wilfried Mercier - IRAP <wilfried.mercier@irap.omp.eu> Implements an easy to use progressbar for Jupyter notebooks. .. note:...
from ipywidgets import IntProgress from IPython.display import display, clear_output from copy import deepcopy from collections.abc import Iterator class ProgressBar: r''' .. codeauthor:: Wilfried Mercier - IRAP <wilfried.mercier@irap.omp.eu> Implements an easy to use progress...
Python
zaydzuhri_stack_edu_python
function make_state_dcd_files topology timestep=5 * femtosecond time_interval=200 output_dir=string output output_data=string output.nc checkpoint_data=string output_checkpoint.nc frame_begin=0 frame_stride=1 center=true begin set file_list = list set output_data_path = join path output_dir output_data comment Get num...
def make_state_dcd_files( topology, timestep=5*unit.femtosecond, time_interval=200, output_dir="output", output_data="output.nc", checkpoint_data="output_checkpoint.nc", frame_begin=0, frame_stride=1, center=True): file_list = [] output_data_path = os.path.join(output_dir, output_data) ...
Python
nomic_cornstack_python_v1
comment data.py就是自訂的module comment 空氣品質AQI的csv檔,線上下載 set FILE_NAME = string aqi.csv set aqiData = none class County begin function __init__ self begin set siteName = none set name = none set AQI = none set status = none set publishTime = none end function end class function downloadAQIDataFromPlatForm begin string 從政府開...
#data.py就是自訂的module #空氣品質AQI的csv檔,線上下載 FILE_NAME = "aqi.csv" aqiData = None class County: def __init__(self): self.siteName = None self.name = None self.AQI = None self.status = None self.publishTime = None def downloadAQIDataFromPlatForm(): """ 從政府開放平台下載行政院aqi的資料,...
Python
zaydzuhri_stack_edu_python
import pandas import re import xlrd import traceback comment from xlrd.xldate.XLDateAmbiguous import XLDateAmbiguous string INTERASIA LINES(IAL:IALK) comment _io = 'C:\\KLNET\\12월 9일자 스케줄.xlsx' class parser begin set _line_code = string IAL set _sheet = none set _filename = none function __init__ self filename begin se...
import pandas import re import xlrd import traceback # from xlrd.xldate.XLDateAmbiguous import XLDateAmbiguous """ INTERASIA LINES(IAL:IALK) """ # _io = 'C:\\KLNET\\12월 9일자 스케줄.xlsx' class parser(): _line_code = "IAL" _sheet = None _filename = None def __init__(self, filename): self._...
Python
zaydzuhri_stack_edu_python
function do_role_detail gc args begin set filter_keys = list string id set filter_items = list comprehension tuple key get attribute args key for key in filter_keys set filters = dictionary list comprehension item for item in filter_items if item at 1 is not none set fields = dictionary filter lambda x -> x at 1 is not...
def do_role_detail(gc, args): filter_keys = ['id'] filter_items = [(key, getattr(args, key)) for key in filter_keys] filters = dict([item for item in filter_items if item[1] is not None]) fields = dict(filter(lambda x: x[1] is not None, vars(args).items())) kwargs = {'filters': filters} if filte...
Python
nomic_cornstack_python_v1
function init_process self begin acquire master_lock set index = random integer MAX_NUMBER_OF_TORCS_PORTS set my_port_lock = port_locks at index for i in range length port_locks begin comment torcs ports are between 3001 and 3010 set port_number = 3001 + i if port_number in ddpg_wrong_ports begin print string Using dif...
def init_process(self): Torcs.master_lock.acquire() index = np.random.randint(Torcs.MAX_NUMBER_OF_TORCS_PORTS) self.my_port_lock = Torcs.port_locks[index] for i in range(len(Torcs.port_locks)): port_number = 3001 + i # torcs ports are between 3001 and 3010 if por...
Python
nomic_cornstack_python_v1
function method self begin return _method end function
def method(self): return self._method
Python
nomic_cornstack_python_v1
function __fill_identity self begin set zero_params = list 0 0 0 comment Initialize a brickwork mould and fill all blanks with identity gates set __bw_mould = dict for row in range __width begin if row in __measured_qubits begin for col in range __bw_depth + 1 begin set __bw_mould at tuple row 4 * col = list string u ...
def __fill_identity(self): zero_params = [0, 0, 0] # Initialize a brickwork mould and fill all blanks with identity gates self.__bw_mould = {} for row in range(self.__width): if row in self.__measured_qubits: for col in range(self.__bw_depth + 1): ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment -*- coding: utf-8 -*- import math from matrix_input import matrix_input set tuple matrix n = call matrix_input for i in range n begin for j in range n begin if matrix at i at j != matrix at j at i begin call quit string матрица не симметрична end end end print string введите вектор b: s...
#!/usr/bin/python # -*- coding: utf-8 -*- import math from matrix_input import matrix_input matrix, n = matrix_input() for i in range(n): for j in range(n): if matrix[i][j] != matrix[j][i]: quit('матрица не симметрична') print('введите вектор b:') vector = [int(input()) for i in range(n)] u ...
Python
zaydzuhri_stack_edu_python
function sort_dict d begin return ordered dictionary list comprehension tuple k d at k for k in sorted keys d end function
def sort_dict(d): return OrderedDict([(k, d[k]) for k in sorted(d.keys())])
Python
nomic_cornstack_python_v1
function sort_sam sam_file_name overwrite=false begin set file_path = join string split sam_file_name string . at slice 0 : - 1 : set file_name = join string split file_path string / at - 1 set sorted_bam_output_path = string %s.sorted % file_path set bam_output_path = string %s.bam % file_path if not exists path sor...
def sort_sam(sam_file_name, overwrite=False): file_path = ''.join(sam_file_name.split('.')[0:-1]) file_name = ''.join(file_path.split('/')[-1]) sorted_bam_output_path = '%s.sorted' % file_path bam_output_path = '%s.bam' % file_path if not os.path.exists(sorted_bam_output_path) or overwrite: ...
Python
nomic_cornstack_python_v1
function divisors x begin set List_divisors = list for i in range 1 x + 1 begin if x % i == 0 begin append List_divisors i end end return List_divisors end function function run begin try begin set x = integer input string ingrese un numero: assert x > 0 msg string print call divisors x end except ValueError begin pr...
def divisors(x): List_divisors = [] for i in range(1, x + 1): if x % i == 0: List_divisors.append(i) return List_divisors def run(): try: x = int(input("ingrese un numero: ")) assert x > 0, "" print(divisors(x)) except ValueError: print("ingrese u...
Python
zaydzuhri_stack_edu_python
function block_name block_id begin return format string progressive_gan_block{} block_id end function
def block_name(block_id): return 'progressive_gan_block{}'.format(block_id)
Python
nomic_cornstack_python_v1
function get__by__column__lower self dbSession column search allow_many=false begin set items = all if items begin if not allow_many begin if length items > 1 begin raise call ValueError string get__by__column__lower should return 1 and only 1 item end else if length items == 1 begin return items at 0 end end else begi...
def get__by__column__lower( self, dbSession, column , search , allow_many=False ): items= dbSession.query(self.__class__).filter( sqlalchemy.sql.func.lower( getattr( self.__class__ , column ) ) == search.lower() ).all() if items: if not allow_many: if len(items) > 1 : ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- encoding: utf-8 -*- comment Copyright (c) 2013 ASMlover. All rights reserved. comment Redistribution and use in source and binary forms, with or without comment modification, are permitted provided that the following conditions comment are met: comment * Redistributions of sourc...
#!/usr/bin/env python # -*- encoding: utf-8 -*- # # Copyright (c) 2013 ASMlover. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyrig...
Python
zaydzuhri_stack_edu_python
function listen self begin if not axis_data begin set axis_data = dict end if not button_data begin set button_data = dict for i in range call get_numbuttons begin set button_data at i = false end end if not hat_data begin set hat_data = dict for i in range call get_numhats begin set hat_data at i = tuple 0 0 end en...
def listen(self): if not self.axis_data: self.axis_data = {} if not self.button_data: self.button_data = {} for i in range(self.controller.get_numbuttons()): self.button_data[i] = False if not self.hat_data: self.hat_data = {} ...
Python
nomic_cornstack_python_v1
function add_categories self categories begin set categories_id = call get_categories_id coco at string categories set cat_name = list keys categories_id set cat_id = list values categories_id set max_id = 0 if cat_id begin set max_id = max cat_id end for item in categories begin set name = item at string name set id =...
def add_categories(self, categories): categories_id = COCOTools.get_categories_id(self.coco["categories"]) cat_name = list(categories_id.keys()) cat_id = list(categories_id.values()) max_id = 0 if cat_id: max_id = max(cat_id) for item in categories: ...
Python
nomic_cornstack_python_v1
import datetime import urllib3 import xmltodict from http import client import logging from collections import OrderedDict import math set RELIABLE_WEBSITE1 = string www.google.com set RELIABLE_WEBSITE2 = string www.amazon.com class InternetConnectionChecker extends object begin string This class helps determine whethe...
import datetime import urllib3 import xmltodict from http import client import logging from collections import OrderedDict import math RELIABLE_WEBSITE1 = "www.google.com" RELIABLE_WEBSITE2 = "www.amazon.com" class InternetConnectionChecker(object): """ This class helps determine whether we have access to we...
Python
zaydzuhri_stack_edu_python
function _set_solver_print self level=2 type_=string all begin call _set_solver_print level=level type_=type_ if precon is not none and type_ != string NL begin call _set_solver_print level=level type_=type_ end end function
def _set_solver_print(self, level=2, type_='all'): super()._set_solver_print(level=level, type_=type_) if self.precon is not None and type_ != 'NL': self.precon._set_solver_print(level=level, type_=type_)
Python
nomic_cornstack_python_v1
function test self *test_files array_rate=none begin comment imports import soundfile as sf import resampy from museval.metrics import Framing import numpy as np set audios = list set maxlen = 0 if is instance test_files str begin set test_files = list test_files end if absolute and length test_files > 1 begin if verb...
def test(self, *test_files, array_rate=None): # imports import soundfile as sf import resampy from museval.metrics import Framing import numpy as np audios = [] maxlen = 0 if isinstance(test_files, str): test_files = [test_files] if s...
Python
nomic_cornstack_python_v1
import functools class HashTable extends object begin string Summary of class here. Longer class information.... Longer class information.... Attributes: MULT: Base value for updating current additive hash code in the string_hash() method. Helps provide large range of values. Important to try to choose prime numbers th...
import functools class HashTable(object): """Summary of class here. Longer class information.... Longer class information.... Attributes: MULT: Base value for updating current additive hash code in the string_hash() method. Helps provide large range of values. Imp...
Python
zaydzuhri_stack_edu_python
string Automatic Snapshots - CCS prod each day we make a snapshot and save it in the daily dir if it is the first day of the month we save it in the monthly dir Save last four dailies - in daily directory Save last four months - in monthly directory Snapshot components: userContent, curriculum and docRoot approximate s...
""" Automatic Snapshots - CCS prod each day we make a snapshot and save it in the daily dir if it is the first day of the month we save it in the monthly dir Save last four dailies - in daily directory Save last four months - in monthly directory Snapshot components: userContent, curriculum and docRoot approximate s...
Python
zaydzuhri_stack_edu_python
import time import numpy as np import theano import theano.tensor as T import lasagne comment We will not use any of these layers in training, so we can cut a lot comment of corners comment This sends a distribution between -1 and 1 to 0 and 1, scaling by 0.5 and comment adding +0.5 y-offset function hard_sigmoid x beg...
import time import numpy as np import theano import theano.tensor as T import lasagne # We will not use any of these layers in training, so we can cut a lot # of corners # This sends a distribution between -1 and 1 to 0 and 1, scaling by 0.5 and # adding +0.5 y-offset def hard_sigmoid(x): return T.clip((x+1.)/...
Python
zaydzuhri_stack_edu_python
class calculadora begin function sumar self a b begin return a + b end function function restar self a b begin return a - b end function end class
class calculadora : def sumar(self,a,b): return a + b def restar(self,a,b): return a - b
Python
zaydzuhri_stack_edu_python
function setMitM self value begin if value begin set mitm = true if arpThread is none begin set arpThread_stop = event set arpThread = thread target=PARPThread args=tuple host call Host string 192.168.1.1 string 192.168.1.1 string 192.168.1.1 arpThread_stop start arpThread end end else begin set mitm = false if arpThre...
def setMitM(self, value): if value: self.mitm = True if self.arpThread is None: self.arpThread_stop = threading.Event() self.arpThread = threading.Thread(target=PARPThread, args=(self.host, Host("192.168.1.1", "192.168.1.1", "192.168.1.1"), self.arpThread_...
Python
nomic_cornstack_python_v1
string 面试题 08.12. 八皇后 设计一种算法,打印 N 皇后在 N × N 棋盘上的各种摆法,其中每个皇后都不同行、不同列,也不在对角线上。 这里的“对角线”指的是所有的对角线,不只是平分整个棋盘的那两条对角线。 注意:本题相对原题做了扩展 示例: 输入:4 输出:[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]] 解释: 4 皇后问题存在如下两个不同的解法。 [ [".Q..", // 解法 1 "...Q", "Q...", "..Q."], ["..Q.", // 解法 2 "Q...", "...Q", ".Q.."] ] from typi...
""" 面试题 08.12. 八皇后 设计一种算法,打印 N 皇后在 N × N 棋盘上的各种摆法,其中每个皇后都不同行、不同列,也不在对角线上。 这里的“对角线”指的是所有的对角线,不只是平分整个棋盘的那两条对角线。 注意:本题相对原题做了扩展 示例: 输入:4 输出:[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]] 解释: 4 皇后问题存在如下两个不同的解法。 [ [".Q..", // 解法 1 "...Q", "Q...", "..Q."], ["..Q.", // 解法 2 "Q...", "...Q", "....
Python
zaydzuhri_stack_edu_python
string read fresnet frame and visualize the local frame on the curve import numpy as np import matplotlib import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D update rcParams dict string font.size 16 import matplotlib.patches as mpatches set fig = figure figsize=tuple 10 20 set ax = call gca projecti...
""" read fresnet frame and visualize the local frame on the curve """ import numpy as np import matplotlib import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D matplotlib.rcParams.update({'font.size': 16}) import matplotlib.patches as mpatches fig = plt.figure(figsize=(10,20)) ax = fig.gca(project...
Python
zaydzuhri_stack_edu_python