text:
Q: Storing a TimeSpan between two DateTimes I need a way to store and manipulate a date range using C# and storing the data in a SQL database. Is storing two DateTimes the best way to go about this?
For example I need to employees to be able to select the duration they spent working on a specific project by selecting the start date and end date using a DatePicker.
I have the following further requirements:

*

*I need to support half days at start
and/or end of the duration.

*I need to be able to calculate the number of
days between the two dates (as a
double where 0.5 is half a day).

*I need to be able to calculate the
number of business days between the
two dates (as a double).

*The time   span needs to be displayed on a
jquery calendar.

*The minimum
duration is half a day.
A Date Range of 1/2 Day From 24th May to a full day 27th May:
2011-05-24 12:00:00.000 => 2011-05-28 00:00:00.000
A Date Range of Full Day From 24th May to a 1/2 day 27th May:
2011-05-24 00:00:00.000 => 2011-05-27 12:00:00.000
A Half Day on 24th May:
2011-05-24 12:00:00.000 => 2011-05-25 00:00:00.000
A Full Day on 24th May:
2011-05-24 00:00:00.000 => 2011-05-25 00:00:00.000
Does this representation make sense? Should I rather look at storing a DateTime for the StartDate and a TimeSpan taking into account my requirements?
Edit: also
Does my representation of end date make sense? So that 2nd of may will be saved as '2011-05-03 00:00:00.000' because that is when the duration ends. Bearing this in mind I'll need to subtract a day from the end date when displaying this in a calendar..

A: I suggest to save the start and end date to your database. The difference can always be calculated.
The critical aspect of date ranges is how to handle the boundaries. You can use a mapper for the start/end date to ensure correct time calculations (Inside/Touching):
// ----------------------------------------------------------------------
public void TimePeriodMapperSample()
{
  TimeCalendar timeCalendar = new TimeCalendar();
  CultureInfo ci = CultureInfo.InvariantCulture;

  DateTime start = new DateTime( 2011, 3, 1, 13, 0, 0 );
  DateTime end = new DateTime( 2011, 3, 1, 14, 0, 0 );

  Console.WriteLine( "Original start: {0}",
                     start.ToString( "HH:mm:ss.fffffff", ci ) );
  // > Original start: 13:00:00.0000000
  Console.WriteLine( "Original end: {0}",
                     end.ToString( "HH:mm:ss.fffffff", ci ) );
  // > Original end: 14:00:00.0000000

  Console.WriteLine( "Mapping offset start: {0}", timeCalendar.StartOffset );
  // > Mapping offset start: 00:00:00
  Console.WriteLine( "Mapping offset end: {0}", timeCalendar.EndOffset );
  // > Mapping offset end: -00:00:00.0000001

  Console.WriteLine( "Mapped start: {0}",
    timeCalendar.MapStart( start ).ToString( "HH:mm:ss.fffffff", ci ) );
  // > Mapped start: 13:00:00.0000000
  Console.WriteLine( "Mapped end: {0}",
    timeCalendar.MapEnd( end ).ToString( "HH:mm:ss.fffffff", ci ) );
  // > Mapped end: 13:59:59.9999999
} // TimePeriodMapperSample

Check out the article Time Period Library for .NET (section Calendar Time Periods).

A: Only store start and end dates. Then to calculate no of days worked:
Round(DateDiff(hour, StartDate, EndDate)/24, 2)

A: Ideally, you will need two fields anyway:

*

*Store two date/time separately --OR--

*Store one date/time and store the time-elapsed

Reviewing your requirements, I would go for two separate date/time fields; and calculate the fulldays/halfdays including (adding/subtracting) holidays.
Keep a separate configuration table to define/configure the max/minimum duration of the day.
Perform any calculations on the day/time, within the query, or alternatively on the UI, upon user actions - if you desire.

A: To me it seems like storing 2 datetime's makes the most sense.

A: It really depends on how you intend to use your data. If your second date will never be used outside of calculating the TimeSpan, you should not store it, and store the TimeSpan instead. If you use the end date frequently and only seldom calculate the duration, you should store the 2 datetimes.
You can even consider to store the three values if you use them frequently and the increase in memory space is not a problem.

A: I believe two DateTime Fields along with checkboxes corresponding to Start and End date to indicate whether its Half or Full day would be sufficient for you. based on the Checkbox state you can manipulate the time component to suit your needs. You will just have to store the Start and End DateTime values which would adhere to the requirements you posted.


text:
Q: Postfix rejects email routed from Google Workspace: NOQUEUE: reject: RCPT from unknown[209.85.128.69]: 451 4.3.0 Temporary lookup failure Setting up Google Workspace and want to test things before changing the production MX records and having everything go through Google. I have a test Workspace account for domain testdomain.tld. I have set up an email route from testdomain.tld in Workspace pointing to the company's legacy mail server mail.corporate1.com. The legacy server is postfix 2.11.3-1 running on an old Debian (Wheezy/Jessie) server.
The route configuration in Workspace is shown at the bottom. This route is to test the advertised ability to route unrecognized email addresses to the legacy server. We need to use this capability to migrate the users and automated email streams gradually.
The email gets routed nicely, but the legacy Postfix mail server does not accept the email. The test I am running is to send email from outside the company to testuser@testdomain.tld and watch the logs on mail.corporate1.com. Tried many different configuration changes and I just keep getting the same error message in the mail log. The test user does not have an account in the testdomain.tld Workspace, a test condition. The test user is set up as a Linux user on corporate1.com and successfully receives email addressed to testuser@corporate1.com. The error, main.cf, and mail route config follow below.
-------error from mail log-------
Sep 19 12:34:56 [postfix/submission/smtpd] NOQUEUE: reject: RCPT from unknown[209.85.128.69]: 451 4.3.0 <testlocation@wherever.com>: Temporary lookup failure; from=<testlocation@wherever.com> to=<testuser@testdomain.tld> proto=ESMTP helo=<mail-ab1-c23.google.com>

-------main.cf---on mail.corporate1.com-------
myhostname = server.corporate1.com
myorigin = /etc/mailname
mydestination = mail.corporate1.com, mail.corporate0.com, corporate0.com, corporate1.com, localhost, localhost.localdomain, corporate2.com, mail.corporate2.com, server.corporate2.com, server.corporate0.com, server0.corporate0.com, server.corporate1.com, server0.corporate1.com, corporate3.com, mail.corporate3.com, testdomain.tld
relayhost =
mailbox_command = /usr/bin/procmail -a "$EXTENSION"
command_execution_directory = $home

masquerade_classes = envelope_recipient, envelope_sender,
        header_sender, header_recipient
masquerade_domains = corporate0.com corporate1.com

mynetworks = 10.0.0.0/8, 127.0.0.0/8, 177.177.77.0/24, 24.213.146.72/29.
        178.178.45.16/28.
        179.254.122.0/24.
        170.170.113.143/32.
        171.171.57.10/32.
        174.129.81.250/32.
        172.172.69.27/32.
        173.173.106.89/32.
        [::ffff:127.0.0.0]/104, [::1]/128

mailbox_size_limit = 0
message_size_limit = 0
command_time_limit = 45m
ipc_timeout = 45m

recipient_delimiter = +
inet_interfaces = all
# inet_protocols = ipv4

# Alias and recipient maps

alias_maps = hash:/etc/mail/aliases
alias_database = hash:/etc/mail/aliases
# Default local_recipient_maps
local_recipient_maps = proxy:unix:passwd.byname $alias_maps

# SSL

smtpd_tls_cert_file=/usr/asher/certificates/mail.corporate1.com.pem
smtpd_tls_key_file=/usr/asher/certificates/server0_priv.pem
smtp_use_tls=yes
smtpd_use_tls=yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtpd_tls_security_level=may
smtpd_tls_protocols = !SSLv2, !SSLv3

proxy_interfaces=177.177.77.118

# SASL
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtpd_sasl_auth_enable = yes
broken_sasl_auth_clients = yes
# smtpd_sasl_security_options = noanonymous
# smtpd_sasl_tls_security_options = $smtpd_sasl_security_options
## Allow plaintext mechanisms, but only over a TLS-encrypted connection:
smtp_sasl_security_options = noanonymous
smtpd_sasl_security_options = noanonymous
#smtp_sasl_security_options = noanonymous, noplaintext
#smtpd_sasl_security_options = noanonymous, noplaintext
broken_sasl_auth_clients = yes
smtpd_sasl_authenticated_header = yes
# smtpd_sasl_local_domain = $myhostname
smtpd_sasl_tls_security_options = noanonymous
smtpd_tls_auth_only = yes
smtpd_relay_restrictions =
        permit_mynetworks,
        permit_sasl_authenticated,
        reject_unauth_destination
#       reject_unknown_recipient_domain
## Keep these ???
#smtpd_sender_login_maps = hash:/etc/postfix/controlled_envelope_senders
smtpd_sender_login_maps =
smtpd_recipient_restrictions =
        permit_mynetworks,
        permit_sasl_authenticated,
        reject_unauth_destination
#       reject_unknown_recipient_domain
smtpd_sasl_local_domain = corporate1.com

luser_relay = non-deliverable@corporate1.com

smtp_defer_if_no_mx_address_found = yes

# anti-spam experiment
smtpd_soft_error_limit = 9
smtpd_hard_error_limit = 19

relay_domains = mail.corporate1.com
transport_maps = hash:/etc/postfix/transport

# DKIM
smtpd_milters = inet:localhost:8891
non_smtpd_milters = $smtpd_milters
milter_default_action = accept

virtual_alias_domains = corporate2.com

-------google-workspace email route configuration-------
Admin > Apps > Google Workspace > Gmail > Routing
   Name:
      Pass-Through Email Delivery for Unrecognized Addresses
   1. Email messages to affect
      * Inbound
      * Internal - Receiving
   2. For the above types of messages, do the following
      * Route
         * Change route
         * Also reroute spam
         * (To:) Legacy Email Server
   Options
   B. Account types to affect
      * Users
      * Unrecognized / Catch-all

A: The virtual table was missing.  Created an empty /etc/postfix/virtual and ran command:
    postmap /etc/postfix/virtual

redpajama_set_name: RedPajamaStackExchange


text: Q: Узнать кто вызвал модуль Есть модуль обращения к сервису. Например getData.js, и есть куча других модулей, которые используют его. Как можно узнать кто вызвал модуль getData (в идеале получить путь). module.parent возвращает только путь к первому модулю, который вызвал


text:
Q: how to switch workspaces in Ubuntu 16.04? When I move my laptop from place to place and switching on and off a second monitor. my workspace seems to mess up easily: I could not be able to bring up some terminal or browser window.
At first I thought these must have crashed, but now realize they are just in different workspaces. But I'm not able to switch to them. CTL+ALT + TAB should be able to do that, but it doesn't stay on. As soon as I hit ENTER key or mouse button the selected window just disappears. Nor do I see an "activities overview" anywhere on my screen.
What am I missing?  I have Ubuntu 16.04 on a Lenovo T450s laptop. Everything else is fine.
thanks for any insight!

A: Solved: Just go to System settings - Apparence - Behaviors, check the 'Enable Workspaces" button.


