text:
Q: Should technology (aka tag) badges awarding depend on number of question on the topic?
Possible Duplicate:
Lower the required upvotes for badges in "small" (framework/tools) tags

Currently to obtain bronze technology badge, one needs to gather 100 up votes. To obtain silver and gold one need to gather 400 and 1000 up votes respectively.
The issue is, for less popular tag it is pretty hard to even think of getting bronze badge - it seems like gold one. That is just because the questions won't attract large number of people, so the answer might be insightful and valuable but still could end up with no up vote (but be accepted).
What do you think? I would suggest that for mature tags (existing for more than one year) the number of up votes to gain tag-related badge should depend on a traffic. For large tags like Java or C# 100 up votes seem just too easy to get, so maybe the number should be sufficiently larger and for tags like extjs with less than 2% of their traffic, 100 up votes is pretty hard to get.
So maybe 50 for bronze badge, 100 for silver and 250 for gold would give a clearer picture of user's competency in the subject.

A: Note that while it takes longer to get the badge (because there are fewer votes) you also have less competition for getting the votes. This helps mitigate the problem, in my opinion.
Taken to the extreme, this also might cause a bit of gaming of the system. Nefarious users might create questions with seldom-used tags in order to increase their badges. (This 'gaming' argument is a weak one, however.)
Edit: Oh, and one more point: if a tag/technology is seldom-used, that indicates that it's not that interesting to the majority of the SO population. Why should we encourage the growth of an otherwise-niche technology?

A: I think the way it works now encourages those in the lesser tags (like myself) to work harder at it, thereby helping grow the tag.


text:
Q: 2 Macs sharing Displays via Spaces or something else? My partner and I work on iOS apps together, he's on one Mac and I'm on another. We often need to see each other's displays though and right now we have a monitor that we swap back and forth. When I want him to watch my screen, I plug the monitor into my external display port and spin the monitor around to him (and vice versa).
Is there any way to get a video IN signal such that I could just swap to a different virtual desktop in Spaces (or something else) and see what he's doing without having to do this lame hardware swapping?
The external monitor I have doesn't match the resolution of our Macs, so whenever we plug in to share the screen it reduces the size of our desktops and that sucks.
Any suggestions?
Looking over the shoulder isn't an acceptable answer ;)

A: Screen sharing?  It does exactly what (I think) you're trying to do.
System Preferences > Sharing > Screen Sharing.  You may need to create him an account on your machine, and vice-versa.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to Get Connected Component with Graphframes in Pyspark and Raw Data in Spark Dataframe? I have a spark data frame which looks like below:
+--+-----+---------+
|id|phone|  address|
+--+-----+---------+
| 0|  123| james st|
| 1|  177|avenue st|
| 2|  123|spring st|
| 3|  999|avenue st|
| 4|  678|  5th ave|
+--+-----+---------+

I am trying to use graphframes package to identify the connected component of ids using phone and address from above spark data frame. So this data frame can be treated as vertices data frame of the graph.
I am wondering what would be the optimal approach creating the edges data frame of the graph to feed into the connectedComponents() function in graphframes?
Ideally, the edges data frame should look like below:
+---+---+------------+
|src|dst|relationship|
+---+---+------------+
| 0 |  2|  same_phone|
| 1 |  3|same_address|
+---+---+------------+

Finally, the connectedComponents() results should be like below. id 0 & 1 are in the same component based on the same_phone relationship and 1 & 3 based on the same_address relationship. Then, this would leave 4 as another component which has no connection with other ids.
+---+-------------------+
|id |connected_component|
+---+-------------------+
|0  |1                  |
|1  |2                  |
|2  |1                  |
|3  |2                  |
|4  |3                  |
+---+-------------------+

Thanks in advance!

A: from functools import reduce

edges = reduce(
    lambda x, y: x.union(y),
    [df.alias('t1')
       .join(df.alias('t2'), c)
       .filter('t1.id < t2.id')
       .selectExpr('t1.id src', 't2.id dst', "'same_%s' relationship"% c) for c in df.columns[1:]
    ]
)

edges.show()
+---+---+------------+
|src|dst|relationship|
+---+---+------------+
|  0|  2|  same_phone|
|  1|  3|same_address|
+---+---+------------+

import pyspark.sql.functions as F
from pyspark.sql.window import Window

connect = edges.select(
    F.array_sort(F.array('src', 'dst')).alias('arr')
).distinct().union(
    df.join(edges, (df.id == edges.src) | (df.id == edges.dst), 'anti').select(F.array('id'))
).withColumn(
    'connected_component',
    F.row_number().over(Window.orderBy('arr'))
).select(F.explode('arr').alias('id'), 'connected_component')

connect.show()
+---+-------------------+
| id|connected_component|
+---+-------------------+
|  0|                  1|
|  2|                  1|
|  1|                  2|
|  3|                  2|
|  4|                  3|
+---+-------------------+


text:
Q: pentaho data integration - cant connect to mysql anyone can help me to resolve my problem?
i can't connect from pentaho to mysql
Error connecting to database [mysql - simpeg] :org.pentaho.di.core.exception.KettleDatabaseException:
Error occurred while trying to connect to the database

Driver class 'org.gjt.mm.mysql.Driver' could not be found, make sure the 'MySQL' driver (jar file) is installed.
org.gjt.mm.mysql.Driver

org.pentaho.di.core.exception.KettleDatabaseException:
Error occurred while trying to connect to the database

Driver class 'org.gjt.mm.mysql.Driver' could not be found, make sure the 'MySQL' driver (jar file) is installed.
org.gjt.mm.mysql.Driver

i already add at \pdi-ce-8.2.0.0-342 PENTAHO\data-integration\lib

com.mysql.jdbc_5.1.5.jar

and i restart my PDI, when i try again, the problem is same.
please help me. Thanks

A: Pentaho Data Integration uses mysql-connector-java-5.x.xx-bin.jar to connect MySQL for example mysql-connector-java-5.1.49-bin.jar and you can download MySQL driver from here also you can find PDI's JDBC Drivers Reference from here


text:
Q: hazelcast queue is not accesssible from listener I have a message queue called (train) and whenever anything added to it I want to create a new queue or perform some operations . So i have attached the listener  to the queue and from the listener I am starting new queue. But the problem is I could not start a queue from the listener as it throwing some error.
'''
This function will be called when we add anything to message_queue.
'''
def notify_when_added(event):
    res = event.item
    if res.status == Activity.train:
        print(res.text)
    elif res.status == Activity.predict:
        print('predict')
        queue = MessageQueue.create_msg_queue("predict") #error in this line

if __name__ == "__main__":
    #load_predictor()
    train_queue = MessageQueue.create_msg_queue("train")

    train_queue.add_listener(True, notify_when_added) #creating a listener
    res = Response(Activity.predict, "Model Trained with test accuracy of: ", "coles_auto_4", 5002)
    train_queue.add_all([res])
    app.run(threaded=True)

So basically here I am adding something to train_queue and want to create new queue which will be used by other processes. But I am getting the following error. This error occurs only when I use add_listener and try to create or access queue in listener. I want to start a queue from the listener which can be used by other process.
Traceback (most recent call last):
  File "C:\Users\shiva_burade\AppData\Roaming\Python\Python36\site-packages\hazelcast\cluster.py", line 124, in _connect_to_cluster
    self._connect_to_address(address)
  File "C:\Users\shiva_burade\AppData\Roaming\Python\Python36\site-packages\hazelcast\cluster.py", line 171, in _connect_to_address
    connection = f.result()
  File "C:\Users\shiva_burade\AppData\Roaming\Python\Python36\site-packages\hazelcast\future.py", line 58, in result
    self._reactor_check()
  File "C:\Users\shiva_burade\AppData\Roaming\Python\Python36\site-packages\hazelcast\future.py", line 70, in _reactor_check
    "Synchronous result for incomplete operation must not be called from Reactor thread. "
RuntimeError: Synchronous result for incomplete operation must not be called from Reactor thread. Use add_done_callback instead.
Aug 27, 2019 05:41:19 PM HazelcastClient.ClusterService
WARNING: [3.12.1] [dev] [hz.client_1] Unable to get alive cluster connection, attempt 2 of 2
Aug 27, 2019 05:41:19 PM HazelcastClient.InvocationService
WARNING: [3.12.1] [dev] [hz.client_0] Error handling event ClientMessage:{length=327, correlationId=6, messageType=204, partitionId=216, isComplete=True, isRetryable=False, isEvent=True, writeOffset=22}
Traceback (most recent call last):
  File "C:\Users\shiva_burade\AppData\Roaming\Python\Python36\site-packages\hazelcast\invocation.py", line 293, in _handle_event
    invocation.event_handler(message)
  File "C:\Users\shiva_burade\AppData\Roaming\Python\Python36\site-packages\hazelcast\proxy\queue.py", line 91, in <lambda>
    lambda m: queue_add_listener_codec.handle(m, handle_event_item),
  File "C:\Users\shiva_burade\AppData\Roaming\Python\Python36\site-packages\hazelcast\protocol\codec\queue_add_listener_codec.py", line 48, in handle
    handle_event_item(item=item, uuid=uuid, event_type=event_type)
  File "C:\Users\shiva_burade\AppData\Roaming\Python\Python36\site-packages\hazelcast\proxy\queue.py", line 85, in handle_event_item
    item_added_func(item_event)
    File "controller_flask.py", line 33, in notify_when_added
queue = MessageQueue.create_msg_queue("predict")
  File "D:\text category\message_queue.py", line 56, in create_msg_queue
    client = hazelcast.HazelcastClient(config)
  File "C:\Users\shiva_burade\AppData\Roaming\Python\Python36\site-packages\hazelcast\client.py", line 59, in __init__
    self._start()
  File "C:\Users\shiva_burade\AppData\Roaming\Python\Python36\site-packages\hazelcast\client.py", line 64, in _start
    self.cluster.start()
  File "C:\Users\shiva_burade\AppData\Roaming\Python\Python36\site-packages\hazelcast\cluster.py", line 50, in start
    self._connect_to_cluster()
  File "C:\Users\shiva_burade\AppData\Roaming\Python\Python36\site-packages\hazelcast\cluster.py", line 142, in _connect_to_cluster
    raise HazelcastError(error_msg)
hazelcast.exception.HazelcastError: Could not connect to any of {Address(host=127.0.0.1, port=5701)} after 2 tries

