C++ quick matrix calculation of XDX^T for X fixed, D diagonal and changing
Take a fixed n by m matrix X. I am interested in creating a function which takes in an m dimensional vector v, and outputs XDX^T where D is a diagonal matrix with entries of v along its diagonals. For fast calculation (here n is around 2000, m can be from 10000 to 100000), my idea is based on one observation.
Note that XDX^T = sum_{i=1,...,m} (Y_i Y_i^T)*v_i where Y_i are the columns of X (so X = [Y_1 Y_2 .... Y_m].
So initially we precaculate and save the n by n matrices (Y_i Y_i^T) for i=1,...,m. This will be saved as an array of m matrices. Then we create a function which takes this array of matrices and v as input, applies element wise multiplication behind v and the array, then returns the sum of the m matrices.
However, I am very new to C++, and efficiently writing this program is difficult. Any help on doing this quickly, and whether this is a good idea? At the moment I am calculate XDX^T using crossproduct function in the Eigen library. My intuition is the above method should be much faster (we are trading off memory for speed). Thanks.
See also questions close to this topic
 a value of type "LPVOID" cannot be assigned to an entity of type "void(*)(DWORD)"

Homework radioamateur  Problem with HH:MM time format
I have a homework  I must to create script with time of broadcasting. Broadcasting is when time is for example 12:21 or 02:20  just the same from behind and from the begin too. I want that time writes in HH:MM format. All works good but up to one thing.. When time < 10 it not was in HH:MM format but is in H:MM format example  04:40 outputs as 4:40  It's a problem.
#include <iostream> #include <string> #include <queue> #include <tuple> #include <limits> int main() { std::cout << "Give me a number: " << std::endl; int c; std::cin >> c; if (c < 1) { std::cout << "Incorrect!." << std::endl; main(); } else if (c > 2000) { std::cout << "Incorrect!" << std::endl; main(); } else { std::cout << "Correct value." << std::endl; std::queue<std::tuple<int, int>> casy; for (int i = 0; i < c; i++) { std::cout << "Give me a time number. " << i << " (HH:MM): "; int hour, minute; char c; std::cin >> hour >> c >> minute; std::cin.clear(); std::cin.ignore(10000, '\n'); /* Uložení času do fronty [std::queue] */ casy.push(std::make_tuple(hour, minute)); } for (int u = 0; u = times.size(); u++) { int broadcastingTimes[15][2] = { { 01, 10 },{ 02, 20 },{ 03, 30 },{ 04, 40 },{ 05, 50 },{ 10, 01 },{ 11, 11 },{ 12, 21 },{ 13, 31 },{ 14, 41 },{ 15, 51 },{ 20, 02 },{ 21, 12 },{ 22, 22 },{ 23, 32 } }; int actuallyBroadcastingIndex = 0; for (int o = 0; o < 15; o++) { if (std::get<0>(times.front()) == broadcastingTimes[o][0]) { if (std::get<1>(times.front()) <= broadcastingTimes[o][1]) { /*if(o != 0) { if(std::get<0>(times.front()) > broadcastingTimes[o1][0]) { if(std::get<0>(times.front()) > broadcastingTimes[o1][1]) { actuallyBroadcastingIndex = o; } else { actuallyBroadcastingIndex = o1; } } else { actuallyBroadcastingIndex = o; } } else { actuallyBroadcastingIndex = o; }*/ actuallyBroadcastingIndex = o; } else { actuallyBroadcastingIndex = o + 1; } if (std::get<0>(times.front()) == 23) { if (std::get<1>(times.front()) > 32) { actuallyBroadcastingIndex = 0; } } } else if (std::get<0>(times.front()) > broadcastingTimes[o][0] & std::get<0>(times.front()) < broadcastingTimes[o + 1][0]) { //std::cout << std::get<0>(casy.front()) << "/" << broadcastingTimes[o][0] << "\n"; actuallyBroadcastingIndex = o + 1; } } int hourInput = std::get<0>(times.front()); std::string timeInputedByUser = std::to_string(hourInput) + ":" + std::to_string(std::get<1>(times.front())); std::string broadcastingTimeActually = std::to_string(broadcastingTimes[actuallyBroadcastingIndex][0]) + ":" + std::to_string(broadcastingTimes[aktualniVysilaniIndex][1]); //std::cout << "sss" << broadcastingTimes[actuallyBroadcastingIndex][0] << "\n"; std::cout << "Nearest broadcasting from " << timeInputedByUser << " will be at " << broadcastingTimeActually << std::endl; casy.pop(); std::cin.get(); } } return 0; }
Expected results are: if nearest broadcasting time will be 04:40  it will be outputs as 04:40  Not 4:40 as now. If nearest broadcasting time is 14:41, all works alright..

Can't Spawn Static Mesh Component
I am trying to spawn a grid but nothing happens. Not even a compile error. At first unreal couldn't find the path. (("
/Game/ModelsTextures/StaticMeshes/Plane_64x64.uasset
")So I couldn't even open unreal. Somehow fixed it now I can compile it without an error but I can't make it work. HELP.
I dont know is it still because of the Path so here's the folder that has the Plane_64x64
F:\UE_projects\GridGame\Content\ModelsTextures\StaticMeshes
#include "GridGenerator.h" #include "Components/StaticMeshComponent.h" #include "ConstructorHelpers.h" // Sets default values AGridGenerator::AGridGenerator() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = false; size = 16; sum = size * size; offsetAmount = 65; for (int i = 0; i < sum; i++) { if (sum % size == 0) { FVector temp; temp.X = sum+offsetAmount; temp.Y = offsetAmount; temp.Z = 0; offsetVector = offsetVector+temp; ReactiveFloor(worldLocation); MeshArray[i] = Mesh; offsetVector.X = offsetVector.X + offsetAmount; } else { ReactiveFloor(worldLocation); MeshArray[i] = Mesh; offsetVector.X = offsetVector.X + offsetAmount; } } } UStaticMeshComponent* AGridGenerator::SpawnMesh(FVector offsetVector) { UStaticMeshComponent* Grid = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Grid")); Grid>SetupAttachment(RootComponent); static ConstructorHelpers::FObjectFinder<UStaticMesh>GridAsset(TEXT("/Game/ModelsTextures/StaticMeshes/Plane_64x64.uasset")); Grid>SetStaticMesh(GridAsset.Object); Grid>SetRelativeLocation(offsetVector); Grid>SetWorldScale3D(FVector(1.f)); worldLocation = offsetVector; return Grid; } void AGridGenerator::ReactiveFloor(FVector worldLocation) { FCollisionQueryParams RV_TraceParams = FCollisionQueryParams(FName(TEXT("RV_Trace")), true, this); RV_TraceParams.bTraceComplex = true; RV_TraceParams.bTraceAsyncScene = true; RV_TraceParams.bReturnPhysicalMaterial = false; FHitResult RV_Hit(ForceInit); GetWorld()>LineTraceSingleByChannel(RV_Hit, worldLocation + (FVector(0, 0, 2000)), worldLocation  (FVector(0, 0, 2000)), ECC_EngineTraceChannel1); FVector temp2; temp2.X = worldLocation.X; temp2.Y = worldLocation.Y; temp2.Z = RV_Hit.ImpactPoint.Z; FRotator tempR; tempR.Pitch = (RV_Hit.ImpactNormal.X * 45); tempR.Roll = (RV_Hit.ImpactNormal.Y * 45); SetActorLocationAndRotation(temp2, tempR); }

From Double Array To DataTable (With Typecast)
I have a
datagridview
and I want to add my values into it from getting SQL Server table. But I want to normalize the all values before adding. How can I add my array values into the datatable row again?It's my code:
foreach (DataRow r in d.Rows) { double[] col = d.AsEnumerable().Select(r => r.Field<double>("column3fromsqltable")).ToArray(); double maximumVal = col.Max(); for (int q=0; q<col.Length; q++) { col[q] = col[q] / maximumVal; } for(int m=0; m< col.Length; m++) { col[m] = col[m] * 100; } dgw.Rows.Add(r["column1fromsqltable"].ToString() + " " + r["column2fromsqltable"].ToString(), r["column3fromsqltable"]); }
Note: Please don't post sql codes, it doesn't work. I want to normalize only selected items. Sql codes always normalize all items (not only selected). I want to only add my col[m] values instead r["
column3fromsqltable
"]. And I did a typecast, normally my "column3fromsqltable
" values was integer, i did them double.Thank you for your answers.

AppleScript list of records to Swift Array (or better)
I test a little OSX app based on this example which use a bridge to AppleScript to get simple infos from iTunes.
Like I said in the ComboDrums's comment (it's me), I have a script to get all my iTunes playlists in a tree but as soon as the return is more complex than a simple string, it fails.
So I'm looking for the way to convert the AppleScript's list returned to a Swift friendly object.
Any idea ?
Thx.

Which one is more advantageous? ( Array or Linked List)  Insert at beginning or Insert at end
Please explain why in detail which of these two data structures I should use for given problem. Which one is more advantageous?
1)
You do quite some inserts at the beginning of your data structure. ( Array or Linked List)
2)
You do quite some inserts at end of your data structure. (Array or Linked List)
It's a homework question and no more options. I think first one is Linked List and second one is Array. Is it false? Why?

