text:
Q: why is this async matrix multiplication code slower than synchronous? I'm trying to implement a matrix multiplication function that is faster than my synchronous multiplication function by using concurrent.futures.threadPoolExecutor() threads. Here is the code:
def asyncmult(m1, m2):
threads = []
prod = np.zeros((m1.shape[0], m2.shape[1]))

def multvecs(inp):
    vec1, vec2, index = inp
    i, j = index
    sum = 0
    for k in range(vec1.shape[0]):
        sum += vec1[k] * vec2[k]
    prod[i][j] = sum

with concurrent.futures.ThreadPoolExecutor() as executor:
    for i in range(m1.shape[0]):
        for j in range(m2.shape[1]):
            f = executor.submit(multvecs, (m1[i], m2[:, j], (i, j)))
            threads.append(f)
return prod

on plotting against time taken with increase in input matrix size this function performs the worse than synchronous.
why is this happening? How can I fix this?


text:
Q: "The Apple Store app is not available in your country or region" after Apple Store update on iPad After Apple Store update I've got "The Apple Store app is not available in your country or region", and my country is missing from the list (it's Ukraine). Just in case I have iPad Air 2020.
On my iPhone though no updates were requested and everything works fine.

A: The thing was that I just have confused App Store and Apple Store apps, and there was no real issue. Just delete the Apple Store app from your device if you don't have an official Apple store in your country.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Null Pointer Exception java array initialization I am having trouble initializing an array of objects. I keep getting an error(NullPointerException), I have tried a few different approaches to initialization. I am fairly new to java ( started from c++). I was thinking maybe I need to create a constructor for the class Customer, but that didn't work when I tried it. Any ideas? Thanks in advance. (these are only snippets of my code)
Update: Ok so I replaced the declaration and I am still getting nullpointerexception errors on a few lines, here is the updated code. Am I initializing the privates of the Customer class wrong?
Thanks again for the help people, much appreciated.
Update 2: So after some tinkering, I created a for loop that individually initializes each index of the class object array. Thanks a bunch!
public static class ATM{
    private double funds = 100;
    private int serial;
    private String location = "UNKNOWN", bank_name;
    private int succ_with = 0, fail_with =0;
    private Customer[] customers = new Customer[10];///////updated here
    public void custSet(String u, String b, int p, double bal, Customer[] customer, int index)
    {
        customer[index].user_name = u;
        customer[index].bank_name = b;//second exception
        customer[index].balance = bal;
        customer[index].pin = p;
    }
    public void populateCust()
    {

        custSet("Alice","OtterUnion",1234,5000.0,customers,0);//3rd exception
        custSet("Tom","OtterUnion",2000,200.0,customers,1);
        custSet("Monica","OtterUnion",3000,50.0,customers,2);
        custSet("Michael", "OtterUnion",7777,0.00,customers,3);
        custSet("John","OtterUnion",8000,500.00,customers,4);
        custSet("Jane","OtterUnion",2222,500.00,customers,5);
        custSet("Robert","BOA",2323,200.00,customers,6);
        custSet("Owen","BOA",4455,50.00,customers,7);
        custSet("Chris","BOA",8787,10.00,customers,8);
        custSet("Rebecca","BOA",8080,555.55, customers,9);
    }

    }
public static class Customer{
    private String user_name, bank_name;
    private int pin;//(first exception complaining about this, but when i
    // change it to public the error goes away, so Ill just need to make a setter
    private double balance;
}

A: You need to instantiate your array before using it: customers = new Cusomter[size]


text:
Q: Reduce the impact of videos in memory to prevent crashes I have an app with potentially a very large amount of images and videos, depending on how many posts users make.
Already in development, with relatively few posts containing tabs with images and videos, occasionally the app crashes on real devices, I fear due to too much memory usage.
Are there any tips and strategies to optimize resource usage?
As for images, I only use medium-resolution regular EncodedImages (no multi-images), as backgrounds in Labels of fixed size.
As for videos, I only use short videos.
As for posts and videos (which are inside complex multilayer hierarchies with many Tabs), I use my own custom version of InfiniteContainer that, unlike the "default" version, never uses "removeAll" during a refresh, but just adds new posts, if any: this has already given me a great benefit in terms of performance. I also try to reuse the same instance of an InfiniteContainer full of images and videos, so I don't have to recreate every time the Media instances: also in this case there is a performance advantage, but everything remains loaded in memory.
Does the garbage collector do its job with videos?
It's not clear to me if Media.cleanup() does something or not with videos.
Thanks for the suggestions.

