code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function search query begin set results = list for document in documents begin if query in document begin append results document end end return results end function
def search(query): results = [] for document in documents: if query in document: results.append(document) return results
Python
flytech_python_25k
import bootstrap function clear **kw begin try begin comment set up the connection wit the passed parameters set kw = setup bootstrap keyword kw end except Exception as e begin raise e end try else begin set redis_conn = get kw string redis_conn comment now loop through each key and remove from the database for key in ...
import bootstrap def clear(**kw): try: # set up the connection wit the passed parameters kw = bootstrap.setup(**kw) except Exception as e: raise e else: redis_conn = kw.get("redis_conn") # now loop through each key and remove from the database for key in redis_conn.keys(): # delete the key ...
Python
zaydzuhri_stack_edu_python
function run_app self begin set server_str = string http:// + marathon_host + string : + marathon_port set marathon_server = call MarathonClient server_str username=marathon_user password=marathon_pass comment validate socket connection with given host and port if call connect marathon_host integer marathon_port begin ...
def run_app(self): server_str = "http://" + self.marathon_host + ":" + self.marathon_port marathon_server = MarathonClient( server_str, username=self.marathon_user, password=self.marathon_pass, ) ### validate socket connection with given host and port...
Python
nomic_cornstack_python_v1
from astnode import * class Compound extends AstNode begin function __init__ self begin call __init__ parent=none set block_items = list end function function prepare_to_print self begin set name = name + string Compound statement: end function end class
from .astnode import * class Compound(AstNode): def __init__(self): super(Compound, self).__init__(parent=None) self.block_items = [] def prepare_to_print(self): self.name += "Compound statement: "
Python
zaydzuhri_stack_edu_python
set inteiro = integer input string Digite um número inteiro: set aux = inteiro - inteiro // 100 * 100 set dezenas = aux // 10 print string O dígito das dezenas é dezenas
inteiro=int(input("Digite um número inteiro: ")) aux = inteiro - (inteiro //100)*100 dezenas = aux//10 print("O dígito das dezenas é",dezenas)
Python
zaydzuhri_stack_edu_python
function execute self cursor begin call error_check set tuple cmd data = call get_string execute cursor cmd data end function
def execute(self, cursor): self.error_check() cmd, data = self.get_string() cursor.execute(cmd, data)
Python
nomic_cornstack_python_v1
function load_model self filepath begin return call load_model filepath end function
def load_model(self, filepath): return tf.keras.models.load_model(filepath)
Python
nomic_cornstack_python_v1
import cv2 import numpy as np import matplotlib.pyplot as plt function plot_matches img1 img2 matches title par begin comment get distinct colors for the lines set cmap = call get_cmap string hsv length matches set img1 = img1 at tuple slice : : slice : : tuple 2 1 0 set img2 = img2 at tuple slice : : slice :...
import cv2 import numpy as np import matplotlib.pyplot as plt def plot_matches(img1, img2, matches, title, par): cmap = plt.cm.get_cmap("hsv", len(matches)) # get distinct colors for the lines img1 = img1[:, :, (2, 1, 0)] img2 = img2[:, :, (2, 1, 0)] plot_img = np.concatenate((img1, img2), axis=1) fig, ax = plt....
Python
zaydzuhri_stack_edu_python
comment This file will read the swagger.yaml file and fetch the tags of the body comment and write it a text file for further use. import os , sys , ntpath , pymongo , time import yaml import xlwt , xlrd , csv from xlwt import Workbook from xlrd import open_workbook from pymongo import MongoClient comment class swagger...
# This file will read the swagger.yaml file and fetch the tags of the body # and write it a text file for further use. import os, sys, ntpath, pymongo, time import yaml import xlwt, xlrd,csv from xlwt import Workbook from xlrd import open_workbook from pymongo import MongoClient #class swaggerToExcel: def readSwagger...
Python
zaydzuhri_stack_edu_python
comment Train the model from shallownet import * from deepwnet import * from transfer_learning_alexnet import * from transfer_learning_resnet import * from data import * import torch from torch import nn from torch.optim import Adam , SGD , RMSprop function train dir num_epochs learning_rate model_name begin if model_n...
# Train the model from shallownet import * from deepwnet import * from transfer_learning_alexnet import * from transfer_learning_resnet import * from data import * import torch from torch import nn from torch.optim import Adam,SGD,RMSprop def train(dir,num_epochs,learning_rate,model_name): if(model_name=='shallow'...
Python
zaydzuhri_stack_edu_python
function pop_many cls longitude latitude location=none ignore_list=none _filter=none begin assert longitude and latitude set radius = get config string matching.radius set unit = get config string matching.unit set _ignore_list = set ignore_list or list set n = get config string matching.num_pop_parking_spaces set redi...
def pop_many(cls, longitude, latitude, location=None, ignore_list=None,_filter=None): assert (longitude and latitude) radius = config.get('matching.radius') unit = config.get('matching.unit') _ignore_list = set(ignore_list or []) n = config.get('matching.num_pop_parking_spaces') ...
Python
nomic_cornstack_python_v1
function clean_prep_xml des_xml rels_rIds pxml_subtags begin set tuple root tree = call gen_tree des_xml set nmsps = nsmap at string r set rId = string { { nmsps } }id for tuple k v in items pxml_subtags begin set subtag1 = find tree k for i in subtag1 begin if get attrib rId begin if get attrib rId not in rels_rIds be...
def clean_prep_xml(des_xml, rels_rIds, pxml_subtags): root, tree = gen_tree(des_xml) nmsps = root.nsmap['r'] rId = f"{{{nmsps}}}id" for k,v in pxml_subtags.items(): subtag1 = tree.find(k) for i in subtag1: if i.attrib.get(rId): if i.attrib.get(rId) not in rel...
Python
nomic_cornstack_python_v1
function arrow_area a b begin set newB = b / 2 return 0.5 * a * newB end function
def arrow_area(a, b): newB = b/2 return 0.5*a*newB
Python
zaydzuhri_stack_edu_python
function test_gpu_simulation_multiple self begin set m = call ModelDescription string test_gpu_simulation_multiple set a1 = call newAgent string a1 call newVariableInt string x set a2 = call newAgent string a2 call newVariableInt string x call newVariableInt string y set func_add = call newRTCFunction string add_func a...
def test_gpu_simulation_multiple(self): m = pyflamegpu.ModelDescription("test_gpu_simulation_multiple") a1 = m.newAgent("a1") a1.newVariableInt("x") a2 = m.newAgent("a2") a2.newVariableInt("x") a2.newVariableInt("y") func_add = a1.newRTCFunction("add_func", self.a...
Python
nomic_cornstack_python_v1
for i in range 0 10 begin set s = x + x / 2 set y = y + s set x = x / 2 end print string 距离 y string 高度 x
for i in range(0,10): s = x +x/2 y = y +s x= x/2 print('距离',y,'高度',x)
Python
zaydzuhri_stack_edu_python
comment 请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。 comment 若队列为空,pop_front 和 max_value 需要返回 -1 comment 示例 1: comment 输入: comment ["MaxQueue","push_back","push_back","max_value","pop_front","max_value"] comment [[],[1],[2],[],[],[]] comment 输出: [null,null,null,2,1,2] comment 示例 ...
# 请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。 # # 若队列为空,pop_front 和 max_value 需要返回 -1 # # 示例 1: # # 输入: # ["MaxQueue","push_back","push_back","max_value","pop_front","max_value"] # [[],[1],[2],[],[],[]] # 输出: [null,null,null,2,1,2] # 示例 2: # # 输入: # ["MaxQueue","pop_front","max_...
Python
zaydzuhri_stack_edu_python
comment requires pip install pillow import qrcode comment from PIL import Image, ImageDraw comment from qrcode.image.pil import PilImage comment generate a paypal payment link to the user identified by "email" for "sum" amount function CreatePayPalLink sum email begin set BaseUrl = string https://www.paypal.com/cgi-bin...
# requires pip install pillow import qrcode #from PIL import Image, ImageDraw #from qrcode.image.pil import PilImage # generate a paypal payment link to the user identified by "email" for "sum" amount def CreatePayPalLink(sum, email): BaseUrl = "https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business=E...
Python
zaydzuhri_stack_edu_python
class Solution begin function minWindow self s t begin if s == string or t == string begin return string end comment 1) Maintain a COUNTER of all characters of t set d = dict for ch in t begin if ch not in d begin set d at ch = 1 end else begin set d at ch = d at ch + 1 end end set required_match = length d comment...
class Solution: def minWindow(self, s, t): if s == '' or t == '': return '' # 1) Maintain a COUNTER of all characters of t d = {} for ch in t: if ch not in d: d[ch] = 1 else: d[ch] += 1 required_mat...
Python
zaydzuhri_stack_edu_python
function load_config self begin comment get information from file set pars = call parse_wfs_config_gui filename comment get only the name of the file set name = split filename string / at - 1 at slice : - 4 : call setText name comment set lineEdits based on what's in file call setText string pars at string energy cal...
def load_config(self): # get information from file pars = wfs_utils.parse_wfs_config_gui(self.filename) # get only the name of the file name = self.filename.split('/')[-1][:-4] self.lineEdit_filename.setText(name) # set lineEdits based on what's in file self.lin...
Python
nomic_cornstack_python_v1
function f_predict_time_series p_serie_tiempo begin comment Meses en el futuro, predecir set meses = 6 comment Ultimo precio set ultimo_precio = p_serie_tiempo at length p_serie_tiempo - 1 comment Reiniciar indice set serie_tiempo = copy p_serie_tiempo reset index serie_tiempo drop=true inplace=true comment -----------...
def f_predict_time_series(p_serie_tiempo): # Meses en el futuro, predecir meses = 6 # Ultimo precio ultimo_precio = p_serie_tiempo[len(p_serie_tiempo) - 1] # Reiniciar indice serie_tiempo = p_serie_tiempo.copy() serie_tiempo.reset_index(drop=True, inplace=True) # --------...
Python
nomic_cornstack_python_v1
function has_unresected_pair resected_idx unresected_imgs img_adjacency begin for idx in unresected_imgs begin if img_adjacency at resected_idx at idx == 1 or img_adjacency at idx at resected_idx == 1 begin return true end end return false end function
def has_unresected_pair(resected_idx, unresected_imgs, img_adjacency): for idx in unresected_imgs: if img_adjacency[resected_idx][idx] == 1 or img_adjacency[idx][resected_idx] == 1: return True return False
Python
nomic_cornstack_python_v1
import pygame call init set GREEN = tuple 0 255 0 set BLACK = tuple 0 0 0 set WHITE = tuple 255 255 255 set RED = tuple 255 0 0 set screenWidth = 1200 set screenHeight = 600 set half_sc = 300 set vel = 9 set x = 20 set y = 236 set a = 64 set b = 64 set obsticle_a = 64 set run = true set isJump = false set jumpCount = 1...
import pygame pygame.init() GREEN = (0, 255, 0) BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) screenWidth = 1200 screenHeight = 600 half_sc = 300 vel = 9 x = 20 y = 236 a = 64 b = 64 obsticle_a = 64 run = True isJump = False jumpCount = 10 win = pygame.display.set_mode((screenWidth, screenHeight)) #mai...
Python
zaydzuhri_stack_edu_python
function get_ip_info self interface begin set ip_re = string ([0-9]+.[0-9]+.[0-9]+.[0-9]+) set type_re = string (\w+) set info_re = string Type: %s, IP: %s Netmask %s Gateway %s % tuple type_re ip_re ip_re ip_re set ip_info = dict set buf = call cmd string get ipaddr %s % interface if match info_re buf at 0 begin set ...
def get_ip_info(self, interface): ip_re = '([0-9]+.[0-9]+.[0-9]+.[0-9]+)' type_re = '(\w+)' info_re = 'Type: %s, IP: %s Netmask %s Gateway %s' % (type_re, ip_re, ip_re, ip_re) ip_info = {} buf = self.cmd("get ipaddr %s" % interface) if re.match(info_re, buf[0]): ...
Python
nomic_cornstack_python_v1
function set_primehub_config_if_not_none cparent name key begin set data = call get_primehub_config key if data is not none begin set attribute cparent name data end end function
def set_primehub_config_if_not_none(cparent, name, key): data = get_primehub_config(key) if data is not None: setattr(cparent, name, data)
Python
nomic_cornstack_python_v1
from parse_json import Tag , TextTag import unittest import html class TestTags extends TestCase begin function setUp self begin set test_tag1 = string h1 set test_value1 = string test1 set test_result1 = string <h1>test1</h1> set test_tag2 = string p set test_value2 = string test2 set test_result2 = string <p>test2</p...
from parse_json import Tag, TextTag import unittest import html class TestTags(unittest.TestCase): def setUp(self): self.test_tag1 = 'h1' self.test_value1 = 'test1' self.test_result1 = '<h1>test1</h1>' self.test_tag2 = 'p' self.test_value2 = 'test2' self.test_resu...
Python
zaydzuhri_stack_edu_python
comment -*- coding: UTF-8 -*- import os import imghdr import cv2 import numpy as np from skimage import io from skimage.feature import canny from skimage.color import rgb2gray from skimage.transform import hough_line , hough_line_peaks from skimage.transform import rotate from PIL import Image
# -*- coding: UTF-8 -*- import os import imghdr import cv2 import numpy as np from skimage import io from skimage.feature import canny from skimage.color import rgb2gray from skimage.transform import hough_line, hough_line_peaks from skimage.transform import rotate from PIL import Image
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding:utf-8 -*- comment ====#====#====#==== comment Author: comment CreatDate: comment Version: comment ====#====#====#==== from woniuboss_test_frame.util.parse_excel import ParseExcel from xml.etree import ElementTree class ReadFile begin string 调用read_excel方法,读取excel文件,主要用于读取...
#!/usr/bin/env python # -*- coding:utf-8 -*- #====#====#====#==== #Author: #CreatDate: #Version: #====#====#====#==== from woniuboss_test_frame.util.parse_excel import ParseExcel from xml.etree import ElementTree class ReadFile: """ 调用read_excel方法,读取excel文件,主要用于读取data数据 调用read_xml方法,读取xml文件,主要用于读取配置...
Python
zaydzuhri_stack_edu_python
function test_range detector begin set image = random tuple 100 100 set out = call detector image call assert_ min >= 0 string Minimum of ` { __name__ } ` is smaller than 0. call assert_ max <= 1 string Maximum of ` { __name__ } ` is larger than 1. end function
def test_range(detector): image = cp.random.random((100, 100)) out = detector(image) assert_( out.min() >= 0, f"Minimum of `{detector.__name__}` is smaller than 0." ) assert_( out.max() <= 1, f"Maximum of `{detector.__name__}` is larger than 1." )
Python
nomic_cornstack_python_v1
function get_bayes_estimates summary map_estimate begin set mean_beta = none set mean_zt = none comment Go through all estimates for tuple index row in call iterrows begin if index == string A begin set mean_A = row at string mean set std_A = row at string sd set C2_5_A = row at string hdi_3% set C97_5_A = row at strin...
def get_bayes_estimates(summary, map_estimate): mean_beta = None mean_zt = None # Go through all estimates for index, row in summary.iterrows(): if index=='A': mean_A = row['mean'] std_A = row['sd'] C2_5_A = row['hdi_3%'] C97_5_A = row['hdi_97%']...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 comment -*- coding: utf-8 -*- comment @Author:Pxz comment @Time :2018/12/20 0020下午 2:39 class A begin set a = string 1 function __init__ self **kwargs begin for tuple key value in items kwargs begin set attribute self key value end end function end class function proce para begin print para en...
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Author:Pxz # @Time :2018/12/20 0020下午 2:39 class A: a = "1" def __init__(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, value) def proce(para): print(para) class B(A): def p(self): proce(self.a) i...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 import sys function main begin set lines = list set index = list for line in stdin begin set line = split line set row = list comprehension c for c in line append lines row end set l1 = lines at 0 set l2 = lines at 1 set i = 0 while i < length l1 and length l2 begin if l1 at i == l2 at i...
#!/usr/bin/env python3 import sys def main(): lines = [] index = [] for line in sys.stdin: line = line.split() row = [c for c in line] lines.append(row) l1 = lines[0] l2 = lines[1] i = 0 while i < len(l1) and len(l2): if l1[i] == l2[i]: index.a...
Python
zaydzuhri_stack_edu_python
function test_search_entry_meal self begin pass end function
def test_search_entry_meal(self): pass
Python
nomic_cornstack_python_v1
from BackProp_Python_v2 import NN from vrep_pioneer_simulation import VrepPioneerSimulation from rdn import Pioneer import rospy from online_trainer import OnlineTrainer import json import threading set robot = call VrepPioneerSimulation comment robot = Pioneer(rospy) set network = nn 3 10 2 set choice = input string D...
from BackProp_Python_v2 import NN from vrep_pioneer_simulation import VrepPioneerSimulation from rdn import Pioneer import rospy from online_trainer import OnlineTrainer import json import threading robot = VrepPioneerSimulation() #robot = Pioneer(rospy) network = NN(3, 10, 2) choice = input('Do you want to load pr...
Python
zaydzuhri_stack_edu_python
class Solution extends object begin function isMatch1 self s p begin string :type s: str :type p: str :rtype: bool comment print 'matching %s %s' % (s, p) if p == string begin return length s == 0 end if length p > 1 and p at 1 == string * begin if call isMatch1 s p at slice 2 : : begin return true end else begin if ...
class Solution(object): def isMatch1(self, s, p): """ :type s: str :type p: str :rtype: bool """ #print 'matching %s %s' % (s, p) if p == '': return len(s)==0 if len(p) > 1 and p[1] == '*': if self.isMatch1(s, p[2:]): ...
Python
zaydzuhri_stack_edu_python
function call_domains input num_states genome cmap output sparse nproc begin print string Starting HMM on + input file=stderr set chroms = call get_chroms genome set df = call create_df inputfile=input chroms=chroms set df = call hmm df num_states print string Finished hmm! set df_sparse = call sparse df call write_to_...
def call_domains( input, num_states, genome, cmap, output, sparse, nproc, ): print("Starting HMM on " + input, file=sys.stderr) chroms = hmm.get_chroms(genome) df = hmm.create_df(inputfile=input, chroms=chroms) df = hmm.hmm(df, num_states) print("Finished hmm!") df_sparse =hmm.sparse(df...
Python
nomic_cornstack_python_v1
for i in range bolas_de_neves begin set vencedora = renas at j set j = j + 1 if j == 9 begin set j = 0 end end print vencedora
for i in range(bolas_de_neves): vencedora = renas[j] j += 1 if j == 9: j = 0 print(vencedora)
Python
zaydzuhri_stack_edu_python
function binarySearch theValues target begin set low = 0 set high = length theValues - 1 while low <= high begin set mid = low + high // 2 if theValues at mid == target begin return true end else if target < theValues at mid begin set high = mid - 1 end else begin set low = mid + 1 end end return true end function func...
def binarySearch(theValues, target): low = 0 high = len(theValues) - 1 while low <= high: mid = (low+high)//2 if theValues[mid] == target: return True elif target < theValues[mid]: high = mid - 1 else: low = mid + 1 return True def bubbleSort(theSeq): n = len(theSeq) for i in range(n - 1): fo...
Python
zaydzuhri_stack_edu_python
function test_div begin set l = list 1 2 3 4 assert call div *l == 1 / 2 / 3 / 4 assert call div 100 20 == 5 assert call div 100.0 20 == 5.0 assert call div 100 20.0 == 5.0 end function
def test_div(): l = [1, 2, 3, 4] assert s7.div(*l) == 1 / 2 / 3 / 4 assert s7.div(100, 20) == 5 assert s7.div(100.0, 20) == 5.0 assert s7.div(100, 20.0) == 5.0
Python
nomic_cornstack_python_v1
function period_seconds self value begin set _properties at string periodSeconds = value end function
def period_seconds(self, value: int): self._properties["periodSeconds"] = value
Python
nomic_cornstack_python_v1
function ping client begin if client_type == WEBHOOK begin return call _ping_webhook client end else begin return call _ping_client client end end function
def ping(client: MobileClient) -> bool: if client.client_type == ClientType.WEBHOOK: return TBANSHelper._ping_webhook(client) else: return TBANSHelper._ping_client(client)
Python
nomic_cornstack_python_v1
comment https://www.acmicpc.net/problem/10809 from sys import stdin set input = readline set text = right strip input set countList = list - 1 * 26 for tuple i c in enumerate text begin set alphaIndex = ordinal c - 97 if countList at alphaIndex == - 1 begin set countList at alphaIndex = i end end print join string map...
# https://www.acmicpc.net/problem/10809 from sys import stdin input = stdin.readline text = input().rstrip() countList = [-1]*26 for i, c in enumerate(text): alphaIndex = ord(c)-97 if countList[alphaIndex] == -1 : countList[alphaIndex] = i print(" ".join(map(str,countList)))
Python
zaydzuhri_stack_edu_python
function _double_controlled_phi_add_mod_N self num_qubits angles begin set circuit = call QuantumCircuit num_qubits name=string ccphi_add_mod_N set ctl_up = 0 set ctl_down = 1 set ctl_aux = 2 comment get qubits from aux register, omitting the control qubit set qubits = range 3 num_qubits comment store the gates represe...
def _double_controlled_phi_add_mod_N( self, num_qubits: int, angles: Union[np.ndarray, ParameterVector] ) -> QuantumCircuit: circuit = QuantumCircuit(num_qubits, name="ccphi_add_mod_N") ctl_up = 0 ctl_down = 1 ctl_aux = 2 # get qubits from aux register, omitting the...
Python
nomic_cornstack_python_v1
async function config_directories request begin return dict string configdir call get_cfg_value string general.configdir ; string basedir call get_cfg_value string general.basedir ; string frontenddir call get_cfg_value string general.frontenddir ; string _links dict string _self call url_for string config.config_direc...
async def config_directories(request) -> ConfigDir: return { "configdir": DopplerrConfig().get_cfg_value("general.configdir"), "basedir": DopplerrConfig().get_cfg_value("general.basedir"), "frontenddir": DopplerrConfig().get_cfg_value("general.frontenddir"), "_links": { "...
Python
nomic_cornstack_python_v1
async function wait_for_blast_search self begin set interval = 3 while true begin await sleep interval set blast = await call check_nuvs_blast analysis_id sequence_index if ready begin info string Retrieved result for BLAST %s rid break end if error begin info string Encountered error for BLAST %s: %s rid error await c...
async def wait_for_blast_search(self): interval = 3 while True: await asyncio.sleep(interval) blast = await self.data.blast.check_nuvs_blast( self.analysis_id, self.sequence_index ) if blast.ready: logger.info("Retrieved...
Python
nomic_cornstack_python_v1
import unittest from barista import Barista from waiter import Waiter class WaiterTestCase extends TestCase begin function setUp self begin set waiter1 = call Waiter string Harry Potter 150 set customers_served = 42 set barista1 = call Barista string Hermione Granger 160 end function function test_init self begin set w...
import unittest from barista import Barista from waiter import Waiter class WaiterTestCase(unittest.TestCase): def setUp(self) -> None: self.waiter1 = Waiter("Harry Potter", 150) self.waiter1.customers_served = 42 self.barista1 = Barista("Hermione Granger", 160) def test_init(self):...
Python
zaydzuhri_stack_edu_python
function print_prime_numbers num begin for i in range 2 num + 1 begin for j in range 2 i begin if i % j == 0 begin break end end for else begin print i end end end function
def print_prime_numbers(num): for i in range(2, num+1): for j in range(2, i): if (i % j) == 0: break else: print(i)
Python
jtatman_500k
comment !/usr/bin/env python comment -*- coding:utf-8 -*- import sys , math , getopt import tensorflow as tf import numpy as np from text_dataset import TextDataset class MyW2V extends object begin string Implementation of PV-DM (Distributed Memory Model of Paragraph Vectors) see Distributd Representation of Sentences ...
#!/usr/bin/env python # -*- coding:utf-8 -*- import sys, math, getopt import tensorflow as tf import numpy as np from text_dataset import TextDataset class MyW2V(object): ''' Implementation of PV-DM (Distributed Memory Model of Paragraph Vectors) see Distributd Representation of Sentences and Do...
Python
zaydzuhri_stack_edu_python
function process_tar_archive tar_file_name begin with open tar_file_name string r as tar begin set tar_log_files = call getnames set queue_log_subset = concat list comprehension call assign Date=string parse time split log string . at 0 string %Y-%m-%d-%H-%M-%S for log in tar_log_files end return queue_log_subset end f...
def process_tar_archive(tar_file_name): with tarfile.open(tar_file_name,'r') as tar: tar_log_files = tar.getnames() queue_log_subset = pd.concat([ pd.read_csv(tar.extractfile(log),delim_whitespace=True).assign( Date=datetime.datetime.strptime(log.split('.')[0],'%Y-%m-%d-%...
Python
nomic_cornstack_python_v1
function predicate self qx begin set lhs = call qx lhs set op = op set name = __name__ set op = get _Op_Map_ name op return call _op_call name op *self.args keyword kw end function
def predicate (self, qx) : lhs = qx (self.lhs) op = self.op name = op.__name__ op = _Op_Map_.get (name, op) return lhs._op_call (name, op, * self.args, ** self.kw)
Python
nomic_cornstack_python_v1
import os , time class Login begin set cal = 0 set call = 0 set ag = none function agencia self begin while cal <= 4 or cal >= 4 begin set agen = string input string AGÊNCIA : set cal = length agen set ag = agen if length agen == 4 begin break end else begin print string DADOS INCORRETO PERMITIDO APENAS 4 DIGITOS sleep...
import os, time class Login: cal = 0 call = 0 ag = None def agencia(self): while self.cal <= 4 or self.cal >= 4: agen = str(input('AGÊNCIA : ')) self.cal = len(agen) self.ag = agen if len(agen) == 4: break ...
Python
zaydzuhri_stack_edu_python
function __on_message self user msg begin print string { user } says: { msg } end function
def __on_message(self, user, msg): print(f'{user} says:\t {msg}')
Python
nomic_cornstack_python_v1
comment _*_ coding: utf-8 _*_ comment author jiudianren comment time:2019/11/5 16:42 import requests import zipfile import configparser function unzip_single src_file dest_dir begin print string unzip_single start set f_str = src_file set zf = zip file f_str try begin extract all zf path=dest_dir end except RuntimeErro...
# _*_ coding: utf-8 _*_ # author jiudianren # time:2019/11/5 16:42 import requests import zipfile import configparser def unzip_single(src_file, dest_dir): print("unzip_single start") f_str = src_file zf = zipfile.ZipFile(f_str) try: zf.extractall(path=dest_dir) except RuntimeError as e:...
Python
zaydzuhri_stack_edu_python
string modul 3 set A = list list 2 3 list 3 1 set B = list list 6 3 list 4 2 set a = length A set b = length B comment 1 comment konsistensi isi dan ukuran matriks set N = 5 set M = 4 set res = list comprehension list comprehension 0 for i in range N for j in range M print string Matriks setelahi inisiasi: + string res...
"""modul 3""" A = [[2,3], [3,1]] B = [[6,3], [4,2]] a = len(A) b = len(B) #1 #konsistensi isi dan ukuran matriks N = 5 M = 4 res = [ [ 0 for i in range(N) ] for j in range(M) ] print("Matriks setelahi inisiasi: " + str(res)) print (' ') #ukuran matriks res = [sum(len(row) > idx for row in B) ...
Python
zaydzuhri_stack_edu_python
set name = input string Hey! Please type your name: print format string Hello, {} name
name=input("Hey! Please type your name: ") print("Hello, {}".format(name))
Python
zaydzuhri_stack_edu_python
function cdsparse self record begin string Finds core genes, and records gene names and sequences in dictionaries :param record: SeqIO record try begin comment Find genes that are present in all strains of interest - the number of times the gene is found is comment equal to the number of strains. Earlier parsing ensure...
def cdsparse(self, record): """ Finds core genes, and records gene names and sequences in dictionaries :param record: SeqIO record """ try: # Find genes that are present in all strains of interest - the number of times the gene is found is # equal to the n...
Python
jtatman_500k
function load_log filename begin set logfile = open directory + filename string r set log = call splitlines set log = list comprehension decimal i for i in log close logfile return log end function
def load_log(filename): logfile = open(directory + filename, "r") log = logfile.read().splitlines() log = [float(i) for i in log] logfile.close() return log
Python
nomic_cornstack_python_v1
from flask_restful import Resource , reqparse from com_stock_api.memberChurn_pred.memberChurn_pred_dto import MemberChurnPredDto from com_stock_api.memberChurn_pred.memberChurn_pred_dao import MemberChurnPredDao class MemberChurnPred extends Resource begin function __init__ self begin set parser = call RequestParser ca...
from flask_restful import Resource, reqparse from com_stock_api.memberChurn_pred.memberChurn_pred_dto import MemberChurnPredDto from com_stock_api.memberChurn_pred.memberChurn_pred_dao import MemberChurnPredDao class MemberChurnPred(Resource): def __init__(self): parser = reqparse.RequestParser() ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment encoding: utf-8 import pickle import numpy as np from scipy import spatial function cos_similarity a b begin with open string image_vectors.pkl string rb as f begin set images = load pickle f set s1 = images at a set s2 = images at b return 1 - call cosine s1 s2 end end function fun...
#!/usr/bin/env python # encoding: utf-8 import pickle import numpy as np from scipy import spatial def cos_similarity(a, b): with open('image_vectors.pkl', 'rb') as f: images = pickle.load(f) s1 = images[a] s2 = images[b] return 1 - spatial.distance.cosine(s1, s2) def print_all_...
Python
zaydzuhri_stack_edu_python
import django_filters from rest_framework import filters from rest_framework import ISO_8601 from distutils.util import strtobool from django.utils.encoding import force_str from django import forms from django.utils.dateparse import parse_datetime from django.forms import DateTimeField set BOOLEAN_CHOICES = tuple tupl...
import django_filters from rest_framework import filters from rest_framework import ISO_8601 from distutils.util import strtobool from django.utils.encoding import force_str from django import forms from django.utils.dateparse import parse_datetime from django.forms import DateTimeField BOOLEAN_CHOICES = ( ...
Python
zaydzuhri_stack_edu_python
function get_test_runs_by_run_id run_id session=none begin set session = session or call get_session set test_runs = all return test_runs end function
def get_test_runs_by_run_id(run_id, session=None): session = session or get_session() test_runs = db_utils.model_query(models.TestRun, session=session).filter_by( run_id=run_id).all() return test_runs
Python
nomic_cornstack_python_v1
function __init__ self env k begin call __init__ self env set k = k set frames = deque list maxlen=k set shp = shape set observation_space = call Box low=0 high=255 shape=tuple shp at 0 shp at 1 shp at 2 * k dtype=uint8 end function
def __init__(self, env, k): gym.Wrapper.__init__(self, env) self.k = k self.frames = deque([], maxlen=k) shp = env.observation_space.shape self.observation_space = spaces.Box(low=0, high=255, shape=(shp[0], shp[1], shp[2] * k), dtype=np.uint8)
Python
nomic_cornstack_python_v1
function describe_list lst name begin print string Description of name string : print string Count: length lst print string Sum: sum lst print string Min: min lst print string Mean: sum lst / length lst print string Max: max lst call distplot lst axlabel=name show print end function
def describe_list(lst, name): print("Description of", name, ":") print("Count:", len(lst)) print("Sum:", sum(lst)) print("Min:", min(lst)) print("Mean:", sum(lst) / len(lst)) print("Max:", max(lst)) sns.distplot(lst, axlabel=name) plt.show() print()
Python
nomic_cornstack_python_v1
from bs4 import BeautifulSoup import requests set res = get requests string https://en.wikipedia.org/wiki/List_of_cities_in_India_by_population set soup = call BeautifulSoup text string lxml text set table = find all string table attrs=dict string class string wikitable sortable p set tb = list for t in table begin se...
from bs4 import BeautifulSoup import requests res = requests.get( "https://en.wikipedia.org/wiki/List_of_cities_in_India_by_population" ) soup = BeautifulSoup(res.text, "lxml") soup.title.text table = soup.findAll("table", attrs={"class": "wikitable sortable"}) soup.p tb = [] for t in table: x = t.findAll("t...
Python
zaydzuhri_stack_edu_python
function test_electron_effective_mass_non_numeric self begin set input_params at string electron_effective_mass = string this string is non-numeric. try begin set El = call SC keyword input_params end except TypeError begin comment Attempting to instantiate a `tec.electrode.SC` with a non-numeric `electron_effective_ma...
def test_electron_effective_mass_non_numeric(self): self.input_params["electron_effective_mass"] = "this string is non-numeric." try: El = SC(**self.input_params) except TypeError: # Attempting to instantiate a `tec.electrode.SC` with a non-numeric `electron_effective_ma...
Python
nomic_cornstack_python_v1
function filter_allowed_extensions extensions allowed_extensions=none begin set allowed_extensions = allowed_extensions or list for ext in extensions begin set ext_name = get OID_NAMES oid none if ext_name in allowed_extensions begin yield ext end else if critical begin raise call CertificateValidationError extension=...
def filter_allowed_extensions(extensions, allowed_extensions=None): allowed_extensions = allowed_extensions or [] for ext in extensions: ext_name = OID_NAMES.get(ext.oid, None) if ext_name in allowed_extensions: yield ext else: if ext.critical: ra...
Python
nomic_cornstack_python_v1
function Check self artifacts begin raise call NotImplementedError string Subclass didn't implement Check method. end function
def Check(self, artifacts: list[T]) -> bool: raise NotImplementedError("Subclass didn't implement Check method.")
Python
nomic_cornstack_python_v1
function func x begin if x % 2 == 0 begin return x + 5 end else begin return x - 5 end end function function test_method begin assert call func 3 == 8 end function function test_method_2 begin assert call func 2 == 7 end function
def func(x): if x%2 == 0: return x+5 else: return x-5 def test_method(): assert func(3)== 8 def test_method_2(): assert func(2) == 7
Python
zaydzuhri_stack_edu_python
function integration_partner_id self integration_partner_id begin set _integration_partner_id = integration_partner_id end function
def integration_partner_id(self, integration_partner_id): self._integration_partner_id = integration_partner_id
Python
nomic_cornstack_python_v1
string Created on Sep/26/2018 @author: Bryce Xu import tensorflow as tf string AlexNet Input Cifar-10:32x32x3 SpatialConvolution (Weight Only) 'VALID' [3,3,3,128] [1,1,1,1] 32x32x3 -> 32x32x128 BatchNormalization HardTanh SpartialConvolution_1 [3,3,128,128] [1,1,1,1] 32x32x128 -> 32x32x128 MaxPooling [1,2,2,1] [1,2,2,1...
''' Created on Sep/26/2018 @author: Bryce Xu ''' import tensorflow as tf ''' AlexNet Input Cifar-10:32x32x3 SpatialConvolution (Weight Only) 'VALID' [3,3,3,128] [1,1,1,1] 32x32x3 -> 32x32x128 BatchNormalization HardTanh SpartialConvolution_1 [3,3,128,128] [1,1,1,1] 32x32x128 -> 32x32x128 M...
Python
zaydzuhri_stack_edu_python
import dash import dash_html_components as html import dash_core_components as dcc import plotly.offline as pyo import plotly.graph_objs as go import pandas as pd import numpy as np from dash.dependencies import Input , Output import dash_table set app = call Dash set server = server set df2 = read csv string contents2...
import dash import dash_html_components as html import dash_core_components as dcc import plotly.offline as pyo import plotly.graph_objs as go import pandas as pd import numpy as np from dash.dependencies import Input, Output import dash_table app = dash.Dash() server = app.server df2 = pd.read_csv('contents2.csv') d...
Python
zaydzuhri_stack_edu_python
comment ! /bin/env python import sys class InputFile begin function __init__ self filename begin set in_file = open filename string r set text = read in_file set temp = split text string set rows = split text at slice length temp at 0 : : string set cases = integer temp at 0 close in_file end function function getSiz...
#! /bin/env python import sys; class InputFile: def __init__(self, filename): in_file = open(filename,"r"); text = in_file.read(); temp = text.split("\n"); self.rows = text[len(temp[0]):].split("\n\n"); self.cases = int(temp[0]); in_file.close() def getSize(self): return self.cases; def getBoard(se...
Python
zaydzuhri_stack_edu_python
if age < 4 begin print string 幼儿 end if age < 12 begin print string 儿童 end if age < 18 begin print string 青少年 end if age < 25 begin print string 青年 end if age < 100 begin print string 少于100 end else begin print string 大于100 end if age < 10 begin print string age end if name == string 小明 begin print string 小明 end commen...
if age < 4 : print('幼儿') if age < 12 : print('儿童') if age < 18 : print('青少年') if age < 25 : print('青年') if age < 100 : print('少于100') else : print('大于100') if age < 10 : print('age') if name == '小明': print('小明') # 局部变量 影响部分代码 在部分代码中有效 # 全局变量 在全部代码中都有效 if age < 5 : info = '小学生' ...
Python
zaydzuhri_stack_edu_python
function test_stundenplaene_duplicates self begin comment the database better be ok before we test this: set problem = call check_stundenplaene_unique assert false problem set cl = call login_user string JochenMelzian set response = get cl string /arbeitsplan/aufgabeEditieren/7/ assert equal status_code 200 call pp con...
def test_stundenplaene_duplicates(self): # the database better be ok before we test this: problem = self.check_stundenplaene_unique() self.assertFalse(problem) cl = self.login_user('JochenMelzian') response = cl.get('/arbeitsplan/aufgabeEditieren/7/') self.assertEqual(r...
Python
nomic_cornstack_python_v1
comment Author: ddlee, me@ddlee.cn comment License: MIT comment Docs: comment there are two special layers, input and loss, comment which stand for the start and the end of a network import numpy as np from collections import defaultdict from zeronet.core.function import * set __all__ = list string layer string Linear ...
# Author: ddlee, me@ddlee.cn # License: MIT # Docs: # there are two special layers, input and loss, # which stand for the start and the end of a network import numpy as np from collections import defaultdict from zeronet.core.function import * __all__ = ['layer', 'Linear', 'Conv', 'Pool', 'ReLU', 'Sigmoid'] class l...
Python
zaydzuhri_stack_edu_python
function free_rec_acc y_true y_pred get_prop_corr=false begin if call shape y_true != call shape y_pred begin print string y_pred type: { type y_pred } { y_pred } print string y_true type: { type y_true } { y_true } raise call ValueError string y_true ( { call shape y_true } ) and y_pred ( { call shape y_pred } ) shoul...
def free_rec_acc(y_true, y_pred, get_prop_corr=False): if np.shape(y_true) != np.shape(y_pred): print(f"\ny_pred\ntype: {type(y_pred)}\n{y_pred}") print(f"\ny_true\ntype: {type(y_true)}\n{y_true}") raise ValueError(f"y_true ({np.shape(y_true)}) and y_pred ({np.shape(y_pred)}) should be same...
Python
nomic_cornstack_python_v1
function flash_write self addr data nbits=none flags=0 begin comment This indicates that all data written from this point on will go into comment the buffer of the flashloader of the DLL. call JLINKARM_BeginDownload flags call memory_write addr data nbits=nbits comment Start downloading the data into the flash memory. ...
def flash_write(self, addr, data, nbits=None, flags=0): # This indicates that all data written from this point on will go into # the buffer of the flashloader of the DLL. self._dll.JLINKARM_BeginDownload(flags) self.memory_write(addr, data, nbits=nbits) # Start downloading the ...
Python
nomic_cornstack_python_v1
function bestAttr attributes data begin set maxGain = 0 set maxGainAttribute = string for item in attributes begin set info_gain = call InfoGain data item attributes comment print(info_gain,maxGain,len(attributes),len(data[0]),sep=' % ') if info_gain > maxGain begin set maxGain = call InfoGain data item attributes set...
def bestAttr(attributes, data): maxGain = 0 maxGainAttribute = '' for item in attributes: info_gain = InfoGain(data, item, attributes) # print(info_gain,maxGain,len(attributes),len(data[0]),sep=' % ') if( info_gain > maxGain): maxGain = InfoGain(data, item, attributes) maxGainAttribute = item return max...
Python
nomic_cornstack_python_v1
function _cat_directions self h begin if bidirectional_encoder begin set h = call cat list h at slice 0 : size h 0 : 2 h at slice 1 : size h 0 : 2 2 end return h end function
def _cat_directions(self, h): if self.bidirectional_encoder: h = torch.cat([h[0:h.size(0):2], h[1:h.size(0):2]], 2) return h
Python
nomic_cornstack_python_v1
comment Blink comment Import Pin class from machine library to configure GPIO Pins. from machine import Pin comment Import utime library to implement delay import utime comment create an object of Pin class and set GPIO Parameters (GPIO Pin, Direction). set led_gpio25 = call Pin 25 OUT comment Create an infinite loop. ...
# Blink #Import Pin class from machine library to configure GPIO Pins. from machine import Pin #Import utime library to implement delay import utime #create an object of Pin class and set GPIO Parameters (GPIO Pin, Direction). led_gpio25 = Pin(25, Pin.OUT) #Create an infinite loop. This is similar to while(1) in C. wh...
Python
zaydzuhri_stack_edu_python
import file1 print string File2: __name__ var is: %s % __name__ if __name__ == string __main__ begin print string File is being run directly end else begin print string File is being imported end
import file1 print("File2: __name__ var is: %s"%__name__) if __name__ == "__main__": print("File is being run directly") else: print("File is being imported")
Python
zaydzuhri_stack_edu_python
from sanic import Blueprint from sanic.response import json from sanic.exceptions import InvalidUsage , NotFound from models import Author , Book import marshallers set bp = call Blueprint string app class InvalidParameter extends InvalidUsage begin set description = string An invalid parameter was provided end class f...
from sanic import Blueprint from sanic.response import json from sanic.exceptions import InvalidUsage, NotFound from models import Author, Book import marshallers bp = Blueprint("app") class InvalidParameter(InvalidUsage): description = "An invalid parameter was provided" def validate_get(request, marshaller...
Python
zaydzuhri_stack_edu_python
from textblob import TextBlob set reviews = list string This is a great product! string It is okay, not bad. string This product is terrible. set classified_reviews = dict string positive list ; string neutral list ; string negative list for review in reviews begin set blob = call TextBlob review if polarity > 0.5 b...
from textblob import TextBlob reviews = ['This is a great product!', 'It is okay, not bad.', 'This product is terrible.'] classified_reviews = {'positive': [], 'neutral': [], 'negative': []} for review in reviews: blob = TextBlob(review) if blob.sentiment.polarity > 0.5: classified_reviews['positive'].a...
Python
flytech_python_25k
comment !/usr/bin/env python3 string module import numpy as np function pdf X m S begin string ` function that calculates the probability density function of a Gaussian distribution if not is instance X ndarray or ndim != 2 begin return none end if not is instance m ndarray or ndim != 1 begin return none end if not is ...
#!/usr/bin/env python3 """ module """ import numpy as np def pdf(X, m, S): """` function that calculates the probability density function of a Gaussian distribution """ if not isinstance(X, np.ndarray) or X.ndim != 2: return None if not isinstance(m, np.ndarray) or m.ndim != 1: return ...
Python
zaydzuhri_stack_edu_python
import cv2 import time from PIL import Image from numpy import array from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.neural_network import MLPClassifier from sklearn.metrics import classification_report , confusion_matrix import pickle call namedWindow ...
import cv2 import time from PIL import Image from numpy import array from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.neural_network import MLPClassifier from sklearn.metrics import classification_report,confusion_matrix import pickle cv2.namedWindow("p...
Python
zaydzuhri_stack_edu_python
class Employee begin function __init__ self employee_id first_name last_name begin set employee_id = employee_id set first_name = first_name set last_name = last_name end function function __str__ self begin return string employee ID: { employee_id } , first name: { first_name } , last name: { last_name } end function ...
class Employee: def __init__(self, employee_id: int, first_name: str, last_name: str): self.employee_id = employee_id self.first_name = first_name self.last_name = last_name def __str__(self): return f"employee ID: {self.employee_id}, first name: {self.first_name}, last name: {...
Python
zaydzuhri_stack_edu_python
function postal_code self postal_code begin if postal_code is not none and length postal_code > 20 begin comment noqa: E501 raise call ValueError string Invalid value for `postal_code`, length must be less than or equal to `20` end set _postal_code = postal_code end function
def postal_code(self, postal_code): if postal_code is not None and len(postal_code) > 20: raise ValueError("Invalid value for `postal_code`, length must be less than or equal to `20`") # noqa: E501 self._postal_code = postal_code
Python
nomic_cornstack_python_v1
import os import sys from clustering_part2 import similarity import nltk from nltk.corpus import stopwords set ROOT = absolute path path string %s/../.. % absolute path path directory name path __file__ append path ROOT set environ at string DJANGO_SETTINGS_MODULE = string confo.settings from django.core.management imp...
import os import sys from clustering_part2 import similarity import nltk from nltk.corpus import stopwords ROOT = os.path.abspath('%s/../..' % os.path.abspath(os.path.dirname(__file__))) sys.path.append(ROOT) os.environ['DJANGO_SETTINGS_MODULE'] = 'confo.settings' from django.core.management import setup_environ from ...
Python
zaydzuhri_stack_edu_python
function _wrap_rest_data self data begin if is instance data dict begin return call _wrap_rest_data_one data end if not is instance data list begin raise call RuntimeError string Result data must be a dict or a list: '%s' was returned % type data end set objs = list for item in data begin append objs call _wrap_rest_d...
def _wrap_rest_data(self, data): if isinstance(data, dict): return self._wrap_rest_data_one(data) if not isinstance(data, list): raise RuntimeError("Result data must be a dict or a list: '%s' was returned" % type(data)) objs = [] for item in data: ob...
Python
nomic_cornstack_python_v1
function create_credential account_Name user_Name user_Password begin set new_credential = call Credentials account_Name user_Name user_Password comment create Credentials object return new_credential end function
def create_credential(account_Name, user_Name, user_Password): new_credential = Credentials( account_Name, user_Name, user_Password) # create Credentials object return new_credential
Python
nomic_cornstack_python_v1
function test_create_displays_success_message create_template mocker begin set message = string create display message patch string app.cli.create_template return_value=dict string msg message set template_name = string flask-app set response = call create_template list string -n template_name assert exit_code == 0 ass...
def test_create_displays_success_message(create_template, mocker): message = 'create display message' mocker.patch('app.cli.create_template', return_value={'msg': message}) template_name = 'flask-app' response = create_template(["-n", template_name]) assert response.exit_code == 0 assert messag...
Python
nomic_cornstack_python_v1
function test_suite begin call test call is_palindrome string abba call test not call is_palindrome string abab call test call is_palindrome string tenet call test not call is_palindrome string banana call test call is_palindrome string straw warts call test call is_palindrome string a end function
def test_suite(): test(is_palindrome("abba")) test(not is_palindrome("abab")) test(is_palindrome("tenet")) test(not is_palindrome("banana")) test(is_palindrome("straw warts")) test(is_palindrome("a"))
Python
nomic_cornstack_python_v1
function label_experiment self exp_id begin set exp = call experiment new_experiment=false ts=string exp_id set label = get form string label call update_metadata change_label=true label=label return string OK end function
def label_experiment(self, exp_id): exp = experiment.experiment(new_experiment=False, ts=str(exp_id)) label = request.form.get('label') exp.update_metadata(change_label=True, label=label) return "OK"
Python
nomic_cornstack_python_v1
function channelport self begin try begin return _channelport end except Exception as e begin raise e end end function
def channelport(self) : try : return self._channelport except Exception as e: raise e
Python
nomic_cornstack_python_v1
function move self partition source dest begin string Return a new state that is the result of moving a single partition. :param partition: The partition index of the partition to move. :param source: The broker index of the broker to move the partition from. :param dest: The broker index of the broker to move the part...
def move(self, partition, source, dest): """Return a new state that is the result of moving a single partition. :param partition: The partition index of the partition to move. :param source: The broker index of the broker to move the partition from. :param dest: The broker i...
Python
jtatman_500k
import json import numpy as np from keras.models import load_model import heapq from nltk.tokenize import RegexpTokenizer set SEQUENCE_LENGTH = 3 set SENTENCE_LENGTH = 10 set tokenizer = call RegexpTokenizer string \w+ with open string data/vocab.json as f begin set unique_words = load json f end set model = call load_...
import json import numpy as np from keras.models import load_model import heapq from nltk.tokenize import RegexpTokenizer SEQUENCE_LENGTH = 3 SENTENCE_LENGTH = 10 tokenizer = RegexpTokenizer(r'\w+') with open('data/vocab.json') as f: unique_words = json.load(f) model = load_model('saved_models/word_prediction.h5...
Python
zaydzuhri_stack_edu_python
import sqlite3 from sklearn.mixture import GaussianMixture import numpy as np set db_name = string data/almgsi_mc_sgc.db function get_data begin set con = call connect db_name set cur = call cursor set sql = string SELECT Al_conc,Mg_conc,Si_conc,mu_c1_0,mu_c1_1,mu_c1_2 set sql = sql + string FROM random_direction_sa WH...
import sqlite3 from sklearn.mixture import GaussianMixture import numpy as np db_name = "data/almgsi_mc_sgc.db" def get_data(): con = sqlite3.connect(db_name) cur = con.cursor() sql = "SELECT Al_conc,Mg_conc,Si_conc,mu_c1_0,mu_c1_1,mu_c1_2 " sql += "FROM random_direction_sa WHERE temperature=200" ...
Python
zaydzuhri_stack_edu_python
while true begin set key = input message_key if key == string end begin break end set value = input message_value if value == string end begin break end set dict_1 at key = value end print string Create dict2: while true begin set key = input message_key if key == string end begin break end set value = input message_va...
while True: key = input(message_key) if key == 'end': break value = input(message_value) if value == 'end': break dict_1[key] = value print("Create dict2: ") while True: key = input(message_key) if key == 'end': break value = input(message_value) if v...
Python
zaydzuhri_stack_edu_python
function save_to_matlab output_file x y x_special begin call savemat output_file dictionary x=x y=y x_special=x_special end function
def save_to_matlab(output_file,x,y,x_special): savemat(output_file,dict(x=x,y=y,x_special=x_special))
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Thu Feb 21 17:46:58 2019 @author: pan comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Sat Jul 28 16:28:46 2018 @author: pan from time import time import numpy as np import pandas as pd from sklearn import svm fro...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Feb 21 17:46:58 2019 @author: pan """ #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jul 28 16:28:46 2018 @author: pan """ from time import time import numpy as np import pandas as pd from sklearn import svm from sklearn.model_select...
Python
zaydzuhri_stack_edu_python
function __unicode__ self begin return name end function
def __unicode__(self): return self.name
Python
nomic_cornstack_python_v1