Q: How can a battery 'come back to life'? Earlier today, one of my family drained our car's battery by accident, by leaving the lights on too long. It wouldn't start at all, so they had to walk back home from where the car was parked (a few streets away). However, when we went over there later on in the day, with our other car and some jumping leads, it just started up right away.
How would/could this happen? Why would the voltage/charge seem to 'recover' over a period of time, when previously it was drained?

A: In general, any electrochemical reaction in a battery creates concentration gradients of different compounds between electrodes, which tend to form thin layers of different substances near them. Some of these layers, if solid, precipitate on the electrodes. Depending of battery's chemistry and charge/discharge mode this can result in an insulating film that would interfere with the battery operation. This is, for example, the reason why $\text{NiCd}$ batteries have the "memory effect", and all (IIRC) batteries based on lithium chemistry can stop charging completely and "play possum", but reverse under tens of hours of steady low charging current due to an eventual dissolution of the parasitic insulating layer.
In the case of lead-acid battery, discharge involves the formation of solid $\text{PbSO}_4$ on both plates. Normally this sulfate is spongy, porous amorphous solid that lets the acidic electrolyte through to reach metal and metal-oxide electrodes under it, and also dissolves easily when a charge current is applied, due to its large cumulative surface area. But under certain conditions, such as constant low discharge current and low battery temperature, the sulfate layer may grow in a densely packed crystalline form, and produce an insulating layer that prevents further discharge. This layer, while it is still thin enough, may eventually let some electrolyte to soak through spots when the load is off. When you connect a low impedance load (starter) to the battery, the thin brittle insulating layer may break down starting from these pores where electrolyte is now present, where it experiences mechanical stress due to thermal expansion, allowing the discharge reaction to continue.
In extreme cases, when the battery spends long periods of time in a deeply discharged state, the amorphous sulfate on electrodes transitions into a densely packed microcrystalline form, resulting in a solid white dense impenetrable layer that no longer dissolves when charging is attempted. It forms primarily on the negative plate of the battery (I just realized do not know why, really, as you got me thinking about it! Furute research required...). This is known as sulfation, and is generally irreversible. This is also one of the processes that limits lifetime of the battery even under optimal use (positive plate corrosion being another one).


Q: How to bind ngFormModel in angular2 using Dart? The following works in a form (the form is displayed)
.html
  <form (ngSubmit) = "onSubmit()"
         #nameForm = "ngForm">
    {{diagnostic}}

Name

        <input
            required
            type = "text"
            [(ngModel)] = "name.first"
            ngControl = "first"
            #first = "ngForm"
            (input)="onInputHandler($event)"
            class = "mdl-textfield__input ng-valid"
            id = "first">
        First
        {{firstErrorMsg}}

        <button id = "startButton"
                class = "mdl-button mdl-js-button mdl-button--raised mdl-button--accent mdl-js-ripple-effect"
        >Submit
        </button>

    <button class = "mdl-button mdl-js-button mdl-button--raised mdl-button--colored">
      Button All
    </button>

  </form>

Trying to follow the example at Forms and Validation in Angular 2.0,
I cannot get the UI to display by changing the first line of the form to
<form (ngSubmit) = "onSubmit()"
        [ngFormModel]="form" #f="form">
    {{diagnostic}}
..

With the change the browser simply does not display anything as if it cannot parse the markup - the error is actually shown in pub-serve or debug mode.
Transform TemplateCompiler on epimss_ng2_reg|lib/components/name_component.ng_meta.json threw error: Template parse errors:
There is no directive with "exportAs" set to "form" ("

  <form (ngSubmit) = "onSubmit()"
        [ng-form-model]="form" [ERROR ->]#f="form">
    {{diagnostic}}

"): NameComponent@12:31
....

Why is this not working?

A: Seems this was changed since when the blog post was created.
NgForm is now exported as ngForm instead of form.
[ngFormModel]="form" #f="ngForm">

It's correct in the GitHub source but not in the blog post.
Full component according to the example in the blog post in Dart
@Component(selector: 'form-element')
@View(template: '''

form-element

<form (ngSubmit)="onSubmit()" [ngFormModel]="form" #f="ngForm">

First Name

        <input type="text" id="firstName" ngControl="firstName">

First Name is required

Street Address

        <input type="text" id="firstName" ngControl="streetAddress">

Street Address is required

Zip Code

        <input type="text" id="zip" ngControl="zip">

Zip code has to be 5 digits long

Address Type

        <select id="type" ngControl="type">
            <option [value]="'home'">Home Address</option>
            <option [value]="'billing'">Billing Address</option>
        </select>

    <button type="submit" [disabled]="!f.form.valid">Save</button>

The form contains the following values

            {{payLoad}}

</form>
''')
class FormElement {
  ControlGroup form;
  String payLoad;
  FormElement(FormBuilder fb) {
    form = fb.group({
      "firstName": ['', Validators.required],
      "streetAddress": ['', Validators.required],
      "zip": [
        '',
        Validators.compose([ZipValidator.validate])
      ],
      "type": ['home']
    });
  }

  void onSubmit() {
    payLoad = JSON.encode(this.form.value);
  }
}


Q: Gmail sending error (C#) I'm trying to send an email via C# but I keep on getting this error:

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at...

The stack trace can be found here:

System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response)
at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception)
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at Repetrel.View.EmailForm.btnSend_Click(Object sender, EventArgs e) in c:\2015 Hyrel Projects\Repetrel\src\Repetrel\View\EmailForm.cs:line 238

Here is my code:
            NetworkCredential loginInfo = new NetworkCredential(Properties.Settings.Default.MyEmailAddress, Properties.Settings.Default.MyEmailPassword);
            //System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(Properties.Settings.Default.SMTPAddress);
            ////Trace.WriteLine("smtp = " + Properties.Settings.Default.SMTPAddress);
            //smtpClient.Port = 587;
            //smtpClient.EnableSsl = true;
            //smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            ////smtpClient.UseDefaultCredentials = false;
            //smtpClient.Credentials = loginInfo;

            var smtpClient = new SmtpClient
            {
                Host = "smtp.gmail.com",
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = true,
                Credentials = loginInfo,
                Timeout = 20000
            };

            //smtpClient.SendAsync(message, "test");
            smtpClient.Send(message);

            //Output to log
            OutputToLog(message);

            //Close Window
            Close();
        }
        catch (Exception ex)
        {
            Trace.WriteLine(ex.ToString());
            MessageBox.Show("An error occurred.  Please see the trace log for more information.");
        }

I have tried everything mentioned in previous posts(there are many of them), but nothing seems to work.  I have tried with and without default credentials and setting the flag to false/true.  Nothing seems to work.  Might anyone be able to point me in the right direction?
Thanks in advance!

A: Apparently GMAIL was blocking my email address from using less secure devices. You can turn off the blocking at: https://www.google.com/settings/security/lesssecureapps.

A: Perhaps UseDefaultCredentials = false, instead?
Edit: This seems similar to an older StackOverflow question: SmtpClient with Gmail


Q: Обязательно ли делать Client.Disconect(boolean flag) перед закрытием программы? (C#, MailKit, MimeKit) Обязательно ли делать Client.Disconect(boolean flag) перед закрытием программы?
    private void FormClose(object sender, FormClosingEventArgs e)
    {
        _token = new CancellationToken(true);
        /*_clientProfile.Client.Disconnect(true); нужно ли делать */
        Application.Exit();
    }


Q: Simple Logarithm and JavaScript Question I have a simple formula that I am trying to convert to JavaScript, I'm just stuck trying to reverse it. My math skills have deteriorated over the last few years and im stuck.
Here is the formula

And here is my interpretation of it in JavaScript
2 * Math.log2(apx) = fval

Given that I only know the value of fval, and im actually trying to get the value of apx, can anyone tell me how I would go about doing that?  Double points if you can help with the javascript conversion :)

A: The main thing to remember about logarithms (indeed, their defining property) is that for positive real numbers $a$ and $b$, with $a\neq 1$, we have
$$\large a^{\log_a(b)}=b$$
Therefore, if you have
$$2\cdot\log_2(N)=A_N$$
then dividing both sides by $2$ we get
$$\log_2(N)=A_N/2$$
and then raising $2$ to the power of both sides we get
$$N=2^{A_N/2}$$
I don't know whether to expect any floating-point arithmetic problems, but naively turning this formula into Javascript would give
apx = Math.pow(2, fval / 2)


Q: How to make permalink structure %category%/%postname%/ work for custom post type? I'm trying to achieve the following permalink structure  for a custom post type called "concept" with taxonomy "category"
http://domain/categoryname/conceptname

Note: The main problem here is I don't want the custompost type slug /concept to appear, and now it seems to be conficting with existing rewrite rules
I did
global $wp_rewrite;
$concept_permalink_structure = '/%category%/%concept%/';
$wp_rewrite->add_rewrite_tag('%concept%/','([^/]+)', 'concept=');
$wp_rewrite->add_permastruct('concept/',$concept_permalink_structure,false );

and
add_filter('post_type_link', 'tt_concept_permalink2', 10,3);

function tt_concept_permalink2($permalink, $post, $leavename ) {

    if($post->post_type != 'concept')
            return $permalink;

    if( !isset($post->ID) ){
        global $post;
    }

    $categories = get_the_terms( $post->ID, 'category');

    if( is_array($categories) && count( $categories ) > 0 ) {
        $cat = $categories[key($categories)]->slug;
        $permalink = str_replace('concept/', $cat .'/', $permalink );
    }

    return $permalink;

}

and it is working!
But!
all other permalink( page, other custom post types ) are giving 404 error!
How can I make them work?


Q: Does AWS Device Farm support Android Orchestrator? Can I upload Android Orchestrator .apk to the AWS Device Farm as a 3rd apk (together with main app apk and test-suite apk)? Or application state is not persistent in the Device Farm, so that it doesn't require external Orchestrator at all?
Currently we use local runner for Android Espresso tests. Some tests require app state/data to be cleared between tests, so that we use Orchestrator. According to a console, it is uploaded as a separate apk to the device. AWS Device Farm allows uploading only 2 apks: app itself and a test-suite.
So, how could I use Orchestrator in the AWS Device Farm for tests to have cleared app state/data after each test?

A: You could send Orchestrator as an auxiliary apps when using AWS Device Farm.
If you're using the console, this is done during the Specify device state step under Install other apps
If you're using the CLI use auxiliaryApps flag https://docs.aws.amazon.com/cli/latest/reference/devicefarm/schedule-run.html

A: Short answer: Uploading the orchestrator seems to work, but you dont need it to get the tests run in separate processes.
Long answer: As Scott's answer said, you can upload and install the orchestrator to the device. You should upload android test services apk as well (test-services-1.4.0-alpha05.apk for example)
Also the Piotr's comment is correct. If you want to use the orchestrator, you should specify your own start command for tests like this: "adb shell "CLASSPATH=$(pm path androidx.test.services) exec app_process / androidx.test.services.shellexecutor.ShellMain am instrument ...". This can be done by using the custom evironment option from the device farm's start test wizard. More info can be found here: https://developer.android.com/training/testing/junit-runner#using-android-test-orchestrator
If you want to get the tests run separatedly, just use the default environment option, as it seems to isolate the tests by default in the aws farm. There's no need to use the orchestrator. Orchestrator is needed only, if you want to use your own custom test runners, or use custom parameters that needs to be passed to the tests.


