text:
Q: Fortify, how to start analysis through command How we can generate FortiFy report using command ??? on linux.
In command, how we can include only some folders or files for analyzing and how we can give the location to store the report. etc.
Please help....
Thanks,
Karthik

A: 1. Step#1 (clean cache)

*

*you need to plan scan structure before starting:

scanid = 9999 (can be anything you like)
ProjectRoot = /local/proj/9999/
WorkingDirectory = /local/proj/9999/working

*

*(this dir is huge, you need to "rm -rf ./working && mkdir ./working" before every scan, or byte code  piles underneath this dir and consume your harddisk fast)

log = /local/proj/9999/working/sca.log
source='/local/proj/9999/source/src/**.*'
classpath='local/proj/9999/source/WEB-INF/lib/*.jar; /local/proj/9999/source/jars/**.*; /local/proj/9999/source/classes/**.*'

./sourceanalyzer -b 9999 -Dcom.fortify.sca.ProjectRoot=/local/proj/9999/ -Dcom.fortify.WorkingDirectory=/local/proj/9999/working -logfile  /local/proj/working/9999/working/sca.log  -clean

*

*It is important to specify ProjectRoot, if not overwrite this system default, it will put under your /home/user.fortify

*sca.log location is very important, if fortify does not find this file, it cannot find byte code to scan.

*You can alter the ProjectRoot and Working Directory once for all if your are the only user: FORTIFY_HOME/Core/config/fortify_sca.properties).

*In such case, your command line would be ./sourceanalyzer -b 9999  -clean
2. Step#2 (translate source code to byte code)
nohup ./sourceanalyzer -b 9999 -verbose -64 -Xmx8000M -Xss24M -XX:MaxPermSize=128M -XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC  -XX:+UseParallelGC -Dcom.fortify.sca.ProjectRoot=/local/proj/9999/ -Dcom.fortify.WorkingDirectory=/local/proj/9999/working  -logfile /local/proj/9999/sca.log -source 1.5 -classpath '/local/proj/9999/source/WEB-INF/lib/*.jar:/local/proj/9999/source/jars/**/*.jar:/local/proj/9999/source/classes/**/*.class'  -extdirs '/local/proj/9999/source/wars/*.war'  '/local/proj/9999/source/src/**/*'  &

*

*always unix background job (&) in case your session to server is timeout, it will keep working.

*cp : put all your known classpath here for fortify to resolve the functiodfn calls. If function not found, fortify will skip the source code translation, so  this part will not be scanned later. You will get a poor scan quality but FPR looks good (low issue reported). It is important to have all dependency jars in place.

*-extdir: put all directories/files you don't want to be scanned here.

*the last section, files between ' ' are your source.

*-64 is to use 64-bit java, if not specified, 32-bit will be used and the max heap should be <1.3 GB (-Xmx1200M is safe).

*-XX: are the same meaning as in launch application server. only use these to control the class heap and garbage collection. This is to tweak performance.

*-source is java version (1.5 to 1.8)
3. Step#3 (scan with rulepack, custom rules, filters, etc)
nohup ./sourceanalyzer -b 9999  -64 -Xmx8000M -Dcom.fortify.sca.ProjectRoot=/local/proj/9999 -Dcom.fortify.WorkingDirectory=/local/proj/9999/working -logfile /local/ssap/proj/9999/working/sca.log **-scan** -filter '/local/other/filter.txt' -rules '/local/other/custom/*.xml -f '/local/proj/9999.fpr' &

*

*-filter: file name must be filter.txt, any ruleguid in this file will not be reported.

*rules: this is the custom rule you wrote. the HP rulepack is in FORTIFY_HOME/Core/config/rules directory

*-scan : keyword to tell fortify engine to scan existing scanid. You can skip step#2 and only do step#3 if you did notchange code, just want to play with different filter/custom rules
4. Step#4 Generate PDF from the FPR file (if required)
./ReportGenerator -format pdf -f '/local/proj/9999.pdf' -source '/local/proj/9999.fpr'


text:
Q: Questions about algebraic identities When people talk about algebraic identities, such as in A Collection of Algebraic Identities, are those variables appearing in them varying in $\mathbb{R}$, $\mathbb{C}$ or some even more general set? I am particularly interested in the last possibility, i.e. what is the most general set where algebraic identities hold?
Are algebraic identities subjects studied in number theory or abstract algebra?
Thanks and regards!

A: Where the variables come from can only be ascertained from the context in which they appear. Your link gives a huge number of identities, and I'm not going to go through the whole site to see the context for each one. Here's one of them: $$n^2+(n+1)^2+(n^2+n)^2=(n^2+n+1)^2$$ It's clear from the context that the author has it in mind that $n$ is an integer. This particular identity certainly holds in any ring that has a $1$ in it.
Algebraic identities are studied in Number Theory and in abstract algebra.

A: The identities you reference are almost all comprised of (multivariate) polynomials with integer coefficients. As such they remain true over any commutative ring, whether interpreted formally (equal iff coefficients are equal) or functionally (equal as functions on an infinite coefficient ring).
Beware that equivalence between formal and functional polynomials may fail over finite rings, e.g. $\rm\: x^p = x\:$ as functions on $\rm\:\mathbb Z/p\ =\:$ integers $\rm\:(mod\ p)\:,\ $ since $\rm\ a^p \equiv a\ (mod\ p)\ $ for all $\rm\ a\in\mathbb Z/p\ $ by Fermat's little Theorem. However this equality is not true when considered as formal polynomials over $\rm\mathbb Z/p$ since, by definition, formal polynomials are equal iff their coefficient sequences are equal; equivalently, subtracting, a formal polynomial is zero iff all of its coefficients are zero.

redpajama_set_name: RedPajamaStackExchange


text:
Q: avoid spaces and apostrophes problems with ls in a awk script I have many identical files in two (local) devices, and it happens that I have renamed some, only in one device (A). I found the following way to rename the identical files in the other device (B), according to the new names in device A, so that at the end I have identical both files and namefiles, without deleting or copying anything, but only renaming.
Indeed I found an interesting answer is here from Hai Vu (the second answer).
The script works, but there are two problems:

*

*with spaces in filenames: the names are truncated by spaces. and

*with apos (') in filenames

The script (rename-identical-files.awk) is
/^total/ {next} # Skip the first line (which contains the total, of ls -l)

{
    if (name[$5] == "") {
    name[$5] = $NF
    print "# File of size", $5, "should be named", $NF
 } else {
    printf "mv '%s' '%s'\n", $NF, name[$5]
 }
}

and it is called from command line (in the destination folder):
awk -f ~/rename-identical-files.awk <(ls -l /model-folder-path) <(ls -l) | sh

The problem seems ls command, that has limits (at least) with spaces and other characters in filenames.
What code should I write, to avoid space (and apostrophes) problems?

A: Yes, there's no easily way to parse the output of ls reliably.
Here, you could use zsh instead:
#! /bin/zsh -
zmodload zsh/stat || exit
typeset -A size_to_name
model_folder=${1?}

for f in $model_folder/*(ND.); do
  stat -LA size +size -- $f &&
    size_to_name[$size]=$f:t &&
    print -r "# File of size $size should be named ${(q)f:t}"
done

for f in *(ND.); do
  stat -LA size +size -- $f &&
    (($+size_to_name[$size])) &&
    [[ $f != $size_to_name[$size] ]] &&
    print -r mv -i -- ${(qq)f} ${(qq)size_to_name[$size]}
done

(to be run as that-script /model-folder-path)
Which should work correctly regardless of what characters or non-characters the file names may contain.
Pipe to sh once you've verified it was correct. Note that we don't check for the case where two files have the same size. In that case, the last in lexical order will be picked (if a and z both have size 42 in the model_folder, then any file of size 42 will be renamed to z in the current folder (though -i will give you a chance to avoid overwriting the first with the second)).

A: It'll be more accurate to use checksums to identify the identical files
between the 2 directories: with bash 4.3+ you can do
getFiles() {
    local -n _files=$1
    local dir=${2:-.}
    cd "$dir"
    for file in *; do
        [[ -d $file ]] && continue
        read sum name < <(md5sum "$file")
        _files[$sum]="$file"
    done
    cd -
}

declare -A pwdFiles
getFiles pwdFiles

declare -A modelFiles
getFiles modelFiles /model-folder-path

for sum in "${!pwdFiles[@]}"; do
    if [[ -v modelFiles[$sum] ]]; then
        mv -v "${pwdFiles[$sum]}" "${modelFiles[$sum]}"
    fi
done

A: Assuming this will be a one-off operation to fix a previous mistake in renaming, what's wrong with a simple diff, something like (untested):
for newfile in *; do
    for oldpath in /model-folder-path/*; do
        if ! diff -q "$oldpath" "$newfile" >/dev/null; then
            oldfile=${oldpath##*/}
            if [[ "$oldfile" != "$newfile" ]]; then
                if [[ -f "$oldfile" ]]; then
                    echo "clash on $oldfile" >&2
                    exit 1
                fi
                mv -- "$newfile" "$oldfile"
            fi
        fi
    done
done


text:
Q: Custom authentication through API I have a laravel API project. I want to be able to send a login request and get back a token depending on some custom logic. I am not using a database  so i cant use the default auth.
I have set up a provider called AuthCustomProvider.

namespace App\Providers;
use Auth;
use App\Authentication\UserProvider;
use Illuminate\Support\ServiceProvider;

class AuthCustomProvider extends ServiceProvider
{
    /**
     * Perform post-registration booting of services.
     *
     * @return  void
     */
    public function boot()
    {
        Auth::provider('custom_auth', function($app, array $config) {
            return new UserProvider();
        });
    }
    /**
     * Register bindings in the container.
     *
     * @return  void
     */
    public function register()
    {
        //
    }
}