A: It may not answer the question fully but I also got the following error when I wanted to get/subscribe/unsubscribe from a topic inside a callback function called when a message is received from another topic.

Synchronous result for incomplete operation must not be called from
Reactor thread. Use add_done_callback instead.

Apparently, some operations that implies the Hazelcast client cannot be performed inside the callback function (the "Reactor" thread). As I could not add the add_done_callback on any of these operations, I eventually set a variable inside the callback function and check the status of this variable in the main (e.g. in a loop).
That's certainly not the most handy/efficient way but at least there is a workaround...


text:
Q: Azure B2C API Connector fails with http: 400 There was a problem processing your request. Please try again I've connection issues between Azure B2C API Connector and a CAPTCHA Web-Service.
Everything worked well until 31.12.2021. Not sure about the first week in January 2022.
All services, whenever offered by Microsoft are in a Swiss data center. Since January I'm playing Mail Ping-Pong with the MS Support Team :-(

*

*Azure B2C calling a service via Azure Front Door in detection mode fails.

*Azure B2C calling a the service "direct" works.

*Calling the service using Postman works via the Azure Front Door and Direct

I don't use custom policies, so no logs. Or maybe I don't know where to look?
Azure unfortunately only returns a HTTP 400 with the message "there was a problem".
The Service is not receiving any get request.
According to the Firewall log, no request is blocked.
Would be happy for any hints. My personal best guess - Microsoft did renew the X.509 SSL certificates and forgot one due to the 31.12.2021
But would be happy for anything else that might had changed?
Thanks a lot.


text:
Q: What does selecting the largest eigenvalues and eigenvectors in the covariance matrix mean in data analysis? Suppose there is a matrix B, where its size is a 500*1000 double(Here, 500 represents the number of observations and 1000 represents the number of features).
sigma is the covariance matrix of B, and D is a diagonal matrix whose diagonal elements are the eigenvalues of sigma. Assume A is the eigenvectors of the covariance matrix sigma.
I have the following questions:

*

*I need to select the first k = 800 eigenvectors corresponding to the eigenvalues with the largest magnitude to rank the selected features. The final matrix named Aq. How can I do this in MATLAB?

*What is the meaning of these selected eigenvectors?

*It seems the size of the final matrix Aq is 1000*800 double once I calculate Aq. The time points/observation information of 500 has disappeared. For the final matrix Aq, what does the value 1000 in matrix Aq represent now? Also, what does the value 800 in matrix Aq represent now?

A: I'm assuming you determined the eigenvectors from the eig function.  What I would recommend to you in the future is to use the eigs function.  This not only computes the eigenvalues and eigenvectors for you, but it will compute the k largest eigenvalues with their associated eigenvectors for you.  This may save computational overhead where you don't have to compute all of the eigenvalues and associated eigenvectors of your matrix as you only want a subset.  You simply supply the covariance matrix of your data to eigs and it returns the k largest eigenvalues and eigenvectors for you.

Now, back to your problem, what you are describing is ultimately Principal Component Analysis.  The mechanics behind this would be to compute the covariance matrix of your data and find the eigenvalues and eigenvectors of the computed result.  It has been known that doing it this way is not recommended due to numerical instability with computing the eigenvalues and eigenvectors for large matrices.  The most canonical way to do this now is via Singular Value Decomposition.  Concretely, the columns of the V matrix give you the eigenvectors of the covariance matrix, or the principal components, and the associated eigenvalues are the square root of the singular values produced in the diagonals of the matrix S.
See this informative post on Cross Validated as to why this is preferred:
https://stats.stackexchange.com/questions/79043/why-pca-of-data-by-means-of-svd-of-the-data
I'll throw in another link as well that talks about the theory behind why the Singular Value Decomposition is used in Principal Component Analysis:
https://stats.stackexchange.com/questions/134282/relationship-between-svd-and-pca-how-to-use-svd-to-perform-pca

Now let's answer your question one at a time.
Question #1
MATLAB generates the eigenvalues and the corresponding ordering of the eigenvectors in such a way where they are unsorted.  If you wish to select out the largest k eigenvalues and associated eigenvectors given the output of eig (800 in your example), you'll need to sort the eigenvalues in descending order, then rearrange the columns of the eigenvector matrix produced from eig then select out the first k values.
I should also note that using eigs will not guarantee sorted order, so you will have to explicitly sort these too when it comes down to it.
In MATLAB, doing what we described above would look something like this:
sigma = cov(B);
[A,D] = eig(sigma);
vals = diag(D);
[~,ind] = sort(abs(vals), 'descend');
Asort = A(:,ind);

It's a good thing to note that you do the sorting on the absolute value of the eigenvalues because scaled eigenvalues are also eigenvalues themselves.  These scales also include negatives.  This means that if we had a component whose eigenvalue was, say -10000, this is a very good indication that this component has some significant meaning to your data, and if we sorted purely on the numbers themselves, this gets placed near the lower ranks.
The first line of code finds the covariance matrix of B, even though you said it's already stored in sigma, but let's make this reproducible.  Next, we find the eigenvalues of your covariance matrix and the associated eigenvectors.  Take note that each column of the eigenvector matrix A represents one eigenvector.  Specifically, the ith column / eigenvector of A corresponds to the ith eigenvalue seen in D.
However, the eigenvalues are in a diagonal matrix, so we extract out the diagonals with the diag command, sort them and figure out their ordering, then rearrange A to respect this ordering.  I use the second output of sort because it tells you the position of where each value in the unsorted result would appear in the sorted result.  This is the ordering we need to rearrange the columns of the eigenvector matrix A.  It's imperative that you choose 'descend' as the flag so that the largest eigenvalue and associated eigenvector appear first, just like we talked about before.
You can then pluck out the first k largest vectors and values via:
k = 800;
Aq = Asort(:,1:k);

Question #2
It's a well known fact that the eigenvectors of the covariance matrix are equal to the principal components.  Concretely, the first principal component (i.e. the largest eigenvector and associated largest eigenvalue) gives you the direction of the maximum variability in your data.  Each principal component after that gives you variability of a decreasing nature.  It's also good to note that each principal component is orthogonal to each other.
Here's a good example from Wikipedia for two dimensional data:

I pulled the above image from the Wikipedia article on Principal Component Analysis, which I linked you to above. This is a scatter plot of samples that are distributed according to a bivariate Gaussian distribution centred at (1,3) with a standard deviation of 3 in roughly the (0.878, 0.478) direction and of 1 in the orthogonal direction.  The component with a standard deviation of 3 is the first principal component while the one that is orthogonal is the second component.  The vectors shown are the eigenvectors of the covariance matrix scaled by the square root of the corresponding eigenvalue, and shifted so their tails are at the mean.
Now let's get back to your question.  The reason why we take a look at the k largest eigenvalues is a way of performing dimensionality reduction.  Essentially, you would be performing a data compression where you would take your higher dimensional data and project them onto a lower dimensional space.  The more principal components you include in your projection, the more it will resemble the original data.  It actually begins to taper off at a certain point, but the first few principal components allow you to faithfully reconstruct your data for the most part.
A great visual example of performing PCA (or SVD rather) and data reconstruction is found by this great Quora post I stumbled upon in the past.
http://qr.ae/RAEU8a
Question #3
You would use this matrix to reproject your higher dimensional data onto a lower dimensional space.  The number of rows being 1000 is still there, which means that there were originally 1000 features in your dataset.  The 800 is what the reduced dimensionality of your data would be.  Consider this matrix as a transformation from the original dimensionality of a feature (1000) down to its reduced dimensionality (800).
You would then use this matrix in conjunction with reconstructing what the original data was.  Concretely, this would give you an approximation of what the original data looked like with the least amount of error.  In this case, you don't need to use all of the principal components (i.e. just the k largest vectors) and you can create an approximation of your data with less information than what you had before.
How you reconstruct your data is very simple. Let's talk about the forward and reverse operations first with the full data.  The forward operation is to take your original data and reproject it but instead of the lower dimensionality, we will use all of the components.  You first need to have your original data but mean subtracted:
Bm = bsxfun(@minus, B, mean(B,1));

Bm will produce a matrix where each feature of every sample is mean subtracted. bsxfun allows the subtraction of two matrices in unequal dimension provided that you can broadcast the dimensions so that they can both match up.  Specifically, what will happen in this case is that the mean of each column / feature of B will be computed and a temporary replicated matrix will be produced that is as large as B.  When you subtract your original data with this replicated matrix, the effect will subtract every data point with their respective feature means, thus decentralizing your data so that the mean of each feature is 0.
Once you do this, the operation to project is simply:
Bproject = Bm*Asort;