text:
Q: Google Cloud Video Intelligence API: VideoAnnotationResults overlay on video I've used the Video Intelligence API to do object tracking on my video - and have received a JSON output with all the frames and objects detected in my video.
Is there a way I can generate a video output from my JSON, using the original video - to show an example of all the objects tracked for the video?
Something like the below:
https://cdn-images-1.medium.com/max/500/1*q1uVc-MU-tC-WwFp2yXJow.gif

A: Video Intelligence API does not generate any video where objects are shown to be tracked with drawn boxes on objects that are detected as shown in your example link. You have to do this separately or manually to images/videos and use other image annotation tool.
You can refer to this article from Spring ML which explains how you can achieve such output. The example use case discussed was about detecting potholes along the road which used an image annotation tool. With the kind of video output you are looking for, you need to work a lot in order to achieve this. Here is a brief summary about the article.

*

*Spliced the video into image/video frames.

*Train your own model to detect desired object of interest.

*Use Label IMG to identify and label objects of interest.

*Apply the labelled images/videos.


text:
Q: Pandas: creating a lagged column with grouped data I'm working with the following DataFrame:
url='https://raw.githubusercontent.com/108michael/ms_thesis/master/crsp.csv'

df=pd.read_csv(url)

df.head()

    feccandid   fec.dyn feccf   cid     date_crsp   catcode     amtsum
0   S8VT00018   NaN     NaN     N00000534   2005    J2100        2.1
1   S8VT00018   NaN     NaN     N00000534   2005    L1200        5.0
2   S8VT00018   NaN     NaN     N00000534   2005    J7300        0.0
4   S8NM00127   0.561   0.382   N00015616   2006    G2900        2.5
5   S8NJ00350   -0.329  NaN     N00000854   2005    LG000        7.5

I would like to lag the amtsumvalues by year. The following code shows how I derived amtsumand provides insight into the nature of my desired outcome:
crsp['amtsum']=crsp[['date_crsp', 'cid', 'catcode', 'amount']].\
groupby(['date_crsp', 'catcode','cid']).amount.transform('sum')
crsp['amtsum'] = crsp['amtsum'] / 1000
crsp.drop(['amount'], axis=1, inplace=True)
crsp.drop_duplicates(inplace=True, keep='first')

I have tried using the following code to get lagged values:
crsp['amtsumlag.1']=crsp.groupby(['date_crsp','catcode', 'cid'])['amtsum'].shift(1)

This returns
    feccandid   fec.dyn     feccf   cid     date_crsp   catcode     amtsum  amtsumlag.1
0   S8VT00018   NaN     NaN     N00000534   2005       J2100    2.1     NaN
1   S8VT00018   NaN     NaN     N00000534   2005       L1200    5.0     NaN
2   S8VT00018   NaN     NaN     N00000534   2005       J7300    0.0     NaN
4   S8NM00127   0.561   0.382   N00015616   2006       G2900    2.5     NaN
5   S8NJ00350   -0.329  NaN     N00000854   2005       LG000    7.5     NaN

Since my date_crsprange is from 2005 to 2014 I expect to have NaNfor 2005 but not for 2006. I have also selected only dates after 2005 and got the same results. Does anyone have a clue on how to solve this problem?

A: You need to look into your .groupby() logic.
crsp.groupby(['date_crsp','catcode', 'cid']).size().value_counts()

results in
1    444508
2      5281
3       619
4         3

Most of the groups have only a single value, so there's not much to shift. Unsurprisingly,
crsp['amtsumlag.1'] = crsp.groupby(['catcode', 'cid', 'date_crsp'])['amtsum'].shift(1)

results in:
Data columns (total 8 columns):
feccandid             456939 non-null object
feccandcfscore.dyn    445710 non-null float64
feccandcfscore        355887 non-null float64
cid                   456939 non-null object
date_crsp             456939 non-null int64
catcode               456939 non-null object
amtsum                456939 non-null float64
amtsumlag.1           6528 non-null float64

If you want to .shift() by date_crsp, for instance, you probably do not want to use it in .groupby() - each group would then only contain a single year. One would expect to see unique group id variables in .groupby(), and ideally a DateTimeIndex, or otherwise a sorted DataFrame. So .sort_values('date_crsp') might be a good idea.
crsp['amtsumlag.1'] = crsp.sort_values('date_crsp').groupby(['catcode', 'cid'])['amtsum'].shift(1)

instead yields:
feccandid             456939 non-null object
feccandcfscore.dyn    445710 non-null float64
feccandcfscore        355887 non-null float64
cid                   456939 non-null object
date_crsp             456939 non-null int64
catcode               456939 non-null object
amtsum                456939 non-null float64
amtsumlag.1           301280 non-null float64
dtypes: float64(4), int64(1), object(3)

Without know the data enough to understand what identifies the groups you are trying to lag it's hard to provide a more specific answer.

A: If you want to shift the years by one, prepare a new column of years:
crsp['next_year'] = crsp['date_crsp'] + 1

and then groupby by ['next_year', 'catcode', 'cid'] instead of ['date_crsp', 'catcode', 'cid']:
crsp['amtsumlag.1'] = (crsp.groupby(['next_year', 'catcode', 'cid'])['amount']
                       .transform('sum'))


text:
Q: What places have the best efficiency for EV training in Black And White? I've decided to look into EV training to make my Pokemon stronger in a competitive battle.  I know about how to train EVs, using items such as Macho Brace or Power Bracer etc, but I was wondering what routes/caves/surf areas/other places were best for each specific EV stat.
My version is Pokemon Black, and I've beaten the Elite 4 and Alder and have access to all areas of the game.
I know that on Route 1, all you can find are Lillipup and Patrat, both of which give +1 Attack EV.
That makes for a 100% chance to get +1 Attack EVs per kill.
I also know that in the cave beside Route 3, all you can find are roggenrola and woobat, which give +1 Defense EV and +1 Speed EV respectively.
This results in only a 50% chance to get +1 Defense EV per kill, or a 50% chance to get +1 Speed EV per kill.
I'd like to know where all the statistically most rewarding places to find each EV are, to minimize the time it takes to EV train.
I believe I know already that route 1 is the best for Attack, but I would also like to know about Defense, Special Attack, Special Defense, Speed, and Health.

A: HP

*

*Surf in Icirrus City - Stunfisk (100%, 2 HP EV)

Note also, There's Victini (for 3 HP EV) that can be rebattled infinitely as long as it is not caught.
Atk

*

*Route 1 - Lillipup and Patrat (total 100%, 1 Atk EV)

*Dragonspiral Tower 2F - Golett (100%, 1 Atk)

*Dragonspiral Tower 1F - Golett and  Mienfoo (total 70%, 1 Atk), Druddigon (30%, 2 Atk)

*Outside of Dragonspiral Tower, Double Grass - Tranquill, Sawsbuck and Druddigon (total 70%, 2 Atk), and Mienfoo (30%, 1 Atk)

Note that During Winter, the Double Grass location changes up. notably with Tranquill being replaced by Vanillish (30%, 2 SpAtk).
Def

*

*Wellspring Cave - Roggengola (50%, 1 Def)

*Pinwheel Forest - Venipede and Sewaddle (total 50%, 1 Def)

*Pinwheel Forest Double Grass - Swadloon and Whirlipede (total 50%, 2 Def)

*Chargestone Cave - Klink, Ferroseed and Boldore (59%, 1 Def)

Note that Boldore also gives 1 Atk in addition to 1 Def!
SpAtk

*

*Celestial Tower - Litwick and Elgyem (100%, 1 SpAtk)

Note that there is a nurse on 3F of the Celestial Tower
SpDef

*

*Surf in Driftveil City - Frillish (100%, 1 SpDef)

Speed

*

*Surf on Route 3 - Basculin (100%, 2 Speed)

Note loads of places with Surf have 100% Basculin, but this one is reachable from a pokécenter without going trough tall grass.
(source)


text:
Q: How to find all files with a filename that ends with tilde I use Emacs and it sometimes makes backup for edited files. After a few days, I would have a lot of backup files whose name ends with a tilde.
Is there a way to find these files and delete them at once?
I tried this:
find "*" -type f -iname *~

But it doesn't work. I want the command to work recursively – something like ls -alR.

A: You can do something like that :
find . -type f -name '*~' -delete

If you want to delete also #*# file :
find . -type f -name '*~' -o -name '#*#' -delete

You can print all deleted files with "-print":
find . -type f -name '*~' -delete -print

A: You need to escape from the shell. And you need to specify search path, not *
find . -type f -name '*~'

To delete the files:
find . -type f -name '*~' -exec rm -f '{}' \;

A: Another way is by using grep.
lnydex99uhc:javastuff user$ ls
Permutation.java VigenereCipher.java    VigenereCipher.java~

lnydex99uhc:javastuff user $ find . | grep .~$
./VigenereCipher.java~

You can also pass any command you want like this :
lnydex99uhc:javastuff zatef$ rm $(find . | grep .~$)


text:
Q: T4MVC showing list of files when stated as StaticFilesFolders in T4MVC .tt.settings.xm Folks, I am currently having an issue with displaying sensitive files while entering url for this folders in T4MVC. Inside of the settings file I configured it to generate links for my other part of the application. However, I do not want to show it to others, when they will enter somethig like {urlofwebsite}/TopSecretFolder. I need links that it creates, because I use them in my application, as js or content files.
Here you can see the folder for content files

How can I handle such problem? ExcludedStaticFileExtensions is not going to work, since it will just remove links that I use
I tried to remove it using ExcludedStaticFileExtensions, but it is just removing every link that I use for my project. I do want not to show my sensitive data and asking if somebody can explain


text:
Q: Adding unary operator to shunting yard algorithm I am creating a calculator-type program that parses an input into postfix notation and then evaluates the expression. It works for +,-,*,/, and ^, but I cannot get the unary - to work. Currently I am just trying to get the unary - to work at the start of an expression. I am using -5+2 to test the algorithm. The return result should be -3, however, I the program is returning -2. I have marked the 2 places in my code that I am trying to handle the unary - sign as
//-------------HERE IS WHERE I TRY TO HANDLE UNARY - as "u"----------------------------

I have been debugging all day and cannot figure out what is not working. Here is my code:
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Stack;

public class Calculator {

    public static void main(String[] args) {
        ArrayList test = new ArrayList();
        Scanner f = new Scanner(System.in);

        System.out.println("Type and equation, then press enter: ");

        String g = f.nextLine();

        test = inputToArrayList(g);

        for (int z = 0; z < test.size(); z++) {
            System.out.println(test.get(z));
        }

        System.out.println(calculateAnswer(test));
    }

    public static class SyntaxErrorException extends Exception {

        SyntaxErrorException(String message) {
            super(message);
        }
    }
    private static final Stack<Double> operandStack = new Stack<Double>();
    private static final Stack<String> operatorStack = new Stack<String>();
    private static final String OPERATORS = "+-/*%^()u";
    private static final String NONBRACES = "+-/*%^u";
    private static final int[] PRECEDENCE = {1, 1, 2, 2, 2, 3, 3, 3, 4};

    static ArrayList<String> charList = new ArrayList<String>();

