text:
Q: MSQuery includeTotalCount doesn't work?
includeTotalCount
  Indicates if the Windows Azure Mobile Service should also include the total count of items on the server (not just the count of items returned) with the query results.

but totalCount is alway -1,
here is my code
MSQuery *query = [_skinsTable query];
query.predicate = bPredicate;
query.includeTotalCount = YES;
query.fetchOffset = offset;
query.fetchLimit = limit;
[query readWithCompletion:^(NSArray *items, NSInteger totalCount, NSError *error) {

    //here everything is OK(items, error), but totalCount is -1
}];

I have no idea what's wrong?

A: As long as you don't have any custom scripts in your read operation for your table, it should just work. For example, if you create a new table (called 'test'), and run this code below, its totalCount parameter will have the appropriate value (4, in this case).
- (IBAction)clickMe:(id)sender {
    MSClient *client = [MSClient clientWithApplicationURLString:@"https://YOUR-SERVICE.azure-mobile.net/"
                                                 applicationKey:@"YOUR-KEY"];
    MSTable *table = [client tableWithName:@"test"];
    NSDictionary *item1 = @{@"name":@"Scooby Doo",@"age":@10};
    NSDictionary *item2 = @{@"name":@"Shaggy",@"age":@19};
    NSDictionary *item3 = @{@"name":@"Daphne",@"age":@18};
    NSDictionary *item4 = @{@"name":@"Fred",@"age":@20};
    NSDictionary *item5 = @{@"name":@"Velma",@"age":@21};
    [table insert:item1 completion:^(NSDictionary *item, NSError *error) {
        [table insert:item2 completion:^(NSDictionary *item, NSError *error) {
            [table insert:item3 completion:^(NSDictionary *item, NSError *error) {
                [table insert:item4 completion:^(NSDictionary *item, NSError *error) {
                    [table insert:item5 completion:^(NSDictionary *item, NSError *error) {
                        MSQuery *query = [table query];
                        NSPredicate *bPredicate = [NSPredicate predicateWithFormat:@"age > 15"];
                        query.predicate = bPredicate;
                        query.includeTotalCount = YES;
                        query.fetchLimit = 3;
                        query.fetchOffset = 0;
                        [query readWithCompletion:^(NSArray *items, NSInteger totalCount, NSError *error) {
                            NSLog(@"Items: %@", items);
                            NSLog(@"TotalCount: %d", totalCount);
                        }];
                    }];
                }];
            }];
        }];
    }];
}

One good way to check that the request and response are the ones expected to get the inlineCount to work is to use a custom filter which logs the request and responses. Define a new interface as the one below:
@interface FPLoggingFilter : NSObject<MSFilter>

@end

@implementation FPLoggingFilter

- (void)handleRequest:(NSURLRequest *)request next:(MSFilterNextBlock)next response:(MSFilterResponseBlock)response {
    NSLog(@"Request: %@", request);
    next(request, ^(NSHTTPURLResponse *resp, NSData *data, NSError *error) {
        NSLog(@"Response: %@", response);
        NSString *respBody = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"Response body: %@", respBody);
        response(resp, data, error);
    });
}

@end

And change the code in the inner-most block to use that:
MSClient *filteredClient = [client clientWithFilter:[FPLoggingFilter new]];
MSTable *filteredTable = [filteredClient tableWithName:@"test"];
MSQuery *query = [filteredTable query];
NSPredicate *bPredicate = [NSPredicate predicateWithFormat:@"age > 15"];
query.predicate = bPredicate;
query.includeTotalCount = YES;
query.fetchLimit = 3;
query.fetchOffset = 0;
[query readWithCompletion:^(NSArray *items, NSInteger totalCount, NSError *error) {
    NSLog(@"Items: %@", items);
    NSLog(@"TotalCount: %d", totalCount);
}];

Now, if you run this code, you should see in the logs that the request has a $inlinecount=allpages query string parameter. And the response isn't a simple array of objects. Instead, it's an object with two properties: results and count:
{
    "results" : [
        {"id":2,"age":19,"name":"Shaggy"},
        {"id":3,"age":18,"name":"Daphne"},
        {"id":4,"age":20,"name":"Fred"}
    ],
    "count":4
}