A: I suggest using the Android memory profiler to try and track potential memory leaks and the source of such leaks. You can also use memory tracking on the simulator but that's a bit more challenging as some overhead stored in the "native system" would be hidden from Java based profilers.
EncodedImage is great for images that aren't shown. When they're shown they are "locked" and take up a lot of RAM. At that point they can't get GC'd. Make sure your infinite container unlocks components that are no longer a part of it. If you keep adding things to the infinite container you'll eventually run out of RAM. There's nothing you can do about that.
Images get "locked" when they're in use (e.g. in the current form but not necessarily visible). It's the responsibility of the form to unlock them  otherwise the image won't be GCd at all. You can use isLocked() to determine if the encoded image takes up the full amount of RAM. Notice that unlocked images might perform very poorly as they'll thrash the GC so tread lightly with this...
I would suggest using FileEncodedImageAsync for data so files can be completely removed from RAM and using it for videos too (using a thumbnail. I suggest placing the video itself only when playback starts.
The difference from EncodedImage is this: Even when it is GCd the EncodedImage keeps the "encoded" part (PNG, JPEG data). FileEncodedImageAsync has the data in FileSystem and as such the cache can be managed as files. Furthermore, the image only takes up the name of the image file in RAM assuming it isn't locked.


text:
Q: Minimum value of numbers in char array I recently ran into this problem in an interview, and I was curious what the best way to solve it would be. The question is given a char array that has the ascii characters '0' to '9' make one swap such that the the set of ascii values in the resultant array forms the lowest possible value. Both the input array will not have preceding 0s and neither should the resultant array.
So here is an example: char a[] = {'1','0', '9','7','6'}
The solution: char b[] = { '1','0', '6', '7', '9'}
Another example: char a[] = {'9','0', '7','6','1'}
The solution:  char b[] = {'1','0', '7','6','9'}
I am looking for the best solution in terms of performance. Since only one swap is allowed I assumed that sorting is not allowed. I did not clarify that though.  So we are looking for the lowest possible value that can be obtained through just using one swap. It would help if you could provide the complexity of the solution as well.

A: Algorithm:
Note that since there can't be a leading 0, 0's should be catered for separately.
Go from the right, keeping track of the minimum non-zero number. Also record the first 0.
Whenever you find a number larger than the recorded non-zero number, record those 2 as the best possible swap so far.
Once you've found a zero, record any non-zero non-leading character from here as the best possible swap for the zero.
Note that you're not doing any comparisons between the quality of either of the swaps above, we simply replace the current best with the new one, as it's always better to swap with a more-left position.
When done, compare the target positions of the best swap for the zero and the best swap for the non-zero and pick the left-most position, or the zero if they're the same.
If no possible swap was found, the array is already the minimum permutation of the given numbers, thus don't do anything. Or, if we have to, swap the two right-most characters.
Running time:
O(n).
Example:
Input: 10976
Processing  6   7   9   0   1
Minimum     6   6   6   6   1
Best swap   -   6+7 6+9 6+9 6+9
Zero?       No  No  No  Yes Yes
Best 0 swap -   -   -   -   -

So the best swap is 6/9, giving us 10679
Input: 3601
Processing  1   0   6   3
Minimum     1   1   1   3
Best swap   -   -   1+6 1+3
Zero?       No  Yes Yes Yes
Best 0 swap -   -   0+6 0+6

Here possible swaps are 1/3 and 0/6.
For the 1/3 swap, the target position is 0 (0-indexed).
For the 0/6 swap, the target position is 1.
So we pick the 1/3 swap giving us 1603.

A: Start at the leftmost digit

While current digit is valued the lowest (non-zero for the first digits equal
  to the number of zeroes in the set) of the remaining set of numbers, advance
  to the next number

Swap current value with lowest remaining value.

You can keep a sorted copy of the array to help you in your decision making process.  You'd need it for knowing how many there are of your current lowest number(s).  You can make it even more efficient if you store their indices as well.
It's not necessary to have any additional storage, but it would likely make things faster.  In a single pass of the first array, you can get the number of 0s as well as the index to the next lowest number, but in an array like 1, 0, 6, 9, 7, you would then have to go through the array 4 different times.
EDIT - slightly more flushed out algorithm
Copy the array into a separate one, called c, and sort c.  (You'll use this to make your decision faster, though you could simply repeatedly analyze the array.)
if c has zeros, find the value of its first non-zero value, called x
if a[0] != x, swap a[0] with x.
set index to 1
while a[index] == c[index], ++index
swap a[index] with c[index]

If you do it this way, it costs you another array, but is done with one sort and one pass through the array.
If you don't do it that way, you'll have to pass through the remainder of the array each time to find the minimums.  I'm not great at complexity, but I believe that's n log n, since you'll be starting from higher indices each iteration.
Without using the array, you'd have to do something like
Find the lowest non-zero value
if a[0] isn't this value, swap with this value
index = 1
find lowest value starting at a[index]
if they're not equal, swap the values, done.  Otherwise,  increment index

That's still n log n.  I think sorting can make it more efficient.

A: Depends on what you mean by best.
Take out the lowest number except '0' as the first item in b, then sort the rest into ascending order.

A: I think that you clearly have to go through the array at least once.  You need to do this to find the smallest value.
You also need to find the value which will satisfy the conditions.  The poster says that the input array will not have '0' as the leading elements.
We loop over the array one position at a time.  We are looking for another position which has the minimum value (non zero for the first spot, anything for the other spots) and is smaller than any other seen.
for (pos = 0; pos < array_size-1; pos++) {
        low_index = pos;
        min_value = (pos == 0) ? '1' : '0';

        for (i = pos+1; i < array_size; i++) {
                if (min_value <= array[i]) && (array[i] < array[low_index])) {
                        low_index = i;
                }
        }

        if (low_index != pos) {
                low_value = array[pos];
                array[pos] = array[low_index];
                array[low_index] = low_value;
                break;
        }
}


text:
Q: how to alter schema by inserting a new column in hive I have a hive table stored on the cluster. I want to modify it by adding a new column, and have the old columns data with the data of the new column added from another table. Is there a way to do it without recreating the table?
the old schema looks like:
create external table XXX
(item_id bigint,
start_dt string,
end_dt string,
title string,
subtitle string,
description string)
row format delimited fields terminated by '\t' lines terminated by '\n'
stored as textfile
location '/user/me/XXX';

A: You should be able to do it using below syntax.
ALTER TABLE table_name
  [PARTITION partition_spec]                 -- (Note: Hive 0.14.0 and later)
  ADD|REPLACE COLUMNS (col_name data_type [COMMENT col_comment], ...)
  [CASCADE|RESTRICT] -- (Note: Hive 0.15.0 and later)


text:
Q: Quantum Fisher Information vs Classical Fisher Information I am currently studying about Fisher Information and have a rather simple doubt which I can't figure out.
Is it possible to have Quantum Fisher Information (QFI) more than Classical Fisher Information (CFI) for a system? What would be the implications, if so?
I am thinking that this is possible when we have entanglement whereupon the QFI being more than CFI would imply that the estimation on the parameter is better as a result of the Classical and Quantum Cramer-Rao Bounds. If so, then what about the case of calculating QFI without entanglement and comparing it with CFI?

A: The quantum Fisher information is always greater than or equal to the classical Fisher information, by definition. The QFI with respect to a parameter $\theta$ is defined by $$\mathcal{H}_\theta[\hat{\rho}_\theta] = \max_{\{\hat{M}_\alpha\}} \mathcal{F}_\theta[\hat{\rho}_\theta,\{\hat{M}_\alpha\}],$$ where $\mathcal{F}_\theta[\hat{\rho},\{\hat{M}_\alpha\}] = \int{\rm d}\alpha\, p(\alpha|\theta)[\partial_\theta \ln p(\alpha|\theta)]^2$ is the classical Fisher information for a measurement of the state $\hat{\rho}_\theta$, which yields outcome $\alpha$ with probability $p(\alpha|\theta) = {\rm Tr}[\hat{M}_\alpha \hat{\rho}_\theta]$, with $\{\hat{M}_\alpha\}$ a positive operator-valued measure satisfying $\int{\rm d}\alpha\, \hat{M}_\alpha = 1$. The maximum defining the QFI is taken over all possible measurements. See Braunstein & Caves, PRL 72, 3439 (1994) for details.
When the CFI for a given measurement is less than the QFI, it just means that one is not using the optimal measurement to estimate the parameter. This may be related to entanglement, e.g. in phase estimation with NOON states, but is not necessarily. In general, even for a simple two-level system, there are infinitely many measurements one can make that do not saturate the quantum Cramer-Rao bound and thus have a smaller Fisher information than the QFI.


text:
Q: How to append an array inside another array? I have an array of selectedWeekdays and I want to append the shifts array in the Weekday object.
For instance, I want to append the array of shifts for every instance in selectedWeekdays where name is equal to Monday
struct Weekday: Identifiable {
    var id: String = UUID().uuidString
    var name: String
    var index: Int
    var shifts: [Shift]
}

struct Shift: Identifiable, Encodable {
    var id: String = UUID().uuidString
    var startTime: Date
    var endTime: Date
}

@Published var selectedWeekdays: [Weekday] = []

I have tried the following but it does not work:
self.selectedWeekdays.contains(where: {$0.name == weekday}).shifts.append({Shift(startTime: startTime, endTime: endTime)})

It shows the following error:
Value of type 'Bool' has no member 'shifts'

A: you can use to get the certain item, but it might require you to unwrap the optional first.
if var item = selectedWeekdays.first(where: {$0.name == weekday}) {
    item.shifts.append(your new element)
}

Edited:
Code above only works if you define your Weekday as a class. If you want to stick with structs, it's not that pretty but works,
struct Weekday {

    // Properties
    // ..

    mutating func updateShifts(for weekdays: String, with newShift: Shift) {
        if self.name == weekdays {
            self.shifts.append(newShift)
        }
    }
}

then use it like:
for i in 0..<selectedWeekdays.count {
    selectedWeekdays[i].updateShifts(for: "Monday", with: newShift)
}

A: The contains returns boolean and you are trying to use as the array of the Weekday itself.
To filter the array and return the same structure, you must use the filter function and iterate with them using compactMap (which iterates to every not null elemen, transform the object and returns the modified object).
But like @Andrew remembered every item is immutable, this happens because we are using a Sequence's method. So to modify the object we need to new and mutable object of the same Class and then insert it into our new array.
Finally, use the result of compactMapto get the array with the inserted element.
    let modifiedSelectedWeekdays = selectedWeekdays
        .filter { $0.name == weekday }
        .compactMap { item -> Weekday in
            var mutable = item

            mutable.shifts.append(
                Shift(startTime: startTime, endTime: endTime)
            )

            return mutable
        }


text:
Q: Trigger a click on first item of ng-repeat, initially and each time new data is loaded I'm very very new to Angular JS and have the following requirement:
I have an ng-repeat as shown below:

{{appname}}

            Some data

The data in this ng-repeat comes from the server.
So the problem statement I have is to perform a click trigger on the first element under ng-repeat, .accordion-head so that the first item in the list is always open. I tried various approaches of putting $watch etc. but when the number of items in the list are same, then the trigger doesn't fire.
(the first item in list has to be clicked even when new data is loaded)
I thought of writing a directive initial-select and perform click based on index but that happens only once. I really need an experts advice.
Any solutions?

A: I think the simplest option is to use data-ng-init="collapse = !$first;".
Another option:
Have you used Angular UI Bootstrap? Also, are you using $http or $resource to get data from the server?
If you use $resource, you can set a variable on the success callback (interceptor response) to open=true. Then, you can either bind this variable to Angular UI Bootstrap is-open attribute or to your data-toggle. Also, with $resource you can set data-ng-if="chart.accordionData.$resolved" (or chart.$resolved depending on your setup), which is nice.

A: You can use a watch to watch the array contents.
Check out the following fiddle:
http://jsfiddle.net/akonchady/w0qdsen7/3/
I have used a variable to keep track when the array content changes since directly watching the array will be more memory intensive.
Here is the main code that watches the variable:
$scope.$watch('arrModified', function(newValue, oldValue) {
  if(newValue) { //array is modified
      //Trigger ng-repeat div click
    setTimeout(function() {
    $('.item:first').trigger('click');
    $scope.arrModified = false;
    $scope.$digest();
  }, 0);
  }
});


text:
Q: Link an in-app purchase to user apple account I'm looking for a way to link an in-app purchase (non-renewable subscription) to the user apple account, because my app doesn't have account system, and obviously I want the user to keep his subscription.
I read that we can't get the Apple ID, but I think there is a way to do it because most of iOS apps can save datas with your Apple account.
Thanks for your answers.

A: If you don't have your own account system (where the user can login etc), you can check the user's purchases for your app from the purchase receipt:
https://developer.apple.com/library/ios/releasenotes/General/ValidateAppStoreReceipt/Introduction.html
Getting personal information like AppleID etc is not possible from the SDK.

A: You should keep track of already purchased products in your app yourself. I usually use [[NSUserDefaults standardUserDefaults] setBool:YES forKey:productIdentifier] for this.
The problem arises when your users reinstalls your app or buys a new device. In this case you must implement a way to restore the purchased products.
The In-App Purchase Programmering Guide states that one way to implement this is by calling [[SKPaymentQueue defaultQueue] restoreCompletedTransactions]. This sends a request to the App Store to restore all of your app's completed transactions.
Then paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions of your transaction observer will be called and transactions holds the restored products. My function usually looks something like this:
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
    for (SKPaymentTransaction * transaction in transactions) {
        switch (transaction.transactionState)
        {
            case SKPaymentTransactionStatePurchased:
                [self completeTransaction:transaction];
                break;
            case SKPaymentTransactionStateFailed:
                [self failedTransaction:transaction];
                break;
            case SKPaymentTransactionStateRestored:
                [self restoreTransaction:transaction];
            default:
                break;
        }
    };
}`

Complete the restoration process (providing content, update NSUserDefaults etc.) in restoreTransaction.

A: For non-renewal subscription you have to manually store the expiry date somewhere because Apple does not manages it for non-renewal.
I had implemented this feature in one of my application where after subscription I used to store the expire date on server and app will check for expire date while accessing paid features.
If found expired, app will ask to purchase subscription again.
Reference link:
https://developer.apple.com/library/mac/documentation/LanguagesUtilities/Conceptual/iTunesConnectInAppPurchase_Guide/Chapters/CreatingInAppPurchaseProducts.html#//apple_ref/doc/uid/TP40013727-CH3-SW1
https://www.progressconcepts.com/blog/non-renewing-subscription-app-purchases-ios/
Hope this helps.


text:
Q: JSON post on PHP CURL i need to upload my file to server using json post data
format server accept is :
"fields": [{
            "external": {
                "name": "file",
                "filename": "myfile",
                "put": {},
                "size": 3895557
            }
        },

My code is :
Array
                        (
                            'external' => Array
                                (
                                    'name' => 'file',
                                    'filename' => 'myfile',
                                    'put' => new stdClass(),
                                    'size' => $filesize
                                )
                        ),

but i can not upload my file.i guess there is problem with 'put' syntax ?
thanks

A: If I did understand well your question. You want to upload a file using a JSON post request. A JSON post is when the server is expecting to receive a JSON encoded data. Well, you must know that it is impossible to upload a file using a JSON post, simply because JSON does not support file type. The value being JSON encoded/decoded can be anything except a resource.
Maybe you are trying to connect with a RESTfull/RESTlike API that returns a JSON response. I guess what you refer to as fields is the JSON response:
[{
  "external": {
       "name": "file",
       "filename": "myfile",
       "put": {},
       "size": 3895557
   }
 },
...]

From this response, it can be concluded that the API accepts multiple uploads. The server returns a brief description for each file uploaded. I guess that it gives you also a link, under the put key, where you can update the file uploaded (I am guessing).
It's pretty simple to upload a file with curl, all you have to do is put the @ symbol before the realpath of the file.
Following an example showing how to perform a simple upload of a document using curl over php:
$target_url = url;
$file_name_with_full_path = realpath('target_file');
$post_fields = array('file'=>'@'.$file_name_with_full_path);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$result=curl_exec ($ch);
curl_close ($ch);

Note: You should perform a Content-Type negotiation to determine the types accepted by the server. Remember that the Content-Type defines the MIME Type of the served document.
Hope it's useful!


text:
Q: NoSuchFieldError _hostname_ - FTPSClient Java with Interpreter I am trying to get the FTPSClient Example from Apache running (See here:
https://svn.apache.org/repos/asf/commons/proper/net/tags/NET_2_2/src/main/java/examples/ftp/FTPSExample.java)
In Eclipse, this example code works fine and I can upload my files to a server. When I try to compile my code within the Interprete,r which can run normal java sourcecode also, it still works. But when I start my compiled program, I get the following errors:
java.lang.NoSuchFieldError: _hostname_
org.apache.commons.net.ftp.FTPSClient.sslNegotiation(FTPSClient.java:266)
org.apache.commons.net.ftp.FTPSClient._connectAction_(FTPSClient.java:226)
org.apache.commons.net.SocketClient.connect(SocketClient:163)
org.apache.commons.net.SocketClient.connect(SocketClient:250)
FTPSExample.doMyUpload(FTPSExample.java:93)

The last "sentence" is Class with my self named method. In line 93, I just try to connect to a Server:
this.ftps.connect(this.server);

Eclipse and my Interpreter are both taking the same classpath where my commons.net.jar is placed (3.6). So I really dont know, why this error appears.
If you need to see the full class, I can post it here. But I did no changes to the original Example from Apache.
Thank you, Louis

A: Probabry, you are using an old versin of Commons Net jar or SocketClient class. The field variable _hostname_ has been introduced since Commons Net version 3.4. See also this history. The field is defined in abstract class SocketClient and used by an extended class FTPSClient. If both new version of FTPSClient and old version of SocketClient is used, then java.lang.NoSuchFieldError: _hostname_ is thrown.


text:
Q: ClickOnce with .NET 4.7.1 fails, cannot find Microsoft.Extensions.FileProviders.Physical in the GAC I've successfully built and deployed a ClickOnce app based on .NET 4.7.1 using the latest (stable) Visual Studio 2017 version. However, another app won't install:

I've tried to install it into the GAC:

*

*Find Microsoft.Extensions.FileProviders.Physical (there is a NuGet package for it, so I can find and extract the DLL)

*Install it in the gac with gacutil -i.

However, I get an error message, telling me:

Failure adding assembly to the cache:   This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.

Where can I find a gacutil which would work with the 2.0.0 version of this assembly?
Or am I doing it in the wrong way? Is there another solution to this issue?
Edited 2017.11.18:
I opened an issue in the Visual Studio Developer Comunity.


text:
Q: Parse Dashboard bundle.js net::ERR_ABORTED 404 (Not Found) When I try to go to Parse Dashboard on https://www.example.net/dashboard it's redirecting me to https://www.example.net/login. and here I'm getting this error. GET https://example.net/bundles/login.bundle.js net::ERR_ABORTED 404 (Not Found) Also the result is blank. just a white screen.
Can anyone help, please?

A: Parse server have problem not in dashboard parse server cannot read your database Uri or username password you want to change all you want to change server url or master key or appId in https://github.com/parse-community/parse-server-example/blob/master/index.js or your index.js file
change here


text:
Q: How to run an isolated Node.js environment inside browser? I am trying to use isomorphic-git to perform git clone command on browser-side. But due to adhering to the same-origin policy, I cannot send a cross-origin request to our company's GitLab, if no cors-proxy I can use. For security consideration, our company's GitLab team is not willing to alter the CORS config. It seemed that there is no way to clone code from the browser-side. Meanwhile, isomorphic-git provides node-version to clone code, there is no cross-origin problem anymore. But I am not willing to leverage one more node server to do that. Is it possible to launch an isolated Node.js environment inside a browser?
Using isomorphic-git to clone code from GitHub with corsProxy:
await git.clone({
  dir,
  corsProxy: 'https://cors.isomorphic-git.org',
  url: 'https://github.com/isomorphic-git/isomorphic-git',
  ref: 'master',
  singleBranch: true,
  depth: 10
});

A: Seems to me the answer is no, because even if you wedged a NodeJS (emulator? environment? thing?) inside the JavaScript thread somehow, when it wanted to git clone, it would have to call out to the browser's API. Then you're in the same place: JavaScript still subject to the same-origin policy.
If you could manage this, you should look into landing a bug bounty; sounds like a big security flaw :-)

A: If your project is small you can use the free cors proxy - https://cors.isomorphic-git.org/ to clone a repo on the browser side.
Usage:
git.clone({
    fs,
    http,
    dir,
    corsProxy: 'https://cors.isomorphic-git.org',
    url: 'https://github.com/example.git',
    ref: 'master',
    singleBranch: true,
    depth: 10
});

Reference: https://github.com/isomorphic-git/isomorphic-git#cors-support


text:
Q: Why does my HWID lock accept any value in acceptedSerial_2 Basically im using a HWID lock to lock my program but im having an issue where my program accepts any value in acceptedSerial_2
Here is the code, please help me make improvements, Thank you!
Obviously when i run the program the accepted serials are not 0, theyre the respected values
    {
        SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 12);
        std::cout << ":: Verifying HWID \n " << std::endl;
        TCHAR volumeName[MAX_PATH + 1] = { 0 };
        TCHAR fileSystemName[MAX_PATH + 1] = { 0 };
        DWORD serialNumber = 0;
        DWORD maxComponentLen = 0;
        DWORD fileSystemFlags = 0;
        if (GetVolumeInformation(
            _T("C:\\"),
            volumeName,
            ARRAYSIZE(volumeName),
            &serialNumber,
            &maxComponentLen,
            &fileSystemFlags,
            fileSystemName,
            ARRAYSIZE(fileSystemName)))
        {

            DWORD acceptedSerial = 0; //
            DWORD acceptedSerial_1 = 0; //
            DWORD acceptedSerial_2 = 0; //

            if (serialNumber == acceptedSerial || acceptedSerial_1 || acceptedSerial_2)
            {
                MessageBox::Show("Access Granted!",
                    "Welcome",
                    MessageBoxButtons::OK,
                    MessageBoxIcon::Exclamation);
                return(0);
            }
            else
            {
                MessageBox::Show("HWID Missmatch",
                    "Error",
                    MessageBoxButtons::OK,
                    MessageBoxIcon::Error);
                exit(0);
            }

        }

    }```

