code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function rename_object_field self object_name field_name new_name begin set save_button = format npsp_lex_locators at string object_manager at string button string Save call open_fields_and_relationships object_name set search_button = format npsp_lex_locators at string object_manager at string input string globalQuick...
def rename_object_field(self,object_name,field_name,new_name): save_button=npsp_lex_locators['object_manager']['button'].format("Save") self.open_fields_and_relationships(object_name) search_button = npsp_lex_locators['object_manager']['input'].format("globalQuickfind") self.selenium.wait_until_page_contains_el...
Python
nomic_cornstack_python_v1
comment n, m, l = map(int, input().split()) comment list_n = list(map(int, input().split())) comment n = input() comment list = [input() for i in range(N) comment list = [[i for i in range(N)] for _ in range(M)] import sys set input = readline set N = integer input set tuple D X = map int split input set list_A = list ...
# n, m, l = map(int, input().split()) # list_n = list(map(int, input().split())) # n = input() # list = [input() for i in range(N) # list = [[i for i in range(N)] for _ in range(M)] import sys input = sys.stdin.readline N = int(input()) D, X = map(int, input().split()) list_A = [int(input()) for i in range(N)] lis...
Python
zaydzuhri_stack_edu_python
function get_team_id team_name begin string Returns the team ID associated with the team name that is passed in. Parameters ---------- team_name : str The team name whose ID we want. NOTE: Only pass in the team name (e.g. "Lakers"), not the city, or city and team name, or the team abbreviation. Returns ------- team_id ...
def get_team_id(team_name): """ Returns the team ID associated with the team name that is passed in. Parameters ---------- team_name : str The team name whose ID we want. NOTE: Only pass in the team name (e.g. "Lakers"), not the city, or city and team name, or the team abbrevia...
Python
jtatman_500k
comment !/usr/bin/python3 string Query to db with states and state id from flask import Flask , render_template from models import storage set app = call Flask __name__ decorator call route string /states strict_slashes=false function states begin string list the states set val = string State set dic = dict set States...
#!/usr/bin/python3 """ Query to db with states and state id """ from flask import Flask, render_template from models import storage app = Flask(__name__) @app.route('/states', strict_slashes=False) def states(): """list the states """ val = 'State' dic = {} States = storage.all('State').items() fo...
Python
zaydzuhri_stack_edu_python
function format_state self state begin return reshape np state at slice 0 : state_size : list 1 state_size end function
def format_state(self, state): return np.reshape(state[0:self.state_size], [1, self.state_size])
Python
nomic_cornstack_python_v1
import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import numpy as np set sdf = read csv string all_string_results.csv set pdf = read csv string all_pkl_results.csv set sdf at string network = string String set pdf at string network = string PheKnowLater set df = concat list sdf pdf comment subse...
import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import numpy as np sdf = pd.read_csv('all_string_results.csv') pdf = pd.read_csv('all_pkl_results.csv') sdf['network'] = 'String' pdf['network'] = 'PheKnowLater' df = pd.concat([sdf,pdf]) # subset the columns percent_df = df[['500 %','100 %'...
Python
zaydzuhri_stack_edu_python
function setup_platform hass config add_devices_callback discovery_info=none begin call add_devices_callback list call LRFLight string Guest Bedroom Light false string R1D1 call LRFLight string Office Ceiling Light false string R2D1 call LRFLight string Office Wall Light false string R2D2 call LRFLight string Living Ro...
def setup_platform(hass, config, add_devices_callback, discovery_info=None): add_devices_callback([ LRFLight("Guest Bedroom Light", False, 'R1D1'), LRFLight("Office Ceiling Light", False, 'R2D1'), LRFLight("Office Wall Light", False, 'R2D2'), LRFLight("Living Room Wall Light", False,...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 comment -*- coding: utf-8 -*- import unittest import random import CorrQ as corr import q class TestExtractor extends TestCase begin function test_exist self begin assert true has attribute q string premier call _ string You did not name the method as expected. end function function test_cases...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import unittest import random import CorrQ as corr import q class TestExtractor(unittest.TestCase): def test_exist(self): self.assertTrue(hasattr(q, 'premier'), _("You did not name the method as expected.")) def test_cases(self): corr_ans = corr.pr...
Python
zaydzuhri_stack_edu_python
function IsDeleted self *args begin return call BRepAlgo_BooleanOperations_IsDeleted self *args end function
def IsDeleted(self, *args): return _BRepAlgo.BRepAlgo_BooleanOperations_IsDeleted(self, *args)
Python
nomic_cornstack_python_v1
function genStartScript self path begin call mkdir_p path set startfile = open join path path string start.py string w set queue = string set comma = false for tuple _ instpath instname in startfiles begin set relpath = call relpath instpath path if comma begin set queue = queue + string , end else begin set comma = t...
def genStartScript(self, path): tools.mkdir_p(path) startfile = open(os.path.join(path, "start.py"), 'w') queue = "" comma = False for (_, instpath, instname) in self.startfiles: relpath = os.path.relpath(instpath, path) if comma: queue += ...
Python
nomic_cornstack_python_v1
from flask import Flask set app = call Flask __name__ decorator call route string / comment Revisit decorators if you unclear of this syntax function index begin return string <h1>Why so easy easy</h1> end function comment Revisit previous challenge if you're uncertain what this does https://code.nextacademy.com/lesson...
from flask import Flask app = Flask(__name__) @app.route("/") # Revisit decorators if you unclear of this syntax def index(): return '<h1>Why so easy easy</h1>' if __name__ == '__main__': # Revisit previous challenge if you're uncertain what this does https://code.nextacademy.com/lessons/name-main/424 app.run(...
Python
zaydzuhri_stack_edu_python
function get_val_from_dict indict col begin set val = indict for col_i in col begin if col_i != string begin if string # in col_i begin set tuple col_name col_id = split col_i string # set col_id = integer col_id if col_name in keys val and col_id < length val at col_name begin set val = val at col_name at integer col...
def get_val_from_dict(indict, col): val = indict for col_i in col: if col_i != ' ': if '#' in col_i: col_name, col_id = col_i.split('#') col_id = int(col_id) if (col_name in val.keys()) and (col_id < len(val[col_name])): v...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import os import time string Boiler plate code for python coding standard. created by - Ajay Singh Parmar dated - September 06, 2019 comment -----------------------------------------------------------# comment Application Constants # comment -------------------------------------------------...
#!/usr/bin/env python import os import time """ Boiler plate code for python coding standard. created by - Ajay Singh Parmar dated - September 06, 2019 """ #-----------------------------------------------------------# # Application Constants # #-------------------...
Python
zaydzuhri_stack_edu_python
import pandas as pd function read_data begin set data = read csv string /home/nixizi/Repository/Analyzing-tiger-mosquito-disease-spread/Data/flu.csv return list comprehension d / 100 for d in list data at string Positive end function if __name__ == string __main__ begin print call read_data end
import pandas as pd def read_data(): data = pd.read_csv("/home/nixizi/Repository/Analyzing-tiger-mosquito-disease-spread/Data/flu.csv") return [d / 100 for d in list(data["Positive"])] if __name__ == "__main__": print(read_data())
Python
zaydzuhri_stack_edu_python
import argparse from sys import exit from brute import Brute function define_arguemnts begin set parser = call ArgumentParser call add_argument string target help=string Target IP address or hostname call add_argument string -u string --userfile help=string Path to user file required=true call add_argument string -p st...
import argparse from sys import exit from brute import Brute def define_arguemnts(): parser = argparse.ArgumentParser() parser.add_argument("target", help="Target IP address or hostname") parser.add_argument("-u", "--userfile", help="Path to user file", required=True) parser.add_argument("-p", "--pass...
Python
zaydzuhri_stack_edu_python
function get_field_schema_validations field begin string Get the JSON Schema validation keywords for a ``field`` with an annotation of a Pydantic ``Schema`` with validation arguments. set f_schema : Dict at tuple str Any = dict if call lenient_issubclass type_ tuple str bytes begin for tuple attr_name t keyword in _st...
def get_field_schema_validations(field: Field) -> Dict[str, Any]: """ Get the JSON Schema validation keywords for a ``field`` with an annotation of a Pydantic ``Schema`` with validation arguments. """ f_schema: Dict[str, Any] = {} if lenient_issubclass(field.type_, (str, bytes)): for att...
Python
jtatman_500k
function get_waveforms self network station location channel starttime endtime quality=none minimumlength=none longestonly=none filename=none attach_response=false **kwargs begin if string dataselect not in services begin set msg = string The current client does not have a dataselect service. raise call ValueError msg ...
def get_waveforms(self, network, station, location, channel, starttime, endtime, quality=None, minimumlength=None, longestonly=None, filename=None, attach_response=False, **kwargs): if "dataselect" not in self.services: msg = "The cur...
Python
nomic_cornstack_python_v1
function users self begin string :class:`~zhmcclient.UserManager`: Access to the :term:`Users <User>` in this Console. comment We do here some lazy loading. if not _users begin set _users = call UserManager self end return _users end function
def users(self): """ :class:`~zhmcclient.UserManager`: Access to the :term:`Users <User>` in this Console. """ # We do here some lazy loading. if not self._users: self._users = UserManager(self) return self._users
Python
jtatman_500k
comment HW 13-2 comment Alec Barker import matplotlib.pyplot as plt import scipy.stats as stats import glob function get_temps file_path begin set file = open file_path set all_temps = list set year_temps = dict set current_year = 1995 set current_year_temps = list for line in file begin set line_data = split line s...
# HW 13-2 # Alec Barker import matplotlib.pyplot as plt import scipy.stats as stats import glob def get_temps(file_path): file = open(file_path) all_temps = [] year_temps = {} current_year = 1995 current_year_temps = [] for line in file: line_data = line.split(" ") ...
Python
zaydzuhri_stack_edu_python
function get_kwargs d begin raise call NotImplementedError string subclass must implement get_kwargs() end function
def get_kwargs(d): raise NotImplementedError("subclass must implement get_kwargs()")
Python
nomic_cornstack_python_v1
function test_unet_verify_output_shape simple_unet_data begin set unet = call UNet set output = call unet simple_unet_data print string Input shape: shape print string Output shape: shape assert shape == shape end function
def test_unet_verify_output_shape(simple_unet_data): unet = models.UNet() output = unet(simple_unet_data) print("Input shape:", simple_unet_data.shape) print("Output shape:", output.shape) assert simple_unet_data.shape == output.shape
Python
nomic_cornstack_python_v1
function get_cardinality self variables begin string Returns cardinality of a given variable Parameters ---------- variables: list, array-like A list of variable names. Returns ------- dict: Dictionary of the form {variable: variable_cardinality} Examples -------- >>> from pgmpy.factors.discrete import DiscreteFactor >...
def get_cardinality(self, variables): """ Returns cardinality of a given variable Parameters ---------- variables: list, array-like A list of variable names. Returns ------- dict: Dictionary of the form {variable: variable_cardinality} ...
Python
jtatman_500k
comment feedforward.py comment author: Playinf comment email: playinf@stu.xmu.edu.cn import theano from linear import linear from utils import get_or_default from config import config , option from initializer import uniform_initializer , zeros_initializer class feedforward_config extends config begin string * dtype: s...
# feedforward.py # author: Playinf # email: playinf@stu.xmu.edu.cn import theano from linear import linear from utils import get_or_default from config import config, option from initializer import uniform_initializer, zeros_initializer class feedforward_config(config): """ * dtype: str, default theano.conf...
Python
zaydzuhri_stack_edu_python
comment Creating 3D visualizations with Mayavi. from mayavi import mlab comment Initialize Mayavi visualization. comment Create 3D plots and surfaces.
# Creating 3D visualizations with Mayavi. from mayavi import mlab # Initialize Mayavi visualization. # Create 3D plots and surfaces.
Python
flytech_python_25k
function status self begin return status_dict at upper call _get_property_ STATUS end function
def status(self): return status_dict[self._get_property_(self.STATUS).upper()]
Python
nomic_cornstack_python_v1
string json_data='{"Family":{"Brother1":{"name":"uday","sal":25000,"address":"vizag"},"Brother3":{"name":"chanti","sal":18000,"address":"rajahmundry"}}}' import json set json_dict = loads json_data print json_dict print type json_dict print type json_data
'''json_data='{"Family":{"Brother1":{"name":"uday","sal":25000,"address":"vizag"},"Brother3":{"name":"chanti","sal":18000,"address":"rajahmundry"}}}' ''' import json json_dict=json.loads(json_data) print(json_dict) print(type(json_dict)) print(type(json_data))
Python
zaydzuhri_stack_edu_python
function GetVersions begin return call getVersions end function
def GetVersions(): return salome_version.getVersions()
Python
nomic_cornstack_python_v1
function __del__ self begin call kill end function
def __del__(self): self._proc.kill()
Python
nomic_cornstack_python_v1
function _get self n begin comment Convert ranges to a list if type n is range begin set n = list n end comment Check if a list passed (must be) if type n is not list begin raise call NotImplementedError string n must be a list end comment Convert list to numpy array set n = array n comment Range check if any n > lengt...
def _get(self, n: Union[range, list]) -> pd.DataFrame: # Convert ranges to a list if type(n) is range: n = list(n) # Check if a list passed (must be) if type(n) is not list: raise NotImplementedError('n must be a list') # Convert list to numpy array ...
Python
nomic_cornstack_python_v1
function corrupt_value self in_str begin comment Empty string, no modification possible if length in_str == 0 begin return in_str end comment Get the possible phonetic modifications for this input string set phonetic_changes = call __get_transformation__ in_str set mod_str = in_str comment Several modifications possibl...
def corrupt_value(self, in_str): if (len(in_str) == 0): # Empty string, no modification possible return in_str # Get the possible phonetic modifications for this input string # phonetic_changes = self.__get_transformation__(in_str) mod_str = in_str if (',...
Python
nomic_cornstack_python_v1
from numpy import * from numpy.linalg import * set a = array eval input string digite: set b = zeros call shape a at 0 dtype=int set c = 1
from numpy import* from numpy.linalg import* a = array(eval(input('digite: '))) b= zeros(shape(a)[0], dtype=int) c=1
Python
zaydzuhri_stack_edu_python
function setEdgeGeometry self coordinates radii start end begin call setEdgeProperty string geometry_start start call setEdgeProperty string geometry_end end call setGraphProperty string edge_geometry_x coordinates at tuple slice : : 0 call setGraphProperty string edge_geometry_y coordinates at tuple slice : : 1 ...
def setEdgeGeometry(self, coordinates, radii, start, end): self.setEdgeProperty('geometry_start', start); self.setEdgeProperty('geometry_end', end); self.setGraphProperty('edge_geometry_x', coordinates[:,0]); self.setGraphProperty('edge_geometry_y', coordinates[:,1]); self.setGraphProperty...
Python
nomic_cornstack_python_v1
comment from pdb import set_trace comment set_trace() comment quetion 4 and 1 function parser text tax begin set split_data = split text string , set quantity = integer split split_data at 1 string : at 1 set price = decimal split strip split_data at 2 string : at 1 set item = split strip string split_data at 0 string ...
# from pdb import set_trace # set_trace() #quetion 4 and 1 def parser(text,tax): split_data = text.split(",") quantity = int(split_data[1].split(":")[1]) price = float(split_data[2].strip().split(":")[1]) item = str(split_data[0]).strip().split(":")[1] #print "The item is " + item subtotal = pr...
Python
zaydzuhri_stack_edu_python
function rank self begin return _history_dict at string rank end function
def rank(self): return self._history_dict['rank']
Python
nomic_cornstack_python_v1
function h_pot psi begin return call conjugate psi * psi - 1 end function
def h_pot(psi): return np.conjugate(psi)*psi-1
Python
nomic_cornstack_python_v1
comment Desenvolvido por Daniel Schinaider de Oliveira comment 01 set num1 = - 1 while num1 < 0 or num1 > 10 begin set num1 = decimal input string Informe uma nota entre 0 e 10: if num1 > 10 or num1 < 0 begin print string Nota com valor inválido! end else begin print string Nota com valor de num1 string é válida! end e...
# Desenvolvido por Daniel Schinaider de Oliveira #01 num1 = -1 while num1 < 0 or num1 > 10: num1 = float(input("Informe uma nota entre 0 e 10: ")) if num1 > 10 or num1 < 0: print("Nota com valor inválido!") else: print("Nota com valor de " , num1 , " é válida!")
Python
zaydzuhri_stack_edu_python
import random set number = random integer 1 9 set chances = 0 print string number between 1-9 while chances < 5 begin set guess = integer input string enter your guess if guess == number begin print string you won break end else begin print string you lost a chance try again guess end set chances = chances + 1 end
import random number=random.randint(1,9) chances=0 print("number between 1-9") while(chances<5): guess=int(input("enter your guess")) if guess==number: print("you won") break else: print("you lost a chance try again",guess) chances+=1
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 string Determine which log file(s) match the downlink received by VTGS and MGS import binascii import numpy import struct import os comment Downlink files set files = list directory string ../command set downlinks = list comprehension join path string ../command f for f in files if string ...
#!/usr/bin/env python3 """ Determine which log file(s) match the downlink received by VTGS and MGS """ import binascii import numpy import struct import os # Downlink files files = os.listdir("../command") downlinks = [os.path.join("../command", f) for f in files if "downlink" in f] # Load all the packets we did rec...
Python
zaydzuhri_stack_edu_python
function fuse_missing_perc name perc begin if perc == 0 begin return name end return string { name } ( { perc } ) end function
def fuse_missing_perc(name: str, perc: float) -> str: if perc == 0: return name return f"{name} ({perc:.1%})"
Python
nomic_cornstack_python_v1
function find_bad_values a begin set opened_brackets = string [{( set closed_brackets = string ]}) set brackets_needed_to_find = list set bad_brackets = list set i = 0 while i < length a begin comment если скобка открывающая, то мы хотим найти для закрывающую comment поэтому складываем скобки, которые хотим найти, в ...
def find_bad_values(a): opened_brackets = '[{(' closed_brackets = ']})' brackets_needed_to_find = [] bad_brackets = [] i = 0 while i < len(a): # если скобка открывающая, то мы хотим найти для закрывающую # поэтому складываем скобки, которые хотим найти, в список ...
Python
zaydzuhri_stack_edu_python
function eval_act self state action *_ **__ begin call pull_function actor string actor return call safe_call actor state action end function
def eval_act(self, state: Dict[str, Any], action: Dict[str, Any], *_, **__): self.pull_function(self.actor, "actor") return safe_call(self.actor, state, action)
Python
nomic_cornstack_python_v1
function StreamSelector host port begin return true end function
def StreamSelector(host, port): return True
Python
nomic_cornstack_python_v1
from sys import stdin set tuple n m = map int split input set pocketmons = dict for i in range n begin set s = right strip read line stdin set pocketmons at string i + 1 = s set pocketmons at s = i + 1 end for i in range m begin set q = right strip read line stdin print pocketmons at q end
from sys import stdin n, m = map(int, input().split()) pocketmons = {} for i in range(n): s = stdin.readline().rstrip() pocketmons[str(i+1)] = s pocketmons[s] = i+1 for i in range(m): q = stdin.readline().rstrip() print(pocketmons[q])
Python
zaydzuhri_stack_edu_python
comment генерация списков (делали циклом через append) set list_again = list comprehension i for i in list 1 2 3 4 print list_again set text = list comprehension title word for word in split string на улице жара print text comment создать новый словарь, который монжо итерировать comment если просто IF comment добавляем...
#генерация списков (делали циклом через append) list_again = [i for i in [1, 2, 3, 4]] print(list_again) text = [word.title() for word in 'на улице жара'.split()] print(text) #создать новый словарь, который монжо итерировать #если просто IF new = [i for i in range(1, 5) if i%2 == 0] #добавляем четные чис...
Python
zaydzuhri_stack_edu_python
function _request self local_ae remote_ae mp pcdl users_pdu=none begin set max_pdu_length = mp set max_pdu_length_par = call MaximumLengthSubItem mp set user_information = if expression users_pdu then list max_pdu_length_par + users_pdu else list max_pdu_length_par set username = get remote_ae string username set passw...
def _request(self, local_ae, remote_ae, mp, pcdl, users_pdu=None): self.max_pdu_length = mp max_pdu_length_par = userdataitems.MaximumLengthSubItem(mp) user_information = [max_pdu_length_par] + users_pdu \ if users_pdu else [max_pdu_length_par] username = remote_ae.get('user...
Python
nomic_cornstack_python_v1
function cuento2 update _ begin set query = callback_query call answer set keyboard = list list call InlineKeyboardButton string 🔙 Volver callback_data=string FOUR call InlineKeyboardButton string 👋 Salir callback_data=string FIVE set reply_markup = call InlineKeyboardMarkup keyboard call edit_message_text text=strin...
def cuento2(update: Update, _: CallbackContext) -> int: query = update.callback_query query.answer() keyboard = [ [ InlineKeyboardButton("\U0001F519 Volver", callback_data=str(FOUR)), InlineKeyboardButton("\U0001F44B Salir", callback_data=str(FIVE)), ] ] reply...
Python
nomic_cornstack_python_v1
from drive import * from entry import * from directory import * class Volume begin comment [line[i:i+n] for i in range(0, len(line), n)] <= string to array seperated by n characters comment ''.join(list) <= list to string with '' between elements set EMPTY_BITMAP = list string - * 128 function __init__ self name begin ...
from drive import * from entry import * from directory import * class Volume: # [line[i:i+n] for i in range(0, len(line), n)] <= string to array seperated by n characters # ''.join(list) <= list to string with '' between elements EMPTY_BITMAP = ['-'] * 128 def __init__(self, name): # Initialize block 0 with r...
Python
zaydzuhri_stack_edu_python
comment ============================================# comment CitadelNerdBot # comment Written by Red X 500/RedX1000/CrownMauler # comment # comment # comment # comment # comment ============================================# import discord import os import requests import json import urllib import sqlalchemy import sql...
#============================================# # CitadelNerdBot # # Written by Red X 500/RedX1000/CrownMauler # # # # # # # # ...
Python
zaydzuhri_stack_edu_python
function from_dict session d begin return call Port chambre=find Chambre session get d string roomNumber switch=find Switch session get d string switchID numero=get d string portNumber end function
def from_dict(session, d): return Port( chambre=Chambre.find(session, d.get("roomNumber")), switch=Switch.find(session, d.get("switchID")), numero=d.get("portNumber"), )
Python
nomic_cornstack_python_v1
string You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't...
""" You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't ha...
Python
zaydzuhri_stack_edu_python
function cylinder_volume self height begin return area * height end function
def cylinder_volume(self, height): return self.area * height
Python
nomic_cornstack_python_v1
function parseargs p begin call set_defaults func=func set description = string delay for a specified amount of time set epilog = string Pause for NUMBER seconds. SUFFIX may be 's' for + string seconds (the default), 'm' for minutes, 'h' for + string hours or 'd' for days. Unlike most implementations + string that requ...
def parseargs(p): p.set_defaults(func=func) p.description = "delay for a specified amount of time" p.epilog = ( "Pause for NUMBER seconds. SUFFIX may be 's' for " + "seconds (the default), 'm' for minutes, 'h' for " + "hours or 'd' for days. Unlike most implementations " + "t...
Python
nomic_cornstack_python_v1
comment Automating cloud resource management with Boto3. import boto3 comment Initialize Boto3 client. comment Create, update, and delete AWS resources programmatically.
# Automating cloud resource management with Boto3. import boto3 # Initialize Boto3 client. # Create, update, and delete AWS resources programmatically.
Python
flytech_python_25k
function on_enter_idle self begin call advertise state_change state call _cancel_deferred if length _del_pm_me and _delete_me_deferred is none begin set _delete_me_deferred = call callLater 0 delete_me end else if length _add_pm_me and _add_me_deferred is none begin set _add_me_deferred = call callLater 0 add_me end el...
def on_enter_idle(self): self.advertise(OpenOmciEventType.state_change, self.state) self._cancel_deferred() if len(self._del_pm_me) and self._delete_me_deferred is None: self._delete_me_deferred = reactor.callLater(0, self.delete_me) elif len(self._add_pm_me) and self._add_...
Python
nomic_cornstack_python_v1
function display_help head_txt=string help: begin set txt = string This calendar is interactive. Here some tips: - Use mouse or keyboard to interact with the calendar. - Hit bottom arrows to cycle through months. - Hit a day to create a linked event. (A day with attached event will appear yellow.) - Create multiple eve...
def display_help(head_txt="help:"): txt = f"""This calendar is interactive. Here some tips: - Use mouse or keyboard to interact with the calendar. - Hit bottom arrows to cycle through months. - Hit a day to create a linked event. (A day with attached event will appear yellow.) - Create multiple event type and...
Python
nomic_cornstack_python_v1
import tensorflow as tf import numpy as np from tensorflow import keras comment /////////////////////////////////////////////////////////////////////////////////////////////////// comment Regression model in small data comment /////////////////////////////////////////////////////////////////////////////////////////////...
import tensorflow as tf import numpy as np from tensorflow import keras # /////////////////////////////////////////////////////////////////////////////////////////////////// # Regression model in small data # /////////////////////////////////////////////////////////////////////////////////////////////////// #...
Python
zaydzuhri_stack_edu_python
function normalize_face_landmarks face_landmarks begin set face_landmarks_norm = zeros shape for tuple i lm in enumerate face_landmarks begin set face_landmarks_norm at i = lm - lm at nose_center_idx end set std_x = standard deviation np reshape face_landmarks_norm at tuple slice : : slice : : 0 tuple - 1 set std...
def normalize_face_landmarks(face_landmarks): face_landmarks_norm = np.zeros(face_landmarks.shape) for (i, lm) in enumerate(face_landmarks): face_landmarks_norm[i] = lm - lm[nose_center_idx] std_x = np.std(face_landmarks_norm[:,:,0].reshape((-1,))) std_y = np.std(face_landmarks_norm[:,:,1].reshape((-...
Python
nomic_cornstack_python_v1
import sys import psycopg2
import sys import psycopg2
Python
zaydzuhri_stack_edu_python
comment [DP-Sequence-Action, Classic] comment https://leetcode.com/problems/coin-path/ comment 656. Coin Path comment History: comment Google comment 1. comment Jun 23, 2020 comment Given an array A (index starts at 1) consisting of N integers: A1, A2, ..., AN and an integer comment B. The integer B denotes that from a...
# [DP-Sequence-Action, Classic] # https://leetcode.com/problems/coin-path/ # 656. Coin Path # History: # Google # 1. # Jun 23, 2020 # Given an array A (index starts at 1) consisting of N integers: A1, A2, ..., AN and an integer # B. The integer B denotes that from any place (suppose the index is i) in the array A, # ...
Python
zaydzuhri_stack_edu_python
comment whenevr we face a higher value we change or swap and move in that and if faced again we change again function merge_linked_list a b begin if a and b begin if val > val begin set tuple a b = tuple b a set next = call merge_linked_list next b end end return a or b end function
# whenevr we face a higher value we change or swap and move in that and if faced again we change again def merge_linked_list(a,b): if a and b: if a.val > b.val: a,b = b,a a.next = merge_linked_list(a.next,b) return a or b
Python
zaydzuhri_stack_edu_python
import heapq import math import unittest from typing import List from utils import stringToListNode , prettyPrintLinkedList , ListNode function get_min_node first_nodes begin set min_val = inf set index = - 1 for i in range length first_nodes begin if val < min_val begin set index = i set min_val = val end end return i...
import heapq import math import unittest from typing import List from utils import stringToListNode, prettyPrintLinkedList, ListNode def get_min_node(first_nodes): min_val = math.inf index = -1 for i in range(len(first_nodes)): if first_nodes[i].val < min_val: index = i m...
Python
zaydzuhri_stack_edu_python
string :Authors: - Wilker Aziz import unittest from legacy.sparse import SparseCategorical class SparseCategoricalTestCase extends TestCase begin function test_zero self begin set c1 = call SparseCategorical 100 assert equal 100 call support_size assert equal 0 call n_represented assert equal 0 sum end function functio...
""" :Authors: - Wilker Aziz """ import unittest from legacy.sparse import SparseCategorical class SparseCategoricalTestCase(unittest.TestCase): def test_zero(self): c1 = SparseCategorical(100) self.assertEqual(100, c1.support_size()) self.assertEqual(0, c1.n_represented()) self....
Python
zaydzuhri_stack_edu_python
function nr_cases self institute_id=none begin string Return the number of cases This function will change when we migrate to 3.7.1 Args: collaborator(str): Institute id Returns: nr_cases(int) set query = dict if institute_id begin set query at string collaborators = institute_id end debug format string Fetch all case...
def nr_cases(self, institute_id=None): """Return the number of cases This function will change when we migrate to 3.7.1 Args: collaborator(str): Institute id Returns: nr_cases(int) """ query = {} if institute_id: query['coll...
Python
jtatman_500k
function get_bounding_box current_building_contour begin set tuple x y w h = call boundingRect current_building_contour at 0 return tuple x y w h end function
def get_bounding_box(current_building_contour): x, y, w, h, = cv.boundingRect(current_building_contour[0]) return x, y, w, h
Python
nomic_cornstack_python_v1
from collections import Counter set card_value = dictionary generator expression tuple string i i for i in range 2 10 set card_value at string T = 10 set card_value at string J = 11 set card_value at string Q = 12 set card_value at string K = 13 set card_value at string A = 14 class Card begin function __init__ self ca...
from collections import Counter card_value = dict((str(i), i) for i in range(2, 10)) card_value['T'] = 10 card_value['J'] = 11 card_value['Q'] = 12 card_value['K'] = 13 card_value['A'] = 14 class Card: def __init__(self, card): self.value = card_value[card[0]] self.suit = card[1] self.car...
Python
zaydzuhri_stack_edu_python
if alien_color == string green begin print string You just earned 5 points end else begin print string You just earned 10 points end
if alien_color == 'green': print("You just earned 5 points") else: print("You just earned 10 points")
Python
zaydzuhri_stack_edu_python
function choose_action self state epsilon_greedy=false begin set chosen_action = none if epsilon_greedy begin if call rand <= epsilon begin print string random actions comment choose random action set chosen_action = random choice actions end else begin print string argmax comment find the action with greatest Q value ...
def choose_action(self, state, epsilon_greedy=False): chosen_action = None if epsilon_greedy: if np.random.rand() <= self.epsilon: print('random actions') # choose random action chosen_action = random.choice(self.actions) else: ...
Python
nomic_cornstack_python_v1
function get self key begin set idx = key % size if mp at idx begin for i in range length mp at idx begin if mp at idx at i at 0 == key begin return mp at idx at i at 1 end end return - 1 end else begin return - 1 end end function
def get(self, key: int) -> int: idx = key % self.size if self.mp[idx]: for i in range(len(self.mp[idx])): if self.mp[idx][i][0] == key: return self.mp[idx][i][1] return -1 else: return -1
Python
nomic_cornstack_python_v1
if num > 0 begin print string 大于0 end else if num == 0 begin print string {"msg":"账户被禁, 可联系在线客服 处理","code":1,"obj":null,"datas":null,"attributes":null,"ext1":"/user/home"} end else begin print string 负数 end
if num > 0: print("大于0") elif num == 0: print('{"msg":"账户被禁, 可联系在线客服 处理","code":1,"obj":null,"datas":null,"attributes":null,"ext1":"/user/home"}') else: print("负数")
Python
zaydzuhri_stack_edu_python
set email = strip input string Enter Your Email: set username = email at slice : index email string @ : set domain = email at slice index email string @ + 1 : : set slicing = string Your user name is ' { username } ' and your domain is ' { domain } ' print slicing
email = input("Enter Your Email: ").strip() username = email[:email.index("@")] domain = email[email.index("@")+1:] slicing = (f"Your user name is '{username}' and your domain is '{domain}'") print(slicing)
Python
zaydzuhri_stack_edu_python
import ssl import urllib.request function fetch_content url begin comment Create an SSL context to configure the TLS version and certificate validation set context = call create_default_context set minimum_version = TLSv1_3 comment Set the certificate verification mode to require a trusted CA set verify_mode = CERT_REQ...
import ssl import urllib.request def fetch_content(url): # Create an SSL context to configure the TLS version and certificate validation context = ssl.create_default_context() context.minimum_version = ssl.TLSVersion.TLSv1_3 # Set the certificate verification mode to require a trusted CA conte...
Python
jtatman_500k
import math import array function binomial S0 u d n begin set stkval = list for i in range n + 1 begin append stkval list if i == 0 begin append stkval at i S0 continue end for j in range 0 2 ^ i - 1 begin append stkval at i stkval at i - 1 at j * u append stkval at i stkval at i - 1 at j * d end end return stkval end...
import math import array def binomial(S0,u,d,n): stkval=[] for i in range(n+1): stkval.append([]) if i==0: stkval[i].append(S0) continue for j in range(0,2**(i-1)): stkval[i].append(stkval[i-1][j]*u) stkval[i].append(stkval[i-1][j]*d) return stkval K=2 u=2.0 d=0.5 S0=4.0 k=4 q=binomial(S0,u,d...
Python
zaydzuhri_stack_edu_python
function update_data self data begin set rebuild = false comment This method needs to substitute some defaultdicts for the normal comment dictionaries that come back from the server. comment Metacontact information comment if data['metacontacts'] set mc_dict = get data string metacontacts dict if not is instance mc_dic...
def update_data(self, data): rebuild = False # This method needs to substitute some defaultdicts for the normal # dictionaries that come back from the server. # Metacontact information #if data['metacontacts'] mc_dict = data.get('metacontacts', {}) if...
Python
nomic_cornstack_python_v1
function calculate_feature_vectorizer_output_shapes operator begin call check_input_and_output_numbers operator input_count_range=list 1 none output_count_range=1 call check_input_and_output_types operator good_input_types=list FloatTensorType Int64TensorType FloatType Int64Type if any generator expression length shape...
def calculate_feature_vectorizer_output_shapes(operator): check_input_and_output_numbers( operator, input_count_range=[1, None], output_count_range=1 ) check_input_and_output_types( operator, good_input_types=[FloatTensorType, Int64TensorType, FloatType, Int64Type], ) if any...
Python
nomic_cornstack_python_v1
function convert_to_plane_basis points basis origo begin comment pick cartesian part of basis set base_x = basis at 0 at slice : - 1 : set base_y = basis at 1 at slice : - 1 : comment normalize to unit lenght set unit_basis_vecs = tuple base_x / square root dot base_x base_x base_y / square root dot base_y base_y s...
def convert_to_plane_basis(points, basis, origo): # pick cartesian part of basis base_x = (basis[0])[:-1] base_y = (basis[1])[:-1] # normalize to unit lenght unit_basis_vecs = ( base_x/math.sqrt(np.dot(base_x, base_x)), base_y/math.sqrt(np.dot(base_y, base_y)) ) plane_coords ...
Python
nomic_cornstack_python_v1
function parse_all sources parser=none begin set use_parser = if expression parser then parser else _parse_auto set source_list = if expression is instance sources list then sources else list sources for source in source_list begin yield call use_parser source end end function
def parse_all(sources: typing.List[str], parser: typing.Callable[[str], typing.Dict] = None) -> typing.Iterator: use_parser = parser if parser else _parse_auto source_list = sources if isinstance(sources, list) else [sources] for source in source_list: yield use_parser(source)
Python
nomic_cornstack_python_v1
comment iterator set a = list 2 3 4 set p = iterate a comment 2 next p comment 3 next p comment 4 next p try begin comment raises a StopIteration exception next p end except StopIteration begin pass end comment ------------------------------------------------------- set a = list 2 3 4 set p = iterate a comment list ite...
# iterator a = [2, 3, 4] p = iter(a) next(p) # 2 next(p) # 3 next(p) # 4 try: next(p) # raises a StopIteration exception except StopIteration: pass # ------------------------------------------------------- a = [2, 3, 4] p = iter(a) type(p) ...
Python
zaydzuhri_stack_edu_python
function organize_students students begin set student_list = split students string ; set student_info = list for student in student_list begin set student_data = split student string , set student_dict = dict string name student_data at 0 ; string age integer student_data at 1 ; string grade integer student_data at 2 ...
def organize_students(students): student_list = students.split(";") student_info = [] for student in student_list: student_data = student.split(",") student_dict = { "name": student_data[0], "age": int(student_data[1]), "grade": int(student_data[2]), ...
Python
jtatman_500k
function relevant_eval_metrics self draw_smooth gt_smooth g_smooth_thred=1000 begin comment Now let's compute the relevant locations set draw_set = call tolist print draw_set set gt_set = call tolist print gt_set set shared_labels = intersection set draw_set set gt_set print shared_labels comment Find the centers of ea...
def relevant_eval_metrics(self, draw_smooth, gt_smooth, g_smooth_thred=1000): #Now let's compute the relevant locations draw_set = np.unique(draw_smooth).tolist() print(draw_set) gt_set = np.unique(gt_smooth).tolist() print(gt_set) shared_labels = set(draw_set).interse...
Python
nomic_cornstack_python_v1
function _mst_decode self head_tag_representation child_tag_representation attended_arcs mask begin set tuple normalized_arc_logits normalized_pairwise_head_logits lengths = call _attend_and_normalize head_tag_representation child_tag_representation attended_arcs mask comment Shape (batch_size, num_head_tags, sequence_...
def _mst_decode( self, head_tag_representation: torch.Tensor, child_tag_representation: torch.Tensor, attended_arcs: torch.Tensor, mask: torch.Tensor, ) -> Tuple[torch.Tensor, torch.Tensor]: normalized_arc_logits, normalized_pairwise_head_logits, lengths = self._atte...
Python
nomic_cornstack_python_v1
function getSuccessorRight self delNode begin set successorParent = delNode set successor = delNode set current = right comment go to right child while current != none begin comment until no more comment left children, set successorParent = successor set successor = current set current = left end comment go to left chi...
def getSuccessorRight(self, delNode): successorParent = delNode successor = delNode current = delNode.right # go to right child while current != None: # until no more # left children, successorParent = successor successor = current curre...
Python
nomic_cornstack_python_v1
string Version : v1.4 History : 1.0 - 07/31/2015 - Initial Version 1.1 - 11/24/2015 - Moved to one version logic 1.2 - 11/30/2015 - Add get_url_health function 1.3 - 12/23/2015 - change get_url_health 1.4 - 01/05/2016 - Set timeout in requests.head import requests , socket function get_domain_details in_domain_name beg...
""" Version : v1.4 History : 1.0 - 07/31/2015 - Initial Version 1.1 - 11/24/2015 - Moved to one version logic 1.2 - 11/30/2015 - Add get_url_health function 1.3 - 12/23/2015 - change get_url_health 1.4 - 01/05/2016 - Set timeo...
Python
zaydzuhri_stack_edu_python
function is_retry self method status_code has_retry_after=false begin string Is this method/status code retryable? (Based on whitelists and control variables such as the number of total retries to allow, whether to respect the Retry-After header, whether this header is present, and whether the returned status code is o...
def is_retry(self, method, status_code, has_retry_after=False): """ Is this method/status code retryable? (Based on whitelists and control variables such as the number of total retries to allow, whether to respect the Retry-After header, whether this header is present, and whether the re...
Python
jtatman_500k
function run_general_policy policy env continuous_actions=true render=true scaler=none begin set training_info = call TrainingInfo set tuple episode_length episode_reward = tuple 0 0 set state = call reset for t in range max_episode_steps begin set state = if expression scaler is not none then call scale_state scaler s...
def run_general_policy( policy: torch.nn.Module, env: gym.Env, continuous_actions: bool = True, render: bool = True, scaler=None) -> Tuple[float, int]: training_info = TrainingInfo() episode_length, episode_reward = 0, 0 state = env.reset() for t in range(env.sp...
Python
nomic_cornstack_python_v1
import math import pickle from sklearn import neighbors import face_recognition import cv2 class FaceRecognizer begin function __init__ self model_path distance_threshold=0.4 begin with open model_path string rb as f begin set knn_clf = load pickle f end set distance_threshold = distance_threshold end function function...
import math import pickle from sklearn import neighbors import face_recognition import cv2 class FaceRecognizer: def __init__(self, model_path, distance_threshold=0.4): with open(model_path, 'rb') as f: self.knn_clf = pickle.load(f) self.distance_threshold = distance_threshold de...
Python
zaydzuhri_stack_edu_python
function printFibo n begin set first = 0 set second = 1 print first print second for i in range 2 n begin set next = first + second print next set first = second set second = next end end function comment Test call printFibo 5
def printFibo(n): first = 0 second = 1 print(first) print(second) for i in range(2, n): next = first + second print(next) first = second second = next #Test printFibo(5)
Python
iamtarun_python_18k_alpaca
function reverse_array arr begin set n = length arr end function for i in range n // 2 begin set tuple arr at i arr at n - i - 1 = tuple arr at n - i - 1 arr at i end return arr
def reverse_array(arr): n = len(arr) for i in range(n // 2): arr[i], arr[n - i - 1] = arr[n - i - 1], arr[i] return arr
Python
flytech_python_25k
function pushs self value begin call push value end function
def pushs(self, value): self.data_stack.push(value)
Python
nomic_cornstack_python_v1
function _create_algorithms self begin if scenario == string original_1 or scenario == string known_1 begin set algorithms = list call PALPOMDP Xtrain numClasses oracles at 0 list 0.0 Bc end else comment PALOriginalScenario1(self.Xtrain, self.numClasses, self.oracles[1], [0.0, self.Bc]), comment PALBaselineRandom(self....
def _create_algorithms(self): if self.scenario == 'original_1' or self.scenario == 'known_1': self.algorithms = [PALPOMDP(self.Xtrain, self.numClasses, self.oracles[0], [0.0, self.Bc]), #PALOriginalScenario1(self.Xtrain, self.numClasses, self.oracles[1], [0.0, self.Bc...
Python
nomic_cornstack_python_v1
function __iter__ self begin return iterate _vars end function
def __iter__(self): return iter(self._vars)
Python
nomic_cornstack_python_v1
function run_iso_forest_test args begin set tuple test_file outdir = args set start = time set n_estimators = n_estimators set max_samples = string auto set contamination = contamination comment default is 1.0 (use all features) set max_features = 1.0 set bootstrap = false set tuple outfile_path1 outfile_path2 = call g...
def run_iso_forest_test(args): test_file, outdir = args start = time.time() n_estimators = config.iso_forest.n_estimators max_samples = 'auto' contamination = config.iso_forest.contamination max_features = 1.0 # default is 1.0 (use all features) bootstrap = False outfile_path1, outfile_...
Python
nomic_cornstack_python_v1
function loadCSPAD2x2CalibParsDefault self begin set defpars = dict set defpars at string center = array list list 198.0 198.0 list 95.0 308.0 list 0.0 0.0 set defpars at string tilt = zeros 2 dtype=float32 set defpars at string beam_vector = zeros 3 dtype=float32 set defpars at string common_mode = array list 1 100 3...
def loadCSPAD2x2CalibParsDefault (self) : self.defpars = {} self.defpars['center'] = np.array( [[198., 198.], [ 95., 308.], [ 0., 0.]]) self.defpars['tilt'] = np.zeros((2), dtype=np.float32) ...
Python
nomic_cornstack_python_v1
string Script that plots framewise displacement(fd), RMS signal derivative (DVARS), and meanSignal per subject per run and indicates potential outliers (motion- induced artifacts) based on commonly used threshold of 0.2-0.5mm for FD and 0.3-0.5% for DVARS. 0.5 was used for DVARS and 0.5 was used for FD. import sys impo...
""" Script that plots framewise displacement(fd), RMS signal derivative (DVARS), and meanSignal per subject per run and indicates potential outliers (motion- induced artifacts) based on commonly used threshold of 0.2-0.5mm for FD and 0.3-0.5% for DVARS. 0.5 was used for DVARS and 0.5 was used for FD. """ import sys ...
Python
zaydzuhri_stack_edu_python
function is_row_echelon self begin return call _is_row_echelon false end function
def is_row_echelon(self): return self._is_row_echelon(False)
Python
nomic_cornstack_python_v1
function cubic_trajectory_planning q0 qf qd0 qdf m=100 begin set n = shape at 0 comment Polynomial Parameters set a0 = copy np q0 set a1 = copy np qd0 set a2 = 3 * qf - q0 - 2 * qd0 - qdf set a3 = - 2 * qf - q0 + qd0 + qdf set timesteps = linear space 0 1 num=m set q = zeros tuple n m set qd = zeros tuple n m set qdd =...
def cubic_trajectory_planning(q0, qf, qd0, qdf, m = 100): n = q0.shape[0] # Polynomial Parameters a0 = np.copy(q0) a1 = np.copy(qd0) a2 = 3 * (qf - q0) - 2 * qd0 - qdf a3 = -2 * (qf - q0) + qd0 + qdf timesteps = np.linspace(0, 1, num = m) q = np.zeros((n, m)) qd = np.zeros((n, m)...
Python
nomic_cornstack_python_v1
function get_min a b begin string return min number among a and b return if expression a < b then a else b end function function get_min_without_arguments begin string raise TypeError exception with message raise call TypeError string No arguments. end function function get_min_with_one_argument x begin string return t...
def get_min(a, b): """ return min number among a and b """ return a if a < b else b def get_min_without_arguments(): """ raise TypeError exception with message """ raise TypeError("No arguments.") def get_min_with_one_argument(x): """ return that value """ r...
Python
zaydzuhri_stack_edu_python
function add_item self item begin call check_param_not_none item string item if path in items begin set total_size = total_size - size end update items dict encode path string utf-8 item set total_size = total_size + size end function
def add_item(self, item): check_param_not_none(item, "item") if item.path in self.items: self.total_size -= self.items.get(item.path).size self.items.update({item.path.encode('utf-8') : item}) self.total_size += item.size
Python
nomic_cornstack_python_v1
function handle_starttag self tag attrs begin for apt in attrs begin if apt at 0 == string href begin if starts with apt at 1 STANDINGS begin set tindx = find apt at 1 string & + 1 set parts = apt at 1 at slice tindx : : if string _ in parts begin if find parts league >= 0 begin append result parts end end end end en...
def handle_starttag(self, tag, attrs): for apt in attrs: if apt[0] == 'href': if apt[1].startswith(STANDINGS): tindx = apt[1].find('&') + 1 parts = apt[1][tindx:] if '_' in parts: if parts.find(self.l...
Python
nomic_cornstack_python_v1
function uniq_stable elems begin set unique = list set unique_set = set for nn in elems begin if nn not in unique_set begin append unique nn add unique_set nn end end return unique end function
def uniq_stable(elems): unique = [] unique_set = set() for nn in elems: if nn not in unique_set: unique.append(nn) unique_set.add(nn) return unique
Python
nomic_cornstack_python_v1
function from_user self id **kwargs begin return call _get_msgs string messages/from_user/%d.json % id keyword kwargs end function
def from_user(self, id, **kwargs): return self._get_msgs('messages/from_user/%d.json' % id, **kwargs)
Python
nomic_cornstack_python_v1