Q: How to synchronize readings with the HIGH and LOW states of a PWM output? I would like to oscillate GPIO infrared LEDs at a high frequency and compare the infrared sensor readings when the LEDs are off and when they are on. To do this I would need to synchronize the readings with the PWM. Currently, I can use a pseudo-PWM by using digitalWrite to toggle them between HIGH and LOW with a delay to take readings, but this only give me 500Hz.
How can I synchronize readings with a PWM output? Or should I just use another method of digital on/off?

A: Generally you'd probably want to use the PWM peripheral on the MCU chip and generate an interrupt from the PWM peripheral, then make the ADC measurement (or at least trigger it to begin) in the interrupt service routine. The details, such as which PWM mode to use, and how well it will work depends a lot on the chip. Worst case, you could wire the PWM output back to an interrupt input. You may also need a delay to allow the ADC input to settle after the LED state changes, so perhaps another timer would be involved depending on exactly when in the PWM cycle the interrupt is generated (check out phase-correct PWM if you're using an ATmega328).
Your use of the term digitalWrite implies you're trying to do this with some Arduino or Arduino-like module, so you'll have to study the underlying chip (eg. Atmega328) features and how to use interrupts.
You may be able to get more specific help in the Arduino forum.


Q: php re-sorting an array I have an array of entries that are separated by year and month like below. I need to sort this array so that entries are "grouped" by year and then by category.
Array
(
    [Oct 2011] => Array
        (
            [0] => Array
                (
                    [title] => CAD Drawing Updates
                    [file] => /gm-June2010-driver.pdf
                    [category] => Windows
                )
        )

    [Sep 2011] => Array
        (
            [0] => Array
                (
                    [title] => title
                    [file] => /gm-June2010-driver.pdf
                    [category] => Windows
                )

            [1] => Array
                (
                    [title] => edges
                    [file] => /gm-June2010-driver.pdf
                    [category] =>Walling
                )

            [2] => Array
                (
                    [title] => Specification update
                    [file] => /gm-June2010-driver.pdf
                    [category] => Windows
                )
        )
)

So this is the sort of thing I'm after.
Array
(
    [Oct 2011] => Array
        (
                [Windows] => Array
                        (
                            [0] => Array
                                (
                                    [title] => CAD Drawing Updates
                                    [file] => /gm-June2010-driver.pdf
                                )
                        )
        )

    [Sep 2011] => Array
        (
                [Windows] => Array
                                (
                            [0] => Array
                                (
                                    [title] => title
                                    [file] => /gm-June2010-driver.pdf
                                    [category] => Windows
                                )

                            [1] => Array
                                (
                                    [title] => Specification update
                                    [file] => /gm-June2010-driver.pdf
                                    [category] => Windows
                                )
                                )
                [Walling] => Array
                                (
                            [0] => Array
                                (
                                    [title] => edges
                                    [file] => /gm-June2010-driver.pdf
                                    [category] => Curtain Walling
                                )
                                )
        )
)

I'm not sure if this is a job for the sort functions, any help would be appreciated, thanks.

A: No, that can't be done with the sort function, you need to create a new array by iterating through your original array with nested foreach loops.
$newArr = array();
foreach($arr as $month => items) {
  foreach($items as $data) {
    $newArr[$month][$data["category"]][] = $data;
  }
}

A: You don't want to sort but just to rename keys. PHP Arrays do not support to rename keys directly, so you need to create a new array first that is build with the new keys while maintaining the existing values.
At the end you can replace the original array with the new one:
$rekeyed = array();
foreach($array as $monthYear => &$value)
{
    $r = sscanf($monthYear, '%s %d', $month, $year);
    if ($r != 2) throw new Exception(sprintf('Invalid Key "%s".', $monthYear));
    $categories = array();
    foreach($value as &$item)
    {
        $category =& $item['category'];
        unset($item['category']);
        $categories[$category][] =& $item;
    }
    unset($item);
    $value =& $categories;
    unset($categories);
    $rekeyed[$year][$month] =& $value;
}
unset($value);
$array =& $rekeyed;
unset($rekeyed);
print_r($array);

Output:
Array
(
    [2011] => Array
        (
            [Oct] => Array
                (
                    [Windows] => Array
                        (
                            [0] => Array
                                (
                                    [title] => CAD Drawing Updates
                                    [file] => /gm-June2010-driver.pdf
                                )

                        )

                )

            [Sep] => Array
                (
                    [Windows] => Array
                        (
                            [0] => Array
                                (
                                    [title] => title
                                    [file] => /gm-June2010-driver.pdf
                                )

                        )

                    [Walling] => Array
                        (
                            [0] => Array
                                (
                                    [title] => edges
                                    [file] => /gm-June2010-driver.pdf
                                )

                        )

                )

        )

)

Demo

A: I think the function you should be looking at is uasort.
http://www.php.net/manual/en/function.uasort.php
First do a sort on the main array, the for each element in the array, do a usort on the child array.


Q: Why is Parallelizable attribute not showing in my SpecFlow feature.cs files I'm using NUnitv3 with SpecFlow 2.0, ive added the attribute [assembly: Parallelizable(ParallelScope.Fixtures)] to my assemblyinfo.cs and have regenerated all of the steps.
However what im noticing is this attribute is not being populated into the generated feature files.
A post by Gaspar Nagy here: https://github.com/techtalk/SpecFlow/wiki/Parallel-Execution
suggests that it should be. Could someone she light on how I can get this attribute included?

A: This is an assembly level attribute. You need it only once. This is the "flag" that the NUnit Test Runner uses to determine if the tests supports parallelism.
SpecFlow 2.0 is not adding this attribute automatically to your code, so have to do it manually once.


Q: Select all events from a month in grails I am new to groovy/grails, and I'm trying to to do a criteria search that finds all posts for a month, basically like this:
def getUserMinutesForYear(User user, Date date){

    Date firstDate = new GregorianCalendar(date.year, Calendar.JANUARY, 1, 0, 0, 0).time
    Date lastDate = new GregorianCalendar(date.year, Calendar.DECEMBER, 31, 23, 59, 59).time

    def c = JobRegistration.createCriteria()

    def minutes = c.get {
        and{
            eq("user.id", user.id)
            between("job.happening", firstDate, lastDate)

        }

        projections {
            sum("minutesWorked")
        }
    }

    return minutes
}

The domain classes are
 class Job {

     String title
     String description
     Date   happening

     static hasMany = [registrations:JobRegistration]
 }

class User {
    static hasMany = [authorities: Role, registrations: JobRegistration]
    static belongsTo = Role
    String username
}

class JobRegistration {

    Job job
    User user

    Integer minutesWorked
    static belongsTo = [user:User,job:Job]

    static constraints = {
        user(blank: false)
        job(blank:false)
        minutesWorked(nullable :true)
    }

    String toString(){
        return user.userRealName
    }

}

Now, why do I get this exception?

org.codehaus.groovy.runtime.InvokerInvocationException: org.hibernate.QueryException: could not resolve property: job.happening of: JobRegistration

A: You need to nest the job relationship (you can also just us eq with user):
def minutes = c.get {
    and{
            eq("user", user)
            job{
                between("happening", firstDate, lastDate)
            }

    }

    projections {
            sum("minutesWorked")
    }
}

cheers
Lee


Q: Find and replace String from Object value using foreach C# I want to replace the value of two "string" members from their record in Object with the string I want.
I'm trying to use the .Contains() and replace() function on object
This is the object:
EmailParam param = new EmailParam();

And the EmailParam:
public class EmailParam {
  public string UserName {get; set;}
  public string Code {get; set;}
  public string Param1 {get; set;}
  public string Param2 {get; set;}
}

And this is the example:
string body = "My name is @UserName and my code is @Code";

param.UserName = "Tony";
param.Code = "A01";

What I want for result will be like My name is Tony and my code is A01
It is come from find body @UserName, and then replace from value Username Tony

A: you can use this code
List<EmailParam> param = new List<EmailParam>()
{
    new EmailParam(){Code ="A01",UserName="Tony"},
    new EmailParam(){Code ="B01",UserName="William"},
};
string body = "My name is @UserName and my code is @Code";

var findItem = param.Where(a => a.UserName.Equals("Tony") && a.Code.Equals("A01")).FirstOrDefault();
body = body.Replace("@UserName", findItem.UserName).Replace("@Code", findItem.Code);

A: You can use something similar to following
string body = "My name is {0} and my code is {1}"; //use placeholders instead of @UserName, @Code.
param.UserName = "Tony";
param.Code = "A01";

var convertedBody = String.Format(body, aram.UserName, param.Code);


Q: How to add "Open terminal here" to Nautilus' context menu? I am working on Ubuntu 12.04 64bit.
I want to add "Open terminal here" to Nautilus context or right-click menu but it tries to download 32bit version from Internet.

A: Just use:
sudo apt-get install nautilus-extension-gnome-terminal

and Logout/Login or reboot.

A: I have just installed Ubuntu 14.04 Desktop edition today 07-18-2014, and all I had to do to get the command line option in Nautilus was the following in a terminal:
sudo apt-get install nautilus-open-terminal
nautilus -q

A: nautilus-open-terminal and nautilus-actions packages are available in Universe repository of Ubuntu 14.04. So run the below commands to enable universe repository and also to install  above mentioned  packages.
sudo add-apt-repository universe
sudo apt-get update
sudo apt-get install nautilus-open-terminal
sudo apt-get install nautilus-actions

Finally run nautilus -q command to quit nautilus.Now you can be able to see Open in terminal option on right-clicking.

A: You have to install the nautilus-open-terminal package from the universe repositories for Ubuntu versions up to Ubuntu 15.04:
sudo apt-get install nautilus-open-terminal

If you want to install it with apturl, use this URL: apt://nautilus-open-terminal
Then:
nautilus -q

In order to restart Nautilus

In Ubuntu 15.10, the functionality is already included in nautilus!

A: You'll need to install nautilus-admin (make sure to install the additional files) to have the right click option and others as well, since nautilus-open-terminal is no longer maintained.

A: If you are using Ubuntu 18.04 or newer:
sudo apt install nautilus-admin

A: Here is my script to open terminal in the current directory,
I built my own after the open-terminal plugin stopped working for me
#!/bin/bash
##################################
# A nautilus script to open gnome-terminal in the current directory
# place in ~/.gnome2/nautilus-scripts
##################################
#                                       Remove file:// from CURRENT_URI
gnome-terminal --working-directory=`echo "$NAUTILUS_SCRIPT_CURRENT_URI" | cut -c 8-`

PS: Here is some bonus info
Assigning a shortcut to the script

*

*Add executable script to ~/.gnome2/nautilus-scripts

*Wait some time - nautilus regenerates accels file

*Edit file ~/.gnome2/accels/nautilus

*Find line similar to this one:
; (gtk_accel_path "<Actions>/ScriptsGroup/script_file:\\s\\s\\shome\\sgautam\\s.gnome2\\snautilus-scripts\\sopen-terminal" "")

*