I have then added this to the config/app.php file in the providers array:
'providers' => [

    App\Providers\AuthCustomProvider::class,

Then i added my custom providers driver to the config/auth.php file in the providers array:
'providers' => [
   'users' => [
       'driver' => 'custom_auth',
   ],
],

As im not using a database, I took out the model property
Lastly I created a folder called App/Authentication which i put my UserProvider.php file in which is this:
<?php

namespace App\Authentication;

use Illuminate\Contracts\Auth\UserProvider as IlluminateUserProvider;

class UserProvider implements IlluminateUserProvider
{
    /**
     * @param    mixed  $identifier
     * @return  \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveById($identifier)
    {
        // Get and return a user by their unique identifier
    }

    /**
     * @param    mixed   $identifier
     * @param    string  $token
     * @return  \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveByToken($identifier, $token)
    {
        // Get and return a user by their unique identifier and "remember me" token
    }

    /**
     * @param    \Illuminate\Contracts\Auth\Authenticatable  $user
     * @param    string  $token
     * @return  void
     */
    public function updateRememberToken(Authenticatable $user, $token)
    {
        // Save the given "remember me" token for the given user
    }

    /**
     * Retrieve a user by the given credentials.
     *
     * @param    array  $credentials
     * @return  \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveByCredentials(array $credentials)
    {
        // Get and return a user by looking up the given credentials
    }

    /**
     * Validate a user against the given credentials.
     *
     * @param    \Illuminate\Contracts\Auth\Authenticatable  $user
     * @param    array  $credentials
     * @return  bool
     */
    public function validateCredentials(Authenticatable $user, array $credentials)
    {
        // Check that given credentials belong to the given user
    }

}

So lastly i make a function on the login controller. This is what the api call goes to:
public function Login(Request $request)
{
        $user  = Consultant::lookup('UserId', 1);
        //Returns collection of user details (user id, username etc)

        //Logic will go here in the future
        $logThemIn = true;

        if ($logThemIn)
        {
            auth()->login($user);
            //return oauth2 token
        }
}

So this is where im at now, if i run this, im getting the error:
'Declaration of App\Authentication\UserProvider::updateRememberToken(App\Authentication\Authenticatable $user, $token) must be compatible with Illuminate\Contracts\Auth\UserProvider::updateRememberToken(Illuminate\Contracts\Auth\Authenticatable $user, $token)'
Im new to laravel and there isnt alot of tutorials for what im trying to do that i can find. Any help is greatly appriciated

A: Change your UserProvider to this which uses Illuminate\Contracts\Auth\Authenticatable instead of App\Authentication\Authenticatable, php will load a class from the current namespace if one isn't specified.
<?php

namespace App\Authentication;

use Illuminate\Contracts\Auth\UserProvider as IlluminateUserProvider;
use Illuminate\Contracts\Auth\Authenticatable;

class UserProvider implements IlluminateUserProvider
{
    /**
     * @param    mixed  $identifier
     * @return  \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveById($identifier)
    {
        // Get and return a user by their unique identifier
    }

    /**
     * @param    mixed   $identifier
     * @param    string  $token
     * @return  \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveByToken($identifier, $token)
    {
        // Get and return a user by their unique identifier and "remember me" token
    }

    /**
     * @param    \Illuminate\Contracts\Auth\Authenticatable  $user
     * @param    string  $token
     * @return  void
     */
    public function updateRememberToken(Authenticatable $user, $token)
    {
        // Save the given "remember me" token for the given user
    }

    /**
     * Retrieve a user by the given credentials.
     *
     * @param    array  $credentials
     * @return  \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveByCredentials(array $credentials)
    {
        // Get and return a user by looking up the given credentials
    }

    /**
     * Validate a user against the given credentials.
     *
     * @param    \Illuminate\Contracts\Auth\Authenticatable  $user
     * @param    array  $credentials
     * @return  bool
     */
    public function validateCredentials(Authenticatable $user, array $credentials)
    {
        // Check that given credentials belong to the given user
    }
}

A: You forgot to import Authenticatable. Just add:
use Illuminate\Contracts\Auth\Authenticatable;


text:
Q: How to pass parameters thru URL? I have two input text box, one recaptcha and submit button.
I want to check if the values that inputted by the user are in the database and if the recaptcha is checked. But the database is located on another server.
The one server, is running Wordpress which is the form is located. Here's the link
The second server, where the database is located and this server doing checking of the inputted values.
How to do this? Thanks.


text:
Q: Data consistency in XA transactions Suppose we have a database (e.g. Oracle) and a JMS provider (e.g. HornetQ) participating in an XA transaction. A message is sent to a JMS queue and some data are persisted in the database in the same distributed transaction. After the transaction is committed, a message consumer will read the persisted data and process them in a separate transaction.
Regarding the first XA transaction, the following sequence of events may be executed by the transaction manager (e.g. JBoss)

*

*prepare (HornetQ)

*prepare (Oracle)

*commit (HornetQ)

*commit (Oracle)

What happens if the message consumer starts reading the data after commit is completed in HornetQ, but is still being executed in Oracle? Will the message consumer read stale data?
The question can be generalized to any kind of multiple resources participating in XA transactions, i.e. is there a possibility for a small time window (when commit phases are executed) in which a reader from another concurrent transaction can get an inconsistent state (by reading committed data from one resource and stale data from another one)?
I would say that the only way for transactional resources to prevent this is to block all readers of affected data once the prepare phase is completed until the commit is issued. This way the example message consumer mentioned above would block until data is committed in the database.

A: Unfortunately XA transactions don't support consistency. When mapped to CAP theorem XA solves Availability and Partition tolerence across multiple datastores. In doing so it must sacrifice on Consistency. When using XA you have to embrace eventual consistency.
In any event creating systems that are CP or AP is hard enough that regardless of your datastore or transactional model you will face this problem.

A: I have a some experience with a bit of different environment based on Weblogic JMS and Oracle 11g. In this answer I suppose that it is working exactly the same. I hope my answer will help you.
In our case there was a "distant" system which was obligatory to notify based on the different events happend inside the local system. The other system also red into our database so the use-case seems almost identical to your problem. The sequence of the events was exacly the same as yours. On the test systems there was not a single faulire. Everyone thought that it will work but some of us doubted if it is the correct solution. As the software hit production some of the BPM processes run unpredictably. So a simple answer to your question: yes it is possible and everyone should be aware it.
Our solution (in my opinion) was not a well planned one, but we recognised that the little time window between the two commit is braking the system, so we added some "delay" to the queue (if I remember it was like 1-2 minutes). It was enough to finish the other commit and read consistent data. In my point of view it is not the best solution. It is not solving the syncronisation problem (what if an oracle transaction is longer than 1-2mins?).
Here is a great blog post that is worth to read and the last solution seems the best to me. We implemented it in an other system and it is working way better. Important to notice that you should limit the retries (re-reads) to prevent "stuck" threads. (With some error reporting.) With this restrictions I was not able to find better solution so far, so if anyone got some better option I am looking forward to hear it. :)
Edit: typos.

A: Yes. It is possible for an external system to receive and consume the messages you send before the DB actually commits, even if the transaction fails and rolls back afterwards.
For the last two years I've been doing maintenance and development of a distributed system using XA transactions with WebSphere MQ as JMS provider and Oracle 11g as backing DB.
One of its batch jobs would read offline messages from the DB, send them to JMS and mark them as sent in the DB -- all as part of the same XA transaction. If any of the messages or the DB failed, the transaction would be rolled back.
Some times, a message would be too large for JMS and cause the send() to fail and the whole transaction to rollback(), leaving the DB unchanged.
However, an external consumer was still receiving and processing every single message sent before the rollback. I knew because they would send me an email for every message processed, and I was getting lots of emails about messages that weren't marked as sent in the DB (because the transaction had been rolled back).
If this external system was to somehow SELECT COUNT(*) the number of messages sent by my system, it would read 0 messages sent, despite having already consumed hundreds of them.
So, yes it is possible for an external system to read stale data even when using XA transactions.

A: I will insert a status field, so after the each step, if it was successful, the status will be updated, and the reader should check the status before performing an operation.


text:
Q: LINQ OrderBy is not sorting correctly I hope someone can prove me wrong here :)
If I do this:
List<string> a = new List<string> { "b", "c", "a", "aa" };
var b = a.OrderBy(o => o).ToList();

I would expect the result of 'b' to be:
a
aa
b
c

Instead, the result I get is:
a
b
c
aa

How can I get OrderBy to do a "correct" alphabetical sort?
Am I just plain wrong? :)

A: Most likely a cultural thing. You could try this:
List<string> a = new List<string> { "b", "c", "a", "aa" };
var b = a.OrderBy(o => o, StringComparer.InvariantCultureIgnoreCase).ToList();

A: You're in the Danish culture, which treats aa as å and puts it after ø accordingly. You can pass a string comparer that acts differently to OrderBy to change that:
var b = a.OrderBy(o => o, StringComparer.InvariantCulture).ToList();


text:
Q: Remove all rows having a specific value in dataframe This might be a duplicate question as I couldn't find the one with an explanation.
I have a dataframe and I want to remove all rows having 999.9 values. But somehow couldn't do it.
df1 = pd.DataFrame({'a':[999.9,999.9,1,3,2], 'b':[999.9,1,999.9,1, 2]})
df1 = df1.loc[(df1 != 999.9).any(1)]
print(df1)

In this case, I would like to drop the 1st and 2nd rows.

A: Try:
df1 = pd.DataFrame({'a':[999.9,999.9,1,3,2], 'b':[999.9,1,999.9,1, 2]})
print(df1[~(df1==999.9).any(axis=1)])

Output:
     a    b
3  3.0  1.0
4  2.0  2.0

A: you check df1 != 999.9 in this check only first row delete because for other row you have column that != 999.9.
Try this:
>>> mask = (df1 == 999.9).any(1)
>>> df1[~mask]

# for more explanation

>>> df1 == 999.9
       a    b
0   True    True
1   True    False
2   False   True
3   False   False
4   False   False

in your solution:
>>> (df1 != 999.9)
       a    b
0   False   False
1   False   True
2   True    False
3   True    True
4   True    True

>>> (df1 != 999.9).any(axis = 1) # for check rows
0    False
1     True
2     True
3     True
4     True
dtype: bool

>>> (df1 != 999.9).any(axis = 0) # for check columns
a    True
b    True
dtype: bool


text:
Q: How do I customize the colors used by 'jq -C'? How do I specify colors other than the defaults used for jq --color-output?

A: Support for the JQ_COLORS environment variable was added to the development version on April 29, 2017 (that is, after the release of jq 1.5), with the following documentation:

To configure alternative colors just set the JQ_COLORS
environment variable to colon-delimited list of partial terminal
escape sequences like "1;31", in this order:
- color for `null`
- color for `false`
- color for `true`
- color for numbers
- color for strings
- color for arrays
- color for objects

The default color scheme is the same as setting
"JQ_COLORS=1;30:0;39:0;39:0;39:0;32:1;39:1;39".
This is not a manual for VT100/ANSI escapes.  However, each of
these color specifications should consist of two numbers separated
by a semi-colon, where the first number is one of these:
- 1 (bright)
- 2 (dim)
- 4 (underscore)
- 5 (blink)
- 7 (reverse)
- 8 (hidden)

and the second is one of these:
- 30 (black)
- 31 (red)
- 32 (green)
- 33 (yellow)
- 34 (blue)
- 35 (magenta)
- 36 (cyan)
- 37 (white)


text:
Q: Showing full categorical x-axis even when there are no points to plot I am using plotly to plot a scatter plot with line+markers. The problem is that I have a categorical x-axis and I want to fix it for full range static on all plots.
Below is the example code:
import(plotly)
x_group <- c('[8-9]','[9-10]','[10-11]','[11-12]','[12-13]','[13-14]','[14-15]','[16-17]','[17-18]','[18-19]','[19-20]')
total <- c('22','17','27','8 ','16','4 ','17','12','15','2 ','22')