Python: improving speed based on cProfile results
I want to improve my code's speed and I am running cProfile to see what drags me down (I've put the output in an excel and order it by total time it took). The code below is a test code that only considers 10 calculations out of the total sample. In total, I would have around 3035 million calculations to do and taking even 1 second per calculation is too long. I would need something to make this run x1000 or at least x100 faster. I'm running the code on an i74510U. Can someone tell me what exactly the first few lines from the cProfile do, so I can pinpoint the cause? Or any other suggestions on how to improve the speed?
It is a lot read and think, so I want to thank in advance to whoever takes the time to help me.
CODE:
from sqlalchemy import create_engine import pandas as pd import cProfile path = 'A:/python project/testing/' def get_cik_per_ip(ip_item, master_df, date): cik_df = master_df[(master_df.date == date) & (master_df.ip == ip_item)] cik_list = cik_df['cik'].values.tolist() cik_set = set(cik_list) return cik_set def get_ips_per_day(master_df, date, base): ip_df = master_df[(master_df.date == date) & (master_df.cik == base)] ip_list = ip_df['ip'].values.tolist() ip_set = set(ip_list) return ip_set def get_num_den(base, peer, master_df, date_list): numerator = 0 denominator = 0 for date in date_list: ip_set = get_ips_per_day(master_df, date, base) for ip_item in ip_set: cik_set = get_cik_per_ip(ip_item, master_df, date) if base and peer in cik_set: numerator += 1 denominator += len(cik_set)  1 # print(numerator, denominator) return numerator, denominator def get_annual_fraction(): engine_db = create_engine("sqlite:///" + path + "test_pd.db") engine_scores = create_engine("sqlite:///" + path + "test_scores.db") master_df = pd.read_sql_table('testing_2', con=engine_db, columns=['ip', 'date', 'cik']) # print(master_df) master_df['ip'] = master_df['ip'].astype('category') master_df['date'] = master_df['date'].astype('datetime64[ns]') master_df['cik'] = master_df['cik'].astype('float64') list_base_firms = master_df['cik'].values.tolist() list_base_firms = set(list_base_firms) list_peer_firms = list_base_firms # print(len(list_base_firms)) date_df_list = master_df['date'].values.tolist() date_list = set(date_df_list) print("Number of dates: ", len(date_list)) counter = 0 for base in list_base_firms: # print("base :", base) final_df = pd.DataFrame(columns=["CIK_B", "CIK_peer", "numerator", "denominator", "asf"]) for peer in list_peer_firms: if peer == base: counter += 1 "do nothing" else: numerator, denominator = get_num_den(base, peer, master_df, date_list) if not denominator: annual_search_fraction = 0 else: annual_search_fraction = numerator/denominator # print("ASF between {} and {}: ".format(base, peer), annual_search_fraction) insert_df = pd.DataFrame({"CIK_B":['{}'.format(base)], "CIK_peer":['{}'.format(peer)], "numerator":["{}".format(numerator)], "denominator":["{}".format(denominator)], "asf":["{}".format(annual_search_fraction)]}) final_df = final_df.append(insert_df, ignore_index=True) if counter == 10: final_df.to_sql('test_scores', con=engine_scores, if_exists='append', chunksize=1000, index=False) break if counter == 10: break if counter == 10: break cProfile.run('get_annual_fraction()')