A: If you want to accept only three values: acceptedSerial, acceptedSerial_1, acceptedSerial_2, then the logical expression will be if ((serialNumber == acceptedSerial) || (serialNumber == acceptedSerial_1) || (serialNumber == acceptedSerial_2)) .
However, the one you currently use: if (serialNumber == acceptedSerial || acceptedSerial_1 || acceptedSerial_2) always is true as long as acceptedSerial_1  or acceptedSerial_2 is not zero even if they are not equal to serialNumber.
Refer to C++ Logical OR operator: ||.


text:
Q: XAML intellisense not working for  I'm writing XAML/WPF and sometimes use object-element syntax to reference a static resource:
<StaticResource ResourceKey="theResourceKey"/>

This seems consistent with the StaticResource Markup Extension docs and is the only option I know of in some cases, e.g.:
<Transform3DGroup>
    <TranslateTransform3D OffsetX="0.5" OffsetY="0.5"/>
    <StaticResource ResourceKey="PlateScaleTransform"/>
</Transform3DGroup>

The problem is, I get no intellisense suggesting <StaticResource, but once I've typed it I do get intellisense suggesting ResourceKey="". Anyone have ideas why the former intellisense suggestion isn't working?

A: It has been long enough, I'm convinced it's a bug/omission. People can up-vote the problem report via the "Report a Problem" tool:

Search for "No Intellisense for StaticResource", and there is a submission to up-vote:


text:
Q: Styling the SharePoint List Column Filter Dialog My users are filtering the column "State" from SharePoint list , Which consists of almost more then 50 values due to which users are getting a long list of choice to select as below.
Now i am thinking to apply some css or JavaScript and present the filter dialog options in 5 rows and 5 columns by increasing it's width .Can any help me in doing this.


text:
Q: Does "$X$ is independent with $Y$" implies "$\mathbb{E}[X|Z]$ is independent with $Y$"? Suppose two random variables $X$ and $Y$ are independent. Does this imply that for any random variable $Z$, $\mathbb{E}[X|Z]$ is independent with $Y$?
The above seems very intuitive to me, but I feel it's hard to prove rigorously using the definitions...

Answered (which is No) by @AlexL in the comments (thanks AlexL!).


text:
Q: How Do I Save and Display HTML in Grails Using the CKEditor? I'm using the CKEditor plugin of Grails and while I can store the HTML content from CKEditor to the database, I can not render it properly in the view.
What I'm getting in the view is the HTML escaped and not as mark-up content.

 sdfsdfsadf

 asdfasdfasdf

 asdfasdfasdf

 ¥

When I want:
sdfsdfsadf
asdfasdfasdf
asdfasdfasdf
¥

How do I get the stored data to render properly?

A: Migrated to Grails 2.4 and after some head scratching, found <%=expression%> is deprecated.
Using the new syntax ${raw(expression)} solved my issue.

A: try ${instance?.attribute?.decodeHTML()}

A: From John Flinchbaugh's Answer on this question about codecs and encodings:

To disable HTML encoding for one expression in a page that is
  otherwise defaulting to HTML, use <%=expression%> notation instead
  of ${...}.


text:
Q: Can I wrap NSLog in a block that takes a variable number of arguments? I'm writing an Objective-C library and I'd like it to offer a simple pluggable logging mechanism, so that the library user can turn the logging on and off. I thought an interesting way to do this would be a block property on the library classes:
typedef void (^Logger)(NSString *fmt, ...);
@property(copy) Logger logger;
logger(@"Foo, %@.", self);

But I don't know how to pass the variable argument list to NSLog:
const Logger SimpleLogger = ^(NSString *fmt, ...) {
    // what goes in here?
};

A: Ah, I completely missed NSLogv:
const Logger SimpleLogger = ^(NSString *fmt, ...) {
    va_list arglist;
    va_start(arglist, fmt);
    NSLogv(fmt, arglist);
    va_end(arglist);
};