example_df <- as.data.frame(list(hour_bin_grp= x_group, total = total))

m <- list(
  l = 50,
  r = 50,
  b = 100,
  t = 100,
  pad = 4
)

hour_bins <- c("[0-7]","[7-8]","[8-9]","[9-10]","[10-11]", "[11-12]","[12-13]", "[13-14]", "[14-15]", "[15-16]","[16-17]", "[17-18]","[18-19]", "[19-20]", "[20-21]","[21-22]")
p <- plot_ly(example_df, x = ~hour_bin_grp, y = ~total, type = 'scatter', mode = 'markers+lines') %>%
  layout(autosize = T, margin = m,
         xaxis = list(
           type='category',
           categoryorder= 'array',
           showgrid = TRUE,
           autorange = FALSE,
           showticklabels = TRUE,
           categoryarray= unique(hour_bins)
         ),
         yaxis = list(
           showgrid = TRUE,
           autorange = TRUE,
           showline = TRUE,
           showticklabels = TRUE,
           rangemode = "tozero",
         ))
p

The plot seems okay, but I want to fix the range of x-axis  to values of hour_bins.
I have already looked up some of the articles on the same, but it does not seem to work under my condition:
Plotly.js: Cannot show full categorical x-axis
https://community.plot.ly/t/cannot-re-arrange-x-axis-when-axis-type-is-category/1274/3

A: As a workaround I'd suggest using numeric ticks with character ticktext:
library(plotly)

bin_df <- data.frame(hour_bins = c("[0-7]","[7-8]","[8-9]","[9-10]","[10-11]", "[11-12]","[12-13]", "[13-14]", "[14-15]", "[15-16]","[16-17]", "[17-18]","[18-19]", "[19-20]", "[20-21]","[21-22]"))
bin_df$hour_bin_grp <- seq_len(nrow(bin_df))

example_df <- data.frame(hour_bin_grp = bin_df$hour_bin_grp[bin_df$hour_bins %in% c('[8-9]','[9-10]','[10-11]','[11-12]','[12-13]','[13-14]','[14-15]','[16-17]','[17-18]','[18-19]','[19-20]')], total = as.numeric(c('22','17','27','8','16','4','17','12','15','2','22')))

p <- plot_ly(example_df, x = ~hour_bin_grp, y = ~total, type = 'scatter', mode = 'markers+lines') %>%
  layout(xaxis = list(
    tickmode = "array",
    tickvals = bin_df$hour_bin_grp,
    ticktext = example_df$hour_bins,
    range = list(min(bin_df$hour_bin_grp), max(bin_df$hour_bin_grp))
  ))
p


text:
Q: Parsing XML - get node based on children I am struggeling to get the node based on the children. So I wan't to get the full person by id 4061106. I am using SimpleXMLElement, for now I did a foreach loop to display all persons but I cannot figure out how to get by a specific id. I do not even know where to start from.
<list>
        <person>
            <id>4061106</id>
            <name>Stefan</name>
            <country></country>
            <is_admin>0</is_admin>
            <lastCallbackTime></lastCallbackTime>

        </person>
        <person>
            <id>4082930</id>
            <name>Mike</name>
            <is_admin>0</is_admin>
            <lastCallbackTime></lastCallbackTime>

        </person>
</list>

A: You need to use Xpath to find the  node with the correct value, and then jump back up to the parent  node.
$xml = '
  <list>
    <person>
      <id>4061106</id>
      <name>Stefan</name>
      <country></country>
      <is_admin>0</is_admin>
      <lastCallbackTime></lastCallbackTime>
    </person>
  </list>
';

$sxml = simplexml_load_string($xml);
$person = $sxml->xpath('/list/person/id[.="4061106"]/parent::person')[0];

echo (string) $person->name; // Stefan


text:
Q: Listview.ItemDrag files handling I am creating a repository for files I use daily at work, using a TabControl to hold multiple ListView holders. I have managed to create the Drag-Drop functionality from inside the ListView to outside my program using the following code inside the ListView.ItemDrag event handler:
Dim fileFullPath As String
Dim mySelectedItem As ListViewItem = lvTools.SelectedItems(0)
Dim dropList As New StringCollection
'DataObject requires a StringCollection
Dim DragPaths As New DataObject()

fileFullPath = Path.Combine(ToolsDirectory, mySelectedItem.Tag)

Try
    'The fileInfo is created because it lets the DoDragDrop be faster
    Dim fileToDrop As New FileInfo(fileFullPath)
    dropList.Add(fileFullPath)

    DragPaths.SetFileDropList(dropList)
    DoDragDrop(DragPaths, DragDropEffects.All)
Catch FNTE As FileNotFoundException
    MsgBox("File could not be found: " & fileFullPath)
Catch ex As Exception
    MsgBox(ex.ToString)
End Try

Do you have any idea how could I copy the contents of the .txt files instead of copying the files?

A: I figured this out, please refer to the following code for solution:
If File.Exists(fileFullPath) Then
    Using tr As TextReader = New StreamReader(fileFullPath)
        Dim fileToDrop As New FileInfo(fileFullPath)
        dropList.Add(fileFullPath)

        DragPaths.SetFileDropList(dropList)
        Dim filecontent As String = tr.ReadToEnd()
        DoDragDrop(filecontent, DragDropEffects.Copy)
    End Using
End If


text:
Q: Mutt login failed in Ubuntu Can anyone please help me.
i'm trying to configure the mutt in Ubuntu .I'm using the below configuration in muttrc :
set imap_user = "khalid@gmail.com"
set imap_pass = "PASS"
set smtp_url = "smtp://khalid@smtp.gmail.com:587/"
set smtp_pass = "PASS"
set from = "khalid@gmail.com"
set realname = "khalid khalid"
set folder = "imaps://imap.gmail.com:993"
set spoolfile = "+INBOX"
set postponed="+[Gmail]/Drafts"
set header_cache=~/.mutt/cache/headers
set message_cachedir=~/.mutt/cache/bodies
set certificate_file=~/.mutt/certificates

while i am writing mutt in terminal i'm getting the below error:
login failed .
any solution for this please

A: *

*Ensure you have enabled IMAP access in your Gmail account.

*Try with the following settings:
set from      = khalid@gmail.com
set realname  = "khalid khalid"
set imap_user = khalid@gmail.com
set imap_pass = PASS
set smtp_url  = smtp://khalid@gmail.com@smtp.gmail.com:587/
set smtp_pass = PASS

set folder    = imaps://imap.gmail.com/
set spoolfile = imaps://imap.gmail.com/INBOX
set postponed = "+[Gmail]/Drafts"

set header_cache     =~/.mutt/cache/headers
set message_cachedir =~/.mutt/cache/bodies
set certificate_file =~/.mutt/certificates

A: I also faced same issue. After Turning on "Less secure app access" in Google account settings, it started working.
hope it may help others.

A: I have the same issue, then I turn on Less secure app access https://myaccount.google.com/lesssecureapps then it works..

A: I finally found a solution to this!

*

*I first tried what @1sloc did by removing quotes.

*I even used an App Password - Some forms stated that using an
app password helped.

*Another attempt I did was giving access to less secure apps. Use this
link
Every time I debugged it with the code below
mutt -d 1

All I kept getting was Login Failed

Then I came across this link posted by Google. The last step is
  what solved the problem. It told me to log in from the new device now
  and it finally worked!!!

It might be different for everyone but try all the above methods and see which one works for you. Also try using passwords without special characters @1sloc said. It might just solve your issue instantly
========================================================================

A: The reason for the "Login failed" error may be the wrong password.
If you have special symbols like "$" in your password, you should use single quotes:
set imap_pass = 'PassWith$Symbol'

Double quotes didn't help.
To investigate causes of message "Login failed." you should enable debug by command:
mutt -d 5

5 mean the most verbose output)
Output could be founded in ~/.muttdebug0 file by default.
Debug possibility shoud be enabled.
To check whether there is a parameter or not by this:
    mutt -v | grep DEBUG
Output must be like this:
+DEBUG

I have same config file and tested it with gmail. It worked successfully.

A: In case of accounts with 2FA (Second Factor) you can follow this simple guide
Basically, you should be able to generate 'application password' for gmail here


text:
Q: PHP MySQL: Insert record with self-referencing lookup field but can't get past foreign key constraint So i have the table company defined as follows:
CREATE TABLE IF NOT EXISTS chkdcrm.company (
  company_id INT(11) NOT NULL AUTO_INCREMENT,
  name_de VARCHAR(150) NOT NULL,
  parent_company INT(11) NULL,
  PRIMARY KEY (company_id),
  CONSTRAINT parent_company
    FOREIGN KEY (parent_company)
    REFERENCES chkdcrm.company (company_id)
    ON DELETE SET NULL)
ENGINE = InnoDB;