    public static ArrayList inputToArrayList(String input) {
        StringBuilder strBuild = new StringBuilder();
        String infix = input.replace(" ", "");
        try {
            for (int i = 0; i < infix.length(); i++) {
                char c = infix.charAt(i);

                boolean isNumber = (c >= '0' && c <= '9');
//------------HERE IS WHERE I HANDLE - AT BEGINNING OF INPUT, SAVED AS U INSTEAD OF -   ----------
                if (i == 0 && c == '-') {
                    isNumber = true;
                    charList.add("u");
                    continue;
                }

                if (isNumber) {
                    strBuild.append(c);
                    if (i == infix.length() - 1) {
                        charList.add(strBuild.toString());
                        strBuild.delete(0, strBuild.length());
                    }
                } else if (c == '.') {
                    for (int j = 0; j < strBuild.length(); j++) {
                        if (strBuild.charAt(j) == '.') {
                            throw new SyntaxErrorException("You can't have two decimals in a number");
                        } else if (j == strBuild.length() - 1) {
                            strBuild.append(c);
                            j = (strBuild.length() + 1);
                        }
                    }
                    if (strBuild.length() == 0) {
                        strBuild.append(c);
                    }
                    if (i == infix.length() - 1) {
                        throw new SyntaxErrorException("You can't end your equation with a decimal");
                    }
                } else if (OPERATORS.indexOf(c) != -1) {
                    if (strBuild.length() != 0) {
                        charList.add(strBuild.toString());
                        strBuild.delete(0, strBuild.length());
                    }
                    strBuild.append(c);
                    charList.add(strBuild.toString());
                    strBuild.delete(0, strBuild.length());
                } else {
                    throw new SyntaxErrorException("Make sure your input only contains numbers, operators, or parantheses");
                }
            }

            int leftParenth = 0;
            int rightParenth = 0;

            for (int p = 0; p < charList.size(); p++) {
                String checkParenth = charList.get(p);

                switch (checkParenth) {
                    case "(":
                        leftParenth++;
                        break;
                    case ")":
                        rightParenth++;
                        break;
                    default: //do nothing
                        break;
                }

            }
            if (leftParenth != rightParenth) {
                throw new SyntaxErrorException("There is not an even number of parenthesis");
            }

            int parenthesis = 0;

            for (int f = 0; f < charList.size(); f++) {
                String awesome = charList.get(f);
                switch (awesome) {
                    case "(":
                        parenthesis++;
                        break;
                    case ")":
                        parenthesis--;
                        break;
                    default:
                        break;
                }
                if (parenthesis < 0) {
                    throw new SyntaxErrorException("Order of parenthesis is off");
                }
            }
            if (NONBRACES.contains(charList.get(charList.size() - 1))) {
                throw new SyntaxErrorException("The input can't end in an operator");
            }
            return charList;
        } catch (SyntaxErrorException ex) {
            System.out.println(ex);
            return charList;
        }
    }

    private static void processOperator(String op) {
        if (operatorStack.empty() || op.equals("(")) {
            operatorStack.push(op);
        } else {
            //peek the operator stack and
            //let topOp be the top operator.
            String topOp = operatorStack.peek();
            if (precedence(op) > precedence(topOp)) {
                if (!op.equals(")")) {
                    operatorStack.push(op);
                }
            } else {
                //Pop all stacked operators with equal
                // or higher precedence than op.
                while (!operatorStack.empty() && precedence(op) >= precedence(topOp)) {
 //-------------HERE IS WHERE I TRY TO HANDLE UNARY - and "u"----------------------------
                    if("u".equals(operatorStack.peek())) {
                        double right = operandStack.pop();
                        String unary = operatorStack.pop();
                        operandStack.push(right * (-1));
                        break;
                    }
                    double right = operandStack.pop();
                    double left = operandStack.pop();
                    String operator = operatorStack.pop();
                    switch (operator) {
                        case "+":
                            operandStack.push(left + right);
                            break;
                        case "-":
                            operandStack.push(left - right);
                            break;
                        case "*":
                            operandStack.push(left * right);
                            break;
                        case "/":
                            operandStack.push(left / right);
                            break;
                        case "%":
                            operandStack.push(left % right);
                            break;
                        case "^":
                            operandStack.push(Math.pow(left, right));
                            break;
                        default: //do nothing, but this should never happen
                            break;
                    }

                    if (topOp.equals("(")) {
                        //matching '(' popped - exit loop.
                        operandStack.push(left);
                        operandStack.push(right);
                        break;
                    }

                    if (!operatorStack.empty()) {
                        //reset topOp
                        topOp = operatorStack.peek();
                    }
                }

                //assert: Operator stack is empty or
                // current operator precedence > top of stack operator precedence.
            }
        }
    }

    public static String calculateAnswer(ArrayList<String> infix) {
        int p;
        for (p = 0; p < infix.size(); p++) {
            if (!OPERATORS.contains(infix.get(p))) {
                double listIndex = Double.parseDouble(infix.get(p));
                operandStack.push(listIndex);
            } else {
                processOperator(infix.get(p));
            }
        }
        if (p == infix.size()) {
            while (!operatorStack.empty()) {
                if ("u".equals(operatorStack.peek())) {

                    double right = operandStack.pop();
                    String unary = operatorStack.pop();
                    operandStack.push(right * (-1));
                    break;
                }
                double right = operandStack.pop();
                double left = operandStack.pop();
                String current = operatorStack.pop();
                switch (current) {
                    case "+":
                        operandStack.push(left + right);
                        break;
                    case "-":
                        operandStack.push(left - right);
                        break;
                    case "*":
                        operandStack.push(left * right);
                        break;
                    case "/":
                        operandStack.push(left / right);
                        break;
                    case "%":
                        operandStack.push(left % right);
                        break;
                    case "^":
                        operandStack.push(Math.pow(left, right));
                        break;
                    default: //do nothing, but this should never happen
                        break;
                }
            }
        }
        return String.valueOf(operandStack.pop());
    }

    private static int precedence(String op) {
        return PRECEDENCE[OPERATORS.indexOf(op)];
    }
}

A: This is not a trivial problem to solve. Dijkstra's original algorithm was explicitly for infix operators and mentions (but doesn't solve) prefix or postfix operators. So there is no simple extension that universally handles unary operators.
You will need to store additional state; specifically, the last type of element parsed and whether you are in a 'inverse' state. If it's an operator or nothing (i.e. start of expression) then '-' should toggle the 'inverse' state. Numbers should check and clear the inverse state and *= -1 if necessary before adding to stack. In other words, this becomes a way of handling the unary operator as a part of the constant rather than as an operator.
Note those two paragraphs aren't contradictory! The solution above won't handle 3 * -(5 + 2) because it's not treating the '-' as an operator but, rather, a flag used when numbers are read.
Also note that the 'proper' solution here is to not use the shunting yard algorithm when your operators aren't all infix. Use a proper grammar parser (e.g. Yacc).

A: If we look at the precedence tables of programming languages see Order of Operations (Wikipedia) we see that the unary operators have a different precedence level to the corresponding infix operator. The table generally looks like

*

*()  brackets

*+-! unary operators

**/  multiply and divide

*+-  infix addition and subtraction

*==  comparision operators

*=   assignment operators
so your program needs a way of distinguishing between unary and binary operators with the same symbol. In Dijkstra work he gives unary minus the same precedence as * and /, but does not address how the parser distinguishes unary and binary cases.
I've successfully followed the technique in Parsing Expressions by Recursive Descent this is very similar to the shunting yard algorithm, but with a bit of recursion to handle the brackets.
We can divide our syntax into two parts: prefix-suffix expressions, P, which includes numbers, identified, unary operators (both as prefix and as suffixes), and bracketed expressions. Full expressions, E, are a bunch of P's separated by binary operators.
P :: number
   | identifier i.e. varible name
   | -P  prefix operator followed by a P
   | ( E ) an E in brackets

The expression E will be
E :: P
  | P + E | P - E | P * E | P / E

i.e. a sequence of P's with binary operators between them say P+P+P-P.
For the E part you use a shunting yard but for P there is a bit of recursion. His algorithm is
Eparser is
   var operators : Stack of Operator := empty
   var operands : Stack of Tree := empty
   push( operators, sentinel )
   E( operators, operands )
   expect( end )
   return top( operands )

E( operators, operands ) is
    P( operators, operands )
    while next is a binary operator
       pushOperator( binary(next), operators, operands )
       consume
       P( operators, operands )
    while top(operators) not= sentinel
       popOperator( operators, operands )

P( operators, operands ) is
    if next is a v
         push( operands, mkLeaf( v ) )
         consume
    else if next = "("
         consume
         push( operators, sentinel )   -- pushes sentinel
         E( operators, operands )      -- note recursion
         expect( ")" )                 -- remove bracket from input
         pop( operators )              -- pops sentinel
    else if next is a unary operator
         pushOperator( unary(next), operators, operands )
         consume
         P( operators, operands )
    else
         error

popOperator( operators, operands ) is
   if top(operators) is binary
        const t1 := pop( operands )
        const t0 := pop( operands )
        push( operands, mkNode( pop(operators), t0, t1 ) )
   else
        push( operands, mkNode( pop(operators), pop(operands) ) )

pushOperator( op, operators, operands ) is
    while top(operators) > op
       popOperator( operators, operands )
    push( op, operators )

Note there is a recursive step when an open brackets is encountered. First sentinel is pushed onto the operator stack, this is some special operator used to prevent too many operators being poped. The code then calls E again. E will run until the closing brace is discovered. When E ends all the operators up to the first sentinel are popped from the stack.


text:
Q: How to auto-create a makefile in the same directory as i create a Latex file? When I create a .tex file using vim I get a nice template from having
autocmd BufNewFile *.tex 0r $HOME/.vim/templates/skeleton.tex

in my .vimrc. I also have a makefile-template in my home directory, but this one I have to manually copy to where the .tex file is. In a Linux environment, how can I auto-copy or auto-generate the makefile at the same time as I create a .tex file?

A: The normal ex command to do this would be
:!cp $HOME/.vim/templates/skeleton.makefile %:p:h

So you just need to add another autocmd (which will execute after the first)
autocmd BufNewFile *.tex silent !cp $HOME/.vim/templates/skeleton.makefile %:p:h

(the silent simply prevents the copy command from being printed on execution).

A: The portable answer would not use cp (which may overwrite a preexisting makefile) but the vim functions readfile() and writefile().
To trigger it, the best thing would be to define and execute a function that loads the first skeleton, and creates the Makefile on the fly:
" untested code
"
function! s:NewTeXPlusMakefile()
  let where = expand('%:p:h')
  " see mu-template's fork for a more advanced way to find template-files
  let skeletons_path = globpath(&rtp, 'templates')

  " the current .tex file
  let lines = readfile(skeletons_path.'/skeleton.tex')
  call setline(1, lines)

  " the Makefile, that MUST not be overwritten when it already exists!
  let makefile = where.'/Makefile'
  if ! filereadable(makefile)
    let lines = readfile(skeletons_path.'/skeleton.makefile')
    call writefile(lines, makefile )
  endif
endfunction

augroup LaTeXTemplates
  au!
  au BufNewFile *.tex call s:NewTeXPlusMakefile()
augroup END


text:
Q: Why is processEvents() needed to get QThread to work? Below is my code for listing all the sub-directories of a directory. I'm using it to understand QThread and signal and slots in PySide. The problem is, when I'm not using Qtcore.QApplication.processEvents() in the scan() method of the Main class, the code does not work. Is the event-loop not already running?
import sys
import os
import time
from PySide import QtGui, QtCore