*Remove comment (semicolon) and specify shortcut like this:

(gtk_accel_path "<Actions>/ScriptsGroup/script_file:\\s\\s\\shome\\sgautam\\s.gnome2\\snautilus-scripts\\sopen-terminal" "<Primary><Shift>t")

*

*Save file.

*Logout - login.

A: I used @Gautam's solution until I found it will not work (I mean a script itself) if path contains non-ascii characters because it's URL encoded.
Here is my little fix which is working at least for me.
So, the script should look like this:
#!/usr/bin/gnome-terminal

According to gnome-terminal docs, when you execute this:
cd path/to/dir
gnome-terminal

gnome-terminal will use path/to/dir as working directory, which explains why that script works.

A: Do
sudo apt-get update

and try again.
Or
cd /tmp
wget http://mirrors.kernel.org/ubuntu/pool/universe/n/nautilus-open-terminal/nautilus-open-terminal_0.20-1_amd64.deb
sudo dpkg -i nautilus*deb
sudo apt-get install -f

A: *

*Find the .bashrc file in Home.

*Open it with any text editor.

*Add a line at the end: cd $PWD

*Save it.

*Close all instances of Nautilus

*Now, when you open Nautilus you will get to see the "Open in terminal" option in the right-click menu and it loads the current directory path when clicked.

A: For recent versions of Ubuntu (eg. 18)... create/save this script in:
~/.local/share/nautilus/scripts/
Note: you need to also chg the permission of this new file to allow execution
It will add a Scripts right click context menu item (with the name given e.g. 'open-in-terminal.sh') for any file or directory you click in nautilus.
#!/bin/bash
#
# When a directory is selected, go there. Otherwise go to current
# directory. If more than one directory is selected, show error.
if [ -n "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS" ]; then
    set $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS
    if [ $# -eq 1 ]; then
        destination="$1"
        # Go to file's directory if it's a file
        if [ ! -d "$destination" ]; then
            destination="`dirname "$destination"`"
        fi
    else
        zenity --error --title="ERROR! Open terminal here" \
            --text="Plz only select one directory."
        exit 1
    fi
else
    destination="`echo "$NAUTILUS_SCRIPT_CURRENT_URI" | sed 's/^file:\/\///'`"
fi

# It's only possible to go to local directories
if [ -n "`echo "$destination" | grep '^[a-zA-Z0-9]\+:'`" ]; then
    zenity --error --title="ERROR! Open terminal here" \
        --text="Sorry, only local directories can be used."
    exit 1
fi

gnome-terminal --working-directory="$destination"

Based on this source: https://help.ubuntu.com/community/NautilusScriptsHowto/SampleScripts#Open_terminal_here

A: This link provides the best working solution for adding the feature "Open terminal here" as context command menu for a folder.
http://www.n00bsonubuntu.net/content/add-open-terminal-here-to-file-menu-ubuntu-14-04/


Q: Call another rest api from my server in Spring-Boot I want to call another web-api from my backend on a specific request of user. For example, I want to call Google FCM send message api to send a message to a specific user on an event.
Does Retrofit have any method to achieve this? If not, how I can do that?

A: Modern Spring 5+ answer using WebClient instead of RestTemplate.
Configure WebClient for a specific web-service or resource as a bean (additional properties can be configured).
@Bean
public WebClient localApiClient() {
    return WebClient.create("http://localhost:8080/api/v3");
}

Inject and use the bean from your service(s).
@Service
public class UserService {

    private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(3);

    private final WebClient localApiClient;

    @Autowired
    public UserService(WebClient localApiClient) {
        this.localApiClient = localApiClient;
    }

    public User getUser(long id) {
        return localApiClient
                .get()
                .uri("/users/" + id)
                .retrieve()
                .bodyToMono(User.class)
                .block(REQUEST_TIMEOUT);
    }

}

A: Create Bean for Rest Template to auto wiring the Rest Template object.
@SpringBootApplication
public class ChatAppApplication {

    @Bean
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }

    public static void main(String[] args) {
        SpringApplication.run(ChatAppApplication.class, args);
    }

}

Consume the GET/POST API by using RestTemplate - exchange() method. Below is for the post api which is defined in the controller.
@RequestMapping(value = "/postdata",method = RequestMethod.POST)
    public String PostData(){

       return "{\n" +
               "   \"value\":\"4\",\n" +
               "   \"name\":\"David\"\n" +
               "}";
    }

    @RequestMapping(value = "/post")
    public String getPostResponse(){
        HttpHeaders headers=new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<String> entity=new HttpEntity<String>(headers);
        return restTemplate.exchange("http://localhost:8080/postdata",HttpMethod.POST,entity,String.class).getBody();
    }

Refer this tutorial[1]
[1] https://www.tutorialspoint.com/spring_boot/spring_boot_rest_template.htm

A: As has been mentioned in the various answers here, WebClient is now the recommended route.
You can start by configuring a WebClient builder:
@Bean
public WebClient.Builder getWebClientBuilder(){
    return WebClient.builder();
}

Then inject the bean and you can consume an API as follows:
@Autowired
private WebClient.Builder webClientBuilder;

Product product = webClientBuilder.build()
            .get()
            .uri("http://localhost:8080/api/products")
            .retrieve()
            .bodyToMono(Product.class)
            .block();

A:
Does Retrofit have any method to achieve this? If not, how I can do that?

YES
Retrofit is type-safe REST client for Android and Java. Retrofit turns your HTTP API into a Java interface.
For more information refer the following link
https://howtodoinjava.com/retrofit2/retrofit2-beginner-tutorial

A: This website has some nice examples for using spring's RestTemplate.
Here is a code example of how it can work to get a simple object:
private static void getEmployees()
{
    final String uri = "http://localhost:8080/springrestexample/employees.xml";

    RestTemplate restTemplate = new RestTemplate();
    String result = restTemplate.getForObject(uri, String.class);

    System.out.println(result);
}

A: Instead of String you are trying to get custom POJO object details as output  by calling another API/URI, try the this solution. I hope it will be clear and helpful for how to use RestTemplate also,
In Spring Boot, first we need to create Bean for RestTemplate under the @Configuration annotated class. You can even write a separate class and annotate with @Configuration like below.
@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
       return builder.build();
    }
}

Then, you have to define RestTemplate with @Autowired or @Injected under your service/Controller, whereever you are trying to use RestTemplate. Use the below code,
@Autowired
private RestTemplate restTemplate;

Now, will see the part of how to call another api from my application using above created RestTemplate. For this we can use multiple methods like execute(), getForEntity(), getForObject() and etc. Here I am placing the code with example of execute(). I have even tried other two, I faced problem of converting returned LinkedHashMap into expected POJO object. The below, execute() method solved my problem.
ResponseEntity<List<POJO>> responseEntity = restTemplate.exchange(
    URL,
    HttpMethod.GET,
    null,
    new ParameterizedTypeReference<List<POJO>>() {
    });
List<POJO> pojoObjList = responseEntity.getBody();

Happy Coding :)

A: In this case need download whit my API, files hosted in other server.
In my case, don't need use a HTTP client to download the file in a external URL, I combined several answers and methods worked in previous code for files that were in my local server.
My code is:
@GetMapping(value = "/download/file/pdf/", produces = MediaType.APPLICATION_PDF_VALUE)
    public ResponseEntity<Resource> downloadFilePdf() throws IOException {
        String url = "http://www.orimi.com/pdf-test.pdf";

        RestTemplate restTemplate = new RestTemplate();
        byte[] byteContent = restTemplate.getForObject(url, String.class).getBytes(StandardCharsets.ISO_8859_1);
        InputStream resourceInputStream = new ByteArrayInputStream(byteContent);

        return ResponseEntity.ok()
                .header("Content-disposition", "attachment; filename=" + "pdf-with-my-API_pdf-test.pdf")
                .contentType(MediaType.parseMediaType("application/pdf;"))
                .contentLength(byteContent.length)
                .body(new InputStreamResource(resourceInputStream));
    }

and it works with HTTP and HTTPS urls!

A: Since the question explicitly tags spring-boot, it worth noting that recent versions already ship a pre-configured instance of a builder for WebClient, thus you can directly inject it inside your service constructor without the needing to define a custom bean.
@Service
public class ClientService {

    private final WebClient webClient;

    public ClientService(WebClient.Builder webClientBuilder) {
        webClient = webClientBuilder
                        .baseUrl("https://your.api.com")
    }

    //Add all the API call methods you need leveraging webClient instance

}

https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/boot-features-webclient.html

A: Simplest way I have found is to:

*

*Create an annotated interface (or have it generated from somehing like OpenAPI)

*Give that interface to Spring RestTemplate Client
The Spring RestTemplate Client will parse the annotations on the interface and give you a type safe client, a proxy-instance. Any invocation on the methods will be seamlessly translated to rest-calls.
final MyApiInterface myClient = SpringRestTemplateClientBuilder
  .create(MyApiInterface.class)
  .setUrl(this.getMockUrl())
  .setRestTemplate(restTemplate)         // Optional
  .setHeader("header-name", "the value") // Optional
  .setHeaders(HttpHeaders)               // Optional
  .build();

And a rest call is made by inoking methods, like:
final ResponseEntity<MyDTO> response = myClient.getMyDto();


Q: “If you are rested I would go,” I urged. Meaning? I was trying to translate this sentence but I got confused in this sentence. Does the sentence "I would go" mean something like "I would go if I were you"?
This sentence is from Hemingway's story The Old Man at the Bridge.
This is the next sentence.

“If you are rested I would go,” I urged. “Get up and try to walk now.”
“Thank you,” he said and got to his feet, swayed from side to side and then sat down backwards in the dust.

A: You are correct, "I would" is a shortening of "if I were you I would." This is a less common sense of the word would: OED has it as a verbal phrase, P7 in "will," v.1, (marked colloquial), defined as 'I advise or recommend you to.' Some other examples:

I wouldn't do that Sir! (a common polite way to tell someone to Stop!)
Q: How do I blow up the bridge? B: Well, if you had to, I'd start with the legs...
I'd be careful with that photo; you don't want it getting out.

The quote you give is particularly hard to parse because of Hemmingway's very curt style. In this case, the way to read

“If you are rested I would go.”

is as

“If you are rested I recommend that you go.”

A: More like "I would recommend that you go" or "I think you should go" than
"I would go if I were you."
The use of "urged" suggests the former meaning.
Translating Hemingway I would probably try to mimic

“If you are rested you should go,” I urged.

word for word with short words. Avoid anything like the three syllable "recommend".


Q: how to take input in python when no of input are not defined this is an c++ code , how can I implement this in python ?
while(scanf("%lld",&n)!=EOF)
    {
        cout<<convert(n)<<endl;
    }

A: This is roughly equivalent:
def convert(input):
     #do something with your input

import sys
for line in sys.stdin:
    convert(int(line))

A: In Python, instead of using scanf and friends, usually you read a line or an entire file into a string, and use string operations to get the results you want.
In your example, you could do something like:
import sys
for line in sys.stdin:
    for word in line.split():
        number = int(word)

        ... = convert(number)

A: it can be done using try except
link below can be used
https://stackoverflow.com/a/38621838/4557946