And for the HTML-Form I have:
<?php
  $require_once '../conn.php';
  //...
  $parent_company="";
  if($_SERVER["REQUEST_METHOD"] == "POST"){
    //codes...
  if ($_POST["parent_company"] == '') {
      $parent_company = 'NULL';
    }
    else {
      $parent_company = $_POST["parent_company"];
    }

  $sql = "INSERT INTO company (name_de, parent_company) VALUES (?, ?)";
  if($stmt = mysqli_prepare($conn, $sql)){
    mysqli_stmt_bind_param($stmt, 'si', $param_name, $param_parent);
    $param_name = $name_de;
    $param_parent = $parent_company;
    mysqli_stmt_execute($stmt) or die(mysqli_error($conn));
    $company_id = mysqli_insert_id($conn);
    mysqli_stmt_close($stmt);
    mysqli_close($conn);
}
?>

//HTML-Form...

    Parent company(if exists)

    <?php
      echo '<select name="parent_company">';
      echo '<option value=""></option>';
      $result = mysqli_query($conn, "SELECT company_id, name_de FROM company ORDER BY name_de ASC");
      while ($row = mysqli_fetch_assoc($result)){
        echo '<option value = "'.$row['company_id'].'">'.$row['name_de'].'</option>';
      }
      echo '</select>';
     ?>

The goal is to select the parent company from the lookup field. But I can't figure out how to insert companies that doesn't have a parent company (i.e the parent_company = NULL). I get the error message:
Cannot add or update a child row: a foreign key constraint fails (chkdcrm.company, CONSTRAINT parent_company FOREIGN KEY (parent_company) REFERENCES company (company_id) ON DELETE SET NULL).
I think the problem is that since company_id is int, it doesn't accept NULL value. Therefore it's treated as an invalid insert. But how can I get around this problem? Can someone please help me?


text:
Q: Polytopes characterization in $\mathbb R^n$ Given $P = \{x \in\mathbb R^n \mid a_1x_1 + \ldots + a_nx_n = \text{constant}\}$,  $(a_1, \ldots , a_n) \ne 0$.
Can $P$ be a polytope? I think that with $N = 1$, $P$ is a point. Can a point in $\mathbb R^1$ be a polytope?
Thank you all!

A: This is essentially an issue of semantics. There are two ways of defining polytopes: the V-representation (the convex hull of a finite set of points) and the H-representation (the intersection of half-spaces).
V-representations are always compact, but H-representations don't have to be. A lot of people would reserve the word "polytope" for these objects when they are compact. Can you see how $P$ is the intersection of two halfspaces?


text:
Q: What to do with a 503 error message when using Ajax Post on LIVE server? My app works fine on my local machine. I'm able to perform all Ajax calls perfectly. Tested thoroughly on several web browsers and everything works seamlessly on localhost. Problems are now happening on live server. While some Ajax calls work, the most important one which is register.php does not. Upon contacting my host, they told me they can't help me since it's outside their scope which is fine I'm on my own. But is a 503 not something they should handle? They told me the php.ini is read-only(shared hosting)... So does it mean I'm doom or what am I doing wrong here? Php is activated on livesite and I also have a live database(mariadb). I'm using phpmailer in the register.php script but they told me I was allowed to use it. Any help?
This is the error I receive in the console on live site :

A: Since it is a 503 server-side error I would try re-uploading the problem files since the other files seem to be working. Maybe some files got corrupted during transfer. Let us know if you solve it and what the problem was.


text:
Q: Find sufficient and necessary conditions on the variable $t$ such that the interval $I$ contain at least one prime numbrer Find sufficient and necessary conditions on the variable $t$ such that the interval $$I=(((ln(t))/(ln2)),((ln(1+t))/(ln2)))$$ contain at least one prime numbrer. I thought about some konwn bounds on prime numbers such as the well known result of Ingham that there is a constant $K$ such that for $x≥1$ there is a prime $p$ satisfying
$$x<p<x+Kx^{(5/8)}$$
and the fact that there is at least one prime between $x³$ and $(x+1)³$ for every $x≥10⁶⁰⁰⁰⁰⁰⁰⁰⁰⁰⁰⁰⁰⁰⁰⁰⁰⁰⁰$. However, I am not able to use these facts to prove my question.

A: It has nothing to do with known bounds on prime numbers. Suppose $p$ lies in that interval. Then
\begin{align}
&& \frac{\ln t}{\ln 2} &< p < \frac{\ln (1+t)}{\ln 2}\\
&\iff & \ln t &< p\ln 2 < \ln (1+t)\\
&\iff& t &< 2^p < 1+t\\
&\iff & 2^p-1 &< t < 2^p.
\end{align}


text:
Q: Vaadin7 Project wirh Maven + Tomcat7 compile error Hi I'm working with Vaadin7 Project.
I am having a hard time with compiling the project.
I really frustrated since I could not run a Simple HelloWorld Project :-(
I am using eclipse Kepler on OSX.
What I have done and tried are below.

*

*Made a Maven Project with some options(add vaadin-archtype-application).

*Add <dependency>vaadin-charts to pom.xml. I follow the guide here. Link : https://vaadin.com/book/vaadin7/-/page/addons.maven.html

*Run this Project with Tomcat and I got error message about widgetset. So I did maven build just like this Link told. Link : Failed to load Widgetsets in maven project in eclipse

*Run Project As Maven clean

*found two warning about version(apache-maven-compiler-plugin, org-mortbat-jetty), so I add  tags. each are 3.1 and 8.1.15.v20140411(Found this in Maven Repository site)

*it seems that everything is fine but My project shows 404 error
There is no web.xml and I really do not know where to fix this.
I think it is quite near to watch 'click' button in Chrome, but can not find.
My Error Log is below
SEVERE: ClassNotFoundException while loading persisted sessions: java.lang.ClassNotFoundException: org.owls.test.VaadinMay.MyVaadinUI
java.lang.ClassNotFoundException: org.owls.test.VaadinMay.MyVaadinUI
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1702)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:270)
    at org.apache.catalina.util.CustomObjectInputStream.resolveClass(CustomObjectInputStream.java:76)
    at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1612)
    at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1517)
    at java.io.ObjectInputStream.readClass(ObjectInputStream.java:1483)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1333)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
    at java.util.HashMap.readObject(HashMap.java:1183)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1017)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1893)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1798)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1350)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1990)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1915)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1798)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1350)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1990)
    at java.io.ObjectInputStream.defaultReadObject(ObjectInputStream.java:500)
    at com.vaadin.server.VaadinSession.readObject(VaadinSession.java:1436)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1017)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1893)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1798)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1350)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
    at org.apache.catalina.session.StandardSession.readObject(StandardSession.java:1597)
    at org.apache.catalina.session.StandardSession.readObjectData(StandardSession.java:1062)
    at org.apache.catalina.session.StandardManager.doLoad(StandardManager.java:284)
    at org.apache.catalina.session.StandardManager.load(StandardManager.java:204)
    at org.apache.catalina.session.StandardManager.startInternal(StandardManager.java:491)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5443)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)

Jun 01, 2014 10:39:41 PM org.apache.catalina.session.StandardManager startInternal
SEVERE: Exception loading sessions from persistent storage
java.lang.ClassNotFoundException: org.owls.test.VaadinMay.MyVaadinUI
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1702)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:270)
    at org.apache.catalina.util.CustomObjectInputStream.resolveClass(CustomObjectInputStream.java:76)
    at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1612)
    at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1517)
    at java.io.ObjectInputStream.readClass(ObjectInputStream.java:1483)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1333)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
    at java.util.HashMap.readObject(HashMap.java:1183)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1017)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1893)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1798)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1350)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1990)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1915)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1798)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1350)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1990)
    at java.io.ObjectInputStream.defaultReadObject(ObjectInputStream.java:500)
    at com.vaadin.server.VaadinSession.readObject(VaadinSession.java:1436)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1017)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1893)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1798)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1350)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
    at org.apache.catalina.session.StandardSession.readObject(StandardSession.java:1597)
    at org.apache.catalina.session.StandardSession.readObjectData(StandardSession.java:1062)
    at org.apache.catalina.session.StandardManager.doLoad(StandardManager.java:284)
    at org.apache.catalina.session.StandardManager.load(StandardManager.java:204)
    at org.apache.catalina.session.StandardManager.startInternal(StandardManager.java:491)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5443)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)

Thanks for sharing my problem :D
============ Edited on 06/02/2014 =======================
My maven clean looks fine. I attached logs
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Vaadin Web Application 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.4.1:clean (default-clean) @ VaadinMvn ---
[INFO] Deleting /Users/juneyoungoh/Documents/vaadinwork/VaadinMvn/target
[INFO]
[INFO] --- vaadin-maven-plugin:7.1.8:clean (default) @ VaadinMvn ---
[INFO] auto discovered modules [org.owls.test.VaadinMvn.AppWidgetSet]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.496s
[INFO] Finished at: Mon Jun 02 21:32:12 KST 2014
[INFO] Final Memory: 6M/81M
[INFO] ------------------------------------------------------------------------

========= Edit #02 ========================
Upper one is Maven clean, and I found an error in Maven build.
I think it could be a clue.
[INFO] --- vaadin-maven-plugin:7.1.8:update-theme (default) @ VaadinMvn ---
[INFO] Updating theme VAADIN/themes/mytheme
[ERROR] Jun 02, 2014 10:22:16 PM com.vaadin.server.widgetsetutils.ClassPathExplorer getAvailableWidgetSetsAndStylesheets
[ERROR] INFO: Widgetsets found from classpath:
[ERROR]     com.vaadin.DefaultWidgetSet in jar:file:/Users/juneyoungoh/.m2/repository/com/vaadin/vaadin-client/7.1.8/vaadin-client-7.1.8.jar!/
[ERROR]     com.vaadin.addon.charts.Widgetset in jar:file:/Users/juneyoungoh/.m2/repository/com/vaadin/addon/vaadin-charts/1.0.0/vaadin-charts-1.0.0.jar!/
[ERROR]     com.vaadin.addon.timeline.gwt.TimelineWidgetSet in jar:file:/Users/juneyoungoh/.m2/repository/com/vaadin/addon/vaadin-charts/1.0.0/vaadin-charts-1.0.0.jar!/
[ERROR]     org.owls.test.VaadinMvn.AppWidgetSet in file:/Users/juneyoungoh/Documents/vaadinwork/VaadinMvn/src/main/java
[ERROR] Addon styles found from classpath:
[ERROR]
[ERROR] Jun 02, 2014 10:22:17 PM com.vaadin.server.widgetsetutils.ClassPathExplorer getAvailableWidgetSetsAndStylesheets
[ERROR] INFO: Search took 27ms

And I found a post in Vaadin forums. but it does not look like my problem. it is about Ivy setting. However link is below
https://vaadin.com/forum/#!/thread/3529974

A: 1) SEVERE: ClassNotFoundException while loading persisted sessions:java.lang.ClassNotFoundException: org.owls.test.VaadinMay.MyVaadinUI pops up because Tomcat is trying to deserialize a previously saved session, and you might have changed some class names in the meantime. This can be disabled globally by editing the CATALINA_HOME/conf/context.xml file. You should find a line reading "Uncomment this to disable session..." More about this here
2) HTTP 404 should have nothing to do with the point above, and is most likely due to your servlet configuration. Since you have no web.xml, everything should be set-up from inside your UI. Open MyVaadinUi, or whatever you have renamed it to, and see the configuration for the URL path mapping as described in the vaadin documentation (scroll down to chapter 4.8.5 Servlet Mapping with URL Patterns). Make sure you are accessing the application on localhost as per this configuration and you should be fine.


text:
Q: Android convert JSONArray to String Array I get data from Json and there's a Json array. I want to convert that Json array into String array, so I can send it into another activity and show it in ListView.
Here's My java code
    if (jsonStr != null) {
        try {

            foodsFilter = new JSONArray(jsonStr);

            // looping through All Contacts
            for (int i = 0; i < foodsFilter.length(); i++) {

                JSONObject c = foodsFilter.getJSONObject(i);
                if(c.getString("category_name").equals("Food")) {
                String category_name = c.getString(TAG_CATEGORY_NAME);
                String filter_type = c.getString(TAG_FILTER_TYPE);
                //String item_list = c.getString(TAG_ITEM_LIST);
                JSONArray itemList = new JSONArray(c.getString("item_list"));
                String item_list = itemList.toString();

                // tmp hashmap for single contact
                HashMap<String, String> filter = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                filter.put(TAG_CATEGORY_NAME, category_name);
                filter.put(TAG_FILTER_TYPE, filter_type);
                filter.put(TAG_ITEM_LIST, item_list);

                // adding contact to contact list
                foodsFilterList.add(filter);

                }
            }
        } catch (JSONException e) {
           e.printStackTrace();
        }
   }