class Scanner(QtCore.QObject):
    folderFound = QtCore.Signal(str)
    done = QtCore.Signal()
    def __init__(self, path):
        super(Scanner, self).__init__()
        self.path = path

    @QtCore.Slot()
    def scan(self):
        for folder in os.listdir(self.path):
            time.sleep(1)
            self.folderFound.emit(folder)

class Main(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.resize(420,130)
        self.setWindowTitle('Threads')
        self.lyt = QtGui.QVBoxLayout()
        self.setLayout(self.lyt)

        self.topLyt = QtGui.QHBoxLayout()
        self.lyt.addLayout(self.topLyt)
        self.scanBtn = QtGui.QPushButton('Scan')
        self.scanBtn.clicked.connect(self.scan)
        self.clearBtn = QtGui.QPushButton('Clear')
        self.topLyt.addWidget(self.scanBtn)
        self.topLyt.addWidget(self.clearBtn)

        self.folders = list()

        self.show()

    def scan(self):
        self.th = QtCore.QThread()
        scanner = Scanner(r"D:\\")
        scanner.moveToThread(self.th)

        scanner.folderFound.connect(self.addFolder)
        scanner.done.connect(scanner.deleteLater)
        scanner.done.connect(self.quit)

        self.th.started.connect(scanner.scan)
        self.th.start()

        QtCore.QApplication.processEvents()

    @QtCore.Slot()
    def addFolder(self, folder):
        lbl = QtGui.QLabel(folder)
        self.folders.append(lbl)

        self.lyt.addWidget(lbl)

    @QtCore.Slot()
    def quit(self):
        self.th.quit()
        self.th.wait()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    main = Main()
    app.exec_()

A: It is a pure fluke that your example works at all.
When you attempt to call QtCore.QApplication.processEvents(), a NameError will be raised, because the QApplication class is actually in the QtGui module, not the QtCore module. However, raising the exception has the side-effect of preventing your scanner object from being garbage-collected, and so the thread appears to run normally.
The correct way to fix your code is to keep a reference to the scanner object, and get rid of the processEvents line, which is not needed:
def scan(self):
    self.th = QtCore.QThread()
    # keep a reference to the scanner
    self.scanner = Scanner(r"D:\\")
    self.scanner.moveToThread(self.th)

    self.scanner.folderFound.connect(self.addFolder)
    self.scanner.done.connect(self.scanner.deleteLater)
    self.scanner.done.connect(self.quit)

    self.th.started.connect(self.scanner.scan)
    self.th.start()

The rest of your code is okay, and the example will now work as expected.

A: Event loop is not something that runs behind your back. You're always the one who has to run it. A thread cannot be doing two things at once: if your code is the locus of control, then obviously the event loop isn't! You need to return from your code to the event loop, and make sure that your code was called from the event loop. Any sort of a UI signal, networking event, or timeout is invoked from the event loop, so most likely your code already has the event loop on the call stack. To keep the loop spinning, you have to return to it, though.
Never use processEvents - instead, invert the control, so that the event loop calls into your code, and then you perform a chunk of work, and finally return back to the event loop.
The idiom for "keep my code working from event loop" is a zero-duration timer. The callable that performs the work is attached to the timeout signal.


text:
Q: What happens if an array is declared of different sizes at each iteration in a loop? See the following program
I think it is different from declaring variables inside loop, because they occupy constant space, so once they are allocated it will be enough, but in case of array, size of array is variable(in the below program, intentionally size is kept small) what if next size of redeclared array is large, or due to size some issue, will it redeclare array at some other location?.By playing with it, i observed that every redeclared array was constructed by extending same memory of previously declared array.Is there any possibility that it can't be extended for newly declared array?
#include<stdio.h>

int main(){
    int n = 5;
    while(5){
        int a[n];
        for(int i = 0; i < n ; ++i){
            a[i] = 0;
        }
        f[n--] = a;
        if(n == 0){
            break;
        }
    }

So here Array a[n] is being declared multiple times of different sizes,

*

*What happens to previous declaration?

Please explain what is happening in this program, why is it printing zero as content?
#include<stdio.h>
int* f[10];
int main(void) {
    int n = 5;
    while(5){
        int a[n];
        for(int i = 0; i < n ; ++i){
            a[i] = 5;
        }
        f[n--] = a;
        if(n == 0) break;
    }
    printf("\ndone\n");

    while(++n < 5){
        for(int i = 0; i < n; ++i){
            printf("\nat size = %-3d : base address = %-7d : a[%d] = %-4d at"
                   "address = %-7d ", n , f[n],i, *(f[n]+i), (f[n]+i));
        }
        printf("\n\n");
    }
    return 0;
}

A: In theory, the variable declared inside a scope (loop, if/else, function, switch) are destroyed/created when reaching the end of a scope or starting.
In practice, the code generated by the compiler will cause the function reuse the same memory area for the loop variable. So you could see remains from previous loop iterations, but you shouldn't rely on those, it is just that memory does not get wiped.
So, when a variable is declared inside a scope ({ }), consider it to be a new variable when reaching the start of the scope (i.e. it needs to be assigned a value inside the scope before being read). But trust the compiler to optimize the "creation/destruction" of the variable, as it will just reuse memory of variables from other scopes/iterations that are no longer accessible.


text:
Q: Steelbrick - how to add product options when selecting product bundle in Apex In steelbrick, I'm creating a quote and quote line through Apex.
//create quote line item
SBQQ__QuoteLine__c qli = new SBQQ__QuoteLine__c();
qli.SBQQ__Quote__c = quote.Id;
qli.SBQQ__Bundle__c = True;
qli.SBQQ__Quantity__c = 1;

qli.SBQQ__ListPrice__c = selectedProd.iS_Minimum_Total_Cost__c;
qli.SBQQ__Product__c = prod2Id;

insert qli;

But if my selected product (Product A) is a bundle and it is linked to any options (Product B, C, D), how do I make Steelbrick add automatically all the related options as separated quote line items.

A: I don't think there is any need of checking the API. What you can do is,
    1) Query the Product Option object and see if the product you are trying to add as the line item is a Configured Product on any of the options. Save it in a map.
map<ProductId,ProductOptions> mapProdOptions
    2) Then, before adding the product as QLI, check if the map.get(ConfiguredProdId) is blank and if it is NOT blank, get all the Optional SKU products on the product option and create Quote Line Items for them along with the main product

A: Instead of doing manually by writing your own code, check with the steelbrick (which is now Salesforce CPQ), Is there any API available which you can use here. where you can configure the Bundle product selection.
If you are configuring a bundle, there are various pricing constraints and rules which are based on that particular bundle product and subsequently on its option products. so rather then you trying to achieve all these by your own, can you check with CPQ team first. As far as I know there are some ready to use API's available.
Take a look on below reference, but again check with CPQ officials for better understanding.
https://community.steelbrick.com/t5/tkb/articleprintpage/tkb-id/developerguidebook/article-id/7


text:
Q: Docker install version Docker download button1
Docker download button2, 3
I wonder whether the docker version, which is downloaded when the "Get Docker"button is clicked, is the stable version or the edge version.
After reading the documentation, there are two versions, the stable version and the edge version, but there was no selection when clicking the "Get Docker"button.

A: Download links in release notes. Stable releases here
https://docs.docker.com/docker-for-mac/release-notes/


text:
Q: MariaDB unexpected token near returning so I set up a new MariaDB Database and tried to insert some data into a table with this code:
INSERT INTO address VALUES (default, 'Test', 'Test', 'Test', 'Test', 'Test') RETURNING id;

This is my table structure:

The error I am getting is telling me that there is an unexpected token near "Returning id" and I really don't have any idea, what exactly is wrong here.
I am using: 10.4.22-MariaDB - mariadb.org binary distribution.
Can anyone help me out?
Thank you in advance.


text:
Q: Excel Сложное условие
Есть два столбца с числами A и B. Подскажите пожалуйста, каким образом можно написать формулу в столбце C, чтобы в ячейке проставлялась буква по условиям из таблицы?

A: В случае если не хочешь хард кодить много ИЛИ :
1) Сделать группы в матрице подстановок ( 0-4 ,0-8) (нужно только для наглядности)

2) Добавить колонки для группы A и B на листе с данными ( через если) ( 0-4 ,0-8)
 и так далее
3) Использовать ИНДЕКС по матрице подстановок и доп колонками ( смещения)

A: Для A
=ЕСЛИ(ИЛИ(И(A1<3;B1>2);И(A1<1;B1>1,8;B1<=2));"A";0)

Для B
=ЕСЛИ(ИЛИ(И(A1>=3;A1<5;B1>2);И(A1>=1;A1<5;B1>1,8;B1<=2);И(A1<2;B1>1,1;B1<=1,8));"B";0)

Для C
=ЕСЛИ(ИЛИ(И(A1<9;A1>=5;B1>1,8);И(A1>=2;A1<5;B1>1,1;B1<=1,8);И(A1<2;B1>0,5;B1<=1,1));"C";0)

Для D
=ЕСЛИ(ИЛИ(И(A1>=9;B1>-2);И(A1>=9;B1<=-2);И(A1>=5;A1<9;B1<=1,8;B1>-2);И(A1>=3;A1<5;B1<=1,1;B1>-2);И(A1>=2;A1<3;B1<=1,1;B1>0);И(A1<2;B1<=0,5;B1>0));"D";0)

Для E
=ЕСЛИ(ИЛИ(И(A1>=2;A1<3;B1<=0;B1>-2);И(A1>=3;A1<9;B1<=-2));"E";0)

Для F
=ЕСЛИ(ИЛИ(И(A1<2;B1<=0;B1>-2);И(A1<3;B1<=-2));"F";0)

Собираем все в одно выражение:
=ЕСЛИ(ИЛИ(И(A1<3;B1>2);И(A1<1;B1>1,8;B1<=2));"A";=ЕСЛИ(ИЛИ(И(A1>=3;A1<5;B1>2);И(A1>=1;A1<5;B1>1,8;B1<=2);И(A1<2;B1>1,1;B1<=1,8));"B";=ЕСЛИ(ИЛИ(И(A1<9;A1>=5;B1>1,8);И(A1>=2;A1<5;B1>1,1;B1<=1,8);И(A1<2;B1>0,5;B1<=1,1));"C";=ЕСЛИ(ИЛИ(И(A1>=9;B1>-2);И(A1>=9;B1<=-2);И(A1>=5;A1<9;B1<=1,8;B1>-2);И(A1>=3;A1<5;B1<=1,1;B1>-2);И(A1>=2;A1<3;B1<=1,1;B1>0);И(A1<2;B1<=0,5;B1>0));"D";=ЕСЛИ(ИЛИ(И(A1>=2;A1<3;B1<=0;B1>-2);И(A1>=3;A1<9;B1<=-2));"E";=ЕСЛИ(ИЛИ(И(A1<2;B1<=0;B1>-2);И(A1<3;B1<=-2));"F";0))))))