Q: matplotlib.plot.show continues shows plots even the script finished There isn't duplicated answer because I was always blocked by solution below !!!!!!!
I want to plot a graph and still run following code without closing the graph automatically like Matlab.
I try plt.show(block=False) , it failed and appear in a small moment then close itself.
Code:
import numpy as np
import matplotlib.pyplot as plt

if __name__ == '__main__':
    plt.figure(figsize=(10, 10))
    plt.plot(range(5), lw=2, label='Real')
    plt.title('Prediction')
    plt.legend(loc="best")
    plt.show(block=False)
    print("---Plot graph finish---")

I try plt.draw() or interactive mode , it failed, too. Check the code below.
Code:
import numpy as np
import matplotlib.pyplot as plt

if __name__ == '__main__':
    plt.figure(figsize=(10, 10))
    plt.plot(range(5), lw=2, label='Real')
    plt.title('Prediction')
    plt.legend(loc="best")
    plt.draw()
    plt.show()
    print("---Plot graph finish---")

Above will block until I close it.
Code:
import numpy as np
import matplotlib.pyplot as plt

if __name__ == '__main__':
    plt.ion()
    plt.figure(figsize=(10, 10))
    plt.plot(range(5), lw=2, label='Real')
    plt.title('Prediction')
    plt.legend(loc="best")
    plt.draw()
    plt.show()
    print("---Plot graph finish---")

Above will appear nothing, or it appear and disappear very fast.
My version is below:
user@ya:~/$ sudo pip freeze | grep matplotlib
matplotlib==2.2.3
user@ya:~/$ sudo pip -V
pip 18.1 from /usr/local/lib/python2.7/dist-packages/pip (python 2.7)

Environments:
I only execute script in Ubuntu ex: user@ya: python xxx.py
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.5 LTS
Release:    16.04
Codename:   xenial

Can anyone help me? I just want to do like Matlab which won't close the plotted graph even if the script finishes.

A: The plots will close when the script is finished, even if you use block=False
Similar to the answer here, when running from the terminal you have to call plt.show at the end of the script to keep these plots open after you've finished. I made a similar code to yours which works as intended; the plot simply refreshes at the end of the code. (added a for loop for a 5 second delay just so you can see it's running).
import numpy as np
import matplotlib.pyplot as plt
import time

if __name__ == '__main__':
    plt.figure(figsize=(10, 10))
    plt.plot(range(5), lw=2, label='Real')
    plt.title('Prediction')
    plt.legend(loc="best")
    plt.show(block=False)
    print("---Plot graph finish---")
    for i in range(5):
        print('waiting...{}'.format(i))
        time.sleep(1)
    print('code is done')
    plt.show()


Q: How to use 'LoginAsync' in SharePoint 2013 Visual Web part? We are working on Open ID authentication. For this we are using IdentityModel.OidcClient dll.
We want Access Token and IdentityToken. We can get both the tokens in one call using  below code snippet
var result = await _oidcClient.LoginAsync(DisplayMode.Visible);

LoginAsync is not working. We need to pass IBrowser object in "var options = new OidcClientOptions". We are not able to get IBrowser object.
We created Web Service and we are able to get IdentityToken using below code
var state = await _oidcClient.PrepareLoginAsync();

Above code snippet is returning redirect URI and from that URI we are able to fetch IdentityToken. But here, we are facing issue while fetching Access Token from the "tokenendpoint".
Now, we are using Visual Web Part and using LoginAsync method by passing "System Browser", "Extended Browser" and "WabBrowser" as IBrowser object in OidcClientOptions. We are getting below error

ActiveX control '' cannot be instantiated because the current thread is not in a single-threaded apartment.

It seems either we are missing something or our approach is not appropriate. Please let us know if any other DLL can be used for the same functionality in C#.


Q: Slide out animation of three elements on top of each other I'm looking for the best way to make the following animation. I've tried some solutions, but none of them seem to tackle my problem as every single solution seems to fail at some point. The animation I need to do is the following:

User swipes his finger up and the tableView & 1 & 2 scroll up (it's like tableView & 1 & 2 are one scrollable element). Then, when 2 becomes invisible upon the scroll, 3 & 1 & tableView become scrollable (again, as if it were one scrollable element). Then, when 3 becomes invisible (as it is scrolled) the tableView is then the only scrollable element.
What I tried:

*

*I initially tried with simple animations like changing height constraints for every 1/2/3 element based on the scroll offset and although it seemed fine to me, it didn't to the reviewer as he wanted more precise scrolling in between hiding elements animations

*I then tried to combine panGesture with scroll. I embedded 1 & 2 and tableView into one scroll View and set panGesture recognizer for it with delegate function shouldRecognizeSimultaneouslyWith returning true while having tableView scrolling disabled. Then, upon intersecting 3 I was disabling the panGesture and tried to enable tableView scrolling, but failed to recognize which panGesture/scrolling works or not, which one to disable, which one to fail or work alone/simultaneously.
How would you dear developers tackle it so that the animations are smooth and as described? Perhaps, you have an awesome idea :)

A: I'm using a simplified version of your idea with a UIScrollView & 3 UILabel instances.
You can easily adapt this to be UITableView & 3 UIView instances.
Idea

*

*UIScrollView & 3 UILabel instances have a common superview. In this case it's UIViewController.view.

*UIScrollView is laid out to be full screen (edge-to-edge) and extends below these 3 UILabel instances.

*UIScrollView has contentInset.top = height_of_three_labels so it's content starts below these other instances.

*Whenever UIScrollView.contentOffset changes, we shift frame.origin.y for these 3 instances to provide the needed effect.

UI Setup
import UIKit

class ViewController: UIViewController {

    let tileHeight: CGFloat = 60
    let view1 = UILabel()
    let view2 = UILabel()
    let view3 = UILabel()

    override func viewDidLoad() {
        super.viewDidLoad()

        let bounds = self.view.bounds

        let scrollView = UIScrollView(frame: bounds)
        scrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        scrollView.delegate = self
        scrollView.alwaysBounceVertical = true
        self.view.addSubview(scrollView)

        view1.frame = CGRect(x: 0, y: 2*tileHeight, width: bounds.width, height: tileHeight)
        configureLabel(view1, text: "1", backgroundColor: .red)

        view2.frame = CGRect(x: 0, y: tileHeight, width: bounds.width, height: tileHeight)
        configureLabel(view2, text: "2", backgroundColor: .blue)

        view3.frame = CGRect(x: 0, y: 0, width: bounds.width, height: tileHeight)
        configureLabel(view3, text: "3", backgroundColor: .green)

        scrollView.contentInset = UIEdgeInsets(top: 3*tileHeight, left: 0, bottom: 0, right: 0)

        // 3 is between 2 and 1, 1 is at the top, order is important here
        self.view.addSubview(view2)
        self.view.addSubview(view3)
        self.view.addSubview(view1)
    }

    private func configureLabel(_ label: UILabel, text: String, backgroundColor: UIColor) {
        label.text = text
        label.textColor = .white
        label.font = .boldSystemFont(ofSize: 34)
        label.textAlignment = .center
        label.backgroundColor = backgroundColor
    }

}

Scroll Management
extension ViewController: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offset = scrollView.adjustedContentInset.top + scrollView.contentOffset.y
        print(offset)
        if offset > 0 {
            view3.frame.origin.y = (offset > tileHeight) ? (tileHeight - offset) : 0
            view2.frame.origin.y = tileHeight - offset
            view1.frame.origin.y = 2*tileHeight - offset
        }
        else {
            view3.frame.origin.y = 0
            view2.frame.origin.y = tileHeight
            view1.frame.origin.y = 2*tileHeight
        }
    }
}

Output

A: I think you'll be fighting a losing battle trying to toggle scrolling.
Here's another approach...

*

*add the tableView as a subview of a "container" UIView

*add the three "top" views as subviews

*give the tableView a contentInset.top of the height of the three views plus vertical spacing

*constrain the three "top" views so

*

*3 will stick to the top, until it is pushed up by 1

*2 till slide under 3 when 1 pushes it up

*update the top constraint for 1 when the tableView scrolls

You can try it with this example code (no @IBOutlet connections needed):
class ExampleViewController: UIViewController, UIScrollViewDelegate {

    let tableView: UITableView = {
        let v = UITableView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.separatorInset = .zero
        return v
    }()
    let view1: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.textAlignment = .center
        v.backgroundColor = .systemRed
        v.text = "1"
        return v
    }()
    let view2: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.textAlignment = .center
        v.backgroundColor = .systemGreen
        v.text = "2"
        return v
    }()
    let view3: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.textAlignment = .center
        v.backgroundColor = .systemBlue
        v.text = "3"
        return v
    }()

    // this will hold the tableView and the
    //  three other views
    let containerView: UIView = {
        let v = UIView()
        v.translatesAutoresizingMaskIntoConstraints = false
        // clip to bounds to prevent the "top" views from showing
        //  as they are "pushed up" out of bounds
        v.clipsToBounds = true
        return v
    }()

    // this constraint constant will be changed
    //  in scrollViewDidScroll
    @IBOutlet var view1TopConstraint: NSLayoutConstraint!

    override func viewDidLoad() {
        super.viewDidLoad()

        // add our container view
        view.addSubview(containerView)

        // add our tableView and three "top" views
        containerView.addSubview(tableView)

        containerView.addSubview(view2)
        containerView.addSubview(view3)
        containerView.addSubview(view1)

        for v in [view1, view2, view3] {
            // all three "top" views should be
            //  equal width to tableView
            //  horizontally centered to tableView
            //  40-pts tall
            NSLayoutConstraint.activate([
                v.widthAnchor.constraint(equalTo: tableView.widthAnchor),
                v.centerXAnchor.constraint(equalTo: tableView.centerXAnchor),
                v.heightAnchor.constraint(equalToConstant: 40.0),
            ])
        }

        let g = view.safeAreaLayoutGuide
        NSLayoutConstraint.activate([

            // constrain container view with 20-pts "padding"
            containerView.topAnchor.constraint(equalTo: g.topAnchor, constant: 20.0),
            containerView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
            containerView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
            containerView.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: -20.0),

            // constrain all 4 sides of tableView ot container view
            tableView.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 0.0),
            tableView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 0.0),
            tableView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: 0.0),
            tableView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: 0.0),

        ])

        // view3 should stick to the top of the table,
        //  unless it's being pushed up by view1
        let v3Top = view3.topAnchor.constraint(equalTo: tableView.topAnchor)
        v3Top.priority = .defaultHigh + 1

        // view2 should stick to the bottom of view3,
        //  unless it's being pushed up by view1
        let v2Top = view2.topAnchor.constraint(equalTo: view3.bottomAnchor, constant: 4.0)
        v2Top.priority = .defaultHigh

        // view1 should ALWAYS be 4-pts from bottom of view2
        let v1TopA = view1.topAnchor.constraint(equalTo: view2.bottomAnchor, constant: 4.0)
        v1TopA.priority = .required

        // view1 should ALWAYS be greater-than-or-equal 4-pts from bottom of view3
        let v1TopB = view1.topAnchor.constraint(greaterThanOrEqualTo: view3.bottomAnchor, constant: 4.0)
        v1TopB.priority = .required

        // view1 top should ALWAYS be greater-than-or-equal top of tableView
        let v1TopC = view1.topAnchor.constraint(greaterThanOrEqualTo: tableView.topAnchor)
        v1TopC.priority = .required

        // 88-pts is 40-pts for view3 and view2 plus 4-pts vertical spacing

        // view1 top should NEVER be more-than 88-pts from top of tableView
        let v1TopD = view1.topAnchor.constraint(lessThanOrEqualTo: tableView.topAnchor, constant: 88.0)
        v1TopD.priority = .required

        // view1 top will start at 88-pts from top of tableView
        view1TopConstraint = view1.topAnchor.constraint(equalTo: tableView.topAnchor, constant: 88.0)
        view1TopConstraint.priority = .defaultHigh + 2

        // activate those constraints
        NSLayoutConstraint.activate([
            v3Top,
            v2Top,
            v1TopA,
            v1TopB,
            v1TopC,
            v1TopD,
            view1TopConstraint,
        ])

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        tableView.dataSource = self
        tableView.delegate = self

        // top inset is
        //  three 40-pt tall views
        //  plus 4-pts vertical spacing between each
        //  and 4-pts vertical spacing below view1
        tableView.contentInset.top = 132
        tableView.contentOffset.y = -132
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        // we're getting called when the tableView scrolls
        // invert the contentOffset y
        let y = -scrollView.contentOffset.y
        // subtract 44-pts (40-pt tall view plus 4-pts vertical spacing)
        view1TopConstraint.constant = y - 44.0
    }

}