I try that code to convert the JSONarray, but I realized that code is for convert the JSONArray into String.
Here's my JSON data
[{"category_name":"Food","filter_type":"Sort by","field_name":"","type":"VALUE","table_name":"","item_list":["Ascending","Descending"]}]

I want to convert the item_list Array into like this
item_list = {"Ascending", "Descending"}

So I can send it into another activity use Intent and show it in ListView

A: What you have
String item_list = itemList.toString();

You need to parse items_list which is a JSONArray.
JSONArray itemList = new JSONArray(c.getString("item_list"));
// loop through the array itemList and get the items
for(int i=0;i<itemList.length();i++)
{
String item = itemList.getString(i); // item at index i
}

Now you can add the strings to a list/array and then do what is required.

A: Please have a look on this tutorial.
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
Maybe this would help you.
ArrayList<String> stringArray = new ArrayList<String>();
JSONArray jsonArray = new JSONArray();
for(int i = 0, count = jsonArray.length(); i< count; i++)
{
    try {
        JSONObject jsonObject = jsonArray.getJSONObject(i);
        stringArray.add(jsonObject.toString());
    }
    catch (JSONException e) {
        e.printStackTrace();
    }
}


text:
Q: In android, is it possible to create a notification when another app is opened? I'd like to know if it is possible to create a notification or toast/alert from my app when another app is opened. For example, my app Foo will create a notification if Facebook is opened.
Edit: What I actually want is to inform the user that my app is running in the background when the default camera app opens/running. My app will modify photos taken with the default camera app when it is running in the background and I want to inform the user that it will do so. Is this possible?

A: Basically what you want is a push notification. Please go through following tuts to help yourself:
https://neurobin.org/docs/android/push-notification-gcm-client-server/
https://developers.google.com/cloud-messaging/android/start

A: Yeah, you can take a look at this and then schedule an alarm using some background running process that looks for Facebook being running.
One way is to use AlarmManager to check running apps every 5-10 mins and you can generate a notification if your condition is met.


text:
Q: Differentiator Op-Amp Circuit not giving correct output using single power rail Im trying to simulate an differentiator Op-Amp using a single supply and the LM324 opamp. I built the differentiator circuit using a voltage divider and the LM3234 opamp.
The input wave is a Sinusodial wave, but the output wave is a square wave, but its suppose to be a phas shifted amplified sinusodial wave. I can get the amplification, but my output wave is not a sin wave.
What am I doing wrong, and how can i fix this?
Here is the Schematic of the circuit:

Here is a screenshot of the output:

Heres an example of what the output should be:
(the sin wave is the input, while the square wave is the output wave, but the output should be an out of phase amplified sin wave))

A: Your gain is too high, your output is clipping. At 60 Hz, the 1 uF (C1) will dominate and have an impedance of about 2.6k.
You either need to input a smaller signal, or lower the value of R2.
Edit: Or reduce C1 as Brian Drummond suggested.


text:
Q: Get attachment from mail using php I need code to monitor my mail inbox and forward the mails with an attachment to another email address. I used the code below to fetch the attachments from the received messages. But I'm getting an error "Notice: Undefined property: stdClass::$disposition in C:\wamp\www\mail\c.php on line 60"
Here is my code
<?php
 $host = '{imap.gmail.com:993/imap/ssl/novalidate-cert/norsh}inbox';
 $login = 'AAAA@CCC.com';
 $password = 'XXXXXXX';
 $savedirpath = "../mail";
 $type = 'ReadAttachment';
$obj = new $type;
$obj->getdata($host,$login,$password,$savedirpath,$delete_emails=false);
class ReadAttachment{

function getdecodevalue($message,$coding) {
    switch($coding) {
        case 0:
        case 1:
            $message = imap_8bit($message);
            break;
        case 2:
            $message = imap_binary($message);
            break;
        case 3:
        case 5:
            $message=imap_base64($message);
            break;
        case 4:
            $message = imap_qprint($message);
            break;
    }
    return $message;
}

function getdata($host,$login,$password,$savedirpath,$delete_emails=false) {
    // make sure save path has trailing slash (/)
    //print_r("test");
    $savedirpath = str_replace('\\', '/', $savedirpath);
    if (substr($savedirpath, strlen($savedirpath) - 1) != '/') {
        $savedirpath .= '/';
    }

    $mbox = imap_open ($host, $login, $password) or die("can't connect: " . imap_last_error());
    $message = array();
    $message["attachment"]["type"][0] = "text";
    $message["attachment"]["type"][1] = "multipart";
    $message["attachment"]["type"][2] = "message";
    $message["attachment"]["type"][3] = "application";
    $message["attachment"]["type"][4] = "audio";
    $message["attachment"]["type"][5] = "image";
    $message["attachment"]["type"][6] = "video";
    $message["attachment"]["type"][7] = "other";
    //print_r($message);
    $emails = imap_search($mbox,'ALL');
    foreach($emails as $email_number) {
        $structure = imap_fetchstructure($mbox, $email_number , FT_UID);
        $parts = $structure->parts;
        $fpos=2;
        for($i = 1; $i < count($parts); $i++) {
            $message["pid"][$i] = ($i);
            $part = $parts[$i];

            if($part->disposition == "ATTACHMENT") {
                $message["type"][$i] = $message["attachment"]["type"][$part->type] . "/" . strtolower($part->subtype);
                $message["subtype"][$i] = strtolower($part->subtype);
                $ext=$part->subtype;
                $params = $part->dparameters;
                $filename=$part->dparameters[0]->value;

                $mege="";
                $data="";
                $mege = imap_fetchbody($mbox,$email_number,$fpos);
                $filename="$filename";
                $fp=fopen($savedirpath.$filename,"w");
                $data=$this->getdecodevalue($mege,$part->type);
                //print_r($data);
                fputs($fp,$data);
                fclose($fp);
                $fpos+=1;
            }
        }

    }
    // imap_expunge deletes all tagged messages

    imap_close($mbox);
}
}

Thanks to the author, but I couldn't get any help further.
I'm getting an error "Notice: Undefined property: stdClass::$disposition in C:\wamp\www\mail\c.php on line 60"
This exactly point out the line if($part->disposition == "ATTACHMENT").
Please provide me with a solution.
I am new to php, struggling to write this mail function,,
Thanks in advance :-)

A: You need to check if $disposition exists first:
if((isset($part->disposition))&&($part->disposition == "ATTACHMENT"))


text:
Q: How to retrieve data from a local var i have this script in my html code
 <script typre="text/javascript">
        var img = new Array();
        img[0] = new Image();
        img[0].src = "../images/poggiatesta2.jpg";
        img[1] = new Image();
        img[1].src = "../images/poggiatesta1.JPG";
        for (var i = 0; i < img.length; i++) {
            var imagetag = document.createElement("img");
            var onclick = document.createAttribute("onclick");
            onclick.value = "myfun("+i+")";

            var sorc = document.createAttribute("src");
            sorc.value = img[i].src;

            var id = document.createAttribute("id");
            id.value = "my_image" + i;

            var clas = document.createAttribute("class");
            clas.value = "my_image_clas";

            imagetag.setAttributeNode(clas);
            imagetag.setAttributeNode(onclick);
            imagetag.setAttributeNode(sorc);
            imagetag.setAttributeNode(id);
            document.body.appendChild(imagetag);
        };
        function myfun(i) {
            var src1 = document.getElementById('my_image' + i).src;
            alert(src1);

        }
        </script>

It allows me to store the src of a selected image in a var. Now im trying to do a check, which means an alert message that pops out if i didnt select any images like this:
 function controllo() {

    if ((src1 == "") || (src1 == "undefined")) {
        alert("Select an image.");
    }
    else {
        location.href = "schienale.html";
    }
}

Here's the problem, src1 is a local var, how can i retrieve its data in order to complete my check funcion?

A: You could store src1 as a global (it is better to use a namespace, but for the sake of this question a global will do)
<script typre="text/javascript">
    var src1; //Notice i've declared the variable here.
    var img = new Array();
    img[0] = new Image();
    img[0].src = "../images/poggiatesta2.jpg";
    ...

Then in myFunc do:
function myfun(i) {
     src1 = document.getElementById('my_image' + i).src;
     alert(src1);
}

This will make src1 available everywhere.
Or, if possible, pass src1 into your controllo function.
This is the preferred method because it prevents cluttering the global namespace, but will require the code to be changed elsewhere.
This might help give you a hint though:
controllo(src1)

function controllo(src1) {

if ((src1 == "") || (src1 == "undefined")) {
        alert("Select an image.");
    }
    else {
        location.href = "schienale.html";
    }
}


text:
Q: Merge sorting a struct #include<stdio.h>
#include<stdlib.h>
typedef struct points{
        float axis[2];
        int id;
}Points;

typedef enum{
        SortById,
        SortByXAxis
}SortType;

Points* fill_Array(char* filename, int* length);
void Print_set(Points* set, int number_of_points);
void mergesort(Points* set, int low, int high, int number_of_points,SortType sort);
void merge(Points* set, int low, int middle, int high, int number_of_points,SortType sort);

int main(int argc, char* argv[])
{
    int length;
    Points *array;
    array=fill_Array(argv[1],&length);
    Print_set(array,length);
    printf("\n\n");
    mergesort(array,0,length,length,SortById);
    Print_set(array,length);
    return 0;
}
Points* fill_Array(char* filename,int* length)
{
    int i;
    Points* array;
    FILE* file=fopen(filename,"r");

    if(file == NULL)
    {
        return NULL;
    }

    fscanf(file,"%d",length);
    array=malloc(sizeof(Points)* *length);

    for(i = 0; i < *length; i++)
    {
        fscanf(file,"%d %f %f", &(array+i)->id,&(array+i)->axis[0],&(array+i)->axis[1]);
    }
    fclose(file);

    return array;
}

void Print_set(Points *set, int number_of_points)
{
    int i;

    for(i = 0; i < number_of_points; i++)
    {
        printf("%d %f %f\n",(set+i)->id,(set+i)->axis[0],(set+i)->axis[1]);
    }
}