How to get Arraylist<Bitmap> with the help of Glide as output?
I have an arraylist mp3 file paths i want to extract thumbnails from them it is working fine with the given below but extraction speed is too slow.....
//filterpath==path of MP3 files for(String path:filterPath) { try { MediaMetadataRetriever mmr = new MediaMetadataRetriever(); mmr.setDataSource(path); byte[] data = mmr.getEmbeddedPicture(); if (data != null) { Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); MEDIACOVER.add(bitmap); mmr.release(); }else{ //add image from drawable } }
As I describe it is working fine but too slow to respond....that's why I use Glide to perform this task which is given below :
for(String path: filterPath){ MediaMetadataRetriever mmr = new MediaMetadataRetriever(); mmr.setDataSource(temp); byte[] data = mmr.getEmbeddedPicture(); if (data != null) { Glide.with(this) .asBitmap() .load(data) .thumbnail(0.1f) .listener(new RequestListener<Bitmap>() { @Override public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) { return false; } @Override public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) { imageview.setImageBitmap(resource); arrayList.add(resource); return false; } }).submit(); } } Toast.maketext(this,""+arraylist.size(),Toast.LENGTH_LONG).show();
Here, I used imageview for checking, The first image of total paths is extracting perfectly but if I add same resource at same time to arraylist it gives me null value.....
I want to get total images from total paths in arraylist or the main motive of this question is to improve the performance and boost the speed of my application.
Help me to solve this problem and feel free to get more description