The above operation is quite simple.  What you are doing is expressing each sample's feature as a linear combination of principal components.  For example, given the first sample or first row of the decentralized data, the first sample's feature in the projected domain is a dot product of the row vector that pertains to the entire sample and the first principal component which is a column vector..  The first sample's second feature in the projected domain is a weighted sum of the entire sample and the second component.  You would repeat this for all samples and all principal components.  In effect, you are reprojecting the data so that it is with respect to the principal components - which are orthogonal basis vectors that transform your data from one representation to another.
A better description of what I just talked about can be found here.  Look at Amro's answer:
Matlab Principal Component Analysis (eigenvalues order)
Now to go backwards, you simply do the inverse operation, but a special property with the eigenvector matrix is that if you transpose this, you get the inverse.  To get the original data back, you undo the operation above and add the means back to the problem:
out = bsxfun(@plus, Bproject*Asort.', mean(B, 1));

You want to get the original data back, so you're solving for Bm with respect to the previous operation that I did.  However, the inverse of Asort is just the transpose here.  What's happening after you perform this operation is that you are getting the original data back, but the data is still decentralized.  To get the original data back, you must add the means of each feature back into the data matrix to get the final result.  That's why we're using another bsxfun call here so that you can do this for each sample's feature values.
You should be able to go back and forth from the original domain and projected domain with the above two lines of code.  Now where the dimensionality reduction (or the approximation of the original data) comes into play is the reverse operation.  What you need to do first is project the data onto the bases of the principal components (i.e. the forward operation), but now to go back to the original domain where we are trying to reconstruct the data with a reduced number of principal components, you simply replace Asort in the above code with Aq and also reduce the amount of features you're using in Bproject.  Concretely:
out = bsxfun(@plus, Bproject(:,1:k)*Aq.', mean(B, 1));

Doing Bproject(:,1:k) selects out the k features in the projected domain of your data, corresponding to the k largest eigenvectors.  Interestingly, if you just want the representation of the data with regards to a reduced dimensionality, you can just use Bproject(:,1:k) and that'll be enough.  However, if you want to go forward and compute an approximation of the original data, we need to compute the reverse step.  The above code is simply what we had before with the full dimensionality of your data, but we use Aq as well as selecting out the k features in Bproject.  This will give you the original data that is represented by the k largest eigenvectors / eigenvalues in your matrix.

If you'd like to see an awesome example, I'll mimic the Quora post that I linked to you but using another image.  Consider doing this with a grayscale image where each row is a "sample" and each column is a feature.  Let's take the cameraman image that's part of the image processing toolbox:
im = imread('camerman.tif');
imshow(im); %// Using the image processing toolbox

We get this image:

This is a 256 x 256 image, which means that we have 256 data points and each point has 256 features.  What I'm going to do is convert the image to double for precision in computing the covariance matrix.  Now what I'm going to do is repeat the above code, but incrementally increasing k at each go from 3, 11, 15, 25, 45, 65 and 125.  Therefore, for each k, we are introducing more principal components and we should slowly start to get a reconstruction of our data.
Here's some runnable code that illustrates my point:
%%%%%%%// Pre-processing stage
clear all;
close all;

%// Read in image - make sure we cast to double
B = double(imread('cameraman.tif'));

%// Calculate covariance matrix
sigma = cov(B);

%// Find eigenvalues and eigenvectors of the covariance matrix
[A,D] = eig(sigma);
vals = diag(D);

%// Sort their eigenvalues
[~,ind] = sort(abs(vals), 'descend');

%// Rearrange eigenvectors
Asort = A(:,ind);

%// Find mean subtracted data
Bm = bsxfun(@minus, B, mean(B,1));

%// Reproject data onto principal components
Bproject = Bm*Asort;

%%%%%%%// Begin reconstruction logic
figure;
counter = 1;

for k = [3 11 15 25 45 65 125 155]
    %// Extract out highest k eigenvectors
    Aq = Asort(:,1:k);

    %// Project back onto original domain
    out = bsxfun(@plus, Bproject(:,1:k)*Aq.', mean(B, 1));

    %// Place projection onto right slot and show the image
    subplot(4, 2, counter);
    counter = counter + 1;
    imshow(out,[]);
    title(['k = ' num2str(k)]);
end

As you can see, the majority of the code is the same from what we have seen.  What's different is that I loop over all values of k, project back onto the original space (i.e. computing the approximation) with the k highest eigenvectors, then show the image.
We get this nice figure:

As you can see, starting with k=3 doesn't really do us any favours... we can see some general structure, but it wouldn't hurt to add more in.  As we start increasing the number of components, we start to get a clearer picture of what the original data looks like.  At k=25, we actually can see what the cameraman looks like perfectly, and we don't need components 26 and beyond to see what's happening.  This is what I was talking about with regards to data compression where you don't need to work on all of the principal components to get a clear picture of what's going on.

I'd like to end this note by referring you to Chris Taylor's wonderful exposition on the topic of Principal Components Analysis, with code, graphs and a great explanation to boot!  This is where I got started on PCA, but the Quora post is what solidified my knowledge.
Matlab - PCA analysis and reconstruction of multi dimensional data


text:
Q: Bootstrap navbar button not clickable on mobile 'm not sure what I'm doing wrong… however here is my problem:
On this website: http://blog.cast.zhdk.ch/360/ I made with bootstrap, I created a menu where the «sandwich» menu button appears on all devices. I added some text to it.
It's not working on smartphone (tested on my iPhone 6, iOS 9.2); if I press the menu button just nothing happens. It works like a charm on my desktop iMac with the newest version Firefox. I couldn't find any HTML errors.
Here is my navbar source code for the wordpress theme (with a bootstrap navwalker):

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                Toggle navigation
                 Menu
            </button>

            <?php
                wp_nav_menu( array(
                    'menu'              => 'Primary Menu',
                    'theme_location'    => '360-menu',
                    'depth'             => 1,
                    'container'         => 'div',
                    'container_class'   => 'collapse navbar-collapse',
            'container_id'      => 'bs-example-navbar-collapse-1',
                    'menu_class'        => 'nav navbar-nav navbar-right',
                    'fallback_cb'       => 'wp_bootstrap_navwalker::fallback',
                    'walker'            => new wp_bootstrap_navwalker())
                );
            ?>


text:
Q: help with parsing json in .net I need help parsing this json, in this snippet there are only three items, but the list goes up to around 2000.
 {"1":
        {"Latitude":52.1643540,
         "Longitude":-2.154353,
         "Name":"AAA"
         },
     "2":
        {"Latitude":53.13,
         "Longitude":-2.13445,
         "Name":"BBB"
        },
     "3":
        {"Latitude":55.143243,
         "Longitude":-2.45234,
         "Name":"CCC"
        }}

I want to produce a List of "Place" objects and I want the number to be used as an ID
eg a class Place with properties PlaceId Latitude, Longitude, Name.
giving for the first list element:
place.PlaceId = 1
place.Latitude = 52.1643540
place.Longitude = 2.154353
place.Name = "AAA"

A: Have you tried using Json.NET? You can find an example on this previous SO post.

A: If you are able to change that JSON then I would go with James' answer but if it turns out tat you can't things will get more complicated.  I wasn't able to find a JSON serialiser that would understand that format with the index numbers in the JSON as property names.  It does however appear to be valid and is well understood by all of the browsers I tried.
I think your best option here is to use a Javascript library for .net (there are a couple of these but I like IronJS).  Using this you can just execute the JSON and read out the result.  Here is some sample code that reads your JSON from a file and writes the results to the console.
public class Place
{
    public int ID { get; set; }
    public double Latitude { get; set; }
    public double Longitude { get; set; }
    public string Name { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var ctx = new IronJS.Hosting.CSharp.Context();
        string json;
        using (TextReader reader = File.OpenText("array_items.txt"))
        {
            json = reader.ReadToEnd();
        }

        CommonObject result= (CommonObject)ctx.Execute("var x=" + json);
        Dictionary<uint,BoxedValue> indexes = new Dictionary<uint,BoxedValue>();
        result.GetAllIndexProperties(indexes, uint.MaxValue);
        List<Place> places = new List<Place>();

        foreach (uint idx in indexes.Keys)
        {
            Place p = new Place();
            p.ID = (int)idx;
            p.Name = (string)indexes[idx].Object.Members["Name"];
            p.Latitude = (double)indexes[idx].Object.Members["Latitude"];
            p.Longitude = (double)indexes[idx].Object.Members["Longitude"];
            places.Add(p);
        }

        foreach (Place place in places)
        {
            Console.WriteLine("ID = {0}", place.ID);
            Console.WriteLine("Name = {0}", place.Name);
            Console.WriteLine("Latitude = {0}", place.Latitude);
            Console.WriteLine("Longitude = {0}", place.Longitude);
        }

        Console.ReadKey();
    }
}

You do, however, need to be careful here.  Depending on where you are running this could leave you open to script injection attacks. It would be best to scan the JS for potentially harmful script (for example any content that isn't part of a number and isn't inside quotes).

A: Hi if you can't change your JSON you could deserialize it by doing the following:
    var serializer = new JavaScriptSerializer();
    var deserializedDictionary = serializer.Deserialize<Dictionary<string, PlaceDetails>>(jsonString);

    var result = new List<Place>();

    foreach (var key  in deserializedDictionary.Keys)
    {
        result.Add(new Place(key, deserializedDictionary[key]));
    }

Classes Required:
    public class PlaceDetails
    {
        public float Latitude { get; set; }
        public float Longitude { get; set; }
        public string Name { get; set; }
    }

    public class Place
    {
        public Place(string placeID, PlaceDetails placeDetails)
        {
            this.PlaceID = Convert.ToInt32(placeID);
            this.Latitude = placeDetails.Latitude;
            this.Longitude = placeDetails.Longitude;
            this.Name = placeDetails.Name;
        }

        public int PlaceID { get; set; }
        public float Latitude { get; set; }
        public float Longitude { get; set; }
        public string Name { get; set; }
    }

you'll still need a reference to System.Web.Extensions.dll and using the System.Web.Script.Serialization namespace.
Hope this helps.

A: Try desearilzation. Here is the posts you might help:
C# automatic property deserialization of JSON
Parse JSON in C#

A: I'd change the format of your JSON to be something like this:
[
    {
        "PlaceID" : 1,
        "Latitude" :52.1643540,
        "Longitude" :-2.154353,
        "Name" :"AAA"
    },
    {
        "PlaceID" : 2,
        "Latitude":53.13,
        "Longitude":-2.13445,
        "Name":"BBB"
    },
    {
        "PlaceID" : 3,
        "Latitude":55.143243,
        "Longitude":-2.45234,
        "Name":"CCC"
    }
]

I'd then use the following:
public class Place
{
    public int PlaceID { get; set; }
    public float Latitude { get; set; }
    public float Longitude { get; set; }
    public string Name { get; set; }
}

To deserialize I would use:
JavaScriptSerializer serializer = new JavaScriptSerializer();
var listOfPlaces = serializer.Deserialize<List<Place>>(jsonString);

In order to use the JavaScriptSerializer you will need a reference to System.Web.Extensions.dll and using the System.Web.Script.Serialization namespace.

A: Did it like this:
   public class Place
    {

        public string ID { get; set; }
        public string Name { get; set; }
        public float Latitude { get; set; }
        public float Longitude { get; set; }

    }
private void Run()
{
    List<Place> places = new List<Place>();
    JObject jObject = JObject.Parse(json);
    foreach (var item in jObject)
    {
        JToken jPlace = jObject[item.Key];
        float latitude = (float)jPlace["Latitude"];
        float longitude = (float)jPlace["Longitude"];
        string name = (string)jPlace["Name"];
        places.Add(new Place { ID = item.Key, Name = name, Latitude = latitude, Longitude = longitude });

    }
}


text:
Q: Правильная реализация MVVM У меня возник вопрос при освоении MVVM.
При таком подходе,когда существуют другие вспомогательные классы, к примеру классы сортировки данных или классы, которые изменяют в зависимости от данных интерфейс экрана (цвет или размер  элементов) нужно также все предоставлять через ViewModel?

A: Постарайтесь более лучше разобратся для чего-же нужен все таки MVVM. Вот вам ссылка Полное понимание MVVM на статью где если я не ошибаюсь идет цепочка статтей от самого простого понимания патерна до использования его в качестве построения полноценного GUI (Graphical user interface) приложения.
От себя отвечу на ваш вопрос, писать вью-модели для ваших моделей, необходимо лиш в том случаи если у вас есть клас (модель) который содержит данные и они изменяются посредством взаимодействия пользователя с интерфейсом. А если у вас есть клас который просто предоставляет необходимую функциональность, в вашем случаии например сортировка данных то для него воовсе не требуетсь никакая вью-модель, так так он не несет никаких данных. Тоесть пишите вью-модели для класов в том случаии если у него есть какие либо данные которые изменяются через пользовательский интерфейс вашего приложения.
Ну например у вас клас с полями name, surname. И в интерфейсе существуют соответствующие поля для ввода имени и фамилии. В таком случаи вам необходимо написать вью-модель, которая будет соеденять ваши данные: name, surname с соответствующими полями в интерфейсе для пользователя. Надеюсь мой ответ был полезен. За более подробной информацией перейдите по указанной ссылке.


text:
Q: How do i get the date from a min and max group by? I am a SAS Developer.
I have a sql to do group by for getting the min and max from a column called "CalculatedPower".
Below is the structure that i got from a group by statement
(lt_dt and lp_dt is what I want. I am putting it here but it is not in my actual table as i do not know how to achieve this)
:
station datetime        calculatedpower min_power   max_power   lt_dt               lp_dt
ABBA    28AUG2018:0:0:0     100         1            100        01SEP2018:1:0:0     28AUG2018:0:0:0
ABBA    31AUG2018:12:0:0    88          1            100        01SEP2018:1:0:0     28AUG2018:0:0:0
ABBA    01SEP2018:1:0:0     1           1            100        01SEP2018:1:0:0     28AUG2018:0:0:0
ZZZZ    07SEP2018:0:0:0     900         900          3000       07SEP2018:0:0:0     21SEP2018:0:0:0
ZZZZ    09SEP2018:0:0:0     1000        900          3000       07SEP2018:0:0:0     21SEP2018:0:0:0
ZZZZ    21SEP2018:0:0:0     3000        900          3000       07SEP2018:0:0:0     21SEP2018:0:0:0

As you all can see, I aggregate them by Station and use Min and Max function to get the min_power and max_power. For now, I need to also get the min datetime(into lt_dt) and max datetime(into lp_dt).
I will be expecting like below:
ABBA lt_dt is 01SEP2018:1:0:0 while lp_dt is 28AUG2018:0:0:0
Meaning to say, lp_dt(datetime based on max_power) while lt_dt(datetime based on min power)
My group by statement is as below:
proc sql;
select
station
,datetime
,calculatedpower
,min(calculatedpower) as lt_calculatedpower
,max(calculatedpower) as lp_calculatedpower
from sumall
group by
station
;
quit;

Is there a way to tweak my existing SQL statement to achieve the datetime that i want?
I tried an additional SQL statement like below(but it is taking forever to process 600k data, not sure if it works or not as it is still running)
proc sql;
select *,
case when calculatedpower=lt_calculatedpower then datetime end as lt_datetime
from minmax;
quit;

With this code, i foresee there will be issue if there are few rows with the same calculated power but different datetime that ties to 1 station.

A: In SQL you will need to use a sub-select that contains a case statement that identifies the date at which the min and max occur.  The sub-select is joined to the original table.
Note: SAS SQL will automatically rejoin summary (aggregate function) results when appropriate.
Example
In this example level1_id is for station, level2_seq is for datetime and x is for calculatedpower.
data have;
  do level1_id = 1 to 5;
    do level2_seq = 1 to 5;
      x = floor(100*ranuni(123));
      output;
    end;
  end;
run;

proc sql;
  create table want as
  select
    have.*
    , min(have.x) as min_x
    , max(have.x) as max_x
    , min(at.min_at) as min_x_first_at_seq
    , min(at.max_at) as max_x_first_at_seq
  from
    have
  left join
  (
    select inside.level1_id, inside.level2_seq
    , case when inside.x = min(inside.x) then inside.level2_seq else . end as min_at
    , case when inside.x = max(inside.x) then inside.level2_seq else . end as max_at
    from have inside
    group by inside.level1_id
  ) at
  on
    have.level1_id = at.level1_id and
    have.level2_seq = at.level2_seq
  group by
    have.level1_id
  order by
    have.level1_id, level2_seq
  ;

A: Here's the SAS PROC SUMMARY and a DATA STEP merge to get your final desired output.
Use the MAXID, MINID options on the OUTPUT statement to get the ID of the max and ID of the minimum values.
The first part of the solution generates your fake data - please provide data in that format in the future. Then the PROC SUMMARY calculates the statistics and you can merge it in. This should complete really quickly on your system, as in less than a minute.
data have;
input station $ datetime  anydtdtm.      calculatedpower ;
format datetime datetime.;
cards;
ABBA    28AUG2018:0:0:0     100
ABBA    31AUG2018:12:0:0    88
ABBA    01SEP2018:1:0:0     1
ZZZZ    07SEP2018:0:0:0     900
ZZZZ    09SEP2018:0:0:0     1000
ZZZZ    21SEP2018:0:0:0     3000
;;;;
run;

proc summary data=have nway;
class station;
id datetime;
var calculatedPower;
output out=summary min=Min_power max=max_power minid=min_date  maxid=max_Date;
run;

data final;
merge have summary;
by station;
run;

EDIT: removed autoname option, since I explicitly named the output variables.
EDIT2:
When multiple observations contain the same extreme values in all the MIN or MAX variables, PROC MEANS uses the observation number to resolve which observation to write to the output. By default, PROC MEANS uses the first observation to resolve any ties. However, if you specify the LAST option, then PROC MEANS uses the last observation to resolve any ties.
https://documentation.sas.com/?docsetId=proc&docsetTarget=p04vbvpcjg2vrjn1v8wyf0daypfi.htm&docsetVersion=9.4&locale=en#p1p58yhxlrc0can1scam7bco7y96


text:
Q: Display Firestore data into UIPicker Swift 4 I am still new in swift development, my problem is, I have Firestore structure as below:

the problem is to display the list of title from firestore into a uipicker, I need to get data into an array like below:
[firsProgramme, secondProgramme, thirdProgramme]
I managed to display all the "title" from firestore in the string, not in the array
below is the code:
func getprogram() {
 let db = Firestore.firestore()
    db.collection("Programme").getDocuments()
        {
            (querySnapshot, err) in

            if let err = err
            {
                print("Error getting documents: \(err)");
            }
            else
            {
                for document in querySnapshot!.documents {
                    let data = document.data()

                    let program = data["title"] as? String ?? ""
                  //  let agencyId = document.documentID
                    print(program)
                    //print("\(document.documentID) => \(document.data())");
                }

            }
    }

}

result print(program) return as below :
firstprogramme
secondprogramme
thirdprogramme
the other part for UIPicker is already being managed well.
Thanks in advance.

A: In you class create an array variable to hold information about your programs:
var programsArray: [String] = []
When reading data from Firebase, instead of print(program) use programsArray.append(program). Call UIPickerView reload function after you have all data.
DispatchQueue.main.async {
    self.your_picker_view.reloadAllComponents()
}
And of course, use this array inside your pickerview datasource methods.


text:
Q: populate chosen multiple get plugin with ajax request I am having trouble with populating chosen plugin multiple get with data from an ajax call. I tired following the below posts,
Jquery Chosen plugin - dynamically populate list by Ajax
Multiple Select - Chosen jQuery
Jquery chosen ajax call populate multiselelect not working
But did not help. The data just doesn't get filled :( my ajax request is as follows,

which returns a json string. the data gets properly displayed over here if I alert it out on a message box. But the issue is how to populate the multiple get plugin? following is my html,
 <select data-placeholder="Tag your question here" style="width:350px;height:50px;" multiple class="chosen-select" id="tags">
      <option value="" ></option>

 </select>

I am very new to this plugin and would very much appreciate your help :)
FYI
I did it using direct php as follows,
 <select data-placeholder="Tag your question here" style="width:350px;height:50px;" multiple class="chosen-select" id="tags">
      <option value="" ></option>

               <?php
                    $con=mysqli_connect("localhost","user","pass","db");
                    $result = mysqli_query($con,"SELECT * FROM tags");

                    while($row = mysqli_fetch_array($result))
                    {
                        echo"<option>".$row['tagName']."</option>";
                        echo"
";
                    }
                ?>
   </select>

and it properly displays the data, but the project requirement states it is a MUST to use AJAX request to populate data. Thank you very much :) your expert advice is very much appreciated :)