That's the reponse returned by a table without any custom scripts (or when the script doesn't override the response) when it receives a request with the $inlinecount=allpages parameter. Now, if we change the read script to change something not in that format (for example, by returning only the items (and not the object with the total count property):
function read(query, user, request) {
    var result = [];
    result.push({ id: 1, name: 'Scooby Doo', age: 10 });
    result.push({ id: 1, name: 'Shaggy', age: 19 });
    request.respond(200, results);
}

Then the client won't be able to retrieve that value, simply because it's not present in the HTTP response.
Update after comment: If you want to go through the results and alter them before sending the response to the client, while still preserving the includeTotalCount functionality, you have two options: either change the results array directly, and call request.respond() (with no parameters) - which will send the (modified) result of the read operation; or if you want to do some more extensive changes in the results you can get the totalCount property from the results array (yes, a number property will be tacked to the array; this is JavaScript, after all, where all goes) if the $inlinecount=allpages parameter was sent in the query string of the request. With that value you can format the response appropriately, as shown below.
function read(query, user, request) {
    request.execute({
        success: function(results) {
            results.forEach(function(result, index) {
                result.newValue = index;
            });

            //request.respond(); - this should work.

            var totalCount = results.totalCount;
            if (totalCount) {
                request.respond(200, { count: totalCount, results: results });
            } else {
                request.respond(200, results);
            }
        }
    });
}


text:
Q: ClaimsIdentity NullReferenceException after installing .NET 4.5 I have an existing .Net 4 solution developed in vs2010, which uses an IIdentity implementation that is used to define the user of the current request. I now want to use vs2012 to continue it's development.
I have opened the solution in vs2012 and set the target framework in properties to be .Net 4. However when I run the solution, I get an exception when the web server is deserializing the GenericIdentity object. The exception occurs in
at System.Security.Claims.ClaimsIdentity.<get_Claims>d__0.MoveNext()
at System.Security.Principal.GenericIdentity.OnDeserializedMethod
                                                  (StreamingContext context)

The cause of the exception seems to be that the property Claims is not initialized.
What I already know:

*

*.Net 4.5 updates .Net 4 on the target machine rather than doing a side-by-side install.

*GenericIdentity is now derived from the new class ClaimsIdentity in .Net 4.5

*Setting target framework to .Net 4 means that although the code is still running with .NET 4.0, the 4.5 implementation is used under the covers i.e. you can't see the hierarchy in the visual studio object browser but the debugger and reflector shows the derivation.

*The GenericIdentity.OnDeserializedMethod accesses the ClaimsIdentity Claims property without checking for null, causing the NullReferenceException
One solution  I came across involved making my custom Identity object inherit from System.MarshalByRefObject, but the problem is that custom Identity object is provided by a "Single Sign On" .dll that is used across all systems in our organisation. This means I have no access to it to change its inheritance heirachy.
Is there an alternative solution or workaraound for this problem?

A: This problem is only occurring when using the inbuilt Visual Studio server, and as we as a team use IIS locally to run our sites in development, we are just going to live with it as I've just spent too much time on it now.
The problem looks to be around object serialization and deserialization following an appDomain transition, but I don't have time to investigate further.
UPDATE: This problem does not occur with .NET 4.5.1

redpajama_set_name: RedPajamaStackExchange


text:
Q: Testing how learning rate affects backpropagation, Artificial neural network I have created an artificial neural network in Java that learns with a backpropagation algorithm, I have produced the following graph which shows how changing the learning rate affects the time it takes for the network to train.
It seems to show that the learning is very unstable considering it either trains correctly very quickly or gets stuck (the backpropagation will stop training at either 1 minute or a specific error threshold). I want to understand why the network is so unpredictable, is the momentum too high? do I need a adaptive learning rate? Is this a good example of how local minima affects training http://www.willamette.edu/~gorr/classes/cs449/momrate.html.
This is the graph I produced:
http://i.stack.imgur.com/ooXqP.png

A: If you are initializing random weights before new experiment - you are starting optimization every time from new random point (in weight space), and for NN it's very important, because from different points with gradient descent you will converge into different local optima, ofcourse with different number of iterations and different time needed to converge. You need to generate initialization weights only once and start every experiment with new learning rate from that state, not from new random state.


text:
Q: SQL Server Date Check based on input This problem has bugged me so many times and i have now decided to try and find the proper solution for it, instead of my long-winded/dirty/horrible way I always revert to (copying the sql statement)
The table has a date column with a default value of NULL
Now what i need to do is pass a value (-1,0,1) to an sql statement which determines what to pull back
-1 - should bring back all rows
0  - should bring back rows with a NULL date value
1  - should bring back rows with a valid date value

I have tried using CASE statements, but the logical operator would need to change depending on the value being passed to the query.
Lets just call the table Quotes and the column completed, so...
CREATE TABLE 'Quotes'
(
    completed DATETIME default(NULL)
)

Solution needs to be for SQL Server 2000, and i'm working in stored procedures not dynamic SQL. So it really needs to be all in one statement.

Thanks
Dan

A: Something like this in the WHERE clause
WHERE (@param = -1)
OR (@param = 0 AND completed IS NULL)
OR (@param = 1 AND completed IS NOT NULL)

A: Try this:
declare @param int
set @param=-1
declare @sql varchar(2000)
set @sql='select * from quotes '+
case @param when 0 then 'where completed is null'
            when 1 then 'where completed is not null'
            when -1 then ''
end
exec(@sql)

Raj


text:
Q: The topology of the Deck group of a covering map I have never been interested in this before, and I have become interested in to find some answers and my teaching on the fundamental group has led me in this direction. Neither, I don't know if it suits for MO. So, please down-vote or vote-to-close after you provided some references.
I think if $X$ is semi-locally simply connected, path connnected, and locally path connected then for the universal cover $p:\widetilde{X}\to X$, its group of Deck transformations, say $\mathrm{Deck}(p)$ acts properly discontinuously on $X$, hence it is equipped with the discrete topology. This then would imply that any covering over $X$ must have discrete group of Deck transformations. Indeed, this does not imply that it is finite, infinite or even countable. So, it could be $\mathbb{R}^\delta$ that is $\mathbb{R}$ equipped with the discrete topology. Is this conclusion correct?
So, if I wish to find a covering whose group of Deck transformations has a non-discrete topology then either $X$, the base space of my covering map, should not be semi-locally simply connected ( like the infinite earring) or $X$ should not be either path connected nor locally path connected. I wonder if there is a place that I can look for examples of such coverings where the topology of the Deck group is determined. I know that in Munkres's book there are some statements/exercises about this. But, anything more recent or some survey articles on this?

A: I reiterate from my comments that a covering map is a discrete-sort-of-thing by definition, no matter what space you're looking at. If you are interested in non-discrete deck transformations or situations where such things are useful, there is a large literature on generalizations of covering space theory (see my answer to this question). I don't know of a reference for the following claim but we can put together a short proof with some basic facts.
Claim: If $p:\widetilde{X}\to X$ is a covering map with $\widetilde{X}$ connected, then the subspace topology on $Deck(p)$ inherited from $Homeo(\widetilde{X})$ is discrete.
Proof. First, $Homeo(\widetilde{X})$ may not be a topological group, but it is a quasitopological group and is therefore homogeneous. So it suffices to show that the trivial subgroup $\{id\}$ is open in $Deck(p)$. Now, let's recall perhaps the strongest version of the uniqueness of lifts: If $Y$ is connected and $f,g:Y\to\widetilde{X}$ are maps such that $p\circ f=p\circ g$ and such that $f(y)=g(y)$ for at least one point $y\in Y$, then $f=g$. Applying this to our situation, we see that if $f,g\in Deck(p)$ agree on at least one point, then $f=g$.
Fix a point $\tilde{x}\in\widetilde{X}$ and let $U$ be an open neighborhood of $p(\tilde{x})$ that is evenly covered by $p$. Write $p^{-1}(U)=\coprod_{j\in J}V_{j}$ where $V_{j}$ is open and is mapped homeomorphically onto $U$ by $p$. We have $\tilde{x}\in V_{k}$ for some $k\in J$. Now $\mathcal{V}=\{f\in Deck(p)\mid f(\{\tilde{x}\})\subseteq V_{k}\}$ is an open neighborhood of $id$ in $Deck(p)$ (recall subbasic sets in the compact-open topology). If $f\in \mathcal{V}$, then $f(\{\tilde{x}\})\subseteq V_{k}\cap p^{-1}(p(\tilde{x}))=\{\tilde{x}\}$. Therefore, $f$ and $id$ agree at a point and must be equal. We conclude that $\{id\}=\mathcal{V}$ is open in $Deck(p)$. $\square$


text:
Q: Failed to expand to the maximum partition size There are two partitions currently allocated on my 100 GiB hard disk. However, only  ~85GB is formatted and I cannot expand /dev/disk0s2 to the maximum size with various attempts such as diskutil and gpt. The last ~20 GB free space does exist, but it cannot be partitioned. disk0 is a VMware vmdk resized from 85 GB to 107 GB with vmware-vdiskmanager.
What may cause this? And how should I achieve the goal?

A: Since resizing the partition that is currently mounted for the operating system is impossible and the filesystem (FS) may be corrupted. One of the solutions is to use a live CD, especially GParted Live ISO which has installed many tools related to disk management such as partition.
However, GParted can check the integrity of the FS, but it is not able to resize the partition to the maximum size. Hence, parted, a command-line tool, is used. (Thanks for @klanomath 's hints.)
Step 1:  Find out which partition has to be expanded.
$ sudo parted /dev/sd[x]
(parted) unit s print free  # unit: sectors

Step 2:  Expand the selected partition to the designated sector.
(parted) resizepart <partition> <end>s

Step 3: Shutdown the Live system.
Step 4: Restart the macOS VM, and repair the disk.
$ sudo diskutil repairDisk disk[y]


text:
Q: undefined reference to 'tridag_' I'm working on a computational project for a class at university and I've come across the following error message:
<undefined reference to 'tridag_'>

when trying to call the tridag subroutine to solve a tridiagonal linear set of equations. Isn't the tridag subroutine included in fortran's library? I'm using code blocks with the gnu fortran compiler. Here's the program:
double precision t0, tc, rc, dt, dx, al, time, alpha
double precision, allocatable :: tmp(:), tmpnew(:), aw(:), ap(:), ae(:), su(:), x(:)
open (1,file='input.txt'); open (2,file='output.txt')
read (1,*) ni, nt
read (1,*) t0, tc, dt, al, alpha
allocate (tmp(ni), tmpnew(ni), aw(ni), ap(ni), ae(ni), su(ni), x(ni))
dx = al/float(ni-1)
do i=1,ni
    x(i)=(i-1)*dx
end do
rc=alpha*dt/dx**2
!ΑΡΧΙΚΗ ΣΥΝΘΗΚΗ
tmp=t0
do it=1,nt
    time=(it-1)*dt
    ap(1)=1; ae(1)=-1; su(1)=0
    ap(ni)=1; aw(ni)=0; su(ni)=tc
    do i=2,ni-1
        ap(i)=-(1+2*rc); ae(i)=rc; aw(i)=rc; su(i)=-tmp(i)
    end do
    call tridag (aw, ap, ae, su, tmpnew, ni)
    do i=1,ni
        tmp(i)=tmpnew(i)
        write(2,*) x(i),tmp(i)
    end do
end do

Thanks in advance.

A: tridag() is not a Fortran intrinsic subroutine, it comes from an external library. You must get this library, compile the subroutine and link it with your code.
As far a I know TRIDAG comes from the Numerical Recipes book so be aware it is commercially licensed. If you get the book and the associated source code, you can use it according to the book's license. You can certainly also find the code on the internet (just use your favourite search engine to search for "TRIDAG Fortran subroutine"), but the license still applies.
Also note that there are many other tridiagonal matrix solvers available, but this site is not for locating or recommending external software libraries.


text:
Q: dependencies reference nonexistent parent node error in Django So, I am learning Django using Django By Example book.
I moved to a new chapter where I needed to make a new project and app. This is what I did.
django-admin startproject myshop

cd to myshop directory
django-admin startapp shop
python manage.py migrate

I am unable to migrate with the following error:

django.db.migrations.exceptions.NodeNotFoundError: Migration django.db.migrations.exceptions.NodeNotFoundError: Migration auth.0009_user_following dependencies reference nonexistent parent node (u'account', u'0002_contact')

I did make Contact model in account app in my last project.
How is the new project related to the old one?
Please help me resolve this problem. Thanks.

A: It means that you don't have the file 0002_contact in your account app's migration folder. You need to recover the file or configure this file  0009_user_following and remove the  (u'account', u'0002_contact') line


text:
Q: Rabbitmq server not picking value from rabbitmq.conf file I am using the latest version of RabbitMQ for clustering. I was setting some custom values and parameters on nodes via rabbitmq.conf file by placing it inside the /etc/rabbitmq directory and then restarting rabbitmq-server, but when I verify it through rabbitmqctl environment it still shows the default values
Current rabbitmq.conf content:
vm_memory_high_watermark.relative = 0.7
disk_free_limit.relative = 1.0
cluster_partition_handling = autoheal
loopback_users = none

Currently cluster is a three node cluster on bare ec2 machines

A: I found it's answer myself. Actually the start_err log helped, if the current directory has old format config file present, it will not activate the values passed in new format .conf configuration file. On rebooting the services it doesn't throw any error.
Sanity while upgrade, a good habit to keep!


text:
Q: CLLocationManager authorization callbacks (when no auth-change) My app needs always-authorization.
Apple states that if an app already has "WhenInUse" authorization, it may ask exactly once for "Always".
So the following workflow pops up:

*

*Ask for "WhenInUse"

*Ask for "Always"

Issues here:
(on 1):
If the user selects 'allow once', I get "WhenInUse" internally. The app won't get told 'allowed only once'. Step 2 fails silently - without any callback or error.
(on 2):
If the user selects "Keep when in use only", no callback is invoked at all.
Does anyone know a workaround for this behavior?
(i.e. like monitoring modally presented view controllers)
Thanks in advance!

A: Since the app becomes inactive whenever a system prompt is displayed, instead of waiting for the callbacks, you can store the authorization status on UserDefaults or any other persistent storage, and whenever the app becomes active check the status again and see if it was changed.


text:
Q: Running C Code from Github in Visual Studio I wanted to play around with the Live Motion code I found on github at this link.
I am fairly new but I thought that all I need to do is clone and download the link. I opened it in VS code (I ran the hello world code in c++ so I assume I have configured it properly). I basically cloned the repository and all files and folders appeared as follows:

However, I am confused as to how I can run the entire project. Previously I would just click on the project name, build, and it would create the exe file. That doesn't seem to exist for cloning the repo.
I need some basic guidance to how I simply run the entire project from github.
I did install QT Creator 5.9.9 and it also shows up in my Visual Studio.
But I am still unsure about how to run the software and if anyone was able to get it to work?
Thanks


text:
Q: Need suggestion for accessing remote machine in asp.net I want to access some places on a remote machine.The folder i want to access have full control to EVERYONE.  The code given below is used to access  network path.
 System.IO.DirectoryInfo locationInfo = new System.IO.DirectoryInfo(BackupLocationTxt.Text);
        if (locationInfo.Exists)
        {
            // do some operations
         }

The application run fine if both the host computer and the remote computer to be accessed  having os windows xp .The application also run fine if the application is running inside visual studio  .
Then my problems is ,any one of the machine( server and remote machine)having an os newer  then windows xp( like windows 7, server 2008) locationInfo.Exists always false.
But if the application is running inside in visual studio, then it work fine independent of os
I searched a lot in net. But didnt find an exact solution yet. Someone suggests impersonation. But i dont know exactly how to do it. Is impersonations is the solution for my problem ?? Or is there any better ideas??
Any help will be greatly appreciated

A: You have an interesting problem, Null. How have you configured your sites Directory Security? If's Anonymous access is enabled, the folder open to Everyone may not be allowing access depending on the OS of the server (see this Microsoft KB Article for more information).
If the site is running as Anonymous, you could change the account that the site runs as in the IIS Manager, or you could enable Impersonation. When you are running the site in Visual Studio the site is running with your permissions, so Anonymous isn't a problem then.
You can use the following code to output the identity of the user that your site is running as to help figure out what is going on. You may be able to give the user your site run as access to the network location without any impersonation. Add a ASP:Label to you page and see who you are running as:
lblSomeLabel.Text = System.Security.Principal.WindowsIdentity.GetCurrent().Name

Impersonation could open you up to additional security risks, so you should do some more reading before making that change - but, the user you use for impersonation doesn't need to be a domain admin. In your case, the user may just need to have full access privileges to the network location.
You can read more about how to enable impersonation on this Microsoft KB Article. Below is some of the code from that page that I'd recommend. Rather than have your whole site run in impersonation mode, the code below runs only the part that you are having a problem with.
public void Page_Load(Object s, EventArgs e)
{
    if(impersonateValidUser("username", "domain", "password"))
    {
        //Insert your code that runs under the security context of a specific user here.
        undoImpersonation();
    }
    else
    {
        //Your impersonation failed. Therefore, include a fail-safe mechanism here.
    }
}

private bool impersonateValidUser(String userName, String domain, String password)
{
    WindowsIdentity tempWindowsIdentity;
    IntPtr token = IntPtr.Zero;
    IntPtr tokenDuplicate = IntPtr.Zero;

    if(RevertToSelf())
    {
        if(LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
            LOGON32_PROVIDER_DEFAULT, ref token) != 0)
        {
            if(DuplicateToken(token, 2, ref tokenDuplicate) != 0)
            {
                tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                impersonationContext = tempWindowsIdentity.Impersonate();
                if (impersonationContext != null)
                {
                    CloseHandle(token);
                    CloseHandle(tokenDuplicate);
                    return true;
                }
            }
        }
    }
    if(token!= IntPtr.Zero)
        CloseHandle(token);
    if(tokenDuplicate!=IntPtr.Zero)
        CloseHandle(tokenDuplicate);
    return false;
}

private void undoImpersonation()
{
    impersonationContext.Undo();
}

Also, while serching for security articles I found this StackOverflow question that is worth a read.

A: Try System.IO.Directory.Exists instead.
Bear in mind that if you do not have at a minimum read-only permission to the directory, the Exists method will return false


text:
Q: understanding openweather api response I'm having trouble interpreting the response from the openweather api. I don't have a clear understanding of the values being returned in the call below.
*the appid is the sample from openweather, not my own
http://samples.openweathermap.org/data/2.5/forecast/daily?zip=91001&appid=b6907d289e10d714a6e88b30761fae22
Particularly dt, but also the day, and min.
{
  dt: 1519070400,
  temp: {
   day: 283.99,
   min: 271.86,
   etc...
}

These are the definitions of these values from the API
dt - Time of data forecasted temp.day - Day temperature. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.
My questions are...
1) I think the dt unit is some kind of utc number, but when I try to do conversions on it using UTC converters, it returns invalid. I can't find more info in the docs on what this is aside from the definition. What is this unit and do you have tips on how to convert it?
2) temp.day - reading the definition I assume it is the temperature today returned in Kelvin, but when I convert it to Fahrenheit, the temperature is off by a significant margin. For this example the zip code is Pasadena, California where the current temperature is 70 degrees F, but when I convert the returned result of 283.99 Kelvin to Fahrenheit the result is 51 degrees. Do you know what this may be?
Any help is appreciated as I try to get better at understanding these types of api responses