text:
Q: Converting JSON file to GEXF file Is there anyway to convert JSON file to GEXF file?
I'm currently using this echarts circular layout graph (https://echarts.apache.org/examples/en/editor.html?c=graph-circular-layout).
However, the JSON file has to be converted to GEXF file format for it to be used in the graph.
Note: My codes are in Javascript.
Thank you!
Updated with codes
Below is the sample codes of using the circular layout graph. It's getting the data from gexf file. However my input data for the graph is in JSON file.
myChart.showLoading();
$.get(ROOT_PATH + '/data/asset/data/les-miserables.gexf', function (xml) {
myChart.hideLoading();

var graph = echarts.dataTool.gexf.parse(xml);
var categories = [];
for (var i = 0; i < 9; i++) {
    categories[i] = {
        name: '类目' + i
    };
}
graph.nodes.forEach(function (node) {
    node.itemStyle = null;
    node.value = node.symbolSize;
    node.symbolSize /= 1.5;
    node.label = {
        normal: {
            show: node.symbolSize > 10
        }
    };
    node.category = node.attributes.modularity_class;
});
option = {
    title: {
        text: 'Les Miserables',
        subtext: 'Circular layout',
        top: 'bottom',
        left: 'right'
    },
    tooltip: {},
    legend: [{
        data: categories.map(function (a) {
            return a.name;
        })
    }],
    animationDurationUpdate: 1500,
    animationEasingUpdate: 'quinticInOut',
    series: [
        {
            name: 'Les Miserables',
            type: 'graph',
            layout: 'circular',
            circular: {
                rotateLabel: true
            },
            data: graph.nodes,
            links: graph.links,
            categories: categories,
            roam: true,
            label: {
                position: 'right',
                formatter: '{b}'
            },
            lineStyle: {
                color: 'source',
                curveness: 0.3
            }
        }
    ]
};

myChart.setOption(option);
}, 'xml');

Github Sample Codes

*

*The github of this graph has the source code for the JSON file (codes) that it uses to populate the graph -> https://github.com/hecore/echart_demo/blob/master/data/hecore.json

*I'm not sure how did the codes transform to this -> https://github.com/hecore/echart_demo/blob/master/data/les-miserables.json

*Lastly, this is the file that they used to populate in the echarts circular layout graph in .gexf format -> https://github.com/hecore/echart_demo/blob/master/data/les-miserables.gexf

A: You could install Gephi (https://gephi.org/users/install/), then the JSON Exporter plugin for Gephi (https://gephi.org/plugins/#/plugin/jsonexporter-plugin). Then open the gexf file in Gephi and go to file>export>graph file>json graph.  I'm not sure if it's exactly the format you need, but could be a starting point.


text:
Q: Cannot find delegate defined in another header I have a very simple problem, yet because it's so simple, I can't find anything wrong with it to fix.
ListSelectorUtility.h
#import <UIKit/UIKit.h>

@protocol ListSelectorDelegate <NSObject>

- (void) returnValueString:(NSString *)value requestID:(long)requestID;

@end

@interface ListSelectorUtility : UITableViewController

@property (strong, nonatomic) NSString *data;
@property (weak, nonatomic) id<ListSelectorDelegate> delegate;
@property (nonatomic) long requestID;

@end

UpdateProperty.h
#import <UIKit/UIKit.h>
#import "ListSelectorUtility.h"

@interface UpdateProperty : UITableViewController <ListSelectorDelegate>

@property (nonatomic, strong) NSDictionary *data;

@end

There's an error on the @interface UpdateProperty : UITableViewController <ListSelectorDelegate> saying that No type or protocol named 'ListSelectorDelegate'. Why is this happened? How to solve this? Thanks.
EDIT: oh, and when I do CMD+click on the <ListSelectorDelegate>, it brings me straight up to the ListSelectorDelegate declaration. That means the IDE (supposedly) can find it.

A: set property of delegate (strong) on ListSelectorUtility.h
@property (strong, nonatomic) id<ListSelectorDelegate> delegate;

may bey problem of that because if it is week then dealloc by ARC and call the delegate method on ListSelectorUtility.h on your pass the data and values
[self.delegate returnValueString:obj_StringValue requestID:obj_requestID];

And finally this delegate method declare in UpdateProperty.h,
- (void) returnValueString:(NSString *)value requestID:(long)requestID
{
  //---------
  //Your Code
  //---------
}


text:
Q: Displaying variable goes wrong in IE , works in FF/Chrome etc So im trying to build me a website, using php mysql.
The following code produces a logo on the site.
<img src='assets/img/<?php echo $bedrijfslogo; ?>' alt='...' />

Where the $bedrijfslogo variable is filled earlier. i know the variable is filled and not null  because the logo renders in Chrome, but refuses to render in IE and FF , since there is no value.
When looking at the source in IE, i can see that the variable IS empty?

When looking at the source in Chrome there IS a value...

WTF am i doing wrong here? :/

A: Since PHP is a server-sided programming language it is in theory impossible to not see a variable in Internet Explorer and see it in Chrome.
I suspect you're HTML is incorrect and/or the filename contains an invalid character, something like:

Notice the ' char.
It can be that the WebKit engine (Chrome) will render it anyway and the MSIE engine (Internet Explorer) won't.
--
Besides,  is the same as

A: try this,
<img src='assets/img/<?=$bedrijfslogo?>' alt='...' />

let me know its helpfull or not?

A:
Where the $bedrijfslogo variable is filled earlier.

Have you checked that it exists/has a value?
In the comments you said that you populate this variable in a select statement with where email = '".$_SESSION['username'] - so if there's difference across browsers, I would assume that your session is simple not working, most likely because of the session id cookie not accepted by some browsers.

If the above is the case, PHP would have warned you already, if you only had set your error reporting to a sensible debugging value - so please do that now!

A: There was no problem at all.
If i had taken a minute and breath, i would have seen that the variable is filled based upon if your logged in or not, the difference was that in one browser i was logged in, and in the others i wasnt...... ASHAMED


text:
Q: Laptop Ubuntu 16.04 has loss of power during OS startup sequence (think I am a total newbie, especially really solving Ubuntu problems,
although copy and paste of code worked sometimes..)
Now during startup of my system, few seconds after showing up the Xubuntu Startup screen, HDD with maximum read operations, there occurs a complete power loss, power lamp still blinking (like standby?).
I press the main power button, screen turns on, laptop continues loading Ubuntu.
After login same failure (power loss/standby) happens once again.
I press main power button, now Xubuntu desktop loads properly.
I have the notion it has something to do with partitions/folders not correctly set up. Please, help!
Here are some things, I did to my laptop/Ubuntu installation:
Hardware
- Had a hardware issue with my HDD, fixed it by replacing HDD connector cable,
 tests in "gnome-disks" and "gparted" didn't give a clue for connection errors
I also disconnected and removed bad internal DVD writer and switched to external USB Logical Drive
Installation
- erased HDD with the tool of RedoBackup "Factory Drive Reset",
 which worked out, telling that some files/areas couldn't be deleted properly

*

*set up partition table and partitions with gparted,
also from bootable media

*finally installed Xubuntu, with Ubuntu 16.04, there is no other OS installed!

Screenshot of Gparted run within the system
Screenshot of kinfocenter
For good luck, there is no data in danger, because it's a new setup.
Looking forward..

A: I had an issue somewhat similar due to a corrupted XServer. Can you logon text only (No XServer) without the issue? I think you can press the Super/Windows button and Function key 5 to get a console. Could be something to look at. Take Care.


text:
Q: Reusing OpenFileDialog I have 2 textboxes and 2 button [...] next to each textbox. Is it possible to use one OpenFileDialog and pass the FilePath to the respective textbox, based on which button is clicked? i.e...if I click buttton one and laod the dialog, when I click open on the dialog, it passes the fileName to the first textbox.

A: Whenever you think "there's common functionality!" you should consider a method to implement it.  It could look like this:
    private void openFile(TextBox box) {
        if (openFileDialog1.ShowDialog(this) == DialogResult.OK) {
            box.Text = openFileDialog1.FileName;
            box.Focus();
        }
        else {
            box.Text = "";
        }
    }

    private void button1_Click(object sender, EventArgs e) {
        openFile(textBox1);
    }

A: There are several ways to do this. One is to have a Dictionary<Button, TextBox> that holds the link between a button and its related textbox, and use that in the click event for the button (both buttons can be hooked up to the same event handler):
public partial class TheForm : Form
{
    private Dictionary<Button, TextBox> _buttonToTextBox = new Dictionary<Button, TextBox>();
    public Form1()
    {
        InitializeComponent();
        _buttonToTextBox.Add(button1, textBox1);
        _buttonToTextBox.Add(button2, textBox2);
    }

    private void Button_Click(object sender, EventArgs e)
    {
        OpenFileDialog ofd = new OpenFileDialog();
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            _buttonToTextBox[sender as Button].Text = ofd.FileName;
        }
    }
}

Of course, the above code should be decorated with null-checks, nice encapsulation of behavior and so on, but you get the idea.

A: Yes it is, basically you need to keep a reference to the button that was clicked, and then a mapping of a textbox to each button:
public class MyClass
{
  public Button ClickedButtonState { get; set; }
  public Dictionary<Button, TextBox> ButtonMapping { get; set; }

  public MyClass
  {
    // setup textbox/button mapping.
  }

   void button1_click(object sender, MouseEventArgs e)
   {
     ClickedButtonState = (Button)sender;
     openDialog();
   }

   void openDialog()
   {
     TextBox current = buttonMapping[ClickedButtonState];
     // Open dialog here with current button and textbox context.
   }
}

