code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
while true begin set palavra = input string Digite uma palavra: if upper palavra == string SAIR begin break end print string A palavra '%s' tem %d caracteres % tuple palavra length palavra end
while True: palavra = input('Digite uma palavra: ') if palavra.upper() == 'SAIR': break print("A palavra '%s' tem %d caracteres" % (palavra, len(palavra)))
Python
zaydzuhri_stack_edu_python
comment Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of S. comment Example : comment Input: comment S = "abcde" comment words = ["a", "bb", "acd", "ace"] comment Output: 3 comment Explanation: There are three words in words that are a subsequence of S: "a", "acd", "a...
# Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of S. # Example : # Input: # S = "abcde" # words = ["a", "bb", "acd", "ace"] # Output: 3 # Explanation: There are three words in words that are a subsequence of S: "a", "acd", "ace". import sys def numMatchingSubseq(S,...
Python
zaydzuhri_stack_edu_python
import argparse import re import collections set COUNT_UNIT_STATISTIC = 10 function load_data filepath begin with open filepath string rt encoding=string utf8 as file_with_text begin return read file_with_text end end function function get_most_frequent_words text_study begin set word_pattern = string [\w\-]+ set words...
import argparse import re import collections COUNT_UNIT_STATISTIC = 10 def load_data(filepath): with open(filepath, 'rt', encoding='utf8') as file_with_text: return file_with_text.read() def get_most_frequent_words(text_study): word_pattern = r'[\w\-]+' words_all = re.findall(word_pattern, text...
Python
zaydzuhri_stack_edu_python
function get_field_schema self value schemas **kwargs begin set keys = get kwargs string keys GET_SCHEMA_KEYS set search = strip lower value for schema in schemas begin if not get schema string selectable begin continue end for key in keys begin if search == lower schema at key begin return schema end end end set msg =...
def get_field_schema(self, value, schemas, **kwargs): keys = kwargs.get("keys", GET_SCHEMA_KEYS) search = value.lower().strip() for schema in schemas: if not schema.get("selectable"): continue for key in keys: if search == schema[key].low...
Python
nomic_cornstack_python_v1
function meanTemplateEig self figsize begin set snIb = call readtemplate string Ib set snIc = call readtemplate string Ic set snIIb = call readtemplate string IIb set snIcBL = call readtemplate string IcBL set tuple f axs = call subplots 2 2 figsize=figsize sharex=true sharey=true call subplots_adjust hspace=0.05 wspac...
def meanTemplateEig(self, figsize): snIb = readtemplate('Ib') snIc = readtemplate('Ic') snIIb = readtemplate('IIb') snIcBL = readtemplate('IcBL') f, axs = plt.subplots(2,2,figsize=figsize, sharex=True, sharey=True) plt.subplots_adjust(hspace=0.05, wspace=0.05) axs...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Thu Jul 19 16:32:57 2018 @author: Lhnet import matplotlib.pyplot as plt import numpy as np set n = randn 100000 set tuple fig axes = call subplots 1 2 figsize=tuple 12 4 histogram n call set_title string Default histogram call set_xlim tuple min n max n histogram n cumula...
# -*- coding: utf-8 -*- """ Created on Thu Jul 19 16:32:57 2018 @author: Lhnet """ import matplotlib.pyplot as plt import numpy as np n = np.random.randn(100000) fig, axes = plt.subplots(1, 2, figsize=(12,4)) axes[0].hist(n) axes[0].set_title("Default histogram") axes[0].set_xlim((min(n), max(n))) axes[1].hist(n, c...
Python
zaydzuhri_stack_edu_python
function prior_min_field field_name field_value begin set name = field_name set value = copy field_value update value dict string label string Min ; string required false return tuple name + string _min value end function
def prior_min_field(field_name, field_value): name = field_name value = field_value.copy() value.update({ 'label': 'Min', 'required': False, }) return name + '_min', value
Python
nomic_cornstack_python_v1
function create_pidfile self begin set pidfile = config at string rnmsd_pid_file set piddir = directory name path pidfile if not is directory path piddir begin error string Exiting, pidfile directory %s doesn't exist piddir exit 1 return end try begin set pf = call file pidfile set pid = integer strip read pf close pf ...
def create_pidfile(self): pidfile = config['rnmsd_pid_file'] piddir = os.path.dirname(pidfile) if not os.path.isdir(piddir): self.log.error( 'Exiting, pidfile directory %s doesn\'t exist', piddir) sys.exit(1) return try:...
Python
nomic_cornstack_python_v1
string Defines all database tables for the `data` django app import re from django.db import models class DataType extends Model begin string Defines db table for `DataType`s comment e.g. VARCHAR, MEASURE, INT etc set name = call CharField max_length=140 unique=true comment pylint: disable=signature-differs function sa...
''' Defines all database tables for the `data` django app ''' import re from django.db import models class DataType(models.Model): ''' Defines db table for `DataType`s ''' name = models.CharField(max_length=140, unique=True) # e.g. VARCHAR, MEASURE, INT etc def save(self, *args, **kwargs): # ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- from django.db import models from django_cache.cache.cache_decorator import * set __author__ = string Zhangxiaofan class BaseDao extends object begin function __init__ self model begin set model = model end function decorator call cache_set function cache_add s...
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.db import models from django_cache.cache.cache_decorator import * __author__ = 'Zhangxiaofan' class BaseDao(object): def __init__(self, model): self.model = model @cache_set() def cache_add(self, model): """ 插入缓存中 ...
Python
zaydzuhri_stack_edu_python
function __init__ self examples model show_progress_bar=none begin if show_progress_bar is none begin set show_progress_bar = call getEffectiveLevel == INFO or call getEffectiveLevel == DEBUG end set show_progress_bar = show_progress_bar call convert_input_examples examples model end function
def __init__(self, examples: List[InputExample], model: SentenceTransformer, show_progress_bar: bool = None): if show_progress_bar is None: show_progress_bar = (logging.getLogger().getEffectiveLevel() == logging.INFO or logging.getLogger().getEffectiveLevel() == logging.DEBUG) self.show_prog...
Python
nomic_cornstack_python_v1
function getNotifications self begin return targets end function
def getNotifications(self): return self.data.notifications.targets
Python
nomic_cornstack_python_v1
for k in vet begin append res count a k end set ok = true set um = false for l in res begin if l and um or l > 1 begin set ok = false end else if l begin set um = true end end if ok and um begin print string YES end else begin print string NO end
for k in vet: res.append(a.count(k)) ok = True um = False for l in res: if((l and um) or (l > 1)): ok = False elif(l): um = True if(ok and um): print("YES") else: print("NO")
Python
zaydzuhri_stack_edu_python
import time from gpio.Buzzer import ActiveBuzzer from gpio.Pcf8591 import Pcf8591 from gpio.RgbLed import RgbLed class Gas begin function __init__ self pcf8591 ain begin set __pcf8591 = pcf8591 set __ain = ain set buzzer = call ActiveBuzzer 35 set rgbLed = call RgbLed redpin=16 end function function read self begin set...
import time from gpio.Buzzer import ActiveBuzzer from gpio.Pcf8591 import Pcf8591 from gpio.RgbLed import RgbLed class Gas: def __init__(self, pcf8591, ain): self.__pcf8591 = pcf8591 self.__ain = ain self.buzzer = ActiveBuzzer(35) self.rgbLed = RgbLed(redpin=16) def read(self...
Python
zaydzuhri_stack_edu_python
function get self begin debug string Request: { request } try begin comment Read from the database debug string Retrieving all picklist values... set all_picklists = call scan comment Convert each record to a dictionary, compile into a list set output = list for picklist in all_picklists begin append output call to_di...
def get(self) -> json: logger.debug(f"Request: {request}") try: # Read from the database logger.debug("Retrieving all picklist values...") all_picklists = Picklist.scan() # Convert each record to a dictionary, compile into a list output = [] ...
Python
nomic_cornstack_python_v1
function initial_concentration self begin return initial_value / 1000.0 * N_a end function
def initial_concentration(self): return self.initial_value / 1000.0 * N_a
Python
nomic_cornstack_python_v1
function search_in_help self topic begin set key_lower = lower topic if key_lower == string args begin call print_help_text docs_args_text end else if key_lower == string sort begin call print_help_text docs_sort_text end else if key_lower == string groups begin call print_help_text docs_groups_text end else if key_low...
def search_in_help(self, topic: str): key_lower = topic.lower() if key_lower == 'args': self.print_help_text(docs_args_text) elif key_lower == 'sort': self.print_help_text(docs_sort_text) elif key_lower == 'groups': self.print_help_text(docs_groups_tex...
Python
nomic_cornstack_python_v1
function encode n minlen=1 charset=CHARSET_DEFAULT begin set chs = list while n > 0 begin set r = n % BASE set n = n // BASE append chs charset at r end if length chs > 0 begin reverse chs end else begin append chs string 0 end set s = join string chs set s = charset at 0 * max minlen - length s 0 + s return s end fu...
def encode(n, minlen=1, charset=CHARSET_DEFAULT): chs = [] while n > 0: r = n % BASE n //= BASE chs.append(charset[r]) if len(chs) > 0: chs.reverse() else: chs.append('0') s = ''.join(chs) s = charset[0] * max(minlen - len(s), 0) + s return s
Python
nomic_cornstack_python_v1
function test_no_exceptions self begin set t = thread target=start start t call put_inbox call dummy_envelope sleep 1 assert handler_called >= 2 end function
def test_no_exceptions(self) -> None: t = Thread(target=self.aea.start) t.start() self.aea_tool.put_inbox(self.aea_tool.dummy_envelope()) time.sleep(1) assert self.handler_called >= 2
Python
nomic_cornstack_python_v1
while p <= n begin set is_prime = true for i in range 2 p begin if p % i == 0 begin set is_prime = false break end end if is_prime is true begin print p end set p = p + 1 end
while p <= n: is_prime = True for i in range(2, p): if p % i == 0: is_prime = False break if (is_prime is True): print(p) p = p + 1
Python
zaydzuhri_stack_edu_python
import argparse from trainer import train from processor import process function output_result final_data output_file begin with open output_file string w as file begin for tuple word wf in final_data begin print strip format string {} {} word wf or string file=file end end end function function main training_dir test_...
import argparse from trainer import train from processor import process def output_result(final_data, output_file): with open(output_file, 'w') as file: for (word, wf) in final_data: print('{} {}'.format(word, wf or '').strip(), file=file) def main(training_dir, test_file, output_file): p...
Python
zaydzuhri_stack_edu_python
function forward self x begin set pre_activation = matrix multiply x + unsqueeze clone _bias 0 return pre_activation end function
def forward(self, x): pre_activation = self._weights.t().matmul(x) + self._bias.clone().unsqueeze(0) return pre_activation
Python
nomic_cornstack_python_v1
function binary_to_seq begin set tuple bin_seq dico_binary comp_seq file_comp = call utf8_to_binary comment for each binary value associate the corresponding letter (key) comment according to the dictionnary set dna_seq = string set reading_binary = string for value in bin_seq begin set reading_binary = reading_binar...
def binary_to_seq(): bin_seq, dico_binary, comp_seq, file_comp = utf8_to_binary() #for each binary value associate the corresponding letter (key) #according to the dictionnary dna_seq = "" reading_binary = "" for value in bin_seq: reading_binary += value for letter, code i...
Python
nomic_cornstack_python_v1
string Nodige imports import hashlib import requests import time string Variabelen set ts = time set public_key = string private set private_key = string public set name = input string Character name: function hash_params begin string Functie voor md5 hash voor api key + tijdstip set hash_md5 = md5 update hash_md5 enco...
"""Nodige imports""" import hashlib import requests import time """Variabelen""" ts = time.time() public_key = 'private' private_key = 'public' name = input("Character name: ") def hash_params(): """ Functie voor md5 hash voor api key + tijdstip """ hash_md5 = hashlib.md5() hash_md5.upda...
Python
zaydzuhri_stack_edu_python
function _is_dynamic self begin return call pn_terminus_is_dynamic _impl end function
def _is_dynamic(self): return pn_terminus_is_dynamic(self._impl)
Python
nomic_cornstack_python_v1
function get_e_log_perturbation log_phi stick_propn_mean stick_propn_info gh_loc gh_weights sum_vector=true begin set e_perturbation_vec = call get_e_fun_normal stick_propn_mean stick_propn_info gh_loc gh_weights log_phi if sum_vector begin return sum e_perturbation_vec end else begin return e_perturbation_vec end end ...
def get_e_log_perturbation(log_phi, stick_propn_mean, stick_propn_info, gh_loc, gh_weights, sum_vector=True): e_perturbation_vec = get_e_fun_normal( stick_propn_mean, stick_propn_info, gh_loc, gh_weights, log_phi) if sum_vector...
Python
nomic_cornstack_python_v1
function sol_4 mat begin set tuple ans ind n = tuple - 1 length mat at 0 - 1 length mat for i in range n begin set j = ind while j >= 0 and mat at i at j begin set j = j - 1 end if ind > j begin set ind = j set ans = i end end return ans end function
def sol_4(mat: list) -> int: ans, ind, n = -1, len(mat[0])-1, len(mat) for i in range(n): j = ind while j >= 0 and mat[i][j]: j -= 1 if ind > j: ind = j ans = i return ans
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding: utf-8 comment In[ ]: set total = 0 while true begin set coin = integer input string Enter a coin! if coin == - 1 begin break end else if coin == 10 or coin == 25 or coin == 50 begin set total = total + coin end else begin print string Please enter a valid coin value! end end...
#!/usr/bin/env python # coding: utf-8 # In[ ]: total = 0 while(True): coin = int(input("Enter a coin! ")) if coin == -1: break elif (coin == 10) or (coin == 25) or (coin == 50): total += coin else: print("Please enter a valid coin value!") # Use while loop to let user enter a...
Python
zaydzuhri_stack_edu_python
import copy from typing import List class Solution begin function trap self heights begin set p1 = 0 set p2 = length heights - 1 set maxL = 0 set maxR = 0 set area_total = 0 while p1 != p2 begin comment A = 1 * (min(maxL, maxR) - heights[i]) set height_in_p1 = heights at p1 set height_in_p2 = heights at p2 comment upda...
import copy from typing import List class Solution: def trap(self, heights: List): p1 = 0 p2 = len(heights) - 1 maxL = 0 maxR = 0 area_total = 0 while p1 != p2: # A = 1 * (min(maxL, maxR) - heights[i]) height_in_p1 = heights[p1] he...
Python
zaydzuhri_stack_edu_python
comment -*- coding:utf-8 -*- from task.ITaskEditorDisplayableObject import * from util.util import adaptTextColor class AbstractSchedulableObject extends ITaskEditorDisplayableObject begin string Classe permettant la généralisation de Task et Group. function __init__ self nom periode desc=string color=string white id=...
# -*- coding:utf-8 -*- from .task.ITaskEditorDisplayableObject import * from util.util import adaptTextColor class AbstractSchedulableObject(ITaskEditorDisplayableObject): """ Classe permettant la généralisation de Task et Group. """ def __init__(self, nom, periode, desc="", color="white", id...
Python
zaydzuhri_stack_edu_python
string Action handler of get request; from django.db.models import Q from django.core.exceptions import ObjectDoesNotExist from spec.exception import InputDataServerException from book.models import Book function get_q object_name arg search_type=string begin string Makes Q object for 'object_name' with search type fro...
'''Action handler of get request;''' from django.db.models import Q from django.core.exceptions import ObjectDoesNotExist from spec.exception import InputDataServerException from book.models import Book def get_q(object_name, arg, search_type=''): "Makes Q object for 'object_name' with search type from 'search_...
Python
zaydzuhri_stack_edu_python
function getAllPlaylist self begin set tuple data _ = call _fetch string playlists return call depaginate data end function
def getAllPlaylist(self): data, _ = self._fetch('playlists') return self.depaginate(data)
Python
nomic_cornstack_python_v1
function _export_table table fname begin string Export DataFrame to .csv import os.path as op set extension = call splitext lower fname at 1 if extension == string begin set fname = fname + string .csv end to csv table fname index=none sep=string , encoding=string utf-8 float_format=string %.4f decimal=string . end fu...
def _export_table(table, fname): """Export DataFrame to .csv""" import os.path as op extension = op.splitext(fname.lower())[1] if extension == '': fname = fname + '.csv' table.to_csv(fname, index=None, sep=',', encoding='utf-8', float_format='%.4f', decimal='.')
Python
jtatman_500k
import nuke import re comment this is a test text
import nuke import re # this is a test text
Python
zaydzuhri_stack_edu_python
import gym from gym import spaces import numpy as np
import gym from gym import spaces import numpy as np
Python
iamtarun_python_18k_alpaca
function is_invalidated self begin if status == string invalidated begin return true end return false end function
def is_invalidated(self): if self.status == "invalidated": return True return False
Python
nomic_cornstack_python_v1
function calculateCircleArea radius begin set MAX_RADIUS = 10 ^ 9 set ROUNDING_FACTOR = 0.5 set radius_squared = radius * radius set area = radius_squared * 4 set rounded_area = integer area + ROUNDING_FACTOR if rounded_area > MAX_RADIUS * 4 begin return MAX_RADIUS * 4 end else begin return rounded_area end end functio...
def calculateCircleArea(radius): MAX_RADIUS = 10 ** 9 ROUNDING_FACTOR = 0.5 radius_squared = radius * radius area = radius_squared * 4 rounded_area = int(area + ROUNDING_FACTOR) if rounded_area > MAX_RADIUS * 4: return MAX_RADIUS * 4 else: return rounded_area
Python
jtatman_500k
function kmeans2 begin pass end function
def kmeans2(): pass
Python
nomic_cornstack_python_v1
function runner begin return call CliRunner end function
def runner() -> CliRunner: return CliRunner()
Python
nomic_cornstack_python_v1
function fit_rois self M ROIs begin set tuple X y = call _fit_rois M ROIs fit call super HyperKNeighborsClassifier self X y end function
def fit_rois(self, M, ROIs): X, y = self._fit_rois(M, ROIs) super(HyperKNeighborsClassifier, self).fit(X, y)
Python
nomic_cornstack_python_v1
import tensorflow as tf from detect_function import * from config import * comment tf.enable_eager_execution() import os set environ at string CUDA_VISIBLE_DEVICES = string 0 set B1 = call constant list list list list 3 5 3 6 dtype=float32 name=string box1 set B2 = call constant list list list list 5 6 3 6 dtype=float3...
import tensorflow as tf from detect_function import * from config import * # tf.enable_eager_execution() import os os.environ["CUDA_VISIBLE_DEVICES"] = "0" B1 = tf.constant([[[[3, 5, 3, 6]]]], dtype=tf.float32, name='box1') B2 = tf.constant([[[[5, 6, 3, 6]]]], dtype=tf.float32, name='box2') IoU = YOLOv3_detection(anch...
Python
zaydzuhri_stack_edu_python
function source_change_tunein_can_interrupt_other_source_playback self begin comment prepare play queue with one radio station set tunein_play_ids = call add_stations_to_play_queue 1 call _tunein_station_play_and_verify tunein_play_ids at 0 call _deezer_track_add_play_and_verify call _tunein_station_play_and_verify tun...
def source_change_tunein_can_interrupt_other_source_playback(self): # prepare play queue with one radio station tunein_play_ids = self._tunein_client.add_stations_to_play_queue(1) self._tunein_station_play_and_verify(tunein_play_ids[0]) self._deezer_track_add_play_and_verify() self._tunein_statio...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- comment @author: hz_company comment @license: (C) Copyright 2016-2019, Node Supply Chain Manager Corporation Limited. comment @software: PyCharm comment @file: read_model.py comment @time: 2019/4/10 11:56 comment @Software: PyCharm comment @Site : comment @desc: import os import yaml impor...
# -*- coding: utf-8 -*- # @author: hz_company # @license: (C) Copyright 2016-2019, Node Supply Chain Manager Corporation Limited. # @software: PyCharm # @file: read_model.py # @time: 2019/4/10 11:56 # @Software: PyCharm # @Site : # @desc: import os import yaml import configparser class ReadModelIni(object): ...
Python
zaydzuhri_stack_edu_python
function hours_known self begin if all begin return true end else begin return false end end function
def hours_known(self): if self.schedules.all(): return True else: return False
Python
nomic_cornstack_python_v1
function my_function arg begin comment write the body of your function here set ind = list end function class FibClass extends object begin function __init__ self begin comment dict creation set memo = dict end function function fib self n begin if n < 0 begin raise ValueError end if n in memo begin return memo at n ...
def my_function(arg): # write the body of your function here ind=[]; class FibClass(object): def __init__(self): self.memo = {}; #dict creation def fib(self,n): if n<0: raise ValueError; if n in self.memo: return self.memo[n]; elif n==0: result = 0; e...
Python
zaydzuhri_stack_edu_python
comment P01: Two Sum comment difficulty: E string Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. class Solution begin function twoSum self nums target be...
# P01: Two Sum # difficulty: E """ Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. """ class Solution: def twoSum(self, nums: [int], target: int) -...
Python
zaydzuhri_stack_edu_python
function splitOnIndex examples attribute index begin set midValue = examples at index at attribute + examples at index + 1 at attribute / 2 set tuple greater lesser = tuple list list for i in range length examples begin if examples at i at attribute > midValue begin append greater examples at i end else begin append le...
def splitOnIndex(examples, attribute, index): midValue = (examples[index][attribute] + examples[index + 1][attribute]) / 2 greater, lesser = list(), list() for i in range(len(examples)): if examples[i][attribute] > midValue: greater.append(examples[i]) else: le...
Python
nomic_cornstack_python_v1
function reconnect_conservative trajs locs locs_array max_blinks=0 frame_interval=0.00548 pixel_size_um=0.16 **kwargs begin set out = list comment A single localization and trajectory pair - assignment comment is unambiguous. This is the only situation where reconnection comment is allowed. set n_trajs = length trajs ...
def reconnect_conservative(trajs, locs, locs_array, max_blinks=0, frame_interval=0.00548, pixel_size_um=0.16, **kwargs): out = [] # A single localization and trajectory pair - assignment # is unambiguous. This is the only situation where reconnection # is allowed. n_trajs = len(trajs) n_loc...
Python
nomic_cornstack_python_v1
import json import csv comment JSON object set json_object = string { "users": [ { "Name": "John", "Age": 28, "Email": "john@example.com" }, { "Name": "Alice", "Age": 24, "Email": "alice@example.com" }, { "Name": "Bob", "Age": 32 }, { "Name": "Eve" } ] } try begin comment Parse JSON object set data = loads json_object ...
import json import csv # JSON object json_object = ''' { "users": [ { "Name": "John", "Age": 28, "Email": "john@example.com" }, { "Name": "Alice", "Age": 24, "Email": "alice@example.com" }, { "Name": "Bob", "Age": 32 }, { "Name": "Eve"...
Python
jtatman_500k
import sys import cv2 import matplotlib.pyplot as plt import numpy as np import requests function get_word word begin set key = string b28515ae-24a1-4796-be7c-e5cda4b47014 set URL = string https://www.dictionaryapi.com/api/v3/references/sd2/json/ set URL = URL + word + string ? set URL = URL + key set PARAMS = dict str...
import sys import cv2 import matplotlib.pyplot as plt import numpy as np import requests def get_word(word): key = 'b28515ae-24a1-4796-be7c-e5cda4b47014' URL = 'https://www.dictionaryapi.com/api/v3/references/sd2/json/' URL += word + '?' URL += key PARAMS = {'word': word,'key': key} r = reque...
Python
zaydzuhri_stack_edu_python
import numpy as np import Outliers as OT string Volatility Bucketing Given a matrix lr, shape of n, m, choose a sebset in the m columns so that the det(R) is minimized, where R is the qr decomposition of the given lr. This is is used to pick the trigger time of strategy in MTS, especially when the look back is long rel...
import numpy as np import Outliers as OT """ Volatility Bucketing Given a matrix lr, shape of n, m, choose a sebset in the m columns so that the det(R) is minimized, where R is the qr decomposition of the given lr. This is is used to pick the trigger time of strategy in MTS, especially when the look back is long r...
Python
zaydzuhri_stack_edu_python
from main import db class PayrollModel extends Model begin set __tablename__ = string payrolls set id = call Column Integer primary=true set gross_salary = call Column Float set net_salary = call Column Float set PAYE = call Column Float set NHIF = call Column Float set NSSF = call Column Float set employee_id = call C...
from main import db class PayrollModel(db.Model): __tablename__ = 'payrolls' id = db.Column(db.Integer, primary=True) gross_salary = db.Column(db.Float) net_salary = db.Column(db.Float) PAYE = db.Column(db.Float) NHIF = db.Column(db.Float) NSSF = db.Column(db.Float) employee_id = db.Co...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Sat Feb 16 10:47:23 2019 @author: Ruman import pandas as pd import numpy as np from sklearn.linear_model import Lasso , LinearRegression , LogisticRegression from sklearn.model_selection import train_test_split from scipy.stats import uniform...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Feb 16 10:47:23 2019 @author: Ruman """ import pandas as pd import numpy as np from sklearn.linear_model import Lasso, LinearRegression, LogisticRegression from sklearn.model_selection import train_test_split from scipy.stats import uniform as sp_rand ...
Python
zaydzuhri_stack_edu_python
comment Use a while loop to take numbers from a user until they give a "q" while true begin set user_input = input string Enter a number to add or q to finish: if user_input == string q begin break end else begin set total = total + integer user_input end end comment Print the total out print string The sum is: total
# Use a while loop to take numbers from a user until they give a "q" while True: user_input = input("Enter a number to add or q to finish: ") if user_input == "q": break else: total += int(user_input) # Print the total out print("The sum is:", total)
Python
zaydzuhri_stack_edu_python
function drop_tables begin set table_names = list comprehension l at 0 for l in rows for table_name in table_names begin call execute_sql format string DROP TABLE {}; table_name end end function
def drop_tables(): table_names = [l[0] for l in execute_sql("""SELECT name FROM sqlite_master WHERE type='table';""").rows] for table_name in table_names: execute_sql("""DROP TABLE {};""".format(table_name))
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment -*- coding: utf-8 -*- from sys import exit comment Handel room goes to Bach or death.
#!/usr/bin/python # -*- coding: utf-8 -*- from sys import exit #Handel room goes to Bach or death.
Python
zaydzuhri_stack_edu_python
function add_monster begin function print_monsters_database begin string Print the Monsters database so the user knows what monsters or characters have been added set monsters = select Monsters clear print GREEN + string * * 80 print string + BRIGHT + string Monsters Database print string + DIM + string (Monsters in ...
def add_monster(): def print_monsters_database(): """Print the Monsters database so the user knows what monsters or characters have been added""" monsters = Monsters.select() clear() print(Fore.GREEN + "*" * 80) print("\t\t\t" + Style.BRIGHT + "Monsters Database") pr...
Python
nomic_cornstack_python_v1
function get_radius self times begin return call projected_radius times end function
def get_radius(self, times): return self._backend.projected_radius(times)
Python
nomic_cornstack_python_v1
function initialize self widget=widget size=size position=position autodestruct=autodestruct begin call set_autodestruct autodestruct comment default widget if widget is none begin set widget = call GalryWidget end comment if widget is not an instance of GalryWidget, maybe it's a class, comment then try to instanciate ...
def initialize(self, widget=widget, size=size, position=position, autodestruct=autodestruct): self.set_autodestruct(autodestruct) # default widget if widget is None: widget = GalryWidget() # if widget is not an instance of GalryWidge...
Python
nomic_cornstack_python_v1
string Uma empresa vende o mesmo produto para quatro diferentes estados. Cada estado possui uma taxa diferente de imposto sobre o produto (MG 7%; SP 12%; RJ 15%; MS 8%). Faça um programa em que o usuário entre com o valor e o estado de destino do produto e o programa retorne o preço final do produto acrecido do imposto...
""" Uma empresa vende o mesmo produto para quatro diferentes estados. Cada estado possui uma taxa diferente de imposto sobre o produto (MG 7%; SP 12%; RJ 15%; MS 8%). Faça um programa em que o usuário entre com o valor e o estado de destino do produto e o programa retorne o preço final do produto acrecido do imposto do...
Python
zaydzuhri_stack_edu_python
function set_attr self name values axis=0 dtype=none begin string **DEPRECATED** - Use `ds.ra.key = values` or `ds.ca.key = values` instead call deprecated string 'set_attr' is deprecated. Use 'ds.ra.key = values' or 'ds.ca.key = values' instead if axis == 0 begin set ra at name = values end else begin set ca at name =...
def set_attr(self, name: str, values: np.ndarray, axis: int = 0, dtype: str = None) -> None: """ **DEPRECATED** - Use `ds.ra.key = values` or `ds.ca.key = values` instead """ deprecated("'set_attr' is deprecated. Use 'ds.ra.key = values' or 'ds.ca.key = values' instead") if axis == 0: self.ra[name] = value...
Python
jtatman_500k
function set_camera_parameters self camera_parameters begin for key in camera_parameters begin if not key in camera_parameters begin raise call KeyError string The specified property keys are not valid + string Valid keys are: + string camera_parameters end set camera_parameters at key = camera_parameters at key end se...
def set_camera_parameters(self, camera_parameters: Dict): for key in camera_parameters: if not key in self.camera_parameters: raise KeyError("The specified property keys are not valid" + " Valid keys are: "+str(self.camera_parameters)) ...
Python
nomic_cornstack_python_v1
from socket import * set severPort = 12000 set severSocket = call socket AF_INET SOCK_DGRAM call bind tuple string severPort print string The sever is ready to receive while true begin set tuple message clientAddress = call recvfrom 2048 set modifiedMessage = upper decode message call sendto encode modifiedMessage cli...
from socket import * severPort = 12000 severSocket = socket(AF_INET,SOCK_DGRAM) severSocket.bind(('',severPort)) print("The sever is ready to receive") while True: message ,clientAddress = severSocket.recvfrom(2048) modifiedMessage = message.decode().upper() severSocket.sendto(modifiedMessage.encode(),clientAddre...
Python
zaydzuhri_stack_edu_python
function run self begin try begin with signal_handler begin while call should_run begin call advance if reloader begin call reloader end end end end except Exception begin pass end end function
def run(self): try: with self.graph.signal_handler: while self.should_run(): self.advance() if self.reloader: self.reloader() except Exception: pass
Python
nomic_cornstack_python_v1
function initialize self request begin if type request == NoneType begin comment Set some defaults for name in attributeNames begin set attributes at name = string Unknown end set attributes at string CreationTime = string call dateTime set attributes at string Status = string New set result = call getProxyInfo if resu...
def initialize( self, request ): if type( request ) == NoneType: # Set some defaults for name in self.attributeNames: self.attributes[name] = 'Unknown' self.attributes['CreationTime'] = str( Time.dateTime() ) self.attributes['Status'] = "New" result = getProxyInfo() if re...
Python
nomic_cornstack_python_v1
comment Iterative python program to reverse an array comment Function to reverse A[] from start to end function reverselist A start end begin while start < end begin set tuple A at start A at end = tuple A at end A at start set start = start + 1 set end = end - 1 end end function comment Driver function to test above f...
# Iterative python program to reverse an array # Function to reverse A[] from start to end def reverselist(A,start,end): while start < end: A[start],A[end] = A[end],A[start] start += 1 end -= 1 # Driver function to test above function A = [1,2,3,4,5,6] print(A) reverselist(A,...
Python
zaydzuhri_stack_edu_python
comment This module consists of the compute_tweets function. comment The function takes two parameters, processes the tweets, and then outputs the results. import string function compute_tweets tweetsFile keywordsFile begin try begin comment Opens keywords file, avoid encoding errors set infile = open keywordsFile stri...
# This module consists of the compute_tweets function. # The function takes two parameters, processes the tweets, and then outputs the results. import string def compute_tweets(tweetsFile, keywordsFile): try: # Opens keywords file, avoid encoding errors infile = open(keywordsFile, "r", enc...
Python
zaydzuhri_stack_edu_python
function reset_login_attempts self begin set login_attempts = 0 end function
def reset_login_attempts(self): self.login_attempts = 0
Python
nomic_cornstack_python_v1
function ignore_listings name_key begin comment for blacklist_str in models_blacklist: comment if blacklist_str in name_key: comment return True return false end function
def ignore_listings(name_key): # for blacklist_str in models_blacklist: # if blacklist_str in name_key: # return True return False
Python
nomic_cornstack_python_v1
function nplm_cost_gradient parameters input output begin set tuple W U H C = parameters set context_size = length input set x = concatenate list comprehension C at input at i for i in range context_size comment Append bias term set x = append np x 1.0 set x = reshape x - 1 1 set hidden_layer = tanh dot x set y = dot x...
def nplm_cost_gradient(parameters, input, output): W, U, H, C = parameters context_size = len(input) x = np.concatenate([C[input[i]] for i in range(context_size)]) x = np.append(x, 1.) # Append bias term x = x.reshape(-1, 1) hidden_layer = np.tanh(H.dot(x)) y = W.dot(x) + U.dot(hidden_lay...
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np from matplotlib.dates import MONDAY , DateFormatter , DayLocator , WeekdayLocator from matplotlib import pyplot as plt from mpl_finance import candlestick_ohlc import matplotlib.dates as mdates from matplotlib.patches import Patch import datetime import os.path import patrones set...
import pandas as pd import numpy as np from matplotlib.dates import MONDAY, DateFormatter, DayLocator, WeekdayLocator from matplotlib import pyplot as plt from mpl_finance import candlestick_ohlc import matplotlib.dates as mdates from matplotlib.patches import Patch import datetime import os.path import patrones dir ...
Python
zaydzuhri_stack_edu_python
import requests from bs4 import BeautifulSoup as BS import json import html function beano_jokes begin set data = list set req = get requests string https://www.beano.com/categories/jokes set soup = call BS content string lxml set layer1 = find all soup string div dict string class string Shelf-tileWrap-1T8aF set base...
import requests from bs4 import BeautifulSoup as BS import json import html def beano_jokes(): data = [] req = requests.get('https://www.beano.com/categories/jokes') soup = BS(req.content,'lxml') layer1 = soup.find_all('div', {'class':'Shelf-tileWrap-1T8aF'}) base_url = 'https://www.beano.com' f...
Python
zaydzuhri_stack_edu_python
function get_field_name_from_lookup lookup begin return split lookup string __ at 0 end function
def get_field_name_from_lookup(lookup): return lookup.split("__")[0]
Python
nomic_cornstack_python_v1
from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import MultinomialNB comment Sample dataset set docs = list string The sky is blue. string Violets are red. string I love programming. string JavaScript is fun.Python is great! set labels = list 0 0 1 1 1 comment Create the vectorizer ...
from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import MultinomialNB # Sample dataset docs = [ "The sky is blue.", "Violets are red.", "I love programming.", "JavaScript is fun." "Python is great!" ] labels = [0, 0, 1, 1, 1] # Create the vectorizer vectorizer = CountVectoriz...
Python
jtatman_500k
function build_model self filtered_model_params begin set model = call XGBRegressor max_depth=filtered_model_params at string max_depth learning_rate=filtered_model_params at string learning_rate n_estimators=filtered_model_params at string n_estimators verbosity=filtered_model_params at string verbosity booster=filter...
def build_model(self, filtered_model_params: Dict) -> XGBRegressor: model = XGBRegressor( max_depth=filtered_model_params["max_depth"], learning_rate=filtered_model_params["learning_rate"], n_estimators=filtered_model_params["n_estimators"], verbosity=filtered_mod...
Python
nomic_cornstack_python_v1
function get_cleared_lines self begin return _cleared_lines end function
def get_cleared_lines(self): return self._cleared_lines
Python
nomic_cornstack_python_v1
import socket import threading set bind_ip = string 0.0.0.0 set bind_port = 9000 set server = call socket AF_INET SOCK_STREAM call bind tuple bind_ip bind_port call listen 5
import socket import threading bind_ip = "0.0.0.0" bind_port = 9000 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((bind_ip, bind_port)) server.listen(5)
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- import random from arraystack import ArrayStack from base import BaseSet set w = 32 class ChainedHashTable extends BaseSet begin function __init__ self iterrable=list begin call _initialize call add_all iterrable end function function _initialize self begin set d = 1 set t = call _alloc_ta...
# -*- coding: utf-8 -*- import random from arraystack import ArrayStack from base import BaseSet w = 32 class ChainedHashTable(BaseSet): def __init__(self, iterrable=[]): self._initialize() self.add_all(iterrable) def _initialize(self): self.d = 1 self.t = self._alloc_table(1...
Python
zaydzuhri_stack_edu_python
function getImageList chunkSize begin set imageList = list directory IMAGE_LOCATION set imageList = sorted imageList key=lambda x -> integer call splitext x at 0 set firstImageNo = integer call splitext imageList at 0 at 0 set chunkList = list imageList at 0 set totalImageInCurrentPass = 1 set expectedImageNo = firstIm...
def getImageList(chunkSize): imageList = os.listdir(IMAGE_LOCATION) imageList = sorted(imageList, key=lambda x : int(os.path.splitext(x)[0])) firstImageNo = int(os.path.splitext(imageList[0])[0]) chunkList = [imageList[0]] totalImageInCurrentPass = 1 expectedImageNo = firstImageNo...
Python
nomic_cornstack_python_v1
function get_row_text self a_index begin if size listbox >= a_index begin set a_value = get listbox a_index end else begin set a_value = none end return a_value end function
def get_row_text( self, a_index ): if self.listbox.size() >= a_index: a_value = self.listbox.get( a_index ) else: a_value = None return a_value
Python
nomic_cornstack_python_v1
function remove_node self data begin if __binarySTree is not none begin set node = search data at 0 if node is not none begin delete data delete node end end else begin print string Can't remove from an empty tree end end function
def remove_node(self, data): if self.__binarySTree is not None: node = self.__binarySTree.search(data)[0] if node is not None: self.__binarySTree.delete(data) self.__repo.delete(node) else: print("Can't remove from an empty tree")
Python
nomic_cornstack_python_v1
import os from twilio.rest import Client import gspread from oauth2client.service_account import ServiceAccountCredentials from pprint import pprint import time print string welcome to the medicine compliance program. This program helps you keep track of your medicine compliance by reminding you on your phone and gathe...
import os from twilio.rest import Client import gspread from oauth2client.service_account import ServiceAccountCredentials from pprint import pprint import time print('welcome to the medicine compliance program. \ This program helps you keep track of your medicine \ compliance by reminding you on your phone and gather...
Python
zaydzuhri_stack_edu_python
import numpy as np set benimListem = list range 10 set benimListem = array list 1 2 3 4 set benimListem = reshape array range start=0 stop=25 step=1 5 5 print benimListem at 1 at 0
import numpy as np benimListem=list(range(10)) benimListem=np.array([1,2,3,4]) benimListem=np.arange(start=0,stop=25,step=1).reshape(5,5) print(benimListem[1][0])
Python
zaydzuhri_stack_edu_python
set r = integer input string Enter radius: set Diameter = 2 * r print string Diameter = Diameter string units set Circumference = 2 * 3.1416 * r print string Circumference = Circumference string units set area = 3.1416 * r ^ 2 print string area = area string units
r = int(input("Enter radius: ")) Diameter = (2*r) print("Diameter = " , Diameter , "units") Circumference = (2*3.1416*r) print("Circumference = ", Circumference, "units") area = 3.1416*(r**2) print("area = ", area , "units")
Python
zaydzuhri_stack_edu_python
import cv2 import numpy as np set count = 1 set imgMain = call imread string /home/omar/Desktop/Omar/ImageProcceing/HW1/ImagesForHW/Fig%d.tif % count image show string sample imgMain call imwrite string sample.tif imgMain while count < 100 begin set count = count + 1 set imgTemp = call imread string /home/omar/Desktop/...
import cv2 import numpy as np count = 1 imgMain = cv2.imread('/home/omar/Desktop/Omar/ImageProcceing/HW1/ImagesForHW/Fig%d.tif'%(count)) cv2.imshow('sample',imgMain) cv2.imwrite('sample.tif',imgMain) while (count<100) : count = count + 1 imgTemp = cv2.imread('/home/omar/Desktop/Omar/ImageProcceing/HW1/Images...
Python
zaydzuhri_stack_edu_python
for file_path in files_to_process begin with open file_path string r as f begin print format string File {} ... file_path set source = read f exec source end end
for file_path in files_to_process: with open(file_path, 'r') as f: print('File {} ...'.format(file_path)) source = f.read() exec(source)
Python
zaydzuhri_stack_edu_python
function load_config self config_file begin with open config_file string r as config_file begin update _shared_state call encode_user_data call convert_to_attribute_dict call safe_load config_file end end function
def load_config(self, config_file: str) -> None: with open(config_file, "r") as config_file: self._shared_state.update( encode_user_data(convert_to_attribute_dict(yaml.safe_load(config_file))) )
Python
nomic_cornstack_python_v1
function calculation element symmetry experiment edge begin return call Calculation element symmetry experiment edge end function
def calculation(element, symmetry, experiment, edge): return Calculation(element, symmetry, experiment, edge)
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 comment needed for floating point division in python2 from __future__ import division from sunrise import sun from datetime import date , datetime , time , timedelta set ct_lookup = list 2000 2300 2600 2900 3300 3800 4300 4600 4700 4800 4900 5000 5050 5100 5200 5300 5400 5500 5500 5500 functio...
#!/usr/bin/python3 # from __future__ import division # needed for floating point division in python2 from sunrise import sun from datetime import date,datetime,time,timedelta ct_lookup = [2000, 2300, 2600, 2900, 3300, 3800, 4300, 4600, 4700, 4800, 4900, 5000, 5050, 5100, 5200, 5300, 5400, 5500, 5500, 5500] def colort...
Python
zaydzuhri_stack_edu_python
import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input , Output , ClientsideFunction import dash_bootstrap_components as dbc import plotly.express as px import plotly.graph_objects as go import numpy as np import pandas as pd import json set tuple CENTER_L...
import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output, ClientsideFunction import dash_bootstrap_components as dbc import plotly.express as px import plotly.graph_objects as go import numpy as np import pandas as pd import json CENTER_LAT, CENTER_...
Python
zaydzuhri_stack_edu_python
function resetDirtyBlocks self begin raise call NotImplemented end function
def resetDirtyBlocks(self): raise (NotImplemented())
Python
nomic_cornstack_python_v1
comment Stack as Linked List class Node begin function __init__ self val=none begin set data = val set next = none end function end class class Stack begin function __init__ self root=none begin set root = none end function function push self item begin set item = call Node item set next = root set root = item return r...
#Stack as Linked List class Node: def __init__(self,val=None): self.data=val self.next=None class Stack: def __init__(self,root=None): self.root=None def push(self,item): item=Node(item) item.next=self.root self.root=item return self.root ...
Python
zaydzuhri_stack_edu_python
from django.shortcuts import render , redirect from django.contrib import messages from django.templatetags.static import static comment Importing Google spreadsheets aka Airtable DB on steroids ... from airtable import Airtable comment Importing os to handle environment variables import os from pprint import pprint co...
from django.shortcuts import render, redirect from django.contrib import messages from django.templatetags.static import static # Importing Google spreadsheets aka Airtable DB on steroids ... from airtable import Airtable # Importing os to handle environment variables import os from pprint import pprint # Airtable con...
Python
zaydzuhri_stack_edu_python
function test_102_keystone_ldap_group_membership self begin set application_name = string keystone-ldap set intended_cfg = call _get_ldap_config set tuple current_cfg non_string_cfg = call config_current_separate_non_string_type_keys non_string_type_keys intended_cfg application_name with call config_change dict non_s...
def test_102_keystone_ldap_group_membership(self): application_name = 'keystone-ldap' intended_cfg = self._get_ldap_config() current_cfg, non_string_cfg = ( self.config_current_separate_non_string_type_keys( self.non_string_type_keys, intended_cfg, application_name) ...
Python
nomic_cornstack_python_v1
from build_array import Solution function test_solution begin set s = call Solution set nums = list 0 2 1 5 3 4 set expected_result = list 0 1 2 4 5 3 set ret = call buildArray nums assert ret == expected_result set nums = list 5 0 1 2 3 4 set expected_result = list 4 5 0 1 2 3 set ret = call buildArray nums assert ret...
from build_array import Solution def test_solution(): s = Solution() nums = [0, 2, 1, 5, 3, 4] expected_result = [0,1,2,4,5,3] ret = s.buildArray(nums) assert ret == expected_result nums = [5,0,1,2,3,4] expected_result = [4,5,0,1,2,3] ret = s.buildArray(nums) assert ret == e...
Python
zaydzuhri_stack_edu_python
function __init__ self begin call __init__ self set _parameterNode = none set postopProgrammingInstance = none set FrameAutoDetect = false end function
def __init__(self): ScriptedLoadableModuleLogic.__init__(self) self._parameterNode = None self.postopProgrammingInstance = None self.FrameAutoDetect = False
Python
nomic_cornstack_python_v1
string Your task is to construct a building which will be a pile of n cubes. The cube at the bottom will have a volume of n^3, the cube above will have volume of (n-1)^3 and so on until the top which will have a volume of 1^3. You are given the total volume m of the building. Being given m can you find the number n of ...
"""Your task is to construct a building which will be a pile of n cubes. The cube at the bottom will have a volume of n^3, the cube above will have volume of (n-1)^3 and so on until the top which will have a volume of 1^3. You are given the total volume m of the building. Being given m can you find the number n of ...
Python
zaydzuhri_stack_edu_python
function property_group_id self begin return get pulumi self string property_group_id end function
def property_group_id(self) -> pulumi.Input[str]: return pulumi.get(self, "property_group_id")
Python
nomic_cornstack_python_v1
from selenium.webdriver import ActionChains class BasePage extends object begin function __init__ self driver begin set driver = driver end function function find_element self *loc begin return call find_element *loc end function function type_text self text *loc begin call send_keys text end function function click se...
from selenium.webdriver import ActionChains class BasePage(object): def __init__(self, driver): self.driver = driver def find_element(self, *loc): return self.driver.find_element(*loc) def type_text(self, text, *loc): self.find_element(*loc).send_keys(text) def click(self, *lo...
Python
zaydzuhri_stack_edu_python
comment Import pandas import pandas as pd comment Read the file into a DataFrame: df set df = read csv string Py_cleaning_pivot_data.csv print string ****** 01. data before pivoting ******* print df print string ****** 02. data after pivoting ******* set df_pivot = call pivot index=string name columns=string treatment ...
# Import pandas import pandas as pd # Read the file into a DataFrame: df df = pd.read_csv('Py_cleaning_pivot_data.csv') print("****** 01. data before pivoting *******") print(df) print("****** 02. data after pivoting *******") df_pivot = df.pivot(index='name',columns='treatment',values='result') print(df_pivot)
Python
zaydzuhri_stack_edu_python