A: *

*To convert a UNIX Timestamp to a JavaScript Date object take it times 1000 in the constructor.
var date = new Date(unix_timestamp * 1000);

*Not knowing what conversion you used it's difficult to debug. If you want to leave the response as Kelvin. be sure to use the following conversion.
var fahrenheitTemp = (kelvinTemp − 273.15) × 9/5 + 32;
Otherwise you can just pass the units query like so.
http://api.openweathermap.org/data/2.5/forecast/daily?zip=91001&appid=xxxxxx&units=imperal

A: I apologize for the delayed. Anyways, i hope that this will be helpful!
1) Please use this converter: https://chrome.google.com/webstore/detail/utime/kpcibgnngaaabebmcabmkocdokepdaki
In it's settings choose the GMT  (Weastern Europe Time, London.....) So the converting will be made according UTC 0000 timezone.
Converts UNIX timestamps to human-readable dates and vice versa.
This is just a timestamp.
2) You use sample file, so it is not connected to the real API service! The real url of API is the following:
http://api.openweathermap.org/data/2.5/forecast/daily?zip=91001&appid=xxxxxx
The url is for 16 daily API which is not available for Free account, so you may not able to access data if you still use Free plan.
The temperature is provided in Kelvins. There is possibility to change units (units=metrics - for C / units=imperal - for F ).


text:
Q: Cannot create an instance of an abstract class (Kotlin) Trying to use LiveData but this error apears.
class GameViewModel : ViewModel() {
private val _score = MutableLiveData<Int>()
val score: LiveData<Int> = _score
private val _word = MutableLiveData<String>()
val word = LiveData<String> = _word


text:
Q: Node+NPM on Laradock I followed everything on the documentation on how to enable NPM on the workspace. However, when I run docker-compose exec workspace bash then check node -v it is missing. The document didn't say too how to use it.

A: Restart docker-compose by using the following commands:
docker-compose stop
docker-compose restart
Once workspace is up, exec workspace and verify node -v again.


text:
Q: Strange blue screen issue after Dell BIOS update After Dell Windows 10 A25 BIOS update, my computer will start and shutdown with no problem but if I use "restart" function, I get blue screen error "inaccessible boot device". I reinstalled BIOS again thinking it might be corrupt, but same problem. ON/OFF = NO PROBLEM, RESTART = PROBLEM. I know eventually I will have to restart the machine so I need to see if I can figure out what the problem is. Thanks!

A: Thanks for your time and effort to help me. After analyzing the issue over and over, I suddenly remembered that when I downloaded the BIOS from Dell that a couple of Intel items were downloaded also. So I deleted Intel Management & Security and Intel Rapid Storage Technology and that cleared up the blue screen issue. Have a great day.


text:
Q: FunctionalTests for App Engine with the generated Cloud Endpoint Library I have created an App Engine service that exposes a REST api. I created that with the Cloud Endpoint framework. One thing that this framework gives me is a java library that I for example can use in my Android app. That works fine.
What I want to do now is to add some testing of the endpoint. I would like to use the generated library to make calls to a running server. The Gradle App Engine plugin already support this by a build step called FunctionalTests. The only problem I have is that I have no idea how to access the generated library classes from my test. Anybody has done something like this?


text:
Q: What is an anonymous inner class? When I tried to do some sample on an abstract class in Java I accidentally got some thing like anonymous inner class in Eclipse.
I have pasted the piece of code below. I don't understand how the abstract class is related to anonymous class.
package com.Demo;

abstract class OuterClass {
    abstract void OuterClassMethod();
}

public abstract class InnerClass extends OuterClass {
    public static void main(String[] args) {
        InnerClass myInnerClass = new InnerClass() {
            @Override
            void OuterClassMethod() {
                int OuterClassVariable = 10;
                System.out.println("OuterClassVariable" + " " + OuterClassVariable);
            }
        };
    }
}

A: A anonymous class is an "in-line" concrete implementation of a class, typically (but not necessarily) of an abstract class or an interface. It is technically a subclass of the extended/implemented super class.
Google for more.

A: In your example, your class (InnerClass) extends class (OuterClass) and implementing their abstract methods which is the typical behavior of extending an abstract class. In the same way if your class implementing any interfaces you have to override their abstract methods. This is the way to implement Anonymous inner class.

A: Basically, an anonymous class is an implementation that has no name -- hence the "anonymous" bit.
This particular bit is what makes your class anonymous:
    InnerClass myInnerClass = new InnerClass() {
        @Override
        void OuterClassMethod() {
            int OuterClassVariable = 10;
            System.out.println("OuterClassVariable" + " " + OuterClassVariable);
        }
    };

In normal class instantiations, you would just use:
InnerClass myInnerClass = new InnerClass();

but in this case, you are specifying a new implementation of that class, by overriding a function (OuterClassMethod()) within it. In other instances of InnerClass, OuterClassMethod() will still have its original implementation, because you only adapted this particular instance of InnerClass, and did not store this new implementation in a new class.
If you don't want anonymous classes, do this instead:
Somewhere, specify AnotherInnerClass to extend InnerClass, and to override that function:
class AnotherInnerClass extends InnerClass {
    @Override
    void OuterClassMethod() {
        int OuterClassVariable = 10;
        System.out.println("OuterClassVariable" + " " + OuterClassVariable);
    }
};

And then instantiate it as such:
AnotherInnerClass myInnerClass = new AnotherInnerClass();


text:
Q: Is the time complexity different for storing attributes of nodes in an array vs. creating instances of a class to store it? I am building a binary search tree from an input array of integers. But I also want to store the size of the left subtree for each node as I am building the BST.
There were two ways that I thought of storing this number, either in an array (of the same size as the input array), or as an instance of the BST initialisation.
From a space complexity stand point, is there any difference? I would think that the space complexity of the array method would be O(n), but if we stored the size for every node as an instance of a class, I would think this results in O(1) space?- just for storing the size of the left subtree. Because I know that constructing the BST would be O(n) anyway for space, since the BST would be the same size of the input array?
For example:
class BST:
    def __init__(self,value):
        self.right = None
        self.left = None
        self.value = value
        self.sizeOfLeftSubtree = 0
        self.parentPointer = None

A: There is no difference in terms of space complexity. In either case you are allocating memory for n integers. Either as an array of n integers, or as one more integer in each of the n nodes.
Some remarks:

*

*If you choose to store it as an array, then you have to deal with two data structures: the tree and the array. And when in a certain algorithm you have a current node, you'll have to know which index in that array corresponds to it. This is not the OOP way to do it. In OOP one makes sure that all data that relates to a specific entity, is stored together with that entity as an object.

*"as an instance of the BST initialisation" mixes two concepts: an instance of the BST class is an object. Initialisation is (in this context) the process of assigning values to an object's attributes. Your code indicates that an instance gets an additional attribute during its initialisation. It is a matter of using the right terminology.


text:
Q: Creating a Image from javafx2 2d Color list using bufferImage I am trying to convert my 2d list of Colors to an actual image and then export it, however, when I try to use it, it distorts the colors (shows the wrong ones)
import javafx.scene.paint.Color;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.imageio.ImageIO;

public class ImageAction {
    public static void fromColorGrid(List<List<Color>> colorGrid) {
        int width = colorGrid.size();
        int height = colorGrid.get(0).size();

        BufferedImage buffImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // Set each pixel of the BufferedImage to the color from the Color[][].
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                String colorStr = colorGrid.get(x).get(y).toString().replace("0x", "");
                int rgb = Integer.parseInt(colorStr, 16);
                System.out.println(colorStr + "   " + rgb);
                buffImage.setRGB(x, y, rgb);
            }
        }
        try {
            File outputfile = new File("saved.png");
            ImageIO.write(buffImage, "png", outputfile);
        } catch (IOException e) {
            System.out.println("Ups");
        }
    }
}

Where am I going wrong?

A: This bit seems odd to me:
String colorStr = colorGrid.get(x).get(y).toString().replace("0x", "");
int rgb = Integer.parseInt(colorStr, 16);
System.out.println(colorStr + "   " + rgb);
buffImage.setRGB(x, y, rgb);

That code relies on toString() method of JavaFX's color class, which explicitly states:

This method is intended to be used only for informational purposes. The content and format of the returned string might vary between implementations.

Instead, just convert directly to an AWT color using the RGB values:
Color fxColor = colorGrid.get(x).get(y);
java.awt.Color awtColor = new java.awt.Color((float) fxColor.getRed(),
        (float) fxColor.getGreen(),
        (float) fxColor.getBlue(),
        (float) fxColor.getOpacity());
buffImage.setRGB(x, y, awtColor.getRGB());

The above doesn't rely on any particular toString() implementation, and in my quick tests the code seems to work fine with it in place.


text:
Q: Codeigniter - If query returns something, do something I have a function in my model that is supposed to check my database to see if a particular username already exists. If so, it should call itself again with an incremented value of $appendDigit (which is then added to the end of the $string and checked again). Otherwise it should just return the original $string as the $username.

Controller
$string = strtolower($value['first_name']) . '_' . strtolower($value['last_name']);
$username = $this->ums_model->checkIfLoginExists($string, 1);

Model
public function checkIfLoginExists($string, $appendDigit)
{
    // When first called, appendDigit will be equal to 1.
    // If the username already exists the method will call itself,
    // incrementing the appendDigit until it finds an unused username

    if ($appendDigit != 1) {
        $username = $string . $appendDigit;
    }
    else {
        $username = $string;
    }

    $this->db   ->select('username')
                ->from('users')
                ->where('username', $username);

    $result = $this->db->get()->row_array();

    if (!empty($result)) {

        $appendDigit++;
        $this->checkIfLoginExists($string, $appendDigit);

    }

    return $username;

}

This works fine for unique usernames but not if the username already exists (I get a duplicate entry database error). So I presume the if (!empty... ) statement is not working properly. I've tried all sorts of variations with result_array(), row(), result()... but nothing seems to work.
I thought I might need to put the return into an else block but when I do that it always returns NULL no matter what.
What am I missing here?

Update: When I do a var_dump($result) this returns
array(1) { ["username"]=> string(11) "original_string" }

So it looks like my query is fine too.