text:
Q: An application of contraction mapping theorem Suppose $\mathbb{R}$ is equipped with the standard metric and I want to show that the equation
$$
3x^3-3x^2+x-2=0
$$
has a unique root $c\geq1$. The equation is equivalent to
$$
f(x)=x,
$$
where $f(x)=1+\frac{1}{1+3x^2}$, so by showing that $f:[1,+\infty)\to \mathbb{R}$ is a contraction mapping I can prove the uniqueness of the root $c$, which will be the fixed point of $f$. Let $x,y\geq 1$, then
$$
|f(x)-f(y)|=\left|\frac{1}{1+3x^2}-\frac{1}{1+3y^2} \right|=3|x-y|\left| \frac{x+y}{(1+3x^2)(1+3y^2)}\right|
$$
So I guess I need to find a bound on $\left| \frac{x+y}{(1+3x^2)(1+3y^2)}\right|$, this is where I am stuck.

A: Note that $x^2-2x+1=(x-1)^2\ge0$, hence $x^2+1\ge2x$ and similarly $y^2+1\ge2y$, hence indeed (very wastefully)
$$\begin{align}(1+3x^2)(1+3y^2)&=9x^2y^2+3x^2+3y^2+1\\&\ge 9+3x^2+3y^2+1\\&=3(x^2+1)+3(y^2+1)+3\\&\ge 6x+6y+3\\&>6( x+y)  \end{align}$$
and you get a contraction factor of $\frac12$.

A: I think it might be easier to use the mean value theorem: $$f(x)-f(y)=(x-y)f'(c)$$ for some $c$ between $x$ and $y$, and hence $c\geq 1$.
Then you just need to find a bound on $|f'(c)|$.


text:
Q: there is no Window object in blank page in Chrome 16 I have this simple script in my bookmark bar.
javascript:window.open("https://mybugs.com/show_bug.cgi?id="+window.prompt('bug number?'),'_blank')

I used it as a short link to one page which need a parameter. It worked well before. But it broken after I upgrade to Chrome 16. Looks like there is no Window object in a blank page.
How to handle this?

A: There is a DOMWindow object (testable by creating a new tab, opening the console and typing "window"). However there has been a deliberate change in security policy recently, to:

"Protect sensistive chrome: and chrome-extension: schemes as not being able to be manipulated by bookmarklets and javascript: URLs typed into the omnibox."

See http://src.chromium.org/viewvc/chrome?view=rev&revision=98849 for details.


text:
Q: How should my Java JAR main class path look like? So I have Test.jar. It's directories look like:
META-INF/MANIFEST.MF
Test/src/test/Test.java
             /MainFrame.java
             /MainPanel.java
             /image.png

And my mainfest file looks like:
Manifest-Version: 1.0
Created-By: 1.7.0_13 (Oracle Corporation)
Main-Class: test.Test

When launching from command line (java -jar Test.jar) i get such error: could not find or load main class test.Test. How to solve it? I know it's problem with Main-Class line in manifest but I dont know how should path look like..

A: thats because your jar apparently contains java source files and not compiled java class files.
your jar layout should be
META-INF/MANIFEST.MF
/test/Test.class
     /MainFrame.class
     /MainPanel.class
     /image.png

your manifest is fine. you should compile your source code files (*.java) to produce *.class files and package those into your jar.


text:
Q: R Shiny: plot with dynamical size I wanna have a plot with dynamic size and all should happen in the shinyUI.
Here is my code:
   shinyUI{
      sidebarPanel(
            sliderInput("width", "Plot Width", min = 10, max = 20, value = 15),
            sliderInput("height", "Plot Height", min = 10, max = 20, value = 15)
       )

        mainPanel(
            plotOutput("plot", width="15cm", height="15cm")
        )
    }

I set "15cm" only to see the plot.
I tried different methods to take the data from the sliderInputs and bring it to the plotOutput. I tried "input.height", "input$heigt" but nothing worked.

A: You must use the inputs in the server side, for example here is one solution :
And the unit of the width and height must be a valid CSS unit, i'm not sure that "cm" is valid, use "%" or "px" (or an int, it will be coerced to a string with "px" at the end)
library(shiny)

runApp(list(
    ui = pageWithSidebar(
    headerPanel("Test"),
    sidebarPanel(
            sliderInput("width", "Plot Width (%)", min = 0, max = 100, value = 100),
            sliderInput("height", "Plot Height (px)", min = 0, max = 400, value = 400)
       ),
        mainPanel(
            uiOutput("plot.ui")
        )
    ),
    server = function(input, output, session) {

        output$plot.ui <- renderUI({
            plotOutput("plot", width = paste0(input$width, "%"), height = input$height)
        })

        output$plot <- renderPlot({
            plot(1:10)
        })
    }
))


text:
Q: Page Design Distortion on Navigation Back ListView Xamarin Forms Basically i have the following code on my ItemTemplate
<Frame BorderColor="{Binding Path=BindingContext.ColorTwo, Source={x:Reference Name=AuctionListViewXaml}}"  BackgroundColor="{Binding Path=BindingContext.ColorOne, Source={x:Reference Name=AuctionListViewXaml}}" Padding="2" HeightRequest="{Binding Path=LeilaoHeight, Source={x:Reference Name=AuctionListViewXaml}}" CornerRadius="0">
    <Grid HorizontalOptions="FillAndExpand">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="2*"/>
            <ColumnDefinition Width="5*"/>
        </Grid.ColumnDefinitions>
        <StackLayout Grid.Column="0" Spacing="0" Margin="0,0,0,0">
            <Image VerticalOptions="Center" HorizontalOptions="Center" Source="{Binding ProdutoImagem}"  Aspect="AspectFit" />
        </StackLayout>
        <Grid Grid.Column="1" ColumnSpacing="0" RowSpacing="0" HorizontalOptions="FillAndExpand" Margin="0,0,5,0">
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <!--<RowDefinition Height="*"/>-->
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="auto"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <Label Grid.Row="0" Grid.Column="0" Text="{Binding TextName}" HorizontalOptions="Center" HorizontalTextAlignment="Center" VerticalOptions="Center" VerticalTextAlignment="Center"  TextColor="{Binding Path=BindingContext.TextColor, Source={x:Reference Name=AuctionListViewXaml}}"/>
            <Label Grid.Row="0" Grid.Column="1" Text="{Binding Nome}" HorizontalOptions="Center" HorizontalTextAlignment="Center" VerticalOptions="Center" VerticalTextAlignment="Center"  TextColor="{Binding Path=BindingContext.TextColor, Source={x:Reference Name=AuctionListViewXaml}}"/>
            <BoxView Color="{Binding Path=BindingContext.ColorTwo, Source={x:Reference Name=AuctionListViewXaml}}" Grid.Row="0" Grid.Column="0" HorizontalOptions="FillAndExpand" VerticalOptions="End" HeightRequest="1"/>
            <BoxView Color="{Binding Path=BindingContext.ColorTwo, Source={x:Reference Name=AuctionListViewXaml}}" Grid.Row="0" Grid.Column="1" HorizontalOptions="FillAndExpand" VerticalOptions="End" HeightRequest="1"/>
            <Label Grid.Row="1" Grid.Column="0" Text="{Binding TextPrize}" HorizontalOptions="Center" HorizontalTextAlignment="Center" VerticalOptions="Center" VerticalTextAlignment="Center"  TextColor="{Binding Path=BindingContext.TextColor, Source={x:Reference Name=AuctionListViewXaml}}"/>
            <Label Grid.Row="1" Grid.Column="1" Text="{Binding ProdutoNome}" HorizontalOptions="Center" HorizontalTextAlignment="Center" VerticalOptions="Center" VerticalTextAlignment="Center"  TextColor="{Binding Path=BindingContext.TextColor, Source={x:Reference Name=AuctionListViewXaml}}"/>
            <BoxView Color="{Binding Path=BindingContext.ColorTwo, Source={x:Reference Name=AuctionListViewXaml}}" Grid.Row="1" Grid.Column="0" HorizontalOptions="FillAndExpand" VerticalOptions="End" HeightRequest="1"/>
            <BoxView Color="{Binding Path=BindingContext.ColorTwo, Source={x:Reference Name=AuctionListViewXaml}}" Grid.Row="1" Grid.Column="1" HorizontalOptions="FillAndExpand" VerticalOptions="End" HeightRequest="1"/>
            <Label Grid.Row="2" Grid.Column="0" Text="{Binding TextMinimumBid}" HorizontalOptions="Center" HorizontalTextAlignment="Center" VerticalOptions="Center" VerticalTextAlignment="Center"  TextColor="{Binding Path=BindingContext.TextColor, Source={x:Reference Name=AuctionListViewXaml}}"/>
            <Label Grid.Row="2" Grid.Column="1" Text="{Binding QuantidadePontos}" HorizontalOptions="Center" HorizontalTextAlignment="Center" VerticalOptions="Center" VerticalTextAlignment="Center"  TextColor="{Binding Path=BindingContext.TextColor, Source={x:Reference Name=AuctionListViewXaml}}"/>
            <!--<Label Grid.Row="3" Grid.Column="0" Text="{Binding TextLastBid}"  VerticalOptions="CenterAndExpand" VerticalTextAlignment="Center"  TextColor="{Binding Path=BindingContext.TextColor, Source={x:Reference Name=AuctionListViewXaml}}"/>
            <Label Grid.Row="3" Grid.Column="1" Text="{Binding UltimoLance}"  VerticalOptions="CenterAndExpand" VerticalTextAlignment="Center"  TextColor="{Binding Path=BindingContext.TextColor, Source={x:Reference Name=AuctionListViewXaml}}"/> -->
            <BoxView Color="{Binding Path=BindingContext.ColorTwo, Source={x:Reference Name=AuctionListViewXaml}}" Grid.Row="2" Grid.Column="0" HorizontalOptions="FillAndExpand" VerticalOptions="End" HeightRequest="1"/>
            <BoxView Color="{Binding Path=BindingContext.ColorTwo, Source={x:Reference Name=AuctionListViewXaml}}" Grid.Row="2" Grid.Column="1" HorizontalOptions="FillAndExpand" VerticalOptions="End" HeightRequest="1"/>
            <Label Grid.Row="3" Grid.Column="0" Text="{Binding TextExpiration}" HorizontalOptions="Center" HorizontalTextAlignment="Center" VerticalOptions="Center" VerticalTextAlignment="Center"  TextColor="{Binding Path=BindingContext.TextColor, Source={x:Reference Name=AuctionListViewXaml}}"/>
            <Label Grid.Row="3" Grid.Column="1" Text="{Binding TempoRestante, Mode=TwoWay}" HorizontalOptions="Center" HorizontalTextAlignment="Center" VerticalOptions="Center"  TextColor="{Binding Path=BindingContext.TextColor, Source={x:Reference Name=AuctionListViewXaml}}"/>
        </Grid>
    </Grid>
</Frame>

which translates to the items in the ListView below

And whenever i navigate forward to another page, if i press back the entire view gets distorted
This one below is a mild example of distortion, check for the text on the second card in the listview, there are words missing but the underlying layout size stays the same, if the screen is smaller it will cut everything so much more.

Has anyone ever had troubles with this before? It happens on the following cases:
I navigate back from another screen.
The object is added to the list from another list.
I've tried loads of things and it consistently happens on Android, iOS is bug free as far as i know.
Xamarin Forms 3.4.0 the listview I'm using is the syncfusion listview.
Edit: also happening in the xamarin list view
ContentPage:
using System;
using System.Collections.Generic;
using System.Timers;
using System.Collections.ObjectModel;
using System.Linq;
using AppAlice.Localization;
using AppAlice.Models;
using AppAlice.UiModels;
using AppAlice.ViewModels;
using Syncfusion.ListView.XForms;
using Xamarin.Forms;