A: Fist of all check your url: 'index.php/rest/resource/qtag',
This may work :
success: function(data) {

   $("#tags").html(data).trigger('liszt:updated');

}

where data = (echo from sourse)

<option value=0> </option>
  <option value=1> Option 1 </option>
  <option value=2> Option 2  </option>


text:
Q: Google Charts: How to create tables with grouped columns names? I'm trying to create a table with Google Charts where some data in the column names could be placed in a higher-level column name to help with readability.
In this example, I would like to move "Group 1" and "Group 2" to a 'higher' level; so the left table would end up like the right table.

I've read through documentation and haven't found a reference for this. Is it possible? If yes, what would be a good approach? Thanks.

A: What about something like this (uses jQuery), you can modify for your own custom needs:
https://jsfiddle.net/7tq6sdwc/
 google.setOnLoadCallback(drawTable);

  function drawTable() {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Name');
    data.addColumn('number', 'Salary');
    data.addColumn('boolean', 'Full Time Employee');
    data.addRows([
      ['Mike',  {v: 10000, f: '$10,000'}, true],
      ['Jim',   {v:8000,   f: '$8,000'},  false],
      ['Alice', {v: 12500, f: '$12,500'}, true],
      ['Bob',   {v: 7000,  f: '$7,000'},  true]
    ]);

    var table = new google.visualization.Table(document.getElementById('table_div'));

    table.draw(data, {showRowNumber: true, width: '100%', height: '100%'});
      var tablehead ='
My Header	</tr';
      var stuff = jQuery('#table_div').find('thead').prepend(tablehead);

  }

Result:

