code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function _systemjacuser self x0 ind=none begin set VARS = dictionary zip varslist array X at coords for tuple i par in enumerate freepars begin set parsdict at par = X at params at i end return call _userjac self VARS parsdict end function
def _systemjacuser(self, x0, ind=None): VARS = dict(zip(self.varslist, array(X)[self.coords])) for i, par in enumerate(self.freepars): self.parsdict[par] = X[self.params[i]] return self._userjac(self, VARS, self.parsdict)
Python
nomic_cornstack_python_v1
function add_nums nums begin set n_splt = split nums string , set n_int = list for i in n_splt begin append n_int integer i end return sum n_int end function
def add_nums(nums): n_splt = nums.split(",") n_int = [] for i in n_splt: n_int.append(int(i)) return sum(n_int)
Python
zaydzuhri_stack_edu_python
function get_executions_by_type self type_name begin set request = call GetExecutionsByTypeRequest set type_name = type_name set response = call GetExecutionsByTypeResponse call _call string GetExecutionsByType request response set result = list for x in executions begin append result x end return result end function
def get_executions_by_type( self, type_name: Text) -> List[metadata_store_pb2.Execution]: request = metadata_store_service_pb2.GetExecutionsByTypeRequest() request.type_name = type_name response = metadata_store_service_pb2.GetExecutionsByTypeResponse() self._call('GetExecutionsByType', request, ...
Python
nomic_cornstack_python_v1
function parse ascii_armor_message signing_key=none sender_pubkeys=none begin string Return a dict with parsed content (decrypted message, signature validation) :: { 'message': { 'fields': {}, 'content': str, }, 'signatures': [ {'pubkey': str, 'valid': bool, fields: {}} ] } :param ascii_armor_message: The Ascii Armor M...
def parse(ascii_armor_message: str, signing_key: Optional[SigningKey] = None, sender_pubkeys: Optional[List[str]] = None) -> dict: """ Return a dict with parsed content (decrypted message, signature validation) :: { 'message': { ...
Python
jtatman_500k
function avg self other weight=0.5 begin if not call _sameSize other begin return end if weight < 0.0 or weight > 1.0 begin return end set buf1 = buf * weight set buf2 = buf * 1.0 - weight set buf = as type buf1 dtype=DTYPE + as type buf2 dtype=DTYPE end function
def avg(self, other, weight=.5): if not self._sameSize(other): return if weight<0.0 or weight>1.0: return buf1 = (self.buf * weight) buf2 = (other.buf * (1.0-weight)) self.buf = buf1.astype(dtype=DTYPE) + buf2.astype(dtype=DTYPE)
Python
nomic_cornstack_python_v1
import sys import requests from bs4 import BeautifulSoup as bs set headers = dict string User-Agent string Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit 537.36 (KHTML, like Gecko) Chrome ; string Accept string text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 set userID = argv at 1...
import sys import requests from bs4 import BeautifulSoup as bs headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit 537.36 (KHTML, like Gecko) Chrome", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8" } userID = sys.argv[1] password = sys...
Python
zaydzuhri_stack_edu_python
function __init__ self bid_prices ask_prices volumes params_file=string params.yaml begin if columns != columns begin raise call ValueError string Bid price and ask price columns mismatch end if columns != columns begin raise call ValueError string Price and volumes columns mismatch end set bid_prices = bid_prices set ...
def __init__(self, bid_prices, ask_prices, volumes, params_file='params.yaml'): if bid_prices.columns != ask_prices.columns: raise ValueError('Bid price and ask price columns mismatch') if volumes.columns != bid_prices.columns: raise ValueError('Price and volumes columns mismatch...
Python
nomic_cornstack_python_v1
function comprobar_estado strvih begin if strvih == string POSITIVO or strvih == string NEGATIVO begin return string SI end else begin return string NO end end function
def comprobar_estado(strvih): if (strvih == "POSITIVO" or strvih == "NEGATIVO"): return "SI" else: return "NO"
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Spyder Editor This is a temporary script file. set n = integer input set screens = dict for i in range 0 n begin set string = input set arr = split string if arr at 0 == string add-screen begin call add_screen arr end end function add_screen arr begin set screen_name = integer arr ...
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ n = int(input()) screens = {} for i in range(0,n): string = input(); arr = string.split() if arr[0] == "add-screen": add_screen(arr) def add_screen(arr): screen_name = int(arr[1]) rows = int(arr[2]) + 1 ...
Python
zaydzuhri_stack_edu_python
function delete_nodes pks_to_delete begin from django.db import transaction from django.db.models import Q from aiida.backends.djsite.db import models from aiida.orm import load_node comment Delete also all children of the given calculations comment Here I get a set of all pks to actually delete, including comment all ...
def delete_nodes(pks_to_delete): from django.db import transaction from django.db.models import Q from aiida.backends.djsite.db import models from aiida.orm import load_node # Delete also all children of the given calculations # Here I get a set of all pks to actually delete, including # al...
Python
nomic_cornstack_python_v1
import numpy as np from scipy.stats import norm from plots import plot_scatter from plots import plot_function_values function roulette_wheel_selection probabilities begin set p = uniform 0 sum probabilities for i in range 0 length probabilities begin set p = p - probabilities at i if p <= 0 begin return i end end end ...
import numpy as np from scipy.stats import norm from plots import plot_scatter from plots import plot_function_values def roulette_wheel_selection(probabilities): p = np.random.uniform(0, sum(probabilities)) for i in range(0, len(probabilities)): p -= probabilities[i] if p <= 0: re...
Python
zaydzuhri_stack_edu_python
function plot_discontinuity self depth colormap=string tomo res=string i verbose=false begin comment - set up a map and colourmap ----------------------------------------- set m = call Basemap projection=string merc llcrnrlat=min grid_lat urcrnrlat=max grid_lat llcrnrlon=min grid_lon urcrnrlon=max grid_lon lat_ts=20 re...
def plot_discontinuity(self,depth,colormap='tomo',res='i',verbose=False): #- set up a map and colourmap ----------------------------------------- m=Basemap(projection='merc',llcrnrlat=np.min(grid_lat),urcrnrlat=np.max(grid_lat),llcrnrlon=np.min(grid_lon),urcrnrlon=np.max(grid_lon),lat_ts=20,resolution=res) ...
Python
nomic_cornstack_python_v1
function construct_stacked_matrix array begin assert ndim == 4 set a_shape = shape set filter_shape = tuple a_shape at 2 a_shape at 3 set stacked_shape = tuple a_shape at 0 * a_shape at 2 + 1 a_shape at 1 * a_shape at 3 + 1 comment logger.debug("Stacked array shape %s", stacked_shape) set stacked = zeros stacked_shape ...
def construct_stacked_matrix(array): assert(array.ndim == 4) a_shape = array.shape filter_shape = (a_shape[2], a_shape[3]) stacked_shape = (a_shape[0] * (a_shape[2] + 1), a_shape[1] * (a_shape[3] + 1)) # logger.debug("Stacked array shape %s", stacked_shape) stacked = np....
Python
nomic_cornstack_python_v1
function client_with_edgelist_csv_loaded client begin set test_data = edgelist_csv_data at string karate call load_csv_as_edge_data test_data at string csv_file_name dtypes=test_data at string dtypes vertex_col_names=list string 0 string 1 type_name=string assert call get_graph_ids == list 0 return tuple client test_da...
def client_with_edgelist_csv_loaded(client): test_data = data.edgelist_csv_data["karate"] client.load_csv_as_edge_data( test_data["csv_file_name"], dtypes=test_data["dtypes"], vertex_col_names=["0", "1"], type_name="", ) assert client.get_graph_ids() == [0] return (cl...
Python
nomic_cornstack_python_v1
class Solution extends object begin function maxProfit self prices begin string :type prices: List[int] :rtype: int if not prices begin return 0 end set buy = prices at 0 set profit = 0 for i in prices at slice 1 : : begin if i - buy > profit begin set profit = i - buy end if i < buy begin set buy = i end end return ...
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if not prices: return 0 buy = prices[0] profit = 0 for i in prices[1:]: if i-buy > profit: profit...
Python
zaydzuhri_stack_edu_python
function test_single_axis_bspline_first_derivative begin set control_points = array list tuple 0.0 0.0 0.0 tuple 1.0 0.0 0.0 set curve = call BSplineCurve control_points for parameter in linear space 0.0 1.0 num=5 begin set first_derivative = tuple parameter 0.0 0.0 call assert_allclose call first_derivative_at paramet...
def test_single_axis_bspline_first_derivative() -> None: control_points = np.array([(0.0, 0.0, 0.0), (1.0, 0.0, 0.0)]) curve = BSplineCurve(control_points) for parameter in np.linspace(0.0, 1.0, num=5): first_derivative = (parameter, 0.0, 0.0) np.testing.assert_allclose( curve.fi...
Python
nomic_cornstack_python_v1
function bootScope paths recorder begin return call finalize dict string isList call isList ; string isMap call isMap ; string isSet call isSet ; string Bool call BoolGuard ; string Bytes call BytesGuard ; string Char call CharGuard ; string Double call DoubleGuard ; string Int call IntGuard ; string Str call StrGuard ...
def bootScope(paths, recorder): return finalize({ u"isList": isList(), u"isMap": isMap(), u"isSet": isSet(), u"Bool": BoolGuard(), u"Bytes": BytesGuard(), u"Char": CharGuard(), u"Double": DoubleGuard(), u"Int": IntGuard(), u"Str": StrGuard(), ...
Python
nomic_cornstack_python_v1
function __str__ self begin return call get_string end function
def __str__(self): return self.get_string()
Python
nomic_cornstack_python_v1
from Telegram.sendmarkdown import SendMarkdown import os import pandas as pd function check_farm_summary begin set req = read popen string chia farm summary comment req = "Farming status: Farming\nTotal chia farmed: 0.0\nUser transaction fees: 0.0\nBlock rewards: 0.0\nLast height farmed: 0\nPlot count: 1\nTotal size of...
from Telegram.sendmarkdown import SendMarkdown import os import pandas as pd def check_farm_summary(): req = os.popen("chia farm summary").read() #req = "Farming status: Farming\nTotal chia farmed: 0.0\nUser transaction fees: 0.0\nBlock rewards: 0.0\nLast height farmed: 0\nPlot count: 1\nTotal size of plots: 1...
Python
zaydzuhri_stack_edu_python
comment def longest_word(filename): comment file= open(filename, 'r') comment words = file.read().split() comment max_len = len(max(words, key=len)) comment return [word for word in words if len(word) == max_len] comment print(longest_word('read write.txt')) function file_lengthy fname begin with open fname as f begin ...
# def longest_word(filename): # file= open(filename, 'r') # words = file.read().split() # max_len = len(max(words, key=len)) # return [word for word in words if len(word) == max_len] # # print(longest_word('read write.txt')) def file_lengthy(fname): with open( fname ) as f: f...
Python
zaydzuhri_stack_edu_python
function add_ambiguous_request db_session new_request_url begin set tuple new_ambiguous is_new = call db_get_or_create db_session AmbiguousRequest request=new_request_url if is_new begin commit db_session call out severity=INFO return new_ambiguous end else begin call out severity=INFO return none end end function
def add_ambiguous_request(db_session, new_request_url: str) -> Optional[AmbiguousRequest]: new_ambiguous, is_new = db_get_or_create(db_session, AmbiguousRequest, request=new_request_url) if is_new: db_session.commit() Logger() \ .event(category="database", action="ambiguous request ...
Python
nomic_cornstack_python_v1
function remove_uploaded_zip self begin string Remove the local and S3 zip file after uploading and updating. comment Remove the uploaded zip from S3, because it is now registered.. call remove_from_s3 zip_path s3_bucket_name comment Finally, delete the local copy our zip package call remove_local_zip end function
def remove_uploaded_zip(self): """ Remove the local and S3 zip file after uploading and updating. """ # Remove the uploaded zip from S3, because it is now registered.. self.zappa.remove_from_s3(self.zip_path, self.s3_bucket_name) # Finally, delete the local copy our zip...
Python
jtatman_500k
import json , time import urllib.parse import requests set url_pattern = string https://udn.com/api/more?page={}&id=&channelId=1&cate_id=0&type=breaknews&totalRecNo=6561 set alldata = list for page in range 1 11 begin set url = format url_pattern page set html = text set data = loads html set titles = data at string li...
import json, time import urllib.parse import requests url_pattern = "https://udn.com/api/more?page={}&id=&channelId=1&cate_id=0&type=breaknews&totalRecNo=6561" alldata = list() for page in range(1, 11): url = url_pattern.format(page) html = requests.get(url).text data = json.loads(html) titles = data['l...
Python
zaydzuhri_stack_edu_python
comment (r,q,d) = (rb2,rab,ra2) b<a function square_number n begin if round n ^ 0.5 ^ 2 == n begin return true end else begin return false end end function set progressive_square = list set limit = power 10 12 for a in range 1 integer power limit 1 / 3 + 1 begin for b in range 1 a begin for r in range 1 integer power ...
# (r,q,d) = (rb2,rab,ra2) b<a def square_number(n): if round(n ** 0.5) ** 2 == n: return True else: return False progressive_square = [] limit = pow(10,12) for a in range(1,int(pow(limit,1/3))+1): for b in range(1,a): for r in range(1,int(pow(limit/(b*pow(a,3)),1/2))+1)...
Python
zaydzuhri_stack_edu_python
import datetime as dt import numpy as np import pandas as pd import json from flask import Flask , render_template , jsonify , request , url_for , redirect , make_response comment Flask Setup set app = call Flask __name__ comment Database Setup from flask_sqlalchemy import SQLAlchemy decorator call route string / comme...
import datetime as dt import numpy as np import pandas as pd import json from flask import ( Flask, render_template, jsonify, request, url_for, redirect, make_response) ################################################# # Flask Setup #########################################...
Python
zaydzuhri_stack_edu_python
import numpy as np import scipy.io as sio import scipy.stats as ss import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D string simulated annealing, 模拟退火法,既可用于寻找全局最优解,也可用于multi-modal分布的采样 seed 2 comment load data set data = call loadmat string peaks.mat print keys data set XX = data at string XX set Y...
import numpy as np import scipy.io as sio import scipy.stats as ss import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D '''simulated annealing, 模拟退火法,既可用于寻找全局最优解,也可用于multi-modal分布的采样''' np.random.seed(2) # load data data = sio.loadmat('peaks.mat') print(data.keys()) XX = data['XX'] YY = data['YY']...
Python
zaydzuhri_stack_edu_python
function process_request request client begin comment type: (Dict, ConnectClient) -> Dict comment Create the subscription in vendor system by calling the Vendor API to create subscription comment TODO: implement the Vendor API call to create the subscription in Vendor portal comment The following is the Mock API and cl...
def process_request(request, client): # type: (Dict, ConnectClient) -> Dict # Create the subscription in vendor system by calling the Vendor API to create subscription # TODO: implement the Vendor API call to create the subscription in Vendor portal # The following is the Mock API and c...
Python
nomic_cornstack_python_v1
import subprocess import sys import os set i = 2 set command = string argv at 1 while i < length argv begin set command = command + string + string argv at i set i = i + 1 end call system command set response = call raw_input string Press enter to close window:
import subprocess import sys import os i=2 command=str(sys.argv[1]) while (i<len(sys.argv)): command = command + " " + str(sys.argv[i]) i+=1 os.system(command) response = raw_input("Press enter to close window: ")
Python
zaydzuhri_stack_edu_python
from django.shortcuts import render comment Create your views here. from booktest.models import BookInfo , HeroInfo from datetime import date comment 导入 F Q 对象 ,聚合Sum, Avg from django.db.models import F , Q , Sum , Avg string 演示增加数据 save和create comment 创建一个记录对象 set book = call BookInfo set btitle = string 西游记 comment d...
from django.shortcuts import render # Create your views here. from booktest.models import BookInfo, HeroInfo from datetime import date from django.db.models import F, Q, Sum, Avg # 导入 F Q 对象 ,聚合Sum, Avg """演示增加数据 save和create""" book = BookInfo() # 创建一个记录对象 book.btitle = '西游记' book.bpub_date = date(1991, 1, 1) # da...
Python
zaydzuhri_stack_edu_python
function _parser_fsm self begin set basic = basic set listener = listener set draw = draw set debug = debug set tuple ESC CSI_C1 = tuple ESC CSI_C1 set OSC_C1 = OSC_C1 set SP_OR_GT = SP + string > set NUL_OR_DEL = NUL + DEL set CAN_OR_SUB = CAN + SUB set ALLOWED_IN_CSI = join string list BEL BS HT LF VT FF CR set OSC_...
def _parser_fsm(self): basic = self.basic listener = self.listener draw = listener.draw debug = listener.debug ESC, CSI_C1 = ctrl.ESC, ctrl.CSI_C1 OSC_C1 = ctrl.OSC_C1 SP_OR_GT = ctrl.SP + ">" NUL_OR_DEL = ctrl.NUL + ctrl.DEL CAN_OR_SUB = ctrl.CAN...
Python
nomic_cornstack_python_v1
function read_2d fpath begin comment check_isfile(fpath) set objs = list set ids = list with open fpath string r as f begin for ff in f begin set tuple id_position players_x players_y = call token_position ff append objs tuple players_x players_y append ids id_position end end set objs = array objs set ids = array id...
def read_2d(fpath): #check_isfile(fpath) objs = [] ids = [] with open(fpath, 'r') as f: for ff in f: id_position, players_x, players_y = token_position(ff) objs.append((players_x, players_y)) ids.append(id_position) objs = np.array(objs) ids = np.array...
Python
nomic_cornstack_python_v1
comment real signature unknown function from_bytes self *args **kwargs begin pass end function
def from_bytes(self, *args, **kwargs): # real signature unknown pass
Python
nomic_cornstack_python_v1
comment encoding=utf-8 import json import utils set __author__ = string lxf import re from scrapy import Request , Selector , Item , Field , log from scrapy.contrib.spiders import CrawlSpider from utils.database import get_mongodb comment -----------------------------------define field------------------------ class Yah...
# encoding=utf-8 import json import utils __author__ = 'lxf' import re from scrapy import Request, Selector, Item, Field, log from scrapy.contrib.spiders import CrawlSpider from utils.database import get_mongodb # -----------------------------------define field------------------------ class YahooCityItem(Item):...
Python
zaydzuhri_stack_edu_python
function set_data_source inst channel=string Ch3 begin if channel not in channels begin raise call ValueError format string Channel "{}" not allowed, must be in {} channel channels end write inst string dat:sou + channel return end function
def set_data_source(inst, channel: str = 'Ch3'): if channel not in channels: raise ValueError('Channel "{}" not allowed, must be in {}'.format(channel, channels)) inst.write('dat:sou ' + channel) return
Python
nomic_cornstack_python_v1
function from_numpy array begin if is instance array ndarray and not flags at string C_CONTIGUOUS begin set array = call ascontiguousarray array end return tensor call from_numpy array end function
def from_numpy(array): if isinstance(array, np.ndarray) and not array.flags['C_CONTIGUOUS']: array = np.ascontiguousarray(array) return Tensor(Tensor_.from_numpy(array))
Python
nomic_cornstack_python_v1
function __create_connection self begin if not _connection begin try begin set _connection = call connect keyword params print string Connection successfully return _connection end except Error as err begin if errno == ER_ACCESS_DENIED_ERROR begin print string Access denied! User or password is incorrect! Please check!...
def __create_connection(self): if not self._connection: try: self._connection = connector.connect(**self.params) print("Connection successfully") return self._connection except connector.Error as err: if err.errno == errorco...
Python
nomic_cornstack_python_v1
function cmd_usage self args begin info string Usage: call blue string $ otto %s %s % tuple call _name join string args exit end function
def cmd_usage(self, args): info("Usage:") blue(" $ otto %s %s" % (self._name(), ' '.join(args))) sys.exit()
Python
nomic_cornstack_python_v1
function close self begin close controller end function
def close(self): self.controller.close()
Python
nomic_cornstack_python_v1
function main begin set n = integer input comment Geração de vetor while n < 2 begin set n = integer input end set vetor = list 0 * n set vetor at 0 = 0 set vetor at 1 = 1 for i in range 2 n begin set vetor at i = vetor at i - 1 + vetor at i - 2 end print vetor end function if __name__ == string __main__ begin call mai...
def main(): n = int(input()) #Geração de vetor while n < 2: n = int(input()) vetor = [0] * n vetor[0] = 0 vetor[1] = 1 for i in range(2, n): vetor[i] = vetor[i - 1] + vetor[i - 2] print(vetor) if __name__ == '__main__': main()
Python
zaydzuhri_stack_edu_python
function train training validation X Y NN_model nan_exception=false begin if length training <= length validation begin print string Validation set bigger than training set, skipping it! return string error end if DATA_AUGMENTATION begin set tuple addedX addedY = call data_augmentation training X Y set added_indices = ...
def train(training, validation, X, Y, NN_model, nan_exception=False): if len(training) <= len(validation): print("Validation set bigger than training set, skipping it!") return 'error' if settings.DATA_AUGMENTATION: addedX, addedY = data_augmentation(training, X, Y) added_indic...
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np import os function get_filelist path begin set filelist = list for file in list directory path begin if ends with file string .csv begin insert filelist length filelist file end end return filelist end function function converDateTime str_date begin set str_time = split str_date s...
import pandas as pd import numpy as np import os def get_filelist(path): filelist = list() for file in os.listdir(path): if file.endswith(".csv"): filelist.insert(len(filelist), file) return filelist def converDateTime(str_date): str_time = str_date.split(' ')[1] str_time = s...
Python
zaydzuhri_stack_edu_python
function _activate_upnp_coordinator self coordinator_constructor begin set _has_upnp_devices = true set _upnp_coord = call coordinator_constructor self return end function
def _activate_upnp_coordinator(self, coordinator_constructor): self._has_upnp_devices = True self._upnp_coord = coordinator_constructor(self) return
Python
nomic_cornstack_python_v1
function removeRemote self id begin if id not in remoteMap begin return end call destroy set remote = remoteMap at id at 0 comment ??? check this call detachNode append freeRemotes remote del remoteMap at id if id in visList begin remove visList id end end function
def removeRemote(self, id) : if id not in self.remoteMap : return self.remoteMap[id][2].destroy() remote = self.remoteMap[id][0] remote.detachNode() # ??? check this self.freeRemotes.append(remote) del self.remoteMap[id] if id in self.visList: self.visList.remove(id)
Python
nomic_cornstack_python_v1
function has_access_permissions self *args **kwargs begin return true end function
def has_access_permissions(self, *args, **kwargs): return True
Python
nomic_cornstack_python_v1
import numpy as np from decimal import * set data = array list list 1 5 list 2 6 list 3 7 list 4 8 list 1.1 5.5 list 2.2 6.6 list 3.3 7.7 list 4.4 8.8 dtype=float function Reconstitute_DataSets begin set X = list set y = list print string for i in range 0 8 begin set index_0 = data at tuple i 0 set index_1 = data at ...
import numpy as np from decimal import * data = np.array([[1, 5], [2, 6], [3, 7], [4, 8], [1.1, 5.5], [2.2, 6.6], [3.3, 7.7], [4.4, 8.8]], dtype=float) def Reconstitute_DataSets(): X = []; y = [] print('') for i in range(0, 8): index_0 = data[i, 0] index_1 = data[i, 1] ...
Python
zaydzuhri_stack_edu_python
function test_formatter5 self begin set tuple start end = call one_day set x = call RiderTimeDelta start end dnf=true assert equal call format_ride_time x show_special=false string end function
def test_formatter5(self): start, end = self.one_day() x = RiderTimeDelta(start, end, dnf=True) self.assertEqual(format_ride_time(x, show_special=False), "")
Python
nomic_cornstack_python_v1
function get_id request request_type begin if request_type == string post begin set id = POST at string id end else begin set id = GET at string id end set id = call rsplit string _ set id = integer id at 1 return id end function
def get_id(request, request_type): if request_type == "post": id = request.POST['id'] else: id = request.GET['id'] id = id.rsplit('_') id = int(id[1]) return id
Python
nomic_cornstack_python_v1
function accuracy predictions targets begin comment PUT YOUR CODE HERE # set correct = 0 for i in range length targets begin if predictions at i == targets at i begin set correct = correct + 1 end end set accuracy = correct / length targets comment raise NotImplementedError comment END OF YOUR CODE # return accuracy en...
def accuracy(predictions, targets): ######################## # PUT YOUR CODE HERE # ####################### correct = 0 for i in range(len(targets)): if(predictions[i] == targets[i]): correct += 1 accuracy = correct/len(targets) #raise NotImplementedError ######################## # E...
Python
nomic_cornstack_python_v1
function process_dataframe df begin if is instance df DataFrame begin set df2 = copy df set required_columns = set literal string name string wkt string lower_limit string upper_limit if not required_columns <= set columns begin raise call ValueError string DataFrame must contain columns 'name', 'wkt', 'lower_limit', '...
def process_dataframe(df): if isinstance(df, pd.DataFrame): df2 = df.copy() required_columns = {'name', 'wkt', 'lower_limit', 'upper_limit'} if not required_columns <= set(df2.columns): raise ValueError("DataFrame must contain columns 'name', 'wkt', 'lower_limit', 'upper_limit'....
Python
nomic_cornstack_python_v1
function _GetSpecificationStore cls format_category begin set specification_store = call FormatSpecificationStore set remainder_list = list for analyzer_helper in values _analyzer_helpers begin if not call IsEnabled begin continue end if format_category in format_categories begin set format_specification = call GetFor...
def _GetSpecificationStore(cls, format_category): specification_store = specification.FormatSpecificationStore() remainder_list = [] for analyzer_helper in cls._analyzer_helpers.values(): if not analyzer_helper.IsEnabled(): continue if format_category in analyzer_helper.format_categori...
Python
nomic_cornstack_python_v1
comment an implementation of Eratosthenes' Sieve: comment http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes comment Checks whether a number is prime or not function _is_prime primes n begin for i in primes begin if n % i == 0 begin return false end end return true end function comment Loops through numbers and jumps b...
# an implementation of Eratosthenes' Sieve: # http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes # Checks whether a number is prime or not def _is_prime(primes, n): for i in primes: if n % i == 0: return False return True # Loops through numbers and jumps back to the test files once one ...
Python
zaydzuhri_stack_edu_python
comment 读取人物名称 comment f = open('name.txt') comment data = f.read() comment print(data.split('|')) comment # 读取兵器名称 comment f2 = open('weapon.txt') comment data2 = f2.read() comment i = 1 comment for line in f2.readlines(): comment if i % 2 == 1: comment print(line.strip('\n')) comment i += 1 comment f3 = open('sanguo....
# 读取人物名称 # f = open('name.txt') # data = f.read() # print(data.split('|')) # # # 读取兵器名称 # f2 = open('weapon.txt') # data2 = f2.read() # i = 1 # for line in f2.readlines(): # if i % 2 == 1: # print(line.strip('\n')) # i += 1 # # f3 = open('sanguo.txt',encoding='GB18030') # print(f3.read().replace('\n', '...
Python
zaydzuhri_stack_edu_python
from dolfin import * from constants import * from channel_tools_new import * import numpy as np comment Define the mesh and ice sheet geometry ### comment Maximum ice thickness set h_max = 1500.0 comment Length of ice sheet set length = 60000.0 comment 60km by 20km rectangular mesh set mesh = call Mesh string sheet.xml...
from dolfin import * from constants import * from channel_tools_new import * import numpy as np ### Define the mesh and ice sheet geometry ### # Maximum ice thickness h_max = 1500. # Length of ice sheet length = 60e3 # 60km by 20km rectangular mesh mesh = Mesh("sheet.xml") # Standard continuous function space for t...
Python
zaydzuhri_stack_edu_python
function cli stage maas_url maas_key debug output_log begin if debug begin call setLevel DEBUG end set detail = dict string start call isoformat set results = dict set log_id = format string {}-{} string stage replace replace call isoformat string : string _ string . string _ set dt = call utcnow set results at string...
def cli(stage, maas_url, maas_key, debug, output_log): if debug: log.setLevel(logging.DEBUG) detail = {'start': datetime.utcnow().isoformat(), } results = {} log_id = '{}-{}'.format(str(stage), datetime.utcnow().isoformat().replace(':', '_').replace('.', '_')) dt = datetime.utcnow() resu...
Python
nomic_cornstack_python_v1
comment TODO typed actions callables function __init__ self text font panel_widget engine text_shift=none on_ok=none on_cancel=none begin call __init__ transparent=true set _on_ok = on_ok set _on_cancel = on_cancel set _panel = call Compound call add_widget panel_widget set _panel_size = call get_size engine set window...
def __init__(self, text, font, panel_widget, engine, text_shift=None, on_ok=None, on_cancel=None): # TODO typed actions callables super().__init__(transparent=True) self._on_ok = on_ok self._on_cancel = on_cancel self._panel = Compound() self._panel.add_widget(panel_widget) _panel_size = panel_widget.get_...
Python
nomic_cornstack_python_v1
function flopViewer begin set allV = call allNodes string Viewer set pV = allV at 0 set List = call selectedNodes call selectAll call invertSelection try begin set n = call toNode string VIEWER_INPUT if call Class == string Mirror begin call setValue not call value for i in allV begin call setValue not call value + cal...
def flopViewer(): allV = nuke.allNodes('Viewer') pV = allV[0] List = nuke.selectedNodes() nuke.selectAll() nuke.invertSelection() try: n = nuke.toNode('VIEWER_INPUT') if n.Class() == 'Mirror': n['Vertical'].setValue(not n['Vertical'].value()) for i in allV...
Python
nomic_cornstack_python_v1
function test_sorting_multiple_contours begin set graph = dict 11 list 10 ; 10 list 5 7 9 ; 9 list 7 8 ; 8 list 2 ; 7 list 6 ; 6 list 2 ; 5 list 4 ; 4 list 3 ; 3 list 2 ; 2 list 0 1 ; 1 list ; 0 list call run_toposort_multisolution_test 2 graph list list 2 0 list 2 1 call run_toposort_multisolution_test 9 graph list ...
def test_sorting_multiple_contours(): graph = { 11: [10], 10: [5, 7, 9], 9: [7, 8], 8: [2], 7: [6], 6: [2], 5: [4], 4: [3], 3: [2], 2: [0, 1], 1: [], 0: [], } run_toposort_multisolution_test(2, graph, [[2, 0], [2...
Python
nomic_cornstack_python_v1
function login username password expiresIn=86400 scope=string internal begin set url = call login_url set payload = dict string client_id string c82SH0WZOsabOXGP2sxqcj34FxkvfnWRZBKlBjFS ; string expires_in expiresIn ; string grant_type string password ; string password password ; string scope scope ; string username us...
def login(username,password,expiresIn=86400,scope='internal'): url = urls.login_url() payload = { 'client_id': 'c82SH0WZOsabOXGP2sxqcj34FxkvfnWRZBKlBjFS', 'expires_in': expiresIn, 'grant_type': 'password', 'password': password, 'scope': scope, 'username': username } data = helper...
Python
nomic_cornstack_python_v1
function call_rvol self other_args begin set parser = call ArgumentParser add_help=false formatter_class=ArgumentDefaultsHelpFormatter prog=string rvol description=string Show rolling volatility portfolio vs benchmark call add_argument string -p string --period type=str dest=string period default=string 1y choices=PERI...
def call_rvol(self, other_args: List[str]): parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="rvol", description="Show rolling volatility portfolio vs benchmark", ) parser.add_argument( ...
Python
nomic_cornstack_python_v1
function getJSONObject self json key begin set toReturn = dict if json is not none begin set toReturn = get json key dict end return toReturn end function
def getJSONObject(self, json, key): toReturn = {} if json is not None: toReturn = json.get(key, {}) return toReturn
Python
nomic_cornstack_python_v1
function OptimizeMathIdentities self begin set addIdentity = compile string add [\w]*, 0 set subIdentity = compile string sub [\w]*, 0 set i = 0 while i < length lines begin if match lines at i != none or match lines at i != none begin del lines at i end else begin set i = i + 1 end end end function
def OptimizeMathIdentities(self): addIdentity = re.compile("add [\w]*, 0") subIdentity = re.compile("sub [\w]*, 0") i=0 while i<len(self.lines): if(addIdentity.match(self.lines[i])!=None or subIdentity.match(self.lines[i])!=None): del(sel...
Python
nomic_cornstack_python_v1
import numpy as np set myArr = zeros 5 print myArr set myArr1 = ones 10 print myArr1 set myArr2 = array list 10 20 30 40 50 60 70 80 90 100 print myArr2 set myArr3 = array list 10 20 30 40 50 60 70 80 90 100 string Asher true print myArr3 comment It creates an empty Array. set myArr4 = call empty 5 print myArr4
import numpy as np myArr = np.zeros(5) print(myArr) myArr1 = np.ones(10) print(myArr1) myArr2 = np.array([10,20,30,40,50,60,70,80,90,100]) print(myArr2) myArr3 = np.array([10,20,30,40,50,60,70,80,90,100,"Asher",True]) print(myArr3) # It creates an empty Array. myArr4 = np.empty(5) print(myArr4)
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Fri Jul 12 13:38:17 2019 @author: rahul import numpy as np import os from sklearn.metrics import confusion_matrix import seaborn as sn import tensorflow as tf from sklearn.utils import shuffle import matplotlib.pyplot as plt import cv2 comment labelling of class names set...
# -*- coding: utf-8 -*- """ Created on Fri Jul 12 13:38:17 2019 @author: rahul """ import numpy as np import os from sklearn.metrics import confusion_matrix import seaborn as sn import tensorflow as tf from sklearn.utils import shuffle import matplotlib.pyplot as plt import cv2 #labelling of class ...
Python
zaydzuhri_stack_edu_python
import pygame from farbkonstanten import constants as const import random call init set tuple width height = tuple 500 500 set screen = call set_mode tuple width height set clock = call Clock set font = call SysFont string Helvetica 30 set blocksize = 10 set enemy_speed = 10 set enemy_count = 0 set enemy_max = 20 set e...
import pygame from farbkonstanten import constants as const import random pygame.init() width, height = 500, 500 screen = pygame.display.set_mode((width, height)) clock = pygame.time.Clock() font = pygame.font.SysFont("Helvetica", 30) blocksize = 10 enemy_speed = 10 enemy_count = 0 enemy_max = ...
Python
zaydzuhri_stack_edu_python
function show_default self begin set formatter = call BaseHtmlFormatter config output is_blank=true set content_type = string %s; charset=%s % tuple media_type config at string charset call response_start b'200' b'OK' list tuple b'Content-Type' encode content_type string ascii tuple b'Cache-Control' b'max-age=300' call...
def show_default(self) -> None: formatter = html.BaseHtmlFormatter(self.config, self.output, is_blank=True) content_type = "%s; charset=%s" % (formatter.media_type, self.config['charset']) self.response_start(b"200", b"OK", [ (b"Content-Type", content_type.encode('ascii')), ...
Python
nomic_cornstack_python_v1
string Created on 2010/05/08 @author: banana if __name__ == string __main__ begin pass end set fp = open string C-large.in string r set lines = read lines fp set T = integer lines at 0 set fpout = open string C-large.txt string w for t in range 1 T + 1 begin set l = list comprehension integer x for x in split lines at ...
''' Created on 2010/05/08 @author: banana ''' if __name__ == '__main__': pass fp = open("C-large.in", "r") lines = fp.readlines() T = int(lines[0]) fpout = open("C-large.txt", "w") for t in range(1, T+1): l = [ int(x) for x in lines[t*2].split()] #check if divisible M = 22 ...
Python
zaydzuhri_stack_edu_python
function quota_create context project_id resource limit begin return call quota_create context project_id resource limit end function
def quota_create(context, project_id, resource, limit): return _get_dbdriver_instance().quota_create(context, project_id, resource, limit)
Python
nomic_cornstack_python_v1
import os import re import csv import json import jieba from util import get_word_to_ix set SPLIT = 16000 function read_data_from_tsv_to_txt tsv_path path train=false begin set corpus = list set txt_path = path if train == true begin set train_path = string train_ + txt_path set test_path = string test_ + txt_path set...
import os import re import csv import json import jieba from util import get_word_to_ix SPLIT = 16000 def read_data_from_tsv_to_txt(tsv_path, path, train=False): corpus = [] txt_path = path if train == True: train_path = 'train_' + txt_path test_path = 'test_' + txt_path train_cor...
Python
zaydzuhri_stack_edu_python
function interpolated_distmod z cosmo=none dz=1e-05 begin set z = call atleast_1d z if min z < 0.0 begin set msg = string all `z` must be greater or equal to 0.0. assert call ValueError msg end if cosmo is none begin set cosmo = default_cosmo end set z_range = max z - min z set n_sample = z_range / dz comment require n...
def interpolated_distmod(z, cosmo=None, dz=1e-5): z = np.atleast_1d(z) if np.min(z)<0.0: msg = ('all `z` must be greater or equal to 0.0.') assert ValueError(msg) if cosmo is None: cosmo = default_cosmo z_range = np.max(z) - np.min(z) n_sample = z_range/dz # require ...
Python
nomic_cornstack_python_v1
function test_tiled_grid_values self begin set xdim = 3 set ydim = 3 set array = reshape array range 1 10 tuple xdim ydim set tiled_array = call tiled_grid array size=3 for value in array range 1 10 begin set counts = tiled_array at where tiled_array == value assert equal length counts xdim * ydim end end function
def test_tiled_grid_values(self): xdim = 3 ydim = 3 array = np.arange(1, 10).reshape((xdim, ydim)) tiled_array = tiled_grid(array, size=3) for value in np.arange(1, 10): counts = tiled_array[np.where(tiled_array == value)] self.assertEqual(len(counts), xdi...
Python
nomic_cornstack_python_v1
function SaveState self begin acquire _next_cache_lock set metadata = dict string _current_cache list _current_cache ; string _used_cache list _used_cache ; string _uncached_files list _uncached_files ; string _next_cache_update list _next_cache_update release _next_cache_lock with open join path _cache_dir _CACHE_META...
def SaveState(self): self._next_cache_lock.acquire() metadata = { '_current_cache': list(self._current_cache), '_used_cache': list(self._used_cache), '_uncached_files': list(self._uncached_files), '_next_cache_update': list(self._next_cache_update) ...
Python
nomic_cornstack_python_v1
function process_part self part begin set content_type = call get_content_type set filename = call get_filename if content_type == string text/plain and not filename begin set text_content = text_content + call get_payload part end else if content_type == string text/html begin set html_content = html_content + call ge...
def process_part(self, part): content_type = part.get_content_type() filename = part.get_filename() if content_type == 'text/plain' and not filename: self.text_content += self.get_payload(part) elif content_type == 'text/html': self.html_content += self.get_payload(part) elif content_type == 'message/...
Python
nomic_cornstack_python_v1
function get_formated firstname lastname begin set full_name = firstname + string + lastname return title full_name end function print call get_formated string aditi string jain
def get_formated(firstname, lastname): full_name = firstname + ' ' + lastname return full_name.title() print(get_formated('aditi', 'jain'))
Python
zaydzuhri_stack_edu_python
function expiration_date self expiration_date begin set _expiration_date = expiration_date end function
def expiration_date(self, expiration_date): self._expiration_date = expiration_date
Python
nomic_cornstack_python_v1
function test_bin_larvaemutattion begin set larvae = array list list 0 0 0 0 0 0 0 0 list 1 1 1 1 0 0 0 0 list 0 0 0 0 1 1 1 1 set pos = array list list 0 3 5 set mode = string bin set larvaemutation_function = call get_larvaemutation_function mode set larvaemutated = call larvaemutation_function larvae pos seed=13 set...
def test_bin_larvaemutattion(): larvae = np.array([[0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 1, 1]]) pos = np.array([[0, 3, 5]]) mode = 'bin' larvaemutation_function = get_larvaemutation_function(mode) larvaemut...
Python
nomic_cornstack_python_v1
while n > 10 begin set n = integer input string dati un nr mai mic decat 10: end set a = list print string introduceti n string elemente pentru vectorul creat for i in range 0 n begin set q = integer input string Dati elementul: extend a list q end print a print string a) afiseaza pe ecran componentele tabloului la un...
while n>10: n=int(input('dati un nr mai mic decat 10: ')) a=[] print('introduceti ',n,' elemente pentru vectorul creat') for i in range(0,n): q=int(input('Dati elementul:')) a.extend([q]) print(a) print('a) afiseaza pe ecran componentele tabloului la un interval de 5 pozitii') print(a[::5]) prin...
Python
zaydzuhri_stack_edu_python
comment Tabuada set num = integer input string Qual tabudada você quer saber? print string - * 15 print string TABUADA print string - * 15 print format string {} X 1 = {} num num * 1 print format string {} X 2 = {} num num * 2 print format string {} X 3 = {} num num * 3 print format string {} X 4 = {} num num * 4 print...
# Tabuada num = int(input("Qual tabudada você quer saber? ")) print("-"*15) print("TABUADA") print("-"*15) print("{} X 1 = {}".format(num, num * 1)) print("{} X 2 = {}".format(num, num * 2)) print("{} X 3 = {}".format(num, num * 3)) print("{} X 4 = {}".format(num, num * 4)) print("{} X 5 = {}".format(num, num * 5)) p...
Python
zaydzuhri_stack_edu_python
function AskText question default=string title=string begin comment build the dialog set dlg = call TextEntryDialog none string question title value=default comment run it and capture answer if call ShowModal != ID_OK begin call Destroy return none end comment convert answer to string set result = string call GetValue...
def AskText(question, default='', title=''): # build the dialog dlg = wx.TextEntryDialog(None, str(question), title, value=default) if (dlg.ShowModal() != wx.ID_OK): # run it and capture answer dlg.Destroy() return None result = str(dlg.GetValue()) # convert answer to string retur...
Python
nomic_cornstack_python_v1
function getRandomDateString begin set year = 2017 set month = random integer 1 12 set day = random integer 1 28 return string year + string - + string month + string - + string day end function
def getRandomDateString(): year = 2017 month = random.randint(1, 12) day = random.randint(1, 28) return str(year) + "-" + str(month) + "-" + str(day)
Python
nomic_cornstack_python_v1
comment languages = 'python,php,Ruby,Perl' set lang_list = split languages string , set separator = string , join separator lang_list print join separator lang_list set poem = string It was nice day. set new_poem = replace poem string nice string bad print poem print new_poem set text = string hello, hello, helo, hello...
# languages = 'python,php,Ruby,Perl' lang_list = languages.split(',') separator = ',' separator.join(lang_list) print(separator.join(lang_list)) poem = 'It was nice day.' new_poem = poem.replace('nice', 'bad') print(poem) print(new_poem) text = 'hello, hello, helo, hello' print(text.count('hello')) name = 'Billy Joe...
Python
zaydzuhri_stack_edu_python
function graph begin comment returns an adjacensy matrix of a graph set V = integer input string give the number of vertices print string Type inn edges: comment create list set L = list comprehension list for i in range V for i in range V begin set connections = input format string Type in all connected vertices to {...
def graph(): # returns an adjacensy matrix of a graph V = int(input('give the number of vertices')) print('Type inn edges:') L = [[] for i in range(V)] # create list for i in range(V): connections = input('Type in all connected vertices to {}, use comma as delimiter'.format(i)) c = c...
Python
zaydzuhri_stack_edu_python
function _call_command_method self name original_method args kwargs begin if call current_controller is not self begin set action = _direct_comm_call_action if action == string warning begin if name not in _command_warned begin print format string Warning: direct call of command '{}' of thread '{}' from a different thr...
def _call_command_method(self, name, original_method, args, kwargs): if threadprop.current_controller() is not self: action=self._direct_comm_call_action if action=="warning": if name not in self._command_warned: print("Warning: direct call of command ...
Python
nomic_cornstack_python_v1
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler , StandardScaler from sklearn.linear_model import LogisticRegression set df_wine = read csv string https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data header=none set columns = li...
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler,StandardScaler from sklearn.linear_model import LogisticRegression df_wine = pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data",header=None) df_wine.columns = ['Cla...
Python
zaydzuhri_stack_edu_python
function align_image src_im ref_im crop_list=none use_autocorr=true precision_fold=100 min_good_drifts=3 drift_diff_th=1.0 all_channels=_allowed_colors ref_all_channels=none drift_channel=string 488 correction_args=dict fitting_args=dict match_distance_th=2.0 verbose=true detailed_verbose=false begin from io_tools.lo...
def align_image( src_im:np.ndarray, ref_im:np.ndarray, crop_list=None, use_autocorr=True, precision_fold=100, min_good_drifts=3, drift_diff_th=1., all_channels=_allowed_colors, ref_all_channels=None, drift_channel='488', correction_args={}, fitting_args={}, match_distanc...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import collections import subprocess import time import os import errno import threading class Logger extends object begin set LoggingDir = string set fd = none set is_started = false end class
#!/usr/bin/env python import collections import subprocess import time import os import errno import threading class Logger(object): LoggingDir = "" fd = None is_started = False
Python
zaydzuhri_stack_edu_python
function resource_discovery_association_count self begin return get pulumi self string resource_discovery_association_count end function
def resource_discovery_association_count(self) -> pulumi.Output[int]: return pulumi.get(self, "resource_discovery_association_count")
Python
nomic_cornstack_python_v1
comment Created By: Evan comment Created on: Sept. 2020 comment This program: Uses neopixels for traffic lights loop from microbit import * import neopixel from random import randint set np = call NeoPixel pin16 4 while true begin set np at 3 = tuple 0 255 0 show sleep 1000 clear np set np at 2 = tuple 255 255 0 show s...
#Created By: Evan #Created on: Sept. 2020 #This program: Uses neopixels for traffic lights loop from microbit import * import neopixel from random import randint np = neopixel.NeoPixel(pin16, 4) while True: np[3] = (0, 255, 0) np.show() sleep(1000) np.clear() np[2] = (255, 255, 0) np.show()...
Python
zaydzuhri_stack_edu_python
function get_global_embeddings self filenames embedding_size embedding_dir begin set sentences = list print embedding_dir if exists path join path embedding_dir string vocab_len.pkl begin set vocab_len_stored = load pickle open join path embedding_dir string vocab_len.pkl string rb end else begin set vocab_len_stored ...
def get_global_embeddings(self, filenames, embedding_size, embedding_dir): sentences = [] print (embedding_dir) if (os.path.exists(os.path.join(embedding_dir , 'vocab_len.pkl'))): vocab_len_stored = pickle.load(open(os.path.join(embedding_dir , "vocab_len.pkl"), "rb")) else:...
Python
nomic_cornstack_python_v1
function make_feature_function features_txt begin set rules_by_tag = dict for tuple rule_i line in enumerate call splitlines begin set tuple which_word index_diff word which_tag = call parse_rule line if which_tag not in rules_by_tag begin set rules_by_tag at which_tag = list end append rules_by_tag at which_tag tupl...
def make_feature_function(features_txt): rules_by_tag = {} for rule_i,line in enumerate(features_txt.splitlines()): which_word, index_diff, word, which_tag = parse_rule(line) if which_tag not in rules_by_tag: rules_by_tag[which_tag] = [] rules_by_tag[which_tag].append((which_...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Wed Oct 28 13:17:12 2020 @author: Gebruiker import numpy as np function k_p2_func k_xx k_xy k_yy begin comment eq 9 Rühs set theta = 0.5 * call arctan 2 * k_xy / k_xx - k_yy comment eq 8 Rühs set k_p2 = k_xx * sin theta ^ 2 - k_xy * sin 2 * theta + k_yy * cos theta ^ 2 re...
# -*- coding: utf-8 -*- """ Created on Wed Oct 28 13:17:12 2020 @author: Gebruiker """ import numpy as np def k_p2_func(k_xx, k_xy, k_yy): theta = 0.5 * np.arctan( 2 * k_xy / (k_xx - k_yy)) # eq 9 Rühs k_p2 = k_xx * np.sin(theta)**2 - k_xy * np.sin(2*theta) + k_yy * np.cos(theta)**2 # eq 8 Rühs return ...
Python
zaydzuhri_stack_edu_python
function bounding_box trajectory begin set box = max absolute trajectory axis=0 call cleanup_small_values box val=1.0 tol=1e-10 return box end function
def bounding_box(trajectory): box = np.max(np.abs(trajectory),axis=0) cleanup_small_values(box,val=1.,tol=1e-10) return box
Python
nomic_cornstack_python_v1
import datetime as dt set arrival_time = call datetime 2019 5 10 19 45 print string Самолёт прибывает в arrival_time comment Что делать, если хочется напечатать сообщение по-человечески, скажем: Сейчас 10:31? comment Для этого существует метод strftime(). comment Его можно применить к любому объекту типа datetime и арг...
import datetime as dt arrival_time = dt.datetime(2019, 5, 10, 19, 45) print('Самолёт прибывает в', arrival_time) # Что делать, если хочется напечатать сообщение по-человечески, скажем: Сейчас 10:31? # Для этого существует метод strftime(). # Его можно применить к любому объекту типа datetime и аргументом задать формат...
Python
zaydzuhri_stack_edu_python
string " Este codigo calcula los retornos mensuales de las 3000 acciones en periodicidad mensual para luego introducirlas al panel import pandas as pd import os print string Se importaron las librerias necesarias set n_stocks = 3000 change directory string C:\Users\usuario\Desktop\Maestrías\Maestria finanzas eafit\Tesi...
"""" Este codigo calcula los retornos mensuales de las 3000 acciones en periodicidad mensual para luego introducirlas al panel """ import pandas as pd import os print ("Se importaron las librerias necesarias") n_stocks=3000 os.chdir(u"C:\\Users\\usuario\\Desktop\\Maestr\xedas\\Maestria finanzas eafit\\Tesis_Network\...
Python
zaydzuhri_stack_edu_python
function __init__ self parent pixmap width height begin call __init__ set parent = parent set width = width set height = height set set_colour = call QColor 255 255 255 comment draw type is initially PIX (pixel) set draw_type = string PIX comment initialse the widget call init_widget pixmap width height set save_pixmap...
def __init__(self, parent, pixmap, width, height): super(View, self).__init__() self.parent = parent self.width = width self.height = height self.set_colour = QtGui.QColor(255,255,255) #draw type is initially PIX (pixel) self.draw_type = 'PIX' ...
Python
nomic_cornstack_python_v1
function serialize element strip=false begin string A handy way to serialize an element to text. set text = call tostring element method=string text encoding=string utf-8 if strip begin set text = strip text end return string text encoding=string utf-8 end function
def serialize(element, strip=False): """ A handy way to serialize an element to text. """ text = etree.tostring(element, method='text', encoding='utf-8') if strip: text = text.strip() return str(text, encoding='utf-8')
Python
jtatman_500k
function play_game grid instruction_list begin set location_x = instruction_list at 1 set location_y = instruction_list at 0 set tile = instruction_list at 2 if tile == 0 begin set grid at location_x at location_y = string end else if tile == 1 begin set grid at location_x at location_y = string W end else if tile == ...
def play_game(grid, instruction_list): location_x = instruction_list[1] location_y = instruction_list[0] tile = instruction_list[2] if tile == 0: grid[location_x][location_y] = ' ' elif tile == 1: grid[location_x][location_y] = 'W' elif tile == 2: grid[location_x][locati...
Python
nomic_cornstack_python_v1
function read_array file n_row n_col dtype begin set val = list for ir in range 0 n_row begin try begin while 1 begin set line = split read line file if length line == 0 or line at 0 == string # begin continue end else begin break end end end except any begin call output string Array (%d, %d) reading failed! % tuple n...
def read_array( file, n_row, n_col, dtype ): val = [] for ir in range( 0, n_row ): try: while 1: line = file.readline().split() if (len( line ) == 0) or (line[0] == "#"): continue else: break exce...
Python
nomic_cornstack_python_v1
from emd import one_dimension_emd import numpy as np from scipy.signal import argrelextrema import matplotlib.pyplot as plt import sys from smooth import gaussian_smooth from smooth import spline_smooth function load_data filename begin with open filename string r as f begin set lines = read lines f set datalist = list...
from emd import one_dimension_emd import numpy as np from scipy.signal import argrelextrema import matplotlib.pyplot as plt import sys from smooth import gaussian_smooth from smooth import spline_smooth def load_data(filename): with open(filename,'r') as f: lines = f.readlines() datalist = [] ...
Python
zaydzuhri_stack_edu_python
function view_addNode self user cTag nTag pkg exe args=string name=string namespace=string begin try begin call addNode nTag pkg exe args name namespace end except KeyError begin raise call InvalidRequest format string Can not add Node, because Container {0} does not exist. cTag end end function comment TODO: Return ...
def view_addNode(self, user, cTag, nTag, pkg, exe, args='', name='', namespace=''): try: user.containers[cTag].addNode(nTag, pkg, exe, args, name, namespace) except KeyError: raise InvalidRequest('Can not add Node, because Container {0} ' ...
Python
nomic_cornstack_python_v1
function Texture self begin set s = texture assert s in range 1 6 msg string Texture score out of bounds. if s == 1 begin return string Non-Solid / Ground Glass Opacity Texture end else if s == 2 begin return string Non-Solid or Mixed Texture end else if s == 3 begin return string Part Solid or Mixed Texture end else i...
def Texture(self): s = self.texture assert s in range(1,6), "Texture score out of bounds." if s == 1: return 'Non-Solid / Ground Glass Opacity Texture' elif s == 2: return 'Non-Solid or Mixed Texture' elif s == 3: return 'Part Solid or Mixed Texture' elif s == 4: return...
Python
nomic_cornstack_python_v1