A: I fixed the issue by returning $appendDigit to the controller instead of the $username. I could then add an if/else to the controller:
$appendDigit = $this->ums_model->checkIfLoginExists($string, 1);

if ($appendDigit == 1) {
    $username = $intranet;
}
else {
    $username = $intranet . $appendDigit;
}


text:
Q: How to update and save model's field in Django Following is my code, Every time I click Like (or Dislike) link, both Dislike and Like are incremented.
I am new to django, your help will be much appreciated. Thank you
Here is my models.py,
from django.db import models
from django.urls import reverse
# Create your models here.
class Movies(models.Model):
   Director=models.CharField(max_length=30)
   Cast_I=models.CharField(max_length=30)
   Cast_II=models.CharField(max_length=30)
   Name=models.TextField()
   ReleaseYear=models.IntegerField()
   ImdbRating=models.CharField(max_length=2)
   Genre=models.TextField(null=True)
   Language=models.CharField(max_length=20,null=True)
   Like=models.IntegerField()
   Dislike=models.IntegerField()
   def like_this_movie(self):
       self.Like+=1
       self.save()
       return reverse ('list',kwargs={})
   def dislike_this_movie(self):
       self.Dislike+=1
       self.save()
       return reverse ('list',kwargs={})

Here is the template,
{% block content %}

Like
Dislike

{% endblock %}

Here is my view class,
class MovieDetailView(DetailView):
    template_name='movie/detail.html'
    queryset=Movies.objects.all()

A: The templates in Django don't work like that, everything you put inside {{ }} is rendered on the server and then the page is sent to the client, so it is not possible to run a function like that.
You would have to do something like an AJAX request to another page which runs like_this_movie and takes the Movies id as a parameter. To send to AJAX request you can use Javascript with jQuery.

A: The problem is that each time you load the page both values are incremented because you call both functions in each call. This link will help you on how do it => How to make user to Like/Dislike post only for once in Django?

A: I have resolved my bug by adding those like_this_movie and dislike_this_movie function to my views.py and updating my urls.py and template. Thank you guys for your valuable answer.
views.py,
def like_this_movie(request,key):
    obj=Movies.objects.get(pk=key)
    obj.Like+=1
    obj.save()
    return redirect('/movie/list')
def dislike_this_movie(request,key):
    obj=Movies.objects.get(pk=key)
    obj.Dislike+=1
    obj.save()
    return redirect('/movie/list')

urls.py,
urlpatterns=[
    path('list/<int:key>/like',like_this_movie,name='like'),
    path('list/<int:key>/dislike',dislike_this_movie,name='dislike')
]

template,
Like
Dislike

A: Now I have resolved this by using jQquery AJAX, like_this_movie and dislike_this_movie function returns json value to ajax request. Now page doesn't reload every time I hit like or dislike button. Thank you guys for your valuable answer.
views.py,
def like_this_movie(request,key):
    obj=Movies.objects.get(pk=key)
    obj.Like+=1
    obj.save()
    return JsonResponse({'success':True,'content':'Like','Like':obj.Like})
def dislike_this_movie(request,key):
    obj=Movies.objects.get(pk=key)
    obj.Dislike+=1
    obj.save()
    return JsonResponse({'success':True,'content':'Dislike','Dislike':obj.Dislike})

urls.py,
urlpatterns=[
    path('<int:key>/like',like_this_movie,name='like'),
    path('<int:key>/dislike',dislike_this_movie,name='dislike')
]

detail.js
  document.addEventListener('DOMContentLoaded',()=>{
    document.querySelector('#likebtn').onclick=()=>{
      const request=new XMLHttpRequest;
      request.open('GET','like',true);
      console.log(request);
      request.onload=()=>{
        const data = JSON.parse(request.responseText);
        if ((data.success)&&(data.content=='Like')){
          totalLike=data.Like;
          likespan=document.querySelector('#likespan');
          likespan.innerHTML=totalLike;
          likebtn=document.querySelector('#likebtn');
          likebtn.disabled = true;
          dislikebtn.disabled=true;
        }
      }
      request.send();
      return false;
    }
    document.querySelector('#dislikebtn').onclick=()=>{
      const request=new XMLHttpRequest;
      request.open('GET','dislike',true);
      request.onload=()=>{
        const data = JSON.parse(request.responseText);
        if ((data.success)&&(data.content=='Dislike')){
          totalDislike=data.Dislike;
          dislikespan=document.querySelector('#dislikespan');
          dislikespan.innerHTML=totalDislike;
          dislikebtn=document.querySelector('#dislikebtn');
          dislikebtn.disabled = true;
          likebtn.disabled=true;
        }
      }
      request.send();
      return false;
    }
  })

detail.html,

        {{object.Like}}
        <button id="likebtn" type="submit" class="btn btn-primary">Like</button>
        {{object.Dislike}}
        <button id="dislikebtn" type="submit" class="btn btn-primary">Dislike</button>


text:
Q: If we suppose, that a perfect odd number exists, can we determine whether infinite many exist? It is currently not known whether odd perfect numbers (numbers with the property $\sigma(n)=2n$, where $\sigma(n)$ is the sum of divisors of $n$, including $1$ and $n$) exist.
But suppose, a perfect odd number exists.

Do we then know whether there are infinite many perfect odd numbers ?

This could be possible because various necessary conditions are known for an odd number to be perfect. Perhaps they allow to construct arbitary many perfect odd numbers, supposing that an odd perfect number exists.

A: This is not a direct answer to your question, but it is certainly related.
We do know that
$$I(q^k) < \frac{5}{4} < \frac{3}{2} \leq I(2^{p-1})$$
where $N=q^k n^2$ is an odd perfect number in Eulerian form and $M=(2^p - 1){2^{p-1}}$ is an even perfect number in Euclidean form.
Because of a property satisfied by the abundancy index $I(x)=\sigma(x)/x$ at prime powers, it follows that
$$2^{p-1} < q^k.$$
(NOTE THAT THE REASONING IS UNSOUND IN THE LAST PARAGRAPH, AS IT ONLY FOLLOWS FROM $I(q^k) < I(2^{p-1})$ THAT $2 < q$.  WHAT FOLLOWS IS THEREFORE INCONCLUSIVE, AT THIS POINT.)
It follows that, since $q^k < n^2$ [Dris, 2012], if $N$ is bounded, then $M$ is also bounded.
Thus, if there exists an odd perfect number, we would infer that there are only finitely many even perfect numbers.

A: This answer attempts to prove your conjecture that if there is an odd perfect number, then there are infinitely many of them.
Briefly, the argument makes use of the following lemma:

Lemma If $q^k n^2$ is an odd perfect number with special/Euler prime $q$, then the biconditional
  $$\frac{q^2}{n}+\frac{n}{q^2} \text{ is bounded from above } \iff \frac{\sigma(q^2)}{n}+\frac{\sigma(n)}{q^2} \text{ is bounded from above}$$
  holds.

Details are in the following question:
If $q^k n^2$ is an odd perfect number with Euler prime $q$, which of the following relationships between $q^2$ and $n$ hold?


text:
Q: Apache Camel Validate with DTD I am working on a POC with Apache Camel, I have to expose a WS through CXF, make some validation and transformation and call another WS.
I tried to use the validator but it seems that it's only work with xml schema...
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route>
    <from uri="cxf:bean:sdmoWSKweb" />
    <to uri="log:input"/>
    <bean ref="CartWSExtractProcessor"/>
    <doTry>
        <to uri="validator:/dtd/configurator.dtd"/>
        <to uri="mock:valid"/>
        <doCatch>
            <exception>org.apache.camel.ValidationException</exception>
            <to uri="mock:invalid"/>
        </doCatch>
        <doFinally>
            <to uri="mock:finally"/>
        </doFinally>
    </doTry>
    <to uri="xslt:messageCopyItem.xslt"/>
    <setHeader headerName="operationName"><constant>copyItemMaster</constant></setHeader>
    <to uri="cxf:bean:qadCopyWeb?defaultOperationName=copyItemMaster"/>
    <to uri="log:Output"/>
</route>

I tried to generate and xsd version of my dtd with the W3.org tool but the result is not valid.
Is there any solution ?

A: Camel Validator does only work with XML/XSD or RelaxNG with the Jing component.
Otherwise, you should trying another DTD->XSD conversion tool or just manually create an XSD version...


text:
Q: Add a where-object on a table construct? Renaming the headers with 'label' and I'd like to filter on that last one 'SpaceLeft'. It doesn't work correctly though. For example:
Get-WmiObject win32_logicaldisk -ComputerName sfuslt167 -Filter "drivetype=3" |
  Format-Table -Property deviceID,
    @{label='freespace(GB)';expression={$_.freespace / 1GB -as [int]}},
    @{label='Size(GB)';expression={$_.size / 1GB -as [int]}},
    @{label='SpaceLeft';expression={$_.freespace / $_.size * 100}} |
      Where-Object {$_.SpaceLeft -lt 10}

Results:
deviceID freespace(GB) Size(GB)        SpaceLeft
-------- ------------- --------        ---------
C:                 130      237 54.8893461475826

This should come back with nothing as the value in 'SpaceLeft' is greater than 10 being specified in the WHERE statement, yet it comes back with results. Why is this??

A: Lee Dailey has provided the crucial pointer in a comment:

*

*To transform data for further programmatic processing, use Select-Object or other data-transformation methods, such as via ForEach-Object.

*Only ever use the Format-* cmdlets to format data for display, as their name suggests.

*

*PowerShell's great evolutionary leap was to send objects rather than text through the pipeline, and while Format-* cmdlets such as Format-Table emit objects as well, these objects no longer represent data, but formatting instructions for PowerShell's output-formatting system - they serve no other purpose.

Therefore, simply replacing Format-Table with Select-Object solves your problem:
Get-WmiObject win32_logicaldisk -ComputerName sfuslt167 -Filter "drivetype=3" |
  Select-Object -Property deviceID,
    @{label='freespace(GB)';expression={$_.freespace / 1GB -as [int]}},
    @{label='Size(GB)';expression={$_.size / 1GB -as [int]}},
    @{label='SpaceLeft';expression={$_.freespace / $_.size * 100}} |
      Where-Object {$_.SpaceLeft -lt 10}

What the two cmdlets do have in common, however, is the ability to accept hashtable-based calculated properties (@{ label = '...'; expression = { ... } }), as in your question.

As for what actually happened in your attempt:
Here's a simplified example, using Format-Table:
PS> [pscustomobject] @{ freespace = 100; size = 1000 } |
      Format-Table @{label='SpaceLeft'; expression={$_.freespace / $_.size * 100}}

SpaceLeft
---------
       10

This looks just fine - and indeed that's the purpose - producing a nice display representation.
In fact, substituting Select-Object for Format-Table results in the same display:
PS> [pscustomobject] @{ freespace = 100; size = 1000 } |
      Select-Object @{ label='SpaceLeft'; expression={$_.freespace / $_.size * 100} }

SpaceLeft
---------
       10

The reason is that when command output goes to the display, PowerShell implicitly, behind the scenes calls an appropriate Format-* cmdlet, which in this case is Format-Table.
In other words, the command above is equivalent to the following command:
PS> [pscustomobject] @{ freespace = 100; size = 1000 } |
      Select-Object @{label='SpaceLeft'; expression={$_.freespace / $_.size * 100}} |
        Format-Table