namespace AppAlice.Views
{
    public partial class AuctionListView : ContentPage
    {
        public AuctionListViewModel viewModel;
        MainPage RootPage { get => Application.Current.MainPage as MainPage; }

        public double ScreenWidth { get; set; } = App.ScreenWidth;
        public double ScreenHeight { get; set; } = App.ScreenHeight;
        public double LeilaoHeight { get; set; } = App.ScreenWidth / 4;

        public AuctionListView()
        {
            Title = AppResources.ResourceManager.GetString("AuctionListViewTitle");
            BindingContext = viewModel = new AuctionListViewModel();
            LeilaoHeight = App.ScreenWidth / 4;
            InitializeComponent();
            activatedButton.Text = AppResources.Active;
            availableButton.WidthRequest = activatedButton.WidthRequest = ScreenWidth / 2;
            availableButton.Text = AppResources.Available;
            HelloLabel.Text = AppResources.Hello;
            SaldoLabel.Text = AppResources.Balance + ": ";
            //XpLabel.Text = AppResources.PointsInBids;
            AuctionLabel.Text = AppResources.PointsAuction;
        }

        private void availableButton_Pressed(object sender, EventArgs e)
        {
            activatedListView.IsVisible = false;
            activatedButton.BackgroundColor = App.ColorThree;
            availableListView.IsVisible = true;
            availableButton.BackgroundColor = App.ColorTwo;

        }

        private void activatedButton_Pressed(object sender, EventArgs e)
        {
            availableListView.IsVisible = false;
            availableButton.BackgroundColor = App.ColorThree;
            activatedListView.IsVisible = true;
            activatedButton.BackgroundColor = App.ColorTwo;

        }

        async void Handle_ItemTapped(object sender, Xamarin.Forms.ItemTappedEventArgs e)
        {
            Leilao leilao = e.Item as Leilao;
            await Navigation.PushModalAsync(new NavigationPage(new AuctionPage(leilao)) { BarBackgroundColor = App.ColorTwo, BarTextColor = App.TextColor });

        }

        protected override void OnAppearing()
        {
            base.OnAppearing();
            if (viewModel.OnAppearingCommand.CanExecute(null))
                viewModel.OnAppearingCommand.Execute(null);
        }

        protected override void OnDisappearing()
        {
            base.OnDisappearing();
            if (viewModel.OnDissappearingCommand.CanExecute(null))
                viewModel.OnDissappearingCommand.Execute(null);
        }

        protected override bool OnBackButtonPressed()
        {
            RootPage.NavigateFromMenu((int)MenuItemType.Browse);
            return true;
        }

    }
}

Relevant ViewModel Methods:
private void OnDisappearing()
{
    Timer.Stop();
}

private async Task OnAppearing()
        {
            AvailableAuctions.Clear();
            ActivatedAuctions.Clear();
            OnPropertyChanged("AvailableAuctions");
            OnPropertyChanged("ActivatedAuctions");
            Timer.Start();
            Timer.Interval = 500; // 0.1 seconds
            await Task.Run(async () =>
            {
                try
                {
                    Perfil = CallsWrapper.GetUser();
                    Nome = Perfil.Nome;
                    Saldo = Perfil.PontuacaoAtual;
                    Xp = Perfil.PontuacaoHistorico;
                    Imagem = Perfil.Foto.Url;

                    if (CallsWrapper.IsOnline())
                    {
                        LeilaoDtoDataStore leilaoDtoDataStore = new LeilaoDtoDataStore(Perfil.Id);
                        var leiloes = await leilaoDtoDataStore.GetItemsAsync();

                        foreach (var l in leiloes.Where(i => i.MeuUltimoLance == 0)) AvailableAuctions.Add(l);
                        foreach (var l in leiloes.Where(i => i.MeuUltimoLance != 0)) ActivatedAuctions.Add(l);
                        //AvailableAuctions = new ObservableCollection<Leilao>(leiloes.Where(i => i.MeuUltimoLance == 0));
                        //ActivatedAuctions = new ObservableCollection<Leilao>(leiloes.Where(i => i.MeuUltimoLance != 0));
                    }
                    else
                    {
                        //TODO: TEXTO FALANDO QUE NAO ESTA ONLINE
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Data);
                    Console.WriteLine(e.Message);
                    Console.WriteLine(e.StackTrace);
                    Perfil = new PerfilClienteDto();
                    Nome = Perfil.Nome;
                    Saldo = Perfil.PontuacaoAtual;
                    Xp = Perfil.PontuacaoHistorico;

                }
                finally

                {
                    Timer.Elapsed += Timer_Elapsed;
                    OnPropertyChanged("Perfil");
                    OnPropertyChanged("Nome");
                    OnPropertyChanged("Saldo");
                    OnPropertyChanged("Xp");
                    OnPropertyChanged("Imagem");
                }
            });
        }

private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            Device.BeginInvokeOnMainThread(() =>
            {
                foreach (Leilao s in ActivatedAuctions)
                {
                    s.Temporizador = getTimeLeft(s.DataEncerramento);
                    if (s.Temporizador.TotalDays > 0)
                    {
                        if (s.Temporizador.TotalDays > 1 && s.Temporizador.TotalDays < 2)
                            s.TempoRestante = string.Format("{0} Dia", (int)s.Temporizador.TotalDays);
                        else
                        {
                            s.TempoRestante = string.Format("{0} Dias", (int)s.Temporizador.TotalDays);
                        }
                    }
                    else
                    {
                        s.TempoRestante = string.Format("{0}h {1}m {2}s", (int)s.Temporizador.TotalHours, s.Temporizador.Minutes, s.Temporizador.Seconds);
                    }
                    s.OnPropertyChanged("TempoRestante");
                }
                foreach (Leilao s in AvailableAuctions)
                {
                    s.Temporizador = getTimeLeft(s.DataEncerramento);
                    if(s.Temporizador.TotalDays > 0)
                    {
                        if (s.Temporizador.TotalDays > 1 && s.Temporizador.TotalDays < 2)
                            s.TempoRestante = string.Format("{0} Dia", (int)s.Temporizador.TotalDays);
                        else
                        {
                            s.TempoRestante = string.Format("{0} Dias", (int)s.Temporizador.TotalDays);
                        }
                    }
                    else
                    {
                        s.TempoRestante = string.Format("{0}h {1}m {2}s", (int)s.Temporizador.TotalHours, s.Temporizador.Minutes, s.Temporizador.Seconds);
                    }
                    s.OnPropertyChanged("TempoRestante");
                }
                //OnPropertyChanged("AvailableAuctions");
                //OnPropertyChanged("ActivatedAuctions");
            });
        }


text:
Q: Add delimter to data posted to form The post data is separated by commas. I need to add a delimiter (concatenate) such as '|' to all the input fields (text, textarea, select, etc) to the post data submitted by a form, but I do not want to change the value of the fields themselves in the form.
<form action="somepage.php" method="post">

<div class"line">
<input type="text" class="sometext" name="desc" />
</div>

<div class"line">
<input type="text" class="sometext" name="desc" />
</div>

<div class"line">
<input type="text" class="sometext" name="desc" />
</div>

<input type="submit" id="submitbutton" />

</form>

I tried the below code, but it changes the data in the form itself
$(document).on('click', '#submitbutton', function(){
   $('.sometext').each(function(){
      var descVal=''
      var descVal = $('.sometext').val() + '|';
      $(this).val(descVal);
   });
});

A: When using $('.sometext').val() you're not specifying exactly which element you want the value of. Change:
var descVal = $('.sometext').val() + '|';

To:
var descVal = $(this).val() + '|';

Alternatively you can simply use:
$(this).val(this.value + '|');

$(document).on('click', '#submitbutton', function(){
   $('.sometext').each(function(){
        $(this).val(this.value + '|');
   });
});


text:
Q: Двухуровневое выпадающее меню Как из этого сделать двухуровневое меню?
<label>Адрес </label>
<select>
<option>район 1</option>
<option>район 2</option>
<option>район 3</option>
<option>район 4</option>
</select>

A: <sarcasm>Как из списка сделать меню?</sarcasm>
Если вы хотите так:
Район 1
--улица 1
--улица 2
Район 2
--улица 3
--улица 4
То и добавляйте в текст пункта маркеры. Если вы хотите, чтобы пользователь не мог выбрать пункт "Район 1" обработайте либо событие "onChange" у select. Либо делайте 2 выпадающих списка аякс и пр плюшки.
A: Посмотрите в сторону optgroup.


text:
Q: Getting x11 to start on ereader already running a Linux Distro independently on sdcard I burn a customized recovery image onto a sdcard that gives me ssh and adb access over wifi. I mount the sdcard and successfully get into the Linux Distro image.
I enter these commands over adb on the device and x11 will not show up. I've already installed the drivers into the linux distro.

startx -- tty01 -sharevts -novtswitch
while true; do echo 1 > /sys/class/graphics/fb0/epd_refresh; sleep 2;
  done & xterm

It throws error saying display is not set. I try to set display with set DISPLAY: 0 or set DISPLAY: 1 or set DISPLAY :tty01
Doesn't work.

root@localhost:~# startx
Fatal server error: Can't read lock file /tmp/.X0-lock
Please consult the The X.Org Foundation support      at
  http://wiki.x.org  for help.   ddxSigGiveUp: Closing log
giving up. xinit:  Stale NFS file handle (errno 116):  unable to
  connect to X server xinit:  No such process (errno 3):  Server error.