A: This worked for me (and it's simpler than the other posts, but either of them would work as well)
private void button1_Click(object sender, EventArgs e)
{
    openFileDialog1.ShowDialog();
    textBox1.Text = openFileDialog1.FileName;
}

private void button2_Click(object sender, EventArgs e)
{
    openFileDialog1.ShowDialog();
    textBox2.Text = openFileDialog1.FileName;
}


text:
Q: Does ORDER BY only work with columns? Why does SELECT * FROM TABLE ORDER BY RAND() Work?  I thought ORDER BY only works for columns.
So what exactly does it mean to ORDER BY RAND() or ORDER BY SUM()?

A: ORDER will work with any value you can put in your results (but doesn't have to be one of the values in the results).  This can be a column in any of the source tables or calculated using a function.  For example, you could use ORDER UPPER(name) for a case-insensitive sort.
If you ORDER BY RAND() you're ordering by a random number generated for each row in the results, i.e. returning the rows in a random order.  If you're ordering by SUM() you've probably got a GROUP BY in there too so you could order customers by total calculated invoice total for example.
Ideally you want to use a column from an index as this will be much faster.

A: You can order by nearly everything, functions (like RAND()), aggregations (like SUM()) and so on.
For example, the MySQL-Documentation states as Syntax:
 [ORDER BY {col_name | expr | position}

Or the Postgresql Documentation is even more explicit:

The optional ORDER BY clause has this general form:
ORDER BY expression [ ASC | DESC | USING operator ] [, ...]
expression can be the name or ordinal number of an output column (SELECT list item), or it can be an arbitrary expression formed from input-column values.

For your second question:

*

*ORDER BY RAND() or ORDER BY RANDOM() does what it states: Your rows are shuffeled and you get them in a random order. So if you do a SELECT * FROM ... ORDER BY RAND() LIMIT 1 you select a (=one) random row out of your table.

*ORDER BY SUM(Column) only makes sense in combination with a GROUP BY statement.

A: Actually it depends on the implementation.The statement you mentioned is not SQL92-compatible but it may be accepted by an implementation.

A: Well, to put it short: You thought wrong.


text:
Q: Runtime error - java.lang.NumberFormatException: empty String I have written this code for image analysis:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ImageAnalysis {

    private double[][] filter;
    private double[][] Im;
    private int k;
    private int n;
    private int m;

    public ImageAnalysis(String filename) {

        BufferedReader br = null;

        try {

            String sCurrentLine;

            br = new BufferedReader(new FileReader(filename));
            sCurrentLine = br.readLine();
            String[] val = sCurrentLine.split(" ");
            // extracting the row and column from file first line
            int row = Integer.parseInt(val[0]);
            int col = Integer.parseInt(val[1]);

            n = row;
            m = col;

            Im = new double[row][col];
            int i = 0;
            // reading the file line by line
            while ((sCurrentLine = br.readLine()) != null) {
                val = sCurrentLine.split(" ");
                // System.out.println(val.length+" "+i);
                // store the values into two dimensional array
                for (int j = 0; j < col; j++) {
                    Im[i][j] = Double.parseDouble(val[j]);
                }
                i++;
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null)
                    br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        /*
         *
         * filter[0][0]=0; filter[0][1]=-1/8; filter[0][2]=0;
         *
         * filter[1][0]=-1/8; filter[1][1]=1/2; filter[1][2]=-1/8;
         *
         * filter[2][0]=0; filter[2][1]=-1/8; filter[2][2]=0;
         */

    }

    // this method will apply filter on image file
    public double[][] runFilter(String filterfilename) {
        BufferedReader br = null;

        try {

            String sCurrentLine;

            br = new BufferedReader(new FileReader(filterfilename));
            sCurrentLine = br.readLine();
            String[] val = sCurrentLine.split(" ");
            // extracting k value from file first line
            k = Integer.parseInt(val[0]);
            // applying the formula 2*k+1 to calculate row and col of matrix
            int row = 2 * k + 1, col = 2 * k + 1;
            // make array
            filter = new double[row][col];
            int i = 0;
            // reading the file line by line
            while ((sCurrentLine = br.readLine()) != null) {
                val = sCurrentLine.split(" ");
                for (int j = 0; j < col; j++) {
                    filter[i][j] = Double.parseDouble(val[j]);
                }
                i++;
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null)
                    br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        // calculate the row and col for filtered image
        int row = n - 2 * k;
        int col = m - 2 * k;
        // make filtered image 2D array
        double[][] filteredImage = new double[row][col];
        // filled the vvalue in filtered array by applying formula
        for (int a = 0; a < row; a++) {
            for (int b = 0; b < col; b++) {
                double sum = 0;
                for (int i = -k; i <= k; i++) {
                    for (int j = -k; j <= k; j++) {
                        sum += filter[i + k][j + k] * Im[a + i + k][b + j + k];
                    }
                }
                filteredImage[a][b] = sum;
                // System.out.println(sum);
            }
        }
        return filteredImage;
    }

}

It seems to work fine with .ftr files, but when I try with .ipi, I get the following runtime error:
Exception in thread "main" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at assignment2.ImageAnalysis.<init>(ImageAnalysis.java:44)
at ImageAnalysis_test_visible_04.main(ImageAnalysis_test_visible_04.java:3)

The .ipi file is:
18 20
1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
-1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0
-1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0
-1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0
-1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0
-1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0
-1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0
-1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0
-1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0
-1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0

The program uses real values between -1 and 1 where -1 means "no light at all" = black, 0 corresponds to 50% gray and 1 is white.

A: In your while loop I would do
val = sCurrentLine.split("\\s+");

just in case there are more than one spaces


text:
Q: Appropriate statistical tests for very limited-range (0, 1, 2) count data? I have some data from an experiment where participants from two different groups viewed a stimulus. There were 9 possible stimuli, distributed over 3 conditions (equivalent example: stimuli were all photos of two people. For the first condition, both participants had brown hair; For the second, both blonde; for the third, one brown and one blonde). Participants had to make two binary judgements about the stimuli (e.g. Person A hair colour: blonde or brown? Person B hair colour: blonde or brown?). The judgements were then scored as correct or incorrect, and summed to make a total score in the range of 0-2 for that particular stimulus. Participants viewed one stimulus from each condition.
I am interested in, primarily, a) whether participants produce judgements that are more accurate than chance, b) how participant group and stimulus condition interact with their score.
The dataset is relatively small (<100 participants), and moderately powered. Are standard parametric tests such as one-tailed t-tests (to test for better performance than chance) or a two-way ANOVA (total_score ~ group x condition) acceptable in this case? I know ANOVAs are generally robust to violations of their prerequisites, but I am concerned about the data range being so severely limited. Other options I considered include: some kind of count regression model (though those don't seem to be designed to deal with such a truncated data range), or a partial proportional odds model (which has an unfortunate lack of online documentation regarding acceptable use-cases, so I'm struggling to know if this is appropriate or not).


text:
Q: Why does my Winforms program reserve so much virtual memory? I have a C#/.NET 4.0 application that when I start it up shows two windows with about a dozen controls.  When I run my program (Debug or Release doesn't matter), before I even do anything in it, I see in Task Manager/Resource Monitor that my program already has upwards of 450MB of private memory.  I realize Task Manager isn't the most reliable way of measuring memory usage, but it is one of the most visible to my users.
When I run the VS2010 .NET Memory Allocation performance analysis, for a full run of my program, it reports about 5MB of RAM actually allocated for managed objects (my program normally uses a few unmanaged objects as well, but they are very small and to simplify this investigation I've disabled them, though to no notable effect).  Likewise, if I call EmptyWorkingSet() from psapi.dll after my main form has been shown, my private memory drops to ~3.5 MB.
I've already looked at the questions about memory footprints here and here, but those questions seem to be dealing with programs that show up as a couple dozen Megabytes.  My program shows almost 500MB, which looks a lot more worrisome.
I can't imagine all of that is from overhead; why is there such a huge discrepancy between the VS profiler and Task Manager?
Update: Interestingly enough, if I comment out a the part of InitializeComponent() that sets up the ImageLists, the number in Task Manager stays under 10MB.  I have two sets of PictureBoxes and ImageLists where the PictureBox displays one of four images depending on which radio button in a radio button group is selected.
These lines of code are the ones that seem to trigger the massive memory increase:
//
// directionImageList
//
this.directionImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("directionImageList.ImageStream")));
this.directionImageList.TransparentColor = System.Drawing.Color.White;
this.directionImageList.Images.SetKeyName(0, "Dir1.png");
this.directionImageList.Images.SetKeyName(1, "Dir2.png");
this.directionImageList.Images.SetKeyName(2, "Dir3.png");
this.directionImageList.Images.SetKeyName(3, "Dir4.png");
//
// modeImageList
//
this.modeImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("modeImageList.ImageStream")));
this.modeImageList.TransparentColor = System.Drawing.Color.White;
this.modeImageList.Images.SetKeyName(0, "Mode1.png");
this.modeImageList.Images.SetKeyName(1, "Mode2.png");
this.modeImageList.Images.SetKeyName(2, "Mode3.png");

I am using ImageLists so I can use transparency.  The Mode images are 100x100 and take up <26KB of disk space each.  The Direction images are 208x277 by default and about 75KB on disk.  I know png is a compressed format, but even uncompressed in memory I wouldn't expect hundreds of megabytes for these seven pictures.
Is there some inefficiency I'm aware of, and is there an alternate way to dynamically display pictures with transparency?
Conclusion: Something is fishy with the ImageList class.  Sometimes it'll lose the alpha channel, and it was causing my program to reserve way more memory than it needed.  It also was slowing down the time to draw the main form initially (both while running and in the designer).
Dumping the two ImageLists brought my program down to a much healthier 10MB of RAM.  Thanks for all of the suggestions everyone!

A: My own experience with this problem is that i had 24bit images in my imageList while i had 32bit option set in imagelist's settings.
I've set 24bit in imagelist's properties and the problem has gone. That seems to be a bug which someone should post to MS =)
Sorry for my English.

A: the .Net framework was designed to run as fast as possible given the resources available. The application will continue to consume more and more memory as it in requested (and is readily available) only letting go when you specifically call the garbage collector or when another application needs the resources it is hogging.
Minimize the app and you should see a better representation of how much memory your application is using.
if you then go back to using it, it will remain at the lower resource state until it gets used and consumes again. minimize it again to see how much is actually (not) being used again. this is built into the .net frameworks memory management system.

A: Someone explained few reasons where memory jumped from 34 MB to 145 MB: Finding the true memory footprint of a Windows application

A: First up, have you tried Debug Diag?  It will analyse a dump of your process and give some nifty graphs memory which might help you figure out who has allocated all that memory.
Also, check to make sure that neither your compiled .exe or any of your referneced / loaded assemblies is very large - it is entirely possible that all ~500MB is just loaded dlls.  This might happen if (for example) large resources have been embedded into the assembly.

A: png's have transparency already. Just make the white a transparent color and save the image. Then use them normally.