Efficiency R codes in windows server
I test r codes in local computer and it works well. local computer: RAM:4 CPU:5i system: windows. I use same codes in windows server: RAM:64 CPU:Intel Xeon 2 x L5640 (24Core x 2.2GhzHT) and hard disk:1TB NVMe and R codes does not work more quickly and it does not work at all with more data. Why R does not have enough efficiency on the server? Unfortunately, I'm not familiar with Linux. I have limited time to use the server and I need your guidance.

Set up movable pivot point for objects in OpenGL
In order to change an object's pivot point, you translate the object to the pivot point, rotate it, and then translate to the negative of that point's location, like
model = translate(model, pivotLocation); model = rotate(model, angle, vec3(0, 1, 0)); model = translate(model, pivotLocation);
Now however if I move the origin location dynamically, the object in question starts translating in relation to the moving origin.
How do I keep the object stationary when I move the pivot point?

Tensorflow tensordot for unknown batch size
there might be an obvious solution, but I haven't found it yet. I want to do a simple multiplication, where I have one tensor that gives me a kind of weight vector and another one that are stacked tensors (same number as weights). It seems straight forward using
tf.tensordot
but that doesn't work for unknown batch sizes.import collections import tensorflow as tf tf.reset_default_graph() x = tf.placeholder(shape=(None, 4, 1), dtype=tf.float32, name='x') y_true = tf.placeholder(shape=(None, 4, 1), dtype=tf.float32, name='y_true') # These are the models that I want to combine linear_model0 = tf.layers.Dense(units=1, name='linear_model0') linear_model1 = tf.layers.Dense(units=1, name='linear_model1') agents = collections.OrderedDict() agents[0] = linear_model0(x) # shape (?,4,1) agents[1] = linear_model1(x) # shape (?,4,1) stacked = tf.stack(list(agents.values()), axis=1) # shape (?,2,4,1) # This is the model that produces the weights x_flat = tf.layers.Flatten()(x) weight_model = tf.layers.Dense(units=2, name='weight_model') weights = weight_model(x_flat) # shape: (?,2) # This is the final output y_pred = tf.tensordot(weights, stacked, axes = 2, name='y_pred') # PROBLEM HERE: shape: (4,1) instead of (?,4,1) # Running the whole thing sess = tf.Session() init = tf.global_variables_initializer() sess.run(init) # Example1 (output of shape (1,4,1) expected, got (4,1)) print('model', sess.run(y_pred, {x: [[[1], [2], [3], [4]]]}).shape) # Example2 (output of (2,4,1) expected, got (4,1)) print('model', sess.run(y_pred, {x: [[[1], [2], [3], [4]], [[1], [2], [3], [4]]]}).shape)
So, the multiplication works as expected for the first input, but does only that first one and not a batch of inputs. Any help?
Similar questions that didn't resolve my issue:

Numpy dot and matmul functions difference
I am referring an example of matrix multiplication in Numpy.
import numpy as np b=np.ones((1, 2, 4, 2)) a=np.ones((2, 2, 4)) np.dot(a,b) Result: array([[[[[4., 4.], [4., 4.]]], [[[4., 4.], [4., 4.]]]], [[[[4., 4.], [4., 4.]]], [[[4., 4.], [4., 4.]]]]]) np.matmul(a,b) array([[[[4., 4.], [4., 4.]], [[4., 4.], [4., 4.]]]])
As both operations are used for multiplication of matrix, why is the output of both function different? How internally both functions work? And Which function should be used in which scenario? Can anyone give me detailed explanation of this?