SpaceLeft
---------
       10

For the logic behind which Format-* cmdlet is chosen when, see this answer.
However, instead of the (implicitly) applied Format-Table, you could have chosen a different formatting cmdlet, such as Format-List for list-style display that shows each property on its own line:
PS> [pscustomobject] @{ freespace = 100; size = 1000 } |
      Select-Object @{label='SpaceLeft'; expression={$_.freespace / $_.size * 100}} |
        Format-List

SpaceLeft : 10

However, when it comes to further processing, Select-Object and Format-Table are not created equal - only Select-Object is suitable:
Let's look at what properties the output object(s) possess, using Get-Member -Type Properties, first with Select-Object:
PS> ([pscustomobject] @{ freespace = 100; size = 1000 } |
      Select-Object @{label='SpaceLeft'; expression={$_.freespace / $_.size * 100}} |
        Get-Member -Type Properties).Name
SpaceLeft

As expected, the output has one property, named SpaceLeft, and that's what your Where-Object call can operate on.
Using Format-Table instead of Select-Object tells a different story:
PS> ([pscustomobject] @{ freespace = 100; size = 1000 } |
      Format-Table @{label='SpaceLeft'; expression={$_.freespace / $_.size * 100}} |
        Get-Member -Type Properties).Name
autosizeInfo
ClassId2e4f51ef21dd47e99d3c952918aff9cd
groupingEntry
pageFooterEntry
pageHeaderEntry
shapeInfo
ClassId2e4f51ef21dd47e99d3c952918aff9cd
groupingEntry
shapeInfo
ClassId2e4f51ef21dd47e99d3c952918aff9cd
formatEntryInfo
outOfBand
writeStream
ClassId2e4f51ef21dd47e99d3c952918aff9cd
groupingEntry
ClassId2e4f51ef21dd47e99d3c952918aff9cd
groupingEntry

It doesn't really matter what these in part obscurely named properties specifically represent - all that matters is:

*

*Their sole purpose is to be interpreted by PowerShell's output-formatting system.

*The selected / calculated properties passed to Format-Table are not present as such in the output.

*

*That's why your Where-Object call didn't work as intended: $_.SpaceLeft referenced a non-existing property, so the expression evaluates to $null, and $null -lt 10 is always $true.

Irrespective of their input, Format-* cmdlets output instances of  Microsoft.PowerShell.Commands.Internal.Format.* types that represent formatting instructions.


text:
Q: Corelation between 2 level categorical variables and a continuous variable I have a dataset where I need to find the relation between the smoking habits  of a person (Yes/No) with the probability risk of a person getting a heart disease.
Please suggest how can I find the correlation between 2 level categorical feature( smoking) to continuous variable(Risk) in Python. Can Pearson correlation coefficient be used ?

A: You could perform logistic regression:
https://en.wikipedia.org/wiki/Logistic_regression
The absolute value of the correlation coefficient will roughly tell you how useful your continuous variable is for predicting the yes/no variable. If the slope is zero, is has no predictive power.


text:
Q: Fourier inverse transform of a piecewise function Given that
$$
\int_0^\infty xY(x)\sin(xt)dx = F(t) = \begin{cases}
      1 & 0<t\leq 1 \\
      2 & 1<t\leq 2
   \end{cases}
$$
The goal is to find $Y(0)$.
I'm trying to apply the inverse Fourier sine transformation:
$$
F(x) = xY(x)= \frac{2}{\pi}\int_0^1\sin(tx)dt+\frac{2}{\pi}\int_1^2 2\sin(tx)dt\\
= \frac{2\cos(x)-4\cos(2x)+2}{\pi x}
$$
Then we can find $Y(x)$. However, it seems like $Y(0)$ is undefined. Am I on the right track to solve this problem? Thanks for the help!

A: In the integral $\int_0^\infty xY(x)\sin(xt)dx,$ changing $Y(0)$'s value won't affect the integral. So you need to use continuity to define $Y$'s value at zero. (I mean that, if you don't assume continuity, you can never get $Y(0)$ as it can be any value.)
You've proved that $Y(x)=\frac{2\cos(x)-4\cos(2x)+2}{\pi x^2},$ so
$$
Y(0)=\lim_{x\rightarrow 0+}\frac{2}{\pi}\frac{\cos(x)+1-2\cos(2x)}{x^2}=\frac{2}{\pi}\frac{-1+8}{2}=\frac{7}{\pi}.
$$


text:
Q: swt DateTime setDate() error I have a DateTime spinner defined like this:
 //Class Global
 DateTime dateMin = null;

 //added to the UI
 DateTime dateMin = new DateTime(grpPlaybackSearchOptions, SWT.BORDER);
 dateMin.setBounds(335, 44, 123, 23);

later on in my code I'd like the user to be able to load a date that may have been saved off. Digging through the swt DateTime docs I'm not seeing how I can update the date.
I've tried this but received an exception error:

//running from a method
      dateMin.setDate(pMinDate[0], pMinDate[1], pMinDate[2]);

Can the object be not be updated or am I trying to update the object incorrectly?
Thanks!

A: Not sure what you are struggling with, the documentation is very clear and provides the methods:
setDate(int year, int month, int day)
setHours(int hours)
setMinutes(int minutes)
setSeconds(int seconds)

Here is a simple example:
public static void main(String[] args)
{
    final Display display = new Display();

    Shell shell = new Shell(display);
    shell.setText("StackOverflow");
    shell.setLayout(new GridLayout(1, false));

    final DateTime date = new DateTime(shell, SWT.DATE);
    final DateTime time = new DateTime(shell, SWT.TIME);

    Button button = new Button(shell, SWT.PUSH);
    button.setText("Change date");
    button.addListener(SWT.Selection, new Listener()
    {
        @Override
        public void handleEvent(Event arg0)
        {
            date.setDate(1999, 0, 1);
            time.setHours(0);
            time.setMinutes(0);
            time.setSeconds(0);
        }
    });

    shell.pack();
    shell.open();
    while (!shell.isDisposed())
    {
        if (!display.readAndDispatch())
            display.sleep();
    }
}

It will set the datetime to: 01/01/1999 00:00:00 (using dd/MM/yyyy HH:mm:ss that is...)


text:
Q: Rails 4 - Yaml configuration file I have this file config/application.yml
settings:
  info:
    name: MyAppName
    domain: example.com
  contact:
    email: mail@example.com
    phone: 1234567890

And in the environment.rb i have this
AppConfig = YAML::load_file('config/application.yml')

So now i can access this by using AppConfig["settings"]["info"]["name"]
How can i access this by using AppConfig.settings.info.name ?

A: If you are using Rails 4.2 or higher, you can use config_for for the config files. They need to be placed under /config folder. (haven't tried otherwise)
In your case it would be: config = Rails.application.config_for(:application)
This is more clear and Rails way to load configs into application.
Then you can use OpenStruct to have dot notation enabled for it.
APP_CONFIG = OpenStruct.new(config)

A: Here's an easy way to do this without any gems, though I'm not sure about the performance if you are doing this frequently.
The idea is to first convert the data to JSON, and then parse the JSON to OpenStruct (which is built into Ruby):
json_data = YAML::load_file('config/application.yml').to_json
data = JSON.parse(json_data, object_class: OpenStruct)

This will deeply convert all hashes to OpenStructs and also correctly handles arrays.
As an example, if I have this YAML:
people:
  -
    name: 'Jerry Rasmussen'
    address:
      address_1: '123 Street St'
  -
    name: 'Sara DeWetzel'

Then it can be loaded and used like so:
json_data = YAML::load_file('config/people.yml').to_json
data = JSON.parse(json_data, object_class: OpenStruct)

data.people.first.name
 => Jerry Rasmussen
data.people.first.address.address_1
 => 123 Street St

A: There is no built-in way to convert a Hash into a construct that's accessible via dot syntax. You can either use a gem like settingslogic gem and point it to your application.yml file OR take a look at the source to find out the process by which this is done. I think the easiest and most robust approach is to use a popular (read: well tested in the wild) and well-documented gem vs. rolling your own.
# app/models/settings.rb
class Settings < Settingslogic
  source "#{Rails.root}/config/application.yml"
  namespace Rails.env
end

You can then access the individual settings via
Settings.info.name
# MyAppName

A: You can use recursive-open-struct gem
app_config = YAML.load_file('config/application.yml').with_indifferent_access
ros = RecursiveOpenStruct.new(app_config)

puts ros.settings.info.name # MyAppName

A: You can install hash dot gem
And, then use following code.
require 'hash_dot'
AppConfig = YAML::load_file('config/application.yml')

and, now call
AppConfig.settings.info.name

It will return your desired out put.

A: You could look into rails native

ActiveSupport::OrderedOptions < Hash

You still would have to convert your hashes with some function though, but as a starting point, if you really don't want any gem.


text:
Q: undefined reference when using dllexport I have created a little test program to understand the __declspec(dllimport) and
__declspec(dllexport) preproc.
In my solution I have :
1) File: produit.h
#pragma once

int  facteur = 5;
int __declspec(dllexport) base = 100;
int __declspec(dllexport) produit(int, int);

2) File : produit.cpp
#include "produit.h"

int produit(int a, int b)
{
   return facteur * (a*b);
}

3) File: produitEx.h
#pragma once

__declspec(dllimport) int base;
__declspec(dllimport) int produit(int a, int b);

4) File : main.cpp
#include <iostream>
#include "produitEx.h"
using namespace std;

int main()
{
    int a =5, b=2, c;
    c = base + produit(a, b);
    std::cout << c << std::endl;
    return 0;
}

looks pretty clear and nothing special just exporting fucntions and importing them.
When Compiling (with MinGW) I got those 2 errors :

..../main.cpp:8   undefined reference to `_imp___Z7produitii'
..../main.cpp:8   undefined reference to `_imp__base'

So I did not know what's confusing for the linker ? How to resolve it?
Thank you. (I use MinGW and NetBeans Cpp)
Just to add: the Same code Works on Visual Studio.


text:
Q: How do I simulate Text input to a WPF TextBox? I want to simulate user input to a WPF TextBox. I want to input a character such that the OnPreviewTextInput event is triggered. I tried setting the Text through the Text property, but this didn't trigger the event:
public void SomeFunction()
{
    var textBox = new TextBox();
    textBox.Text = "A";
}

Can I trigger the event explicitly somehow?

A: Another way to do this would be by using WinAPI, SendMessage to be specific:
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);

Then call it this way, when the focus is on the TextBox:
SendMessage(new WindowInteropHelper(this).Handle, 0x0102, 72, 0)

0x0102 is the constant value for WM_CHAR and 72 is the keycode for H (you can change this accordingly).

A: See the answer to How can I programmatically generate keypress events in C#? for a good description of how to simulate input events.
You could also do:
TextCompositionManager.StartComposition(
    new TextComposition(InputManager.Current, textBox, "A"));

This will raise the PreviewTextInput event and then raise the TextInput event and change the text.


text:
Q: How do I successfully push 50 randomly generated numbers into an array? I have written a function that generates different numbers each time it is called. Now I want it to genarate say 50 different numbers and then push it into an array. How do I go about it? This is the code below:
function generateRandomNumbers() {
    let randomArray = [];
    let digits = Math.floor(Math.random() * 900000000) + 100000000;
    digits = `0${digits}`;
    // Last task is to push 50 random digits into the array;

    return randomArray;
}
console.log(generateRandomNumbers());