Here are some links of instructions that I followed.
X running on nook touch(independent without stock os)
simple touch tweaked to run linux distros
UPDATE
Some information has been deleted as it was no longer needed and the problem has been fixed, but startx is still being difficult to launch.
I have managed to get one step closer by running fsck.ext2 -fyc /sdcard/ubuntu.img  while running the aforementioned startx command these errors popped up.
What should I do now with this information?
Here, I try to find the device files for the screen. I look into graphics and fb0 is beyond my knowledge.  (NOTE THIS IS THE ANDROID's DEVICE DIRECTORY)
The first screenshot of the ubuntu's /dev folder and the 2nd is android's


text:
Q: Динамический массив (Java) Задача : Массив состоит из натуральных чисел.
Количество элементов неизвестно,но если i-тый элемент массива будет == 0,то чтение элементов с клавиатуры прекращается и выводится максимальный элемент массива.
Предисловие : Не работал раньше с динамическим массивом ListArray
Мой код :
int rez = 1;
int max=0;
ArrayList<Integer> b = new ArrayList<>();
b.ensureCapacity(100);
System.out.println("Введите элементы");
while(!(rez==0)){
 int j;
    for (j = 0; j<b.size(); j++) {
        b.set(j, in.nextInt());
        if(!(b.get(j)==0)){
            if(b.get(j)>max){b.set(j, b.get(j));}
        }else{
            rez=0;
            break;
        }
    }
}
    System.out.println("Максимальный элемент вашего массива = " + max);

A: Вот вам решение:
System.out.println("Введите элементы");

Scanner scanner = new Scanner(System.in);
int number;
ArrayList<Integer> numbers = new ArrayList<>();
while ((number = scanner.nextInt())!=0)
        numbers.add(number);

System.out.println("Максимальный элемент вашего массива = " + Collections.max(numbers));


text:
Q: Is there a way to change an element's default getter? I'm writing a userscript and need to make it so any iframe appended to the DOM with document.body.appendChild()'s content document has the hidden getter set to always return false.
I can change the getter with:
iframe.contentDocument.__defineGetter__("hidden",()=>false)

I need this to modify elements before they're added to the DOM, so that
var i = document.createElement("iframe");
i.sandbox = "allow-same-origin";
document.body.appendChild(i);
document.__defineGetter__("hidden", i.contentDocument.__lookupGetter__("hidden"))

will always redefine the document hidden getter to return false.
I've tried:
const oldAppend = Node.prototype.appendChild;
Node.prototype.appendChild = function (child) {
  child?.contentDocument?.__defineGetter__("hidden",()=>false);
  return oldAppend(child);
}

But then when I try to use the appendChild method, I get: TypeError: 'appendChild' called on an object that does not implement interface Node.
Is there a way (in pure JS) to change the appendChild method so that it does this for every iframe that gets appended to the DOM?

A: You can use a MutationObserver to watch for nodes added anywhere in the document, and patch them if they haven't been patched yet.

// userscript code
const parsed = new WeakSet();
const parse = iframe => {
  if (parsed.has(iframe)) return;
  parsed.add(iframe);
  Object.defineProperty(iframe, 'hidden', { get() { return false; } });
};
new MutationObserver(() => {
  document.querySelectorAll('iframe').forEach(parse);
})
  .observe(document.documentElement, { childList: true, subtree: true });

// site code
const iframe = document.body.appendChild(document.createElement('iframe'));
console.log(iframe.hidden);

Object.defineProperty should be preferred over __defineGetter__, which is deprecated.
A MutationObserver is probably a bit better than working with only appendChild because appendChild is not the only way that nodes can be added to the document. (A MutationObserver will catch everything)

A: I managed to solve my problem by redefining document.body.appendChild like this:
const oldAppend = Node.prototype.appendChild;
document.body.appendChild = function(...args) {
  const toReturn = oldAppend.call(this, ...args);

  if (args[0].nodeName === "IFRAME") {
    args[0].contentDocument.__defineGetter__("hidden",()=>false);
  }

  return toReturn;
}


text:
Q: Fix yaxis in place Here is some code I've written/adapted, which produces the output below it:
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

import sys

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure

import matplotlib.pyplot as plt
import numpy as np

class LineBuilder:
    def __init__(self, ax):
        self.ax = ax
        self.on = 1
        self.lastline, = self.ax.plot([0],[0])
        self.cid = ax.figure.canvas.mpl_connect('pick_event', self)

    def __call__(self, event):
        self.on *=-1
        thisline = event.artist
        xdata = thisline.get_xdata()
        ydata = thisline.get_ydata()
        ind = event.ind
        print(xdata[ind])
        print('modified',xdata[ind][0])
        self.lastline.remove()
        self.lastline=self.ax.axvline(x=xdata[ind][0])
        self.ax.figure.canvas.draw()

class View(QGraphicsView):

    def __init__(self):
        super(View, self).__init__()

        self.initScene(5)

    def initScene(self,h):

        self.scene = QGraphicsScene()
        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)
        self.figure.subplots_adjust(left=0.03,right=1,bottom=.1,top=1,wspace=0, hspace=0)

        ax = self.figure.add_subplot(111)
        ax.set_xlim([0,1000])
        data = np.random.rand(1000)
        ax.plot(data, '-')

        self.canvas.draw()
        self.setScene(self.scene)
        self.scene.addWidget(self.canvas)

class MainWindow(QMainWindow):

    def __init__(self):
        super(MainWindow,self).__init__()

        self.setGeometry(150, 150, 700, 550)

        self.view = View()
        self.view.setGeometry(0,0,self.width()*2,500)
        self.view.canvas.setGeometry(0,0,self.width()*2,500)

        self.setCentralWidget(self.view)

app = QApplication(sys.argv)

window = MainWindow()
window.show()

app.exec_()

I can use the scrollbar on the bottom to view the entire image. However, when scrolling, I quickly lose sight of the y-axis labels. Would it be possible to fix them in place, so that the scrollbar only changes the part of the xaxis that's visible (whilst the yaxis ticks and labels stay fixed)?

A: Instead of scolling the complete figure inside a QGraphicsView one may rather add a QScrollBar to the window and connect it to a function, which updates the xlim of the axes inside the figure.
import numpy as np
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure

class Fig(FigureCanvas):
    def __init__(self, *args,**kwargs):
        self.factor = kwargs.pop("factor", 2)
        FigureCanvas.__init__(self, Figure(), *args,**kwargs)
        self.plot()
        self.scroll = QScrollBar(Qt.Horizontal)
        self.scroll.actionTriggered.connect(self.updateFromScroll)

    def plot(self):
        self.ax = self.figure.add_subplot(111)
        data = np.random.rand(1000)
        self.ax.plot(data, '-')
        self.xmin,self.xmax = self.ax.get_xlim()
        self.ax.set_xlim(self.xmin, self.xmax/float(self.factor))

    def updateFromScroll(self, evt):
        v = self.scroll.value()
        a = [self.xmin, self.xmax/float(self.factor)]
        lim = a+v/100.*np.diff(a)[0]
        self.ax.set_xlim(lim)
        self.draw_idle()

class Window(QMainWindow):
    def __init__(self):

        QMainWindow.__init__(self)
        self.widget = QWidget()
        self.setCentralWidget(self.widget)
        self.widget.setLayout(QVBoxLayout())
        self.widget.layout().setContentsMargins(0,0,0,0)
        self.widget.layout().setSpacing(0)

        self.canvas = Fig()
        self.canvas.draw()

        self.nav = NavigationToolbar(self.canvas, self.widget)
        self.widget.layout().addWidget(self.nav)
        self.widget.layout().addWidget(self.canvas)
        self.widget.layout().addWidget(self.canvas.scroll)

        self.show()

qapp = QApplication([])
# pass the figure to the custom window
a = Window()
exit(qapp.exec_())


text:
Q: Uncaught exception 'Exception' with message 'DateTime::__construct() I have the following query in my page ?filterFrom=11%2F01%2F2014&filterTo=11%2F25%2F2014
Now I have the following code
// Get Start
if(isset($_GET['filterFrom']) && !empty($_GET['filterFrom'])) {
    $startDate = new DateTime(str_replace('/', '-', $_GET['filterFrom']));
    $sqlArray[":searchFrom"] = $startDate->format('Y-m-d').' 00:00:00';
}
// Get End
if(isset($_GET['filterTo']) && !empty($_GET['filterTo'])) {
    $endDate = new DateTime(str_replace('/', '-', $_GET['filterTo']));
    $sqlArray[":searchTo"] = $endDate->format('Y-m-d').' 23:59:59';
}

The "Get Start" part of the script works fine, but when it gets to "Get End", I get the following error:

Fatal error: Uncaught exception 'Exception' with message
  'DateTime::__construct(): Failed to parse time string (11-25-2014) at
  position 0 (1): Unexpected character'

I have this exact same script on 6 other pages and don't have any issues! Does anyone know what could be going wrong??

A: It turns out php was having an issue parsing my date, so I used the following code
$endDate = DateTime::createFromFormat('d/m/Y', $_GET['filterTo']);


text:
Q: Exclude artifacts from assemble task In order to use results of one project's task in another project I created a consumable configuration in one project and use this configuration in another project. Although this is the origins of the issue, it boils down to the simple java build file with a configuration:
plugins {
    id 'java'
}
task createChecksums(type: Task) {
}
configurations {
    release {
        canBeConsumed = true
        canBeResolved = false
    }
}
artifacts {
    release(file("someFile")) {
        builtBy createChecksums
    }
}

When I run gradlew assemble it also runs createChecksums task. It seems to me that the assemble task builds all artifacts.
Is there any way to configure configurations in such a way that artifacts are only built when needed by another project which consumes the configuration?


text:
Q: Qualified double not displayed properly I'm trying to make some controls which size would be set using qualified double so that the control size are the same no matter which screen it's displayed on.
So I have this converter which converts double to qualified double:
double effectiveValue = cm;
string qualifiedDouble = effectiveValue + "cm";
LengthConverter lc = new LengthConverter();
double converted = (double)lc.ConvertFrom(qualifiedDouble);

The problem is that it's not really efficient regarding the system parameters such as resolution or the default system zooming (idk how it's called in English)

Do you have any clue on how it may be possible to have the exact same values in centimeters displayed on any screen for any resolution, any zoom settings and so on.
Thanks

A: It should (mostly) work, I've done similar things few times, but you need to ensure that in your desktop appearance settings (and graphic card settings, presentation profiles etc - if you have any such software) you have all the scaling disabled (set to 100% normal, no big fonts etc). I belive that's the "system zooming" you mentioned.
After setting it to 100%, all WPF units should display the same on any screen. So 10x10rectangle (or 10cmx10cm) on all screens should look the same. If you use qualified, then it should look the same on any resolution. In theory, or rather, in OperatingSystem's point of view.
The problem is, even if the OS is 100% sure that all is calculated well, still some card/monitor configurations can "lie" to the OS about their capabilities. You can't get actual DPIs from i.e. a wall projector. Some monitors with wierd dimensions can scale the image and will distort the image horizontally or vertically to fill the whole screen so no black margins will apear. Software drivers of your graphics card can do that too, internally, so OS will not know it. And WPF's DPIs, device-independent-units and qualified-lengths are all about what system knows and how's that related to the real screen.
However, if you ensure that all system-scaling, screen-filling, 16:9/4:3 translations, etc are disabled, than you can mostly expect it to be displayed correctly. You can't escape from having the users configure that. Once they do that, they can verify the results with some simple "ruler" screen that your app will display. If it's still wrong, then that's mostly to blame on the hardware, and you're stuck. It will need to be changed if user really wants to have it running.
btw. I have not found any way to consitently handle "system zooming", that is a weird part of the OS display. It seems easy at first, just read the settings from registry/etc and scale up/down accordingly, but then, it turns out that on different OS versions (like i.e. winXP vs win7) that scaling works a little differently.. maybe you will find a way, I have not. I just asked users to set to 100%. Or to change the hardware, because when they had it set on non-100% already then it almost always indicated that their gpu/monitor had weird resolutions had some "smart software" that did some extra scaling..

A: So I finally found a way to do so using the EDID which contains the sufficient informations on displays that were connected to the computer. The EDID are stored in a registry:
HKLM\SYSTEM\CurrentControlSet\Enum\\DISPLAY\ + displayId + registryId

Here is the code to retrieve the ratio that will convert the cm to pixel on screen
public static double GetCmToPixelRatio()
{
    var diagVector = GetActiveDisplayDiag();

    var width = System.Windows.SystemParameters.PrimaryScreenWidth;
    return width / diagVector.X;
}

public static int GetDPIX()
{
    var dpiXProperty = typeof(SystemParameters).GetProperty("DpiX", BindingFlags.NonPublic | BindingFlags.Static);

    return (int)dpiXProperty.GetValue(null, null);

}