A: I'm submitting this as an answer because I don't have sufficient reputation to comment, although it's really a comment on the answer by @KevinBrown:
First of all, this is great! I'd upvote, but again lack rep, so for what it's worth, +1.
There is a small bug, however- if the table is large enough to get scrollbars, the added header scrolls with the rows instead of staying put.  I see the "stock" header gets a dynamically-adjusted style="top: 40px;" where the top is changed as one scrolls through the table.  So far I haven't been able to get the added header to do the same.  If I figure it out, I'll post here unless someone gets it before me!
Got it:
You need to catch the scroll event on the table, then copy the style property of the stock header rows to your header rows.  There is probably a more elegant and/or robust way, but this is working for me at the moment:
google.setOnLoadCallback(drawTable);

function drawTable() {
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Name');
  data.addColumn('number', 'Salary');
  data.addColumn('boolean', 'Full Time Employee');
  data.addRows([
    ['Mike',  {v: 10000, f: '$10,000'}, true],
    ['Jim',   {v:8000,   f: '$8,000'},  false],
    ['Alice', {v: 12500, f: '$12,500'}, true],
    ['Bob',   {v: 7000,  f: '$7,000'},  true]
  ]);

  var table = new google.visualization.Table(document.getElementById('table_div'));

  table.draw(data, {showRowNumber: true, width: '100%', height: '100%'});
  var tablehead ='
My Header	</tr';
  var stuff = jQuery('#table_div').find('thead').prepend(tablehead);

  //Add scroll event handler to div enclosing table:
  var stuff = $('#playerTable_div').find('div').scroll(function(event) {
    //my custom header row is the first row in the thead section:
    var myHeaderRow = $('#playerTable_div').find('thead').children('tr');
    //the "stock" header row immediately follows mine:
    var stockHeaderRow = myHeaderRow.next('tr');
    //copy the stock th element's style to mine:
    var styleToCopy = stockHeaderRow.children('th').attr("style");
    myHeaderRow.children('th').attr("style", styleToCopy);
  });

}

Thanks to @Kevin for getting me started!


text:
Q: eslint not ignoring node_modules and getting error when try to lint I'm trying to implement eslint in a Next.js project.The file structure look like below
.eslintignore
.eslintrc.js
.next
.prettierrc
.stylelintrc.js
components
forms
modals
modules
node_modules

And I have node_modules/* in my .eslintignore file. When I try to lint these by eslint --fix /sources/**/*.js I am getting below error
You are linting "/sources/node_modules/ally.js", but all of the files matching the glob pattern "/sources/node_modules/ally.js" are ignored.

Anyone can help me to solve this? Thanks