void mergesort(Points* set,int low,int high,int number_of_points, SortType sort)
{
    int mid1;

    if((high-low)>=1)
    {
        mid1 = (low+high)/2;

        mergesort(set, low, mid1, number_of_points, sort);
        mergesort(set, mid1+1, high, number_of_points, sort);
        merge(set, low, mid1, high, number_of_points, sort);

    }

}
void merge(Points* set, int low, int middle, int high, int number_of_points, SortType sort)
{
        int leftIndex=low;
        int rightIndex=middle;
        int combinedIndex = low;
        Points tempArray[number_of_points];
        int i;

        while(leftIndex <= middle && rightIndex<= high)
        {
            if(set[leftIndex].id <= set[rightIndex].id)
            {
                tempArray[combinedIndex++] = set[leftIndex++];
            }
            else
                tempArray[combinedIndex++] = set[rightIndex++];
        }

        if(leftIndex == middle+1)
        {
            while(rightIndex <= high)
            {
                tempArray[combinedIndex++] = set[rightIndex++];
            }
        }
        else
        {
            while(leftIndex <= middle)
            {
                tempArray[combinedIndex++] = set[leftIndex++];
            }
        }

        for( i = low; i < high; i++)
        {
            set[i] = tempArray[i];
        }
}

I am trying to perform a merge sort on an input file using a custom merge sort function. The merge sort functions however are not working and print out down below, the first block being the actual input file printed out to make sure fscanf is reading in everything correctly and the second being the printing after the merge functions are run. The functions are duplicating some of the values and are not sorting them either and I cannot find the mistake in the code. Note that the enum will be used to sort either the ids or the first float values I am just trying to get the merge sort to work before I use it to sort either the ids or those values.
1 13.000000 7.000000
13 14.000000 6.000000
95 7.000000 13.000000
39 0.000000 20.000000
78 10.000000 10.000000
68 3.000000 17.000000
32 6.000000 14.000000
10 19.000000 1.000000
0 18.000000 2.000000
45 17.000000 3.000000
92 4.000000 16.000000
29 5.000000 15.000000
85 8.000000 12.000000
79 15.000000 5.000000
12 16.000000 4.000000
32 1.000000 19.000000
77 9.000000 11.000000
52 12.000000 8.000000
80 11.000000 9.000000
31 2.000000 18.000000

1 13.000000 7.000000
13 14.000000 6.000000
68 3.000000 17.000000
0 18.000000 2.000000
10 19.000000 1.000000
0 18.000000 2.000000
0 18.000000 2.000000
92 4.000000 16.000000
92 4.000000 16.000000
29 5.000000 15.000000
32 1.000000 19.000000
52 12.000000 8.000000
77 9.000000 11.000000
79 15.000000 5.000000
12 16.000000 4.000000
32 1.000000 19.000000
32 1.000000 19.000000
80 11.000000 9.000000
95 7.000000 13.000000
95 7.000000 13.000000

A: You appear to have gotten confused about the meaning of your boundary indices.  Consider the initial call to function mergesort():
    mergesort(array,0,length,length,SortById);

You pass the same value for arguments high and number_of_points, which is fine, but it implies that high represents an exclusive upper bound on the indices of the sort range.  The mergesort() implementation, however, seems geared for argument high to represent an inclusive bound.
The confusion continues with your merge() function, which is probably the main culprit here.  By taking the passed midpoint value as the start index of the right sub-array, it seems to be expecting the midpoint as an exclusive upper bound of the left sub-array, but the current mergesort() implementation passes an inclusive upper bound.  On the other hand, some of the index comparisons performed by merge() are appropriate only if middle is an inclusive upper bound of the subarray.
In short, you have a muddle.  The basic outline of the algorithm looks fine, but you need to decide (and document for yourself) what your function parameters represent, and reconcile your implementation details with that.  Were I you, I would adopt half-open representation for all intervals, so that lower bounds are always inclusive, and upper bounds always exclusive.  Among other things, that has the advantage that each midpoint value can be interpreted equally correctly as the (exclusive) upper bound of the left half of its subarray or as the (inclusive) lower bound of the right half.

A:     void mergesort(Points* set,int low,int high,int number_of_points, SortType sort)
    {
        int mid1;

        if((high-low)>1)
        {
            mid1 = (low+high)/2;

            mergesort(set, low, mid1, number_of_points, sort);
            mergesort(set, mid1, high, number_of_points, sort);
            merge(set, low, mid1, high, number_of_points, sort);

        }

    }
    void merge(Points* set, int low, int middle, int high, int number_of_points, SortType sort)
    {
            int leftIndex=low;
            int rightIndex=middle;
            int combinedIndex = low;
            Points tempArray[number_of_points];
            int i;

            while(leftIndex <= middle && rightIndex < high)
            {
                if(set[leftIndex].id <= set[rightIndex].id)
                {
                    tempArray[combinedIndex++] = set[leftIndex++];
                }
                else
                    tempArray[combinedIndex++] = set[rightIndex++];
            }

            if(leftIndex == middle+1)
            {
                while(rightIndex < high)
                {
                    tempArray[combinedIndex++] = set[rightIndex++];
                }
            }
            else
            {
                while(leftIndex < middle)
                {
                    tempArray[combinedIndex++] = set[leftIndex++];
                }
            }

            for( i = low; i < high; i++)
            {
                set[i] = tempArray[i];
            }
    }

0 18.000000 2.000000
1 13.000000 7.000000
10 19.000000 1.000000
0 18.000000 2.000000
12 16.000000 4.000000
13 14.000000 6.000000
29 5.000000 15.000000
31 2.000000 18.000000
32 6.000000 14.000000
32 1.000000 19.000000
39 0.000000 20.000000
39 0.000000 20.000000
52 12.000000 8.000000
31 2.000000 18.000000
68 3.000000 17.000000
77 9.000000 11.000000
78 10.000000 10.000000
12 16.000000 4.000000
79 15.000000 5.000000
85 8.000000 12.000000


text:
Q: How to limit foreach in the first object of a json file Hello I am trying to print a json file to a table. The json file is from this website https://jsonvat.com/. I want to print $data->rates->periods->rates[0]->standard. But I get

"Cannot use object of type stdClass as array in ..."

My code is this:
$data = json_decode($response);

echo '

Country	First	Last	Handle

';
foreach($data->rates as $rate){
    echo '
'.$rate->name.'	';
    foreach($rate->periods as $period){
    echo ''.$period->rates->standard.'	'.$period->rates->redused.'	'.$period->rates->super_reduced.'
';
    }
}
echo '

';