A: You need to do something like this:

function generateRandomNumbers(howMany) {
  let arr = [];
  for(let i = 0; i <= howMany; i++)
  {
    let digits = Math.floor(Math.random() * 900000000) + 100000000;
    digits = `0${digits}`;
    arr.push(digits);
  }

  return arr;
}

let randomArray = generateRandomNumbers(50);

console.log(randomArray);


text:
Q: Could I change the certificate and provisioning profile for production to allow APNS without upload my binary? I have an error with the certificate and provisioning profile for allowing push notifications, so now, I would like to re-stat the work with the certificate and provisioning profile, after finish, should I upload a new version of the binary????

A: Yes you can upload new version of the binary, just remember Budle identifier is not changed.

A: If you only changed your certificate,  you wouldn't need to upload a new binary of your app. Only your server would be affected.
But changing the provisioning profile requires uploading a new binary of your app.


text:
Q: "Add contact" with non-empty fields On BlackBerry I want to display an "Add contact" dialog with some fields populated.
I supposed the following code would work:
    BlackBerryContact contact = (BlackBerryContact) mContactList.createContact();
    populateSomeFields (contact);
    AddressBookArguments args = new AddressBookArguments(
            AddressBookArguments.ARG_NEW, contact);
    Invoke.invokeApplication(Invoke.APP_TYPE_ADDRESSBOOK, args);

but no way.
If I Invoke with ARG_NEW a completely EMPTY fields are displayed. If I Invoke with ARG_COMPOSE an IllegalArgumentException is thrown.
Is there any way I can display "Add contact" with some fields filled in?

A: Well, there is no way to do just I want. But there is a nice crutch: commit contact (i.e. add it to phonebook) and then call Invoke with ARG_VIEW.
After that, user can press "edit" or "delete" from the menu.


text:
Q: Difference between catch and onErrorResumeNext In RxJS, there seems to be very little difference between an Observable instance's catch method and onErrorResumeNext method, besides the fact that onErrorResumeNext concatenates the original Observable with the Observable parameters whether an error happens or not.
If that's the case, isn't the naming a bit confusing? Because in case there is an error , onErrorResumeNext works exactly the same way than catch does:
var testObservable = Rx.Observable.return(1).concat(Rx.Observable.throw("Error"))

// Both onError and onCatch will emit the same result: 1, 2
var onError = testObservable.onErrorResumeNext(Rx.Observable.return(2));
var onCatch = testObservable.catch(Rx.Observable.return(2));

Is there a strong reason for not always using catch?

A: They are distinct.
As you've noted, both operators handle failure similarly; however, they differ in their handling of completion.
OnErrorResumeNext is simply a specialization with the following semantics:
"My query concatenates two observables. If the first observable fails, then resume with the next observable anyway."
Catch is far more general:
"My query avoids failure. If the observable fails, then continue with another observable."
If you're avoiding failure on the boundary of concatenation, then use OnErrorResumeNext; otherwise, to avoid failures in general use Catch.


text:
Q: How to I get Eclipse to work with the SVN server? Could anyone help me out a bit? I've downloaded Eclipse for JS and I'm currently investigating if it could be a great tool at my work.
Right now I'm using NPP text editor with the FTP plugin to edit files on out web server. After editing is done I do some SVN commands (committing/updating) in a putty window to the same server.
I imagine Eclipse could do it all? If so, how?

A: Subclipse is an eclipse module that allows you to manage your repositories directly through eclipse ;)


text:
Q: C++ not deducting correctly using guide template <typename T>
class SomeClass {
public:
    using container = std::vector<T>;

    container  buffer;
public:
    SomeClass(T elem): buffer({elem})  {
    }
};

SomeClass(char const*) -> SomeClass<std::string>;

int main() {

    std::cout << typeid(SomeClass<char const*>).name() << std::endl;

    SomeClass a("test");

    std::cout << typeid(a).name() << std::endl;

    return 0;
}

I specified a guide to convert from char const* to std::string as I saw in an example, but the output gives me
class SomeClass<char const *\>
class SomeClass<char const *>
I would expect both types to be instantiated to std::string, not char const*
How would I change this code to produce that output?


text:
Q: How to add music to my iPhone while Apple Music and iCloud Music Library are enabled? Hi I was trying to get some music into my iPhone through iTunes and it just doesn't seem to work? I've looked it up online and it just says drag and drop files but it doesn't work for me. I have Apple Music and iCloud Music Library enabled. Does this mean that now I can't download music and put it on my iPhone?
I also found same question here but it's from 2015 has anything changed since that?


text:
Q: XSLT Sorting with xsl:sort doesn't work The output xml doesn't sort as expected when I use the xsl:sort.
As you can see in the result section the 1.1.1.10, 2.10, 2.11, 2.12 are not correctly sorted.
I would expect the sorted lists to be as shown in the expected result xml.
Am I doing something wrong here? Please help.
Input XML
    <children>
        <child name="1.1.1.1 BDR Enter Customer"  prefix="1.1.1.1"/>
        <child name="1.1.1.10 BDR for Tax Office"  prefix="1.1.1.10"/>
        <child name="1.1.1.2 BDR Enter Customs"  prefix="1.1.1.2"/>
        <child name="1.1.1.3 BDR Enter Employee"  prefix="1.1.1.3"/>
        <child name="1.1.1.4 BDR Enter Forwarder"  prefix="1.1.1.4"/>
        <child name="1.1.1.5 BDR Enter Manufacturer"  prefix="1.1.1.5"/>
        <child name="1.1.1.6 BDR Enter Owner"  prefix="1.1.1.6"/>
        <child name="1.1.1.7 BDR Enter Person"  prefix="1.1.1.7"/>
        <child name="1.1.1.8 BDR Enter Resource"  prefix="1.1.1.8"/>
        <child name="1.1.1.9 BDR Enter Supplier"  prefix="1.1.1.9"/>
        <child name="1.1 Define System Basics" prefix="1.1"/>
        <child name="2.9 Set Up Basic Data Accounting Rules" prefix="2.9"/>
        <child name="2.2 Budget Management"  prefix="2.2"/>
        <child name="2.10 Customer Bill of Exchange Payment"  prefix="2.10"/>
        <child name="2.5 Depreciation Plan"  prefix="2.5"/>
        <child name="2.12 Supplier Credit Invoice"  prefix="2.12"/>
        <child name="2.11 AP/AR Nettings"  prefix="2.11"/>
        <child name="2.3 Arrival Entry Supplier Invoice"  prefix="2.3"/>
        <child name="2.1 Archive Data, Internal Ledger"  prefix="2.1"/>
</children>

My XSL
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" encoding="utf-8" indent="yes"/>
    <xsl:template match="children">
        <children>
            <xsl:for-each select="child">
                <xsl:sort select="@prefix"/>
                <child>
                    <xsl:attribute name="name">
                        <xsl:value-of select="@name"/>
                    </xsl:attribute>
                    <xsl:attribute name="prefix">
                        <xsl:value-of select="@prefix"/>
                    </xsl:attribute>
                </child>
            </xsl:for-each>
        </children>
    </xsl:template>
</xsl:stylesheet>

Result
<?xml version="1.0" encoding="utf-8"?>
<children>
  <child name="1.1 Define System Basics" prefix="1.1"/>
  <child name="1.1.1.1 BDR Enter Customer" prefix="1.1.1.1"/>
  <child name="1.1.1.10 BDR for Tax Office" prefix="1.1.1.10"/>
  <child name="1.1.1.2 BDR Enter Customs" prefix="1.1.1.2"/>
  <child name="1.1.1.3 BDR Enter Employee" prefix="1.1.1.3"/>
  <child name="1.1.1.4 BDR Enter Forwarder" prefix="1.1.1.4"/>
  <child name="1.1.1.5 BDR Enter Manufacturer" prefix="1.1.1.5"/>
  <child name="1.1.1.6 BDR Enter Owner" prefix="1.1.1.6"/>
  <child name="1.1.1.7 BDR Enter Person" prefix="1.1.1.7"/>
  <child name="1.1.1.8 BDR Enter Resource" prefix="1.1.1.8"/>
  <child name="1.1.1.9 BDR Enter Supplier" prefix="1.1.1.9"/>
  <child name="2.1 Archive Data, Internal Ledger" prefix="2.1"/>
  <child name="2.10 Customer Bill of Exchange Payment" prefix="2.10"/>
  <child name="2.11 AP/AR Nettings" prefix="2.11"/>
  <child name="2.12 Supplier Credit Invoice" prefix="2.12"/>
  <child name="2.2 Budget Management" prefix="2.2"/>
  <child name="2.3 Arrival Entry Supplier Invoice" prefix="2.3"/>
  <child name="2.5 Depreciation Plan" prefix="2.5"/>
  <child name="2.9 Set Up Basic Data Accounting Rules" prefix="2.9"/>
</children>

Expected Result
<?xml version="1.0" encoding="utf-8"?>
<children>
  <child name="1.1 Define System Basics" prefix="1.1"/>
  <child name="1.1.1.1 BDR Enter Customer" prefix="1.1.1.1"/>
  <child name="1.1.1.2 BDR Enter Customs" prefix="1.1.1.2"/>
  <child name="1.1.1.3 BDR Enter Employee" prefix="1.1.1.3"/>
  <child name="1.1.1.4 BDR Enter Forwarder" prefix="1.1.1.4"/>
  <child name="1.1.1.5 BDR Enter Manufacturer" prefix="1.1.1.5"/>
  <child name="1.1.1.6 BDR Enter Owner" prefix="1.1.1.6"/>
  <child name="1.1.1.7 BDR Enter Person" prefix="1.1.1.7"/>
  <child name="1.1.1.8 BDR Enter Resource" prefix="1.1.1.8"/>
  <child name="1.1.1.9 BDR Enter Supplier" prefix="1.1.1.9"/>
  <child name="1.1.1.10 BDR for Tax Office" prefix="1.1.1.10"/>
  <child name="2.1 Archive Data, Internal Ledger" prefix="2.1"/>
  <child name="2.2 Budget Management" prefix="2.2"/>
  <child name="2.3 Arrival Entry Supplier Invoice" prefix="2.3"/>
  <child name="2.5 Depreciation Plan" prefix="2.5"/>
  <child name="2.9 Set Up Basic Data Accounting Rules" prefix="2.9"/>
  <child name="2.10 Customer Bill of Exchange Payment" prefix="2.10"/>
  <child name="2.11 AP/AR Nettings" prefix="2.11"/>
  <child name="2.12 Supplier Credit Invoice" prefix="2.12"/>
</children>

A: Using XSLT 3.0 and the sort function from XPath 3.1 you could do it with
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:math="http://www.w3.org/2005/xpath-functions/math"
    exclude-result-prefixes="xs math"
    version="3.0">

    <xsl:mode on-no-match="shallow-copy"/>

    <xsl:output indent="yes"/>

    <xsl:template match="children">
        <xsl:copy>
            <xsl:apply-templates select="sort(child, (), function($c) { tokenize($c/@prefix, '\.')!xs:integer(.) })"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