A: If .eslintignore located in the same directory as node_modules you can specify it as node_modules.
# .eslintignore
node_modules
**/.next/**
**/_next/**
**/dist/**

.eslintignore follows .gitignore syntax.
See .gitignore specs for more details.

A: linters dosnt work same with diffrent node versions
in this case updating node to v16.x from v14.x worked for me.

if ignorefile config dosnt work for you. check your node version.


text:
Q: transform data frame with missing dates into time series I have an issue with transforming a data frame into a time series object.
The data frame is olympic from fpp package.
library(fpp)
olympic

How do I transform this data frame having a Year column with gaps into a time series to be used with fpp package for forecasting?
I tried
olympic_new <- ts(olympic[,-1], start=1896, end=1996, deltat=4)

but this does not work because the olympics during the war had a gap longer than 4 years.
How can I use the Year column in the olympic to be understood as the index of the new ts object?
My end goal is to use a forecasting function on the new object, such as:
meanf(olympic_new, h=4)

A: If you use dput(olympic) and copy it in your question, it would be easier for us.
olympic <-
structure(list(Year = c(1896L, 1900L, 1904L, 1908L, 1912L, 1920L,
1924L, 1928L, 1932L, 1936L, 1948L, 1952L, 1956L, 1960L, 1964L,
1968L, 1972L, 1976L, 1980L, 1984L, 1988L, 1992L, 1996L), time = c(54.2,
49.4, 49.2, 50, 48.2, 49.6, 47.6, 47.8, 46.2, 46.5, 46.2, 45.9,
46.7, 44.9, 45.1, 43.8, 44.66, 44.26, 44.6, 44.27, 43.87, 43.5,
43.49)), .Names = c("Year", "time"), class = "data.frame", row.names = c(NA,
-23L))

You just pad some NA where it is needed.
year <- seq.int(1896L, 1996L, by = 4L)
y <- rep.int(NA, length(year))
y[match(olympic$Year, year)] <- olympic$time

olympic_new <- ts(y, start = 1896, end = 1996, deltat = 4)

#Time Series:
#Start = 1896
#End = 1996
#Frequency = 0.25
# [1] 54.20 49.40 49.20 50.00 48.20    NA 49.60 47.60 47.80 46.20 46.50    NA
#[13]    NA 46.20 45.90 46.70 44.90 45.10 43.80 44.66 44.26 44.60 44.27 43.87
#[25] 43.50 43.49

Then
meanf(olympic_new,h=4)

#     Point Forecast    Lo 80    Hi 80    Lo 95    Hi 95
#2000       46.51957 42.93628 50.10285 40.91319 52.12594
#2004       46.51957 42.93628 50.10285 40.91319 52.12594
#2008       46.51957 42.93628 50.10285 40.91319 52.12594
#2012       46.51957 42.93628 50.10285 40.91319 52.12594


text:
Q: jquery value not updating on continous hover attempts I got a hover effect which should alert the value of that divs name="address". I got multiply divs with the class Display. But they each have their unique id. Below is what I got so far, but it aren't working. Any help is appreciated!
JS
$(".Display").hover(function(){
    alert($(this.id).find("[name='address']").val());
});

HTML

    <input type="hidden" name="address" value="somevalue">

A: try like this
$(this).find("input[name='address']").val()

SNIPPET

$(".Display").hover(function(){
    alert($(this).find("input[name='address']").val());
});

    <input type="hidden" name="address" value="somevalue">
  Jam

A: Fo what you are trying to do you need the # in the selector before the id:
$('#' + this.id).find("[name='address']").val()

However, there is no point in using the id to find the element when you already have a reference to the element:
$(this).find("[name='address']").val()

You don't even have to create a jQuery object from the element, you can use it as scope when you find the input:
$("[name='address']", this).val()


text:
Q: How to Scroll multiple scroll of same Controller at once with sync to another one horizontal scroll? so i have created a custom calender on top the dates will be in a horizontal scroll inside a list view builder
and below some icons as per the number of the days in a month in anthor list view builder
now the list view builder with icons is inside another list view builder which scroll vertically
i have used linked scroll controller and if i scroll the top one with dates the whole screen list with horizonal scroll happens as expected
But when i scroll any of the one row with icons only the date row is changing not the other rows with icon. so when i scroll row with icon only that one and the top horizontal scroll with the date is scrolling .
what iam trying to achieve is to scroll al the icons horizontal scroll even when i scroll any one of it along with the rest
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:linked_scroll_controller/linked_scroll_controller.dart';

import 'package:stacked/stacked.dart';

class TeamViewTab extends StatefulWidget {
  @override
  _TeamViewTabState createState() => _TeamViewTabState();
}

class _TeamViewTabState extends State<TeamViewTab> {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Expanded(
          child: _TeamViewList(),
        ),
      ],
    );
  }
}

class _TeamViewList extends StatefulWidget {
  @override
  __TeamViewListState createState() => __TeamViewListState();
}

class __TeamViewListState extends State<_TeamViewList> {
  DateTime now = DateTime.now();
  DateTime? _monthAndYear;
  DateTime? firstWeekDay;
  TeamViewTabViewModel _viewModel = TeamViewTabViewModel();
  LinkedScrollControllerGroup _mainScrollControllers =
      LinkedScrollControllerGroup();
  ScrollController _datesController = ScrollController();
  ScrollController _iconsController = ScrollController();

  int? _numberOfDays, selectedIndexList;
  final List<int> _date = [];
  final List<String> _weeks = [];
  void _goToElement(double today) {
    double jumpTo = _datesController.position.maxScrollExtent / _numberOfDays!;
    _datesController.animateTo(jumpTo * (today + 3),
        duration: const Duration(seconds: 1), curve: Curves.easeIn);
  }

  double today = 0.0;
  @override
  void initState() {
    super.initState();
    _mainScrollControllers = LinkedScrollControllerGroup();
    _datesController = _mainScrollControllers.addAndGet();
    _iconsController = _mainScrollControllers.addAndGet();
    _monthAndYear = now;
    today = now.day.toDouble();
    _numberOfDays =
        DateUtils.getDaysInMonth(_monthAndYear!.year, _monthAndYear!.month);

    for (var i = 1; i <= _numberOfDays!; i++) {
      _date.add(i);
      firstWeekDay = DateTime(_monthAndYear!.year, _monthAndYear!.month, i);
      String week = DateFormat("EEE").format(firstWeekDay!);
      _weeks.add(week.substring(0, 1));
    }
  }

  @override
  void dispose() {
    _datesController.dispose();
    _iconsController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double deviceWidth = MediaQuery.of(context).size.width;
    return Column(
      children: [
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 10),
          color: containerBackgroundColorWhite,
          height: 120,
          width: deviceWidth,
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      IconButton(
                        icon: const Icon(
                          NeOfficeIcons.chevron_left,
                          size: 12,
                          color: greyPrimaryTextColor,
                        ),
                        onPressed: () async {
                          await _onChangeOfMonth(false);
                        },
                      ),
                      Text(
                        DateFormat("MMMM yyyy").format(_monthAndYear!),
                        style: const TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w600,
                            color: titleTextColor),
                      ),
                      IconButton(
                        icon: const Icon(
                          NeOfficeIcons.chevron_right,
                          size: 12,
                          color: greyPrimaryTextColor,
                        ),
                        onPressed: () async {
                          await _onChangeOfMonth(true);
                        },
                      ),
                    ],
                  ),
                  IconButton(
                      onPressed: () {
                        _showLegend();
                      },
                      icon: Icon(Icons.info_outline_rounded,
                          color: infoIconColor, size: 21))
                ],
              ),
              Padding(
                padding: const EdgeInsets.only(left: 10.0),
                child: Row(
                  children: [
                    SizedBox(
                      width: 55,
                      child: Center(
                        child: Text(
                          DateFormat("MMM").format(_monthAndYear!),
                          style: const TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w600,
                              color: titleTextColor),
                        ),
                      ),
                    ),
                    Expanded(
                      child: SizedBox(
                        height: 60,
                        child: ListView.builder(
                            controller: _datesController,
                            scrollDirection: Axis.horizontal,
                            itemCount: _numberOfDays,
                            itemBuilder: (BuildContext context, int index) {
                              return GestureDetector(
                                onTap: () {
                                  setState(() {
                                    selectedIndexList = index;
                                  });
                                },
                                child: Container(
                                  width: 48,
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Text(_weeks[index],
                                          style: TextStyle(
                                              color: selectedIndexList !=
                                                          null &&
                                                      selectedIndexList == index
                                                  ? findMyFriendColor
                                                  : titleTextColor,
                                              fontSize: 12,
                                              fontWeight: FontWeight.bold)),
                                      const SizedBox(height: 10),
                                      Text('${_date[index]}',
                                          style: TextStyle(
                                              color: selectedIndexList !=
                                                          null &&
                                                      selectedIndexList == index
                                                  ? findMyFriendColor
                                                  : titleTextColor,
                                              fontSize: 12,
                                              fontWeight: FontWeight.bold)),
                                    ],
                                  ),
                                ),
                              );
                            }),
                      ),
                    )
                  ],
                ),
              ),
            ],
          ),
        ),
        TeamViewListWidget(
          numberOfDays: _numberOfDays!,
          selectedIndexList: selectedIndexList,
          iconsController: _iconsController,
          viewModel: _viewModel,
          jumpToCurrentDate: () {
            _goToElement(today);
          },
        )
      ],
    );
  }

  Future _onChangeOfMonth(bool direction) async {
    if (direction) {
      setState(() {
        _monthAndYear = DateTime(
            _monthAndYear!.year, _monthAndYear!.month + 1, _monthAndYear!.day);
        _viewModel.getRequiredDataOnChangeOfMonth(
            _monthAndYear!.month, _monthAndYear!.year, _monthAndYear!);
        _numberOfDays =
            DateUtils.getDaysInMonth(_monthAndYear!.year, _monthAndYear!.month);
        _weeks.clear();
        _date.clear();
        if (_monthAndYear!.month == now.month) {
          today = now.day.toDouble();
        } else {
          today = 0;
        }
        for (var i = 1; i <= _numberOfDays!; i++) {
          _date.add(i);
          firstWeekDay = DateTime(_monthAndYear!.year, _monthAndYear!.month, i);
          String week = DateFormat("EEE").format(firstWeekDay!);
          _weeks.add(week.substring(0, 1));
        }
      });
    } else {
      setState(() {
        _monthAndYear = DateTime(
            _monthAndYear!.year, _monthAndYear!.month - 1, _monthAndYear!.day);
        _viewModel.getRequiredDataOnChangeOfMonth(
            _monthAndYear!.month, _monthAndYear!.year, _monthAndYear!);
        _numberOfDays =
            DateUtils.getDaysInMonth(_monthAndYear!.year, _monthAndYear!.month);
        _weeks.clear();
        _date.clear();
        if (_monthAndYear!.month == now.month) {
          today = now.day.toDouble();
        } else {
          today = 0;
        }
        for (var i = 1; i <= _numberOfDays!; i++) {
          _date.add(i);
          firstWeekDay = DateTime(_monthAndYear!.year, _monthAndYear!.month, i);
          String week = DateFormat("EEE").format(firstWeekDay!);
          _weeks.add(week.substring(0, 1));
        }
      });
    }
  }

  }
}

// ignore: must_be_immutable
class TeamViewListWidget extends StatefulWidget {
  final int? numberOfDays;
  int? selectedIndexList;
  TeamViewTabViewModel? viewModel = TeamViewTabViewModel();
  ScrollController? iconsController = ScrollController();

  Function? jumpToCurrentDate;

  TeamViewListWidget({
    Key? key,
    this.numberOfDays,
    this.selectedIndexList,
    this.viewModel,
    this.iconsController,
    this.jumpToCurrentDate,
  }) : super(key: key);

  @override
  State<TeamViewListWidget> createState() => _TeamViewListWidgetState();
}

class _TeamViewListWidgetState extends State<TeamViewListWidget> {
  @override
  Widget build(BuildContext context) {
    double deviceWidth = MediaQuery.of(context).size.width;
    return ViewModelBuilder<TeamViewTabViewModel>.reactive(
      onModelReady: (_viewModel) {
        _viewModel.getRequiredDataOnModelReady();
      },
      builder: (context, model, child) {
        if (widget.viewModel!.isBusy) {
          return Expanded(
            child: Center(
              child: CircularProgressIndicator(
                color: primaryColor,
              ),
            ),
          );
        }
        if (!widget.viewModel!.isBusy) {
          widget.jumpToCurrentDate!.call();
        }

        return widget.viewModel!.isTeamDetailsAvailable
            ? Expanded(
                child: SizedBox(
                  width: deviceWidth,
                  child: ListView.builder(
                      controller: ScrollController(),
                      itemCount: widget.viewModel!.teamDetailsModel.length,
                      itemBuilder: (BuildContext context, int indexOfRow) {
                        return Container(
                          margin: const EdgeInsets.symmetric(vertical: 1),
                          height: 80,
                          color: indexOfRow % 2 == 0
                              ? null
                              : containerBackgroundColorWhite,
                          child: Padding(
                            padding:
                                const EdgeInsets.only(left: 15.0, right: 10),
                            child: Row(
                              children: [
                                Padding(
                                  padding: const EdgeInsets.only(right: 8.0),
                                  child: SizedBox(
                                    width: 55,
                                    child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      children: [
                                        widget
                                                    .viewModel!
                                                    .teamDetailsModel[
                                                        indexOfRow]
                                                    .profilePicUrl !=
                                                'NA'
                                            ? ClipRRect(
                                                child: Image.network(
                                                  widget
                                                      .viewModel!
                                                      .teamDetailsModel[
                                                          indexOfRow]
                                                      .profilePicUrl!,
                                                  loadingBuilder:
                                                      (context, widget, chunk) {
                                                    if (chunk == null)
                                                      return widget;

                                                    return Center(
                                                      child:
                                                          CircularProgressIndicator(
                                                        color: primaryColor,
                                                      ),
                                                    );
                                                  },
                                                  errorBuilder: (context, obj,
                                                      stackTrace) {
                                                    return UserProfileIconWidget(
                                                      widget
                                                          .viewModel!
                                                          .teamDetailsModel[
                                                              indexOfRow]
                                                          .userName!
                                                          .substring(0, 2)
                                                          .toUpperCase(),
                                                      onTap: () async {},
                                                    );
                                                  },
                                                  height: 35,
                                                  width: 35,
                                                ),
                                                borderRadius:
                                                    BorderRadius.circular(60),
                                              )
                                            : UserProfileIconWidget(
                                                widget
                                                    .viewModel!
                                                    .teamDetailsModel[
                                                        indexOfRow]
                                                    .userName!
                                                    .substring(0, 2)
                                                    .toUpperCase(),
                                                onTap: () async {},
                                              ),
                                        Text(
                                          widget
                                                      .viewModel!
                                                      .teamDetailsModel[
                                                          indexOfRow]
                                                      .userName!
                                                      .length <
                                                  7
                                              ? widget
                                                  .viewModel!
                                                  .teamDetailsModel[indexOfRow]
                                                  .userName!
                                              : widget
                                                  .viewModel!
                                                  .teamDetailsModel[indexOfRow]
                                                  .userName!
                                                  .substring(0, 7),
                                          overflow: TextOverflow.ellipsis,
                                          style: const TextStyle(
                                              fontSize: 12,
                                              fontWeight: FontWeight.bold),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                                Expanded(
                                  child: SizedBox(
                                    height: 60,
                                    child: ListView.builder(
                                      scrollDirection: Axis.horizontal,
                                      // physics: NeverScrollableScrollPhysics(),
                                      controller: widget.iconsController,
                                      itemCount: widget.numberOfDays,
                                      itemBuilder: (BuildContext context,
                                          int indexOfIcon) {
                                        return GestureDetector(
                                          onTap: () {
                                            setState(() {
                                              widget.selectedIndexList =
                                                  indexOfIcon;
                                            });
                                          },
                                          child: Container(
                                            width: 48,
                                            child: Icon(
                                                widget.viewModel!
                                                                .monthlyDetailsOfTeam[
                                                            indexOfRow] !=
                                                        null
                                                    ? widget.viewModel!.monthlyDetailsOfTeam[
                                                                    indexOfRow]![
                                                                indexOfIcon] !=
                                                            null
                                                        ? _iconHelper(widget
                                                            .viewModel!
                                                            .monthlyDetailsOfTeam[
                                                                indexOfRow]![
                                                                indexOfIcon]!
                                                            .workMode)
                                                        : Icons.no_data
                                                    : Icons.no_data,
                                                size: 26,
                                                color: widget.selectedIndexList !=
                                                            null &&
                                                        widget.selectedIndexList ==
                                                            indexOfIcon
                                                    ? titleTextColor
                                                    : disabledIconColor),
                                          ),
                                        );
                                      },
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        );
                      }),
                ),
              )
            : Expanded(
                child: Center(
                  child: SizedBox(),
                ),
              );
      },
      viewModelBuilder: () => widget.viewModel!,
    );
  }

}

A: I cannot understand your question clearly But you are using singlechildscrollview .Instead of it you can try interactive viewer


text:
Q: Building a searchable/filtering database? I am building a searchable database that will be able to be filtered by JS using classes.
When I write my items to put into my mysql database, will I be able to assign classes, or 'tags' to an item so I can for example, hide all items with out this 1 tag/class?
I have made a few that work offline with the items just using divs in HTML but will need to this to be dynamic.
$SQL = "INSERT INTO tb_products (Type, Size, Material, Price) VALUES ('Toy', '15inch', 'Glass', '50')";

Is this the correct syntax for me to later come in and use JS to 'show' only toys that are made of glass? or other types of filtering?

A: If you wish to be able to filter items based on their defined attributes only then you should not use tags. Simple SQL queries will do in this case. If you want items to be filtered based on non-attribute values then you can use tags(like transparent for glass items)


text:
Q: ios Audio Unit kAUVoiceIOProperty_DuckNonVoiceAudio error -10879 I use Novocaine framework https://github.com/alexbw/novocaine, if I pause input unit (but output is working) from mic and then play it again in result I get echo. In apple documentation I see Voice-Processing I/O Audio Unit Properties - kAUVoiceIOProperty_DuckNonVoiceAudio. I try:
UInt32 zero = 0;
CheckError( AudioUnitSetProperty(inputUnit,
                                 kAUVoiceIOProperty_DuckNonVoiceAudio,
                                 kAudioUnitScope_Global,
                                 kInputBus,
                                 &zero,
                                 sizeof(UInt32)), "ERROR");

in method setupAudio
in result I have
ERROR (-10879)

In documentation I don't find description. In general, how I can make implement echo cancellation in iOS for audioUnits? I think problem maybe not in this property (becouse by default it should be enabled).. I find this great article - http://atastypixel.com/blog/developing-loopy-part-2-implementation/ author say about correlation signals and their subtraction..  for this case I think I need adaptive filter, but if it possible implement for iOS?
Any ideas?
Thanks in advance

A: I find answer why this error occurred: in Novocaine AudioComponentDescription init as:
inputDescription.componentSubType = kAudioUnitSubType_RemoteIO;

but in my my case correct:
inputDescription.componentSubType = kAudioUnitSubType_VoiceProcessingIO;

After some experiments I concluded that after using kAudioUnitSubType_VoiceProcessingIO echo disable but not completely. May be I don't correctly use it.


text:
Q: Comparing function pointers How can I compare function pointers in C++? Is it stable?
For example, would something like this be valid:
if(pFnc == &myFnc){
//Do something
}

A: The function pointer is essentially a memory address like any other pointer in C++. So when comparing pointers you are always comparing memory addresses not values which means that it doesn't matter what those pointers point to as long as both pointers are of the same type.

A: C++03 5.10/1 [expr.eq]:

The == (equal to) and the != (not equal to) operators have the same
  semantic restrictions, conversions, and result type as the relational
  operators except for their lower precedence and truth-value result.
  [Note: a < b
  == c < d is true whenever a < b and c < d have the same truth-value. ] Pointers to objects or functions of the same type (after pointer conversions) can be compared for equality. Two pointers of the same
  type compare equal if and only if they are both null, both point to
  the same function, or both represent the same address (3.9.2).

Emphasis mine.

A: Both pFnc and myFnc have to be defined. The correct comparison would be:
if(pFnc == myFnc)
{
    //Do something
}


text: Q: Outlook addin is not showing in ItemRead mode I am loading an Office.js outlook addin (hello-world-addin sample https://github.com/jasonjoh/hello-world-addin) in my web account. The addin seems to be working fine in my old outlook account. However, if i test it in new outlook account, the addin doesnt show at all the Incoming folder (email read). Does anybody knows how to solve that issue?


text:
Q: Application_PreRequestHandlerExecute: null HttpContext.Current? Is it safe to always assume that HttpContext.Current will be non-null in Application_PreRequestHandlerExecute?
EDIT: Assuming ASP.NET webforms (not MVC).

A: Yes, unless you're running the code outside of the asp.net pipeline (in unit tests or some such).
The HttpApplication is handed an HttpContext upon creation.

A: There has to be a current httpcontext object if the app is running.


text:
Q: Get results from pivot table based on the combination of two IDs in Laravel Project Hey guys In a new project for a client I have to make a filtration system for books that have genres.
I've made a many to many relationship and a pivot table. So far I've made the form with check boxes, because the goal is to query a combination of two or more genres and show only the results that have all the selected genres.
My migrations are:

    Schema::create('genres', function (Blueprint $table) {
                $table->increments('id');
                $table->string('name', 40);
                $table->timestamps();
            });

    Schema::create('books', function (Blueprint $table) {
                $table->increments('id');
                $table->string('name', 125);
                $table->timestamps();
            });

    Schema::create('book_genre', function (Blueprint $table) {
                $table->increments('id');

                $table->integer('genre_id')->unsigned();
                $table->foreign('genre_id')->references('id')->on('genres')->onDelete('cascade');

                $table->integer('book_id')->unsigned();
                $table->foreign('book_id')->references('id')->on('books')->onDelete('cascade');

                $table->timestamps();
            });

My model is:

    class Book extends Model{
        public function genres(){
            return $this->belongsToMany('App\Genre', 'book_genre');
        }
    }

This is my controller where I take the Get array with genre IDs:

    class FilterController extends Controller
    {

      public function index()
      {
        $genreIds = Input::get('genres');

        $books = Book::whereHas('genres', function($q) use ($genreIds){$q->whereIn('genres.id', $genreIds);})->orderBy('created_at', 'desc')->paginate(10);
      }

      return view('filter.index', compact('books'));

    }

Here the problem is that it is not filtering the results by a combination of the genres, it is filtering them simply if they have one of the genres.
What should I change so I can query out only the matching books what have the listed genres?

A: $query = Book::with('genres');

foreach($genreIds as $genreId){
    $query->whereHas('genres', function($q) use ($genreId){
        $q->where('id', $genreId);
    });
}
$filteredBook = $query->get();

I found the same solution in Stackoverflow


text:
Q: onclicklistener textView in android I have one TextView with two different colors. Here if I click mini it should redirect to one activity, if I click metro redirect to another activity.  How can I achieve this?
TextView t = (TextView)v.findViewById(R.id.text);
String text = ""+"mini"+" added "+"Metro"+" as a favourite.";
t.setText(Html.fromHtml(text));

A: What you can do is create an custom class that extends ClickableSpan and manage your clickable text. I had answered the same here.

A: On your click listener of textview you have to find its text and you can use getText property just compare the text and opens activity as per the text.

A: In an onclick listener I'd try this:
if (text.equalsIgnoreCase("mini")) {
    // call your next activity here
} else if(text.equalsIgnoreCase("metro")) {
    // call your next activity here
}

Don't forget to set android:clickable="true" in your XML file of the TextView.

A: I think you can use two textview in linear layout with two different colours and text. Then you can implement onClicklistener() for two text view. You will achieve what you want and it looks same like what you expecting.
<LinearLayout
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
<TextView
    android:id="@+id/text1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_below="@+id/settings"
    android:layout_marginTop = "10dip"
    android:padding="3dip"
    android:text="@string/txt1"
    android:textColor="#000000"
    android:textSize="25sp"
    android:textStyle="bold" />

<TextView
    android:id="@+id/text2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_below="@+id/settings"
    android:layout_marginTop = "10dip"
    android:padding="3dip"
    android:text="@string/txt2"
    android:textColor="#1569C7"
    android:textSize="25sp"
    android:textStyle="bold" />

</LinearLayout>

Hope it helps

A: This answers what you want, though keep in mind that it's very hard to get the usability of such a component right. It's very likely that someone somewhere will have trouble clicking the links - especially if the text is on multiple lines and the linked words are close to each other vertically.
I would advice against such a solution.


text:
Q: Injecting into existing constructor I'm having some difficulties trying to inject a service into another in Angular. I'm trying to create a service by extending another class with an existing constructor, as follows:
@Injectable()
export class AuthHttpService extends AuthHttp {
    constructor(options: AuthConfig, http: Http, defOpts?: RequestOptions) {
        super(options, http, defOpts);
    }
}

My issue is: I need to inject another service into it and I can't seem to put it as argument in the constructor (can't put a required argument after an optional one and if I put it as optional with ? then it doesn't work).
I've tried with injector.get and it works reasonably well but it injects a different instance of the service than the other components and is breaking my app (I rely on some service properties to show information).
Any solution? Thanks!

A: To inject another service, just add it to the constructor before the optional parameter. Then it will be fine.
@Injectable()
export class AuthHttpService extends AuthHttp {
    constructor(options: AuthConfig, http: Http,
                otherservice: OtherService,
                defOpts?: RequestOptions) {
        super(options, http, defOpts);
    }
}


text:
Q: Django ModelForm instance with custom queryset for a specific field I have a model not unlike the following:
class Bike(models.Model):
    made_at = models.ForeignKey(Factory)
    added_on = models.DateField(auto_add_now=True)

All users may work at a number of factories and therefore their user profiles all have a ManyToManyField to Factory.
Now I want to construct a ModelForm for Bike but I want the made_at list to consist of only factories at which the current user works. The idea is that users should be able to add bikes that they've assembled and enter which of the factories the bike was made at.
How do I do that?

A: try something like this in the view
form  = BikeForm()
form.fields["made_at"].queryset = Factory.objects.filter(user__factory)

modify the Factory queryset so that it identifies the factory which the user works at.

A: You question might be a dupe of this.
S. Lott's answer there is the ticket to solve your problem.
He answered:

ForeignKey is represented by django.forms.ModelChoiceField, which is a ChoiceField whose choices are a model QuerySet. See the reference for ModelChoiceField.
So, provide a QuerySet to the field's queryset attribute. Depends on how your form is built. If you build an explicit form, you'll have fields named directly.
form.rate.queryset = Rate.objects.filter(company_id=the_company.id)
  If you take the default ModelForm object, form.fields["rate"].queryset = ...
This is done explicitly in the view. No hacking around.

A: Nowaday, you should use:
    form.base_fields['alumno_item'].queryset = AlumnoItem.objects.prefetch_related(
        'alumno',
        'alumno__estudiante',
        'alumno__estudiante__profile',
        'item'
    )


text:
Q: Redirection issue (Google finding Urls that are not available) I am facing an issue where Google picking the urls that are not available and returning errors in my search console.
I had an homepage on my website(https://suntrics.com/home/) initially but later on I have redirected the url to (https://suntrics.com/)
Now Google picking my pagination urls with this page.
For example: https://suntrics.com/home/amp/page/182/
I want to redirect to: https://suntrics.com/amp/page/182/
I am trying manually to do redirection but I have more than 200 pages so it's taking lot of time. I have tried to find any better solution but I couldn't get any. So could you guys please help me?
Couldn't able to find any better solution.


text:
Q: Xcode UIButton appear and disappear TitleLabel Value (button.titleLabel.hidden YES NO) I have a one UIButton with a value, when you start the app, the TitleLabel  of the button has been Hidden "call" (button.titleLabel.hidden=YES).
I have connected the button with a one IBAction (TouchDown) for when the user press the button appear the value /  "call" (button.titleLabel.hidden=NO)  and disappear with one NSTimer in 3 seconds after call (button.titleLabel.hidden=YES)
If you press one time the button is work good, (appear and disappear) but when you press without release the  button and you move outside area and return inside area of the button the Value of Title appear again. Not work (button.titleLabel.hidden=YES)
I tested with another IBAction (Drag enter, Drag exit)  in parallel to force the (button.titleLabel.hidden=YES) but the Value of the Title appear. Also take out the Timer but not working…
Please could you help me.
Thanks
Edit.

A: you must have created the button via Storyboard/XIB. Please check the sent events by right-clicking the button and set it to touch down. This should resolve the problem. :)


text:
Q: "error: array type has incomplete element type" after trying to pass two-dimensional array newbie need help. This code works on Windows(Visual Studio 2012), but on GCC i get error: "array type has incomplete element type" for all void type functions below. Can someone tell me why ? (this is only a piece of my all code).
Thank you :-)
void initialize_arrays(struct data data_list[][ARRAY_SIZE]);
void read_file(struct data data_list[][ARRAY_SIZE]);
void print_struct_array(struct data data_list[][ARRAY_SIZE]);
void parallel_print(int thread_number, struct data data_list[][ARRAY_SIZE]);
void print_struct(struct data data_struct, int thread, int array_num, int elem_num);

struct data {
    char *name;
    int age;
    double lenght;
};

int main()
{
    struct data data_array[STRUCT_SIZE][ARRAY_SIZE];
    initialize_arrays(data_array);
    read_file(data_array);
    print_struct_array(data_array);
    parallel_print(6, data_array);
    getchar();
    return 0;
}

void initialize_arrays(struct data data_list[][ARRAY_SIZE])
{
    int i,j;
    for(i = 0; i < ARRAY_SIZE; i++)
        for(j = 0; j < STRUCT_SIZE; j++)
        {
            data_list[i][j].name = NULL;
            data_list[i][j].age = 0;
            data_list[i][j].lenght = 0.0;
        }
}

A: At the point where the function prototypes are declared, there is no such thing as struct data known to the program, because the struct declaration appear further down.
Move the struct declaration above the function prototypes.
(Whether some C language code works or not in Visual Studio is one big lottery, since it barely follows any C standard.)


text:
Q: Derivation of null-quantified implication. I'm supposed to derive $\exists x(P \to Q(x))$ from $P \to \exists xQ(x)$ using only the basic introduction/elimination rules from used in Fitch. I've tried this by means of contradiction and universal introduction but I get stuck because I don't know how to deal with the null quantified $P$. There seems to be some trick that I'm supposed to apply which I can not figure out.
Any help would be greatly appreciated.
Allowed rules:
$\land$-introduction/-elimination
$\lor$-introduction/-elimination
$\neg$-introduction/-elimination
$\forall$-introduction/-elimination
$\exists$-introduction/-elimination
$\bot$-introduction/-elimination
$\to$-introduction/-elimination
$=$-introduction/-elimination

A: You have $P\to \exists xQ(x).$ Now assume $P.$ Eliminating $\to,$ you have $\exists xQ(x). $ Eliminating $\exists,$ you have $Q(c).$ By $\to$ introduction you have $P\to Q(c)$ and you discharge the assumption of $P.$ Then by $\exists$ introduction you have $\exists x(P\to Q(x)).$

A: You are trying to establish $P \to \exists x~Qx \vdash \exists x ~ (P \to Qx)$.  It will help to first work on proving an almost equivalent but much easier claim:
$$B \to (C \lor T) \vdash (B \to C) \lor (B \to T)$$
The hangup here is the "knowing which one it is" issue.  In constructive reasoning $A \lor B$ always means that you know which one of $A$ or $B$ holds.
 Consider the following conversation (the analogy is that $B$ is blueprints, $C$ is car, $T$ is truck) :
Alice asserts:  "If I give Bob the blueprints in that desk, then Bob can build a car, or he can build a truck, and he'll know which one once he sees the blueprints."
Based on that, Bob responds with:  "If Alice gives me the blueprints in that desk then I can build a car, or if she gives me the blueprints in the desk then I can build a truck: and I know which one it will be (before I even see the blueprints)".
Hopefully you'll say to Bob "How the heck will you know which before you see the blueprints?"  If Bob answers "I always know whether blue prints are for a car or not, even before I see them, same for trucks" then (a) that is a pretty awesome useless skill and (b) his response now makes sense.  So that means that what Bob is really saying is:
$$\begin{array} {rll}
& B \to (C \lor T) \\
& (B \to C) \lor \lnot (B \to C) \\
& (B \to T) \lor \lnot (B \to T) \\
\hline
\therefore & (B \to C) \lor (B \to T)
\end{array}$$
Back to the original question, Bob's assumptions are the like saying that $P \to Qx$ is always decidable, that is $\forall x ~ (P \to Qx) \lor \lnot (P \to Qx)$.  So to prove this LEM you probably want to approach the question like
$$(P \to Qt) \lor \lnot(P \to Qt),~ P \to \exists x ~Qx \vdash \exists x ~(P \to Qx)$$
(I'm trying to make it clear why $P \to Qx$ is the statement that has to be instantiated with LEM using the example of cars and trucks and blueprints, I hope it is clear enough).
So the proof follows using straightforward natural deduction now:
$$\begin{array} {rll}
(1) & (P \to Qt) \lor \lnot(P \to Qt) & \text{Law of Excluded Middle} \\
(2) &  P \to \exists x ~Qx & \text{Premise} \\
\\
(3) & \quad \quad P \to Qt & \text{Assumption (case 1)} \\
(4) & \quad \quad \exists x ~ (P \to Qx) & \text{From 4} \\
\\
(5) & \quad \quad \lnot (P \to Qt) & \text{Assumption (case 2)} \\
(6) & \quad \quad \quad \quad Qt & \text{Assumption} \\
(7) & \quad \quad \quad \quad \quad \quad P & \text{Assumption} \\
(8) & \quad \quad \quad \quad \quad \quad Qt & \text{From 6} \\
(9) & \quad \quad \quad \quad P \to Qt & \to-\text{Elim 7 to 8} \\
(10)  & \quad \quad \quad \quad \bot \\
\\
(11) & \quad \quad \quad \quad P & \text{Assumption} \\
(12) & \quad \quad \quad \quad \exists x ~ Qx & \text{From 2 and 6} \\
(13) & \quad \quad \quad \quad \bot & \exists-\text{Elim of 12 and 6 to 10} \\
(14) & \quad \quad \quad \quad Qx & \text{From 13} \\
\\
(15) & \quad \quad P \to Qx & \to-\text{Elim of 11 to 14} \\
(16) & \quad \quad \exists x ~ (P \to Qx) & \text{From 15} \\
\\
(17) & \exists x ~ (P \to Qx) & \lor-\text{Elim, 1, 3 to 4, 5 to 16}
\end{array}$$

A: You were right to try to do a proof by contradiction. You can then try to prove the universal, but what you really want is just $P$ ... and that you can do by a proof by contradiction as well. And once you have $P$, it's easy. Here's the proof:


text:
Q: Question about the proportions of primes p for which $ord_p(2)$ satisfies certain congruences let $p$ be a prime.
I have observed numerically that the proportion of $p$ satisfying $ord_p(2)\equiv4[8]$ seems to be $1/3$. Why is it so? Is there a simple proof?
Moreover the proportion $c$ of prime $p$ satisfying  $ord_p(2)\equiv2[4]$ seems to be the same as the proportion of primes $p$ for which  $ord_p(2)\equiv1[2]$ or those $ord_p(2)$ which are odd. Again, why is it so?
$c\approx0.29..$  Who is that number?

A: Recall that each residue class $1,3,5,7\pmod8$ contains $\frac14$ of the primes, asymptotically, by the prime number theorem for arithmetic progressions.
If $p\equiv3\pmod8$, then $p-1\equiv2\pmod4$, and $2$ is a quadratic nonresidue modulo $p$, which means that $ord_p(2)\equiv2\pmod4$ as well.
If $p\equiv7\pmod8$, then again $p-1\equiv2\pmod4$, but $2$ is now a quadratic residue modulo $p$, which means that $ord_p(2)\equiv1\pmod2$.
If $p\equiv5\pmod8$, then $p-1\equiv4\pmod8$, and $2$ is a quadratic nonresidue modulo $p$, which means that $ord_p(2)\equiv4\pmod8$ as well.
Finally, suppose that $p\equiv1\pmod8$, and let $k$ be the the exponent of $2$ in the factorization of $p-1$, so that $k\ge3$. Note that among these primes, $k=3$ for $\frac12$ of them, $k=4$ for $\frac14$ of them, $k=5$ for $\frac18$ of them, etc., again by the prime number theorem for arithmetic progressions.
Let $j$ be the the exponent of $2$ in the factorization of $ord_p(2)$. Since $2$ is a quadratic residue modulo $p$, we know that $j\le k-1$. We have $j=k-1$ if and only if $2$ is not a fourth power modulo $p$; $j=k-1$ if and only if $2$ is a fourth power but not an eighth power modulo $p$; $j=k-1$ if and only if $2$ is an eighth power but not a sixteenth power modulo $p$; and so on until $j=0$ if and only if $2$ is a $2^k$th power modulo $p$.
We can show (possibly requiring the assumption of a suitable generalized Riemann hypothesis) that among the primes $p\equiv1\pmod8$, $2$ is not a fourth power for $\frac12$ of them; $2$ is a fourth power but not an eighth power for $\frac14$ of them; $2$ is an eighth power but not a sixteenth power for $\frac18$ of them; and so on. (This is what we'd expect on the heuristic that $2$ is randomly distributed among the quadratic residues modulo $p$.)
Therefore the proportion of primes $p$ such that $ord_p(2)\equiv4\pmod8$ equals
$$
0+0+\frac14+\frac14\bigg( \frac12\cdot\frac12+\frac14\cdot\frac14+\frac18\cdot\frac18+\cdots \bigg) = \frac13.
$$
Similarly, the proportion of primes $p$ such that $ord_p(2)\equiv2\pmod4$ equals
$$
\frac14+0+0+\frac14\bigg( \frac12\cdot\frac14+\frac14\cdot\frac18+\frac18\cdot\frac1{16}+\cdots \bigg) = \frac7{24} = 0.291\bar6.
$$
A similar calculation gives $\frac7{24}$ for the proportion of primes $p$ such that $ord_p(2)$ is odd. Finally, the proportion of primes $p$ such that $ord_p(2)\equiv2^k\pmod{2^{k+1}}$ is $1/(3\cdot2^k)$.