When I change $data = json_decode($response); to $data = json_decode($response, true); and the code becomes
foreach($data as $rate){
        echo '
'.$rate['name'].'	';

I get an error saying

Warning: Illegal string offset 'name' in
  C:\xampp\htdocs\wordpress\wp-content\plugins\test-plug\functions.php
  on line 23.

Thanks in advance.

A: You need to change your code as below:
$json = file_get_contents("https://jsonvat.com/");
$dataObject = json_decode($json, true);

echo '

Country	First	Last	Handle

';
foreach($dataObject['rates'] as $rate){
    echo '
'.$rate['name'].'	';
    foreach($rate['periods'] as $period){
    echo ''.$period['rates']['standard'].'	'.$period['rates']['reduced'].'	'.$period['rates']['super_reduced'].'
';
    }
}
echo '

';

Here, I found that sometime reduced or super_reduced key does not exist in Rate key. so you need to make your code changes accordingly. Hope it helps you.

A:  $tarray = json_decode($sjson);
$newarray = array('sample'=>array());
foreach($tarray->name as $ix => $name) {
    $newarray['catalog'][]=array(
        'name'  => $tarray->name[$ix],
        'image' => $tarray->image[$ix],
        'price' => $tarray->price[$ix],
    );
}
$sjson = json_encode($newarray);

or you can use .split()

A: You have a few problems with the various elements your trying to access (typos included).  Not all elements have a reduced (not 'redused') value, some do have a reduced1 (and reduced2) values or non at all, same with super_reduced.  In the code I've used a null coalesce (??) to set a default if no value is found.  You may want to tweak these to show something which you feel is best to show no value ...
    echo ''.$period->rates->standard.'	'.
            ($period->rates->reduced??$period->rates->reduced1??'Non').
            '	'.($period->rates->super_reduced??'Non').'
';

A: You can access the values with simple foreach() loop and set as you wish on your
 element
 $array = json_decode($json,1);
 foreach($array['rates'] as $k=>$v){
       echo $v['periods'][0]['rates']['standard'].PHP_EOL;
 }

DEMO: https://3v4l.org/O9EjB

A: You misunderstood the second parameter of json_decode: the doc tells:

When TRUE, returned objects will be converted into associative arrays.

So, when before you were supposed to access rates using $data->rates, you should now use $data['rates'] (same for $rate->periods which becomes $rate['periods']).
You could should thus look like (untested)
foreach($data['rates'] as $rate) {
   echo '
'.$rate['name'].'	';
}

A: When you decode as an object the nesting is $data->rates[0]->periods[0]->rates->standard where the first rates and periods are arrays.  Just loop them both:
foreach($data->rates as $rates) {
    foreach($rates->periods as $period) {
        echo $period->rates->standard . "
\n";
        echo $period->rates->reduced. "
\n";
        echo $period->rates->super_reduced . "
\n";
    }
}

If certain properties are not guaranteed to exist, then check with isset.

A: try this can help you, or you can use this on function
<?php
$count = 0;
$limit = 50;
foreach($data['rates'] as $rate) {

 //count times export data
 $count++;//first = 0
 if($count == $limit)
   break;//if limit == count stop

   //export data
   echo $rate['name'];
}
?>


text:
Q: here my listview is not scrolling dart flutter , please help me iam new to flutter return Scaffold(
   body: Container(
     width: MediaQuery.of(context).size.width,
     height: MediaQuery.of(context).size.height,
     child: Stack(
       children: [
         Positioned(
           width: MediaQuery.of(context).size.width,
           height: 25.0*SizeConfig.heightMultiplier,
           child:Container(
             decoration: BoxDecoration(
                 gradient: LinearGradient(
                     begin: Alignment.topCenter,
                     end: Alignment.bottomCenter,
                     colors: [Color(0xff009cba), Color(0xff000e11)])

             ),
             child: Row(
               mainAxisAlignment: MainAxisAlignment.spaceEvenly,
               crossAxisAlignment: CrossAxisAlignment.center,
               children: [
                 Expanded(flex:3,
                   child: Container(
                     child: Column(
                       mainAxisAlignment: MainAxisAlignment.center,
                       crossAxisAlignment: CrossAxisAlignment.end,
                       children: [
                         FittedBox(child: Text("Firm Details",style: GoogleFonts.lato(color: Color(0xfffbfbfb),fontSize: 1.6*SizeConfig.textMultiplier),/*TextStyle(color: Color(0xfffbfbfb),)*/)),
                         SizedBox(height: 0.5*SizeConfig.heightMultiplier,),
                         FittedBox(child: Text("Please select the category that best describes your business model.",style: GoogleFonts.lato(color: Color(0xffb3fbfbfb),fontSize: 1.3*SizeConfig.textMultiplier) /*TextStyle(color: Color(0xffb3fbfbfb),fontSize: 12.0)*/,)),
                       ],
                     ),
                   ),
                 ),
                 Expanded(flex:1,child:Container(
                   width: 10.0*SizeConfig.widthMultiplier,
                   height: 10.0*SizeConfig.heightMultiplier,
                   child:Image.asset("assets/images/firmDetail.png",width:1.0*SizeConfig.widthMultiplier,height: 1.0*SizeConfig.heightMultiplier,),
                 ), ),
               ],
             ),
           ), ),
         Positioned(
           top:20.0*SizeConfig.heightMultiplier,
           child:Container(
             width: MediaQuery.of(context).size.width,
             height: 500.0*SizeConfig.heightMultiplier,
             decoration: BoxDecoration(
               borderRadius: BorderRadius.circular(5.0*SizeConfig.widthMultiplier),
               color: Colors.white,
             ),
             child:new Container(
               child: ListView(
                 scrollDirection: Axis.vertical,
                 children: <Widget>[
                   SizedBox(height: 2.0*SizeConfig.heightMultiplier,),
                   Center(child: Padding(
                     padding:  EdgeInsets.all(1.8*SizeConfig.heightMultiplier),
                     child: Text("Please select the category that best describes your business model.",style: GoogleFonts.lato(fontWeight: FontWeight.bold),),
                   )),
                   horizontalList1,
                   verticalList,    // here vertical list
                 ],
               ),
             ),
           ),
         ),
       ],
     ),
   ),
 );

here in widget verticallist Listview is not scrolling,but when we add Sizedbox after form with fixedheight then it is scrolling but i dont need fixed height for scrollview
      Widget verticalList = new Container(
        margin: EdgeInsets.symmetric(vertical: 0*SizeConfig.heightMultiplier),
        height: MediaQuery.of(context).size.height,
        child:ListView(
          shrinkWrap: true,
          scrollDirection: Axis.vertical,
          children: [
            Form(
              key: _formKey,
              child:ListView(
                shrinkWrap: true,
                children: [
                  Padding(
                    padding:EdgeInsets.only(left:6.0*SizeConfig.widthMultiplier,right: 6.0*SizeConfig.widthMultiplier,top:1.8*SizeConfig.widthMultiplier,bottom: 1.8*SizeConfig.widthMultiplier),
                    child: new TextFormField(
                      validator: (String value) {
                        if (value.isEmpty) {
                          return 'PinCode';
                        } else {
                          return null;
                        }
                      },
                      keyboardType: TextInputType.phone,
                      controller: _pincode,
                      // selectionColor:Color(0xffe4065f),
                      style: GoogleFonts.lato(fontSize: 1.6*SizeConfig.textMultiplier,),
                      decoration: const InputDecoration(
                        labelText: "PinCode",
                        labelStyle: TextStyle(color: Color(0xffe4065f)),
                        focusColor: Color(0xffe4065f),
                        hintText:
                        "PinCode",
                        hintStyle: TextStyle(fontSize: 13.0),
                        focusedBorder: UnderlineInputBorder(
                            borderSide: BorderSide(
                                color: Color(0xffe4065f))),
                      ),
                      //  style: Theme.of(context).textTheme.body1,
                    ),
                  ),
                  Padding(
                    padding:EdgeInsets.only(left:6.0*SizeConfig.widthMultiplier,right: 6.0*SizeConfig.widthMultiplier,top:1.8*SizeConfig.widthMultiplier,bottom: 1.8*SizeConfig.widthMultiplier),
                    child: new TextFormField(
                      validator: (String value) {
                        if (value.isEmpty) {
                          return 'PAN of the unit. is required';
                        } else {
                          return null;
                        }
                      },
                      keyboardType: TextInputType.text,
                      controller: _pan,
                      // selectionColor:Color(0xffe4065f),
                      style: GoogleFonts.lato(fontSize: 1.6*SizeConfig.textMultiplier,),
                      decoration: const InputDecoration(
                        labelText: "PAN of the unit",
                        labelStyle: TextStyle(color: Color(0xffe4065f)),
                        focusColor: Color(0xffe4065f),
                        hintText:
                        "PAN of the unit",
                        hintStyle: TextStyle(fontSize: 13.0),
                        focusedBorder: UnderlineInputBorder(
                            borderSide: BorderSide(
                                color: Color(0xffe4065f))),
                      ),
                      //  style: Theme.of(context).textTheme.body1,
                    ),
                  ),
                  Padding(
                    padding:EdgeInsets.only(left:6.0*SizeConfig.widthMultiplier,right: 6.0*SizeConfig.widthMultiplier,top:1.8*SizeConfig.widthMultiplier,bottom: 1.8*SizeConfig.widthMultiplier),
                    child: FormField<String>(
                      builder: (FormFieldState<String> state) {
                        return InputDecorator(
                          decoration: InputDecoration(
                            labelText: "Constitution",
                            errorStyle: TextStyle(color: Colors.redAccent, fontSize: 1.6*SizeConfig.textMultiplier),
                            hintText: 'Please select expense',),
                          isEmpty: _constitutions == '',
                          child: DropdownButtonHideUnderline(
                            child: DropdownButton<String>(
                              value: _constitutions,
                              isDense: true,
                              onChanged: (String newValue) {
                                setState(() {
                                  _constitutions = newValue;
                                  state.didChange(newValue);
                                });
                              },
                              items: _constitution.map((String value) {
                                return DropdownMenuItem<String>(
                                  value: value,
                                  child: Text(value,style: GoogleFonts.lato(fontSize: 1.6*SizeConfig.textMultiplier,)),
                                );
                              }).toList(),
                            ),
                          ),
                        );
                      },
                    ),
                  ),
                  Padding(
                    padding:EdgeInsets.only(left:6.0*SizeConfig.widthMultiplier,right: 6.0*SizeConfig.widthMultiplier,top:1.8*SizeConfig.widthMultiplier,bottom: 1.8*SizeConfig.widthMultiplier),
                    child: new TextFormField(
                      validator: (String value) {
                        if (value.isEmpty) {
                          return 'Line of Activity is required';
                        } else {
                          return null;
                        }
                      },
                      keyboardType: TextInputType.text,
                      controller: _lineActicity,
                      // selectionColor:Color(0xffe4065f),
                      style: GoogleFonts.lato(fontSize: 1.6*SizeConfig.textMultiplier,),
                      decoration: const InputDecoration(
                        labelText: "Line of Activity",
                        labelStyle: TextStyle(color: Color(0xffe4065f)),
                        focusColor: Color(0xffe4065f),
                        hintText:
                        "Line of Activity",
                        hintStyle: TextStyle(fontSize: 13.0),
                        focusedBorder: UnderlineInputBorder(
                            borderSide: BorderSide(
                                color: Color(0xffe4065f))),
                      ),
                      //  style: Theme.of(context).textTheme.body1,
                    ),
                  ),
                  Padding(
                    padding:EdgeInsets.only(
                      left: 1.0*SizeConfig.widthMultiplier,
                      right: 1.0*SizeConfig.widthMultiplier,
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        FlatButton(
                          onPressed: () {
//x                        _postData();
                            if (!_formKey.currentState.validate()) {
                              //_formKey.currentState.save();
                              if (_constitutions == null || _districtSelectedValue == null) {
                                print("eroore");
                                Flushbar(
                                  message:  "please select required fields",
                                  duration:  Duration(seconds: 3),
                                )..show(context);
                              }  else {
                                // Every of the data in the form are valid at this point
                                _formKey.currentState.save();
                                print(_constitutions);
                              }
                            } else {
                              // submitOtp();
                              _postData();
                            }
                          },
                          child: Text(
                            "SAVE & NEXT",
                            style: GoogleFonts.lato(color: Colors.white),
                          ),
                          color: Color(0xffe4065f),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8.0),
                            side: BorderSide(color: Color(0xffe4065f)),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
         //   SizedBox(height: 1000,),
          ],
        )
    );

here ,when we add Sizedbox after form with fixedheight then it is scrolling but i dont need fixed height for scrollview im new to flutter please help

A: You can wrap your main widget with the SingleChildScrollView widget

A: I would suggest a simple widget hierarchy like
Scaffold
 - Container (For the red background)
  - Column
   - Container (with size for the lorem ipsom text.
    - Lorem Ipso Text.
   - Expanded (So that it will use the rest of the height automatically.)
    - Container (with white back ground and top rounded borders. Makes sure you add circular borders only to top and not to bottom of this container.
     - DefaultTabController
      - builder (to get different context of the default tab controller if more than one is used in your full app.)
       - Column
        - TabBar (if the number of categories is large use scrolling here as a property of the tab bar.) wrap in container if you need specific height of the tab bar.
        - Expanded
         - TabBarView to show the appropriate form.
          - SingleChildScrollView
           -Column
            -Your fields

A: your list view is wrapper in a container that is very long and has no scroll on it. So it wont scroll as the list fits within that long container.
With list views you want a fixed height. It is the fixed height that is given for the visible parts of the list. Remove the wrapping container or reduce the height so all of it is visible on screen.
Also look at your use of the stack. You might have issues once you fix this with the list scrolling on top of the text "Firm Details" etc.


text:
Q: What vavr collection to use to wrap a java.util.ArrayList I have a java.util.ArrayList returned by a library. As soon as I receive the object I would like to convert it to a vavr collection.
What should I use to minimize the computations for this? I don't have a clear scenario of usage after that.

*

*The first thing that comes to mind is to use io.vavr.collection.Iterator.ofAll(x) but this will be optimum only if I will iterate.

*Using a io.vavr.collection.Vector or io.vavr.collection.Array will instantiate vavr collections.

What should I use? These might be called views (not wrappers). There are any guidelines on how to properly interoperate between java and vavr collections with minimal friction/computation - eventually only when is needed?

Update
The question looks similar to Lazy view of java.util.Collection in Vavr

A: I would just create a vavr Array or Vector from it and forget about the cost of copying.
Are you working with huge collections or doing this in a tight loop? If not, I wouldn't worry too much about the cost of copying. If yes, you'll have to think about something to avoid the conversion, but that would depend on the actual use case. There's no solution that fits all use-cases.
You could also create a new type that wraps the ArrayList that lazily creates either a vavr Iterator, an Array or a Vector and you choose which conversion method to invoke on a use case basis, but the usefulness of such a type is limited in my opinion.


text:
Q: Sequence of unit disk automorphisms converge l.u. to an automorphism Given $\{f_n\}$ sequence of automorphisms on the (open) unit disk converging locally uniformly to some nonconstant function $f$. Show that $f$ is an automorphism of the open unit disk.
For injectivity we may use Hurwitz theorem (and identity theorem). For surjectivity I wanted to use maximum modulus principle on $\frac{1}{f(z)-w}$ for some $w \notin f(D)$, but $f$ is not defined on the unit circle...?

A: Fix $w^* \in \Bbb D$. The $(f_n)$ are automorphisms of the unit disk, therefore there exists a sequence $(z_n)$ in $\Bbb D$ with $f_n(z_n) = w^*$ for all $n$.
Case 1: $z_{n_k} \to z^* \in \Bbb D$ for some subsequence $(z_{n_k})$ of $(z_n)$. Then $f_{n_k}(z_{n_k}) \to f(z^*)$ which implies $f(z^*) = w^*$.
Case 2: $|z_n| \to 1$. Applying the Schwarz–Pick theorem to the inverse functions $f_n^{-1}$ gives
$$
\left|\frac{z-z_n}{1-\overline{z_n} z} \right| \le \left|\frac{f_n(z)-w^*}{1-\overline{w^*} f_n(z)} \right| \, ,
$$
which can equivalently be written as
$$
 \frac{(1-|f_n(z)|^2)(1-|w^*|^2)}{|1-\overline{w^*} f_n(z)|^2}
\le \frac{(1-|z|^2)(1-|z_n|^2)}{|1-\overline{z_n} z|^2} \, .
$$
(Actually equality holds for automorphisms, but that is not needed here). For fixed $z$ and $n \to \infty$ the right-hand side converges to zero, and it follows that $|f(z)| = 1$ for all $z \in \Bbb D$. That is not possible for a non-constant holomorphic function.
So only the first case can occur, which proves that $f: \Bbb D \to \Bbb D$ is surjective.
Remark: The condition that the limit function $f$ is not constant is important, as the example
$$
 f_n(z) = \frac{z-(1- \frac 1n)}{1-(1-\frac 1n)z}
$$
demonstrates. The $f_n$ are automorphisms of the unit disk with $f_n \to -1$ locally uniformly.


text:
Q: How to launch Firefox browser in Kubuntu? I'm having the same problem with 12.04.01 as Eeesy in a previous post.
I use the link in Kubuntu to invoke the installer to 'Install Mozilla Firefox Browser.'
 (By 'invoking the installer' I mean K menu-->Applications-->Internet-->'Mozilla Firefox Browser Installer') I go through the installation dialogue boxes, and it indicates Package successfully installed. After this, I do not seem to be able to locate the link to Firefox. (I have tried: which firefox and which Firefox, neither of which result in a path.)
I have also tried: sudo apt-get install firefox
[sudo] password for chphunk:
Reading package lists...
Done Building
dependency tree
Reading state information...
Done Package firefox is
not available, but is referred to by another package. This may mean
that the package is missing, has been obsoleted, or is only available
from another source

E: Package 'firefox' has no installation candidate

When I browse the Muon Software Center, it shows Firefox Web Browser as installed. When i select 'More Info', it indicates 'Find in the menu: K --> Applications -->Internet -->Mozilla Firefox Browser Installer.
I just want to run Firefox. Can you offer any guidance here? Thanks in advance.

A: Here are three ways to install firefox on Kubuntu 12.04. Make sure you enabled all the repositories and do an sudo apt-get update in the konsole program.

*

*Install from the konsole with sudo apt-get install firefox.

*Alternatively you can install the Firefox by clicking on the
Firefox installer icon in the start menu (or Kickoff menu). Search for it by typing "Firefox" in the start menu.

*Another alternative, (which the OP followed to solve his issue) is
using Muon software center. Open it, Go to Get software →
Internet → Web Browsers and select FireFox Web browser and click on the Install button next to it's label.


text:
Q: Setting Backbone Route to Accept N Parameters I'd like to be able to accepts URL paths using the backbone.js routing system, to interpret before navigating. Ideally, I will be able to set up a single route, or a series of a few routes that can be used in understanding all possibilities.
For example, these are possible URLs
mysite.com/books/war_and_peace.12.b
mysite.com/books/philosophy/war_and_peace.12.b
mysite.com/russian/books/philosophy/war_and_peace.12.b
mysite.com/philosophy/the_brothers_karamozov.68.b
mysite.com/crime_and_punishment.44.b

Ideally, I want to write a 'route' that accepts n parameters, and can then use logic to sort out the query and how to navigate.
This is what I have so far, yet isn't cutting it:
this.route(':p1/:p2/:p3/:p4/:p5/:p6/:p7', 'home', function(p1, p2, p3, p4, p5, p6, p7) {
    // do stuff
});

A: Use a wildcard.
this.route('*path', 'home', function(path) {
    path = path.split('/');
    // do stuff
});


text:
Q: How to deny access of a user group on particular views of a joomla component in admin panel. Not for whole component I'm working with joomla 3.
Consider a joomla component with 6 views.
And two user groups named user-group1, user-group2.
My requirement is like this:
user-group1 should be able to access the first three views of the component.( access on last three views should be denied for user-group1).
user-group2 should be able to access the last three views of the component.( access on first three views should be denied for user-group2).


text:
Q: View procedure in multiple line in Oracle SQL Developer? I'm using Oracle SQL Developer Version 4.1.2.20.
I expand the procedures folder, find the procedure I need to edit, and I right-click->Edit.
The procedure appears as one entire line, even though the procedure is multiple lines long.
Is there a view option to see the procedure with block structure with multiple lines?


text:
Q: How to create a DB Model for Anonymous users? I have created a web app using Flask where you can leave a note as text. Ig goes well you leave a text and it got saved in our database. But it only happens when you are an authorized user and can't be done if you are an unauthorized (anonymous user) and if you attempt as such this error message pops up: "'AnonymousUserMixin' object has no attribute 'id'".
Here the code goes:
#home.py

def home():
    if request.method == 'POST':
        note = request.form.get('note')
    if len(note) < 1:
        flash('Note is too short!', category='error')
    else:
        new_note = Note(data=note, user_id=current_user.id)
        db.session.add(new_note)
        db.session.commit()
        flash('Note added!', category='success')

return render_template("home.html", user=current_user)

And the DB models:
#models.py
class Note(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    data = db.Column(db.String(10000))
    date = db.Column(db.DateTime(timezone=True), default=func.now())
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(150), unique=True)
    password = db.Column(db.String(150))
    first_name = db.Column(db.String(150))
    confirmed = db.Column(db.Boolean, nullable=False, default=False)
    notes = db.relationship('Note')

A: You are setting a user_id value when creating a Note:
new_note = Note(data=note, user_id=current_user.id)

Evidently anonymous users  don't have an id attribute, so you must either set user_id=None when creating notes for anonymous users or create a default user to represent anonymous users and user that user's id when creating notes.


text:
Q: SR5: Chance of rolling 2 dice with a result of 5 or 6 and 4 dice with a result of one out of eight dice total This question is regarding calculating probability for the SR5 role-playing game.
The setup: a number of d6, $n$, are rolled. Any dice that come up as a 5 or a 6 are considered 'hits', and they add to a running tally. More hits is better. If half or more of the $n$ dice come up as ones, this generates a glitch, which is generally undesirable. If there are no hits, and the glitch condition is met, this is considered a critical glitch, and this is Really Bad News.
I am trying to calculate probabilities for different scenarios using the above rules.
I already know how to calculate the probability of getting any number of hits for any number of dice. For example, to calculate the chance of getting exactly two hits out of six dice rolled, where $n$ is the number of dice total rolled (6), $r$ is the number of results I am interested in (2), and $p$ is the chance of getting a 'hit' ($1/3$), a binomial trial will give me the answer:
$$\frac{n!}{(n-r)!r!} p^r (1-p)^{n-r}$$
Which results in $80/243$. To calculate the chance of getting two or more hits, I use the same equation, starting with the probability of two hits, then three hits, and so on, up to the number of dice rolled. At this point, summing the results gives me the chance for rolling two or more hits. So far, so good. Using similar methods, I can calculate the odds of rolling half or more $1$'s.
The problem I have is I am unsure how to go about calculating a scenario where I get a number of hits -and- half or more of the dice come up ones. I can enumerate and tally, and have done so for up to three dice, but this becomes hard to do by hand past that. And by the rules of the game, it's possible to roll upwards of 18 dice, at which point enumeration becomes quite a lot for even the computer to handle.
If anyone could give me guidance on how to answer the question posed in the title, I can probably take it from there to handle all scenarios I am interested in. As an end result, I'm hoping to be able to determine probability of rolling $r$ hits with a glitch, and chance of getting a critical glitch.
As an example output, through enumeration, for two dice, there's a $7/36$ chance of a critical glitch, a $4/9$ chance of one hit ($1/9$ chance of one hit and a glitch, $3/9$ chance of a clean hit with no glitch), $1/9$ chance of two hits ($0$ chance of two hits and a glitch), and a $1/4$ chance of a null result (neither hits nor glitches).

A: Okay, I figured it out.
Allow $t$ to be the total number of dice rolled, $H$ to be the probability of getting a 'hit' (a 5 or a 6, so $1/3$), $X$ to be the probability of rolling a 1 ($1/6$), and $N$ the probability of getting a result we aren't interested in (a 2,3, or 4, so $1/2$). Also allow $h$ to be the number of hits we are interested in, $x$ the number of 1's we are interested in, and $n$ to be $t-(x+h)$
With the above, I can calculate the probability of a specific arranged result. For the question as asked, it will look like $HHXXXXNN$, or $H^2X^4N^2$. The next step is to figure out how many states this arrangement can be formed into. This can be done with $\frac{n!}{h!x!n!}$. This leads us to a final answer of the probability of that arrangement multiplied by all the possible combinations of that arrangement, for a final answer of $$\frac{t!}{h!x!n!}H^2X^4N^2=\frac{35}{3888}\approx0.009$$
This can be used to get most of your standard results in Shadowrun 4th edition  or 5th edition. For example, to calculate the chance of getting two hits and a glitch with eight dice, we can use the above result and sum it with the results for the arrangments $HHXXXXXN$ and $HHXXXXXX$, covering all the ways in which a glitch can result while still getting two hits.


text:
Q: Update record in table if it exists (with clause) or creates it if not I am attempting to write a query that will update the record if it exists, or create it if it does not, however I want to do that based on the condition that text_value is not already set.
I initally thought of using REPLACE, but that does not support a WHERE clause.
REPLACE INTO settings
    SET var_name = '',
        var_group = '',
        text_value = '',
        country_id = ''

Can I do what I want to do in one query? I am trying to do so without having to write something like this where I have two queries in my PHP:
SELECT FROM settings WHERE text_value != '' AND country_id = $country_id
IF that returns no results then
INSERT INTO settings...
This is my table DDL information:
CREATE TABLE `settings` (
  `settings_id` int(11) NOT NULL auto_increment,
  `var_name` varchar(50) default NULL,
  `var_group` varchar(26) NOT NULL,
  `text_value` text NOT NULL,
  `country_id` int(11) NOT NULL,
  PRIMARY KEY  (`settings_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8