Saxon 9.7 PE or EE and recent versions of Altova XMLSpy or Raptor support XSLT 3.0.
Using Saxon 9 (including HE) you can do it with XSLT 2.0 and collation="http://saxon.sf.net/collation?alphanumeric=yes" on the xsl:sort:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">

    <xsl:output indent="yes"/>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="children">
        <xsl:copy>
            <xsl:apply-templates select="child">
                <xsl:sort select="@prefix" collation="http://saxon.sf.net/collation?alphanumeric=yes"/>
            </xsl:apply-templates>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

A:
Am I doing something wrong here?

Yes, you are doing two things wrong:

*

*In the first place, you are sorting by a single sort key, when in fact you have four sort keys (at least) -- the separate segments of @prefix delimited by '.' characters.

*In the second place, you appear to want a numeric sort by each key, but you are instead accepting the default lexicographic sort.
In XSLT, you can sort by multiple keys by providing multiple xsl:sort elements, and you can get numeric sorting via the data-type attributes of those elements.  If you are restricted to XSLT 1.0 with no extensions, however, then that still leaves you with a slightly tricky problem of breaking up your prefix attribute into keys.  For a fixed maximum number of segments, you can do it like this:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" encoding="utf-8" indent="yes"/>

  <xsl:template match="node()|@*">
    <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="children">
    <xsl:copy>
      <xsl:apply-templates select="child">
        <xsl:sort data-type="number"
            select="substring-before(@prefix, '.')"/>
        <xsl:sort data-type="number"
            select="substring-before(substring-after(concat(@prefix, '.0.0.0.'), '.'), '.')"/>
        <xsl:sort data-type="number"
            select="substring-before(substring-after(substring-after(concat(@prefix, '.0.0.0.'), '.'), '.'), '.')"/>
        <xsl:sort data-type="number"
            select="substring-before(substring-after(substring-after(substring-after(concat(@prefix, '.0.0.0.'), '.'), '.'), '.'), '.')"/>
      </xsl:apply-templates>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

Note the use of the substring-before() and substring-after() functions to pick apart the prefix at the '.' delimiters, and the concatenation of '.0.0.0.' to the prefix to ensure that all prefixes are treated the same, regardless of depth, up to the maximum supported depth (four in this case, but that could be extended to whatever depth is needed).
Note also that xsl:copy is usually to be preferred over a literal output element, xsl:element, or xsl:attribute where the former is applicable, and that sorting can be applied to xsl:apply-templates, too, not just xsl:for-each.

A: If there really is no way to do this either by moving forward to a newer XSLT version or by exploiting vendor extensions, then the way I would tackle it is to preprocess the XML modifying the content from
<child name="1.1.1.10 BDR for Tax Office" prefix="1.1.1.10"/>

to
<child name="1.1.1.10 BDR for Tax Office" prefix="1.1.1.10"
  k1="1" k2="1" k3="1" k4="10"/>

and then sort using a multi-part sort key:
<xsl:sort select="@k1" data-type="number"/>
<xsl:sort select="@k2" data-type="number"/>
<xsl:sort select="@k3" data-type="number"/>
<xsl:sort select="@k4" data-type="number"/>

The preprocessing can be done using a sequence of instructions such as
<xsl:attribute name="k2">
  <xsl:value-of select="substring-before(substring-after(@prefix, '.'), '.')"/>
</xsl:attribute>


text:
Q: Google Fusion Tables and Update JSONP Query issues I combine two examples to one, first example is for Fusion Tables Layers Update Query from  dropdown menu and second example is geocodezip example for Fusion tables hover and click polygons.
Everything works fine (hover and click polygons, updateMap function etc.) except that when I want to choose values from  dropdown menu my Query not working, but when I remove WHERE clause my Query works fine. I know that I have some issues with this Query and I've spent the past 24 hours to solve this but without success, so does anyone have any suggestions?
My entire code is shown below.
<!DOCTYPE html>

    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="UTF-8">
    <title>Fusion Tables Layer Example: Update Query from  dropdown menu and Mouseover Map Styles</title>

<link href="/apis/fusiontables/docs/samples/style/default.css" rel="stylesheet" type="text/css">

Select Regional Council:

*Select Regional Council from the list

    <select id="regional_council">
      <option value="">--Select--</option>
      <option value="Auckland">Auckland</option>
      <option value="Bay of Plenty">Bay of Plenty</option>
      <option value="Canterbury">Canterbury</option>
      <option value="Gisborne">Gisborne</option>
      <option value="Hawkes Bay">Hawke's Bay</option>
      <option value="Manawatu-Wanganui">Manawatu-Wanganui</option>
      <option value="Marlborough">Marlborough</option>
      <option value="Nelson">Nelson</option>
      <option value="Northland">Northland</option>
      <option value="Otago">Otago</option>
      <option value="Southland">Southland</option>
      <option value="Taranaki">Taranaki</option>
      <option value="Waikato">Waikato</option>
      <option value="Wellington">Wellington</option>
      <option value="West Coast">West Coast</option>
    </select>

Select Area Unit:

*Select Area Unit by clicking on the Polygon


text:
Q: Where does Ubuntu 18.04 stores network settings? I have two virtual Ubuntu systems, set network settings via graphical interface on one system and decided to enter them manualy in the second one, but  known to me config files seem empty. Where can I find the right place?

A: To be more precise, connections you created via graphical interface are stored in /etc/NetworkManager/system-connections, for example on my working PC I have file Wired connection 1.nmconnection in this directory with such content for static IP connection:
[connection]
id=Wired connection 1
uuid=a3e912b0-f428-333f-a097-3a82d768a3cd
type=ethernet
autoconnect-priority=-100
permissions=

[ethernet]
duplex=half
mac-address=78:24:AF:3D:CD:21
mac-address-blacklist=
speed=100

[ipv4]
address1=192.168.1.8/21
dns-search=
method=manual

[ipv6]
addr-gen-mode=stable-privacy
dns-search=
method=auto

and Wired connection 2.nmconnection for DHCP connection, which differs in [ipv4] section:
[ipv4]
dns-search=
method=auto

Note, in this file there is device uuid instead of network card name. To match uuid's and card name you can use nmcli connection show:
NAME                    UUID                                  TYPE      DEVICE
Wired connection 1      a3e912b0-f428-333f-a097-3a82d768a3cd  ethernet  eno1

A: It is in /etc/NetworkManager directory


text:
Q: freeradius unlang disable escaping I have the following list of VLAN's I want to check against ldap.
Tmp-String-0 = "CN=vlan10,CN=Users,DC=aaa,DC=local;CN=vlan20,CN=Users,DC=aaa,DC=local"