text:
Q: Symfony2 doctrine2 working with collections - performances The point of this question is to figure out what technique is better and heard different opinions from some skilled symfony2 coders.
An example will be ilustrated on challenges and "challenge rating" table where many people can rate certain challenge. (something like stackoverflow vote question system).
The tables look like this: (like_dislike is boolean(1= like, 0 = dislike)

The amount of data will be from 10-200+  rates for challenge.

Working with collections
Challenges entity
/**
 * Challanges
 *
 * @ORM\Table(name="challanges")
 * @ORM\Entity(repositoryClass="TB\ChallangesBundle\Entity\ChallangesRepository")
 */
class Challanges
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     * @Assert\NotBlank()
     */
    private $name;

    /**
     * @var string
     *
     * @ORM\Column(name="slug", type="string", length=255, unique=true)
     */
    private $slug;

    /**
     * @var string
     *
     * @ORM\Column(name="description", type="text")
     * @Assert\NotBlank()
     */
    private $description;

    /**
     * @var \DateTime
     * @ORM\Column(name="start_date", type="datetime", nullable=false)
     * @Assert\DateTime()
     */
    private $start_date;

    /**
     * @var \DateTime
     * @ORM\Column(name="end_date", type="datetime", nullable=false)
     * @Assert\DateTime()
     */
    private $end_date;

    /**
     * @ORM\ManyToOne(targetEntity="TB\UserBundle\Entity\User", fetch="EXTRA_LAZY")
     * @ORM\JoinColumn(name="owner_id", referencedColumnName="id", nullable=false)
     */
    protected $owner;

    /**
     * @ORM\OneToMany(targetEntity="TB\ChallangesBundle\Entity\ChallangeRating", mappedBy="challange", cascade={"persist", "remove"})
     */
    protected $likes;

/**
 * Constructor
 */
public function __construct()
{
    $this->likes = new \Doctrine\Common\Collections\ArrayCollection();
}

/**
 * Add likes
 *
 * @param \TB\ChallangesBundle\Entity\ChallangeRating $likes
 * @return Challanges
 */
public function addLike(\TB\ChallangesBundle\Entity\ChallangeRating $likes)
{
    $this->likes[] = $likes;

    return $this;
}

/**
 * Remove likes
 *
 * @param \TB\ChallangesBundle\Entity\ChallangeRating $likes
 */
public function removeLike(\TB\ChallangesBundle\Entity\ChallangeRating $likes)
{
    $this->likes->removeElement($likes);
}

/**
 * Get likes
 *
 * @return \Doctrine\Common\Collections\Collection
 */
public function getLikes()
{
    return $this->likes;
}

public function filterLikesInChallenge($like_dislike) {
    $criteria = Criteria::create();
    $criteria->where(Criteria::expr()->eq('like_dislike', $like_dislike));

    return $this->likes->matching($criteria);
}

public function checkIfUserRatedAlready(\TB\UserBundle\Entity\User $user)
{
    $criteria = Criteria::create();
    $criteria->where(Criteria::expr()->eq('fan', $user));

    return $this->likes->matching($criteria);
}

Challenge rating entity
<?php

namespace TB\ChallangesBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * ChallangeRating
 *
 * @ORM\Table(name="challange_rating")
 * @ORM\Entity(repositoryClass="TB\ChallangesBundle\Entity\ChallangeRatingRepository")
 */
class ChallangeRating
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var boolean
     *
     * @ORM\Column(name="like_dislike", type="boolean")
     */
    private $like_dislike;

    /**
     * @ORM\ManyToOne(targetEntity="TB\UserBundle\Entity\User", inversedBy="fans")
     */
    protected $fan;

    /**
     * @ORM\ManyToOne(targetEntity="TB\ChallangesBundle\Entity\Challanges", inversedBy="likes")
     */
    protected $challange;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Get like_dislike
     *
     * @return boolean
     */
    public function getLikeDislike()
    {
        return $this->like_dislike;
    }

    /**
     * Set like_dislike
     *
     * @param boolean $like_dislike
     * @return ChallangeRating
     */
    public function setLikeDislike($like_dislike)
    {
        $this->like_dislike = $like_dislike;

        return $this;
    }

    /**
     * Set fan
     *
     * @param \TB\UserBundle\Entity\User $fan
     * @return ChallangeRating
     */
    public function setFan(\TB\UserBundle\Entity\User $fan = null)
    {
        $this->fan = $fan;

        return $this;
    }

    /**
     * Get fan
     *
     * @return \TB\UserBundle\Entity\User
     */
    public function getFan()
    {
        return $this->fan;
    }

    /**
     * Set challange
     *
     * @param \TB\ChallangesBundle\Entity\Challanges $challange
     * @return ChallangeRating
     */
    public function setChallange(\TB\ChallangesBundle\Entity\Challanges $challange = null)
    {
        $this->challange = $challange;

        return $this;
    }

    /**
     * Get challange
     *
     * @return \TB\ChallangesBundle\Entity\Challanges
     */
    public function getChallange()
    {
        return $this->challange;
    }
}

Okay and now i would like:

*

*Display challenge details

*Display rate feature (like, dislike) also with numbers of likes and dislikes

*Display the list of all users that have rated this challenge

Controller
So classic beginning with obtaining $challenge
// this will take care of point number 1 (display challenge details) (1.)
$challange = $challangesRepo->findOneBy(array('slug'=>$slug));

// display numbers of likes and dislikes for certain challenge (2.)

But now comes a decision...
Question 1
Should i obtain the likes via quering the DB from querybuilder? (classic select count)
OR
Should i use collections and criteria like this ? :
    $challangeLikes = $challange->filterLikesInChallenge(1);
    $challangeDislikes = $challange->filterLikesInChallenge(0);

**What is better for memory usage? what is better for DB performances? **
If i am not wrong the following two queries are executed by these two methods:
SELECT
  t0.id AS id1,
  t0.like_dislike AS like_dislike2,
  t0.fan_id AS fan_id3,
  t0.challange_id AS challange_id4
FROM
  challange_rating t0
WHERE
  (
    t0.like_dislike = ? AND t0.challange_id = ?
  )
Parameters: [1, 12]

SELECT
  t0.id AS id1,
  t0.like_dislike AS like_dislike2,
  t0.fan_id AS fan_id3,
  t0.challange_id AS challange_id4
FROM
  challange_rating t0
WHERE
  (
    t0.like_dislike = ? AND t0.challange_id = ?
  )

And now i can pass the number of likes,dislikes to the view as follow:
'challangeLikes'=>$challangeLikes->count(),
'challangeDislikes'=>$challangeDislikes->count(),

Question 2
What if i want to know if certain user rated this challenge already?
Again...
*Should i use classic querybuilder style with select count *
OR
I should use a method like:
$ratedAlreadyCol = $challange->checkIfUserRatedAlready($user)->first();

That will execute actually another query ? something like classic select count but the collection will do this for me? So it's not a search in some big memory array with allll likes but it's a query to DB ?
SELECT
  t0.id AS id1,
  t0.like_dislike AS like_dislike2,
  t0.fan_id AS fan_id3,
  t0.challange_id AS challange_id4
FROM
  challange_rating t0
WHERE
  (
    t0.fan_id = ? AND t0.challange_id = ?
  )
Parameters: [25, 12]

Question 3 - probably the most important for performances
I want to display all "fans - people who rated the certain challenge"...
Again...
Should i create a separate querybuilder method in repository with selecting all ratings for certain challenge with inner join to the users table (so i can display profile image and username)
OR
Should i just get all ratings and in twig loop through it like:
 $challangeLikesCollection = $challange->getLikes();

{% for bla bla

BUT
If i will do it this way... doctrine will execute a select query to the user table for every "fan" in loop... and when there will be let's say... 200 fans... that's not good right?
BONUS QUESTION
Can somehow please provide his way of dealing with these situations? any suggestions?
Or do you use any other technique?
i care a lot about memory usage and DB load time because this will be used everywhere and every user will have such a list with different challenges. The list will consist of let's say 15 challenges and to connect all the likes,dislikes to every challenge in the list etc etc... performances...
Thank you for your explanations, tips and hints that will help me and other readers to move on another level!

A: I would do the following:

*

*Denormalize a little and add number of likes and number of dislikes fields to Challenge and update these values in addLike and removeLike

*Rename like_dislike to like as it's a boolean field and 1 means like 0 means dislike

*Query the list of users with a separate query and use array hydration and INDEXBY username (it must be unique or user id) or maybe create a custom hydrator
SELECT u.username, u.photo FROM User u INNER JOIN u.ratings WITH r.fan = :fan INDEX BY u.username
or something like that. And you can check if the current user's username is in the array or not.
I think this could be performant enough.
Some explanation:
INDEX BY means that the result collection or array key (index) will be the value of a field (this field has to be unique). When you use INDEX BY the result set will contain known keys so you can reach (and e.g. check for existence) individual results directly in constant time (you don't have to search through the whole result set).
Doctrine uses PDO underneath, hydration means how the PDO result set will be processed and transformed into something else. The default object hydration means the result set will be transformed into an object graph, it is a very expensive operation. There are other hydration modes which are less expensive, but you loose some felxibility. E.g. if you use array hydration the result will be an array of arrays so you can't modify it (I mean persist back to the database) so it's just for reading and as the result not entity objects you can't use it's methods, e.g. custom getters. You can create custom hydrators if you want.


text:
Q: Unable to resolve name [org.hibernate.dialect.MySQL5Dialect ] as strategy [org.hibernate.dialect.Dialect] I am new in Spring Application with Gradle.
Running my project to create the database objects based on my classes created, i got the following error:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.boot.registry.selector.spi.StrategySelectionException: Unable to resolve name [org.hibernate.dialect.MySQL5Dialect ] as strategy [org.hibernate.dialect.Dialect]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1572)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:960)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:749)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:117)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:689)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:321)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:969)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:958)
at com.krypton.smartImmo.SmartImmoApplication.main(SmartImmoApplication.java:10)

Caused by: org.hibernate.boot.registry.selector.spi.StrategySelectionException: Unable to resolve name [org.hibernate.dialect.MySQL5Dialect ] as strategy [org.hibernate.dialect.Dialect]
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.selectStrategyImplementor(StrategySelectorImpl.java:128)
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveDefaultableStrategy(StrategySelectorImpl.java:155)
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveStrategy(StrategySelectorImpl.java:136)
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.constructDialect(DialectFactoryImpl.java:78)
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:68)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:165)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)

in the application.properties i ahve the following setting concerning hibernate
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

A: I also faced the same issue, no need to declare any dialect in the properties file, after removing dialect properties, it work's fine.
My dependencies:
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.6.7</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.6.7</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