extension ExampleViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 30
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let c = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        c.textLabel?.text = "Row \(indexPath.row)"
        return c
    }
}

Here's how it looks to start:

then, after scrolling up just a bit (2 is sliding under 3):

scrolling a bit more (1 is pushing 3 up and out of view):

and then table scrolling while 1 remains at the top:


Q: Preimage of codimension one subvarieties under a dominant map Let $f:X\to Y$ be a dominant morphism of projective varieties over an algebraically closed field. If $Z\subset Y$ is a codimension $1$ subvariety, do the irreducible components of $f^{-1}(Z)$ necessarily have codimension $1$ in $X$?
I am asking about codimension $1$ since I know codimension $1$ usually behaves the best.
If this is true, is there an easy explanation? If this is almost true, what is the correction?

A: EDIT: I rewrote this answer with more details.
You need some more assumptions; the easiest one I know is to require that the dimension of the fiber $f^{-1}(\eta)$ of the generic point $\eta \in Y$ is equal to $\dim(X) - \dim(Y)$.
(1)  Let $f : X \to Y$ be a morphism of schemes over a base scheme $S$.  Recall that if $X \to S$ is universally closed, then $f : X \to Y$ is also universally closed.  In fact we can factor $f$ through the closed immersion $X \hookrightarrow X \times_S Y$ and the projection $X \times_S Y \to Y$; closed immersions are proper, hence a priori universally closed, and the second is a base change of a universally closed morphism, hence also universally closed.  See (Stacks, 01W6).
(2)  Suppose the structural morphism $X \to S$ is universally closed.  Any $S$-morphism $f : X \to Y$ is closed by (1), and hence surjective if it is dominant.
(3)  The following proposition is from (EGA, IV_2, 5.6.6):
Let $X$ and $Y$ be irreducible schemes, $Y$ locally noetherian, $f : X \to Y$ dominant and locally of finite type.  Let $e = \dim(f^{-1}(\eta))$ be the dimension of the generic fiber ($\eta \in Y$ being the generic point).  Then one has the inequality
$$ \dim(X) \leq \dim(Y) + e. $$
Further, if $Y$ is universally catenary then one has equality if and only if
$$ \dim(Y) = \sup_{y \in f(X)} \dim(\mathscr{O}_{Y,y}). $$
Note that this clearly holds when $f$ is surjective (EGA, IV_2, 5.1.4).
(4)  Let $S$ be a locally noetherian and universally catenary scheme, and let $X$ and $Y$ be schemes locally of finite type over $S$, with $X$ proper over $S$.  Let $Z \subset Y$ be a closed irreducible subscheme, let $(W_\alpha)$ be the irreducible components of the inverse image $f^{-1}(Z)$, and let $f_\alpha : W_\alpha \to Z$ denote the restrictions of $f$ to $W_\alpha$.  Since $X$ and $Y$ are locally of finite type over $S$, $W_\alpha$ and $Z$ are locally of finite type over $S$ and it follows that $f_\alpha : W_\alpha \to Z$ are locally of finite type (Stacks, 01T8).  Also, $Z$ is universally catenary (Stacks, 02J9) and locally noetherian (Stacks, 01T6).  Since $W_\alpha$ is proper over $S$, $f_\alpha$ is surjective by (2).  Hence by (3) one sees
$$ \dim(W_\alpha) = \dim(Z) + e, $$
where $e$ is the dimension of the fiber of the generic point $\eta \in Y$, and in particular the inverse image $f^{-1}(Z)$ is purely of dimension $\dim(Z) + e$.
(5)  If $X$ and $Y$ are further biequidimensional (EGA, 0_IV, 14.3.3), i.e. one has the formula
$$ \dim(W) + \mathrm{codim}(W, X) = \dim(X) $$
for every closed subspace $W \subset X$ (and likewise for $Y$), then one can rewrite (4) as
$$ \mathrm{codim}(f^{-1}(Z), X) = \mathrm{codim}(Z, Y) + m - n - e, $$
where $m$ and $n$ are the dimensions of $X$ and $Y$, respectively.
(6)  In particular, when $S = \mathrm{Spec}(k)$ is the spectrum of a field $k$, then $X$ and $Y$ are biequidimensional (EGA, IV_2, 5.2.1) and the formula of (5) holds.  More generally, $S$ only needs to be Jacobson (and locally noetherian, universally catenary); this is not in EGA but I believe it's buried in some form in the Stacks project (see the comments on (Stacks, 02S2)).
(7)  Concluding, we have seen that in good cases, and in particular in your case, when the dimension of the generic fiber is equal to $\dim(X) - \dim(Y)$, the codimension of the inverse image $f^{-1}(Z)$ in $X$ is equal to the codimension of $Z$ in $Y$.

A: [This answer has been edited to discuss the general case.]
I will assume that variety means irreducible (otherwise you could work on individual irreducible components).  Then $f:X \to Y$ is dominant by assumption, and has closed image since its source is projective, thus it is surjective.
Thus $f^{-1}(Z) \to Z$ is also surjective.
Now, as described in e.g. this MO answer (or in a Hartshorne exercise, maybe in Section 4 of Chapter II), for the proper map $f$, the function $y \mapsto \dim f^{-1}(y)$ is upper semicontinuous, so if $z \in Z$, then the dimensions of $f^{-1}(z)$ are at least $\dim X - \dim Y$.  This implies that $f^{-1}(Z)$ contains components of
codimension $1$. (The intuition is just that we can add the dimension of $Z$ and of a typical fibre.  One way to make this precise is to note that if every component of $f^{-1}(Z)$ were of codimension at least $2$, then since it dominates $Z$, we would see that
a generic fibre would be of dimension $\dim X - \dim Y -1$, whereas we already noted that every fibre has dimension at least $\dim X - \dim Y$.)

In general you can't do better than this, because there are morphisms of $3$-folds (just to take an example) which are birational, but in which the preimage of some particular point $y \in Y$ is a curve.  Then if you take $Z$ to be a generic codim'n one subvariety passing through $y$, its preimage will be the union of a codim'n subvariety of $X$ (the proper transform of $Z$) and the curve $f^{-1}(P)$.   So in general you can't expect $f^{-1}(Z)$ to be equidimensional.
Note also that $f^{-1}(Z)$ can also contain multiple components of codimension $1$.  (E.g. let $X \to Y$ be the blow up of a surface at a point, and let $Z$ be a curve that passes through the blown up point.)

Rereading the question, I see that the point of the question might be the equidimensionality, and so you might be interested in the counterexample involving $3$-folds.  This MO question and answers gives one such example.


Q: How to compute $\sum_{n=0}^{\infty}{\frac{3^n(n + \frac{1}{2})}{n!}}$? I have to compute the series $\displaystyle\sum_{n=0}^{\infty}{\frac{3^n(n + \frac{1}{2})}{n!}}$.
$$\displaystyle\sum_{n=0}^{\infty}{\frac{3^n(n + \frac{1}{2})}{n!}} = \sum_{n=0}^{\infty}{\frac{3^n\frac{1}{2}}{n!}} + \sum_{n=0}^{\infty}{\frac{3^nn}{n!}} = \frac{e^3}{2} + \sum_{n=0}^{\infty}{\frac{3^nn}{n!}},$$ but how to compute the $\displaystyle\sum_{n=0}^{\infty}{\frac{3^nn}{n!}}$?

A: $$\begin{align}
\sum_{n=0}^\infty\frac{3^nn}{n!} & =0+\sum_{n=1}^\infty\frac{3^n}{(n-1)!}\\
& =\sum_{n=0}^\infty\frac{3^{n+1}}{n!}\\
& =3e^3.\\
\end{align}$$

A: $$\begin{align}\sum\limits_{n=0}^\infty \frac{n\cdot 3^n}{n!}&=0+\sum\limits_{n=1}^\infty \frac{3^n}{(n-1)!}\\&=3\sum\limits_{n=0}^\infty \frac{3^n}{n!}\\&=3\cdot e^3\end{align}$$

A: As for integer $n>0, n!=n\cdot(n-1)!,$
$$\sum_{n=0}^{\infty}{\frac{3^nn}{n!}}=\sum_{n=1}^{\infty}{\frac{3^nn}{n!}}=3\sum_{n=1}^\infty\dfrac{3^{n-1}}{(n-1)!}=?$$

A: Hint:
$$\sum_{n=0}^{\infty}{\frac{3^nn}{n!}}=0+3\sum_{n=1}^{\infty}{\frac{3^{n-1}}{(n-1)!}}$$

A: We have
$$
x(e^x)'=xe^x=\sum_{n=0}^\infty \frac{nx^n}{n!}
$$
Now take $x=3$.


Q: Building a nested HashMap I want to build a nested hashmap in java like this
   {Customer:
             {
              Area:{}
             }
      Bank:
            {
            City:{}
            }
   }

How can i do this?

A: The easiest way is to use a map as the value of your outer map, like the following:
Map<String, Map<String, String>> nestedMap = new HashMap<> ();
Map<String, String> fooInnerMap = new HashMap<> (), barInnerMap = new HashMap<> ();
nestedMap.put ("foo", fooInnerMap);
nestedMap.put ("bar", barInnerMap);

However, this is not really convenient to use. If you want better answers, please specify what you want and what you tried.
Your data structure, for example, looks like JSON. If you need your Map to save or exchange data, you could use a JSON library.


Q: React Material UI 2 TableRows in one loop error I'm making my first project in React and I have a problem rendering my table correctly.
What I'm trying to achieve is this;

