code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function templatePath self begin return string modules/gsoc/dashboard/list_component.html end function
def templatePath(self): return'modules/gsoc/dashboard/list_component.html'
Python
nomic_cornstack_python_v1
from sqlalchemy import Column , Integer , String , Float , Date , ForeignKey from sqlalchemy.engine.interfaces import Dialect from sqlalchemy.orm import relationship from db import Database , Base , engine , sessionmaker set db = call Database class City extends Base begin set __tablename__ = string city set id = call ...
from sqlalchemy import Column, Integer, String, Float, Date, ForeignKey from sqlalchemy.engine.interfaces import Dialect from sqlalchemy.orm import relationship from db import Database, Base, engine, sessionmaker db = Database() class City(Base): __tablename__ = 'city' id = Column(Integer, primary_key=True)...
Python
zaydzuhri_stack_edu_python
function find_submatrix_indices array1 array2 begin set tuple n1 m1 = tuple length array1 length array1 at 0 set tuple n2 m2 = tuple length array2 length array2 at 0 for i in range n1 - n2 + 1 begin for j in range m1 - m2 + 1 begin set match = true for k in range n2 begin for l in range m2 begin if array1 at i + k at j...
def find_submatrix_indices(array1, array2): n1, m1 = len(array1), len(array1[0]) n2, m2 = len(array2), len(array2[0]) for i in range(n1 - n2 + 1): for j in range(m1 - m2 + 1): match = True for k in range(n2): for l in range(m2): if array1[...
Python
greatdarklord_python_dataset
function check_event touch_service begin set arm = - 1 comment Get current status of touch sensors set s = call getStatus for e in s begin comment Return 0 if Left Arm sensor is touched if e at 0 == string LArm and e at 1 begin set arm = 0 end end end function
def check_event(touch_service): arm = -1 # Get current status of touch sensors s = touch_service.getStatus() for e in s: # Return 0 if Left Arm sensor is touched if e[0]=='LArm' and e[1]: arm = 0
Python
nomic_cornstack_python_v1
class Solution begin function bitwiseComplement self N begin set b_N = binary N set count = 0 set res = 0 for i in range length b_N - 1 1 - 1 begin if b_N at i == string 0 begin set res = res + 2 ^ count set count = count + 1 end else if b_N at i == string 1 begin set count = count + 1 end end return res end function e...
class Solution: def bitwiseComplement(self, N: int) -> int: b_N = bin(N) count = 0 res = 0 for i in range(len(b_N)-1, 1, -1): if b_N[i] == '0': res += 2**count count += 1 elif b_N[i] == '1': count += 1 r...
Python
zaydzuhri_stack_edu_python
function SetPointSetSigma self _arg begin return call itkExpectationBasedPointSetToPointSetMetricv4PSD2_SetPointSetSigma self _arg end function
def SetPointSetSigma(self, _arg: 'float const') -> "void": return _itkExpectationBasedPointSetToPointSetMetricv4Python.itkExpectationBasedPointSetToPointSetMetricv4PSD2_SetPointSetSigma(self, _arg)
Python
nomic_cornstack_python_v1
function multiplicative_cipher_encrypt plain_text key begin set encryptedtext = string for c in plain_text begin if is upper c begin set index = ordinal c - ordinal string A set c_shift = index * key % 26 + ordinal string A set c_new = character c_shift set encryptedtext = encryptedtext + c_new end else if is lower c ...
def multiplicative_cipher_encrypt(plain_text, key): encryptedtext = "" for c in plain_text: if c.isupper(): index = ord(c) - ord('A') c_shift = (index * key) % 26 + ord('A') c_new = chr(c_shift) encryptedtext += c_new elif c.islower(): ...
Python
zaydzuhri_stack_edu_python
import Adafruit_MPR121.MPR121 as MPR121 import cv2 import itertools import math import random import numpy as np import sys set X_RES = 192 set Y_RES = 108 set NUM_X = 8 set NUM_Y = 4 set COV_MULT = 0.1 set DEBUG_TOUCH = false set DEBUG_IMAGE = false set DEBUG_CENTERS = false set EMPTY_TOUCH_STATE = list 0 0 0 0 0 0 0 ...
import Adafruit_MPR121.MPR121 as MPR121 import cv2 import itertools import math import random import numpy as np import sys X_RES = 192 Y_RES = 108 NUM_X = 8 NUM_Y = 4 COV_MULT = 0.1 DEBUG_TOUCH = False DEBUG_IMAGE = False DEBUG_CENTERS = False EMPTY_TOUCH_STATE = [0,0,0,0,0,0,0,0,0,0,0,0] IMAGE_NAME = "rendering" ...
Python
zaydzuhri_stack_edu_python
from django import forms from django.contrib.auth.hashers import check_password from airtic.models import User class LoginForm extends Form begin set username = call CharField max_length=10 required=true error_messages=dict string required string 用户名必填 ; string max_length string 用户名不能超过20字符 set pwd = call CharField max...
from django import forms from django.contrib.auth.hashers import check_password from airtic.models import User class LoginForm(forms.Form): username = forms.CharField(max_length=10, required=True, error_messages={'required': '用户名必填', 'max_length': '用户名不能超过20字符', ...
Python
zaydzuhri_stack_edu_python
import numpy as np function unit_range arr data_min=none data_max=none samples_in=string row begin string Normalize the data to have unit range. Return the normalized data, and the min, and max used. Data is assumed to be in row samples If data is arranged in column samples, use samples_in='col' Computes norm_arr = (ar...
import numpy as np def unit_range(arr, data_min=None, data_max=None, samples_in='row'): """ Normalize the data to have unit range. Return the normalized data, and the min, and max used. Data is assumed to be in row samples If data is arranged in column samples, use samples_in='col' Computes...
Python
zaydzuhri_stack_edu_python
function _get_short self url cutoff=4 begin comment Base64-encode the MD5 digest of the URL set short = base64 encode call digest at slice - cutoff : : comment Remove radix-64 padding characters '=' set short = replace short string = string comment Replace reserved character '/' by underscore return replace short stri...
def _get_short(self, url, cutoff=4): # Base64-encode the MD5 digest of the URL short = base64.b64encode(md5.new(url).digest()[-cutoff:]) # Remove radix-64 padding characters '=' short = short.replace('=', '') # Replace reserved character '/' by underscore return short.rep...
Python
nomic_cornstack_python_v1
function _analyze self tree original_lines begin try begin set analyzer = call SourceAnalyzer original_lines call visit tree set tuple source_stats import_stats = call get_stats return tuple source_stats import_stats end except Exception as err begin call failure string err _path return none end end function
def _analyze( self, tree: ast.AST, original_lines: List[str] ) -> Tuple[scan.SourceStats, scan.ImportStats]: try: analyzer = scan.SourceAnalyzer(original_lines) analyzer.visit(tree) source_stats, import_stats = analyzer.get_stats() return source_stats,...
Python
nomic_cornstack_python_v1
function has_elev_bounds self begin if call has_bounds begin if string bounds in metadata begin return metadata at string bounds == string elev_bounds end if VERT_COORD in metadata begin return string elev_bounds in metadata at VERT_COORD end end end function
def has_elev_bounds(self): if self.has_bounds(): if 'bounds' in self.metadata: return self.metadata['bounds'] == 'elev_bounds' if const.VERT_COORD in self.metadata: return 'elev_bounds' in self.metadata[const.VERT_COORD]
Python
nomic_cornstack_python_v1
function execute_bulk_insert_aws_pricing self query data=none arg_str=none begin set data_str = join string , generator expression decode call mogrify arg_str tuple row at slice 1 : : string utf-8 for row in call itertuples execute __cursor query + data_str end function
def execute_bulk_insert_aws_pricing(self, query, data=None, arg_str=None): data_str = ','.join(self.__cursor.mogrify(arg_str, tuple(row[1:])).decode('utf-8') for row in data.itertuples()) self.__cursor.execute(query + data_str)
Python
nomic_cornstack_python_v1
function get_supplier self code begin set endpoint = string { endpoint_base } /suppliers/ { code } / return search endpoint end function
def get_supplier(self, code): endpoint = f'{self.endpoint_base}/suppliers/{code}/' return self._api.search(endpoint)
Python
nomic_cornstack_python_v1
function pushnotify subject message api=string pushover priority=0 timestamp=none begin string Send push notifications using pre-existing APIs Requires a config `pushnotify.ini` file in the user home area containing the necessary api tokens and user keys. Default API: "pushover" Config file format: ------------------- ...
def pushnotify(subject, message, api="pushover", priority=0, timestamp=None): """ Send push notifications using pre-existing APIs Requires a config `pushnotify.ini` file in the user home area containing the necessary api tokens and user keys. Default API: "pushover" Config file format: --...
Python
jtatman_500k
function __repr__ self begin return string PVT( upper_glass: { upper_glass } , glass: { glass } , pv: { pv } , eva: { eva } , adhesive: { adhesive } tedlar: { tedlar } absorber: { absorber } , bond: { bond } , outer_pipe_diameter: { outer_pipe_diameter } m (ta)_ug = { upper_glass_transmissivity_absorptivity_product } (...
def __repr__(self) -> str: return ( "PVT(\n" f" upper_glass: {self.upper_glass},\n" f" glass: {self.glass},\n" f" pv: {self.pv},\n" f" eva: {self.eva},\n" f" adhesive: {self.adhesive}\n" f" tedlar: {self.tedlar}\n" ...
Python
nomic_cornstack_python_v1
function quickAddEvent client calendarName content=string Tennis with John today 3pm-3:30pm begin set event = call CalendarEventEntry set content = call Content text=content set quick_add = call QuickAdd value=string true set new_event = call InsertEvent event string /calendar/feeds/%s/private/full % tuple calendarName...
def quickAddEvent(client, calendarName, content="Tennis with John today 3pm-3:30pm"): event = calendar.CalendarEventEntry() event.content = atom.Content(text=content) event.quick_add = calendar.QuickAdd(value='true'); new_event = client.InsertEvent(event, '/calendar/feeds/%s/private/full' % (ca...
Python
nomic_cornstack_python_v1
function mark_need_resolved need_id begin set need = get Need need_id comment Check validity of need_id if not need begin return call api_error string Need not found end if not is_admin and id != user_id begin return call api_error string Permission denied end if resolved begin return call api_error string Need already...
def mark_need_resolved(need_id): need = Need.get(need_id) # Check validity of need_id if not need: return api_error('Need not found') if not current_user.is_admin and current_user.id != need.alert.user_id: return api_error('Permission denied') if need.resolved: return api_er...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Tue Jun 2 12:52:57 2020 @author: tony import pickle import os import time import traceback import sys from sys import argv from src.utils.scraping import scroll_down , get_links , get_article_text , get_driver , login set tuple script search_terms save_dir = argv set sear...
# -*- coding: utf-8 -*- """ Created on Tue Jun 2 12:52:57 2020 @author: tony """ import pickle import os import time import traceback import sys from sys import argv from src.utils.scraping import scroll_down, get_links, get_article_text, get_driver, login script, search_terms, save_dir = argv search_list = list(ma...
Python
zaydzuhri_stack_edu_python
function folder self begin return get pulumi self string folder end function
def folder(self) -> Optional['outputs.DatasetResponseFolder']: return pulumi.get(self, "folder")
Python
nomic_cornstack_python_v1
function get_account_by_id self id begin return call find_by_key id end function
def get_account_by_id(self, id): return self.__account_mapper.find_by_key(id)
Python
nomic_cornstack_python_v1
function get_sys_name self begin return call call_sdk_function string PrlVmDevHdPart_GetSysName handle end function
def get_sys_name(self): return call_sdk_function('PrlVmDevHdPart_GetSysName', self.handle)
Python
nomic_cornstack_python_v1
string Example reStructuredText from Sphinx-Needs project. From http://sphinxcontrib-needs.readthedocs.io/en/latest/ but will not work in isolation - cut down just to trigger RST304. **Some text** Wohooo, we have created :need:`req_001`, which is linked by :need_incoming:`req_001`. print string sphinx-needs defines its...
"""Example reStructuredText from Sphinx-Needs project. From http://sphinxcontrib-needs.readthedocs.io/en/latest/ but will not work in isolation - cut down just to trigger RST304. **Some text** Wohooo, we have created :need:`req_001`, which is linked by :need_incoming:`req_001`. """ print("sphinx-needs defines its ...
Python
jtatman_500k
class Solution begin function insert self intervals newInterval begin set tuple left right = tuple none none set tuple s e = tuple newInterval at 0 newInterval at 1 comment 3个edge cases comment intervals为空,新区间在所有老区间左边,新区间在所有老区间右边 if length intervals == 0 begin return list newInterval end if intervals at 0 at 0 > e begi...
class Solution: def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: left, right = None, None s,e = newInterval[0], newInterval[1] # 3个edge cases # intervals为空,新区间在所有老区间左边,新区间在所有老区间右边 if len(intervals)==0: return [newInterval] if in...
Python
zaydzuhri_stack_edu_python
function _collect_induced_spikes spikes input_targeted_times trial_length_ms targeted_gid begin set inter_induction_wins = call make_windows input_targeted_times tuple 0 trial_length_ms set inter_induction_wins = call ExclusiveWindows inter_induction_wins set targeted_spikes = spikes at gid == targeted_gid set targeted...
def _collect_induced_spikes(spikes, input_targeted_times, trial_length_ms, targeted_gid): inter_induction_wins = spt.make_windows(input_targeted_times, (0, trial_length_ms)) inter_induction_wins = spt.ExclusiveWindows(inter_induction_wins) targeted_spikes = spikes[spikes.gid == targeted_gid] targeted_sp...
Python
nomic_cornstack_python_v1
import pygame import game_fuctions as gf import random set size = list 800 800 set screen = call set_mode size set bg = load image string bg.jpg comment Colors set WHITE = tuple 255 255 255 set BLACK = tuple 0 0 0 set player = call Player 50 400 set list_cubs_condition = false set cubs = list set k = 0 print length cu...
import pygame import game_fuctions as gf import random size = [800,800] screen = pygame.display.set_mode(size) bg = pygame.image.load("bg.jpg") #Colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) player = gf.Player(50, 400) list_cubs_condition = False cubs = [] k = 0 print(len(cubs)) last_obj = 12 first_ob...
Python
zaydzuhri_stack_edu_python
function test_init self begin set purchase = call Purchase assert equal string where assert equal string when assert equal string url set purchase = call Purchase call TextType string Amazon call TextType string 2011-11-10 call TextType string http://amazon.de/dp/B001CIEOD8 assert equal string Amazon where assert eq...
def test_init(self): purchase = Purchase() self.assertEqual("", purchase.where) self.assertEqual("", purchase.when) self.assertEqual("", purchase.url) purchase = Purchase(TextType("Amazon"), TextType("2011-11-10"), TextType("http://amazon.de/dp/B001CI...
Python
nomic_cornstack_python_v1
function _get_api_resource_type_name self begin return string AWS::Serverless::HttpApi end function
def _get_api_resource_type_name(self): return "AWS::Serverless::HttpApi"
Python
nomic_cornstack_python_v1
function l2 self begin return call get_l2 end function
def l2(self): return self._internal.get_l2()
Python
nomic_cornstack_python_v1
function enabled self begin return get pulumi self string enabled end function
def enabled(self) -> str: return pulumi.get(self, "enabled")
Python
nomic_cornstack_python_v1
function dist s_i s_j g_i g_j begin return absolute s_i - g_i + absolute s_j - g_j end function function solve wait_A wait_B state_A state_B begin global min_ set t = 0 while wait_A or wait_B or count state_A 0 != 3 or count state_B 0 != 3 begin if t > min_ begin set t = t + 1 break end for i in range 3 begin if state_...
def dist(s_i, s_j, g_i, g_j): return abs(s_i-g_i)+abs(s_j-g_j) def solve(wait_A, wait_B, state_A, state_B): global min_ t = 0 while wait_A or wait_B or state_A.count(0) != 3 or state_B.count(0) != 3: if t>min_: t += 1 break for i in range(3): if sta...
Python
zaydzuhri_stack_edu_python
function __init__ self element gdim=none begin if family == custom begin set _is_custom = true set repr = string custom Basix element ( { call _compute_signature element } ) end else begin set _is_custom = false set repr = string Basix element ( { name } , { name } , { degree } , { name } , { name } , { discontinuous }...
def __init__(self, element: _basix.finite_element.FiniteElement, gdim: _typing.Optional[int] = None): if element.family == _basix.ElementFamily.custom: self._is_custom = True repr = f"custom Basix element ({_compute_signature(element)})" else: self._is_custom = False ...
Python
nomic_cornstack_python_v1
import numpy as np import pandas as pd from datetime import datetime from sklearn.linear_model import LinearRegression from sklearn.model_selection import TimeSeriesSplit from sklearn.metrics import mean_absolute_error from sklearn.metrics import mean_squared_error set path = string data/clean/train.csv set db = read c...
import numpy as np import pandas as pd from datetime import datetime from sklearn.linear_model import LinearRegression from sklearn.model_selection import TimeSeriesSplit from sklearn.metrics import mean_absolute_error from sklearn.metrics import mean_squared_error path = "data/clean/train.csv" db = pd.read_csv(path) ...
Python
zaydzuhri_stack_edu_python
function serialize self buff begin try begin set _x = self write buff call pack seq secs nsecs set _x = frame_id set length = length _x if python3 or type _x == unicode begin set _x = encode _x string utf-8 set length = length _x end write buff call pack length _x set _x = self write buff call pack voltage current leve...
def serialize(self, buff): try: _x = self buff.write(_get_struct_3I().pack(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs)) _x = self.header.frame_id length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) buff.writ...
Python
nomic_cornstack_python_v1
function changeTrafficLight state begin if state == NORTH_SUTH_GREEN begin call setRedYellowGreenState string node0 string GGGGGrrrrrGGGGGrrrrr end else if state == NORTH_SUTH_YELLOW begin call setRedYellowGreenState string node0 string yyyyyrrrrryyyyyrrrrr end else if state == WEST_EST_GREEN begin call setRedYellowGre...
def changeTrafficLight(state): if state == TrafficState.NORTH_SUTH_GREEN: traci.trafficlight.setRedYellowGreenState("node0", "GGGGGrrrrrGGGGGrrrrr") elif state == TrafficState.NORTH_SUTH_YELLOW: traci.trafficlight.setRedYellowGreenState('node0', 'yyyyyrrrrryyyyyrrrrr') elif state == Traffic...
Python
nomic_cornstack_python_v1
function _allocate_power self begin comment number of powerplants set size = length powerplants comment initialize an allocation snapshot set allocation = dict string p_list list 0 * size ; string curr_index 0 function _reallocate allocation new_power new_index begin string Update and return a new allocation snapshot. ...
def _allocate_power(self): # number of powerplants size = len(self.powerplants) # initialize an allocation snapshot allocation = { 'p_list': [0] * size, 'curr_index': 0 } def _reallocate(allocation, new_power, new_index): """Update an...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import json import csv set data = dict string uberon_to_fma dict ; string fma_to_uberon dict with open string uberon_fma.csv string rb as csvfile begin set reader = reader csvfile delimiter=string , comment skip the first line, which is just a header next reader none for row in reader beg...
#!/usr/bin/env python import json import csv data = { 'uberon_to_fma': {}, 'fma_to_uberon': {} } with open('uberon_fma.csv', 'rb') as csvfile: reader = csv.reader(csvfile, delimiter=',') next(reader, None) # skip the first line, which is just a header for row in reader: uberon_id = row[0...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Wed Feb 17 14:59:09 2021 @author: mikva import numpy as np import sparse class Simulator begin function __init__ self gates register custom measurements begin set gates = gates set register = register set singlegates = dict string x array list list 0 1 list 1 0 ; string y...
# -*- coding: utf-8 -*- """ Created on Wed Feb 17 14:59:09 2021 @author: mikva """ import numpy as np import sparse class Simulator(): def __init__(self, gates, register, custom, measurements): self.gates = gates self.register = register self.singlegates = {'x' : np.array([[0,1], [1,0]]), ...
Python
zaydzuhri_stack_edu_python
function reportRates allData begin if not DATA_ONLY begin call reportMonitorRates allData call reportSupernovaRates allData call reportTimeCalRates allData end call reportDataRates allData end function
def reportRates(allData): if not DATA_ONLY: reportMonitorRates(allData) reportSupernovaRates(allData) reportTimeCalRates(allData) reportDataRates(allData)
Python
nomic_cornstack_python_v1
function getSum dp pos s e type_ begin if e < s begin return 0 end if type_ == string D begin if e == m - 1 begin return dp at pos at s end return dp at pos at s - dp at pos at e + 1 end else begin if e == n - 1 begin return dp at s at pos end return dp at s at pos - dp at e + 1 at pos end end function set mod = 10 ^ 9...
def getSum(dp, pos, s, e, type_): if e < s: return 0 if type_=='D': if e==m-1: return dp[pos][s] return dp[pos][s]-dp[pos][e+1] else: if e==n-1: return dp[s][pos] return dp[s][pos]-dp[e+1][pos] mod = 10**9+7 n, m = map(int, input(...
Python
jtatman_500k
class User begin function __init__ self first_name last_name begin set first_name = first_name set last_name = last_name end function function describe_user self begin print string First name: { first_name } , Last name: { last_name } end function function greet_user self begin print string Greetings of the day, { firs...
class User: def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name def describe_user(self): print(f"First name: {self.first_name}, Last name: {self.last_name}") def greet_user(self): print(f"Greetings of the day, {self.first_name}!"...
Python
zaydzuhri_stack_edu_python
function multivariate_t_samples matrix df N mean=none begin if mean is none begin set mean = zeros N shape at 0 end set d = length matrix if df == inf begin set x = 1.0 end else begin set x = call chisquare df N / df end set z = call multivariate_normal zeros d matrix N comment same output format as random.multivariate...
def multivariate_t_samples(matrix, df, N, mean=None): if mean is None: mean = np.zeros(N,matrix.shape[0]) d = len(matrix) if df == np.inf: x = 1. else: x = np.random.chisquare(df, N)/df z = np.random.multivariate_normal(np.zeros(d), matrix, N) return mean + z/np.sqrt(x)[...
Python
nomic_cornstack_python_v1
import random import requests comment Incorrect URL set url = string http://exa78mpe.com comment Generate a random position to replace a character set position = random integer 0 length url - 1 comment Generate a random character to replace at the chosen position set new_char = random choice string abcdefghijklmnopqrst...
import random import requests # Incorrect URL url = "http://exa78mpe.com" # Generate a random position to replace a character position = random.randint(0, len(url) - 1) # Generate a random character to replace at the chosen position new_char = random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345...
Python
jtatman_500k
function run self begin comment Update time call set_time comment Error catcher try begin set name = CONFIG at string logfiletowatch set current = open name string r set curino = st_ino set buf = read lines current while true begin while true begin set buf = read lines current if length buf == 0 begin break end for row...
def run(self): # # Update time # self.set_time() # # Error catcher # try: name = self.CONFIG['logfiletowatch'] current = open(name, "r") curino = os.fstat(current.fileno()).st_ino buf=current.readlines() ...
Python
nomic_cornstack_python_v1
function setServerLogLevel self *args **kwargs begin return call EClient_setServerLogLevel self *args keyword kwargs end function
def setServerLogLevel(self, *args, **kwargs): return _swigibpy.EClient_setServerLogLevel(self, *args, **kwargs)
Python
nomic_cornstack_python_v1
from math import log function getDigit num base digit_num begin return num // base ^ digit_num % base end function function makeBlanks size begin return list comprehension list for i in range size end function function split sequence base digit_num begin set buckets = call makeBlanks base for num in sequence begin app...
from math import log def getDigit(num, base, digit_num): return (num // base ** digit_num) % base def makeBlanks(size): return [ [] for i in range(size) ] def split(sequence, base, digit_num): buckets = makeBlanks(base) for num in sequence: buckets[getDigit(num, base, digit_num)].append(num) return buc...
Python
zaydzuhri_stack_edu_python
function create_observe_operations self terminal reward index begin string Returns the tf op to fetch when an observation batch is passed in (e.g. an episode's rewards and terminals). Uses the filled tf buffers for states, actions and internals to run the tf_observe_timestep (model-dependent), resets buffer index and i...
def create_observe_operations(self, terminal, reward, index): """ Returns the tf op to fetch when an observation batch is passed in (e.g. an episode's rewards and terminals). Uses the filled tf buffers for states, actions and internals to run the tf_observe_timestep (model-dependent), re...
Python
jtatman_500k
import pandas as lectorCsv import pymongo from pymongo import MongoClient function captura begin set temperatura = read csv string ./Datos/temperature.csv set humedad = read csv string ./Datos/humidity.csv set temperatura = temperatura at list string datetime string San Francisco set temperatura = rename columns=dict s...
import pandas as lectorCsv import pymongo from pymongo import MongoClient def captura(): temperatura = lectorCsv.read_csv("./Datos/temperature.csv") humedad = lectorCsv.read_csv("./Datos/humidity.csv") temperatura = temperatura[['datetime','San Francisco']] temperatura = temperatura.rename(column...
Python
zaydzuhri_stack_edu_python
while a1 != 0 begin set a1 = a1 + a1 % 2 print format string {} 5 * a1 + 4 set a1 = integer input end
while a1 != 0: a1 += a1 % 2 print('{}'.format(5 * (a1 + 4))) a1 = int(input())
Python
zaydzuhri_stack_edu_python
import cv2 import numpy as np set image = call imread string imgs/one.png set image = call resize image none fx=0.5 fy=0.5 comment h, w, c = image.shape comment image = cv2.resize(image, (int(w/2), int(h/2))) set tuple h w _ = shape set fx = 100 set fy = 50 set M = call float32 list list 1 0.1 fx list 0.1 1 fy set imag...
import cv2 import numpy as np image = cv2.imread("imgs/one.png") image = cv2.resize(image, None, fx=0.5, fy=0.5) #h, w, c = image.shape #image = cv2.resize(image, (int(w/2), int(h/2))) h, w, _ = image.shape fx = 100 fy = 50 M = np.float32([ [1, 0.1, fx], [0.1, 1, fy] ]) image1 = cv2.warpAffine(image, M, (w +...
Python
zaydzuhri_stack_edu_python
async function handle_countdown_reminders begin set reminders = list for tuple tag cd in items dictionary data at string countdown begin set dt = parse pendulum cd at string time tz=cd at string tz set cd = dictionary cd set cd at string tag = tag set cd at string dt = dt append reminders cd end if not reminders begin...
async def handle_countdown_reminders(): reminders = [] for tag, cd in dict(time_cfg.data["countdown"]).items(): dt = pendulum.parse(cd["time"], tz=cd["tz"]) cd = dict(cd) cd["tag"] = tag cd["dt"] = dt reminders.append(cd) if not reminders: return # Go t...
Python
nomic_cornstack_python_v1
import numpy as np from numpy import random set x = random integer 100 size=tuple 5 10 set arr = array list x print sort np arr
import numpy as np from numpy import random x = random.randint(100,size=(5,10)) arr = np.array([x]) print(np.sort(arr))
Python
zaydzuhri_stack_edu_python
function main begin set tuple n m = map int split input set k = list 0 * n for i in range m begin set tuple a b = map int split input set k at a - 1 = k at a - 1 + 1 set k at b - 1 = k at b - 1 + 1 end for i in k begin if i % 2 == 1 begin print string NO exit end end print string YES end function if __name__ == string ...
def main(): n,m=map(int, input().split()) k = [0]*n for i in range(m): a,b=map(int, input().split()) k[a-1]+=1 k[b-1]+=1 for i in k: if i%2==1: print("NO") exit() print("YES") if __name__ == '__main__': main()
Python
zaydzuhri_stack_edu_python
function __ne__ self *args begin return call ccase_t___ne__ self *args end function
def __ne__(self, *args): return _ida_hexrays.ccase_t___ne__(self, *args)
Python
nomic_cornstack_python_v1
comment arrayForProblem2 = ["Kenn", "Kevin", "Erin", "Meka"]
# arrayForProblem2 = ["Kenn", "Kevin", "Erin", "Meka"] #
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Mon Jan 15 15:01:33 2018 @author: haimingwd comment Kadane's algo for 2D array function maxSubArray arr begin set n = length arr set tuple cumSum minCumSum maxSum = tuple 0 0 0 for i in range n begin set cumSum = cumSum + arr at i set minCumSum = min minCumSum cumSum set ...
# -*- coding: utf-8 -*- """ Created on Mon Jan 15 15:01:33 2018 @author: haimingwd """ ## Kadane's algo for 2D array def maxSubArray(arr): n = len(arr) cumSum, minCumSum, maxSum = 0, 0, 0 for i in range(n): cumSum = cumSum + arr[i] minCumSum = min(minCumSum, cumSum) maxSum = max(m...
Python
zaydzuhri_stack_edu_python
function handle_discovery_errors fn begin decorator wraps fn function wrapped *args **kwargs begin try begin return call fn *args keyword kwargs end except tuple ValueError RequestException as e begin warning string exc_info=true return call redirect string /? + url encode dict string failure string e end end function...
def handle_discovery_errors(fn): @functools.wraps(fn) def wrapped(*args, **kwargs): try: return fn(*args, **kwargs) except (ValueError, requests.RequestException) as e: logger.warning('', exc_info=True) return redirect('/?' + urllib.parse.urlencode({'failure': str(e)})) return wrapped
Python
nomic_cornstack_python_v1
for i in range nu begin set x = decimal call raw_input set su = su + x end set prom = su / nu
for i in range(nu): x = float(raw_input()) su = su + x prom = su / nu
Python
zaydzuhri_stack_edu_python
function add_new_artwork begin set artist_name = call get_artist_name if not call artist_already_in_db artist_name begin print string Artist not registered, creating new registration. set email = call get_artist_email set new_artist = call Artist artist_name email call add_artist new_artist end set artwork_name = call ...
def add_new_artwork(): artist_name = get_artist_name() if not controls_utils.artist_already_in_db(artist_name): print('Artist not registered, creating new registration. ') email = get_artist_email() new_artist = Artist(artist_name, email) artwork_db.add_artist(new_artist) art...
Python
nomic_cornstack_python_v1
comment real signature unknown function __init_subclass__ self *args **kwargs begin pass end function
def __init_subclass__(self, *args, **kwargs): # real signature unknown pass
Python
nomic_cornstack_python_v1
comment Leia as variáveis A0, Limite e R e escreva os valores menores que Limite gerados pela Progressão Geométrica que tem por valor inicial A0 e razão R. function main begin set A0 = integer input string Primeiro termo: set limite = integer input string Último número: set r = integer input string Razão: set p = A0 wh...
# Leia as variáveis A0, Limite e R e escreva os valores menores que Limite gerados pela Progressão Geométrica que tem por valor inicial A0 e razão R. def main(): A0 = int(input('Primeiro termo: ')) limite = int(input('Último número: ')) r = int(input('Razão: ')) p = A0 while p < limite: ...
Python
zaydzuhri_stack_edu_python
function likes names begin set like = list set listlike = 0 set c = 0 set a = input string Digite os números de likes: if a == 0 begin print string no one like this end else begin while c < a begin append like input string Set names likes in the list: set c = c + 1 end set listlike = length like end end function
def likes(names): like = [] listlike=0 c=0 a = input('Digite os números de likes: ') if a==0: print('no one like this') else: while c < a: like.append(input('Set names likes in the list: ')) c+=1 listlike=len(like)
Python
zaydzuhri_stack_edu_python
function read_and_pre_process_xml file_name begin with open file_name as xml_file begin return replace read xml_file string string end end function
def read_and_pre_process_xml(file_name): with open(file_name) as xml_file: return xml_file.read().replace('\n', '')
Python
nomic_cornstack_python_v1
import datetime import struct import bz2 function datetime_from_julian julian_date begin set day_one = call date 1970 1 1 return day_one + time delta days=julian_date - 1 end function function time_from_milliseconds millis begin set init_time = call datetime 1970 1 1 0 0 0 return time end function function time_from_mi...
import datetime import struct import bz2 def datetime_from_julian(julian_date): day_one = datetime.date(1970, 1, 1) return day_one + datetime.timedelta(days=julian_date-1) def time_from_milliseconds(millis): init_time = datetime.datetime(1970, 1, 1, 0, 0, 0) return (init_time + datetime.timedelta(mi...
Python
zaydzuhri_stack_edu_python
import os set buffer = bytes set data = b'123456' set buffer = buffer + data print buffer print string sub 1:3 -> buffer at slice 1 : 3 : print string sub 3 -> buffer at slice 3 : : print string sub all -> buffer at slice : :
import os buffer = bytes() data = b'123456' buffer += data print(buffer) print("sub 1:3 ->", buffer[1:3]) print("sub 3 ->", buffer[3:]) print("sub all ->", buffer[:])
Python
zaydzuhri_stack_edu_python
function setUp self begin setup call super set test_assembly_id = string 882083b7-ea62-4aab-aa6a-f0d08d65ee2b set test_etag = string fake_etag set request_id = 1 set account_id = schema at slice 4 : : set manifest_id = 1 set report_name = string koku-1.csv.gz set report_path = string /my/ { test_assembly_id } / { rep...
def setUp(self): super().setUp() self.test_assembly_id = "882083b7-ea62-4aab-aa6a-f0d08d65ee2b" self.test_etag = "fake_etag" self.request_id = 1 self.account_id = self.schema[4:] self.manifest_id = 1 self.report_name = "koku-1.csv.gz" self.report_path = f"...
Python
nomic_cornstack_python_v1
function delete_deals self begin if not call connected begin return end set selected = call get_selected_rows if length selected > 0 begin call taremove_deal map lambda dl -> dl at 0 selected call call_update_callback end end function
def delete_deals(self): if not self._parent.connected(): return selected = self.deals_view.get_selected_rows() if len(selected) > 0: self._parent.model.taremove_deal(map(lambda dl: dl[0], selected)) self._parent.call_update_callback()
Python
nomic_cornstack_python_v1
function leastAbsoluteDeviations filename=string simdata.txt begin comment raise NotImplementedError("Problem 5 Incomplete") set df = read csv filename delimiter=string header=none set data = values set tuple m n = shape set n = n - 1 set c = zeros 3 * m + 2 * n + 1 set c at slice : m : = 1 set y = call empty 2 * m ...
def leastAbsoluteDeviations(filename='simdata.txt'): #raise NotImplementedError("Problem 5 Incomplete") df = pd.read_csv(filename,delimiter=' ',header=None) data = df.values m,n = data.shape n -= 1 c = np.zeros(3*m+2*(n+1)) c[:m] = 1 y = np.empty(2*m) y[::2] = -data[:,0] y[1::2] = d...
Python
nomic_cornstack_python_v1
from tkinter import * from tkinter import messagebox from random import choice comment Fkt zu Messageboxactionen function info_box begin set infotxt = string *********************** Autor: Kevin Rettig Datum: 22.12.2017 Version: 1.2.0 *********************** call showinfo message=infotxt title=string Info end function ...
from tkinter import * from tkinter import messagebox from random import choice #Fkt zu Messageboxactionen def info_box(): infotxt = "***********************\nAutor: Kevin Rettig\nDatum: 22.12.2017\nVersion: 1.2.0\n***********************" messagebox.showinfo(message = infotxt, title = "Info") def d...
Python
zaydzuhri_stack_edu_python
function get_network users_ids as_edgelist=true begin set edges = list set amount = 0 for ind1 in range length users_ids begin for ind2 in range length users_ids begin try begin if users_ids at ind2 in call get_friends users_ids at ind1 at string response at string items begin set edges = edges + list tuple ind1 ind2 ...
def get_network(users_ids, as_edgelist=True): edges = [] amount = 0 for ind1 in range(len(users_ids)): for ind2 in range(len(users_ids)): try: if users_ids[ind2] in get_friends(users_ids[ind1])['response']['items']: edges += [(ind1, ind2)] ...
Python
nomic_cornstack_python_v1
if ordinal alpha >= 65 and ordinal alpha <= 90 begin print character ordinal alpha + 32 end if ordinal alpha >= 90 and ordinal alpha <= 122 begin print character ordinal alpha - 32 end
if ord(alpha)>=65 and ord(alpha)<=90: print(chr(ord(alpha)+32)) if ord(alpha)>=90 and ord(alpha)<=122: print(chr(ord(alpha)-32))
Python
zaydzuhri_stack_edu_python
import tensorflow as tf class discriminator begin function __init__ self state_dim action_dim name action_type begin set state_dim = state_dim set action_dim = action_dim set name = name set action_type = action_type with call variable_scope name begin comment discriminaor estimates whether the (s, a) is the pair of le...
import tensorflow as tf class discriminator: def __init__(self, state_dim, action_dim, name, action_type): self.state_dim = state_dim self.action_dim = action_dim self.name = name self.action_type = action_type with tf.variable_scope(self.name): # discriminaor...
Python
zaydzuhri_stack_edu_python
function CallbackImpl self arg parameters begin raise call NotImplementedError end function
def CallbackImpl(self, arg, parameters): raise NotImplementedError()
Python
nomic_cornstack_python_v1
function test_le_2 begin set a = call FixedPoint 1 string Q2.8 set b = call FixedPoint 1.1 string Q2.8 assert a < b end function
def test_le_2(): a = FixedPoint(1, 'Q2.8') b = FixedPoint(1.1, 'Q2.8') assert a < b
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib.pyplot as plt import pandas as pd from scipy.stats import pearsonr comment Inport data ############ set inputData = string ./questionnaireData.csv set df = read csv inputData header=0 comment remove empty line drop missing df axis=0 inplace=true comment remove secondary column descr...
import numpy as np import matplotlib.pyplot as plt import pandas as pd from scipy.stats import pearsonr ####### Inport data ############ inputData = "./questionnaireData.csv" df = pd.read_csv(inputData,header=0) df.dropna(axis=0,inplace=True) #remove empty line df.drop([0],inplace=True) #remove secondary column descri...
Python
zaydzuhri_stack_edu_python
function expand_short_forms self begin function make_entity x begin return string # + replace x string string _ + string # end function comment Find substitutions set subs = dict for sent in call splitlines begin for tuple s l in call find_short_long_pairs strip sent begin if s not in subs or length l < length subs a...
def expand_short_forms(self): def make_entity(x): return '#' + x.replace(' ', '_') + '#' # Find substitutions subs = {} for sent in self.text().splitlines(): for s, l in find_short_long_pairs(sent.strip()): if s not in subs or len(l) < len(subs[s...
Python
nomic_cornstack_python_v1
string Mix CharlieWing class and MicroPython FrameBuffer from is31fl3731 import CharlieWing import framebuf class FramedCharlie extends CharlieWing begin string Class that embed CharliePlexing with FrameBuffer - 1 bit depth color function __init__ self i2c begin call __init__ i2c set _intensity = 255 comment Créer un F...
""" Mix CharlieWing class and MicroPython FrameBuffer """ from is31fl3731 import CharlieWing import framebuf class FramedCharlie( CharlieWing ): """ Class that embed CharliePlexing with FrameBuffer - 1 bit depth color""" def __init__( self, i2c ): super().__init__( i2c ) self._intensity = 255 # Créer un FrameB...
Python
zaydzuhri_stack_edu_python
function ubbi_dubbi w begin set ubb = list for c in w begin if c in string aeiou begin append ubb string ub end append ubb c end return join string ubb end function print call ubbi_dubbi string elephant print call ubbi_dubbi string soap print call ubbi_dubbi string octopus
def ubbi_dubbi(w): ubb = [] for c in w: if c in 'aeiou': ubb.append('ub') ubb.append(c) return "".join(ubb) print(ubbi_dubbi("elephant")) print(ubbi_dubbi("soap")) print(ubbi_dubbi("octopus"))
Python
zaydzuhri_stack_edu_python
function client_initializer begin try begin set server_addr = argv at 1 set server_port = integer argv at 2 if server_port < 1024 or server_port > 65535 begin raise ValueError end end except IndexError begin set server_addr = DEFAULT_IP_ADDRESS set server_port = DEFAULT_PORT end except ValueError begin print string Onl...
def client_initializer(): try: server_addr = sys.argv[1] server_port = int(sys.argv[2]) if server_port < 1024 or server_port > 65535: raise ValueError except IndexError: server_addr = DEFAULT_IP_ADDRESS server_port = DEFAULT_PORT except ValueError: ...
Python
nomic_cornstack_python_v1
import nlp_tools import threading class AnalysisHandler extends object begin string Main class for the analysis ... function __init__ self settings folder_name begin set settings = settings set input_text = none set folder_name = folder_name comment locks http://effbot.org/zone/thread-synchronization.htm set lock = loc...
import nlp_tools import threading class AnalysisHandler(object): """ Main class for the analysis ... """ def __init__(self, settings, folder_name): self.settings = settings self.input_text = None self.folder_name = folder_name # locks http://effbot.org/zone/thread-sync...
Python
zaydzuhri_stack_edu_python
from app.db import db from passlib.hash import pbkdf2_sha512 class Role extends Model begin set __tablename__ = string roles set id = call Column Integer primary_key=true set name = call Column call String 80 set users = call relationship string User lazy=string dynamic function __init__ self _id name begin set id = _i...
from app.db import db from passlib.hash import pbkdf2_sha512 class Role(db.Model): __tablename__ = 'roles' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) users = db.relationship('User', lazy='dynamic') def __init__(self, _id, name): self.id = _id sel...
Python
zaydzuhri_stack_edu_python
import speech_recognition as sr from os import path function printWAV file_name pos clip begin set AUDIO_FILE = join path directory name path real path path __file__ string static/ + file_name set text = string set r = call Recognizer with call AudioFile AUDIO_FILE as source begin set audio = call record source durati...
import speech_recognition as sr from os import path def printWAV(file_name, pos, clip): AUDIO_FILE = path.join(path.dirname(path.realpath(__file__)), "static/"+file_name) text = '' r = sr.Recognizer() with sr.AudioFile(AUDIO_FILE) as source: audio = r.record(source, duration=clip, offset=pos) ...
Python
zaydzuhri_stack_edu_python
function time_stats df month day begin print string Calculating The Most Frequent Times of Travel... set start_time = time comment display the most common month if month == string All begin set most_common_month = drop missing df at string Start Month if empty begin print string No common month found, Please refilter y...
def time_stats(df, month, day): print('\nCalculating The Most Frequent Times of Travel...\n') start_time = time.time() # display the most common month if month == 'All': most_common_month = df['Start Month'].dropna() if most_common_month.empty: print('No common month found,...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment Question 1 import random function magic8ball begin input string Please ask a question: set list = list string Yes string No string Maybe string Try Again string Never ask me again string Yes and No string I don't know string Absolutely string Sure? string Try asking tomorrow print ...
#!/usr/bin/env python3 # Question 1 import random def magic8ball (): input("Please ask a question: ") list = ["Yes", "No", "Maybe", "Try Again", "Never ask me again", "Yes and No", "I don't know", "Absolutely", "Sure?", "Try asking tomorrow"] print(random.choice(list)) magic8ball() #Question 2 codes = { "...
Python
zaydzuhri_stack_edu_python
function tell self begin return position end function
def tell(self): return self.position
Python
nomic_cornstack_python_v1
set A = integer input set B = integer input set X = integer A + B
A = int(input()) B = int(input()) X = int(A + B)
Python
zaydzuhri_stack_edu_python
function import_gtf path key=none begin set ht = call import_table path comment=string # no_header=true types=dict string f3 tint ; string f4 tint ; string f5 tfloat ; string f7 tint missing=string . delimiter=string set ht = rename dict string f0 string seqname ; string f1 string source ; string f2 string feature ; st...
def import_gtf(path, key=None): ht = hl.import_table(path, comment='#', no_header=True, types={'f3': hl.tint, 'f4': hl.tint, 'f5': hl.tfloat, 'f...
Python
nomic_cornstack_python_v1
function read_busiest_week path begin string Find the earliest week with the most trips set feed = call load_raw_feed path return call _busiest_week feed end function
def read_busiest_week(path: str) -> Dict[datetime.date, FrozenSet[str]]: """Find the earliest week with the most trips""" feed = load_raw_feed(path) return _busiest_week(feed)
Python
jtatman_500k
import shelve from random import randint from dclass import player function show_menu begin print print string MENU print string ---- print string 1) New Game print string 2) Load Game print string 3) Save Game print string 4) Roll print string 5) Show Stats print string 6) Exit end function function get_choice begin s...
import shelve from random import randint from dclass import player def show_menu(): print() print('MENU') print('----') print('1) New Game') print('2) Load Game') print('3) Save Game') print('4) Roll') print('5) Show Stats') print('6) Exit') def get_choice(): valid_choices = (...
Python
zaydzuhri_stack_edu_python
comment {{{1 function normalize_name string begin set lower = lower string set ascii = sub NON_WORD_PATTERN string lower if ascii == string begin set ascii = lower end return strip sub string \s+ string ascii end function
def normalize_name(string): # {{{1 lower = string.lower() ascii = re.sub(NON_WORD_PATTERN, ' ', lower) if ascii == '': ascii = lower return re.sub('\s+', ' ', ascii).strip()
Python
nomic_cornstack_python_v1
import numpy as np import torch from gulpio import GulpDirectory class EpicDataset extends Dataset begin string Epic-kitchen video dataset loader. Construct the Epic-kitchen video dataset loader. For training and validation, video clip is randomly sampled from every video with random cropping, scaling, and flipping. fu...
import numpy as np import torch from gulpio import GulpDirectory class EpicDataset(torch.utils.data.Dataset): """ Epic-kitchen video dataset loader. Construct the Epic-kitchen video dataset loader. For training and validation, video clip is randomly sampled from every video with random cropping, scal...
Python
zaydzuhri_stack_edu_python
function cosine_similarity vector1 vector2 begin string Calculate the cosine similarity between two vectors Inputs: vector1 - list of numbers vector2 - list of numbers Output: cosine_similarity - float value end function import math comment Error handling if length vector1 != length vector2 begin return string Error: v...
def cosine_similarity(vector1, vector2): ''' Calculate the cosine similarity between two vectors Inputs: vector1 - list of numbers vector2 - list of numbers Output: cosine_similarity - float value ''' import math #Error handling if len(vector1) != len(vector2): return "Error: vector lengths must be equal" #...
Python
jtatman_500k
import math function is_prime n begin if n <= 1 begin return false end for i in range 2 integer square root n + 1 begin if n % i == 0 begin return false end end return true end function function filter_primes arr begin set primes = list set non_primes_sum = 0 for num in arr begin if call is_prime num begin append prim...
import math def is_prime(n): if n <= 1: return False for i in range(2, int(math.sqrt(n)) + 1): if n % i == 0: return False return True def filter_primes(arr): primes = [] non_primes_sum = 0 for num in arr: if is_prime(num): primes.append(num...
Python
greatdarklord_python_dataset
import sys comment Don’t use global keyword unless you know what you are doing. comment Global & Return function add_a value1 value2 begin set result_a = value1 + value2 end function function add_b value1 value2 begin global result_b set result_b = value1 + value2 end function comment Multiple return values comment Not...
import sys #Don’t use global keyword unless you know what you are doing. # Global & Return def add_a(value1, value2): result_a = value1 + value2 def add_b(value1, value2): global result_b result_b = value1 + value2 # Multiple return values # Not good def profile(): global name global age na...
Python
zaydzuhri_stack_edu_python
function test_rshift_array_num_array_b1 self begin for testvalue in testarray2 begin with call subTest msg=string Failed with parameter testvalue=testvalue begin comment Copy the array so we don't change the original data. set testarray1 = copy copy testarray1 set badarray1 = copy copy badarray1 comment This version is...
def test_rshift_array_num_array_b1(self): for testvalue in self.testarray2: with self.subTest(msg='Failed with parameter', testvalue = testvalue): # Copy the array so we don't change the original data. testarray1 = copy.copy(self.testarray1) badarray1 = copy.copy(self.badarray1) # This version is...
Python
nomic_cornstack_python_v1
function test_ascii7Printable begin set testString = call generator 32 set testAscii = call AsciiBytes set testAscii2 = call AsciiBytes call fromAscii8 testString call fromAscii7 call toAscii7 assert call toAscii8 == testString end function
def test_ascii7Printable(): testString = generator(32) testAscii = AsciiBytes() testAscii2 = AsciiBytes() testAscii.fromAscii8(testString) testAscii2.fromAscii7(testAscii.toAscii7()) assert testAscii2.toAscii8() == testString
Python
nomic_cornstack_python_v1
comment Time: O(n) comment Space: O(1) comment Given an array of integers, every element appears twice except for one. comment Find that single one. comment Note: comment Your algorithm should have a linear runtime complexity. Could you implement it comment without using extra memory? import argparse class Solution beg...
# Time: O(n) # Space: O(1) # # Given an array of integers, every element appears twice except for one. # Find that single one. # # Note: # Your algorithm should have a linear runtime complexity. Could you implement it # without using extra memory? # import argparse class Solution: @staticmethod def single_n...
Python
zaydzuhri_stack_edu_python
function getlist self key begin try begin set vals = call _dict_getitem self lower key end except KeyError begin return list end try else begin if is instance vals tuple begin return list vals at 1 end else begin return vals at slice 1 : : end end end function
def getlist(self, key): try: vals = _dict_getitem(self, key.lower()) except KeyError: return [] else: if isinstance(vals, tuple): return [vals[1]] else: return vals[1:]
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- from FileIO import Load from dtw import dtw import os from GlobalParameter import * import cPickle as pickle import numpy as np from Matrix import symmetric from numpy.linalg import norm class Self begin function __init__ self begin pass end function end class
# -*- coding: utf-8 -*- from FileIO import Load from dtw import dtw import os from GlobalParameter import * import cPickle as pickle import numpy as np from Matrix import symmetric from numpy.linalg import norm class Self: def __init__(self): pass
Python
zaydzuhri_stack_edu_python