Application properties:

spring.datasource.name =test
spring.datasource.url=jdbc:mysql://localhost:3306/myDB
spring.datasource.username=root
spring.datasource.password=root
#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#spring.jpa.properties.hibernate.dialect=org.hibernate.deialect.MySql5InnoDBDialect
#spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
#spring.jpa.properties.hibernate.dialect=org.hibernate.deialect.MySql55Dialect
spring.datasource.hikari.maximum-pool-size=10
##spring.jpa.hibernate.ddl-auto=updates`

A: Since you errormessage contains that suspicious extra space at the end:
Unable to resolve name [org.hibernate.dialect.MySQL5Dialect ]

I will take a wild guess that you have an extra space at the end of your dialect property.
So look for
"org.hibernate.dialect.MySQL5Dialect "

and change it to:
"org.hibernate.dialect.MySQL5Dialect"

A: Actually space is not the problem if your dialect name is correct.
But as Rajiv Mishra said, you don't need to explicitly specify the dialect, springboot does it for you automatically.
I am using STS ide for this.

A: [Solved 2023] I am using MySQL'8' so I simply changed it to MySQL8Dialect

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect

So please check your MySQL Version and it will work fine

A: Thanks! I too had the same problem of extra space. Just we have to make sure that, whenever we click on different lines in app.properties file , the cursor should be at the end ,just beside letter t of MySQL8Dialect.Enclose the value for the key spring.jpa.properties.hibernate.dialect with " " quotes and then remove it, that way I had to resolve the issue, as cursor was not coming just after the letter t.


