code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function collect_variables self g_scope=string gen d_scope=string discrim begin string Assign `self.g_vars` to the parameters under scope `g_scope`, and same with `self.d_vars`. set g_vars = call get_collection TRAINABLE_VARIABLES g_scope assert g_vars set d_vars = call get_collection TRAINABLE_VARIABLES d_scope assert...
def collect_variables(self, g_scope='gen', d_scope='discrim'): """ Assign `self.g_vars` to the parameters under scope `g_scope`, and same with `self.d_vars`. """ self.g_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, g_scope) assert self.g_vars self.d_v...
Python
jtatman_500k
function dropEvent self event begin set source = call mimeData set shellwidget = call currentWidget if call hasText begin set qstr = call text if call __is_python_script qstr begin start self qstr end else if shellwidget begin call insert_text qstr end end else if call hasUrls begin set pathlist = call mimedata2url sou...
def dropEvent(self, event): source = event.mimeData() shellwidget = self.tabwidget.currentWidget() if source.hasText(): qstr = source.text() if self.__is_python_script(qstr): self.start(qstr) elif shellwidget: shellwidget.shell....
Python
nomic_cornstack_python_v1
import threading import time function cat param begin for i in range 5 begin print string i + string cat + param sleep 1 end end function function kitten begin sleep 0.5 for i in range 5 begin print string i + string kitten sleep 1 end end function set t1 = thread target=cat kwargs=dict string param x set t2 = thread t...
import threading import time def cat(param): for i in range(5): print(str(i) + "cat" + param) time.sleep(1) def kitten(): time.sleep(.5) for i in range(5): print(str(i) + "kitten") time.sleep(1) t1 = threading.Thread(target=cat,kwargs={"param":x}) t2 = threading.Thread(tar...
Python
zaydzuhri_stack_edu_python
function _update_cache self cset begin comment If this changeset is already in the cache, remove it try begin remove _lru_cache cset end except ValueError begin pass end comment Add the changeset at the end if length _lru_cache >= _LRU_CACHE_SIZE begin del _lru_cache at 0 end append _lru_cache cset end function
def _update_cache(self, cset): # If this changeset is already in the cache, remove it try: self._lru_cache.remove(cset) except ValueError: pass # Add the changeset at the end if len(self._lru_cache) >= Repository._LRU_CACHE_SIZE: del self._lru...
Python
nomic_cornstack_python_v1
function is_selection cfg begin if LIBRARIES in list keys cfg begin return true end else begin return false end end function
def is_selection(cfg): if LIBRARIES in list(cfg.keys()): return True else: return False
Python
nomic_cornstack_python_v1
comment Methods vs Functions comment Built-in Functions list print max min input comment User Defined Functions function some_function begin pass end function call some_function comment Methods print capitalize string helloo
# Methods vs Functions # Built-in Functions list() print() max() min() input() # User Defined Functions def some_function(): pass some_function() # Methods print('helloo'.capitalize())
Python
zaydzuhri_stack_edu_python
comment code:utf-8 comment 面向对象的基础 : 类(class)和实例(Instance) comment 类;class comment 类:初始化、基本数据、方法 class Student extends object begin comment 类属性 set base = string init function __init__ self name score begin comment 访问限制 set __name = name comment 特俗变量 set _score = score end function function get_score self begin return ...
# code:utf-8 # 面向对象的基础 : 类(class)和实例(Instance) # 类;class # 类:初始化、基本数据、方法 class Student(object): base ='init' # 类属性 def __init__(self,name,score): self.__name = name # 访问限制 self._score = score # 特俗变量 def get_score(self): return self._score student = Student('ccy',45) print(student....
Python
zaydzuhri_stack_edu_python
import webbrowser import time set total_breaks = 3 set breaks = 0
import webbrowser import time total_breaks = 3 breaks = 0
Python
zaydzuhri_stack_edu_python
function get_object cls name key=string [] begin set tid = call getpid set default _instances tid dict set default _instances at tid name dict return get _instances at tid at name key none end function
def get_object(cls, name: str, key: str = "[]") -> Optional[T]: tid = os.getpid() cls._instances.setdefault(tid, {}) cls._instances[tid].setdefault(name, {}) return cls._instances[tid][name].get(key, None)
Python
nomic_cornstack_python_v1
import random import time comment додаткове завдання: генерувати а в діапазоні (1..50),вивести час виконання програми set start = time set a0 = random integer 1 50 set a1 = random integer 1 50 set a2 = random integer 1 50 set a3 = random integer 1 50 set X1 = list comprehension call randrange 1 21 1 for i in range 8 se...
import random import time #додаткове завдання: генерувати а в діапазоні (1..50),вивести час виконання програми start = time.time() a0 = (random.randint(1,50)) a1 = (random.randint(1,50)) a2 = (random.randint(1,50)) a3 = (random.randint(1,50)) X1 = [random.randrange(1,21,1) for i in range(8)] X2 = [random.randrange(1,21...
Python
zaydzuhri_stack_edu_python
import re set word = input if starts with word string m == ends with word string e begin print string Match end else begin print string No match end comment soleved comment if True and False: comment print ('Match') comment else: comment print()
import re word = input() if word.startswith("m") == word.endswith("e"): print("Match") else: print("No match") #soleved # if True and False: # print ('Match') # else: # print()
Python
zaydzuhri_stack_edu_python
function test_json_output_for_macros self begin set test_project_macros = join path test_workspaces at string NORMAL string test_files string macros set extract_cmd = list string CodeChecker string parse string -e string json test_project_macros set tuple out _ result = call call_command extract_cmd cwd=test_dir env=en...
def test_json_output_for_macros(self): test_project_macros = os.path.join(self.test_workspaces['NORMAL'], "test_files", "macros") extract_cmd = ['CodeChecker', 'parse', "-e", "json", test_project_macros] out, _, result = call_co...
Python
nomic_cornstack_python_v1
function solve begin set n = integer call raw_input if n == 0 begin return string INSOMNIA end set d = dict set t = 0 while length d < 10 begin set t = t + n set dig = list comprehension integer x for x in string t for x in dig begin if call has_key x begin set d at x = d at x + 1 end else begin set d at x = 1 end end...
def solve(): n = int(raw_input()) if n == 0: return 'INSOMNIA' d = {} t = 0 while len(d) < 10: t += n dig = [int(x) for x in str(t)] for x in dig: if d.has_key(x): d[x] += 1 else: d[x] = 1 return t def ...
Python
zaydzuhri_stack_edu_python
import tensorflow as tf call enable_eager_execution import numpy as np import os import matplotlib.pyplot as plt comment ------- Checkpoint paths for all authors ---------- # set path_caesar = string ./training_data/training_data_caesar set path_petronius = string ./training_data/training_data_petronius set path_ovid =...
import tensorflow as tf tf.enable_eager_execution() import numpy as np import os import matplotlib.pyplot as plt # ------- Checkpoint paths for all authors ---------- # path_caesar = './training_data/training_data_caesar' path_petronius = './training_data/training_data_petronius' path_ovid = './training_d...
Python
zaydzuhri_stack_edu_python
import random function gen_random_points n begin string generate n random linearly seperable points set r = random set points = list set count = 0 while count < n begin set tuple x y = tuple random integer 0 99 random integer 0 99 if 100 - x > y + 1 begin append points tuple tuple x y - 1 set count = count + 1 end els...
import random def gen_random_points(n): """generate n random linearly seperable points""" r = random.Random() points = [] count = 0 while count < n: x, y = (r.randint(0,99), r.randint(0,99)) if 100 - x > y + 1: points.append(((x,y),-1)) count += 1 eli...
Python
zaydzuhri_stack_edu_python
function check self id begin try begin call authorize set bot_id = call get_me at string id return if expression call get_chat_member chat_id=id user_id=bot_id at string can_post_messages then true else false end except Unauthorized begin call authorize set bot_id = call get_me at string id return if expression call ge...
def check(self, id): try: self.authorize() bot_id = self.bot.get_me()['id'] return True if self.bot.get_chat_member(chat_id=id, user_id=bot_id)['can_post_messages'] else False except telegram.error.Unauthorized: self.authorize() bot_id = self.b...
Python
nomic_cornstack_python_v1
import turtle set screen = call getscreen set ted = call Turtle call forward 100 call right 90 call forward 100 call right 90 call forward 100 call right 90 call forward 100
import turtle screen = turtle.getscreen() ted = turtle.Turtle() ted.forward(100) ted.right(90) ted.forward(100) ted.right(90) ted.forward(100) ted.right(90) ted.forward(100)
Python
zaydzuhri_stack_edu_python
from sys import argv from os.path import exists set tuple script from_file to_file = argv print string Copying from %s to %s % tuple from_file to_file set input_file = open from_file set indata = read input_file print string The input file is %d bytes long % length indata print string Does the output file exist? %r % e...
from sys import argv from os.path import exists script,from_file,to_file = argv print("Copying from %s to %s" %(from_file,to_file)) input_file = open(from_file) indata = input_file.read() print("The input file is %d bytes long" %(len(indata))) print("Does the output file exist? %r" %(exists(to_file))) print("Ready,...
Python
zaydzuhri_stack_edu_python
function merge_sort arr begin set n = length arr if n < 2 begin return arr end set stack = list for i in range n begin append stack list arr at i end while length stack > 1 begin set pair1 = pop stack set pair2 = pop stack set merged = merge pair1 pair2 append stack merged end return stack at 0 end function function m...
def merge_sort(arr): n = len(arr) if n < 2: return arr stack = [] for i in range(n): stack.append([arr[i]]) while len(stack) > 1: pair1 = stack.pop() pair2 = stack.pop() merged = merge(pair1, pair2) stack.append(merged) return stack[0] def mer...
Python
jtatman_500k
function safe_location self location_name geom max_distance=200 begin set location = call geocode location_name if location is none begin return none end set location_point = location at string point if not location_point begin return none end set srid = 4326 set tuple is_close distance = call locations_are_close locat...
def safe_location(self, location_name, geom, max_distance=200): location = self.geocode(location_name) if location is None: return None location_point = location['point'] if not location_point: return None location_point.srid = 4326 is_clos...
Python
nomic_cornstack_python_v1
string Created on Sep 27, 2016 @author: tomd import matplotlib.pyplot as plt from sklearn.metrics.ranking import roc_curve function plot_roc_curve y_true y_pred begin set tuple a b _thresholds = call roc_curve y_true y_pred plot a b c=string green label=string model 1 legend loc=4 show end function
''' Created on Sep 27, 2016 @author: tomd ''' import matplotlib.pyplot as plt from sklearn.metrics.ranking import roc_curve def plot_roc_curve(y_true,y_pred): a,b,_thresholds = roc_curve(y_true,y_pred) plt.plot(a,b,c="green",label="model 1") plt.legend(loc=4) plt.show()
Python
zaydzuhri_stack_edu_python
from xlrd import open_workbook set wb = call open_workbook string email_list.xls set ws = call sheet_by_index 0 set receList = list for i in range nrows begin for j in range ncols begin if call cell_value i j == string Email begin print call cell_value 0 j print i j set i = 1 while i < nrows begin print call cell_valu...
from xlrd import open_workbook wb = open_workbook('email_list.xls') ws = wb.sheet_by_index(0) receList = [] for i in range(ws.nrows): for j in range(ws.ncols): if ws.cell_value(i, j) == 'Email': print(ws.cell_value(0, j)) print(i, j) i = 1 while i < ws.nr...
Python
zaydzuhri_stack_edu_python
function on_spread_pos self begin set spread_pos = call get_spread_pos call put_event end function
def on_spread_pos(self): self.spread_pos = self.get_spread_pos() self.put_event()
Python
nomic_cornstack_python_v1
comment -*- coding:utf8 -*- set __author__ = string admin import logging import threading import time comment 等待守护进程完成要用join,防止无限阻塞用join(sec) call basicConfig level=DEBUG format=string [%(levelname)s] %(message)s function daemon begin debug string Starting sleep 3 comment 没有输出 因为非守护进程 和主程序已经退出 debug string Exting end f...
#-*- coding:utf8 -*- __author__ = 'admin' import logging import threading import time #等待守护进程完成要用join,防止无限阻塞用join(sec) logging.basicConfig( level=logging.DEBUG, format='[%(levelname)s] %(message)s' ) def daemon(): logging.debug('Starting') time.sleep(3) logging.debug('Exting')#没有输出 因为非守护进程 和主程序已经退...
Python
zaydzuhri_stack_edu_python
from PIL import Image from torch.utils.data import DataLoader import pandas as pd import numpy as np from keras.utils import to_categorical from torchvision.models.resnet import ResNet , BasicBlock from tqdm import tqdm_notebook as tqdm from sklearn.metrics import precision_score , recall_score , f1_score , accuracy_sc...
from PIL import Image from torch.utils.data import DataLoader import pandas as pd import numpy as np from keras.utils import to_categorical from torchvision.models.resnet import ResNet, BasicBlock from tqdm import tqdm_notebook as tqdm from sklearn.metrics import precision_score, recall_score, f1_score, accuracy_score ...
Python
zaydzuhri_stack_edu_python
function parameters self begin return get pulumi self string parameters end function
def parameters(self) -> Optional[Mapping[str, 'outputs.ParameterSpecificationResponse']]: return pulumi.get(self, "parameters")
Python
nomic_cornstack_python_v1
function chain self visitor begin set tail = list visitor_iterator at - 1 set _next = visitor return self end function
def chain(self: _ExtT, visitor: ExternalTraversal) -> _ExtT: tail = list(self.visitor_iterator)[-1] tail._next = visitor return self
Python
nomic_cornstack_python_v1
import unittest from application import Tenis class TestTenis extends TestCase begin function test_scorePlayer1_shouldReturnPlayer1AddedScore self begin set tenis = call Tenis call scorePlayer1 assert equal call getScorePlayer1 string 15 assert equal call getScorePlayer2 string 0 end function function test_scorePlayer1...
import unittest from application import Tenis class TestTenis(unittest.TestCase): def test_scorePlayer1_shouldReturnPlayer1AddedScore(self): tenis = Tenis() tenis.scorePlayer1() self.assertEqual(tenis.getScorePlayer1(), "15") self.assertEqual(tenis.getScorePlayer2(), "0") def test_scorePlayer1_shouldRe...
Python
zaydzuhri_stack_edu_python
comment Trabalho 1 de Segurança Computacional comment Alunos: Guilherme Braga (17/0162290) e Gabriel Moretto (15/0154917) comment UnB, 2021/01 comment Imports comment ------------------------------------------------ from gerador_chave import keystream_gerador comment ------------------------------------------------ fun...
# # Trabalho 1 de Segurança Computacional # Alunos: Guilherme Braga (17/0162290) e Gabriel Moretto (15/0154917) # UnB, 2021/01 # # Imports # ------------------------------------------------ from gerador_chave import keystream_gerador # ------------------------------------------------ def cifrador(msg, chave): # ...
Python
zaydzuhri_stack_edu_python
comment def vowels(string): comment vowels = ['a', 'e', 'i', 'o', 'u'] comment # string ='hApPyHalLOweEn!' comment numVowels = 0 comment i = 0 comment while i < len(string): comment if (string[i].lower() in vowels): comment numVowels += 1 comment i += 1 comment return numVowels comment assert vowels("apPyHalLoween!") =...
# def vowels(string): # vowels = ['a', 'e', 'i', 'o', 'u'] # # string ='hApPyHalLOweEn!' # numVowels = 0 # i = 0 # # while i < len(string): # # if (string[i].lower() in vowels): # numVowels += 1 # # i += 1 # # return numVowels # # assert vowels("apPyHalLoween!") == 5 # assert vowels("hApPyHalLOweEn!") == 5...
Python
zaydzuhri_stack_edu_python
function subnetpool_create request name prefixes **kwargs begin debug string subnetpool_create(): name=%(name)s, prefixes=%(prefixes)s, kwargs=%(kwargs)s dict string name name ; string prefixes prefixes ; string kwargs kwargs set body = dict string subnetpool dict string name name ; string prefixes prefixes if string t...
def subnetpool_create(request, name, prefixes, **kwargs): LOG.debug("subnetpool_create(): name=%(name)s, prefixes=%(prefixes)s, " "kwargs=%(kwargs)s", {'name': name, 'prefixes': prefixes, 'kwargs': kwargs}) body = {'subnetpool': {'name': name, ...
Python
nomic_cornstack_python_v1
function mitigate_endpoint_status endpoint_status_list user **kwargs begin for endpoint_status in endpoint_status_list begin comment Only mitigate endpoints that are actually active if not mitigated begin debug string Re-import: mitigating endpoint %s that is no longer present string endpoint set mitigated_by = user se...
def mitigate_endpoint_status(endpoint_status_list, user, **kwargs): for endpoint_status in endpoint_status_list: # Only mitigate endpoints that are actually active if not endpoint_status.mitigated: logger.debug("Re-import: mitigating endpoint %s that is no longer present", str(endpoint_s...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 -u import sys , re , math from img2c import * function bmp2c bmp img dest=stdout invert=false h=none w=none begin comment Assume that the BITMAPINFOHEADER is used set offset = call bytes_to_int bmp 10 set width = call bytes_to_int bmp 18 set height = absolute call bytes_to_int bmp 22 comment F...
#!/usr/bin/python3 -u import sys, re, math from img2c import * def bmp2c(bmp, img, dest = sys.stdout, invert = False, h = None, w = None): # Assume that the BITMAPINFOHEADER is used offset = bytes_to_int(bmp, 10) width = bytes_to_int(bmp, 18) height = abs(bytes_to_int(bmp, 22)) # Form 2D...
Python
zaydzuhri_stack_edu_python
function can_move_right self begin return _position < length _list - 1 end function
def can_move_right(self): return self._position < len(self._list) - 1
Python
nomic_cornstack_python_v1
comment with @staticmethod class Fraction begin function __init__ self nr dr=1 begin set nr = nr set dr = dr if dr < 0 begin set nr = nr * - 1 set dr = dr * - 1 end end function function show self begin print string nr + string / + string dr end function function multiply self other begin if is instance other int begin...
# with @staticmethod class Fraction: def __init__(self, nr, dr=1): self.nr = nr self.dr = dr if self.dr < 0: self.nr *= -1 self.dr *= -1 def show(self): print(str(self.nr) + '/' + str(self.dr)) def multiply(self, other): ...
Python
zaydzuhri_stack_edu_python
function is_differential self mother daughter begin comment info(10, mother, daughter, " asking for redist") comment if not self.supports_redistributions: comment info(10, mother, daughter, " model doesn't support redist") comment return False if daughter <= redist_threshold_ID or tuple mother daughter in incl_diff_idc...
def is_differential(self, mother, daughter): # info(10, mother, daughter, " asking for redist") # if not self.supports_redistributions: # info(10, mother, daughter, " model doesn't support redist") # return False if (daughter <= config.redist_threshold_ID ...
Python
nomic_cornstack_python_v1
import yaml import json with open string app.yaml as fh begin set struct = load yaml fh end print struct print type struct comment help(json.dumps) comment let us dump struct to a string as struct as a dict isn't all that convenient to read. set str1 = dumps struct indent=4 separators=tuple string , string : print str1...
import yaml import json with open('app.yaml') as fh: struct = yaml.load(fh) print(struct) print(type(struct)) # help(json.dumps) # let us dump struct to a string as struct as a dict isn't all that convenient to read. str1 = json.dumps(struct, indent=4, separators=(',', ':')) print(str1) with open('app1.html', ...
Python
zaydzuhri_stack_edu_python
comment Script must check string with brackets on correctness. comment There are 3 different ways(functions) for checking. comment If string is correct - function returns 'Success' comment else position with symbol which breaks sequence. from typing import Union function quick_check s begin set open_brackets = string (...
# Script must check string with brackets on correctness. # There are 3 different ways(functions) for checking. # If string is correct - function returns 'Success' # else position with symbol which breaks sequence. from typing import Union def quick_check(s: str) -> Union[int, str]: open_brackets = '([{' clos...
Python
zaydzuhri_stack_edu_python
for index in range 40 begin set f = open string data + string index + string .txt string w encoding=string utf8 for i in data at slice segment * index : segment * index + 1 : begin write f i end close f end
for index in range(40): f=open('data'+str(index)+'.txt','w',encoding='utf8') for i in data[segment*index:segment*(index+1)]: f.write(i) f.close()
Python
zaydzuhri_stack_edu_python
function generate_sent self begin set n = _n set sent = list comment this enforces to generate complete phrases comment otherwise we should start without the START comment token. I mean: with p_tokens = [] set p_tokens = tuple list START * n - 1 while true begin set token = call generate_token tuple p_tokens set sent ...
def generate_sent(self): n = self._n sent = [] # this enforces to generate complete phrases # otherwise we should start without the START # token. I mean: with p_tokens = [] p_tokens = tuple([START] * (n-1)) while True: token = self.generate_token(t...
Python
nomic_cornstack_python_v1
import os import shutil set KeyWordDic = dict string 图像增强 list string Inpainting string Denoising string Restoration string Resolution string Demosaicing ; string 风格迁移 list string Style string Translation string GAN string Face string Editing string Attribution ; string 目标检测 list string Detection string Stage string An...
import os import shutil KeyWordDic = { '图像增强': ['Inpainting','Denoising','Restoration','Resolution','Demosaicing'], '风格迁移': ['Style','Translation','GAN','Face','Editing','Attribution'], '目标检测': ['Detection','Stage','Anchor','Object','Detecor'], '架构搜索': ['Prune','Compress','NAS','Architecture'], '元学...
Python
zaydzuhri_stack_edu_python
function define_components m begin comment fixed cost (per mmBtu/year of capacity) of having each tier in service comment during each period note: this must be zero if a tier has unlimited comment capacity, to avoid having infinite cost set rfm_supply_tier_fixed_cost = call Param RFM_SUPPLY_TIERS default=0.0 within=Non...
def define_components(m): # fixed cost (per mmBtu/year of capacity) of having each tier in service # during each period note: this must be zero if a tier has unlimited # capacity, to avoid having infinite cost m.rfm_supply_tier_fixed_cost = Param( m.RFM_SUPPLY_TIERS, default=0.0, ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python from setuptools import setup with open string README.md string r as fh begin set long_description = read fh end setup name=string Taerbit version=string 0.0.1 author=string Finn Torbet author_email=string finnt26@gmail.com description=string Package to process images through interpretabilit...
#!/usr/bin/env python from setuptools import setup with open("README.md", "r") as fh: long_description = fh.read() setup( name="Taerbit", version="0.0.1", author="Finn Torbet", author_email="finnt26@gmail.com", description="Package to process images through interpretability methods and then m...
Python
jtatman_500k
function ben_s self begin return string beneficiaires or string ∞ end function
def ben_s(self) -> str: return str(self.beneficiaires or "∞")
Python
nomic_cornstack_python_v1
function gagne self begin if partie_en_cours begin for i in range taille at 1 begin for j in range taille at 0 begin if matriceGraph at i + 1 at j + 1 == string and matrice at i at j != - 1 begin return 0 end end end comment A ce point, la partie est gagnée set partie_en_cours = false call play set fenetre_gagne = cal...
def gagne(self): if self.partie_en_cours: for i in range(self.taille[1]): for j in range(self.taille[0]): if self.matriceGraph[i+1][j+1] == " " and self.matrice[i][j] != -1: return 0 #A ce point, la partie est gagnée ...
Python
nomic_cornstack_python_v1
import csv from collections import defaultdict from collections import namedtuple import matplotlib.pyplot as plt from collections import defaultdict set Point = named tuple string Point list string system string large string delay_ms string failure function load filename points keys begin with open filename string r a...
import csv from collections import defaultdict from collections import namedtuple import matplotlib.pyplot as plt from collections import defaultdict Point = namedtuple("Point", ["system", "large", "delay_ms", "failure"]) def load(filename, points, keys): with open(filename, 'r') as f: r = csv.DictReader...
Python
zaydzuhri_stack_edu_python
function paraMatch para1 para2 begin set length = length para1 if length != length para2 begin return false end comment If two parameter's type is equal then comment these two parameter is equal for i in range length begin if para1 at i at 1 != para2 at i at 1 begin return false end end return true end function
def paraMatch(para1: opParameter, para2: opParameter) -> bool: length = len(para1) if length != len(para2): return False # If two parameter's type is equal then # these two parameter is equal for i in range(length): if para1[i][1] != para2[i][1]: return False return...
Python
nomic_cornstack_python_v1
from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.svm import SVC from sklearn.model_selection import cross_val_score function test_raw_predictor predictor begin for item in predictor begin set model = item set cv_scores = cross val score model X_train y...
from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.svm import SVC from sklearn.model_selection import cross_val_score def test_raw_predictor(predictor): for item in predictor: model = item cv_scores = cross_val_score(model, X_train, ...
Python
zaydzuhri_stack_edu_python
function decrypt_with_private_key data private_key begin return call _pkcs1_unpad call decrypt data end function
def decrypt_with_private_key(data, private_key): return _pkcs1_unpad(private_key.decrypt(data))
Python
nomic_cornstack_python_v1
import pickle from typing import Dict function load_pickle pickle_file begin string Loads a skeleton dictionary from a saved skeleton .pickle file with open pickle_file string rb as handle begin set data = load pickle handle end return data end function
import pickle from typing import Dict def load_pickle(pickle_file) -> Dict: """ Loads a skeleton dictionary from a saved skeleton .pickle file """ with open(pickle_file, 'rb') as handle: data = pickle.load(handle) return(data)
Python
zaydzuhri_stack_edu_python
from funktioner import difstat , listval , slowprint from random import random , randint from copy import copy , deepcopy from klasser import EngangsForemal import forvandling as fv import fiender as fi comment ------------------------------------------------------------------------------ comment KLASSER class Effekt b...
from funktioner import difstat, listval, slowprint from random import random, randint from copy import copy, deepcopy from klasser import EngangsForemal import forvandling as fv import fiender as fi #------------------------------------------------------------------------------ #KLASSER class Effekt: def __init_...
Python
zaydzuhri_stack_edu_python
function fft_lowpass nelevation low_bound high_bound begin if length nelevation % 2 begin set result = call rfft nelevation length nelevation end else begin set result = call rfft nelevation end set freq = call fftfreq length nelevation at slice : length nelevation / 2 : set factor = ones like result set factor at fr...
def fft_lowpass(nelevation, low_bound, high_bound): if len(nelevation) % 2: result = fft.rfft(nelevation, len(nelevation)) else: result = fft.rfft(nelevation) freq = fft.fftfreq(len(nelevation))[:len(nelevation)/2] factor = np.ones_like(result) factor[freq > low_bound] = 0.0 sl ...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import os , time , re import urlparse , random , getpass from selenium import webdriver from selenium.webdriver.common.keys import Keys from bs4 import BeautifulSoup function getEmail begin set email_verrified = false while not email_verrified begin set email = call raw_input string Ceviu ...
# -*- coding: utf-8 -*- import os, time, re import urlparse, random, getpass from selenium import webdriver from selenium.webdriver.common.keys import Keys from bs4 import BeautifulSoup def getEmail(): email_verrified = False while not email_verrified: email = raw_input('Ceviu Email:') if re....
Python
zaydzuhri_stack_edu_python
function jac_deproject_rad self u v projection=none begin if projection not in _valid_projections begin raise call ValueError string Unknown projection: %s % projection end return call _jac_deproject u v projection end function
def jac_deproject_rad(self, u, v, projection=None): if projection not in CelestialCoord._valid_projections: raise ValueError('Unknown projection: %s'%projection) return self._jac_deproject(u, v, projection)
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib.pyplot as plt set xsize = 100.0 set dx = 1.0 set xpt = linear space 0 xsize integer xsize / dx + 1 print xpt
import numpy as np import matplotlib.pyplot as plt # xsize=100. dx=1. xpt=np.linspace(0,xsize,int(xsize/dx)+1) print(xpt)
Python
zaydzuhri_stack_edu_python
function create_user self email role password=none begin if not email begin raise call ValueError call _ string Users Must Have an email address end set user = model email=call normalize_email email role=role call set_password password save using=_db return user end function
def create_user(self, email, role, password=None): if not email: raise ValueError(_('Users Must Have an email address')) user = self.model( email=self.normalize_email(email), role=role ) user.set_password(password) user.save(using=self._db) return...
Python
nomic_cornstack_python_v1
function subscribe self publication name dbname=none username=none **params begin comment yapf: disable return call Subscription name=name node=self publication=publication dbname=dbname username=username keyword params end function comment yapf: enable
def subscribe(self, publication, name, dbname=None, username=None, **params): # yapf: disable return Subscription(name=name, node=self, publication=publication, dbname=dbname, username=u...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Thu Jul 8 13:57:24 2021 @author: Omen 15 import random set P = list for i in range 0 10 begin append P list 0 * 10 end comment Se puede evitar líneas 11 a 13, simplemente poniendo un 1 en lugar de 0 en línea 9. for f in range 0 10 begin for c in range 0 10 begin set P at...
# -*- coding: utf-8 -*- """ Created on Thu Jul 8 13:57:24 2021 @author: Omen 15 """ import random P = [] for i in range(0,10): P.append( [0]*10 ) for f in range (0, 10): # Se puede evitar líneas 11 a 13, simplemente poniendo un 1 en lugar de 0 en línea 9. for c in range (0, 10): P[f][c] = 1 pri...
Python
zaydzuhri_stack_edu_python
function qc sexmodel sexcutoff path begin info format string Running quality control on project based on path ''{}'' path set path_items = call parse_batch_file_path path set annotator = call get_processed_libraries qc=true end function
def qc(sexmodel, sexcutoff, path): logger.info("Running quality control on project based on path ''{}''" .format(path)) path_items = bripipetools.parsing.parse_batch_file_path(path) annotator = bripipetools.annotation.WorkflowBatchAnnotator( workflowbatch_file=path, pipeline_...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python2 comment -*- coding: utf-8 -*- import formatter import htmllib import md5 import subprocess import sys import urllib
#!/usr/bin/python2 # -*- coding: utf-8 -*- import formatter import htmllib import md5 import subprocess import sys import urllib
Python
zaydzuhri_stack_edu_python
function edit_trace trace_id begin if method == string POST begin update filter id == trace_id dict string name form at string name ; string comment form at string comment ; string type form at string type ; string geom string SRID=4326; + form at string wkt_geom commit session call flash string Your trace has been suc...
def edit_trace(trace_id): if request.method == 'POST': db.session.query(Traces).filter(Traces.id == trace_id).update( {'name' : request.form['name'], 'comment': request.form['comment'], 'type' : request.form['t...
Python
nomic_cornstack_python_v1
function adapt_to_window_size self allocated_width begin set can_expand = allocated_width > _limit_size set incoherent = can_expand == _is_narrow if incoherent begin call set_compact not _is_narrow end end function
def adapt_to_window_size(self, allocated_width): can_expand = (allocated_width > self._limit_size) incoherent = (can_expand == self._is_narrow) if incoherent: self.set_compact(not self._is_narrow)
Python
nomic_cornstack_python_v1
function insert_or_update table defaults **where begin set insertion = dict none defaults ; none where set fields = join string , map _quote_key keys insertion set values = join string , list comprehension call _quote v for v in values insertion set updates = call _dict2str defaults set tmpl = string insert into %s (%s...
def insert_or_update(table, defaults, **where): insertion = {**defaults, **where} fields = ",".join(map(_quote_key, insertion.keys())) values = ",".join([_quote(v) for v in insertion.values()]) updates = _dict2str(defaults) tmpl = "insert into %s (%s) values (%s) on duplicate key update %s" stmt...
Python
nomic_cornstack_python_v1
function get_meta_content self doc metaName begin set meta = call css_select doc metaName set content = none if meta is not none and length meta > 0 begin set content = call getAttribute meta at 0 string content end if content begin return strip content end return string end function
def get_meta_content(self, doc, metaName): meta = self.parser.css_select(doc, metaName) content = None if meta is not None and len(meta) > 0: content = self.parser.getAttribute(meta[0], 'content') if content: return content.strip() return ''
Python
nomic_cornstack_python_v1
import numpy as np import pandas as pd import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import matplotlib.patches as mpatches comment Lab Version function plot_scatter data title begin set fig = figure set ax = call Axes3D fig set x = data at tuple slice : : 0 set y = data at tuple slice : :...
import numpy as np import pandas as pd import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import matplotlib.patches as mpatches # Lab Version def plot_scatter(data, title): fig = plt.figure() ax = Axes3D(fig) x = data[:, 0] y = data[:, 1] z = data[:, 2] t...
Python
zaydzuhri_stack_edu_python
function google_api begin return GOOGLE_MAPS_API_KEY end function
def google_api(): return GOOGLE_MAPS_API_KEY
Python
nomic_cornstack_python_v1
function date2str datetime_object begin if datetime_object is none begin return string None end return string format time datetime_object string %Y-%m-%dT%H:%M:%S.%f at slice 0 : - 3 : end function
def date2str(datetime_object): if datetime_object is None: return 'None' return datetime_object.strftime('%Y-%m-%dT%H:%M:%S.%f')[0:-3]
Python
nomic_cornstack_python_v1
comment RSS Feed Filter import feedparser import string import time import threading from project_util import translate_html from mtTkinter import * from datetime import datetime import pytz from abc import ABC , abstractmethod comment ====================== comment Code for retrieving and parsing comment Google and Ya...
# RSS Feed Filter import feedparser import string import time import threading from project_util import translate_html from mtTkinter import * from datetime import datetime import pytz from abc import ABC, abstractmethod #====================== # Code for retrieving and parsing # Google and Yahoo News feeds # Do not ...
Python
zaydzuhri_stack_edu_python
from _collections import deque set x = 0 function sum_recursive list begin set tuple x *tail = list print x string ***** tail if length tail > 0 begin return x + call sum_recursive tail end else begin return x end end function set lista = list 10 20 comment print(sum_recursive(lista)) comment print(sum_recursive([10,20...
from _collections import deque x = 0 def sum_recursive(list): x, *tail = list print(x, '*****',tail) if len(tail) > 0: return x + sum_recursive(tail) else: return x lista = [10,20] # print(sum_recursive(lista)) # # print(sum_recursive([10,20])) listb = [int(10),str('abc')] print(list...
Python
zaydzuhri_stack_edu_python
import functools from flask import jsonify , request string Constant value representing the endpoint. This has to be written with two uppercase letter, eg. API Gateway -> AG) comment Reactions service identifier set EP_CODE = string AR string Dictionary with all errors related to this service and the corresponding erro...
import functools from flask import jsonify, request ''' Constant value representing the endpoint. This has to be written with two uppercase letter, eg. API Gateway -> AG) ''' EP_CODE = 'AR' # Reactions service identifier ''' Dictionary with all errors related to this service and the corresponding error messages and ...
Python
zaydzuhri_stack_edu_python
import MapReduce import sys string See Problem statement #4 in README set mr = call MapReduce comment ============================= comment Do not modify above this line function mapper record begin set person_name = record at 0 set frnd_name = record at 1 if person_name > frnd_name begin call emit_intermediate tuple p...
import MapReduce import sys """ See Problem statement #4 in README """ mr = MapReduce.MapReduce() # ============================= # Do not modify above this line def mapper(record): person_name = record[0] frnd_name = record[1] if (person_name > frnd_name): mr.emit_intermediate((person_name, frnd_...
Python
zaydzuhri_stack_edu_python
function __init__ self begin set elevations = list end function
def __init__(self): self.elevations = []
Python
nomic_cornstack_python_v1
set numlist = list 2 4 5 6 7 set x = integer input string enter the number: if x not in numlist begin print string member not found end else begin print string member found end
numlist=[2,4,5,6,7] x=int(input("enter the number: ")) if(x not in numlist): print("member not found") else: print("member found")
Python
zaydzuhri_stack_edu_python
comment check whether the given year is leap or not. if year is leap print'LEAP YEAR' comment esle print"COMMON YEAR". comment Hint: a year is leap year if its number is exactly divisible by 4 and is not exactly divisible by 100 comment a year is always a leap year if its number is exactly divisible by 400 set year = i...
#check whether the given year is leap or not. if year is leap print'LEAP YEAR' #esle print"COMMON YEAR". # Hint: a year is leap year if its number is exactly divisible by 4 and is not exactly divisible by 100 # a year is always a leap year if its number is exactly divisible by 400 year= int(input('Enter the leap year:...
Python
zaydzuhri_stack_edu_python
function clean self begin if string password1 in cleaned_data and string password2 in cleaned_data begin if cleaned_data at string password1 != cleaned_data at string password2 begin raise call ValidationError string Passwords don't match. Please enter both fields again. end end return cleaned_data end function
def clean(self): if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data: if self.cleaned_data['password1'] != self.cleaned_data['password2']: raise forms.ValidationError("Passwords don't match. Please enter both fields again.") return self.cleaned_data
Python
nomic_cornstack_python_v1
function minimise self funct test_statistic begin comment Loop over all possible combinations of fit parameter values for tuple values indices in call _get_fit_par_values begin comment Call funct and pass array to it set tuple result penalty = call funct *values comment Check result is of correct form comment expecting...
def minimise(self, funct, test_statistic): # Loop over all possible combinations of fit parameter values for values, indices in self._get_fit_par_values(): # Call funct and pass array to it result, penalty = funct(*values) # Check result is of correct form ...
Python
nomic_cornstack_python_v1
function setLives self lives begin set _lives = lives end function
def setLives(self, lives): self._lives = lives
Python
nomic_cornstack_python_v1
import requests , bs4 from selenium import webdriver comment Getting the browser comment browser = webdriver.Firefox() comment Signin to linkedin comment browser.get('https://www.linkedin.com') comment usernameElem = browser.find_element_by_css_selector('input[name="session_key"]') comment usernameElem.send_keys('jayes...
import requests,bs4 from selenium import webdriver #Getting the browser #browser = webdriver.Firefox() #Signin to linkedin #browser.get('https://www.linkedin.com') #usernameElem = browser.find_element_by_css_selector('input[name="session_key"]') #usernameElem.send_keys('jayeshgar@gmail.com') #passwordElem = browser.f...
Python
zaydzuhri_stack_edu_python
comment self에 대해 이해하기전, class를 짚고 넘어가야한다. class는 각종 변수와 함수들을 묶어 하나의 객체로 만드는 것을 뜻한다. class Example begin comment class내의 함수를 메서드라 부른다. function set_info self name email addr begin set name = name set email = email set addr = addr end function end class comment Example()을 Example이라는 클래스의 인스턴스라 부름 comment 인스턴스가 메모리의 한 위치에...
#self에 대해 이해하기전, class를 짚고 넘어가야한다. class는 각종 변수와 함수들을 묶어 하나의 객체로 만드는 것을 뜻한다. class Example: def set_info(self, name, email, addr): #class내의 함수를 메서드라 부른다. self.name = name self.email = email self.addr = addr #Example()을 Example이라는 클래스의 인스턴스라 부름 card1 = Example() #인스턴스가 메모리의 한 위치에 생성되고, card1이라는 ...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt import numpy as np import itertools from sklearn.metrics import roc_curve , auc import pandas as pd comment This function prints and plots the confusion matrix. comment Normalization can be applied by setting `normalize=True`. function plot_confusion_matrix cm classes normalize=false tit...
import matplotlib.pyplot as plt import numpy as np import itertools from sklearn.metrics import roc_curve, auc import pandas as pd ################################################################### # This function prints and plots the confusion matrix. # Normalization can be applied by setting `normalize=True`. ####...
Python
zaydzuhri_stack_edu_python
function __init__ __self__ gradient_accumulation_steps=none learning_rate=none learning_rate_scheduler=none model_name=none number_of_epochs=none training_batch_size=none validation_batch_size=none warmup_ratio=none weight_decay=none begin if gradient_accumulation_steps is not none begin set __self__ string gradient_ac...
def __init__(__self__, *, gradient_accumulation_steps: Optional[int] = None, learning_rate: Optional[float] = None, learning_rate_scheduler: Optional[str] = None, model_name: Optional[str] = None, number_of_epochs: Optional[int] = None...
Python
nomic_cornstack_python_v1
function _compute_demographic_parity_tr self begin return selection_rate_a - selection_rate_b end function
def _compute_demographic_parity_tr(self): return self.selection_rate_a - self.selection_rate_b
Python
nomic_cornstack_python_v1
string Escreva um programa que ordene uma lista numérica com três elementos. set valor1 = integer input string Digite o valor1: set valor2 = integer input string Digite o valor1: set valor3 = integer input string Digite o valor1: set maior = 0 set menor = 0 set medio = 0 comment Caso 1 if valor3 >= valor2 and valor3 >=...
''' Escreva um programa que ordene uma lista numérica com três elementos. ''' valor1 = int(input("Digite o valor1: ")) valor2 = int(input("Digite o valor1: ")) valor3 = int(input("Digite o valor1: ")) maior = 0 menor = 0 medio = 0 # Caso 1 if valor3 >= valor2 and valor3 >= valor1: maior = valor3 if valor2 >=...
Python
zaydzuhri_stack_edu_python
string This computes the output of 2-layer Cross Validation for different LRM or classification models. It is based on algorithm 6, see 02450 course book. It also handles hyperparameters optimization and CV output relevant for statistical evaluation. Because of tehnical issues, the model that are being compared are nee...
""" This computes the output of 2-layer Cross Validation for different LRM or classification models. It is based on algorithm 6, see 02450 course book. It also handles hyperparameters optimization and CV output relevant for statistical evaluation. Because of tehnical issues, the model that are being compared are neede...
Python
zaydzuhri_stack_edu_python
function get_instrumental_variables self begin return instrumental_variables end function
def get_instrumental_variables(self): return self.instrumental_variables
Python
nomic_cornstack_python_v1
import json import math import statistics import sys from PyQt5 import QtCore from PyQt5.QtChart import QLineSeries from PyQt5.QtCore import QPointF , QLocale from PyQt5.QtCore import QSize from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QAction , QSlider , QLabel , QDoubleSpinBox , QMessageBox from PyQt5.QtWid...
import json import math import statistics import sys from PyQt5 import QtCore from PyQt5.QtChart import QLineSeries from PyQt5.QtCore import QPointF, QLocale from PyQt5.QtCore import QSize from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QAction, QSlider, QLabel, QDoubleSpinBox, QMessageBox from PyQt5.QtWidgets...
Python
zaydzuhri_stack_edu_python
function compute_resilience ugraph attack_order begin set resilience_list = list call largest_cc_size ugraph for node in attack_order begin comment remove node and edges for neigh in ugraph at node begin discard ugraph at neigh node end pop ugraph node append resilience_list call largest_cc_size ugraph end return resil...
def compute_resilience(ugraph, attack_order): resilience_list = [largest_cc_size(ugraph)] for node in attack_order: # remove node and edges for neigh in ugraph[node]: ugraph[neigh].discard(node) ugraph.pop(node) resilience_list.append(largest_cc_size(ugraph)) ...
Python
nomic_cornstack_python_v1
function add_without_plus a b begin set add_without_carry = a ? b while a or b begin set ca = if expression a then a else 0 set cb = if expression b then b else 0 if ca ? 1 ? cb ? 1 begin set carry = 1 end else begin set carry = 0 end set a = a ? 1 set b = b ? 1 end end function print call add_without_plus 3 5
def add_without_plus(a, b): add_without_carry = a ^ b while a or b: ca = a if a else 0 cb = b if b else 0 if (ca & 1) & (cb & 1): carry = 1 else: carry = 0 a >>= 1 b >>= 1 print(add_without_plus(3, 5))
Python
zaydzuhri_stack_edu_python
import string import sys from collections import deque call setrecursionlimit 10 ^ 9 set input = readline function getXYidx x y begin return x * 3 + y end function set startStr = string for _ in range 3 begin set startStr = startStr + replace right strip input string string end set idx = find startStr string 0 set st...
import string import sys from collections import deque sys.setrecursionlimit(10**9) input = sys.stdin.readline def getXYidx(x, y): return x * 3 + y startStr = "" for _ in range(3): startStr += input().rstrip().replace(" ", "") idx = startStr.find('0') startX = idx // 3 startY = idx % 3 history = set() hist...
Python
zaydzuhri_stack_edu_python
function is_gps_timestamp key begin return key in tuple string gps_timestamp end function
def is_gps_timestamp(key) -> bool: return key in ("gps_timestamp", )
Python
nomic_cornstack_python_v1
function substitution fname prefix begin if not ends with prefix string / begin set prefix = prefix + string / end set lines = list for line in read lines open fname begin append lines call fix_line line prefix end set out = open fname string w for line in lines begin write out line end close out end function
def substitution(fname,prefix): if not prefix.endswith("/"): prefix += "/" lines = [] for line in open(fname).readlines(): lines.append(fix_line(line,prefix)) out = open(fname,"w") for line in lines: out.write(line) out.close()
Python
nomic_cornstack_python_v1
function New *args **kargs begin set obj = call __New_orig__ import itkTemplate call New obj *args keyword kargs return obj end function
def New(*args, **kargs): obj = itkBoundedReciprocalImageFilterIUC3IUC3.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj
Python
nomic_cornstack_python_v1
function downloadAndReplaceFile file_path download_url begin set file = url open download_url with open file_path string wb as output begin write output read file end end function
def downloadAndReplaceFile(file_path, download_url): file = urllib.request.urlopen(download_url) with open(file_path, 'wb') as output: output.write(file.read())
Python
nomic_cornstack_python_v1
function test_cant_add_too_many_per_team fill_players begin with call test_session_scope as ts begin set t = call Team assert call add_player 1 season=TEST_SEASON dbsession=ts assert call add_player 21 season=TEST_SEASON dbsession=ts assert call add_player 41 season=TEST_SEASON dbsession=ts assert not call add_player 6...
def test_cant_add_too_many_per_team(fill_players): with test_session_scope() as ts: t = Team() assert t.add_player(1,season=TEST_SEASON,dbsession=ts) assert t.add_player(21,season=TEST_SEASON,dbsession=ts) assert t.add_player(41,season=TEST_SEASON,dbsession=ts) assert not t.a...
Python
nomic_cornstack_python_v1
function test_request_missing_shapefile self begin set req_url = string http://localhost/wms/test/wms.cgi?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&FORMAT=image%2Fpng&TRANSPARENT=true&LAYERS=Layer_Missing_Shapefile&CRS=EPSG%3A4326&STYLES=&WIDTH=1024&HEIGHT=512&BBOX=-180,-90,180,90&TIME=default if DEBUG begin print strin...
def test_request_missing_shapefile(self): req_url = 'http://localhost/wms/test/wms.cgi?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&FORMAT=image%2Fpng&TRANSPARENT=true&LAYERS=Layer_Missing_Shapefile&CRS=EPSG%3A4326&STYLES=&WIDTH=1024&HEIGHT=512&BBOX=-180,-90,180,90&TIME=default' if DEBUG: print(...
Python
nomic_cornstack_python_v1
function occlusionVisible self mode=none begin if false and glGenQueries begin set query = query if not query begin set query = call glGenQueries 1 set query = call glGenQueries 1 end call glColorMask GL_FALSE GL_FALSE GL_FALSE GL_FALSE try begin call glDepthMask GL_FALSE call glBeginQuery GL_SAMPLES_PASSED query call ...
def occlusionVisible( self, mode=None ): if (False and glGenQueries): query = self.query if not self.query: self.query = query = glGenQueries(1) glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); try: glDepthMask(GL_FALSE); ...
Python
nomic_cornstack_python_v1
function mixin self content begin set pool = pool at slice - 3 : : + pool at slice : - 3 : set l = length pool for i in content begin set pool at i + 3 % l = pool at i + 3 % l ? i ? i - 1 ? 255 end end function
def mixin(self, content): self.pool = self.pool[-3:] + self.pool[:-3] l = len(self.pool) for i in content: self.pool[(i + 3) % l] ^= (i ^ (i - 1)) & 0xff
Python
nomic_cornstack_python_v1
string 予測 comment 73で学習したロジスティック回帰モデルを用い,与えられた文の極性ラベル(正例なら"+1",負例なら"-1")と,その予測確率を計算するプログラムを実装せよ. import pandas as pd import numpy as np import p72 import nltk set FILE = string sentiment-identity.txt set S_FILE = string stop-word.txt set CORRECT_DATA = string sentiment.txt set W_FILE = string sentiment-identity.txt fun...
''' 予測 ''' # 73で学習したロジスティック回帰モデルを用い,与えられた文の極性ラベル(正例なら"+1",負例なら"-1")と,その予測確率を計算するプログラムを実装せよ. import pandas as pd import numpy as np import p72 import nltk FILE = 'sentiment-identity.txt' S_FILE='stop-word.txt' CORRECT_DATA='sentiment.txt' W_FILE='sentiment-identity.txt' def main(): X = [] Y = [] sentiment...
Python
zaydzuhri_stack_edu_python
from flask import request from quokka import app from quokka.controller.utils import log_console from quokka.models.apis import get_device , record_capture decorator call route string /capture/register methods=list string GET string POST function capture_register begin set registration_info = call get_json if not regis...
from flask import request from quokka import app from quokka.controller.utils import log_console from quokka.models.apis import get_device, record_capture @app.route("/capture/register", methods=["GET", "POST"]) def capture_register(): registration_info = request.get_json() if not registration_info: ...
Python
zaydzuhri_stack_edu_python
function lun_start self path begin return call request string lun-start dict string path list path string path list basestring string None false dict end function
def lun_start(self, path): return self.request( "lun-start", { 'path': [ path, 'path', [ basestring, 'None' ], False ], }, { } )
Python
nomic_cornstack_python_v1