The green brackets are what's inside my loop. The problem is that REACT says I need a wrapper for my TableRow-elements. I would assume my wrapper is my TableBody. The return method of my table looks like this;
return(

                    <TableHead>
                        <TableRow>
                            {this.props.headers.map((el, i) =>
                                <TableCell key={i+3}>{el}</TableCell>
                            )}
                        </TableRow>
                    </TableHead>
                    <TableBody>
                    {this.props.data.map((element, j) =>
                        <TableRow key={j+j+j+j+j}>
                            <TableCell key={element["Nr"]+j}>{element["Nr"]}</TableCell>
                            <TableCell key={element["Description"]+j}>{element["Description"]}</TableCell>
                            <TableCell key={element["Reference"]+j}>{element["Reference"]}</TableCell>
                            <TableCell key={element["Parameters"]+j}><FontAwesomeIcon data-index={j} className="font-awesome-icon info-icon" onMouseLeave={this.hideToolTip} onMouseEnter={this.showToolTip} icon={faInfoCircle} />
                                {toolTip[j]}
                            </TableCell>
                        </TableRow>
                        <TableRow> !!REACT WON'T ACCEPT  THIS SECOND TABLEROW!! </TableRow>
                    )}
                    </TableBody>

        )

The error is the following;
Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment < >...< />?
What I've tried so far is wrap both TableRows of this loop in a parent TableRow, but Table rows cannot directly contains Table rows, of course.
Any help is greatly appreciated!

A: In react some things (almost everything) needs the same start and end tag to be valid, take a return for example, this is valid:
export default observer(() => {
    return (

Hello

    )
})

This will reslut in a error
export default observer(() => {
    return (

Hello

    )
})

So what you can do is to use the <React.Fragment>tag around all code in your loop, or simply use a loop foreach block. This is valid
export default observer(() => {
    return (
     <React.Fragment>

Hello

     </React.Fragment>
    )
})

Your code with fragment
return(

                    <TableHead>
                        <TableRow>
                            {this.props.headers.map((el, i) =>
                                <TableCell key={i+3}>{el}</TableCell>
                            )}
                        </TableRow>
                    </TableHead>
                    <TableBody>
                    {this.props.data.map((element, j) =>
                       <React.Fragment>
                        <TableRow key={j+j+j+j+j}>
                            <TableCell key={element["Nr"]+j}>{element["Nr"]}</TableCell>
                            <TableCell key={element["Description"]+j}>{element["Description"]}</TableCell>
                            <TableCell key={element["Reference"]+j}>{element["Reference"]}</TableCell>
                            <TableCell key={element["Parameters"]+j}><FontAwesomeIcon data-index={j} className="font-awesome-icon info-icon" onMouseLeave={this.hideToolTip} onMouseEnter={this.showToolTip} icon={faInfoCircle} />
                                {toolTip[j]}
                            </TableCell>
                        </TableRow>
                        <TableRow> !!REACT WILL ACCEPT  THIS SECOND TABLEROW!! </TableRow>
                      </React.Fragment>
                    )}
                    </TableBody>

        )


Q: Using lazy-init pattern properties on Apex data objects in LWC More of a technical question than a philosophical, because I am mainly interested in the intelligence of the LWC cache and any performance implications.
I use the lazy-init pattern extensively in Apex, when implementing complex objects. The code usually looks something like this
@AuraEnabled
public List<String> Errors {
    public get {
        if (Errors == null) Errors = getErrors();
        return Errors;
    }
    private set;
}

Where Errors is an object property and getErrors() is a private function that initializes the List of errors (where I know, that once initialized, the errors will never change during the life-time of the object).
Now considering client/server round trips: What happens in LWC under the hood, if I use @wire to import and call an apex method that retrieves a list of objects with lazy-init properties? My JavaScript / HTML may access said properties. Are there any unnecessary round trips where it would be faster / more efficient to simply load all Properties with the constructor?
PS: I recently started with LWC, so I'm always thankful if you point me to existing resources that already answer my question.

A: When LWC actually calls some Apex, the AuraEnabled results are serialized to JSON, allowing it to be transported over HTTP (AJAX) to the client. That means the whole object (at least the AuraEnabled parts) is walked, during the serialization, to access all property values at that time. This means your properties will all get read (and therefore all your lazy loading private methods called as a side effect) at that point.
LWC communications do not get partial objects back and then fetch other parts later. (This is different to your application allowing partial object trees to be returned, but that's code you write to set up and return the required Apex objects.)


Q: iOS CoreBluetooth CBPeripheral didReceiveReadRequest I have two projects. One acts as central ,the other as a peripheral. Central has connected to peripheral, then central calls method readValueForCharacteristic.
Not immediately, but after about 5-10 seconds, peripheral invokes delegate method - (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request. Why is there a delay? How can I eliminate the delay?
 Any thoughts? I've been trying for almost a week now.
 Appreciate every helps, thanks
central
- (void)sendBtnClick:(id)sender
{
    USCPeerBtn *btn = (USCPeerBtn *)sender;
    CBPeripheral *peripheral = btn.connectedPeripheral;
    if (!peripheral) {
        return;
    }

    [self.charachterMDict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {

        if (key == peripheral) {
            [(CBPeripheral *)key readValueForCharacteristic:(CBCharacteristic *)obj]; // read
            *stop = YES;
        }
    }];
}

periperal
// CBPeripheralManagerDelegate
- (void)peripheralManager:(CBPeripheralManager *)peripheral  didReceiveReadRequest:(CBATTRequest *)request
{
    NSLog(@"didReceiveReadRequest");
}

A: Call respondToRequest: in method - (void)peripheralManager:(CBPeripheralManager *)peripheral  didReceiveReadRequest:(CBATTRequest *)request
// CBPeripheralManagerDelegate
- (void)peripheralManager:(CBPeripheralManager *)peripheral     didReceiveReadRequest:(CBATTRequest *)request
{
    [peripheral respondToRequest:request withResult:CBATTErrorSuccess];
    NSLog(@"didReceiveReadRequest");
}

@Paulw11 ,thanks


Q: How can I make a path for a folder on the root? Here is my directory:
/myweb
    /css
        style.css
    /img
        icon.png
    index.php
    .htaccess

I need to call icon.png in style.css. I've tested lots of cases but none of these works:
// style.css

url(../img/icon.png)
url(./img/icon.png)
url(/img/icon.png)
url(img/icon.png)
url(../icon.png)
url(./icon.png)

Does anybody know what's the correct path?

A: Calling url(../img/icon.png) is correct.
Did you try to call the image from somewhere else, in example for background:
body {
    background-image: url(../img/icon.png);
}

Also please check the configuration in your .htaccess.


Q: Extracting text from PDF file using pdfbox I am trying to extract text from PDF file using pdfbox but not as a command line tool but inside my Java app. I am downloading pdf using jsoup.
res = Jsoup
.connect(host+action)
.ignoreContentType(true)
.data(data)
.cookies(cookies)
.method(Method.POST)
.timeout(20*1000)
.execute();

// prepare document
InputStream is = new ByteArrayInputStream(res.bodyAsBytes());
PDDocument pdf = new PDDocument();
pdf.load(is,true);

// extract text
PDFTextStripper stripper = new PDFTextStripper();
String text = stripper.getText(pdf);

// print extracted text
System.out.println(text);

This code prints just empty line. When I do this:
System.out.println(res.body());

it prints the pdf file to output like this:
%PDF-1.4
%����
6 0 obj
<<
/Filter /FlateDecode
/Length 1869
>>
stream
x��X�n��

...
<<
/Size 28
/Info 27 0 R
/Root 26 0 R
>>
startxref
20632
%%EOF

So I am sure that pdf in downloaded correctly - just this PDF stripper doesnt work...
---------------------------------------------- edit
this problem is solved - working code is here http://thottingal.in/blog/2009/06/24/pdfbox-extract-text-from-pdf/

A: (Question answered in the comments. See Question with no answers, but issue solved in the comments (or extended in chat) )
@WeloSefer wrote:

maybe this can help you get started ... I have never worked with jsoup nor pdfbox so I am no help but I sure will try pdfbox since I've been testing itextpdf reader for extracting texts.

The OP wrote:

Thanks, that is what I was looking for - it works now :)
  this problem is solved - working code is here http://thottingal.in/blog/2009/06/24/pdfbox-extract-text-from-pdf/


Q: how to solve the no mono behavior script found error in unity? I have a problem with a game I am programming in unity. This specificaly occured when i added the script given below. the error message says that no monobehaviorscripts in the file, or their names do not match the file name. This script is meant to spawn the eniemies in the game.
I have already tried changing the class name, file name and copy the one into the other. but this does not seem to help.
screenshot unity of error message and code

i just edited my code and it does not seem to be solved.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class wavesystem : MonoBehaviour
{
    public int enimicount;
    public int[] enimi = { 1 };
    public int wave = 1;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (enimicount = 0)
        {
            int threat = 0;
            for (threat < wavesystem.wave)
            {
            int name = Random.Range(0, wavesystem.enimi.Length);
            int enimitreat = wavesystem.enimi[name];
            if (threat + enimitreat <= wave)
                {
                float xpos = Random.Range(0, 2);
                Instantiate("enimie" + name, (xpos, 1));
                wavesystem.enimicount = wavesystem.enimicount + 1;
                threat = threat + enimitreat;
                }

            }
            wavesystem.wave = wavesystem.wave + 1;
        }

    }
}

A: you need the exact same name in the unity editor for the script as well as in the  code editor (I suppose visual studio). the name is Case Sensitive and needs to be correctly spelled in each part. check the name and the location of the file and place them so they are easily found by you.
for example:
Name in unity: WaveSystem_LoL
//Name in C# code:

   public class WaveSystem_LoL : MonoBehavior

if they do not match the error will appear so double and even triple check!

A: Seems like your file name is different than class name. Your file name of cs file should be wavesystem.cs