private static Point GetActiveDisplayDiag()
{
    //get active display
    string wmiQuery = string.Format("Select * from Win32_DesktopMonitor");

    ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmiQuery);
    ManagementObjectCollection retObjectCollection = searcher.Get();

    foreach (ManagementObject retObject in retObjectCollection)
    {
        try
        {
            //get display id
            string regPath = (string)retObject.GetPropertyValue("PNPDeviceID");
            if (regPath != null)
            {
                var pathInfo = regPath.Split('\\');
                var displayId = pathInfo[1];
                RegistryKey reg = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Enum\\DISPLAY\\" + displayId);
                var firstSubReg = reg.GetSubKeyNames()[0];
                reg = reg.OpenSubKey(firstSubReg + "\\Device Parameters");
                var edid = (byte[])reg.GetValue("EDID");
                return new Point(edid[21], edid[22]);
            }
        }
        catch (Exception) { }
    }
    return new Point();
}

Using that I created my converter:
public class CmToPixelConverter : IValueConverter
{
    double ratio = DisplayHelper.GetCmToPixelRatio();

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (double)value * ratio;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}


text:
Q: If $A^2B^2 = ABAB$, for square matrices A,B having same size, then prove that $AB = BA$. I actually know it's false if A and B are not invertible.
But how can i prove that not by using counterexamples

A: You can prove that by considering the null-space and value space of matrices. Recall that we know that if a matrix is non-invertible then the dimension of the null-space is greater than $0$ and the dimension of the value space is less than the row count. Also we know that $\dim N(M) + \dim V(M)$ is the actual row count of $M$.
What we use that given two subspaces $U$ and $W$ with $\dim U + \dim W$ being the row count then there exist a matrix $M$ that has $U = N(M)$ and $W = V(M)$. This can be seen as the ortogonal complement to $U$ has the same dimension as $W$ and therefore it exists a linear bijection between $U^\perp\to W$ and then we can define a mapping of the whole space by projecting the argument on $U^\perp$.
Now we know that if there's at least two dimensions there therefore exists $A$ and $B$ such that $N(A) = V(B)$ and $N(B) \perp V(A)$, and $\dim V(A), \dim V(B)> 0$. This means that $B$ would map anything to something that $A$ maps to $0$ which means that $AB$ always maps to zero which means that $AB=0$. On the other hand $V(A)$ contains vectors not in $N(B)$ which means that $A$ will map some vectors to vectors not in $N(B)$ which means that $B$ will not map those vectors to $0$, that is there exists vectors $x$ such that $BAx\ne 0$ which means $BA\ne 0$. This clearly means that $AB-BA\ne 0$. But sice $AB=0$ then so is $A^2B^2 = A (AB) B$ and also $ABAB=(AB)(AB)$.
We have concluded that there exists $A$ and $B$ such that $AB\ne BA$ yet $A^2B^2 = ABAB$.

Note that although this may seem to be a proof without using counter-example it's probably not that free of counter-example. For example showing that there exists linear bijection between spaces of the same dimension is probably shown by actually constructing such a mapping. Also see that we construct the mapping with prescribed zero and value space from this through direct construction from the linear bijection to the value space. Also that there are subspaces $N(A), V(A), N(B), V(B)$ with the desired properties is also probably done by direct construction.
Actually normally when we want to show the existence of something one often relies on concrete examples, otherwise one constructs an example abstractly starting from something that is known to exist. Only occationally one proves the existence non-constructively. And disproving a general assertion means that we're to prove that there exists an object that falsifies the assertion.

A:
Supposing A,B are invertible

$$A^2B^2=ABAB$$
$$A\color{green}{AB}B=A\color{green}{BA}B$$
Pre multiplying by $A^{-1} $ and post multiplying by $B^{-1}$

$$\color{red}{A^{-1}A}AB\color{blue}{BB^{-1}}=\color{red}{A^{-1}A}BA\color{blue}{BB^{-1}}$$$$AB=BA$$

If they are not invertible, you cannot say anything about the matter at hand.

A: Suppose $A,B$ are both invertible. Then rewrite:
$$A^2B^2 - ABAB = A(AB - BA)B = 0 $$
$$ A^{-1}A(AB-BA)BB^{-1} = 0 $$
$$ AB-BA =0$$
$$AB=BA$$

A: It is indeed false. For a counterexample, consider:
$$
A = \begin{bmatrix}
0 & 1 \\
0 & 0
\end{bmatrix}
\qquad\text{and}\qquad
B = \begin{bmatrix}
1 & 0 \\
0 & 0
\end{bmatrix}
$$
Note that $BA = A$, and:
$$
A^2 = AB = \textbf{0} = \begin{bmatrix}
0 & 0 \\
0 & 0
\end{bmatrix}
$$
so we have that $A^2B^2 = \textbf{0}(B^2) = \textbf{0} = \textbf{0}(AB) = ABAB$, yet $AB = \textbf{0} \neq A = BA$.


text:
Q: Joomla - Cannot configure RSSocial! module I am currently trying to use RSSocial! extension to add social media button that can link to my social media site. However, when I follow the instruction to edit the module, there is no parameter that I can change and this is what it showed:

Pressing "Show full description..." show nothing.
Can anyone help me with this issue? Many thanks.
P/s: If there is other way to do the same, I would really appreciated it.

A: Try the following:

*

*Uninstall and then re-install the extension

*Disable PowerAdmin (I suspect that this is the problem)

Let us know of your findings.


text:
Q: How to capture a video of an external screen in Android? I have an Android app running as a Presentation on a secondary display.
I'd like to record its screen in a way similar to adb screenrecord.
I searched the web but was unable to find anything except for this question. That dates back to 2014 and I was wondering if there is a more intuitive way to do it now? I am an Android newbie so the answer to that question was unfortunately not very helpful to me.


text:
Q: listview count vs adapter count in android Why do listview.getChildCount() and adapter.getCount() return different values? I have an onScroll method and from within it, if I call the methods above, each return different values. Does anyone know why?

A: adapter.getCount() returns total objects count contained in it. listView.getChildCount() return number of views showed in this listview.
Adapter uses caching mechanism, and a lot of views are reused, that's why it's number differs from that shown in adapter.getCount()

A: ListView.getChildCount() returns the number of Views on the screen. Adapters getCount() returns the total number of objects in your list.
getChildCount()
getCount()
You might have 50 Strings in say an ArrayAdapter but only 10 are drawn on the screen at the current moment so your ListView count will be 10 but your Adapter count will be 50.


text:
Q: Why do I need to explicitly instantiate an object?  I am having a problem on my MVC framework. Here is my loadModel() method inside the main controller:
public function loadModel($name) {
$path = 'models/' . $name . '_Model.php';

    if (file_exists($path)) {
        require $path;
        $modelName = $name . '_Model';
        $this->model = new $modelName;
    }
}

As you can see, when i try to load a controller, it automatically loads a model with the same name + _model.php.
I do not have any problem, when I use wamp or xampp, but, when I uploaded it in my website, it says "Undefined property" on every model. That means the model is not loaded. I know the problem is in there...
Is that some kind of an error in php.ini file of the server? Or maybe it because of different PHP versions?

A: Windows is not case sensitive, i.e. Model.php and model.php are the same as far as windows is concerned. ON unix/linux however (which I'm assuming your website server is) the file system IS case sensitive.
Basically, check your files names - if you're trying to load $name_Model.php but the file is $name_model.php it's going to fail when you upload it.

A: You might wanna consider using autoloading, that fixes all your problems:

A: Don't rely on relative paths, they depend on the current directory.
Make an absolute path like (adapt to your needs):
$path = __DIR__ . '/models/' . $name . '_Model.php';

If you get something like that to work locally, it should work on the server too.
BTW, i don't understand why _Model suffix. Wouldn't models/Car.php be sufficient ?


text:
Q: Angular $http post with custom headers I am new to angular and am from .net framework. I need to post a angular request to .net service, where it expects two custom headers from the client.
angular post command:
var request = $http(
        {
            url: "http://localhost:53585/api/myService/Validate",
            method: "POST",
            data: JSON.stringify(payload),
            headers: {  'first_token': sessionService.first_token, 'second_token': sessionService.second_token }

            });

But in the service side, I can see only first_token in the request header and not the second token.  What I am missing here?

A: Issue is with my service. I figured out and restarted the IIS and then service was able to read both the headers token

A: I found this method in a forum, it works.
return this.http.post<any>('https://yourendpoint', { username, password }, { headers: new HttpHeaders().set('Authorizaion', 'your token')})
      .pipe(map(user => {
        // login successful if there's a jwt token in the response
        if (user && user.token) {
          // sto`enter code here`re user details and jwt token in local storage to keep user logged in between page refreshes
          localStorage.setItem('currentUser', JSON.stringify(user));
        }
        console.log(user);
        return user;


text:
Q: UINavigation with UITextField as subview I want to make UI like following,

I tried to increase the height of UINavigationController like
[self.navigationController.navigationBar setFrame:CGRectMake(0, 0, 320, 110)];

but navigation title and BarButtonItem appears down.
i can not add hide navigation as i am using third party side menu which uses Left BarButtonItem.
i can very well keep navigation as it is and below i have added uiview as subview with same background colour as that of navigation but there is fine line appears in between...:(

A: You can't increase height of UINavigationBar. Add an UIView with those elements just below the UINavigationBar.
Then there will be extra line below UINavigationBar. You can remove that line. Refer How to hide iOS7 UINavigationBar 1px bottom line
or else use this code(I have just copied it from that link in swift, convert it to Objective-C)
import UIKit

class ViewController: UIViewController {

    private var shadowImageView: UIImageView?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        if shadowImageView == nil {
            shadowImageView = findShadowImage(under: navigationController!.navigationBar)
        }
        shadowImageView?.isHidden = true
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

        shadowImageView?.isHidden = false
    }

    private func findShadowImage(under view: UIView) -> UIImageView? {
        if view is UIImageView && view.bounds.size.height <= 1 {
            return (view as! UIImageView)
        }

        for subview in view.subviews {
            if let imageView = findShadowImage(under: subview) {
                return imageView
            }
        }
        return nil
    }
}

This is the result

A: Actually you cant change height of UINavigationBar. Your actual ViewController's view will start from 64 pixel from TopLayoutGuide (Vertical Space)
Status Bar Height is 20 Pixel
Navigation Bar Height is 44 Pixel
So to design such UI, simply do these steps

*

*Hide NavigationBar on that view controller like
self.navigationController.navigationBarHidden = YES;
self.navigationItem.hidesBackButton = YES;

*Then add View from storyboard with vertical space as 0 from TopLayoutGuide. And design it as per your requirement. So you can
simply give this look and handle it using IBOutlets and IBActions
for each item
Also you can add UILable to show title of screen.

A: You can't increase the size of the UINavigationBar. That is of standard size 44 (Nav Height) + 20  (size of the status bar). Here you've two options to achieve.
First, by adding menu, dashboard title label & notification icon to the UINavigationBar. Add Jobs, Conditions, and Interview as a separate view below to navigation bar.
Second by customizing the entire view, as mentioned by @Pushkraj i.e, by hiding the current Navigation Bar and adding your own view which contains all the UI elements.