text:
Q: Mutable Array of SimpleDB Items, Attributes and Values in UITableView Below is this returned NSLog of an array (items3) of AWS SimpleDB Item with two attributes and two attribute values. I want to show a UITableView of the cell.textLabel.text = ItemName and cell.detailTextLabel.text = Value2.
items3 = (
    "ItemName",
        (
        "{Name: Attribute1,AlternateNameEncoding: (null),Value: Value1,AlternateValueEncoding: (null),<SimpleDBAttribute: 0x2eeaf0>}",
        "{Name: Attribute2,AlternateNameEncoding: (null),Value: Value2,AlternateValueEncoding: (null),<SimpleDBAttribute: 0x2f38e0>}",
    )

How do show all items, but only the value for Attribute2? Is there a way to say object for Key@"Attribute2" which equals value2?
Something like:
cell.textLabel.text = [itmes3 objectAtIndex: indexpath.row];
[[ cell.detailTextLabel.text = [[items3 objectAtIndex:0] stringForKey:@"Attribute2"];

A: Use:
for (SimpleDBItem *item in selectResponse.items)

then run a GetAttributesRequest on item.name, like this:
for (SimpleDBAttribute *attr in response.attributes) {
    if ([attr.name isEqualToString:@"Attribute2"])


text:
Q: Comparing two lists of different length and returning data I have a workbook with two worksheets F1 and F2.
On each, Column A is last names, Column B is first names, and Column C is department names. F2 lacks the department names.
I am trying to compare and match the names in F2 with the names in F1 and return the department names from F1's Column C to F2's Column C.
The difficulty I'm having is that F1's list is significantly longer than F2's list. Otherwise I could just do a simple comparing thing.
Thank you for any help.

A: So if we have data like this:
Sheet F1
     A           B          C
----------------------------------
Last Name   First Name  Department
Bar         Foo                  1
Bar2        Foo                  2
Bar3        Foo                  3
Bar4        Foo                  4

And we want this:
Sheet F2
     A           B          C
----------------------------------
Last Name   First Name  Department
Bar3        Foo                  3

You can use an array formula in column C (entered with Ctrl + Shift + Enter)
=INDEX(F1!C:C,MATCH(CONCATENATE(F2!A2,F2!B2),CONCATENATE(F1!A:A,F1!B:B),0))

Then fill down to suit
If you find the execution time to be too long for that formula you can narrow down the CONCATENATE range to your specific data.  i.e.:
=INDEX(F1!C:C,MATCH(CONCATENATE(F2!A2,F2!B2),CONCATENATE(F1!$A$1:$A$5,F1!$B$1:$B$5),0))


text:
Q: Event Viewer Errors: Address  being plumbed for adapter  already exists I'm seeing these errors repeating ~every 5 minutes in my Administrative Events:

Address 192.168.0.195 being plumbed for adapter 18 already exists

and

An error has occurred in initializing the interface 18. Error Code is 0x1392

Doing a route print shows that adapter 18 (shown with the green box in the screenshot below) is the hardware NIC on my MOBO, named "Intel® l211 (etc.)" a.k.a. "LAN", which is required for my computer to have internet access.
I also have a software NIC that is setup when enabling Hyper-V, a Bridge I believe, named "vEthernet Hyper-V [External]", shown in the orange box, which is also required for the computer to have internet access.

I have both of those set to automatically get their IP4 DNS settings via their properties.
My thought is that somehow the router is getting these 2 adapters "confused" and wanting to set them both to the same IP, thus giving the hardware NIC an error?
I have read here:
https://richardcarterorg.wordpress.com/2011/05/10/event-id-50034-50068/
that disabling one should "fix" the issue, but as mentioned, my machine requires both in order to have network/internet access; disabling wither one of them disconnects me from the net. I have also tired temporarily disable/re-enabling each one to see if that sorted things out, but it did not.
Anyone have any idea how to solved this error?

A: I had this same issue on my Hyper-V hypervisor and believe I figured out what causes it...
The MAC address of my primary network card, the one referenced in the event log, matches the MAC address of my Hyper-V Virtual Switch. I confirmed this using the 'ipconfig /all' command in command prompt.
My primary network card has a statically assigned address, but I also added a DHCP reservation for that MAC address on the DHCP server, in case the static setting ever got cleared out for some reason.
So DHCP is seeing the MAC address of my Hyper-V Virtual Switch, which matches my primary network card, and is trying to assign the Hyper-V Virtual Switch the same IP that I have set statically on my primary network card.
Long story short, I am guessing you have a DHCP reservation set up for the MAC address of your 'LAN' network adapter, and your Hyper-V Virtual Switch 'vEthernet (Hyper-V [External])', is trying to pick up the same IP as your LAN network adapter.


text:
Q: Can I write PowerShell binary cmdlet with .NET Core? I'm trying to create a basic PowerShell Module with a binary Cmdlet internals, cause writing things in PowerShell only doesn't look as convenient as in C#.
Following this guide, it looks like I have to:

*

*add Microsoft.PowerShell.SDK to my project.json

*mark my cmdlet class with required attributes

*write manifest file, with RootModule, targeting my .dll

*put that .dll nearby manifest

*put both under PSModulePath
but, when I'm trying to Import-Module, PowerShell core complains on missing runtime:
Import-Module : Could not load file or assembly 'System.Runtime, Version=4.1.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system
cannot find the file specified.
At line:1 char:1

Am I doing something wrong, or such tricky things are not supported yet as well?

A: For netcore, there is a new template for powershell that you can install and use then you can modify the c# code.

*

*Installing the PowerShell Standard Module Template

$ dotnet new -i Microsoft.PowerShell.Standard.Module.Template

*

*Creating a New Module Project in a new folder

$ dotnet new psmodule

*

*Building the Module

dotnet build

For more details read doc

A: This gets a lot easier with .NET Core 2.0 SDK and Visual Studio 2017 Update 15.3 (or higher).  If you don't have VS, you can do this from the command line with the .NET Core 2.0 SDK.
The important bit is to add the PowerShellStandard.Library 3.0.0-preview-01 (or higher) NuGet package to your project file (.csproj).
Here is a simple command line example:
cd $home
dotnet new classlib --name psmodule
cd .\psmodule
dotnet add package PowerShellStandard.Library --version 3.0.0-preview-01
Remove-Item .\Class1.cs
@'
using System.Management.Automation;

namespace PSCmdletExample
{
    [Cmdlet("Get", "Foo")]
    public class GetFooCommand : PSCmdlet
    {
        [Parameter]
        public string Name { get; set; } = string.Empty;

        protected override void EndProcessing()
        {
            this.WriteObject("Foo is " + this.Name);
            base.EndProcessing();
        }
    }
}
'@ | Out-File GetFooCommand.cs -Encoding UTF8

dotnet build
cd .\bin\Debug\netstandard2.0\
ipmo .\psmodule.dll
get-foo

To get this same command to run in Windows PowerShell 5.1 requires a bit more work.  You have to execute the following before the command will work:
Add-Type -Path "C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.netcore.app\2.0.0\ref\netcoreapp2.0\netstandard.dll"

A: You need to use PowerShell Core to write a PowerShell CmdLet in .NET Core.
There is a guide here, including corrections to your project.json:
https://github.com/PowerShell/PowerShell/tree/master/docs/cmdlet-example
To summarize you need the following in your project.json
    "dependencies": {
        "Microsoft.PowerShell.5.ReferenceAssemblies": "1.0.0-*"
    },

    "frameworks": {
        "netstandard1.3": {
            "imports": [ "net40" ],
            "dependencies": {
                "Microsoft.NETCore": "5.0.1-*",
                "Microsoft.NETCore.Portable.Compatibility": "1.0.1-*"
            }
        }
    }


text:
Q: Reset sequence number monthly VL/11/2014/050 to VL/12/2014/001
    <record id="seq_new_lead" model="ir.sequence">
        <field name="name">Visit Log</field>
        <field name="code">lead</field>
        <field name="prefix">VL/%(month)s/%(year)s/</field>
        <field name="interval number">1</field>
        <field name="interval units">months</field>
        <field name="padding">3</field>

    </record>

but it's not working. It should reset automatically at every month and start with 001.

A: You need this module:
OpenERP ir sequence autoreset
It was very helpful to me. It works with standard implementation but if you need working with no_gap implementation you will have to code a little by your own like I did, I can help you if you ask.
I know it's late for answering but maybe someone need this now.


text:
Q: Windows/Python UDP Broadcast Blocked No Firewall OS: Windows 10
I use an Ethernet switch to send UDP packets to two other systems (connected directly to that same switch) simultaneously via Python 3.4.4. The same code works on two other dev/testing PC's so I know it's not the Python code, but for some reason it doesn't work on the PC that I want the system to be utilized by.
When I use Wireshark to view the UDP traffic at 169.254.255.255 (the target IP for sending the UDP packets to), nothing appears. However, sending packets to 169.X.X.1 works. On the other hand, packets sent to 169.X.X.255 are sent, but I receive time-to-live exceeded messages in return. I am restricted to that target IP, so changing the IP is not a solution. I also have it sending on port 6000 (arbitrary), I have tried changing the port number to no avail. Also won't let me send to 169.254.255.1
I have the firewalls turned off.
Thanks for your help.

A: same problem here,
solution is bind socket to adapter which is sending multicast
example:
msg = \
    'M-SEARCH * HTTP/1.1\r\n' \
    'HOST:239.255.255.250:1900\r\n' \
    'ST:upnp:rootdevice\r\n' \
    'MX:2\r\n' \
    'MAN:"ssdp:discover"\r\n' \
    'USER-AGENT:Python\r\n\r\n'

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
s.bind(('ip of interface',1901))
s.settimeout(10)
print msg,len(msg)
print s.sendto(msg, ('239.255.255.250', 1900) )
resp, (addr, port) = s.recvfrom(1024)
print resp
s.close()

solution from this post Can't send multicast over non-default NIC

A: The strange thing about my problem, was that this exact code worked on the computer in question (and two development computers) previously, but wasn't working at the time that I posted this question.
Wireshark wasn't leading me to my answer (only showing me that the UDP packets were not sent), so I decided to ping the IP via the command prompt. I received one of two errors (destination host unreachable, or request timed out). These errors led me to adding my desired target IP (169.254.255.255) to the ARP cache,  which my problem was solved.
I'd like to thank you for suggesting a possible solution.


text:
Q: Equivalence relation on pairs of integers by their gcd On $\mathbb{N}\times\mathbb{N}$ define the relation  $R$, where $((a,b),(c,d)) \in R$ if and only if $\gcd(a,b)=\gcd(c,d)$. Show that $R$ is a equivalence relation.
Reflexivity :
For every $(a,b) \in \mathbb{N}\times\mathbb{N}$ we have $\gcd(a,b)=\gcd(b,a)$ and $\gcd(c,d)= \gcd(d,c)$
so $(a,b)R(a,b)$ and $R$ is reflexive
Symmetry :
Therefore $(c,d)R (d,c)$
Transitivity :
$\gcd(a,b)=x, \gcd(c,d)=y$ AND $\gcd(e,f)=z$.
$\gcd(a,b)= \gcd(c,d)$ and $\gcd(c,d)= \gcd(e,f)$ therefore  $\gcd(a,b)=\gcd(e,f)$.
I am confused with the transitivity. Is that right ?


text:
Q: Pixelated Icon when rendered I am working on an app that's a social media app. I have my icon but it's pixelated.  I was wondering how I could clear that up. I have never had this issue before. The login screen has the logo and it's the same logo for the icon. I am assuming the icon cannot handle the image.

Here is the icon:

Any advice would be helpful.

A: Try using SVG format for the icon

A: This is because you're trying to render a high res image as an icon
Use an online formatter like Appicon to convert that image to lower res and then use that newly created image as the icon


text:
Q: orthogonality of matrices A theorem in linear Algebra tells us

A matrix U is orthogonal iff $U^TU=I$ where I is the identity matrix.

I get the part that if U is orthogonal then $U^TU=I$, but why should $U^T$ also be orthogonal, consider the following case:
Let $$U =\begin{bmatrix}
a&b\\c&d
\end{bmatrix}
$$
let $$ a_1= \begin{bmatrix} a\\c \end{bmatrix} \ and\ a_2= \begin{bmatrix} b\\d \end{bmatrix}$$
we have,
$$a_1.a_2=0,\ |a_1|=1 \ and\ |a_2|=1$$
  i.e. from the theorem
 $$a^2+b^2=1,\ c^2+d^2=1,\ ac+bd=0 \ \ \ \ \ -> case1$$
Now, the real confusion is this site gives proof then $U^T$ is also orthogonal, but for that to happen this should hold true:
$$a^2+c^2=1,\ b^2+d^2=1,\ ab+cd=0\ \ \ \ \ ->case2$$
I don't see how is this possible in general cases where $U$ is an orthogonal matrix. How is $U^T$ orthongonal and how can both case1 and case2 hold at the same time in every case where $U$ is an orthogonal matrix?

A: Suppose the set of equalities in case 1 holds. We can write $a=\sin x,b=\cos x,c=\cos y,d=\pm\sin y$ for some angles $x$ and $y$, by the Pythagorean trigonometric identity (the sign in front of $d$ is important, and differentiates rotation and reflection matrices). Then $ac+bd=0$ is $\sin x\cos y\pm\cos x\sin y=\sin(x\pm y)=0$, so $x=-y$ or $x=y$ up to periodicity (modulo $2\pi$) if the sign in front of $d$ was $+$ or $-$ respectively. Hence
$$a^2+c^2=\sin^2x+\cos^2x=1$$
$$b^2+d^2=\cos^2x+\sin^2x=1$$
$$ab+cd=\sin x\cos x-\cos x\sin x=0$$
and case 2 holds. A similar argument proves case 1 from case 2, so $U$ and $U^T$ are both orthogonal.

A: $U$ is a square matrix.
$U^TU=I$ means $U^T$ is the inverse of $U$, hence we have $UU^T=I$.


text:
Q: Как открыть ViewPager2 сразу на нужной странице? Одна активность вызывает другую активность на которой расположен ViewPager2. Нужно вывести ViewPager2 сразу на определённой странице (например на 10-й). Если я пишу
viewPager2.setCurrentItem(10);

то он открывает 10 страницу, но при этом видно как он листает предыдущие страницы. Как открыть ViewPager2 сразу на нужной странице?

A: Используйте viewPager2.setCurrentItem(10, false).
Второй параметр как раз отвечает за то нужна прокрутка или нет.
https://stackoverflow.com/a/59827597/8389574


text:
Q: PFQueryTableView Auto Refresh When New Data Updated or Refresh Every Minute Using Parse Currently Im following this tutorial http://www.appcoda.com/ios-programming-app-backend-parse/
But I want the tableviewcontroller to be refresh with new data when data from parse.com is update automatically. I don't want the user to always have to pull to refresh.
or maybe having time refresh every minute?
I heard about reloaddata but how to implement the code?
- (id)initWithCoder:(NSCoder *)aCoder
{
 self = [super initWithCoder:aCoder];
 if (self) {
     // The className to query on
     self.parseClassName = @"Recipe";

     // The key of the PFObject to display in the label of the default cell style
     self.textKey = @"name";

     // Whether the built-in pull-to-refresh is enabled
     self.pullToRefreshEnabled = YES;

     // Whether the built-in pagination is enabled
     self.paginationEnabled = NO;
 }
 return self;
}

- (PFQuery *)queryForTable
{
 PFQuery *query = [PFQuery queryWithClassName:self.parseClassName];

 return query;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object
{
 static NSString *simpleTableIdentifier = @"RecipeCell";

 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
 if (cell == nil) {
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
 }

 // Configure the cell
 PFFile *thumbnail = [object objectForKey:@"imageFile"];
 PFImageView *thumbnailImageView = (PFImageView*)[cell viewWithTag:100];
 thumbnailImageView.image = [UIImage imageNamed:@"placeholder.jpg"];
 thumbnailImageView.file = thumbnail;
 [thumbnailImageView loadInBackground];

 UILabel *nameLabel = (UILabel*) [cell viewWithTag:101];
 nameLabel.text = [object objectForKey:@"name"];

 UILabel *prepTimeLabel = (UILabel*) [cell viewWithTag:102];
 prepTimeLabel.text = [object objectForKey:@"prepTime"];

 return cell;
}

A: In .h file
@property (nonatomic, strong) NSTimer *fetchTimer;
@property (nonatomic, strong) NSArray *items;

In .m file
- (void)viewDidLoad
{
    NSTimer *timer = [NSTimer timerWithTimeInterval:3600
                                             target:(id)self
                                           selector:@selector(fetch)
                                           userInfo:nil
                                            repeats:YES];
    self.fetchTimer = timer;
}

- (void)fetch
{
    PFQuery *query = [PFObject query];
    [query whereKey:@"" equalTo:@""];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {

        self.items = [NSArray arrayWithArray:objects];
        [self.tableView reloadData];
    }];
}

1) Set a NSTimer with 3600 intervalTime and trigger the fetch data function.
2) Just call [self.tableView reloadData] when the data has been fetch. It is all depends on how you design your coding structure.


text:
Q: Yandex Map Api работа с существующими на карте метками 3 день изучаю работу с апи, но так нигде и не нашёл следующих возможностей:
1) Обрабатывать нажатие на не пользовательские объекты на карте (рестораны, кафе, аптеки и.т.д), затем получая координаты этих меток.
2) Отображение объектов карты определённых категорий. Например только аптеки или только рестораны.
3) Могу ли для существующего объекта переопределить balloon?
4) Как запретить открывание ballon при клике на любой из объектов карты.
Вопросы относятся только к уже существующим объектам на карте, которые стандартно отображаются. О том как работать со своими кастомными объектами понятно, документация только об этом.

A: Изменять данные карты средствами API нельзя, более того это запрещено Пользовательским соглашением (п. 2.3.10.2) https://yandex.ru/legal/maps_api/


text:
Q: python lists of lists: сгруппировать записи из sqlite по email Всем привет,
ищу совета по решению задачи, делаю выборку из бд sqlite, и в выборке повторяется электронный адрес клиента, чтоб не высылать два раза клиенту письмо, нужно высылать одним письмом.
вид вывода данных о клиенте:
email1|data1|data2
email2|data1|data2
email3|data1|data2
email1|data1|data2

если email1 существует то просто дабавить инфу уже к существующей записи, и так с другими адресами, идея в том чтоб клиент не получал спама из кучи писем, а все в одном, как можно реализовать такую функцию, допустим если я буду парсить адрес клиента в списке:([-a-zA-Z0-9_.]+@\w+.\w+), то как создавать список на основании его мейла? и как грамотно реализовать такую функцию. Спасибо за советы.

A: решил задачу таким образом,
когда вытягиваю данные о клиенте из бд, делаю еще раз запрос, но только почтовый адресс, и делаю обработку на повторения, если нет такого ключа то добавляю новую запись и тд.
mail_data = {}

if result_mail in mail_data:
   mail_data[result_mail] += (value)
   print("get it")
else:
   mail_data.update({key: value})