Q: Laravel 5 shows php file content in browser (doesn't render html) Laravel 5 site doesn't render html, rather it shows php file content in browser. I tried various apache configurations and changes in htaccess but no luck. Not sure where this is going wrong.
Here is the .htaccess file
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>
DirectoryIndex index.php
RewriteEngine On

# Redirect Trailing Slashes...
#RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ public/$1 [L]
#  RewriteRule ^ index.php [L]

</IfModule>

and here is the apache conf file:
<VirtualHost *:80>
DocumentRoot /var/www/laravelapp/public
ServerName laravelapp.dev
ServerAlias laravelapp.dev
<Directory "/var/www/laravelapp/public">
 AllowOverride all
 Allow from all
</Directory>
</VirtualHost>


Q: AOSP - Android 6 Marshmallow compilation - make: *** [run_soong] Error 126 I've tried to compile Android 6 Marshmallow for my Sony Xperia Z1 Compact.
I've done everything what was in:
How to build AOSP Marshmallow for unlocked Xperia devices (developer.sonymobile.com)
and checking out:
Android - Downloading and Building (source.android.com)
on virtual machine with newest Debian (32-bit), but when I was on

To start the build, type: make –j < insert the cpu thread number of
  your computer >

I've received an error:
root@debian:~/android# make –j 8
============================================
PLATFORM_VERSION_CODENAME=REL
PLATFORM_VERSION=6.0.1
TARGET_PRODUCT=aosp_d5503
TARGET_BUILD_VARIANT=userdebug
TARGET_BUILD_TYPE=release
TARGET_BUILD_APPS=
TARGET_ARCH=arm
TARGET_ARCH_VARIANT=armv7-a-neon
TARGET_CPU_VARIANT=krait
TARGET_2ND_ARCH=
TARGET_2ND_ARCH_VARIANT=
TARGET_2ND_CPU_VARIANT=
HOST_ARCH=x86
HOST_2ND_ARCH=
HOST_OS=linux
HOST_OS_EXTRA=Linux-4.5.0-2-686-pae-i686-with-debian-stretch-sid
HOST_CROSS_OS=windows
HOST_CROSS_ARCH=x86
HOST_CROSS_2ND_ARCH=x86_64
HOST_BUILD_TYPE=release
BUILD_ID=MASTER
OUT_DIR=out
============================================
out/soong/soong: line 43: prebuilts/build-tools/linux-x86/bin/ninja: cannot execute binary file: Exec format error
build/core/soong.mk:87: recipe for target 'run_soong' failed
make: *** [run_soong] Error 126

#### make failed to build some targets (1 seconds) ####

Debug info:
root@debian:~/android# make -nd –j 8
GNU Make 4.1
Built for i586-pc-linux-gnu
Copyright (C) 1988-2014 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Reading makefiles...
Reading makefile 'Makefile'...
(...)
Reading makefile 'build/core/dumpvar.mk' (search path) (no ~ expansion)...
============================================
PLATFORM_VERSION_CODENAME=REL
PLATFORM_VERSION=6.0.1
TARGET_PRODUCT=aosp_d5503
TARGET_BUILD_VARIANT=userdebug
TARGET_BUILD_TYPE=release
TARGET_BUILD_APPS=
TARGET_ARCH=arm
TARGET_ARCH_VARIANT=armv7-a-neon
TARGET_CPU_VARIANT=krait
TARGET_2ND_ARCH=
TARGET_2ND_ARCH_VARIANT=
TARGET_2ND_CPU_VARIANT=
HOST_ARCH=x86
HOST_2ND_ARCH=
HOST_OS=linux
HOST_OS_EXTRA=Linux-4.5.0-2-686-pae-i686-with-debian-stretch-sid
HOST_CROSS_OS=windows
HOST_CROSS_ARCH=x86
HOST_CROSS_2ND_ARCH=x86_64
HOST_BUILD_TYPE=release
BUILD_ID=MASTER
OUT_DIR=out
============================================
Reading makefile 'build/core/ninja.mk' (search path) (no ~ expansion)...
Reading makefile 'build/core/soong.mk' (search path) (no ~ expansion)...
Reading makefile 'vendor/google/build/ninja_config.mk' (search path) (do not care) (no ~ expansion)...
Updating makefiles....
 Considering target file 'vendor/google/build/ninja_config.mk'.
  File 'vendor/google/build/ninja_config.mk' does not exist.
  Looking for an implicit rule for 'vendor/google/build/ninja_config.mk'.
  No implicit rule found for 'vendor/google/build/ninja_config.mk'.
  Finished prerequisites of target file 'vendor/google/build/ninja_config.mk'.
 Must remake target 'vendor/google/build/ninja_config.mk'.
 Failed to remake target file 'vendor/google/build/ninja_config.mk'.
 Considering target file 'build/core/soong.mk'.
  Looking for an implicit rule for 'build/core/soong.mk'.
  No implicit rule found for 'build/core/soong.mk'.
  Finished prerequisites of target file 'build/core/soong.mk'.
 No need to remake target 'build/core/soong.mk'.
 Considering target file 'build/core/ninja.mk'.
  Looking for an implicit rule for 'build/core/ninja.mk'.
  No implicit rule found for 'build/core/ninja.mk'.
  Finished prerequisites of target file 'build/core/ninja.mk'.
 No need to remake target 'build/core/ninja.mk'.
 Considering target file 'build/core/dumpvar.mk'.
  Looking for an implicit rule for 'build/core/dumpvar.mk'.
  No implicit rule found for 'build/core/dumpvar.mk'.
  Finished prerequisites of target file 'build/core/dumpvar.mk'.
 (...)
 No need to remake target 'build/core/main.mk'.
 Considering target file 'Makefile'.
  Looking for an implicit rule for 'Makefile'.
  No implicit rule found for 'Makefile'.
  Finished prerequisites of target file 'Makefile'.
 No need to remake target 'Makefile'.
Updating goal targets....
Considering target file '–j'.
 File '–j' does not exist.
  Considering target file 'ninja_wrapper'.
   File 'ninja_wrapper' does not exist.
    Considering target file 'out/combined-aosp_d5503.ninja'.
     File 'out/combined-aosp_d5503.ninja' does not exist.
      Considering target file 'out/build-aosp_d5503.ninja'.
       File 'out/build-aosp_d5503.ninja' does not exist.
        Considering target file 'prebuilts/build-tools/linux-x86/bin/ckati'.
         Looking for an implicit rule for 'prebuilts/build-tools/linux-x86/bin/ckati'.
         No implicit rule found for 'prebuilts/build-tools/linux-x86/bin/ckati'.
         Finished prerequisites of target file 'prebuilts/build-tools/linux-x86/bin/ckati'.
        No need to remake target 'prebuilts/build-tools/linux-x86/bin/ckati'.
        Considering target file 'prebuilts/build-tools/linux-x86/bin/makeparallel'.
         Looking for an implicit rule for 'prebuilts/build-tools/linux-x86/bin/makeparallel'.
         No implicit rule found for 'prebuilts/build-tools/linux-x86/bin/makeparallel'.
         Finished prerequisites of target file 'prebuilts/build-tools/linux-x86/bin/makeparallel'.
        No need to remake target 'prebuilts/build-tools/linux-x86/bin/makeparallel'.
        Considering target file 'out/Android.mk'.
         Finished prerequisites of target file 'out/Android.mk'.
        No need to remake target 'out/Android.mk'.
        Considering target file 'out/CleanSpec.mk'.
         Finished prerequisites of target file 'out/CleanSpec.mk'.
        No need to remake target 'out/CleanSpec.mk'.
        Considering target file 'run_soong'.
         File 'run_soong' does not exist.
          Considering target file 'out/soong/.soong.bootstrap'.
            Considering target file 'bootstrap.bash'.
             Looking for an implicit rule for 'bootstrap.bash'.
             No implicit rule found for 'bootstrap.bash'.
             Finished prerequisites of target file 'bootstrap.bash'.
            No need to remake target 'bootstrap.bash'.
           Finished prerequisites of target file 'out/soong/.soong.bootstrap'.
           Prerequisite 'bootstrap.bash' is older than target 'out/soong/.soong.bootstrap'.
          No need to remake target 'out/soong/.soong.bootstrap'.
          Considering target file 'out/soong/soong.variables'.
            Considering target file 'FORCE'.
             File 'FORCE' does not exist.
             Finished prerequisites of target file 'FORCE'.
            Must remake target 'FORCE'.
            Successfully remade target file 'FORCE'.
           Finished prerequisites of target file 'out/soong/soong.variables'.
           Prerequisite 'FORCE' of target 'out/soong/soong.variables' does not exist.
          Must remake target 'out/soong/soong.variables'.
mkdir -p out/soong/
(\
echo '{'; \
echo '    "Make_suffix": "-aosp_d5503",'; \
echo ''; \
echo '    "Platform_sdk_version": 23,'; \
echo '    "Unbundled_build": false,'; \
echo '    "Brillo": false,'; \
echo '    "Malloc_not_svelte": true,'; \
echo '    "Allow_missing_dependencies": false,'; \
echo '    "SanitizeHost": [],'; \
echo '    "SanitizeDevice": [],'; \
echo '    "HostStaticBinaries": false,'; \
echo ''; \
echo '    "DeviceName": "amami",'; \
echo '    "DeviceArch": "arm",'; \
echo '    "DeviceArchVariant": "armv7-a-neon",'; \
echo '    "DeviceCpuVariant": "krait",'; \
echo '    "DeviceAbi": ["armeabi-v7a", "armeabi"],'; \
echo '    "DeviceUsesClang": true,'; \
echo ''; \
echo '    "DeviceSecondaryArch": "",'; \
echo '    "DeviceSecondaryArchVariant": "",'; \
echo '    "DeviceSecondaryCpuVariant": "",'; \
echo '    "DeviceSecondaryAbi": ["", ""],'; \
echo ''; \
echo '    "HostArch": "x86",'; \
echo '    "HostSecondaryArch": "",'; \
echo ''; \
echo '    "CrossHost": "windows",'; \
echo '    "CrossHostArch": "x86",'; \
echo '    "CrossHostSecondaryArch": "x86_64",'; \
echo '    "Safestack": false'; \
echo '}') > out/soong/soong.variables.$$; \
if ! cmp -s out/soong/soong.variables.$$ out/soong/soong.variables; then \
  mv out/soong/soong.variables.$$ out/soong/soong.variables; \
else \
  rm out/soong/soong.variables.$$; \
fi
          Successfully remade target file 'out/soong/soong.variables'.
          Considering target file 'out/soong/.soong.in_make'.
           Finished prerequisites of target file 'out/soong/.soong.in_make'.
          No need to remake target 'out/soong/.soong.in_make'.
          Pruning file 'FORCE'.
         Finished prerequisites of target file 'run_soong'.
        Must remake target 'run_soong'.
out/soong/soong out/soong/build.ninja  -w dupbuild=err
        Successfully remade target file 'run_soong'.
        Pruning file 'FORCE'.
       Finished prerequisites of target file 'out/build-aosp_d5503.ninja'.
      Must remake target 'out/build-aosp_d5503.ninja'.
echo Running kati to generate build-aosp_d5503.ninja...
prebuilts/build-tools/linux-x86/bin/ckati --ninja --ninja_dir=out --ninja_suffix=-aosp_d5503 --regen --ignore_dirty=out/% --no_ignore_dirty=out/soong/Android-aosp_d5503.mk --no_ignore_dirty=out/soong/make_vars-aosp_d5503.mk --ignore_optional_include=out/%.P --detect_android_echo --use_find_emulator -f build/core/main.mk  --gen_all_targets BUILDING_WITH_NINJA=true SOONG_ANDROID_MK=out/soong/Android-aosp_d5503.mk SOONG_MAKEVARS_MK=out/soong/make_vars-aosp_d5503.mk
Putting child 0x94b8a18 (out/build-aosp_d5503.ninja) PID 8221 on the chain.
Live child 0x94b8a18 (out/build-aosp_d5503.ninja) PID 8221
/bin/bash: prebuilts/build-tools/linux-x86/bin/ckati: cannot execute binary file: Exec format error
Reaping losing child 0x94b8a18 PID 8221
build/core/ninja.mk:161: recipe for target 'out/build-aosp_d5503.ninja' failed
make: *** [out/build-aosp_d5503.ninja] Error 126
Removing child 0x94b8a18 PID 8221 from chain.

#### make failed to build some targets (1 seconds) ####

What should I do to compile this correctly?

A: This post is not going to be an answer, it didn't really solve the problem. The purpose is to provide more valuable information.
Create two symbolic links in your build top directory. It will get rid of the problem. Run following command in you build top directory.
$ ln -s build/soong/bootstrap.bash
$ ln -s build/soong/Android.bp

But as you go further, you will encounter problems like following
FAILED: out/soong/.bootstrap/bin/minibp -t -m ./build/soong/build.ninja.in -b out/soong -d out/soong/.bootstrap/bootstrap.ninja.in.d -o out/soong/.bootstrap/bootstrap.ninja.in Android.bp
error: Android.bp:81:1: "soong-android" depends on undefined module "blueprint"
error: Android.bp:81:1: "soong-android" depends on undefined module "blueprint-bootstrap"
[2/4] minibp out/soong/.bootstrap/primary.ninja.in
FAILED: out/soong/.bootstrap/bin/minibp --build-primary -t -m ./build/soong/build.ninja.in --timestamp out/soong/.bootstrap/primary.ninja.in.timestamp --timestampdep out/soong/.bootstrap/primary.ninja.in.timestamp.d -b out/soong -d out/soong/.bootstrap/primary.ninja.in.d -o out/soong/.bootstrap/primary.ninja.in Android.bp
error: Android.bp:13:1: "soong_build" depends on undefined module "blueprint"
error: Android.bp:13:1: "soong_build" depends on undefined module "blueprint-bootstrap"
ninja: error: rebuilding 'out/soong/build.ninja': subcommand failed
make: *** [run_soong] Error 1

I have no idea how to solve this either. Maybe the new build system for aosp master branch is not fully prepared.


Q: Como fazer nested tables com bootstrap? Como posso fazer nested tables com o bootstrap como neste exempo com ASP.Net?

Há forma de fazer isso com bootstrap?

A: Assumindo o uso de jQuery pode fazer o seguinte:

function esconderLinha(idDaLinha) {

    // procura o elemento com o ID passado para a função e coloca o estado para o contrario do estado actual
    $("#" + idDaLinha).toggle();
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

        Contact Name

        City

        <button onClick="esconderLinha('linhaAEsconder')">
          +
        </button>

      Maria Anders
      Berlin

                Order Id

                Date

                10643

                8/25/1997 12:00:00 AM

A: No caso o Bootstrap requer jQuery, então você pode usar jQuery, apenas é preciso aportar o elemento com $(...).next().
Exemplo:

$(document).on("click", ".mytable .open", function() {
    var tr = $(this).parents("tr").next();
    if (tr.hasClass("hide")) {
       tr.removeClass("hide");
    } else {
       tr.addClass("hide");
    }
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

            x
            y
            z

            <button class="btn open">+</button>
            x
            y

            Sua sub tabela deve vir aqui

            <button class="btn open">+</button>
            x
            y

            Sua sub tabela deve vir aqui

            <button class="btn open">+</button>
            x
            y

            Sua sub tabela deve vir aqui

Exemplo 2:
Automaticamente fecha os outros elementos
:

$(document).on("click", ".mytable .open", function() {
    var tr = $(this).parents("tr").next();

    if (tr.hasClass("hide")) {
       //Fecha todos outros tr antes de abrir o escolhido
       $(".mytable .subcontent").addClass("hide");

       //Abre o escolhido
       tr.removeClass("hide");
    } else {
       tr.addClass("hide");
    }
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

            x
            y
            z

            <button class="btn open">+</button>
            x
            y

            Sua sub tabela deve vir aqui

            <button class="btn open">+</button>
            x
            y

            Sua sub tabela deve vir aqui

            <button class="btn open">+</button>
            x
            y

            Sua sub tabela deve vir aqui


Q: Как сделать ограничение на количество кликов в секунду js Как можно реализовать ограниченное количество кликов в секунду по кнопке с помощью js.
Если вот такой вот код - jsfiddle.net
Нужно сделать так чтобы на кнопку с id="big-btn" можно было нажать не больше 15 раз в 1 секунду. Если пользователь нажимает более 15 раз то должно срабатывать действие, например появляться всплывающие окно.
var clicks = 0;

function insertText(clicks) {
  document.getElementById('clicks-count').innerText = clicks;
}

const onClick = () => {
    clicks += 1;
    insertText(clicks);
}

document.getElementById('big-btn').addEventListener('click', onClick)

  <button id="big-btn">Клик</button>

0

A: Речь точно о кликах мышкой, не о нажатиях клавиши? Не могу представить себе человека, кликающего 15 раз в секунду. :)
В любом случае, можно использовать такую конструкцию. Она будет обрабатывать клики раз в 100мс, все остальные клики игнорируются.

var clicks = 0;

function delay(f) {

  let isCooldown = false;

  return function() {
    if (isCooldown) return;

    f.apply(this, arguments);

    isCooldown = true;

    setTimeout(() => isCooldown = false, 100);
  };

}

function insertText(clicks) {
  document.getElementById('clicks-count').innerText = clicks;
}

const onClick = () => {
    console.log('click!');
    clicks += 1;
    insertText(clicks);
}

document.getElementById('big-btn').addEventListener('click', delay(onClick))

  <button id="big-btn">Клик</button>

0


Q: input type hidden attribute value missing when I inspect with Fiddler For the same request, the attrib value of tag input type=hidden is not displayed on the content (raw text) of the response using Fiddler and VStudio debugger. But when I inspect the code with Chrome it is displayed. Why does this happen?  See these snapshots:
Element inspect from google

Inspector response content from Fiddler4

I'm a beginner in HTTP and HTML.


Q: How to add a Hyperlink to a tab in Excel? I want to add a hyperlink to a Tab in Excel. Actually I want to do it as an Excel Add in?
But now it seems there is not option for it by customizing ribbon directly. I know there is document location with a drop down list. But I want a link to a URL. From what I know hyperlinks can be placed on cells only. Please give me some ideas.

A: What is a hyperlink, really? Its a text "button" that, when clicked, brings you to a website or opens a link of some sort.
So in this case, use a button in a tab on the Excel ribbon that when clicked brings you to a website. Easy:
Private Sub MyRibbonButton_Click(Byval sender as Object, Byval e as EventArgs) Handles MyRibbonButton.Click

System.Diagnostics.Process.Start("my website url")

End Sub

Does it look like a button? Of course, but essentially it's just a hyperlink, right?

A: Use a CustomUI to create buttons for macros:
'To send email
'Callback for customButton onAction
Sub MyWeb(control As IRibbonControl)
Dim oShell As Object
Set oShell = CreateObject("Wscript.Shell")
    oShell.Run ("http://www.plugpro.com.br")
End Sub

'To Open URL
'Callback for customButton onAction
Sub MyWeb(control As IRibbonControl)
Dim oShell As Object
Set oShell = CreateObject("Wscript.Shell")
    oShell.Run ("mailto:oton@podium.pro.br")
End Sub


Q: Jquery cross domain request? I just need a single digit returned, but I can't get it to work I am making a dashcode webapp and all I want is a single digit, a 1 or 0 returned from an external server so if there is an easier way to do this please let me know.  I am using the plug in found at http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/ to try to make a cross domain request, but everything I am trying isn't working.
When I run this code
$.ajax({
  url: "status.html",
  context: document.body,
  success: function(data){
    alert("working" + data);
  }
});

everything works perfectly and an alert with the text "working1" is displayed, but when I run this code
$.ajax({
  url: "http://externalsite.com/status.html",
  context: document.body,
  success: function(data){
    alert("working" + data);
  }
});

nothing happens.  Can anyone help?  This is just what I am trying now, I've also tried a .get request and the returned data was "objectObject"  I also tried a php proxy without any luck.  I'm just asking for a simple solution to return a SINGLE number from an external server.

A: If you can control other server output, put header:
Access-Control-Allow-Origin: *

in http response, and load with ajax without plugins or using YQL
https://developer.mozilla.org/en/HTTP_access_control

A: It looks like the plugin is making a JSONP request via YQL (see line 18 here).
If you load up Firebug or the developer tools in Chrome, do you see the JSONP request being made?


Q: Redirect to a specific page when WooCommerce product search returns "no product found" In Woocommerce I am trying to use the following code snippet to redirect to a specific page of my site instead of showing "no result found" on an empty product search.
Now the shortcode [insert page id="99"] doesn't work, and displays [insert page id="99"] as plain text. If I use shortcode any shortcode like '[recent_products per_page="4"]' it displays products.
remove_action( 'woocommerce_no_products_found', 'wc_no_products_found' );
add_action( 'woocommerce_no_products_found', 'show_products_on_no_products_found', 20 );
function show_products_on_no_products_found() {
    echo '<h4>' . __( 'Are u looking for this?', 'domain' ) . '</h4>';
    echo do_shortcode( '[insert page id="99"]' );
}

But I want is to redirect to a specific WordPress page which post id is 99.
How to redirect user to a specific page when a product search returns "no product found"?

A: Using template_redirect hook, you can redirect user to a specific page when there is "no results found" on a product query search, like:
add_action( 'template_redirect', 'no_products_found_redirect' );
function no_products_found_redirect() {
    global $wp_query;
    if( isset($_GET['s']) && isset($_GET['post_type']) && 'product' === $_GET['post_type']
    && ! empty($wp_query) && $wp_query->post_count == 0 ) {
        wp_redirect( get_permalink( 99 ) );
        exit();
    }
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.


Q: Turn "fieldname .startsWith. 'fieldValue'" into .Where(p => p.fieldname.StartsWith('fieldValue')) predicate? I attempted to do this below, with mind blanks as it got complicated.
I need to build a predicate to pass to my Product Repository from a client string:
"fieldname .startsWith. 'fieldvalue'"
"fieldname .contains. 'fieldvalue'"
"fieldname .equals. 3"
"fieldname .greaterThan. 3"
"fieldname .lessThan. 3"

The field names could be any existing field in the Entity.  It's there job to match them exactly.  There are only numbers and string, and only the commands listed.
Code so far (wild flailing):
// p => p.L == R
// L is the left side (the field to examine)
// R is the right side (the value to compare to)
// O is the operator (Equal)

var fieldParm    = Expression.Parameter(typeof(Entity), typeof(Entity).Name);

var compareL1 = MemberExpression.Property(fieldParm, "fieldName"); // fieldname
var compareR1 = Expression.Constant("fieldValue");  // what field should equal
var compareO1 = MemberExpression.Equal(compareWhat, compareTo);

// Do it again for each one (probably should make a foreach out of this)
var compareL2 = MemberExpression.Property(fieldParm, "fieldName"); // fieldname
var compareR2 = Expression.Constant("fieldValue");  // what field should equal
var compareO2 = MemberExpression.Equal(compareWhat, compareTo);

// Put them all together
var myExpress = Expression.And(compareO1, compareO2) // And them together

// Create predicate
Expression<Func<Entity, bool>> resultLambda =
    Expression.Lambda<Func<Entity, bool>>( myExpress,
        new ParameterExpression[] { fieldParm });

And resultLambda should contain our predicate to pass to our .Where() clause
How would you do this for a series of AND conditions like above?


Q: Adding an Enter key to the end of scanned data I have Motorola MC32.. and Windows CE 7.
I intend to use Symbol.Barcode2 namespace and looking for the setting to set this data modifying rule.
There is the Datawedge preinstalled but I want to set the rule programmaticaly. I have found nothing in EMDK Help.
Could somebody help me where can I found this opportunity?