code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function gradunwarp_version self begin set cmd = list string gradient_unwarp.py string -v set process = popen cmd env=environment stdout=PIPE stderr=PIPE set tuple stdout stderr = communicate process set exitcode = returncode if exitcode != 0 begin return none end return strip stderr string end function
def gradunwarp_version(self): cmd = ["gradient_unwarp.py", "-v"] process = subprocess.Popen( cmd, env=self.environment, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = process.communicate() exitcode = process.returncode ...
Python
nomic_cornstack_python_v1
function associate_candidates self begin info string Associating candidate events set dt_ot = time delta seconds=assoc_ot_uncert comment ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ comment Query all candidate ots comment ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ set candidate_ots = a...
def associate_candidates(self): log.info('Associating candidate events') dt_ot = timedelta(seconds=self.assoc_ot_uncert) # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # Query all candidate ots # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ candidate...
Python
nomic_cornstack_python_v1
function pytest_sessionfinish session exitstatus begin pass end function
def pytest_sessionfinish(session, exitstatus): pass
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np import torch from torch.nn import functional as F from torch.utils.data import DataLoader , Dataset from transformers import AutoTokenizer , ElectraForSequenceClassification , AdamW from tqdm.notebook import tqdm comment ================= comment 새로운 문장 테스트 comment ===============...
import pandas as pd import numpy as np import torch from torch.nn import functional as F from torch.utils.data import DataLoader, Dataset from transformers import AutoTokenizer, ElectraForSequenceClassification, AdamW from tqdm.notebook import tqdm # ================= # 새로운 문장 테스트 # ================= # GPU 사용 device ...
Python
zaydzuhri_stack_edu_python
function test_execute_dump_var_transaction self begin set instruction = call Instruction string dump(3) with call std_out as tuple out err begin execute transaction_manager instruction end set output = strip call getvalue assert equal output string {'x14': { x14: 140 }, 'x18': { x18: 180 }, 'x10': { x10: 100 }, 'x8': {...
def test_execute_dump_var_transaction(self): instruction = Instruction("dump(3)") with std_out() as (out, err): self.transaction_manager.execute(instruction) output = out.getvalue().strip() self.assertEqual(output, "{'x14': { x14: 140 }, 'x18': { x18: 180 }, 'x10': { x10: ...
Python
nomic_cornstack_python_v1
import pygame import traceback import sys import copy import math from collections import defaultdict class States extends object begin function __init__ self begin set fnt = call SysFont string comicsans 40 set fnt2 = call SysFont string comicsans 15 set done = false set next = none set quit = false set previous = non...
import pygame import traceback import sys import copy import math from collections import defaultdict class States(object): def __init__(self): self.fnt = pygame.font.SysFont("comicsans", 40) self.fnt2 = pygame.font.SysFont("comicsans", 15) self.done = False self.next = None ...
Python
zaydzuhri_stack_edu_python
from unittest import TestCase , main from unittest.mock import patch from BrowserAutomator.runner import get_actions , get_action_functions class RunnerTest extends TestCase begin decorator patch string BrowserAutomator.runner.read_actions side_effect=lambda filename -> list string action_0 decorator patch string Brows...
from unittest import TestCase, main from unittest.mock import patch from BrowserAutomator.runner import get_actions, get_action_functions class RunnerTest(TestCase): @patch("BrowserAutomator.runner.read_actions", side_effect=lambda filename: ["action_0"]) @patch("BrowserAutomator.runner.get_action_functions",...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 comment Python Assignment comment Program 2: Implement a python code to find the area of a triangle. function areat alt base begin return alt * base * 0.5 end function set alt = decimal input string Please enter the Altitude of the Triangle: set base = decimal input string Please enter the Bas...
# !/usr/bin/python3 # Python Assignment # Program 2: Implement a python code to find the area of a triangle. def areat(alt,base): return (alt*base*0.5) alt = float(input("Please enter the Altitude of the Triangle: ")) base = float(input("Please enter the Base of the Triangle: ")) print ("The area of triangle is:",...
Python
zaydzuhri_stack_edu_python
function boundaryOperator Q begin set sgn = 1 set c = dictionary set Ql = list Q for ind in range length Ql begin set n = pop Ql ind if length Ql == 0 begin set c at tuple Ql = 0 end else begin set c at tuple Ql = sgn end insert Ql ind n set sgn = - 1 * sgn end return c end function
def boundaryOperator(Q): sgn = 1 c = dict() Ql = list(Q) for ind in range(len(Ql)): n = Ql.pop(ind) if len(Ql) == 0: c[tuple(Ql)] = 0 else: c[tuple(Ql)] = sgn Ql.insert(ind, n) sgn = -1 * sgn return c
Python
nomic_cornstack_python_v1
function get_customer_accounts self accept customer_id status=none begin comment Validate required parameters call validate_parameters accept=accept customer_id=customer_id comment Prepare query URL set _url_path = string /aggregation/v1/customers/{customerId}/accounts set _url_path = call append_url_with_template_para...
def get_customer_accounts(self, accept, customer_id, status=None): # Validate required parameters self.validate_parameters(accept=accept, customer_id=customer_id) ...
Python
nomic_cornstack_python_v1
function receive_telegram_callback self event_id payload_event *args begin assert event_id == string telegram_callback set params = split replace payload_event at string data string / string string ; if length params > 0 begin if length params > 2 and params at 0 == string slideshow begin call handle_slideshow target=p...
def receive_telegram_callback(self, event_id, payload_event, *args): assert event_id == 'telegram_callback' params = payload_event['data'].replace("/","").split(";") if len(params) > 0: if len(params) > 2 and params[0] == "slideshow": self.handle_slideshow(target=payload_event[...
Python
nomic_cornstack_python_v1
comment Problem ID: KOL16J comment Problem Name: Quentin Tarantin for _ in range integer input begin set n = integer input set l = list map int split input set c = list for i in range 1 n + 1 begin append c i end if l != sorted l and sorted l == c begin print string yes end else begin print string no end end
#Problem ID: KOL16J #Problem Name: Quentin Tarantin for _ in range(int(input())): n = int(input()) l = list(map(int, input().split())) c = [] for i in range(1, n+1): c.append(i) if(l != sorted(l) and sorted(l) == c): print("yes") else: print("no")
Python
zaydzuhri_stack_edu_python
function assert_series_equal left right check_dtype=true check_index_type=string equiv check_series_type=true check_less_precise=false check_names=true check_exact=false check_datetimelike_compat=false check_categorical=true obj=string Series begin set __tracebackhide__ = true comment instance validation call _check_is...
def assert_series_equal(left, right, check_dtype=True, check_index_type='equiv', check_series_type=True, check_less_precise=False, check_names=True, check_exact=False, check_da...
Python
nomic_cornstack_python_v1
comment def check(l, r, value): # 이진탐색 comment global cnt comment m = (l+r)//2 comment if n_arr[m] == value: comment cnt += 1 comment return comment elif l <= r: comment if value < n_arr[m]: comment check(l, m-1, value) comment if n_arr[m] < value: comment check(m+1, r, value) comment else: comment return for tc in ran...
# def check(l, r, value): # 이진탐색 # global cnt # m = (l+r)//2 # # if n_arr[m] == value: # cnt += 1 # return # elif l <= r: # if value < n_arr[m]: # check(l, m-1, value) # if n_arr[m] < value: # check(m+1, r, value) # else: # return for ...
Python
zaydzuhri_stack_edu_python
function _set_preempt self v load=false begin if has attribute v string _utype begin set v = call _utype v end try begin set t = call YANGDynClass v base=YANGBool default=call YANGBool string true is_leaf=true yang_name=string preempt parent=self path_helper=_path_helper extmethods=_extmethods register_paths=true names...
def _set_preempt(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, default=YANGBool("true"), is_leaf=True, yang_name="preempt", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconf...
Python
nomic_cornstack_python_v1
function get_node_children_names model node begin set output_nodes = call get_children node set outputs = list comprehension name for node in output_nodes return outputs end function
def get_node_children_names(model, node): output_nodes = model.get_children(node) outputs = [node.name for node in output_nodes] return outputs
Python
nomic_cornstack_python_v1
comment students = [ comment {'first_name': 'Michael', 'last_name' : 'Jordan'}, comment {'first_name' : 'John', 'last_name' : 'Rosales'}, comment {'first_name' : 'Mark', 'last_name' : 'Guillen'}, comment {'first_name' : 'KB', 'last_name' : 'Tonel'} comment ] comment for i in students: comment print i['first_name'] +" "...
# students = [ # {'first_name': 'Michael', 'last_name' : 'Jordan'}, # {'first_name' : 'John', 'last_name' : 'Rosales'}, # {'first_name' : 'Mark', 'last_name' : 'Guillen'}, # {'first_name' : 'KB', 'last_name' : 'Tonel'} # ] # # for i in students: # print i['first_name'] +" "+ i['last_name'] # #...
Python
zaydzuhri_stack_edu_python
function test_validation_errors_are_not_raised_for_valid_exploration self begin set exploration = call create_default_exploration VALID_EXP_ID title=string title category=string category objective=string Test Exploration call add_states list string End set intro_state = states at string Introduction set end_state = sta...
def test_validation_errors_are_not_raised_for_valid_exploration(self): exploration = exp_domain.Exploration.create_default_exploration( self.VALID_EXP_ID, title='title', category='category', objective='Test Exploration') exploration.add_states(['End']) intro_state = expl...
Python
nomic_cornstack_python_v1
function variable_length_to_fixed_length_categorical self left_edge=4 right_edge=4 max_length=15 begin set cache_key = tuple string fixed_length_categorical left_edge right_edge max_length if cache_key not in encoding_cache begin set fixed_length_sequences = call sequences_to_fixed_length_index_encoded_array sequences ...
def variable_length_to_fixed_length_categorical( self, left_edge=4, right_edge=4, max_length=15): cache_key = ( "fixed_length_categorical", left_edge, right_edge, max_length) if cache_key not in self.encoding_cache: fixed_length_s...
Python
nomic_cornstack_python_v1
comment ______________________________________________________________________________ comment Termin 1 comment Pogojni stavek comment ______________________________________________________________________________ comment Ugotovili smo da primerjave nam za odgovor podajo tip boolean (True/False) comment To lahko uporab...
#______________________________________________________________________________ # Termin 1 # Pogojni stavek #______________________________________________________________________________ # Ugotovili smo da primerjave nam za odgovor podajo tip boolean (True/False) # To lahko uporabimo tako da programu naročimo da prev...
Python
zaydzuhri_stack_edu_python
function vote_view request begin set votes = call get_votes student set is_voting_active = call is_system_active return call TemplateResponse request string offer/vote/view.html locals end function
def vote_view(request): votes = SingleVote.get_votes(request.user.student) is_voting_active = SystemState.get_state(date.today().year).is_system_active() return TemplateResponse(request, 'offer/vote/view.html', locals())
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 import argparse import json import sys import yaml function main begin string Convert a YAML document to a JSON document. set parser = call ArgumentParser description=__doc__ call add_argument string file nargs=string ? set args = call parse_args if file begin with open file string rb as f...
#!/usr/bin/env python3 import argparse import json import sys import yaml def main() -> None: """ Convert a YAML document to a JSON document. """ parser = argparse.ArgumentParser(description=main.__doc__) parser.add_argument("file", nargs="?") args = parser.parse_args() if args.file: ...
Python
zaydzuhri_stack_edu_python
import random set IMAGENES = list string +---+ | | | | | | ========= string +---+ | | O | | | | ========= string +---+ | | O | | | | | ========= string +---+ | | O | /| | | | ========= string +---+ | | O | /|\ | | | ========= string +---+ | | O | /|\ | | | | ========= string +---+ | | O | /|\ | | | / | ========= string...
import random IMAGENES= [''' +---+ | | | | | | =========''', ''' +---+ | | O | | | | =========''', ''' +---+ | | O | | | ...
Python
zaydzuhri_stack_edu_python
function endpoints self begin return list comprehension call text el for el in call elements ITEMS_LOCATOR parent=self end function
def endpoints(self): return [self.browser.text(el) for el in self.browser.elements(self.ITEMS_LOCATOR, parent=self)]
Python
nomic_cornstack_python_v1
string This file contains methods for importing and pre-processing the data from the Breast Cancer data set used in the paper "Evaluating gene set enrichment analysis via a hybrid data model" by J. Hua et al. 2014. ASSUMES ALL FILES ARE ENCODED AS UTF-7! (Which they are originally!) import os import glob from data_mode...
''' This file contains methods for importing and pre-processing the data from the Breast Cancer data set used in the paper "Evaluating gene set enrichment analysis via a hybrid data model" by J. Hua et al. 2014. ASSUMES ALL FILES ARE ENCODED AS UTF-7! (Which they are originally!) ''' import os import glob from data_...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt import numpy as np import pandas as pd import matplotlib as mpl from matplotlib.colors import ListedColormap from sklearn import datasets , neighbors , linear_model from sklearn.model_selection import train_test_split import functools import itertools from ipywidgets import interact , fi...
import matplotlib.pyplot as plt import numpy as np import pandas as pd import matplotlib as mpl from matplotlib.colors import ListedColormap from sklearn import datasets, neighbors, linear_model from sklearn.model_selection import train_test_split import functools import itertools from ipywidgets import interact, f...
Python
zaydzuhri_stack_edu_python
comment pandas.Series class Series begin string http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html http://pandas.pydata.org/pandas-docs/stable/api.html#series comment Series.get function get key default=none begin string @key : object @Returns: value : type of items contained in object Get item fr...
class Series(data=None, index=None, dtype=None, name=None, copy=False, fastpath=False): # pandas.Series ''' http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html http://pandas.pydata.org/pandas-docs/stable/api.html#series ''' def get(key, default=None): # Series.get ''' @key : objec...
Python
zaydzuhri_stack_edu_python
import urllib.request import cv2 import numpy as numpy import os function store_raw_images begin set neg_images_link = string http://www.image-net.org/api/text/imagenet.synset.geturls?wnid=n00523513 set neg_image_urls = decode read url open nneg_images_link if not exists path string neg begin make directories string ne...
import urllib.request import cv2 import numpy as numpy import os def store_raw_images(): neg_images_link = 'http://www.image-net.org/api/text/imagenet.synset.geturls?wnid=n00523513' neg_image_urls = urllib.request.urlopen(nneg_images_link).read().decode() if not os.path.exists('neg'): os.makedirs('neg') pic_nu...
Python
zaydzuhri_stack_edu_python
function _to_ms atime begin return integer call mktime call timetuple * 1000 + microsecond / 1000 end function
def _to_ms(atime): return int(time.mktime(atime.timetuple()) * 1000 + atime.microsecond/1000)
Python
nomic_cornstack_python_v1
comment ! python3 comment formFiller.py - フォームの自動入力 import pyautogui , time comment 以下の値は実際に調べたものに置き換えること。 set name_field = tuple 648 319 set submit_button = tuple 651 817 set submit_button_color = tuple 75 141 249 set submit_another_link = tuple 760 224
#! python3 # formFiller.py - フォームの自動入力 import pyautogui, time # 以下の値は実際に調べたものに置き換えること。 name_field = (648, 319) submit_button = (651, 817) submit_button_color = (75, 141, 249) submit_another_link = (760, 224)
Python
zaydzuhri_stack_edu_python
comment path for this file: /Users/engin/Documents/COURSES/UDACITY PFDS/PYTHON/Projecti import time import pandas as pd import numpy as np import sys comment dictionary to file names for each city set CITY_DATA = dict string chicago string chicago.csv ; string new york string new_york_city.csv ; string washington strin...
## path for this file: /Users/engin/Documents/COURSES/UDACITY PFDS/PYTHON/Projecti import time import pandas as pd import numpy as np import sys #dictionary to file names for each city CITY_DATA = { 'chicago': 'chicago.csv', 'new york': 'new_york_city.csv', 'washington': 'washington.csv' }...
Python
zaydzuhri_stack_edu_python
if asc in range 33 48 begin print string This character is not an alphanumeric character. end else if asc in range 48 58 begin print string This character is a number. end else if asc in range 58 65 begin print string This character is not an alphanumeric character. end else if asc in range 65 91 begin print string Thi...
if asc in range (33, 48): print("This character is not an alphanumeric character.") elif asc in range (48, 58): print("This character is a number.") elif asc in range (58, 65): print("This character is not an alphanumeric character.") elif asc in range (65, 91): print("This character is a cap...
Python
zaydzuhri_stack_edu_python
comment Santa's Sleigh comment Santa claus comment Santa's sleigh comment https://www.novelgames.com/en/sleigh/ comment https://www.itread01.com/content/1544360780.html comment %% comment deepcopy import copy comment ceil import math import random seed 10 function printNode msg node begin string print msg and node stat...
# Santa's Sleigh # Santa claus # Santa's sleigh # https://www.novelgames.com/en/sleigh/ # https://www.itread01.com/content/1544360780.html # %% import copy # deepcopy import math # ceil import random random.seed(10) def printNode(msg, node): """print msg and node state Arguments: msg {string}...
Python
zaydzuhri_stack_edu_python
import sqlite3 from Guest import Guest class InterfaceDB extends object begin function __init__ self begin pass end function function selectGuests self begin set db = call connect string Guests.db set cur = call cursor set datas = execute cur string SELECT * FROM guest set listDB = list for i in datas begin print i ap...
import sqlite3 from Guest import Guest class InterfaceDB(object): def __init__(self): pass def selectGuests(self): db = sqlite3.connect('Guests.db') cur = db.cursor() datas = cur.execute("SELECT * FROM guest") # listDB = [] # for i in datas: ...
Python
zaydzuhri_stack_edu_python
from datetime import datetime import webbrowser if call weekday == 1 begin open string https://www.producthunt.com/ end
from datetime import datetime import webbrowser if datetime.now().weekday() == 1: webbrowser.open('https://www.producthunt.com/')
Python
flytech_python_25k
class Solution begin function merge self nums1 m nums2 n begin string Do not return anything, modify nums1 in-place instead. set tuple i j = tuple m - 1 n - 1 set end = m + n - 1 while i > - 1 and j > - 1 begin if nums1 at i > nums2 at j begin set nums1 at end = nums1 at i set i = i - 1 end else begin set nums1 at end ...
class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ i,j = m-1,n-1 end = m+n -1 while i > -1 and j > -1: if nums1[i] > nums2[j]: nums1[en...
Python
zaydzuhri_stack_edu_python
function delete self user begin set created_groups = filter creator == user if call _groups_have_anns_from_other_users created_groups user begin raise call UserDeleteError string Other users have annotated in groups created by this user end call _delete_annotations user call _delete_groups created_groups delete user en...
def delete(self, user): created_groups = self.request.db.query(Group) \ .filter(Group.creator == user) if self._groups_have_anns_from_other_users(created_groups, user): raise UserDeleteError('Other users have annotated in groups created by this user')...
Python
nomic_cornstack_python_v1
import sys set data = list function hor data begin for x in data begin yield x end end function function ver data begin for x in range 4 begin yield list comprehension y at x for y in data end end function function diag data begin yield tuple data at 0 at 0 data at 1 at 1 data at 2 at 2 data at 3 at 3 yield tuple data...
import sys data = [] def hor(data): for x in data: yield x def ver(data): for x in range(4): yield [y[x] for y in data] def diag(data): yield data[0][0], data[1][1] , data[2][2] , data[3][3] yield data[0][3], data[1][2] , data[2][1] , data[3][0]
Python
zaydzuhri_stack_edu_python
comment pylint:disable=redefined-outer-name from __future__ import print_function import json from player import Player function test_serialising begin set p = call Player 1 2 set jsonStr = dumps p cls=Encoder set jsonObj = loads jsonStr assert jsonObj at string playerID == 2 assert jsonObj at string teamID == 1 assert...
# pylint:disable=redefined-outer-name from __future__ import print_function import json from player import Player def test_serialising(): p = Player(1, 2) jsonStr = json.dumps(p, cls=Player.Encoder) jsonObj = json.loads(jsonStr) assert jsonObj["playerID"] == 2 assert jsonObj["teamID"] == 1 ...
Python
zaydzuhri_stack_edu_python
function bboxes_resize bbox_ref bboxes name=none begin comment Bboxes is dictionary. if is instance bboxes dict begin with call name_scope name string bboxes_resize_dict begin set d_bboxes = dict for c in keys bboxes begin set d_bboxes at c = call bboxes_resize bbox_ref bboxes at c end return d_bboxes end end comment ...
def bboxes_resize(bbox_ref, bboxes, name=None): # Bboxes is dictionary. if isinstance(bboxes, dict): with tf.name_scope(name, 'bboxes_resize_dict'): d_bboxes = {} for c in bboxes.keys(): d_bboxes[c] = bboxes_resize(bbox_ref, bboxes[c]) return d_bboxes ...
Python
nomic_cornstack_python_v1
function test_stdout_detached convert_newlines begin with call stdio_mgr as tuple i o e begin print string test str set f = detach o assert is instance f BufferedRandom assert f is _buf assert f is _buf assert call convert_newlines string test str == call getvalue with raises ValueError as err begin write o string seco...
def test_stdout_detached(convert_newlines): with stdio_mgr() as (i, o, e): print("test str") f = o.detach() assert isinstance(f, io.BufferedRandom) assert f is o._buf assert f is i.tee._buf assert convert_newlines("test str\n") == o.getvalue() with pytest....
Python
nomic_cornstack_python_v1
function Autoencoder input_tensor begin with call variable_scope string autoencoder begin set pad = string SAME comment ENCODER ### comment 1,8,8,2048 with call variable_scope string conv1 begin set out = call convolution2d inputs=input_tensor num_outputs=2048 kernel_size=3 stride=1 padding=pad rate=1 activation_fn=rel...
def Autoencoder(input_tensor): with tf.variable_scope('autoencoder'): pad = 'SAME' ##################### ### ENCODER ### ##################### #1,8,8,2048 with tf.variable_scope('conv1'): out = convolution2d(inputs=input_tensor, num_outputs=2048, k...
Python
nomic_cornstack_python_v1
from math import ceil function main begin set n = integer input set n_len = length string n set h_n_len = ceil n_len / 2 set count = 10 ^ h_n_len - 1 - 1 for i in range 10 ^ h_n_len - 1 10 ^ h_n_len begin set num = integer string i * 2 if num > n begin break end set count = count + 1 end print count end function if __n...
from math import ceil def main(): n = int(input()) n_len = len(str(n)) h_n_len = ceil(n_len / 2) count = 10 ** (h_n_len - 1) - 1 for i in range(10 ** (h_n_len - 1), 10 ** h_n_len): num = int(str(i) * 2) if num > n: break count += 1 print(count) if __name__...
Python
zaydzuhri_stack_edu_python
string 2017年6月1日15:15:15 读取代理IP网站的API,并获得代理IP 1. 访问西祠代理的API接口 2. 获得数据,并用正则表达式提取关键内容 3. 用列表保存关键内容 import requests import re comment from requests import ProxyError comment 存储IP地址的容器 set all_url = list comment 代理IP的网址 set url = string http://dev.kdlapi.com/api/getproxy set r = get requests url=url print text set all_url...
''' 2017年6月1日15:15:15 读取代理IP网站的API,并获得代理IP 1. 访问西祠代理的API接口 2. 获得数据,并用正则表达式提取关键内容 3. 用列表保存关键内容 ''' import requests import re # from requests import ProxyError all_url = [] # 存储IP地址的容器 # 代理IP的网址 url = "http://dev.kdlapi.com/api/getproxy" r = requests.get(url=url) print(r.text) all_url = re.findall("\d+\.\d+\.\d+...
Python
zaydzuhri_stack_edu_python
function _updateCalendar_VTODO self calendar newToken begin comment Grab old hrefs prior to the PROPFIND so we sync with the old state. We need this because comment the sim can fire a PUT between the PROPFIND and when process the removals. set old_hrefs = set list comprehension url + child for child in keys events set ...
def _updateCalendar_VTODO(self, calendar, newToken): # Grab old hrefs prior to the PROPFIND so we sync with the old state. We need this because # the sim can fire a PUT between the PROPFIND and when process the removals. old_hrefs = set([calendar.url + child for child in calendar.events.keys()]...
Python
nomic_cornstack_python_v1
from flask import Flask , jsonify import Prediction set app = call Flask __name__ decorator call route string /GLAPS/<int:homeValue>/<string:stateCountyString> methods=list string GET function yourfunctionname stateCountyString homeValue begin set tuple prediction predictionS homeValue homeValueS = call prediction stat...
from flask import Flask, jsonify import Prediction app = Flask(__name__) @app.route('/GLAPS/<int:homeValue>/<string:stateCountyString>', methods=['GET']) def yourfunctionname(stateCountyString, homeValue): prediction, predictionS, homeValue, homeValueS = Prediction.prediction(stateCountyString, homeValue) val...
Python
zaydzuhri_stack_edu_python
function getTriples planes begin set n = length planes set triples = list for i in range n begin for j in range i + 1 n begin for k in range j + 1 n begin append triples tuple planes at i planes at j planes at k end end end return triples end function
def getTriples(planes): n = len(planes) triples = [] for i in range(n): for j in range(i+1, n): for k in range(j+1, n): triples.append((planes[i], planes[j], planes[k])) return triples
Python
nomic_cornstack_python_v1
import math class Circle begin comment 생성자 function __init__ self radius begin set radius = radius end function function Length self begin return 2 * radius * pi end function function Area self begin return radius ^ 2 * pi end function end class set c1 = call Circle 3 comment "c1's radius : 3" 출력 print string c1's radi...
import math class Circle: def __init__(self, radius): # 생성자 self.radius = radius def Length(self): return 2*self.radius*math.pi def Area(self): return (self.radius**2)*math.pi c1 = Circle(3) print("c1's radius : " + str(c1.radius)) # "c1's radius : 3" 출력 print("c1's length : " + ...
Python
zaydzuhri_stack_edu_python
function plot_acc_loss self title prefix_1 prefix_2=none slice_=call slice none save=false fname=string log=false begin with call context string ggplot begin set fig = figure figsize=tuple 6 8 set ax = list append ax call add_subplot 211 append ax call add_subplot 212 call set_title title call set_ylabel string Accur...
def plot_acc_loss(self, title, prefix_1, prefix_2=None, slice_=slice(None), save=False, fname="", log=False): with plt.style.context('ggplot'): fig = plt.figure(figsize=(6, 8)) ax = [] ax.append(fig.add_subplot(211)) ax.append(fig.add_subplot(212)) a...
Python
nomic_cornstack_python_v1
function sanitize url begin comment 7 set protocol = string http:// comment 8 set protocol1 = string https:// if url at slice 0 : 7 : == protocol or url at slice 0 : 8 : == protocol1 begin return true end else begin return false end end function
def sanitize(url): protocol = 'http://' # 7 protocol1 = 'https://' # 8 if url[0:7] == protocol or url[0:8] == protocol1: return True else: return False
Python
zaydzuhri_stack_edu_python
function __select_min_call self df_call_market k a m j begin return iloc at 0 at string Last end function
def __select_min_call(self, df_call_market, k, a, m, j): return ((df_call_market[(df_call_market.index.get_level_values(0) == k) & (df_call_market.index.get_level_values(1) == dt.datetime.strptime( str(a) + '-' + str(m) + '-' + str(j), '%Y-%...
Python
nomic_cornstack_python_v1
function fit self x y y_sigma=1e-10 params_0=none method=string direct **kwargs begin if params_0 is not none begin assert is instance params_0 list end else begin set params_0 = params end set x_known = x if get kwargs string y_shift true begin set y_shift = mean np y end else begin set y_shift = 0.0 end set y_known =...
def fit(self, x, y, y_sigma=1e-10, params_0=None, method="direct", **kwargs): if params_0 is not None: assert isinstance(params_0, list) else: params_0 = self.cov_fn.params self.x_known = x if kwargs.get("y_shift", True): self.y_shift = np.mean(y) ...
Python
nomic_cornstack_python_v1
function lerp_color start_color end_color blend_value begin set r = call red + call red - call red * blend_value set g = call green + call green - call green * blend_value set b = call blue + call blue - call blue * blend_value return call QColor r g b end function
def lerp_color(start_color, end_color, blend_value): r = start_color.red() + (end_color.red() - start_color.red()) * blend_value g = start_color.green() + (end_color.green() - start_color.green()) * blend_value b = start_color.blue() + (end_color.blue() - start_color.blue()) * blend_value return QtGui.Q...
Python
nomic_cornstack_python_v1
comment Тема 4. Функции. comment 1: Создайте функцию, принимающую на вход имя, возраст и город проживания человека. comment Функция должна возвращать строку вида «Василий, 21 год(а), проживает в print string Задание 1 set name = input string Введите свое имя: set age = input string Введите свой возраст: set city = inpu...
#Тема 4. Функции. #1: Создайте функцию, принимающую на вход имя, возраст и город проживания человека. # Функция должна возвращать строку вида «Василий, 21 год(а), проживает в print(' Задание 1 \n') name = input('Введите свое имя: ', ) age = input('Введите свой возраст: ') city = input('Введите город проживания: ') def ...
Python
zaydzuhri_stack_edu_python
function check_bootstrap_new_branch branch version_path addn_kwargs begin set addn_kwargs at string version_path = version_path set addn_kwargs at string head = string { branch } @head if not exists path version_path begin comment Bootstrap initial directory structure call ensure_tree version_path mode=493 end end func...
def check_bootstrap_new_branch(branch, version_path, addn_kwargs): addn_kwargs['version_path'] = version_path addn_kwargs['head'] = f'{branch}@head' if not os.path.exists(version_path): # Bootstrap initial directory structure fileutils.ensure_tree(version_path, mode=0o755)
Python
nomic_cornstack_python_v1
function put self pet_id begin info string Request to Update a pet with id [%s] pet_id comment check_content_type('application/json') set pet = find Pet pet_id if not pet begin call abort HTTP_404_NOT_FOUND format string Pet with id '{}' was not found. pet_id end set payload = call get_json try begin call deserialize p...
def put(self, pet_id): app.logger.info('Request to Update a pet with id [%s]', pet_id) #check_content_type('application/json') pet = Pet.find(pet_id) if not pet: abort(status.HTTP_404_NOT_FOUND, "Pet with id '{}' was not found.".format(pet_id)) payload = request.get_...
Python
nomic_cornstack_python_v1
function push_stack self value begin set new_node = call Node value if head is none begin set head = new_node return end set next = head set head = new_node set num_elements = num_elements + 1 end function
def push_stack(self, value): new_node = Node(value) if self.head is None: self.head = new_node return new_node.next = self.head self.head = new_node self.num_elements += 1
Python
nomic_cornstack_python_v1
function getSkyAt self **argv begin raise call NotImplementedError string getSkyAt end function
def getSkyAt(self, **argv): raise NotImplementedError("getSkyAt")
Python
nomic_cornstack_python_v1
function suma lista begin if lista == list begin return 0 end else begin return lista at 0 + call suma lista at slice 1 : : end end function
def suma (lista): if lista ==[]: return 0 else: return lista[0]+suma(lista[1:])
Python
zaydzuhri_stack_edu_python
import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model comment generate dataset containing input and output set bedrooms = list 3 2 4 2 3 4 set lot_sizes = list 10000 20000 30000 40000 50000 60000 set prices = list 20000 25000 30000 35000 40000 45000 comment reshape the data set bedrooms_da...
import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model #generate dataset containing input and output bedrooms = [3,2,4,2,3,4] lot_sizes = [10000,20000,30000,40000,50000,60000] prices = [20000,25000,30000,35000,40000,45000] #reshape the data bedrooms_data = np.array(bedrooms).reshape(-1,1)...
Python
flytech_python_25k
from math import floor comment Clase Entrada Cuco comment Descripcion: Crea un nodo tipo entrada. comment Atributos: Clave y dato del nodo. comment Métodos: Ninguno. class EntradaCuco extends object begin function __init__ self clave dato begin set clave = clave set dato = dato end function end class comment Clase Hash...
from math import floor ################################################################################ # Clase Entrada Cuco # Descripcion: Crea un nodo tipo entrada. # Atributos: Clave y dato del nodo. # Métodos: Ninguno. ################################################################################ class EntradaC...
Python
zaydzuhri_stack_edu_python
function set_input_layer_combobox self cbBox item=string begin clear cbBox set layer_list = call get_raster_layers false if length layer_list > 0 begin for tuple index aName in enumerate layer_list begin call addItem string call setItemText index aName if aName == item begin call setCurrentIndex index end end end retur...
def set_input_layer_combobox(self, cbBox, item=''): cbBox.clear() layer_list = self.get_raster_layers(False) if len(layer_list) > 0: for index, aName in enumerate(layer_list): cbBox.addItem('') cbBox.setItemText(index, aName) if aName =...
Python
nomic_cornstack_python_v1
while senha == usuario begin print string Senha inválida! A senha não deve ser igual ao nome de usuário. set usuario = input string Nome de usuário: set senha = input string Senha: end print string Cadastro realizado com sucesso!
while senha == usuario : print ('Senha inválida! A senha não deve ser igual ao nome de usuário.') usuario = input ('Nome de usuário: ') senha = input ('Senha: ') print ('Cadastro realizado com sucesso!')
Python
zaydzuhri_stack_edu_python
import sys set roll = input if integer roll > 2 or integer roll < 1 begin print string roll error exit end set score = input if integer score > 100 or integer score < 0 begin print string score error exit end if integer roll == 1 begin if integer score < 60 begin print string fail end else begin print string pass end e...
import sys roll = input() if int(roll) > 2 or int(roll) < 1: print('roll error') sys.exit() score = input() if int(score) > 100 or int(score) < 0: print('score error') sys.exit() if int(roll) == 1: if int(score) < 60: print('fail') else: print('pass') else: if int(score) < 70: print('f...
Python
zaydzuhri_stack_edu_python
comment modules_2.py => comment L3-4 problem: comment Run this and observe the output. comment Then uncomment the three r.seed(...) statements, and rerun. comment We'll discuss in class why the output changes, and explain why r.seed() is useful import random as r print string with seed(4747): seed 4747 for count in ran...
# # modules_2.py => # # L3-4 problem: # # Run this and observe the output. # # Then uncomment the three r.seed(...) statements, and rerun. # # We'll discuss in class why the output changes, and explain why r.seed() is useful # import random as r print ("\nwith seed(4747):\n") r.seed(4747) for count in range(5): p...
Python
zaydzuhri_stack_edu_python
string This player keeps a map of the maze as much as known. Using this, it can find areas that are left to explore, and try to find the nearest one. Areas left to explore are called "Path" in this game. We don't know where on the map we start, and we don't know how big the map is. We could be lazy and simply make a ve...
""" This player keeps a map of the maze as much as known. Using this, it can find areas that are left to explore, and try to find the nearest one. Areas left to explore are called "Path" in this game. We don't know where on the map we start, and we don't know how big the map is. We could be lazy and simply make a very...
Python
zaydzuhri_stack_edu_python
function which program_name extra_paths=list begin set paths = list if call has_key string PATH begin set paths = environ at string PATH set paths = split paths pathsep end set paths = paths + extra_paths for dir in paths begin set full_path = join path dir program_name if exists path full_path begin return full_path ...
def which(program_name, extra_paths=[]): paths = [] if os.environ.has_key("PATH"): paths = os.environ["PATH"] paths = paths.split(os.pathsep) paths = paths + extra_paths for dir in paths: full_path = os.path.join(dir, program_name) if os.path.exists(full_path): ...
Python
nomic_cornstack_python_v1
function test_logout_route_auth_redirects_to_home testapp begin set response = get testapp string /logout set home = path assert ends with location home end function
def test_logout_route_auth_redirects_to_home(testapp): response = testapp.get("/logout") home = testapp.app.routes_mapper.get_route('home').path assert response.location.endswith(home)
Python
nomic_cornstack_python_v1
function on_wrong_path_visibility self begin call _set_filter_value string vizWrongPathState call isChecked end function
def on_wrong_path_visibility(self): self._set_filter_value( 'vizWrongPathState', self.wrong_path_visibility_btn.isChecked())
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import matplotlib.lines as mlines import numpy.lib.recfunctions as rfn from spaceutils import megaparsec_to_lightyear , show_maximized_plot comment =================================================================================...
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import matplotlib.lines as mlines import numpy.lib.recfunctions as rfn from spaceutils import megaparsec_to_lightyear, show_maximized_plot #=============================================================================...
Python
zaydzuhri_stack_edu_python
function test_create_classical_registers_noname self begin set q_program = call QuantumProgram set classical_registers = list dict string size 4 dict string size 2 set crs = call create_classical_registers classical_registers for i in crs begin assert is instance i ClassicalRegister end end function
def test_create_classical_registers_noname(self): q_program = QuantumProgram() classical_registers = [{"size": 4}, {"size": 2}] crs = q_program.create_classical_registers(classical_registers) for i in crs: self.assertIsInstance(i, ClassicalRegis...
Python
nomic_cornstack_python_v1
import json import threading from time import sleep from requests import get from cv2 import VideoCapture , imwrite , CAP_DSHOW from watson_developer_cloud import VisualRecognitionV3 set visual_recognition = call VisualRecognitionV3 string 2018-03-19 iam_apikey=string 5mZ_49J41rVBfJdLXFd47jcbbsQWm71yMpqZorMzxUSa set ca...
import json import threading from time import sleep from requests import get from cv2 import VideoCapture,imwrite,CAP_DSHOW from watson_developer_cloud import VisualRecognitionV3 visual_recognition = VisualRecognitionV3('2018-03-19',iam_apikey='5mZ_49J41rVBfJdLXFd47jcbbsQWm71yMpqZorMzxUSa') camera = VideoCapture(0) i...
Python
zaydzuhri_stack_edu_python
import bisect import math import sys set n = integer input set ans = 0 set a = list map int split input set b = list map int split input set c = list map int split input sort a sort b sort c for i in b begin set aa = call bisect_left a i set cc = length c - call bisect_right c i set ans = ans + aa * cc end print ans
import bisect import math import sys n=int(input()) ans=0 a=list(map(int,input().split())) b=list(map(int,input().split())) c=list(map(int,input().split())) a.sort() b.sort() c.sort() for i in b: aa=bisect.bisect_left(a,i) cc=len(c)-bisect.bisect_right(c,i) ans+=aa*cc print(ans)
Python
zaydzuhri_stack_edu_python
for i in range 10 begin for j in range 10 begin if j < i begin print string end=string end else begin print j - i end=string end end print end
for i in range(10): for j in range(10): if j < i: print(" ", end=" ") else: print(j-i, end=" ") print()
Python
zaydzuhri_stack_edu_python
function download_and_extract_tiny_imagenet_pre_trained_resnet_v2_50 begin if not is directory path string ./data begin make directory os string ./data end if not is directory path string ./data/models begin make directory os string ./data/models end set resnet_v2_50_meta_file = join path string ./ string data string m...
def download_and_extract_tiny_imagenet_pre_trained_resnet_v2_50(): if not os.path.isdir('./data'): os.mkdir('./data') if not os.path.isdir('./data/models'): os.mkdir('./data/models') resnet_v2_50_meta_file = os.path.join('./', 'data', 'models', 'tiny_imagenet_base_2018_06_26.ckpt.meta') ...
Python
nomic_cornstack_python_v1
function _on_connection_close_ok self method_frame begin debug string _on_connection_close_ok: frame=%s method_frame call _terminate_stream none end function
def _on_connection_close_ok(self, method_frame): LOGGER.debug('_on_connection_close_ok: frame=%s', method_frame) self._terminate_stream(None)
Python
nomic_cornstack_python_v1
function test__rmod__ parameter begin set tuple par _ = parameter call assert_allclose 2 % par 2 call assert_allclose 25 % par 5 end function
def test__rmod__(parameter): par, _ = parameter assert_allclose(2 % par, 2) assert_allclose(25 % par, 5)
Python
nomic_cornstack_python_v1
for i in range len_start begin set spoken at inputs at i = list - 1 i end set prev = inputs at - 1 for i in range len_start 30000000 begin comment not spoken before if spoken at prev at 0 == - 1 begin set cur = 0 end else begin set cur = spoken at prev at 1 - spoken at prev at 0 end comment update dict if cur in spoken...
for i in range(len_start): spoken[inputs[i]] = [-1, i] prev = inputs[-1] for i in range(len_start, 30000000): # not spoken before if spoken[prev][0] == -1: cur = 0 else: cur = spoken[prev][1] - spoken[prev][0] # update dict if cur in spoken: spoken[cur][0] = spoken[cur]...
Python
zaydzuhri_stack_edu_python
comment 求平均值 ,问题来自讨论区 comment 法一 comment zum = 0 comment count = 0 comment moredata = "y" comment while moredata == "y": # 记得上下条件一致,否则进不了循环,就会得到错误的结果 comment x = int(input("Enter a number >>")) comment zum += x comment count += 1 comment moredata = input("Do you have more numbers(yes or no)?>>") comment print("The aver...
# 求平均值 ,问题来自讨论区 # 法一 # zum = 0 # count = 0 # moredata = "y" # while moredata == "y": # 记得上下条件一致,否则进不了循环,就会得到错误的结果 # x = int(input("Enter a number >>")) # zum += x # count += 1 # moredata = input("Do you have more numbers(yes or no)?>>") # print("The average of the number is", zum / count) # print(type...
Python
zaydzuhri_stack_edu_python
from sqlalchemy import create_engine , MetaData , Table , Column , Integer , String , Float , Date , insert , delete , text import pandas as pd function create_postgress_engine username password dialect_driver host port database begin set db_url = string { dialect_driver } :// { username } : { password } @ { host } : {...
from sqlalchemy import (create_engine, MetaData, Table, Column, Integer, String, Float, Date, insert, ...
Python
zaydzuhri_stack_edu_python
function from_file cls slots fileobj offset=0 begin return call from_fileno slots call fileno offset end function
def from_file(cls, slots, fileobj, offset = 0): return cls.from_fileno(slots, fileobj.fileno(), offset)
Python
nomic_cornstack_python_v1
string sum 对数组中全部或某轴向的元素求和。零长度的数组的sum为0。 mean 算术平均数。零长度的数组的mean为NaN。 std, var 分别为标准差和方差,自由度可调(默认为n)。 min, max 最大值和最小值 argmin 分别为最大值和最小值的索引 cumsum 所有元素的累计和 cumprod 所有元素的累计积 comment 标准差和方差的解释 comment cumsum和cumprod的解释 print string 求和,求平均 set arr = randn 5 4 print arr print mean arr print sum comment 对每一行的元素求平均 print mean...
''' sum 对数组中全部或某轴向的元素求和。零长度的数组的sum为0。 mean 算术平均数。零长度的数组的mean为NaN。 std, var 分别为标准差和方差,自由度可调(默认为n)。 min, max 最大值和最小值 argmin 分别为最大值和最小值的索引 cumsum 所有元素的累计和 cumprod 所有元素的累计积 ''' # 标准差和方差的解释 # cumsum和cumprod的解释 print('求和,求平均') arr = np.random.randn(5, 4) print(arr ) print( arr.mean()) print( arr.sum()) print( arr....
Python
zaydzuhri_stack_edu_python
from bs4 import BeautifulSoup import string import mimetypes import base64 import hmac import hashlib import pystache import argparse from datetime import datetime , timezone from distutils import dir_util from pbkdf2 import PBKDF2 from Crypto.Cipher import AES set VERSION = string 0.2 comment https://gist.github.com/s...
from bs4 import BeautifulSoup import string import mimetypes import base64 import hmac import hashlib import pystache import argparse from datetime import datetime,timezone from distutils import dir_util from pbkdf2 import PBKDF2 from Crypto.Cipher import AES VERSION = "0.2" # https://gist.github.com/seanh/93666 def ...
Python
zaydzuhri_stack_edu_python
while c != 0 begin set f = f * c set c = c - 1 end print f
while c != 0: f *= c c -= 1 print(f)
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Sat Mar 19 16:10:01 2016 @author: Maya comment Import the random forest package from sklearn.ensemble import RandomForestClassifier comment Create the random forest object which will include all the parameters comment for the fit set forest = random forest classifier n_es...
# -*- coding: utf-8 -*- """ Created on Sat Mar 19 16:10:01 2016 @author: Maya """ # Import the random forest package from sklearn.ensemble import RandomForestClassifier # Create the random forest object which will include all the parameters # for the fit forest = RandomForestClassifier(n_estimators = 100) # Fit th...
Python
zaydzuhri_stack_edu_python
function basic_operations a b begin return tuple a + b a - b a * b a / b a ^ b a // b a % b end function set tuple A B = tuple 7 3 comment These two assignations are equivalent set tuple addition difference multiplication division exponent integerPart module = call basic_operations A B set results = call basic_operatio...
def basic_operations(a, b): return a + b, a - b, a * b, a / b, a ** b, a // b, a % b A, B = 7, 3 # These two assignations are equivalent addition, difference, multiplication, division, exponent, integerPart, module = basic_operations(A, B) results = basic_operations(A, B) print("A =", A, "\tB =", B, "\n") prin...
Python
zaydzuhri_stack_edu_python
comment these are 2 ways to print the first 100 odd numbers set my_list = list set i = 0 while length my_list < 100 begin if i % 2 != 0 begin append my_list i set i = i + 1 end else begin set i = i + 1 end end print length my_list print my_list set list2 = list for i in range 1 200 2 begin set list2 = list2 + list i ...
# these are 2 ways to print the first 100 odd numbers my_list = [] i = 0 while len(my_list) < 100: if (i % 2) != 0: my_list.append(i) i += 1 else: i += 1 print(len(my_list)) print(my_list) list2 = [] for i in range(1, 200, 2): list2 += [i] print(list2) print(sum(my_list) == sum(...
Python
zaydzuhri_stack_edu_python
function returnOrderBook self limit=25 begin set orders = call get_order_book limit api=string market_history set r = dict set r at string GOLOS:GBG = orders set r at string GBG:GOLOS = dict string bids list ; string asks list for side in list string bids string asks begin for o in orders at side begin append r at s...
def returnOrderBook(self, limit=25): orders = self.ws.get_order_book(limit, api="market_history") r = {} r["GOLOS:GBG"] = orders r["GBG:GOLOS"] = {"bids": [], "asks": []} for side in ["bids", "asks"]: for o in orders[side]: r["GBG:GOLOS"][side].append(...
Python
nomic_cornstack_python_v1
async function reset self begin set index = 0 set target = none return end function
async def reset(self): self.index = 0 self.target = None return
Python
nomic_cornstack_python_v1
function failing_target infile output_dir region_id client_id begin comment pylint: disable=unused-argument if client_id == region_id begin call write_text string failed return false end call write_text string succeded return true end function
def failing_target(infile, output_dir, region_id, client_id): # pylint: disable=unused-argument if client_id == region_id: (output_dir / "touch").write_text("failed") return False (output_dir / "touch").write_text("succeded") return True
Python
nomic_cornstack_python_v1
function _augment_channelswap audio begin if shape at 0 == 2 and call uniform_ < 0.5 begin return call flip audio list 0 end else begin return audio end end function
def _augment_channelswap(audio: torch.Tensor) -> torch.Tensor: if audio.shape[0] == 2 and torch.tensor(1.0).uniform_() < 0.5: return torch.flip(audio, [0]) else: return audio
Python
nomic_cornstack_python_v1
function process_data_ransomware self log_folder begin comment only for syslog set labels = list 1 1 1 set tactic_names = list string Initial Access string Command and Control string Impact set technique_names = list string Exploit Public-Facing Application string Non-Application Layer Protocol string Data Encrypted se...
def process_data_ransomware(self, log_folder): labels = [1, 1, 1] # only for syslog tactic_names = ['Initial Access', 'Command and Control', 'Impact'] technique_names = ['Exploit Public-Facing Application', 'Non-Application Layer Protocol', 'Data Encrypted'] sub_technique_names = ['Expl...
Python
nomic_cornstack_python_v1
import inspect import sys function GetFunctionsFromPath filePath begin return get members modules at filePath isclass end function function GetFunctionsWithAttributeFromPath filePath attribute begin return list comprehension mem for mem in call GetFunctionsFromPath filePath if has attribute mem at 1 attribute end funct...
import inspect import sys def GetFunctionsFromPath(filePath): return inspect.getmembers(sys.modules[filePath], inspect.isclass) def GetFunctionsWithAttributeFromPath(filePath, attribute): return [mem for mem in GetFunctionsFromPath(filePath) if hasattr(mem[1], attribute)] def GetPublicFacingFunctionsFromP...
Python
zaydzuhri_stack_edu_python
function post_update_subscription self response begin return response end function
def post_update_subscription( self, response: pubsub.Subscription ) -> pubsub.Subscription: return response
Python
nomic_cornstack_python_v1
function send_receipt self begin set email_server = env at string ir.mail_server set email_sender = search list set ir_model_data = env at string ir.model.data if is_student == true begin set template_id = call get_object_reference string edsys_edu_fee string email_template_send_receipt at 1 set template_rec = call bro...
def send_receipt(self): email_server = self.env['ir.mail_server'] email_sender = email_server.sudo().search([]) ir_model_data = self.env['ir.model.data'] if self.partner_id.is_student == True: template_id = ir_model_data.get_object_reference('edsys_edu_fee', 'email_template_...
Python
nomic_cornstack_python_v1
function returnDifference num1 num2 begin set difference = num1 - num2 string returns the diffeence bewtween tow numbers return difference end function print call returnDifference 5 2
def returnDifference(num1, num2): difference = num1 - num2 """returns the diffeence bewtween tow numbers""" return difference print(returnDifference(5,2))
Python
zaydzuhri_stack_edu_python
function wait_for self timeout available=true error=none begin if not wait controller timeout=timeout condition=if expression available then available else not_available begin if error begin raise call NoSuchElementException if expression is instance error string_types then error else format string Element by selector ...
def wait_for(self, timeout, available=True, error=None): if not self.controller.wait(timeout=timeout, condition=self.check.available \ if available else self.check.not_available): if error: raise NoSuchElementException(error if isinstance(error, string_types) else \ ...
Python
nomic_cornstack_python_v1
comment the code below makes extensive use of the code from this blog post: comment https://gist.github.com/pprett/3813537 comment exports a classification tree object to relevant information in JSON function export_json decision_tree out_file=none feature_names=none begin from sklearn.tree import _tree function arr_to...
# the code below makes extensive use of the code from this blog post: # https://gist.github.com/pprett/3813537 # exports a classification tree object to relevant information in JSON def export_json(decision_tree, out_file=None, feature_names=None): from sklearn.tree import _tree def arr_to_py(arr): arr = arr.ravel(...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python2 from __future__ import print_function import psychopy.parallel import tornado.ioloop import tornado.web import tornado.websocket import tornado.gen import argparse import sys import time set parallelPort = none set args = none set webSocketHandlers = list class ParallelWebSocket extends W...
#!/usr/bin/env python2 from __future__ import print_function import psychopy.parallel import tornado.ioloop import tornado.web import tornado.websocket import tornado.gen import argparse import sys import time parallelPort = None args = None webSocketHandlers = [] class ParallelWebSocket(tornado.websocket.WebSocke...
Python
zaydzuhri_stack_edu_python
function peek peekorator n=0 default=call PeekoratorDefault begin try begin return call __peek__ n=n end except StopIteration begin if is instance default PeekoratorDefault begin comment StopIteration raise end else begin return default end end end function
def peek(peekorator, n=0, default=PeekoratorDefault()): try: return peekorator.__peek__(n=n) except StopIteration: if isinstance(default, PeekoratorDefault): raise # StopIteration else: return default
Python
nomic_cornstack_python_v1