TRI CODER — 4Coder
My favorite block of codes of BASTA 2020, EKON 24 and ML Munich
1 CSHARP
2 PASCAL
3 PYTHON
4 JAVA
C#
// demo of graphviz integration of a C# wrapper for the GraphViz graph generator for dotnet core. // by Max Kleiner for BASTA // https://www.nuget.org/packages/GraphViz.NET/ // https://sourceforge.net/projects/maxbox/upload/Examples/EKON/BASTA2020/visout/ // dotnet run C:\maXbox\BASTA2020\visout\BASTA_GraphVizCoreProgram.cs // dotnet run C:\maXbox\BASTA2020\visout\visout.csproj using System; using System.Collections; using System.Runtime.InteropServices; using GraphVizWrapper; using GraphVizWrapper.Commands; using GraphVizWrapper.Queries; using Graphviz4Net.Graphs; //# using ImageFormat.Png; using System.Drawing.Imaging; using System.Drawing; using System.Drawing.Drawing2D; using System.IO; //memory stream using System.Diagnostics; namespace visout { class ProgramGraph { static void Main(string[] args) { // These three instances can be injected via the IGetStartProcessQuery, // IGetProcessStartInfoQuery and // IRegisterLayoutPluginCommand interfaces var getStartProcessQuery = new GetStartProcessQuery(); var getProcessStartInfoQuery = new GetProcessStartInfoQuery(); var registerLayoutPluginCommand = new RegisterLayoutPluginCommand(getProcessStartInfoQuery, getStartProcessQuery); // GraphGeneration can be injected via the IGraphGeneration interface var wrapper = new GraphGeneration(getStartProcessQuery, getProcessStartInfoQuery, registerLayoutPluginCommand); //byte[] bitmap = wrapper.GenerateGraph("digraph{a -> b; b -> c; c -> a;}", Enums.GraphReturnType.Png); //byte[] bitmap = wrapper.GenerateGraph("digraph{a -> b; b -> d; b -> c; d ->a; a->d;}", // Enums.GraphReturnType.Png); byte[] bitmap = wrapper.GenerateGraph("digraph M {R -> A; A -> S; S -> T; T -> A;" +"A -> 20 -> 20 [color=green];}", Enums.GraphReturnType.Png); using(Image image = Image.FromStream(new MemoryStream(bitmap))) { image.Save("graphvizoutput3114.png", ImageFormat.Png); // Or Jpg } //Process.Start(@"graphvizoutput3114.png"); Process pim = new Process(); pim.StartInfo = new ProcessStartInfo() { //CreateNoWindow = true, no mspaint platform! Verb = "show", FileName = "mspaint.exe", //put the path to the software e.g. Arguments = @"C:\maXbox\BASTA2020\visout\graphvizoutput3114.png" }; pim.Start(); Console.WriteLine("Hello maXbox Core Viz maXbox474 World!"); Console.WriteLine("Welcome to GraphViz GraphViz.NET 1.0.1"); unsafe { GViz gviz = new GViz(); GViz* p = &gviz; //ptr to member operator struct DateTime currentDateTime = DateTime.Now; p->x = currentDateTime.Year; Console.WriteLine(gviz.x); } } } struct GViz { public int x; } }
Materialien Namespace Visout: Visualisieren in VS Code BASTA 2020:
Article at Windows Developer:
Pascal
procedure TForm1Button1ClickExcel(Sender: TObject); Var XLApp: OLEVariant; x,y: byte; path: variant; SG: TStringGrid; begin XLApp:= CreateOleObject('Excel.Application'); // requires comobj in uses try XLApp.Visible:= False; // Hide Excel XLApp.DisplayAlerts:= False; path:= 'edit1.Text'; XLApp.Workbooks.Open(Path); // Open the Workbook for x:= 1 to 4 do for y:= 1 to 6 do SG.Cells[x,y]:= XLApp.Cells[y,x].Value; // fill stringgrid with values finally XLApp.Quit; XLAPP:= Unassigned; end; end; Const aURL= 'https://api.metadefender.com/v4/file/bzIwMDYxNi1TSW42NDBPVlprTWw3YjRBMQ'; Begin //@main external OLE object writeln(GetHTM(aURL2)+CRLF) // Instantiate a WinHttpRequest object. httpReq:= CreateOleObject('WinHttp.WinHttpRequest.5.1'); // Open an HTTP connection. hr:= httpReq.Open('GET', aURL, false); if hr= S_OK then httpReq.setRequestheader('apikey','6b337c92c792174a54acd715ab1aae64'); HttpReq.Send() /// Send HTTP Request & get Responses. writeln(httpReq.responseText) writeln(httpReq.GetAllResponseHeaders()); httpReq:= NULL; println(GetDosOutput('jupyter kernelspec list','C:\')); println(GetDosOutput('dotnet --info','C:\')); QueryPerformanceCounter(startTime64); writeln(GetDosOutput(RUNSCRIPTCOREEXE,'C:\maXbox\BASTA2020\visout\bin\Debug\netcoreapp3.1\')); //writeln(GetDosOutput(RUNSCRIPTCORE,'C:\')); QueryPerformanceCounter(endTime64); println('elapsedSeconds:= '+floattostr((endTime64-startTime64) / frequency64)); QueryPerformanceCounter(startTime64); writeln(GetDosOutput('dotnet run --project '+RUNSCRIPTCOREPROJ,'C:\maXbox\BASTA2020\visout\')); QueryPerformanceCounter(endTime64); println('elapsedSeconds:= '+floattostr((endTime64-startTime64) / frequency64)); Openfile('C:\maXbox\BASTA2020\visout\graphvizoutput3114.png') End.
Doc: Microsoft Windows HTTP Services (WinHTTP) provides developers with an HTTP client application programming interface (API) to send requests through the HTTP protocol to other HTTP servers.
WinHTTP supports desktop client applications, Windows services, and Windows server-based applications.
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange
The name of the new WinHTTP 5.1 DLL is Winhttp.dll, whereas the name of the WinHTTP 5.0 DLL is Winhttp5.dll. WinHTTP 5.0 and 5.1 can coexist on the same system; WinHTTP 5.1 does not replace, or install over, WinHTTP 5.0.
What is ServerXMLHTTP?
ServerXMLHTTP provides methods and properties for server-safe HTTP access between different Web servers. You can use this object to exchange XML data between different Web servers.
Output from Pascal Code:
27T14:46:00.000Z”}},”rescan_available”:true,”scan_all_result_i”:1,”start_time”:”2020–08–27T18:50:46.081Z”,”total_time”:4016,”total_avs”:38,”total_detected_avs”:3,”progress_percentage”:100,”scan_all_result_a”:”Infected”},”file_info”:{“file_size”:29608248,”upload_timestamp”:”2020–06–16T15:02:33.000Z”,”md5″:”21648AFA06BEAD05E50D20D8BC0B67D9″,”sha1″:”DA4C716E31E2A4298013DFFBDA7A98D48650B0C7″,”sha256″:”E0CB57D978207D09A6849EFB0E972FD4D0B407A42F6EB891AB41E68B53785293″,”file_type_category”:”E”,”file_type_description”:”Executable File”,”file_type_extension”:”exe”,”display_name”:”maXbox4.exe”},”share_file”:1,”rest_version”:”4″,”newer”:”bzIwMDYxNi1TSW42NDBPVkRJMENYbGlOaQ”,”additional_info”:[“peinfo”,”sandbox”],”votes”:{“up”:0,”down”:0}}
Connection: keep-alive
Date: Mon, 28 Sep 2020 16:32:54 GMT
Content-Length: 5410
Content-Type: application/json; charset=utf-8
ETag: “1522–7CRlgQvwth5SqKaZ0bApOTQeVJo”
Vary: Accept-Encoding
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
X-Content-Type-Options: nosniff
X-Response-Time: 665ms
X-Authenticated: by apikey
X-Account-Type: anonymous
X-Datacenter: wus
X-Frame-Options: SAMEORIGIN
x-content-type-options: nosniff
X-UA-Compatible: IE=edge
X-XSS-Protection: 1; mode=block
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
X-Rendering-Stack: Dynamic
Akamai-Cache-Status: Hit from child
report-to: {“group”:”network-errors”,”max_age”:604800,”endpoints”:[{“url”:” https://mdec.nelreports.net/api/report?cat=mdocs”}]}
nel: {“report_to”:”network-errors”,”max_age”:604800,”success_fraction”:0.01,”failure_fraction”:1.0}
Article at Entwickler:
https://entwickler-konferenz.de/blog/machine-learning-mit-cai/
Python
#sign:max: MAXBOX8: 28/09/2020 07:46:37 # optimal moving average OMA for market index signals - max kleiner # v2 shell argument forecast days - 4 lines compare - ^GDAXI for DAX # pip install pandas-datareader # C:\maXbox\mX46210\DataScience\princeton\AB_NYC_2019.csv AB_NYC_2019.csv #https://medium.com/abzuai/the-qlattice-a-new-machine-learning-model-you-didnt-know-you-needed-c2e037878cd #https://www.kaggle.com/dgomonov/data-exploration-on-nyc-airbnb #https://www.kaggle.com/duygut/airbnb-nyc-price-prediction import numpy as np import matplotlib.pyplot as plt import sys from sklearn import tree from sklearn.svm import SVC from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.preprocessing import StandardScaler from sklearn.metrics import accuracy_score from sklearn.metrics import r2_score from sklearn.metrics import mean_squared_error from sklearn.metrics import mean_absolute_error from sklearn.model_selection import train_test_split #import feyn import pandas as pd rentals = pd.read_csv(r'C:\maXbox\mX46210\DataScience\princeton\AB_NYC_2019\AB_NYC_2019.csv') print(rentals.head(3).T) #Transposed for column overview #rentals = rentals.drop(["id","host_id","host_name","name","last_review","neighbourhood_group"],axis=1) ## select multiple columns print('unique values of n_group',rentals.neighbourhood_group.unique()) print('unique values of room_type',rentals.room_type.unique()) #print('unique values of n_hood',rentals.neighbourhood.unique()) # categorical variables will be mapped with help of cat.code. rentals['room_type'] = rentals['room_type'].astype("category").cat.codes rentals['neighbourhood_group'] = rentals['neighbourhood_group'].astype("category").cat.codes rentals['neighbourhood'] = rentals['neighbourhood'].astype("category").cat.codes rentals = rentals[["number_of_reviews","neighbourhood_group", \ "longitude", "room_type","price"]][1:20000] from scipy import stats #We drop all rows with NaN values rentals = rentals.dropna() #Then we drop all prices that are equal to 0 rentals = rentals[rentals.price != 0] #Finally we drop values that are further than three standard deviations from the mean. z = np.abs(stats.zscore(rentals['price'])) print(type(z)) #<class 'numpy.ndarray'> rentals = rentals[z < 3] #Data ready ,lets split it. we will do with a train and test set. train, test = train_test_split(rentals, random_state=12) target = 'price' #Also we serve the reg the target y_train= train[target] X_train = train.drop([target], axis=1) y_test= test[target] X_test = test.drop([target], axis=1) print('full rental shape: ',rentals.shape) print('train shape len1: ',len(y_train),len(X_train)) print('test shape len2: ',len(y_test),len(X_test)) #print(y_train) from sklearn.svm import SVR #scaler = StandardScaler() #X_train = scaler.fit_transform(X_train) # - Create SVR model and train it svr_rbf= SVR(kernel='rbf',C=50,gamma=0.5, verbose=True) #x_train = x_train.reshape(-1,1) svr_rbf.fit(X_train,y_train) print('predict ',svr_rbf.predict(X_test)[1:20]) #DBASTAr - Get score R2 confidence svr_rbf_confidence=svr_rbf.score(X_test,y_test) print(f"SVR Confidence: {round(svr_rbf_confidence*100,2)}%") print('R2 %f' % r2_score(y_test, svr_rbf.predict(X_test))) print('MAE: %f' % mean_absolute_error(y_test,svr_rbf.predict(X_test))) #MAE print('RMSE: %f' % np.sqrt(mean_squared_error(y_test,svr_rbf.predict(X_test)))) #RMSE import matplotlib.pyplot as plt import seaborn as sns plt.figure(figsize=(8,12)) palette = sns.diverging_palette(20, 220, n=256) corr=rentals.corr(method='pearson') sns.heatmap(corr, annot=True, fmt=".2f", cmap=palette, vmax=.3, center=0, square=True, linewidths=.5, cbar_kws={"shrink": .5}).set(ylim=(5,0)) plt.title("Rentals Correlation Matrix",size=15, weight='bold') plt.show() # ql = feyn.QLattice(url = "your_qlattice_url", api_token = "your_api_token")
Java
We compare a Tokenizer from maXbox Pascal to Java
sr:= 'This is!a.sample text,with punctuation!marks@and_space''s and two .words'; wordlist2:= TStringlist.create; SplitRegExpr('[!._,''@?\s]', sr, wordlist2) writeln('tokenizer items to inspect2: '+itoa(wordlist2.count)); for it:= 0 to wordlist2.count-1 do write(itoa(it)+' '+wordlist2.strings[it]+' '); wordlist2.free;
Output: 0 This 1 is 2 a 3 sample 4 text 5 with 6 punctuation 7 marks 8 and 9 space 10 s 11 and 12 two 13 14 words
For example, if you pass single space “ “ as a delimiter to this method and try to split a String. This method considers the word between two spaces as one token and returns an array of words (between spaces) in the current String.
Therefore, to split a string at every space and punctuation, invoke the split() method on it by passing the above specified regular expression as a parameter.
import java.util.Scanner; import java.util.StringTokenizer; public class RegExample { public static void main( String args[] ) { String regex = "[!._,'@? ]"; System.out.println("Enter a string: "); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); StringTokenizer str = new StringTokenizer(input,regex); while(str.hasMoreTokens()) { System.out.println(str.nextToken()); } } }
Article at ML Conference Munich:
http://www.softwareschule.ch/examples/992_detector21_wget_integrate2.htm
[16 rows x 3 columns]
unique values of n_group [‘Brooklyn’ ‘Manhattan’ ‘Queens’ ‘Staten Island’ ‘Bronx’]
unique values of room_type [‘Private room’ ‘Entire home/apt’ ‘Shared room’]
full rental shape: (19836, 5)
train shape len1: 14877 14877
test shape len2: 4959 4959
…………….. …..
optimization finished, #iter = 22286
obj = -35743277.478693, rho = -95.344865
nSV = 14828, nBSV = 13888
[LibSVM]predict [131.02293814 62.00901798 119.05872585 177.55307327 86.9398244
153.54274126 52.94037611 174.61665161 95.32338823 94.60439355
62.98206385 172.07078977 62.94059634 62.45954219 130.7547558
49.25527038 161.02574779 151.04497807 81.83590457]
SVR Confidence: 25.69%
R2 0.256940
MAE: 49.731829
RMSE: 86.498994
C:\maXbox\mX46210\DataScience\confusionlist>
In this tutorial, we’re going to walk through how to set up a basic Python repl that can learn the difference between two categories of sentences, positive and negative.
https://repl.it/@MaxKleiner/machinelearning4#main.py
https://repl.it/@MaxKleiner/machinelearning4#main.py
from sklearn import tree from sklearn.feature_extraction.text import CountVectorizer #https://ritza.co/showcase/repl.it/introduction-to-machine-learning-with-python-and-repl-it.html positive_texts = [ "we love you", "they love us", "you are good", "he is good", "they love max" ] negative_texts = [ "we hate you", "they hate us", "you are bad", "he is bad", "we hate max" ] test_texts = [ "they love mad max", "they are good", "why do you hate mary", "they are almost always good", "we are very bad" ] print('testset: ',test_texts) training_texts = negative_texts + positive_texts training_labels = ["negative"] * len(negative_texts) + ["positive"] * len(positive_texts) #print(training_labels) #mapping the words to numbers (bag of words) vectorizer = CountVectorizer() vectorizer.fit(training_texts) print('vocabulary: ',vectorizer.vocabulary_) #vectorizer.fit(test_texts) #print(vectorizer.vocabulary_) training_vectors = vectorizer.transform(training_texts) testing_vectors = vectorizer.transform(test_texts) classifier = tree.DecisionTreeClassifier() classifier.fit(training_vectors, training_labels) predictions = classifier.predict(testing_vectors) print('predict: ',predictions) #print('testset: ',test_texts) #http://www.webgraphviz.com/ tree.export_graphviz( classifier, out_file='maxtree.dot', feature_names=vectorizer.get_feature_names(), ) # Create a linear SVM classifier clf = svm.SVC(kernel='linear') # Train classifier clf.fit(training_vectors, training_labels) # Make predictions on unseen test data clf_predictions = clf.predict(testing_vectors) print('predict SVC: ',clf_predictions) test_labels=['positive','positive','negative','positive','negative'] print("Accuracy: {}%".format(clf.score(testing_vectors,test_labels)*100))
Teaching in Code Hybrid Mode
Function ExecuteMultiProcessor(FileName:string; Visibility:Int; BitMask:Int; Synch:Bool): Longword; if ExecuteMultiProcessor('notepad.exe',SW_SHOW,4,true)= 0 then writeln('Multiprocessing Runs on kernel CPU 3;
Therefore, in short, Logical cores are the number of Physical cores times the number of threads that each core can run.
//#sign:breitsch: BREITSCH-BOX: 01.10.2020 17:18:06
//#tech:.4.64perf: 0:0:3.559 threads: 10 192.168.56.1 17:18:06 4.7.4.6498
//bitmask ---> 1 means on first CPU, sync or async possible! //bitmask ---> 2 means on second CPU, sync or async possible! //bitmask ---> 4 means on third CPU, sync or async possible! //bitmask ---> 8 means on fourth CPU, sync or async possible -true-false! if ExecuteProcess(exepath+EXENAME+' '+ FILETO_RUN +' para1', SW_SHOW, 1, false)= 0 then writeln('Multiproc Runs on CPU 1'); if ExecuteProcess(exepath+EXENAME+' '+ FILETO_RUN +' para2', SW_SHOW, 2, false)= 0 then writeln('Multiproc Runs on CPU 2'); if ExecuteProcess(exepath+EXENAME+' '+ FILETO_RUN +' para3', SW_SHOW, 4, false)= 0 then writeln('Multiproc Runs on CPU 3'); if ExecuteProcess(exepath+EXENAME+' '+ FILETO_RUN +' para3', SW_SHOW, 8, false)= 0 then writeln('Multiproc Runs on CPU 4'); if ExecuteProcess(exepath+EXENAME+' '+ FILETO_RUN +' para3', SW_SHOW, 16, false)= 0 then writeln('Multiproc Runs on CPU 5'); if ExecuteProcess(exepath+EXENAME+' '+ FILETO_RUN +' para3', SW_SHOW, 32, false)= 0 then writeln('Multiproc Runs on CPU 6'); if ExecuteProcess(exepath+EXENAME+' '+ FILETO_RUN +' para3', SW_SHOW, 64, false)= 0 then writeln('Multiproc Runs on CPU 7'); if ExecuteMultiProcessor(exepath+EXENAME+' '+ FILETO_RUN +' para4', SW_SHOW, 128, false) = 0 then begin writeln('Multiproc Runs on CPU 8'); ShowMessage(SysErrorMessage(GetLastError)) end;
Problem — Given a dataset of m training examples, each of which contains information in the form of various features and a label. Each label corresponds to a class, to which the training example belongs to. In multiclass classification, we have a finite set of classes. Each training example also has n features.
For example, in the case of identification of different types of fruits, “Shape”, “Color”, “Radius” can be features and “Apple”, “Orange”, “Lemon” , “Mandarin”, can be different class labels.
In a multiclass classification, we train a classifier using our training data, and use this classifier for classifying new examples.
At least the shortest song ever (1:43) with the shortest text: You from G9
https://www.top4download.com/maxbox/upiwcqtc.html.

Originally published at http://maxbox4.wordpress.com on September 28, 2020.