With ulang I explode them and loop through them
 if ("%{explode:&control:Tmp-String-0 ;}" > 0) {
           foreach &control:Tmp-String-0 {

Then I try to do checking with
Tmp-String-1 := "%{ldap_aaa.local:ldapi://192.168.0.199:389/cn=Users,dc=aaa,dc=local?memberof?sub?(&(objectCategory=User)(sAMAccountName=%{%{Stripped-User-Name}:-%{User-Name}})(memberOf=%{Foreach-Variable-0}))}"

However %{Foreach-Variable-0} gets the escaped version of the string:
CN3dvlan202cCN3dUsers2cDC3daaa2cDC3dlocal
The escaped version is not working, if I replace it with hardcoded unescaped version the it works.
CN=vlan20,CN=Users,DC=aaa,DC=local
How to prevent unlang for escaping the variable?

A: You can't prevent unescaping in v3.  In version 4 there's the concept of "tainted" and "untainted" values, with tainted values being escaped, and "untainted" values being inserted verbatim, but I'm not sure that's implemented yet in the LDAP module expansions.
You could use the group membership checks in the LDAP module to do what you're trying to implement with the xlat expansion?
e.g.
 if ("%{explode:&control:Tmp-String-0 ;}" > 0) {
           foreach &control:Tmp-String-0 {
                      if (LDAP-Group == "%{control:Tmp-String-0}") {
                                 update reply {
                                            # VLAN-Attrs
                                 }
                      }
           }
}


text:
Q: Creating a trigger function in SQL I've been given a task to create a trigger function for this question:
Add an update to the support ticket from a given staff member. If the ticket is closed no more updates should be allowed by either customers or staff members.
Insert an update to a ticket with values: ticketUpdateID = 10050; Message ='Highlight folder for backup and press to trash or right click and choose delete'; TicketID = 1010 ; StaffID=2
All I've managed so far is:
CREATE OR REPLACE FUNCTION update_ticket()
RETURNS trigger AS $BODY$
BEGIN

I would just like to know the layout of what i would have to put next.
Thanks

A: The question becomes "How do you want to handle bypassing the update: silently ignore the action or raise an exception"? Postgres provides for both cases. The trigger  function for an Update DML receives 2 pseudo rows conveniently named old and new (at least by default) which represent the current database row and the "tobe" database row respectively. Somewhere in the table definition you have some column indicating the current status of the some value indicating "closed". Unfortunately you have not defined either so I will just make something up for demo purpose. The following will suppress the any update on a 'closed' ticket. I will leave Raising an exception for your research.
create or replace
function update_ticket()
  returns trigger
 language plpgsql
as $$
begin
    if old.status = 'closed' then
       return null;
    end if;
    return new;
end;
$$;


text:
Q: How to use regex for XPath attribute definition I have a DOM element with the following unique attribute
ui-sref=".carts.cart({type:'agent'})"

so I need to define a XPath for Selenium to find this element.
I can use
//li[contains(@ui-sref,"carts") and contains(@ui-sref,"agent")]

and it works fine.
Can I use something like
//li[contains(@ui-sref,"carts"*"agent")


text:
Q: pandas: create a row per combination of index value and external list value I am trying to create a row in a dataframe that would represent a unique combination between the index of the df and a value in a list.
A short example would be more explicit than lots of words!
           Id
0    16342939
1    16346727

and the list
Location = ['DC1', 'DC2', 'store1','store2']

what I am looking to achieve is this:
           Id    Loc
0    16342939    DC1
0    16342939    DC2
0    16342939 store1
0    16342939 store2
1    16346727    DC1
1    16346727    DC2
1    16346727 store1
1    16346727 store2

I am asking what tool should I use to do that in python. I have thought and searched about itertools and combinations. But it does not seem to do the trick. I have also thought of merging the list, but it does not work either.
A recommendation on the tool to use would be highly appreciated!

A: You can do this with list comprehension and the pandas explode function.
First populate the "Loc" column with the Location list. To do this you need to use list comprehension otherwise pandas will try to populate the rows of the column with the individual list entries instead of the entire list. Sample code for the list comprehension is below:
df['Loc'] = [Location for i in range(len(df))]
Then you can use the explode function to split the pandas explode function to split the list data into seperate rows with the same "Id" value. Sample code for this is below:
df = df.explode('Loc')
The final result will be the following:
         Id     Loc
0  16342939     DC1
0  16342939     DC2
0  16342939  store1
0  16342939  store2
1  16346727     DC1
1  16346727     DC2
1  16346727  store1
1  16346727  store2

A: You could also use the expand_grid from the pyjanitor library
others = {"Id": df.Id.array, 'Loc': Location}

In [87]: janitor.expand_grid(others = others)
Out[87]:
         Id     Loc
0  16342939     DC1
1  16342939     DC2
2  16342939  store1
3  16342939  store2
4  16346727     DC1
5  16346727     DC2
6  16346727  store1
7  16346727  store2

You could get more speed with numpy:
left = np.repeat(df.Id.array, len(Location))
right = np.resize(Location, len(df)*len(Location))
combo =zip(['Id', 'Loc'],  map(pd.Series, (left, right)))
pd.concat(dict(combo), axis = 'columns')
         Id     Loc
0  16342939     DC1
1  16342939     DC2
2  16342939  store1
3  16342939  store2
4  16346727     DC1
5  16346727     DC2
6  16346727  store1
7  16346727  store2

A: You can use pandas.DataFrame.merge:
>>> df.merge(pd.Series(Location, name = 'Loc'), how = "cross")
         Id     Loc
0  16342939     DC1
1  16342939     DC2
2  16342939  store1
3  16342939  store2
4  16346727     DC1
5  16346727     DC2
6  16346727  store1
7  16346727  store2


text:
Q: How to build imported project on Eclipse? I just imported source folders and required libraries from another PC on which I had been working. The project contains JAVA and Python code in separate packages. Now there seems to be some problem with running the Java parts.
Error: Could not find or load main class Drivers.DependencyFinder
I have tried Cleaning and Building the project. It didn't create any classes in the bin folder. When I copied class files from the older PC, it gives some version error.
I'd like to make a fresh build, removing all the things I had earlier other than the source code. Clicking Build All or Build doesn't produce anything. What's going wrong?

A: Go to the project properties and check Source tab under Java Build Path. Make sure the proper folders are included in the build path.


text:
Q: Prove the sequence $x_n = \frac{2^n}{n^2}$ is unbounded. I am having difficulties proving the sequence  $x_n = \frac{2^n}{n^2}$ is unbounded.
I can prove it is monotone from some term, but I don't know if it is necessary:
$\frac{2^n}{n^2}$ v $\frac{2^{n+1}}{(n + 1)^2}$
After transformations I get:
$\frac{2^n}{n^2}$ < $\frac{2^{n+1}}{(n + 1)^2}$, when $n > 1 + \sqrt{2}$
However, when I am trying to prove by contradiction that the sequence is unbounded, I get:
$\frac{2^n}{n^2} < M$
$n < log_2 (M*n^2)$
And after that I can only get the initial statement and I do not know how to proceed. Can someone show me what to do next? Thanks!

A: Notice that $\frac{x_{n+1}}{x_n} = \frac{2}{(\frac{n+1}{n})^2}$ and the ratio approximates 2 for big $n$.  Therefore the sequence is not bounded, since for sufficiently big $n$, $x_{n+1} \approx 2 x_n$

A: As an alternative we can easily prove by induction that $2^n\ge n^3$ then
$$x_n = \frac{2^n}{n^2}\ge \frac{n^3}{n^2}=n$$
which is clearly unbounded.
Refer to the related:

*

*Prove using Induction | Tricky one!

*Use induction to prove that $2^n \gt n^3$ for every integer $n \ge 10$.


text:
Q: Cart details not getting in mini cart For some purpose (something like popup) I'm trying to fetch cart details in minicart.phtml from Magento2\vendor\magento\module-checkout\view\frontend\templates\cart\minicart.phtml.
I directly modified core file just for checking purpose only. The point is cart details (from below code) are displaying only in cart page. It is not displaying in other pages like home page, product, category pages.I'm using default Magento EE 2.2.5 Luma theme. Any suggestion will be appreciated...
Below is my code (It's dirty, just for checking purpose),
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cart = $objectManager->get('\Magento\Checkout\Model\Cart');

// get quote items collection
$itemsCollection = $cart->getQuote()->getItemsCollection();

// get array of all items what can be display directly
$itemsVisible = $cart->getQuote()->getAllVisibleItems();

// get quote items array
$items = $cart->getQuote()->getAllItems();

foreach($items as $item) {
    echo 'ID: '.$item->getProductId().'
';
    echo 'Name: '.$item->getName().'
';
    echo 'Sku: '.$item->getSku().'
';
    echo 'Quantity: '.$item->getQty().'
';
    echo 'Price: '.$item->getPrice().'
';
    echo "
";
}

I tried with block also through the constructor (like proper way) magento2ee\vendor\magento\module-checkout\Block\Onepage.php But same like working only in cart page. Not in other pages..
Update:
I'm just wondering below piece of code for fetching product details is working but not for cart.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
/** Apply filters here */
$collection = $productCollection->addAttributeToSelect('*')
            ->load();

foreach ($collection as $product){
     echo 'Name  =  '.$product->getName().'
';
     break;
}

A: Little Modifications in your code.
Not sure but it should work I had same issue while ago.
Little modifications in your method.
You can give a try with Magento\Checkout\Model\Session.

A: We are using below code on our custom phtml file which is located under

/view/frontend/templates/checkout/cart/custom.phtml

$om =   \Magento\Framework\App\ObjectManager::getInstance();

//Getting cart Item//

$quote = $om->create('Magento\Checkout\Model\Cart')->getQuote();
$quoteitems = $quote->getAllVisibleItems();

You can try this one.

A: Get cart items from customer local storage.
And render it using knock out.
You can get Cart item details of the guest user also,
in your js file
define([
        'jquery',
        'knockout',
        'Magento_Customer/js/customer-data',
        'uiComponent'
    ], function ($, ko, customerData, Component) {
        return Component.extend({
            initialize: function () {
                self = this;
                self.cart = customerData.get('cart');

                let cartData = self.cart().items ? self.cart().items: [];

                cartData.map(function(item) {
                    console.log(item.product_id);
                    console.log(item.product_name);
                    console.log(item.product_sku);
                });

            },

        });
    });


text:
Q: How to Avoid Firing ObservableCollection.CollectionChanged Multiple Times When Replacing All Elements Or Adding a Collection of Elements I have ObservableCollection<T> collection, and I want to replace all elements with a new collection of elements, I could do:
collection.Clear();

OR:
collection.ClearItems();

(BTW, what's the difference between these two methods?)
I could also use foreach to collection.Add one by one, but this will fire multiple times
Same when adding a collection of elements.
EDIT:
I found a good library here: Enhanced ObservableCollection with ability to delay or disable notifications but it seems that it does NOT support silverlight.

A: ColinE is right with all his informations. I only want to add my subclass of ObservableCollection that I use for this specific case.
public class SmartCollection<T> : ObservableCollection<T> {
    public SmartCollection()
        : base() {
    }

    public SmartCollection(IEnumerable<T> collection)
        : base(collection) {
    }

    public SmartCollection(List<T> list)
        : base(list) {
    }

    public void AddRange(IEnumerable<T> range) {
        foreach (var item in range) {
            Items.Add(item);
        }

        this.OnPropertyChanged(new PropertyChangedEventArgs("Count"));
        this.OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
        this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    }

    public void Reset(IEnumerable<T> range) {
        this.Items.Clear();

        AddRange(range);
    }
}

A: Here is what I implemented for other folks' reference:
// http://stackoverflow.com/questions/13302933/how-to-avoid-firing-observablecollection-collectionchanged-multiple-times-when-r
// http://stackoverflow.com/questions/670577/observablecollection-doesnt-support-addrange-method-so-i-get-notified-for-each
public class ObservableCollectionFast<T> : ObservableCollection<T>
{
    public ObservableCollectionFast()
        : base()
    {

    }

    public ObservableCollectionFast(IEnumerable<T> collection)
        : base(collection)
    {

    }

    public ObservableCollectionFast(List<T> list)
        : base(list)
    {

    }

    public virtual void AddRange(IEnumerable<T> collection)
    {
        if (collection.IsNullOrEmpty())
            return;

        foreach (T item in collection)
        {
            this.Items.Add(item);
        }

        this.OnPropertyChanged(new PropertyChangedEventArgs("Count"));
        this.OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
        this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
        // Cannot use NotifyCollectionChangedAction.Add, because Constructor supports only the 'Reset' action.
    }

    public virtual void RemoveRange(IEnumerable<T> collection)
    {
        if (collection.IsNullOrEmpty())
            return;

        bool removed = false;
        foreach (T item in collection)
        {
            if (this.Items.Remove(item))
                removed = true;
        }

        if (removed)
        {
            this.OnPropertyChanged(new PropertyChangedEventArgs("Count"));
            this.OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
            this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
            // Cannot use NotifyCollectionChangedAction.Remove, because Constructor supports only the 'Reset' action.
        }
    }

    public virtual void Reset(T item)
    {
        this.Reset(new List<T>() { item });
    }

    public virtual void Reset(IEnumerable<T> collection)
    {
        if (collection.IsNullOrEmpty() && this.Items.IsNullOrEmpty())
            return;

        // Step 0: Check if collection is exactly same as this.Items
        if (IEnumerableUtils.Equals<T>(collection, this.Items))
            return;

        int count = this.Count;

        // Step 1: Clear the old items
        this.Items.Clear();

        // Step 2: Add new items
        if (!collection.IsNullOrEmpty())
        {
            foreach (T item in collection)
            {
                this.Items.Add(item);
            }
        }

        // Step 3: Don't forget the event
        if (this.Count != count)
            this.OnPropertyChanged(new PropertyChangedEventArgs("Count"));
        this.OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
        this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    }
}

A: I can't comment on previous answers yet, so I'm adding here a RemoveRange adaptation of the SmartCollection implementations above that won't throw a C# InvalidOperationException: Collection Was Modified. It uses a predicate to check if the item should be removed which, in my case, is more optimal than creating a subset of items that meet the remove criteria.
public void RemoveRange(Predicate<T> remove)
{
    // iterates backwards so can remove multiple items without invalidating indexes
    for (var i = Items.Count-1; i > -1; i--) {
        if (remove(Items[i]))
            Items.RemoveAt(i);
    }

    this.OnPropertyChanged(new PropertyChangedEventArgs("Count"));
    this.OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
    this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}

Example:
LogEntries.RemoveRange(i => closeFileIndexes.Contains(i.fileIndex));

A: You can achieve this by subclassing ObservableCollection and implementing your own ReplaceAll method. The implementation of this methods would replace all the items within the internal Items property, then fire a CollectionChanged event. Likewise, you can add an AddRange method. For an implementation of this, see the answer to this question:
ObservableCollection Doesn't support AddRange method, so I get notified for each item added, besides what about INotifyCollectionChanging?
The difference between Collection.Clear and Collection.ClearItems is that Clear is a public API method, whereas ClearItems is protected, it is an extension point that allows your to extend / modify the behaviour of Clear.

A: For the past few years I am using a more generic solution to eliminate too many ObservableCollection notifications by creating a batch change operation and notifying observers with a Reset action:
public class ExtendedObservableCollection<T>: ObservableCollection<T>
{
    public ExtendedObservableCollection()
    {
    }

    public ExtendedObservableCollection(IEnumerable<T> items)
        : base(items)
    {
    }

    public void Execute(Action<IList<T>> itemsAction)
    {
        itemsAction(Items);
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    }
}

Using it is straightforward:
var collection = new ExtendedObservableCollection<string>(new[]
{
    "Test",
    "Items",
    "Here"
});
collection.Execute(items => {
    items.RemoveAt(1);
    items.Insert(1, "Elements");
    items.Add("and there");
});

Calling Execute will generate a single notification but with a drawback - list will be updated in UI as a whole, not only modified elements. This makes it perfect for items.Clear() followed by items.AddRange(newItems).