text:
Q: How to picture the Quantum Harmonic Oscillator with particle creation interpretation? For the simple quantum harmonic oscillator we can solve Schrodinger's equation and derive the analytic form of the eigenstates of e.g. a non relativistic electron in a harmonic potential. We may then go on to define ladder operators which enable us to move between eigenstates of the potential. One interpretation of these ladder operators is that they 'create' or 'destroy' a photon of energy hw. One can go on to define the Number operator which enables us to determine how many times the oscillator has been excited or equivalently how many 'photons' there are in the system.
My question is: is it correct to say the wavefunction we derived for the different energy levels still just describes the single non-relativistic electron and doesn't describe the newly created/destroyed photons.
If this is correct then where does the interpretation of 'creation' of particles even come from because it seems like we are not describing the produced photons with any wavefunction we are merely postulating that they have been created? What is a good intuitive explanation for the interpretation in terms of photon creation?

A: In my opinion, the answer to your question is no. So we can write our problem as $\hat{H}\psi = E\psi$, and we can derive (check David Griffiths, "Introduction to Quantum Mechanics" for example) that $\psi^{n}\left( x\right) = A_n \left( a^{\dagger}\right)^n \psi_{0}\left( x\right)$, where $A_n$ is a normalization constant, and $\psi_{0}\left(x \right)$ is the ground-level wave function.
So the creation operator $a^{\dagger}$ does enter in the wavefunctions. :)

A: To me, the boson interpretation comes only clear when one considers a many particle situation.
When we deal with one single harmonic oscillator, one has one creation $a^{\dagger}$ and one annihilation operator $a$. Each time you act with $a^{\dagger}$ you are essential raising the total energy of the oscillator by one quanta of energy. One way to see this is that $H= \epsilon (n+ \frac{1}{2})$, i.e. your total energy only depends on how many times you acted with $a^{\dagger}$ as $H$ essentially counts how many times this happens and multiplies it by some energy gap $\epsilon$. The interpretation is that you have one single particle which can be excited upwards or downwards with the ladder ops. Note I didn't mention bosons yet as it wouldn't make sense as explained below.
Now consider a chain of independent harmonic oscillators. We are dealing with the same story as before as the oscillators are completely unaware of each other. Now we label each oscillator with an index $i$ to keep track of it. We also label their associated creation $a^{\dagger}_i$ and annihilation operators $a_i$. If you play a bit with the algebra, you can show that they satisfy the canonical commutation relationships,
$$
[a_i, a^{\dagger}_j] =\delta_{ij} \quad [a_i,a_j]=[a_i^{\dagger},a_j^{\dagger}]=0
$$
which is a defining property for bosonic particles (whether or not they are fundamental is a different story, they can, and are, quasiparticles).
The interpretation now is clear, at each site you can create/destroy a boson with its corresponding creation and annihilation operators. The energy of the system is simply the sum of the energies at each site, or the number of excitations/bosons we have at each site,
$$
H= \sum_i \epsilon (n_i+ \frac{1}{2}).
$$

To finish off, yes, the wave function that solves the Schrödinger equation for a particle in a harmonic potential will always be a valid wave function for such situation. Now, you can alternatively interpret it as bosonic quasiparticles exactly as explained above.


text:
Q: how do i get rid of space on the left side of the slideshow I have got this space on the left side of my slideshow i have tried getting rid of it by using padding:0px and margin:0px but it kind of makes more mess
can anyone help me please here is the link to the site
http://goo.gl/aS3y1

A:

i have added right:0px to the li

A: Try this in #slides
#slides {
    float: left;
    margin: 0;
    padding: 0;
    width: 950px;
}

A: Try this
#slideshow {
        height: 240px;

        margin-left: -40px;
        position: relative;
        width: 950px;
    }

A: Insert the style in the #main2 and this will solve you more issues :) because you have float in previous DIV and your slider is above the menu and you will be unable to click the items.
#main2 {
 ....
 clear:both;
}

and in
#slides {
   float: left;
   padding: 0;
}

A: Quickfix
ul#slides {
    margin-left:-37px;
}

A: .column-inmiddle {
    width: 138%; remove this or make 100%
}

#slideshow {
    position: relative;
    width: 950px;
    height: 240px;
    margin: 40px auto 0 auto; add this
}

hopefully you'll get what u want

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to find out what consumes the KeyPressed event in a Swing application? So when maintaining a large Java Swing application I have an issue: the arrow keys in the filename textfield of a sub-class derived from JFileChooser don't work.
If I just put this class into a tiny stand-alone Swing app with just a JFrame, the arrow keys (specifically left and right) will move around the cursor in the filename field just fine, but it won't work in the original application.  I have checked all KeyListeners of all its containers, but couldn't find anything that captures the event.  So the question is: is there any way to stop the IDE in debug mode (or any method to debug the issue without an IDE) upon a certain or all KeyPress event(s)?

A: The way I would do this is put a breakpoint inside java\awt\Component.java. You should be able to find it in your JDK. This is the method which dispatches all events to the listeners you've registered:
protected void processKeyEvent(KeyEvent e) {
    KeyListener listener = keyListener;
    if (listener != null) {
        int id = e.getID();
        switch(id) {
          case KeyEvent.KEY_TYPED:
              listener.keyTyped(e);
              break;
          case KeyEvent.KEY_PRESSED:
              listener.keyPressed(e);
              break;
          case KeyEvent.KEY_RELEASED:
              listener.keyReleased(e);
              break;
        }
    }
}

The KeyListener variable in this case is a little bit un-intuitive if you have more than one listener. You might expect it to iterate over a list of listeners in the order they were added. If fact, it uses a composite object called an AWTEventMulticaster which is basically just a pair of listeners.
If you have two listeners the structure is simple:
AWTEventMulticaster
{
   first_listener_you_added;
   second_listener_you_added;
}

If you have three listeners, the structure uses nested Multicasters:
AWTEventMulticaster
{
   first_listener_you_added;
   AWTEventMulticaster
   {
       second_listener_you_added;
       third_listener_you_added;
   }
}

and so on...
By carefully tracing your application through from this point you should be able to find the point where the event is consumed.


text:
Q: Android theming: Set Status Bar color to Action Bar color in Material3 I am migrating my app's Material Design theme from V2 (1.4.0) to V3 (1.5.0).
Unlike Theme.MaterialComponents.DayNight, which had a DarkActionBar sub style that used the Primary color for the Action Bar, Theme.Material3.DayNight doesn't have DarkActionBar sub style.
I can't figure out what color is used for the Action Bar in the default settings.
This is how my current app theme shows up:

As can be seen, my Primary color is Blue, but the Action Bar has automatically been colored using a shade/alpha of the primary. The hexadecimal color notation of the Action Bar was not defined by me. I tried setting the Status Bar to all the various shades of blue that I defined in my colors.xml file, but none of them are a perfect match.
Can someone explain how is the Action Bar color determined or how I may be able to set the Status Bar to the same color as the Action Bar?
colors.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="black">#000000</color>
    <color name="white">#ffffff</color>

    <color name="black_alpha_020">#33000000</color>
    <color name="white_alpha_060">#99ffffff</color>

    <color name="blue_50">#e3f2fd</color>
    <color name="blue_50_bit_black">#E4F0F5</color>
    <color name="blue_100">#bbdefb</color>
    <color name="blue_300">#64b5f6</color>
    <color name="blue_500">#2196f3</color>
    <color name="blue_700">#1976d2</color>
    <color name="blue_a100">#82b1ff</color>

    <color name="blue_black_3_3">#072451</color>
    <color name="blue_black_3_3_bit_black">#031228</color>
    <color name="blue_white_5_6">#fafdff</color>
    <color name="blue_black_5_6">#061929</color>
    <color name="blue_black_10_2">#CEDCE6</color>
    <color name="blue500_black_5_6">#26282A</color>

    <color name="blue_50_alpha_060">#99e3f2fd</color>

    <color name="blue_grey_700">#455a64</color>
    <color name="blue_grey_800">#37474f</color>

    <color name="amber_100">#ffecb3</color>
    <color name="amber_700">#ffa000</color>
    <color name="amber_black_3_4">#401C00</color>

    <color name="red_50">#ffebee</color>
    <color name="red_black_2_3">#3D0909</color>
    <color name="red_900">#b71c1c</color>

    <color name="grey_600">#757575</color>

</resources>

themes.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools">
    <style name="Theme.SimpleTheme" parent="Theme.Material3.DayNight">
        <!--Color-->
        <item name="colorPrimary">@color/blue_500</item>
        <item name="colorOnPrimary">@color/white</item>
        <item name="colorPrimaryContainer">@color/blue_50</item>
        <item name="colorOnPrimaryContainer">@color/blue_black_3_3</item>

        <item name="colorSecondary">@color/blue_grey_800</item>
        <item name="colorOnSecondary">@color/white</item>
        <item name="colorSecondaryContainer">@color/blue_50_bit_black</item>
        <item name="colorOnSecondaryContainer">@color/blue_black_3_3_bit_black</item>

        <item name="colorTertiary">@color/amber_700</item>
        <item name="colorOnTertiary">@color/white</item>
        <item name="colorTertiaryContainer">@color/amber_100</item>
        <item name="colorOnTertiaryContainer">@color/amber_black_3_4</item>

        <item name="colorError">@color/red_900</item>
        <item name="colorOnError">@color/white</item>
        <item name="colorErrorContainer">@color/red_50</item>
        <item name="colorOnErrorContainer">@color/red_black_2_3</item>

        <item name="android:colorBackground">@color/blue_white_5_6</item>
        <item name="colorOnBackground">@color/blue_black_5_6</item>
        <item name="colorSurface">@color/blue_white_5_6</item>
        <item name="colorOnSurface">@color/blue_black_5_6</item>

        <item name="colorSurfaceVariant">@color/blue_black_10_2</item>
        <item name="colorOnSurfaceVariant">@color/blue500_black_5_6</item>
        <item name="colorOutline">@color/grey_600</item>

        <item name="colorSurfaceInverse">@color/blue_black_5_6</item>
        <item name="colorOnSurfaceInverse">@color/blue_white_5_6</item>
        <item name="colorPrimaryInverse">@color/blue_a100</item>

        <item name="android:navigationBarColor" tools:targetApi="o_mr1">?attr/colorSurface</item>
        <item name="android:windowLightNavigationBar" tools:targetApi="o_mr1">true</item>
    </style>

    <style name="Theme.SimpleTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>
</resources>

A: Make your status bar transparent:
themes.xml
<item name="android:statusBarColor">@android:color/transparent</item>
<item name="android:windowLightStatusBar">true</item>

themes.xml (night)
<item name="android:statusBarColor">@android:color/transparent</item>
<item name="android:windowLightStatusBar">false</item>

Edit your activity_main.xml file like below sample code:
<androidx.coordinatorlayout.widget.CoordinatorLayout
    ...
    android:fitsSystemWindows="true">

    <com.google.android.material.appbar.AppBarLayout
        ...
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true"
        ...>

        <com.google.android.material.MaterialToolbar
        ...
        />

    </com.google.android.material.appbar.AppBarLayout>
    ...
</androidx.coordinatorlayout.widget.CoordinatorLayout>

For more information, check this doc: https://m3.material.io/components/top-app-bar/implementation/android#collapsing-top-app-bars

A: Using SurfaceColors class
The color of the Action Bar is colorSurface with elevation.
If you want to change the color of the Status Bar. Using SurfaceColors class. This function also works with Dynamic Coloring in Material 3 and day/night mode.
Code in Kotlin
val color = SurfaceColors.SURFACE_2.getColor(this)
window.statusBarColor = color // Set color of system statusBar same as ActionBar
window.navigationBarColor = color // Set color of system navigationBar same as BottomNavigationView

Result

Thanks

A: theme.xml(no-night):
<style name="Theme.AllCodeApp" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
     <item name="android:statusBarColor" tools:targetApi="l">@color/white</item>
         <item name="actionBarStyle">
            @style/MyActionBarDarkStyle
        </item>
</style>
<style name="MyActionBarDarkStyle" parent="Widget.MaterialComponents.ActionBar.Primary">
        <item name="backgroundColor">@color/white</item>
 </style>

theme.xml(night):
<style name="Theme.AllCodeApp" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
    <item name="android:statusBarColor" tools:targetApi="l">@color/teal_200</item>
        <item name="actionBarStyle">
            @style/MyActionBarDarkStyle
        </item>
</style>
<style name="MyActionBarDarkStyle" parent="Widget.MaterialComponents.ActionBar.Primary">
        <item name="backgroundColor">@color/teal_200</item>
</style>

A: The parent theme what you are using has an attribute colorSurface and this attribute is responsible for the background color of the action bar. But in material3 , primary colored elevation are applied to surface color to create a mixed color . Refer this link below and read the section Using Surface Colors carefully , you'll get your answer. Here is the link.
As that color is generated dynamically, you can set the the status bar color for your app dynamically using SurfaceColors Api .
In java getWindow().setStatusBarColor(SurfaceColors.SURFACE_5.getColor(this));
I have used enum SURFACE_5 above for example purpose , you can use different enums from SURFACE_0 to SURFACE-5 , to get the desired color.


text:
Q: php login file is redirecting me to the users folder in xampp but not in the cpanel My login script when am using xampp as server is redirecting me to the users folder after successful login , but when i upload to the cpanel it just reloads and not redirect. But when i type the folder of the users after the domain name it shows the users is already logged in. Like www.goo.com/users it will take to the users index file as successful login. What can i do for proper redirecting.
<?php
    require_once('../includes/config.php');
    $_SESSION['timestamp']=time();
?>

Login Procedures

- Login Details will be sent to your email aproximately 20 minutes after payment.

            - Login using the payment confirmation code and mobile phone number without the country code after payment.

            <?php
    if(isset($_POST['submit'])) {
        $username = $_POST['username'];
        $password = $_POST['password'];

        $result = $dbh->prepare("SELECT * FROM tb_users WHERE username= :username AND password= :password");
        $result->bindParam(':username', $username);
        $result->bindParam(':password', $password);
        $result->execute();
        $rows = $result->fetch(PDO::FETCH_NUM);
        if($rows > 0) {

            $result=$dbh->prepare("SELECT * FROM tb_users WHERE username=:username");
            $result->bindParam(':username', $username);
            $result->execute();
            while($row = $result->fetch(PDO::FETCH_ASSOC)){
                $res_id = $row['username'];
                $curr_status = $row['user_status'];
            }

                if($curr_status=='deactive') {
                    $message = "Sorry $username, You've Exhausted Your Subscription.
Make a new Subscription to login or write to admin for Bonus Days.
";
                }else{
                    $_SESSION['username'] = $res_id;
                    header("location:users/index.php");
                }

        }
        else{
            $message = 'Wrong Credentials!';
        }
    }
?>

                    <form class="form-signin" id="login-form" method="post">

                                <input type="text" name="username" class="form-control" placeholder="Email / Phone" required>

                                <input class="form-control" name="password" type="password" placeholder="Password" id="myInput">

                <?php
                    if(!empty($message)) {
                        echo "
".$message."
";
                    }
                ?>

                            <input type="submit" name="submit" value="Access" class="btn btn-success"/>

                    </form>

A: Headers must be set before any output is sent. You are sending a lot of HTML to the user before doing that header() call. Perhaps its working in one environment but not in another because output_buffering is set on your localhost php.ini but not on the server.
You should rework your code to make sure header() is sent before any stuff, but if you want to just get it working append ob_start() to the beginning of your code, it will enforce the buffering.
See also


text:
Q: How can I pass all arguments with xargs in middle of command in linux I want to pass all the files as a single argument on Linux but I am not able to do that.
This is working
ls | sort -n | xargs  -i pdftk  {} cat output combinewd2.pdf

This passes a single argument per command, but I want all in one command.

A: This should work on filenames containing spaces, newlines, apostrophes and quotation marks (all of which are possible on UNIX filesystems):
find . -maxdepth 1 -type f -print0 |
  sort -zn |
  xargs -0 sh -c 'pdftk "$@" cat output combinewd2.pdf' "$0"

That might be overkill compared to the accepted answer, if you know you are working with simple filenames.
But if you are writing a script that will be used again in future, it is desirable that it won't explode one day when it meets unusual (but valid) inputs.
This is basically an adaptation of andrewdotn's answer which terminates input files with a zero-byte, instead of with a newline, hence preserving filenames which contain one or more newline characters.
The respective options -print0, -z and -0 tell each of the programs that input/output should be delimited by the zero-byte.  Three different programs, three different arguments!

A: The most intuitive way I found was to:

*

*first construct the commands with -I{} and "echo",

*then execute the commands with "bash" (as if you are executing a shell script)

Here is an example to rename extensions from ".txt" to ".txt.json":
find .|grep txt$|xargs -I{} echo "mv {} {}.json"|bash

Slightly advanced example to rename .txt to .json (removing .txt extension)
find $PWD|grep txt$|cut -d"." -f1|xargs -I{} echo "mv {}.txt {}.json"|bash

I once had a requirement to append the string "End of File" to all files.
find .|grep txt|xargs -I{} echo "echo End of File >> {}"|bash

If you do it right, xargs is the king of all commands!

A: Use -I option:
echo prefix | xargs -I % echo % post

Output:
prefix post

A: Here's what I did for the same problem, and am actually using in production:
cat chapter_order-pdf-sample.txt | xargs -J % pdftk % cat output sample.pdf

A: You can do this by chaining two calls to xargs. Use the first to chain all of the args together into one string and pass that as a param to echo, and the second using -I to place that chain of args into the place where you want it, as follows:
ls | sort -n | xargs echo | xargs -I {} pdftk {} cat output combinewd2.pdf

A: This is one way to do it
pdftk $(ls | sort -n) cat output combinewd2.pdf

or using backtick
pdftk `ls | sort -n` cat output combinewd2.pdf

For example, if the filenames are 100, 2, 9, 3.14, 10, 1 the command will be
pdftk 1 2 3.14 9 10 100 cat output combinewd2.pdf

To handle filenames with spaces or other special characters consider this fixed version of @joeytwiddle's excellent answer (which does not sort numerically, see discussion below):
#-- The following will handle special characters, and
#   will sort filenames numerically
#   e.g. filenames 100, 2, 9, 3.14, 10, 1 results in
#      ./1 ./2 ./3.14 ./9 ./10 ./100
#
find . -maxdepth 1 -type f -print0 |
  sort -k1.3n -z -t '\0' |
  xargs -0 sh -c 'pdftk "$@" cat output combinewd2.pdf' "$0"

Alternatives to xargs (bash specific)
xargs is an external command, in the previous example it invokes sh which in turn invokes pdftk.
An alternative is to use the builtin mapfile if available, or use the positional parameters.  The following examples use two functions, print0_files generates the NUL terminated filenames and create_pdf invokes pdftk:
print0_files | create_pdf combinewd2.pdf

The functions are defined as follows
#-- Generate the NUL terminated filenames, numerically sorted
print0_files() {
    find . -maxdepth 1 -type f -print0 |
        sort -k1.3n -z -t '\0'
}

#-- Read NUL terminated filenames using mapfile
create_pdf() {
    mapfile -d ''
    pdftk "${MAPFILE[@]}" cat output "$1"
}

#-- Alternative using positional parameters
create_pdf() {
    local -r pdf=$1
    set --
    while IFS= read -r -d '' f; do set -- "$@" "$f"; done
    pdftk "$@" cat output "$pdf"
}

Discussion
As pointed out in the comments the simple initial answer does not work with filenames containing spaces or other special characters.
The answer by @joeytwiddle does handle special characters, although it does not sort numerically
#-- The following will not sort numerically due to ./ prefix,
#   e.g. filenames 100, 2, 9, 3.14, 10, 1 results in
#      ./1 ./10 ./100 ./2 ./3.14 ./9
#
find . -maxdepth 1 -type f -print0 |
  sort -zn |
  xargs -0 sh -c 'pdftk "$@" cat output combinewd2.pdf' "$0"

It does not sort numerically due to each filename being prefixed by ./ by the find command.  Some versions of the find command support -printf '%P\0' which would not include the ./ prefix.  A simpler, portable fix is to add the -d, --dictionary-order option to the sort command so that it considers only blank spaces and alphanumeric characters in comparisons, but might still produce the wrong ordering
#-- The following will not sort numerically due to decimals
#   e.g. filenames 100, 2, 9, 3.14, 10, 1 results in
#      ./1 ./2 ./9 ./10 ./100 ./3.14
#
find . -maxdepth 1 -type f -print0 |
  sort -dzn |
  xargs -0 sh -c 'pdftk "$@" cat output combinewd2.pdf' "$0"

If filenames contain decimals this could lead to incorrect numeric sorting. The sort command does allow an offset into a field when sorting, sort -k1.3n, one must be careful though in defining the field separator if filenames are to be as general as possible, fortunately sort -t '\0' specifies NUL as the field separator, and the find -print0 option indicates NUL is to be used as the delimiter between filenames, so sort -z -t '\0' specifies NUL as both the record delimiter and field separator-- each filename is then a single field record.  Given that, we can then offset into the single field and skip the ./ prefix by specifying the 3rd character of the 1st field as the starting position for the numeric sort, sort -k1.3n -z -t '\0'.

A: Don't following any xargs -I solution because it can't handle white space correctly and won't work as you expected.
TLDR
ls | sort -n | xargs -d '\n' sh -c 'echo pdftk "$@" cat output combinewd2.pdf' sh

For the following solutions, I'll use ruby -e 'p ARGV' to inspect arguments, for your reference:
ruby -e 'p ARGV' foo bar buz

["foo", "bar", "buz"]

BSD xargs
This is the easiest way if you use BSD system (like macOS).
echo 3 4 | xargs -J@ ruby -e 'p ARGV' 1 2 @ 5 6

["1", "2", "3", "4", "5", "6"]

references:
-J  replstr
         If this option is specified, xargs will use the data read from
         standard input to replace the first occurrence of replstr instead
         of appending that data after all other arguments.  This option
         will not affect how many arguments will be read from input (-n),
         or the size of the command(s) xargs will generate (-s).  The op-
         tion just moves where those arguments will be placed in the com-
         mand(s) that are executed.  The replstr must show up as a dis-
         tinct argument to xargs.  It will not be recognized if, for in-
         stance, it is in the middle of a quoted string.  Furthermore,
         only the first occurrence of the replstr will be replaced.  For
         example, the following command will copy the list of files and
         directories which start with an uppercase letter in the current
         directory to destdir:

           /bin/ls -1d [A-Z]* | xargs -J % cp -Rp % destdir

GNU xargs
Because there is no -J flag, here we create a sub-shell and make use of $@ to solve the problem.
It might be a little tricky but easy to remember if you know how $@ works.
echo 3 4 | xargs sh -c 'ruby -e "p ARGV" 1 2 "$@" 5 6' sh

["1", "2", "3", "4", "5", "6"]

Note that the last sh is required, otherwise $0 would be "3" and the output would be ["1", "2", "4", "5", "6"]. It doesn't need to be sh but you should use any sensible name for $0.
-c string

    If the -c option is present, then commands are read from string.
    If there are arguments after the string, they are assigned to the positional
    parameters, starting with $0.

Why not -I?
Because it cannot handle white space correctly, for example:
echo  3 4 | xargs -I @ ruby -e 'p ARGV' 1 2 @ 5 6

["1", "2", "3 4", "5", "6"]

another example:
printf "hello world\0goodbye world" | xargs -0 -I @ ruby -e 'p ARGV' before @ after

["before", "hello world", "after"]
["before", "goodbye world", "after"]

Got expected output using sub-shell and $@:
printf "hello world\0goodbye world" | xargs -0 sh -c 'ruby -e "p ARGV" before "$@" after' sh

["before", "hello world", "goodbye world", "after"]

A: It's ugly, but you can run sh -c and access the list of arguments passed by xargs as "${@}", like so:
ls | sort -n | xargs -d'\n' sh -c 'pdftk "${@}" cat output combinewd2.pdf' "${0}"

The extra "${0}" at the end is there because, as the sh man page says

-c string
If the -c option is present, then commands are read from string. If there are arguments after the string, they are assigned to the positional parameters, starting with $0.

To test this, let's first create some files with complicated names that will mess up most other solutions:
$ seq 1 100 | xargs -I{} touch '{} with "spaces"'
$ ls
1 with "spaces"    31 with "spaces"  54 with "spaces"  77 with "spaces"
10 with "spaces"   32 with "spaces"  55 with "spaces"  78 with "spaces"
100 with "spaces"  33 with "spaces"  56 with "spaces"  79 with "spaces"
11 with "spaces"   34 with "spaces"  57 with "spaces"  8 with "spaces"
12 with "spaces"   35 with "spaces"  58 with "spaces"  80 with "spaces"
13 with "spaces"   36 with "spaces"  59 with "spaces"  81 with "spaces"
14 with "spaces"   37 with "spaces"  6 with "spaces"   82 with "spaces"
15 with "spaces"   38 with "spaces"  60 with "spaces"  83 with "spaces"
16 with "spaces"   39 with "spaces"  61 with "spaces"  84 with "spaces"
17 with "spaces"   4 with "spaces"   62 with "spaces"  85 with "spaces"
18 with "spaces"   40 with "spaces"  63 with "spaces"  86 with "spaces"
19 with "spaces"   41 with "spaces"  64 with "spaces"  87 with "spaces"
2 with "spaces"    42 with "spaces"  65 with "spaces"  88 with "spaces"
20 with "spaces"   43 with "spaces"  66 with "spaces"  89 with "spaces"
21 with "spaces"   44 with "spaces"  67 with "spaces"  9 with "spaces"
22 with "spaces"   45 with "spaces"  68 with "spaces"  90 with "spaces"
23 with "spaces"   46 with "spaces"  69 with "spaces"  91 with "spaces"
24 with "spaces"   47 with "spaces"  7 with "spaces"   92 with "spaces"
25 with "spaces"   48 with "spaces"  70 with "spaces"  93 with "spaces"
26 with "spaces"   49 with "spaces"  71 with "spaces"  94 with "spaces"
27 with "spaces"   5 with "spaces"   72 with "spaces"  95 with "spaces"
28 with "spaces"   50 with "spaces"  73 with "spaces"  96 with "spaces"
29 with "spaces"   51 with "spaces"  74 with "spaces"  97 with "spaces"
3 with "spaces"    52 with "spaces"  75 with "spaces"  98 with "spaces"
30 with "spaces"   53 with "spaces"  76 with "spaces"  99 with "spaces"
$  ls | sort -n | xargs -d'\n' sh -c 'set -x; pdftk "${@}" cat output combinewd2.pdf' "${0}"
+ pdftk '1 with "spaces"' '2 with "spaces"' '3 with "spaces"' '4 with "spaces"' '5 with "spaces"' '6 with "spaces"' '7 with "spaces"' '8 with "spaces"' '9 with "spaces"' '10 with "spaces"' '11 with "spaces"' '12 with "spaces"' '13 with "spaces"' '14 with "spaces"' '15 with "spaces"' '16 with "spaces"' '17 with "spaces"' '18 with "spaces"' '19 with "spaces"' '20 with "spaces"' '21 with "spaces"' '22 with "spaces"' '23 with "spaces"' '24 with "spaces"' '25 with "spaces"' '26 with "spaces"' '27 with "spaces"' '28 with "spaces"' '29 with "spaces"' '30 with "spaces"' '31 with "spaces"' '32 with "spaces"' '33 with "spaces"' '34 with "spaces"' '35 with "spaces"' '36 with "spaces"' '37 with "spaces"' '38 with "spaces"' '39 with "spaces"' '40 with "spaces"' '41 with "spaces"' '42 with "spaces"' '43 with "spaces"' '44 with "spaces"' '45 with "spaces"' '46 with "spaces"' '47 with "spaces"' '48 with "spaces"' '49 with "spaces"' '50 with "spaces"' '51 with "spaces"' '52 with "spaces"' '53 with "spaces"' '54 with "spaces"' '55 with "spaces"' '56 with "spaces"' '57 with "spaces"' '58 with "spaces"' '59 with "spaces"' '60 with "spaces"' '61 with "spaces"' '62 with "spaces"' '63 with "spaces"' '64 with "spaces"' '65 with "spaces"' '66 with "spaces"' '67 with "spaces"' '68 with "spaces"' '69 with "spaces"' '70 with "spaces"' '71 with "spaces"' '72 with "spaces"' '73 with "spaces"' '74 with "spaces"' '75 with "spaces"' '76 with "spaces"' '77 with "spaces"' '78 with "spaces"' '79 with "spaces"' '80 with "spaces"' '81 with "spaces"' '82 with "spaces"' '83 with "spaces"' '84 with "spaces"' '85 with "spaces"' '86 with "spaces"' '87 with "spaces"' '88 with "spaces"' '89 with "spaces"' '90 with "spaces"' '91 with "spaces"' '92 with "spaces"' '93 with "spaces"' '94 with "spaces"' '95 with "spaces"' '96 with "spaces"' '97 with "spaces"' '98 with "spaces"' '99 with "spaces"' '100 with "spaces"' cat output combinewd2.pdf

All the arguments are quoted correctly. Note that this will fail if any filenames contain newlines, and that ls -v is basically ls | sort -n.

A: I know this is not the OP's question, but I found this useful.
If you want to reshuffle your arguments you can use parallel in combination with xargs.
# limit the number of arguments per line
echo last first middle last first middle | xargs -n 3
last first middle
last first middle

GNU-parallel can now reshuffle those arguments at will with the --colsep argument.
echo last first middle last first middle | xargs -n 3 | parallel --colsep=" " echo {2} {3} {1}
first middle last
first middle last

You can also add constant arguments in there.
echo last first middle last first middle | xargs -n 3 | parallel --colsep=" " echo {2} {3} middle2 {1}
first middle middle2 last
first middle middle2 last


text:
Q: Is this a secure way to connect to mysql database I plan to use the following connection script as an include on other php scripts. My question is if I use my browser and go to this file directly I get the following message...
"Connection failed: Access denied for user 'myusername'@'localhost' (using password: YES)"
My question is should I get this message accessing the connection script directly or should I be connecting to the db. If I should be connecting, what is to prevent someone else from guessing the url of my connection script and what can they do if they do. Also if I should be connecting, why would I be getting this error as I have given the user all access privilages.
<?php
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
$db = "databasename";

// Create connection
$conn = new mysqli($servername, $username, $password, $db);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully. ";
?>


text:
Q: DataImportHandler setup with PhpMyAdmin-MySQL I am trying to index a mysql database on phpmyadmin into solr.
SOLVED BY @MatsLindh
I have tried to find information necessary but no tutorials I have found deal with this setup.
MY DATABASE:
My mysql db is locally hosted and accessed through phpmyadmin. Here is the admin page.

As you can see I have a db titled solrtest with table solr having fields id, date, Problem, and Solution.
Now to link my db, the tutorials online were a bit inconsistent. The most consistent parts told me I would need to use solrs DataImportHandler and the mysql-connector-java. Another also mentioned a jdbc plug in. I have installed and put the .jar files here in my solr/dist directory.
In some tutorials they have these also in the contrib folder but I have left in /dist.
MY FILES:
I have created a core titled solrhelp and made the following changes in the solhelp/conf files.
solrconfig.xml
<lib dir="C:\Program Files\Solr\solr-7.5.0\dist\" regex="solr-dataimporthandler-7.5.0.jar" />
  <lib dir="C:\Program Files\Solr\solr-7.5.0\dist\" regex="solr-dataimporthandler-extras-7.5.0.jar" />
  <lib dir="C:\Program Files\Solr\solr-7.5.0\dist\" regex="mysql-connector-java-8.0.13.jar" />
  <lib dir="C:\Program Files\Solr\solr-7.5.0\dist\" regex="sqljdbc41.jar" />
  <lib dir="C:\Program Files\Solr\solr-7.5.0\dist\" regex="sqljdbc42.jar" />
  <requestHandler name=" /dataimport" class=" org.apache.solr.handler.dataimport.DataImportHandler">
    <lst name=" defaults">
    <str name=" config">data-config.xml</str>
    </lst>
  </requestHandler>
  <requestHandler name " /dataimport" class=org.apache.solr.handler.dataimport.DataImportHandler">
    <lst name="defaults">
      <str name="name">solrhelp</str>
      <str name="driver">jdbc:mysql.jdbc.Driver</str>
      <str name="url">jdbc:mysql://localhost:8983/solrtest</str>
      <str name="user">root</str>
      <str name="password"></str>
    </lst>
  </requestHandler>

the created data-config.xml
<dataConfig>
<dataSource type="JdbcDataSource"
            driver="com.mysql.jdbc.Driver"
            url="jdbc:mysql://localhost:8983/solrtest"
            user="root"
            password=""/>
    <document>
    <entity name="solr"
            pk="id"
            query="select id, date, Problem, Solution from solr"
        >
        <field column="id" name="id"/>
        <field column="date" name="date"/>
        <field column="Problem" name="Problem"/>
        <field column="Solution" name="Solution"/>
    </entity>
    </document>
</dataConfig>

and the managed-schema.xml
 <field name="id" type="string" indexed="true" stored="true" multiValued="false" />
  <field name="pdate" type="date" indexed="true" stored="true" multiValued="false" />
  <field name="Problem" type="text_general" indexed="true" stored="true" />
  <field name="Solution" type="text_general" indexed="true" stored="true" />

My question to the community is rather broad and I apologize. I want to know what all I am missing before I attempt to post this db. I dont think I have edited my files correctly and I dont really know of a way to test them before I attempt to post.
It should be noted that in the dist folder I have two verions of the jdbc and have both in my solrconfig.xml file.
Any direction to better tutorials or documentation would be appreciated.
UPDATED FILES
solrconfig
  <lib dir="C:\Program Files\Solr\solr-7.5.0\dist\"
    regex="solr-dataimporthandler-7.5.0.jar" />
  <lib dir="C:\Program Files\Solr\solr-7.5.0\dist\"
    regex="solr-dataimporthandler-extras-7.5.0.jar" />
  <lib dir="C:\Program Files\Solr\solr-7.5.0\contrib\dataimporthandler\lib"
    regex="mysql-connector-java-8.0.13.jar" />
  <lib dir="C:\Program Files\Solr\solr-7.5.0\contrib\dataimporthandler\lib"
    regex="sqljdbc41.jar" />
  <lib dir="C:\Program Files\Solr\solr-7.5.0\contrib\dataimporthandler\lib"
    regex="sqljdbc42.jar" />

  <requestHandler name="/dataimport" class="org.apache.solr.handler.dataimport.DataImportHandler">
    <lst name="defaults">
    <str name="config">data-config.xml</str>
    </lst>
  </requestHandler>

data-config
<dataConfig>
<dataSource type="JdbcDataSource"
            driver="com.mysql.cj.jdbc.Driver"
            url="jdbc:mysql://localhost:8983/solrtest/solr"
            user="root"
            password=""/>
    <document>
    <entity name="solr"
            pk="id"
            query="select * from solr"
        >
        <field column="id" name="id"/>
        <field column="date" name="date"/>
        <field column="Problem" name="Problem"/>
        <field column="Solution" name="Solution"/>
    </entity>
    </document>
</dataConfig>

A: You don't import "through phpmyadmin". You use the connection information to your MySQL server. There is no http involved. jdbc:mysql://localhost:3306/dbname would be the string in your case, assuming that MySQL runs on the same computer as you're running Solr on.
Pay close attention to the port number (3306) in the connection string and the dbname. It should refer to the values of your MySQL server and not your Solr server.

A: THIS PROBLEM WAS SOLVED BY @MatsLindh
My issue was configuration syntax. Below are the corrected data-config.xml and solrconfig.xml
data-config
<dataConfig>
<dataSource type="JdbcDataSource"
            driver="com.mysql.cj.jdbc.Driver"
            url="jdbc:mysql://localhost:3306/solrtest"
            user="root"
            password=""/>
    <document>
    <entity name="solr"
            pk="id"
            query="select * from solr"
        >
        <field column="id" name="id"/>
        <field column="date" name="date"/>
        <field column="Problem" name="Problem"/>
        <field column="Solution" name="Solution"/>
    </entity>
    </document>
</dataConfig>

solrconfig
<lib dir="C:\Program Files\Solr\solr-7.5.0\dist\"
    regex="solr-dataimporthandler-7.5.0.jar" />
  <lib dir="C:\Program Files\Solr\solr-7.5.0\dist\"
    regex="solr-dataimporthandler-extras-7.5.0.jar" />
  <lib dir="C:\Program Files\Solr\solr-7.5.0\contrib\dataimporthandler\lib"
    regex="mysql-connector-java-8.0.13.jar" />
  <lib dir="C:\Program Files\Solr\solr-7.5.0\contrib\dataimporthandler\lib"
    regex="sqljdbc41.jar" />
  <lib dir="C:\Program Files\Solr\solr-7.5.0\contrib\dataimporthandler\lib"
    regex="sqljdbc42.jar" />

  <requestHandler name="/dataimport" class="org.apache.solr.handler.dataimport.DataImportHandler">
    <lst name="defaults">
    <str name="config">data-config.xml</str>
    </lst>
  </requestHandler>


text:
Q: node.js/typescript test: Unit test should return 201 response code I have a test 'should return 201 response code' which is failing:
Expected: 201
Received: 200
orderController.ts
import { Request, Response } from "express";
import { Orders } from "../models/orders";

const createOrder = async ( req: Request, res: Response) => {
  try {
    const newOrder = await Orders.create(req.body)

    res.status(201).json({
      status: 'success',
      data: {
        order: newOrder,
      }
    })
  } catch (error) {
    res.status(400).json({
      status: 'fail',
      message: error,
    });
  }
}

orderController.test.ts
import { Request, Response } from "express";
import { createOrder } from "../../controllers/orderController";
import { Orders } from "../../models/orders";
import httpMocks from 'node-mocks-http'
import newOrder from '../mock-data/new-order.json'

Orders.create = jest.fn()

let req: Request, res: Response
beforeEach(() => {
  req = httpMocks.createRequest()
  res = httpMocks.createResponse()
})

describe("createOrder", () => {
  it("should have a createOrder function", () => {
    expect(typeof createOrder).toBe("function");
  })
  it("should call Orders.create", () => {
    req.body = newOrder
    createOrder(req, res)
    expect(Orders.create).toBeCalledWith(newOrder)
  })
  it("should return 201 response code", () => {
    req.body = newOrder;
    createOrder(req, res);
    expect(res.statusCode).toBe(201);
  })
})

So in terminal getting:
✕ should return 201 response code (1 ms)

  ● createOrder › should return 201 response code

    expect(received).toBe(expected) // Object.is equality

    Expected: 201
    Received: 200

However if manually create an order in postman shows status: 201 Created.
I have changed even to a more simple orderController.ts like:
const createOrder = async (req: Request, res: Response) => {
  const newOrder = await Orders.create(req.body)
  res.status(201)
}

but getting the same result, cannot pass 'should return 201 response code'. Any ideas?

A: Just a guess:

*

*200 is the default status code of your mocked response.

*createOrder is async.

*when you assert the status code to be 201, createOrder has not been run yet.

Try to await createOrder(...) in your test and see if this helps.


text:
Q: Disabling Multiple Buttons in QTableWidget In my app,  we can add items to the QTableWidget and subsequently update buttons and Delete buttons are added to the QTableWidget, Update and delete function represent network operation, So here I have simulated with QTimer which is linked to the progress Bar. So I want to disable all the buttons whenever I clicked the Delete or Update buttons except the button which is clicked and reenable  all the buttons whenever the task is completed.
class LoginNew(QMainWindow, ui):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setupUi(self)
        self.show_database()
        self.pushButton.clicked.connect(self.addToTableWidget)

    def addToTableWidget(self):

        self.row_data = []
        self.val1 =  self.lineEdit.text()
        self.row_data.append(self.val1)
        self.val2 = self.lineEdit_2.text()
        self.row_data.append(self.val2)
        self.val3 =  self.lineEdit_3.text()
        self.row_data.append(self.val3)

        row = self.tableWidget.rowCount()
        self.tableWidget.setRowCount(row+1)
        col = 0
        for item in self.row_data:
            cell = QTableWidgetItem(str(item))
            self.tableWidget.setItem(row, col, cell)
            col += 1

        db_new.insert(self.val1,self.val2, self.val3)

        for index in range(self.tableWidget.rowCount()):
            self.btx =  QPushButton(self.tableWidget)
            self.btn =  QPushButton(self.tableWidget)
            self.btx.setText("Update")
            self.btn.setIcon(QIcon(QPixmap("delete.png")))
            self.btn.setIconSize(QSize(35,45))
            self.btx.clicked.connect(self.update_pos)
            self.btn.clicked.connect(self.delete_pos)
            self.tableWidget.setCellWidget(index,3, self.btx)
            self.tableWidget.setCellWidget(index,4,self.btn)

    def show_database(self):
        res = db_new.fetch_data()
        self.tableWidget.setRowCount(0)
        for row_number, row_data in enumerate(res):
            self.tableWidget.insertRow(row_number)
            for column_number, data in enumerate(row_data):
                self.tableWidget.setItem(row_number, column_number+1  ,  QTableWidgetItem(str(data)))

        for index in range(self.tableWidget.rowCount()):
            self.btx =  QPushButton(self.tableWidget)
            self.btn =  QPushButton(self.tableWidget)
            self.btx.setText("Update")
            self.btn.setIcon(QIcon(QPixmap("delete.png")))
            self.btn.setIconSize(QSize(35,35))
            self.btx.clicked.connect(self.update_pos)
            self.btn.clicked.connect(self.delete_pos)
            self.tableWidget.setCellWidget(index,4, self.btx)
            self.tableWidget.setCellWidget(index,0,self.btn)

    def update_pos(self):
        self.button =self.focusWidget()
        self.index = self.tableWidget.indexAt(self.button.pos())
        self.button.clicked.connect(self.btn_trigger)

    def btn_trigger(self):

        QMessageBox.information(self, "Update Data", f' Value  is {self.index.row()} {self.index.column()}')
        self.geti=10
        self.timer = QTimer()
        self.timer.timeout.connect(self.num)
        self.timer.start(2000)
        self.show_database()

    def cell_was_clicked(self, row,column, kale):
        print("Row %d and Column %d was clicked" % (row, column))
        item = self.tableWidget.itemAt(row, column)
        self.ID = item.text()
        QMessageBox.information(self, "INFORMATION",f'ID VALUE is  {item.text()}')

    def delete_pos(self):

        print("delete Button was clicked")
        self.geti=0
        self.timer = QTimer()
        self.timer.timeout.connect(self.num)

        self.timer.start(1000)

    def num(self):

        if self.geti <9999:
            print ( self.geti )
            self.geti += 1
            self.progressBar.setValue(self.geti)
        else:
            self.timer.stop()

def main():
    app =  QApplication(sys.argv)
    win = LoginNew()
    win.show()
    app.exec_()

if __name__ =='__main__':
    main()

I have tried using  self.btx.setEnabled(False)  But I am unable to decide which all buttons should be disabled??
Link for the UI image
Actual Ui

A: If you just want to collect all of specific elements, like lineEdits, into an
iterable collection, such as a list, here's a one-time function that lets you pass various instructions to that function to affect all of its fields.
I hope this routine is helpful to someone.   ~Mike

        def all_fields(switch=""):
            field_list = [  self.lineEdit_1,
                            self.lineEdit_2,
                            self.lineEdit_3,
                            self.lineEdit_4,
                            self.lineEdit_5,
                            self.lineEdit_6,
                            self.lineEdit_7,
                            self.lineEdit_8,
                            self.lineEdit_9,
                            self.lineEdit_10,
                            self.textEdit  ]
            for field in field_list:
                if str(switch).lower() == "clear":
                    field.clear()
                elif str(switch).lower() == "disable":
                    field.setDisabled(True)
                elif str(switch).lower() == "enable":
                    field.setDisabled(False)

        all_fields("disable")

A: The task at hands is:

I want to disable all the buttons whenever I clicked the Delete or Update buttons except the button which is clicked

One solution could be:

*

*Keep a list of all buttons

*Write a method that disables all buttons except the specified one (in an argument).
You can go through all buttons and compare to the specified one to determine disable or enable

*For each button, write a small lambda that calls the method in (2) with the button as argument. Connect this lambda to the button's pressed event

Alternatively, you could also use a QSignalMapper. You would then connect the mapped signal to the method in (2).


text:
Q: Rails 3 query matching attribute of has_one association that is a subset of has_many association The title is confusing, but allow me to explain. I have a Car model that has multiple datapoints with different timestamps. We are almost always concerned with attributes of its latest status. So the model has_many statuses, along with a has_one to easily access it's latest one:
class Car < ActiveRecord::Base
  has_many :statuses, class_name: 'CarStatus', order: "timestamp DESC"
  has_one :latest_status, class_name: 'CarStatus', order: "timestamp DESC"

  delegate :location, :timestamp, to: 'latest_status', prefix: 'latest', allow_nil: true

  # ...
end

To give you an idea of what the statuses hold:
loc = Car.first.latest_location   # Location object (id = 1 for example)
loc.name                          # "Miami, FL"

Let's say I wanted to have a (chainable) scope to find all cars with a latest location id of 1. Currently I have a sort of complex method:
# car.rb
def self.by_location_id(id)
  ids = []
  find_each(include: :latest_status) do |car|
    ids << car.id if car.latest_status.try(:location_id) == id.to_i
  end
  where("id in (?)", ids)
end

There may be a quicker way to do this using SQL, but not sure how to only get the latest status for each car. There may be many status records with a location_id of 1, but if that's not the latest location for its car, it should not be included.
To make it harder... let's add another level and be able to scope by location name. I have this method, preloading statuses along with their location objects to be able to access the name:
def by_location_name(loc)
  ids = []
  find_each(include: {latest_status: :location}) do |car|
    ids << car.id if car.latest_location.try(:name) =~ /#{loc}/i
  end
  where("id in (?)", ids)
end

This will match the location above with "miami", "fl", "MIA", etc... Does anyone have any suggestions on how I can make this more succinct/efficient? Would it be better to define my associations differently? Or maybe it will take some SQL ninja skills, which I admittedly don't have.
Using Postgres 9.1 (hosted on Heroku cedar stack)

A: All right. Since you're using postgres 9.1 like I am, I'll take a shot at this. Tackling the first problem first (scope to filter by location of last status):
This solution takes advantage of PostGres's support for analytic functions, as described here: http://explainextended.com/2009/11/26/postgresql-selecting-records-holding-group-wise-maximum/
I think the following gives you part of what you need (replace/interpolate the location id you're interested in for the '?', naturally):
select *
from (
  select cars.id as car_id, statuses.id as status_id, statuses.location_id, statuses.created_at, row_number() over (partition by statuses.id order by statuses.created_at) as rn
  from cars join statuses on cars.id = statuses.car_id
) q
where rn = 1 and location_id = ?

This query will return car_id, status_id, location_id, and a timestamp (called created_at by default, although you could alias it if some other name is easier to work with).
Now to convince Rails to return results based on this. Because you'll probably want to use eager loading with this, find_by_sql is pretty much out. There is a trick I discovered though, using .joins to join to a subquery. Here's approximately what it might look like:
def self.by_location(loc)
  joins(
    self.escape_sql('join (
    select *
    from (
      select cars.id as car_id, statuses.id as status_id, statuses.location_id, statuses.created_at, row_number() over (partition by statuses.id order by statuses.created_at) as rn
      from cars join statuses on cars.id = statuses.car_id
    ) q
    where rn = 1 and location_id = ?
    ) as subquery on subquery.car_id = cars.id order by subquery.created_at desc', loc)
  )
end

Join will act as a filter, giving you only the Car objects that were involved in the subquery.
Note: In order to refer to escape_sql as I do above, you'll need to modify ActiveRecord::Base slightly. I do this by adding this to an initializer in the app (which I place in app/config/initializers/active_record.rb):
class ActiveRecord::Base
  def self.escape_sql(clause, *rest)
    self.send(:sanitize_sql_array, rest.empty? ? clause : ([clause] + rest))
  end
end

This allows you to call .escape_sql on any of your models that are based on AR::B. I find this profoundly useful, but if you've got some other way to sanitize sql, feel free to use that instead.
For the second part of the question - unless there are multiple locations with the same name, I'd just do a Location.find_by_name to turn it into  an id to pass into the above. Basically this:
def self.by_location_name(name)
 loc = Location.find_by_name(name)
 by_location(loc)
end


text:
Q: Counter is working, but how to make it list counted values? I have a macro with counter for unique values that met specific conditions. As you can see on the image, I have list of unique values in column F. Macro checks, if value is listed in column AE (can contain duplicated lines) and checks if there is no "OB" in column AH. Then returns how many values it found in cell K2. But I need this counter to also list these values in column AD, but I am struggling to make it happen. I checked many forums and managed to crash Excel twice already. Any ideas how to achieve it?

Dim myTbl As range, mStr As String, Miss As Long, xCol As Variant

Set myTbl = Sheets("OB").range("AE2")      '
xCol = "AH"

mStr = ""
Set myTbl = range(myTbl, myTbl.End(xlDown).Offset(0, 1))
xCol = Cells(1, xCol).Column - myTbl.Cells(1, 1).Column + 1
For i = 1 To myTbl.Rows.count
    If myTbl.Cells(i, 1) <> "" Then
        If myTbl.Cells(i, xCol) <> "OB" And InStr(1, mStr, "##" & myTbl.Cells(i, 1), vbTextCompare) = 0 Then
            mStr = mStr & "##" & myTbl.Cells(i, 1)
            Miss = Miss + 1
        End If
    End If
Next i

If Miss > 0 Then
     range("K2") = Miss & " still active"
     range("K2").Font.ColorIndex = 46

     Else
     range("K2") = "None"
     range("K2").Font.ColorIndex = 10
End If

A: Please, test the next code. It, also, is able to return how many occurrences per each Value x have been found (if more than one per each exist):
Sub ExtractUniqueCondValues()
   Dim sh As Worksheet, lastR As Long, arr, i As Long, dict As Object

   Set sh = Sheets("OB")
   lastR = sh.Range("AE" & sh.rows.count).End(xlUp).row
   arr = sh.Range("AE2:AH" & lastR).Value

   Set dict = CreateObject("Scripting.Dictionary")
   For i = 1 To UBound(arr)
        If arr(i, 4) <> "OB" Then dict(arr(i, 1)) = dict(arr(i, 1)) + 1
   Next i

   sh.Range("K2").Value = dict.count
   sh.Range("AD2").Resize(dict.count, 1).Value = Application.Transpose(dict.Keys)
End Sub

About occurrences per each 'Value x' element, it can return in an adiacent column 'Value 2| 1 andValue 4` | 2, for your picture case... Of course, if it may have relevance for your purpose. The dictionary already keeps this data.

A: Maybe using formulas is an option for you? See column G where the formula in G2 is the following and copied down.
=IF(COUNTIFS(AE:AE,F2,AH:AH,"<>OB")>0,F2,"")

Using Count or Countifs may be an option instead of VBA.


text:
Q: Drawing board/grid with Cocoa I'm writing a small boardgame for Mac OS X using Cocoa. I the actual grid is drawn as follows:
- (void)drawRect:(NSRect)rect
{
    for (int x=0; x < GRIDSIZE; x++) {
        for (int y=0; y < GRIDSIZE; y++) {

            float ix = x*cellWidth;
            float iy = y*cellHeight;

            NSColor *color = (x % 2 == y % 2) ? boardColors[0] : boardColors[1];
            [color set];

            NSRect r = NSMakeRect(ix, iy, cellWidth, cellHeight);

            NSBezierPath *path = [NSBezierPath bezierPath];
            [path appendBezierPathWithRect:r];

            [path fill];
            [path stroke];
        }
    }
}

This works great, except that I see some errors in colors between the tiles. I guess this is due to some antialiasing or similar. See screenshots below (hopefully you can also see the same problems... its some black lines where the tiles overlap):

Therefore I have these questions:

*

*Is there any way I can remove these graphical artefacts while still maintaining a resizable/scalable board?

*Should I rather use some other graphical library like Core Graphics or OpenGL?

Update:
const int GRIDSIZE = 16;
cellWidth = (frame.size.width / GRIDSIZE);
cellHeight = (frame.size.height / GRIDSIZE);

A: If you want crisp rectangles you need to align coordinates so that they match the underlying pixels. NSView has a method for this purpose: - (NSRect)backingAlignedRect:(NSRect)aRect options:(NSAlignmentOptions)options. Here's a complete example for drawing the grid:
const NSInteger GRIDSIZE = 16;

- (void)drawRect:(NSRect)dirtyRect {
    for (NSUInteger x = 0; x < GRIDSIZE; x++) {
        for (NSUInteger y = 0; y < GRIDSIZE; y++) {
            NSColor *color = (x % 2 == y % 2) ? [NSColor greenColor] : [NSColor redColor];
            [color set];
            [NSBezierPath fillRect:[self rectOfCellAtColumn:x row:y]];
        }
    }
}

- (NSRect)rectOfCellAtColumn:(NSUInteger)column row:(NSUInteger)row {
    NSRect frame = [self frame];
    CGFloat cellWidth = frame.size.width / GRIDSIZE;
    CGFloat cellHeight = frame.size.height / GRIDSIZE;
    CGFloat x = column * cellWidth;
    CGFloat y = row * cellHeight;
    NSRect rect = NSMakeRect(x, y, cellWidth, cellHeight);
    NSAlignmentOptions alignOpts = NSAlignMinXNearest | NSAlignMinYNearest |
            NSAlignMaxXNearest | NSAlignMaxYNearest ;
    return [self backingAlignedRect:rect options:alignOpts];
}

Note that you don't need stroke to draw a game board. To draw pixel aligned strokes you need to remember that coordinates in Cocoa actually point to lower left corners of pixels. To crisp lines you need to offset coordinates by half a pixel from integral coordinates so that coordinates point to centers of pixels. For example to draw a crisp border for a grid cell you can do this:
NSRect rect = NSInsetRect([self rectOfCellAtColumn:column row:row], 0.5, 0.5);
[NSBezierPath strokeRect:rect];

A: First, make sure your stroke color is not black or gray. (You're setting color but is that stroke or fill color? I can never remember.)
Second, what happens if you simply fill with green, then draw red squares over it, or vice-versa?
There are other ways to do what you want, too. You can use the CICheckerboardGenerator to make your background instead.
Alternately, you could also use a CGBitmapContext that you filled by hand.

A: First of all, if you don't actually want your rectangles to have a border, you shouldn't call [path stroke].
Second, creating a bezier path for filling a rectangle is overkill. You can do the same with NSRectFill(r). This function is probably more efficient and I suspect less prone to introduce rounding errors to your floats – I assume you realize that your floats must not have a fractional part if you want pixel-precise rectangles. I believe that if the width and height of your view is a multiple of GRIDSIZE and you use NSRectFill, the artifacts should go away.
Third, there's the obvious question as to how you want your board drawn if the view's width and height are not a multiple of GRIDSIZE. This is of course not an issue if the size of your view is fixed and a multiple of that constant. If it is not, however, you first have to clarify how you want the possible remainder of the width or height handled. Should there be a border? Should the last cell in the row or column take up the remainder? Or should it rather be distributed equally among the cells of the rows or columns? You might have to accept cells of varying width and/or height. What the best solution for your problem is, depends on your exact requirements.
You might also want to look into other ways of drawing a checkerboard, e.g. using CICheckerboardGenerator or creating a pattern color with an image ([NSColor colorWithPatternImage:yourImage]) and then filling the whole view with it.
There's also the possibility of (temporarily) turning off anti-aliasing. To do that, add the following line to the beginning of your drawing method:
  [[NSGraphicsContext currentContext] setShouldAntialias:NO];

My last observation is about your general approach. If your game is going to have more complicated graphics and animations, e.g. animated movement of pieces, you might be better off using OpenGL.

A: As of iOS 6, you can generate a checkerboard pattern using CICheckerboardGenerator.
You'll want to guard against the force unwraps in here, but here's the basic implementation:
var checkerboardImage: UIImage? {
    let filter = CIFilter(name: "CICheckerboardGenerator")!

    let width = NSNumber(value: Float(viewSize.width/16))
    let center = CIVector(cgPoint: .zero)
    let darkColor = CIColor.red
    let lightColor = CIColor.green
    let sharpness = NSNumber(value: 1.0)

    filter.setDefaults()
    filter.setValue(width, forKey: "inputWidth")
    filter.setValue(center, forKey: "inputCenter")
    filter.setValue(darkColor, forKey: "inputColor0")
    filter.setValue(lightColor, forKey: "inputColor1")
    filter.setValue(sharpness, forKey: "inputSharpness")

    let context = CIContext(options: nil)
    let cgImage = context.createCGImage(filter.outputImage!, from: viewSize)
    let uiImage = UIImage(cgImage: cgImage!, scale: UIScreen.main.scale, orientation: UIImage.Orientation.up)

    return uiImage
}

Apple Developer Docs

A: Your squares overlap. ix + CELLWIDTH is the same coordinate as ix in the next iteration of the loop.
You can fix this by setting the stroke color explicitly to transparent, or by not calling stroke.
[color set];
[[NSColor clearColor] setStroke];

or
[path fill];
// not [path stroke];


text:
Q: How to have bash' history as the same as the preceding Bash'? How to have bash' history as the same as the preceding Bash'?
Few last history of bash is demanded to be so in the following but fail
$ bash -lc 'find . -iname \*.c;  bash -l'
#or

$ bash -lc 'history -s find . -iname \*.c; history -w; bash -l'

won't have history of
find . -iname \*.c

How to solve such this?

A: You are invoking a non-interactive shell to run your find-command.
Non-interactive shells do not have history by default.
See History command inside bash script for possible solutions.


text:
Q: problems with MultiIndex I'm having problems with MultiIndex and stack(). The following example is based on a solution from Calvin Cheung on StackOvervlow.
=== multi.csv ===
  h1,main,h3,sub,h5
  a,A,1,A1,1
  b,B,2,B1,2
  c,B,3,A1,3
  d,A,4,B2,4
  e,A,5,B3,5
  f,B,6,A2,6

=== multi.py ===
  #!/usr/bin/env python

  import pandas as pd

  df1 = pd.read_csv('multi.csv')
  df2 = df1.pivot('main', 'sub').stack()
  print(df2)

=== output ===
           h1  h3  h5
  main sub
  A    A1   a   1   1
       B2   d   4   4
       B3   e   5   5
  B    A1   c   3   3
       A2   f   6   6
       B1   b   2   2

This works as long as the entries in the sub column are unique with respect to the corresponding entry in the main column. But if we change the sub column entry in row e to B2, then B2 is no longer unique in the group of A rows and we get an error message: "pandas.core.reshape.ReshapeError: Index contains duplicate entries, cannot reshape".
I was expected the shape of the sub index to behave like the shape of the primary index where duplicates are indicated with blank entries under the first row entry.
=== expected output ===
           h1  h3  h5
  main sub
  A    A1   a   1   1
       B2   d   4   4
            e   5   5
  B    A1   c   3   3
       A2   f   6   6
       B1   b   2   2

So my question is, how can I structure a MultiIndex in a way that allows duplicates in sub-levels?

A: Rather than do a pivot*, just set_index directly (this works for both examples):
In [11]: df
Out[11]:
  h1 main  h3 sub  h5
0  a    A   1  A1   1
1  b    B   2  B1   2
2  c    B   3  A1   3
3  d    A   4  B2   4
4  e    A   5  B2   5
5  f    B   6  A2   6

In [12]: df.set_index(['main', 'sub'])
Out[12]:
         h1  h3  h5
main sub
A    A1   a   1   1
B    B1   b   2   2
     A1   c   3   3
A    B2   d   4   4
     B2   e   5   5
B    A2   f   6   6

*You're not really doing a pivot here anyway, it just happens to work in the above case.


text:
Q: How open Foundation modal loaded dynamically I'm using $.load() function to load html content. Inside this it, I listed card with button that on click should open a Foundation modal:
<button class="button button--modal-info button--modal-info--white user-area-card-modal-info" data-open="<?php echo 'user-area-card-' . $post_id . '-modal'; ?>" aria-controls="<?php echo 'user-area-card-' . $post_id . '-modal'; ?>" aria-haspopup="true" tabindex="0">

</button>

<button class="close-button modal__close-btn" data-close aria-label="Close modal" type="button">
    ×
</button>

<?php echo get_field( '_m_legend_modal_description' ); ?>

Now I solved (in some way) my problem with this:
$('body').on('click', '.user-area-card-modal-info', function() {
    const open_id = $(this).data('open');
    new Foundation.Reveal($('#' + open_id)).open();
});

But often if I open and close modal, the latter close, but Overlay remains
How can I solve?

A: I solved in this way:

*

*I included of modal out of the content generated dinamically

*Fetch text with attribute/hidden field and put it inside modal


text:
Q: One check mark per section I try to only show one check mark per section. So when the user selects a row in a section the last selected row in this row should be deselected and the new row selected with a checkmark. I want to approach this very dynamic and generic since there is going to be an dynamic number of sections.
What I have so far is the following:
if(self.product ? subMenus.group.selectedRow  : subMenusInProductCart.group.selectedRow)
    {
        UITableViewCell *uncheckCell;

        if (self.product) {

            uncheckCell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:subMenus.group.selectedRow.integerValue inSection:indexPath.section]];

            if (uncheckCell.accessoryType == UITableViewCellAccessoryCheckmark) {

                SubMenus *subMenu = [self.indexPathController.dataModel itemAtIndexPath:[NSIndexPath indexPathForRow:subMenus.group.selectedRow.integerValue inSection:indexPath.section]];

                subMenu.selected = @(NO);

                if (subMenus.price.floatValue > 0) {

                    self.totalPrice = [self subtractSubMenuPrice:subMenus.price.floatValue fromProductPrice:self.totalPrice];

                }

            }

        }else if (self.cartProduct) {

            uncheckCell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:subMenusInProductCart.group.selectedRow.integerValue inSection:indexPath.section]];

            if (uncheckCell.accessoryType == UITableViewCellAccessoryCheckmark) {

                SubMenuProductCart *subMenuProductCart = [self.indexPathController.dataModel itemAtIndexPath:[NSIndexPath indexPathForRow:subMenus.group.selectedRow.integerValue inSection:indexPath.section]];
                subMenuProductCart.selected = @(NO);

                if (subMenuProductCart.subMenu.price.floatValue > 0) {
                    self.totalPrice = [self subtractSubMenuPrice:subMenuProductCart.subMenu.price.floatValue fromProductPrice:self.totalPrice];
                }

            }

        }

        uncheckCell.accessoryType = UITableViewCellAccessoryNone;

    }

    if ([subMenus.group.selectedRow isEqualToNumber:@(indexPath.row)])
    {

        if (self.product) {

            subMenus.selected = @(NO);

            subMenus.group.selectedRow = nil;

            if (subMenus.price.floatValue > 0) {

                self.totalPrice = [self subtractSubMenuPrice:subMenus.price.floatValue fromProductPrice:self.totalPrice];

            }

        }

    }else {

        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

        cell.accessoryType = UITableViewCellAccessoryCheckmark;

        if (self.product) {

            subMenus.selected = @(YES);

            subMenus.group.selectedRow = @(indexPath.row);

            if (subMenus.price.floatValue > 0) {
                self.totalPrice = [self addSubMenuPrice:subMenus.price.floatValue toProductPrice:self.totalPrice];
            }

        }else if (self.cartProduct) {

            subMenusInProductCart.selected = @(YES);

            subMenusInProductCart.group.selectedRow = @(indexPath.row);

            if (subMenusInProductCart.subMenu.price.floatValue > 0) {
                self.totalPrice = [self addSubMenuPrice:subMenusInProductCart.subMenu.price.floatValue toProductPrice:self.totalPrice];
            }

        }

    }

The above code is working, but I think their must be a better solution to this, than saving the selected row in Core Data? Please bear in mind that the selected state is going to be manipulated later, since the user can change his or her's selection (shopping cart). Currently the selected object (row) is passed to another object (a relationship object) with an independent selected row property.
In order to illustrate my setup:

So is there a better and more generic way to handle this one selection per section with Core Data objects instead of saving the selected row in with the NSMangedObject, which dosen't seems so MVC'ish?

A: If selectedRow is a meaningful part of your data model I see no problem with saving the selected state in Core Data. I am not sure what the relationship between the selected and selectedRow attribute is, but ideally you would do with only one of these.


text:
Q: WCF Service with SSL and Custom Authentication So I am trying to create a WCF Service that uses SSL and with a Custom Authenticator.
This is the Server config:
<?xml version="1.0"?>

<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" strict="false" explicit="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2"/>
  </system.web>
  <system.serviceModel>

    <bindings>
      <wsHttpBinding>
        <binding name="SSL">
          <security mode="TransportWithMessageCredential">
            <message clientCredentialType="UserName"/>
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>

    <services>
      <service behaviorConfiguration="CustomValidation" name="WCFService.Service1">
        <endpoint address="" binding="wsHttpBinding" contract="WCFService.IService1" bindingConfiguration="SSL"/>
        <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/>
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="CustomValidation">
          <serviceMetadata httpsGetEnabled="true" />
          <serviceDebug httpsHelpPageEnabled="true" includeExceptionDetailInFaults="true" />
          <serviceCredentials>
            <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="WCFService.Verification, WCFService" />
          </serviceCredentials>
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="false" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="false"/>
  </system.webServer>

</configuration>

This is my Validation Class:
Imports System.IdentityModel.Selectors

Public Class Verification
    Inherits UserNamePasswordValidator

    Public Overrides Sub Validate(userName As String, password As String)

        If Not (username = "Admin" AndAlso password = "Fake Password") Then
            Throw New Exception("Wrong Username Password combination.")
        End If

    End Sub

End Class

App Config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.diagnostics>
        <sources>
            <source name="System.ServiceModel.MessageLogging" switchValue="Warning,ActivityTracing">
                <listeners>
                    <add type="System.Diagnostics.DefaultTraceListener" name="Default">
                        <filter type="" />
                    </add>
                    <add name="ServiceModelMessageLoggingListener">
                        <filter type="" />
                    </add>
                </listeners>
            </source>
        </sources>
        <sharedListeners>
            <add initializeData="c:\users\connor smith\documents\visual studio 2015\projects\wcfserviceconsumer\wcfserviceconsumer\app_messages.svclog"
                type="System.Diagnostics.XmlWriterTraceListener, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
                name="ServiceModelMessageLoggingListener" traceOutputOptions="Timestamp">
                <filter type="" />
            </add>
        </sharedListeners>
        <trace autoflush="true" />
    </system.diagnostics>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
    <system.serviceModel>
        <diagnostics>
            <messageLogging logEntireMessage="true" logMalformedMessages="true"
                logMessagesAtTransportLevel="true" />
        </diagnostics>
        <bindings>
            <wsHttpBinding>
                <binding name="WSHttpBinding_IService1">
                    <security mode="TransportWithMessageCredential">
                        <transport clientCredentialType="None" />
                        <message clientCredentialType="UserName" />
                    </security>
                </binding>
            </wsHttpBinding>
        </bindings>
        <client>
            <endpoint address="https://mysite.co.uk/WCFService/Service1.svc"
                binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService1"
                contract="AService.IService1" name="WSHttpBinding_IService1" />
        </client>
    </system.serviceModel>
</configuration>

I consume it in a test application, then I set the Username and Password to be Admin and Fake Password, then I go to use the service and get the following error:
Error
Edit: Some more error information:
'An unhandled exception of type 'System.ServiceModel.ProtocolException' occurred in mscorlib.dll'
Am I missing something?


text:
Q: Flash/Php/MySQL Registration Form I've been to almost every forum possible with this question (including this one). I almost got the answer to my question. The problem is no one seems to figure out my problem because everything looks right, and everything looks right to me too. Can someone please help me? Here are my codes.
Flash Code:
var lvSend:LoadVars = new LoadVars();
var lvReceive:LoadVars = new LoadVars();

register_button.onRelease = function(){
var valid:Boolean = validateForm();
if (valid) {
    //gather information and put in loadvars object
    lvSend.username = username1.text;
    lvSend.password = password1.text;
    lvSend.email = email1.text;
    lvSend.sendAndLoad("register.php", lvReceive, "POST");
    gotoAndStop(1);
}
};
lvReceive.onLoad = function(success:Boolean) {
if (success) {
    username1.text = "";
    password1.text = "";
    email1.text = "";
}
}
function validateForm():Boolean {
if (username1.text == "" || password1.text == "" || email1.text == "") {
    return false;
}
return true;
}

Php Code:
http://i.stack.imgur.com/RXPWb.png
(Sorry its in link form)
Please favorite this or something until I get an answer because I've been everywhere and no one could help me. :/ BTW I have been getting a few blank entries into my database but I don't know why. Also, the lvReceive function doesn't seem to work, but when I add the username1.text = ""; into the register_button function it seems to clear the text fields. Please help me. I left the database info on the php file cause I thought maybe the database I entered could be the problem, but I did use this php code with an html file and it worked fine. I will accept any answers. Thanks in advance! :D

A: lvSend.sendAndLoad("register.php", lvReceive, "POST");

You put the information in lvSend and not in lvReceive.
Perhaps you should put the information in lvReceive:
    lvReceive.username = username1.text;
    lvReceive.password = password1.text;
    lvReceive.email = email1.text;
    lvSend.sendAndLoad("register.php", lvReceive, "POST");


text: Q: How to prove that $ \max_{i=1,2}\{ |X_{i}^{\top}\theta| \}\geq a\delta $ where $ a=(|x_{1}-x_{2}|)/(4\max\{1,|x_{1}|,|x_{2}|\}) $? It is known that $ \| \theta\|_{2}\geq \delta>0 $ and $ \theta\in\mathbb{R}^{2} $. Let $ X_{i}=(1,x_{i})^{\top},i=1,2, $ where $ x_{1}\neq x_{2} $ and $ x_{1},x_{2}\in\mathbb{R} $. How to prove that the following inequality is true: $ \max_{i=1,2}\{ |X_{i}^{\top}\theta| \}\geq a\delta $ where $ a=(|x_{1}-x_{2}|)/(4\max\{1,|x_{1}|,|x_{2}|\}) $?


text:
Q: Timeout a java function when a third party method call hangs I have a java application which calls a third party method, which can block indefinitely without throwing an exception.
Is it possible to wrap my method call in a timeout block (or thread, or other construct) such that I get back control after I assume the call is never returning?

A: The ThreadPoolExecutor should do what you need. Using the awaitTermination method:

Blocks until all tasks have completed execution after a shutdown
  request, or the timeout occurs, or the current thread is interrupted,
  whichever happens first.

A: all this multi threading is surely an answer but think if ur application is not a multi-threaded one, you can just store the timestamp of the moment you send the request and check it against the current timestamp. of course you will need a thread to keep track of the time. but all in all you can use that same thread for this purpose for as many functions calls you need. so dont go on implementing the runnable in ur classes. just make one tracker thread.


text:
Q: Redirect to Same method in Same Controller in Symfony (Pagination links) Well i have this Method:
/**
 * @Route("/articles/{category}/{id}/true/{page}", defaults={"page"=1}, name="articleAjax")
 */
public function getArticlesAjax($category, $id, $page)
{
}

Inside i want to create pagination link, like this:
    $html .= '
';

    for ($i = 1; $i <= $totalPages; $i++) {
        $html .= '
' . $i . '
';
    }

    $html .= '
';

But now, how to set href to same method and pass variables. Then in view file, just to render this variable $html Any ideas?

A: If you want to generate a url of a controller inside a controller use $this->generateUrl() in your exmaple you could do something like this:
for ($i = 1; $i <= $totalPages; $i++) {
    $route = $this->generateUrl('articleAjax', [
        'category' => $category,
        'id' => $id,
        'page' => $i,
    ]);

    $html .= '
' . $i . '
';
}

But I would recomment to this in your twig template and there use the {{ path() }} function.


text:
Q: Text box and Drop Down list I want design a web form,its have to control one Text Box and one Drop Down list when type a number between 5 and 10 in Text Box, Drop Down list is include 1,2,3,4,5 and when type a number between 11 and 20 in Text Box, Drop Down list is include 6,7,8,9,10.
How to do it without page refreshing?
please explain with code.

A: I think the following code may help you.
 <select id="txt" onchange="changeNumber()">
   <option>select value</option>
  <option>10</option>
  <option>11</option>
  <option>12</option>
  <option>13</option>
  <option>14</option>
  <option>15</option>
  <option>16</option>
  <option>17</option>
  <option>18</option>
  <option>19</option>
  <option>20</option>
</select>
<select id="mySelect">
  <option>21</option>
  <option>22</option>
  <option>23</option>
  <option>24</option>
</select>
<script>
function changeNumber(){
    var t_value=document.getElementById('txt').value;
    if(t_value==10 ||t_value==11 || t_value==12 || t_value==13 || t_value==14 || t_value==15 ){
        var x = document.getElementById("mySelect").selectedIndex;
        var y = document.getElementById("mySelect");
        var j=1
        for(var i=0;i<=y.options.length;i++){
            y[i].text=j;
            j++;
        }
    }
}
</script>

In this way you can solve your 2nd problem.

A: You can also follow the below code.
<input type="text" id="txt" onkeyup="checkValue();" />
<select id="mySelect">
  <option>21</option>
  <option>22</option>
  <option>23</option>
  <option>24</option>
</select>
<script>
function checkValue(){
    var t_value=document.getElementById('txt').value;
    if(t_value==10 ||t_value==11 || t_value==12 || t_value==13 || t_value==14 || t_value==15){
        var x = document.getElementById("mySelect").selectedIndex;
        var y = document.getElementById("mySelect");
        var j=1
        for(var i=0;i<=y.options.length;i++){
            y[i].text=j;
            j++;
        }
    }
}
</script>

I think this type of solution you need.


text:
Q: Postprocessing of image segmentation I have a 3D NumPy dataset [images number, x, y] in which the probability that the pixel belongs to a class is stored as a float (0-1). I would like to correct the wrong segmented pixels (with high performance).
The probabilities are part of a movie in which objects are moving from right to left and possibly back again. The basic idea is that I fit the pixels with a Gaussian function or comparable function and look at around 15-30 images ( [i-15 : i+15 ,x, y] ). It is very probable that if the previous 5 pixels and the following 5 pixels are classified in this class, this pixel also belongs to this class.
If I solve this problem with looping it takes too much time (although I use multiprocessing and multi-threading). The size of the NumPy array is [300, 600,600] or higher but the images are always square.
Here my example code with comments:
from scipy.optimize import curve_fit
from scipy import exp
import numpy as np

def gaus(x, a, x0, sigma):
    return a*exp(-(x-x0)**2/(2*sigma**2))

if __name__ == '__main__':
    # output_AI = [imageNr, x, y] example 5, 2, 2
    # At position [2][1][1] is the error, the pixels before and after were classified to the class but not this pixel.
    # The objects do not move in such a speed, so the probability should be corrected.
    outputAI = np.array([[[0.1, 0], [0, 0]], [[0.8, 0.3], [0, 0.2]], [[1, 0.1], [0, 0.2]],
                         [[0.1, 0.3], [0, 0.2]], [[0.8, 0.3], [0, 0.2]]])
    correct_output = np.zeros(outputAI.shape)

    # I correct now in this example only all pixels in image 3, in the code a loop runs over the whole 3D array and
    # corrects every image and every pixel separately
    size_of_array = outputAI.shape
    x = range(size_of_array[0])
    for i in range(size_of_array[1]):
        for k in range(size_of_array[2]):
            args, cov = curve_fit(gaus, x, outputAI[:, i, k])
            correct_output[2, i, k] = gaus(2, *args)

    print(correct_output[2])
    # [[9.88432346e-01 2.10068763e-01]
    # [6.02428922e-20 2.07921125e-01]]
    # The wrong pixel at position [0][0] was corrected from 0.2 to almost 1, the others are still not assigned
    # to the class.


text:
Q: Why do npm packages resolve from /AppData and not from local /node_modules? When developing locally in VS Code, packages are resolving to C:/Users/<User>/AppData/Local/Microsoft/TypeScript/3.5/node_modules/@types/<package>/index and not from the /node_modules directory local to the package.json.
I'm not getting any compiling errors or when deploying, but I can't wrap my head around why it's not resolving to the location I'd expect it to. Any idea why and how to fix it?
I'm using Node 8.12 and NPM 6.4.1.
Here's an example

package.json
{
  "name": "superapp",
  "version": "0.0.1",
  "description": "",
  "main": "server.js",
  "scripts": {
    "start": "node server"
  },
  "keywords": [],
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "dotenv": "^8.0.0",
    "express": "^4.17.1"
  }
}

A: Your module in question @types/express is not present in package.json
npm install @types/express --save-dev

You may have installed it globally previously and that is why it can be found in AppData as a backup solution for the compiler


text:
Q: What is the difference between MessagePack, Protobuf and JSON ? Can anyone tell me which one to use when I need to understand the difference between
- message pack
- protocol buffers
- JSON

A: Without having jumped in deeply into the matter I'd say the following:
All three are data formats that help you serialize information in a structured form so you can easily exchange it between software components (for example client and server).
While I'm not too familiar with the other two, JSON is currently a quasi-standard due to the fact that it is practically built into JavaScript - it's not a coincidence it is called JavaScript Object Notation. The other two seem to require additional libraries on both ends to create the required format.
So when to use which? Use JSON for REST services, for example if you want to publish your API or need different clients to access it. JSON seems to have the broadest acceptance.


text:
Q: How would you set a background on a grid css?

@media only screen and (min-width: 1024px) {
  * {
    margin: 0px;
    padding: 0px;
    border: 0px;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
  }

  ::-webkit-scrollbar {
    width: 0px;
    background: transparent;
  }

  body {
    min-height: 100%;
  }

  .gridFirstTP {
    display: grid;
    grid-template-columns: 1fr 2fr 1fr;
  }

  .First-display {
    height: 100%;
    width: 100%;
    background: rgb(254, 122, 255);
    background: linear-gradient(
      96deg,
      rgba(254, 122, 255, 1) 0%,
      rgba(55, 154, 237, 1) 67%
    );
  }

  .statistiquesRight {

    grid-column: 3/3;
    grid-row: 3/1;
    background: rgb(105, 177, 239);
    background: linear-gradient(
      21deg,
      rgba(105, 177, 239, 1) 0%,
      rgba(235, 119, 238, 1) 83%
    );
    box-shadow: -6px 0px 15px -4px;
  }
 }

-Les Statistiques-

Nombre d'article visités:

0

I have a projet website where I try stuff, and I'm trying to figure out something.
I have a css grid
 grid-column: 3/3;
 grid-row: 3/1;

so this element is taking the whole right side of the screen which is fine.
But for some reasons my div, I mean. the lengh of this element is not entirely rendered, for some reason it doesn't take the whole screen, the element is rendered but right as the middle on my webpage the element stop and it seems to display the default background of a webpage , if I understand it correctly I have to set a background, but I already have a div made for this :
.First-display {
    height: 100%;
    width: 100%;
    background: rgb(254, 122, 255);
    background: linear-gradient(
        96deg,
        rgba(254, 122, 255, 1) 0%,
        rgba(55, 154, 237, 1) 67%
    );
}

Is it because of the css grid, I have to add something, because the page is now behaving differently ?
Should I do it directly on my element ? or is this a bad idea. Thank you very much for your time <3

A: Height: 100% doesn't work exactly how you meant (for non-positioned elements). You need to set (min-)height: 100vh to .gridFirstTP element to use whole viewport height.

@media only screen and (min-width: 1024px) {
  * {
    margin: 0px;
    padding: 0px;
    border: 0px;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
  }

  ::-webkit-scrollbar {
    width: 0px;
    background: transparent;
  }

  body {
    min-height: 100%; /* you can remove it */
  }

  .gridFirstTP {
    display: grid;
    grid-template-columns: 1fr 2fr 1fr;
    height: 100vh;
  }

  .First-display {
    height: 100%; /* you can remove it */
    width: 100%;
    background: rgb(254, 122, 255);
    background: linear-gradient(
      96deg,
      rgba(254, 122, 255, 1) 0%,
      rgba(55, 154, 237, 1) 67%
    );
  }

  .statistiquesRight {

    grid-column: 3/3;
    grid-row: 3/1;
    background: rgb(105, 177, 239);
    background: linear-gradient(
      21deg,
      rgba(105, 177, 239, 1) 0%,
      rgba(235, 119, 238, 1) 83%
    );
    box-shadow: -6px 0px 15px -4px;
  }
 }

-Les Statistiques-

Nombre d'article visités:

0


text:
Q: execute jquery in asp.net How does this work?
protected void btnLogin_Click(object sender, EventArgs e)
    {
        //$.blockUI();
        //select from DB;
        //$.unblockUI();
    }

Thanks From Allllll

A: Simple, it doesn't work.  JavaScript code (hence, jQuery code) executes in the browser on the client-side.  .NET (ASP) code executes on the server-side.  They can interact in varying ways, but not in this way.  You can't write JavaScript code in a C# method as in your example.
What, specifically, are you trying to accomplish?  I see that you're trying to run JavaScript code in your C# method, sure, but for what purpose?  Usually one attempts this as a result of not fully understanding the page life cycle and how/when different things get executed.  What's the end goal here?

A: You should clarify your question. But if you want to know how to fetch server side data through javascript (ajax) using jquery, you should take a look at: http://api.jquery.com/jQuery.ajax/

A: Can you please clarify regarding the scenario in which you are using this?
As I can understand, when user clicks a button, you black out the screen, fetch some results from the DB and when you have to show stuff back on the UI, you remove the black out.. Right?
If that is so, then you can do like this -

*

*in the aspx page, use OnClientClick property of the button to specify a javascript function. Lets call it 'JSButtonClick'.

*In this, function you call $.blockUI();

*Also, make a ajax call to the server side. Use jQuery Ajax.
To call page behind you will have to define a public static function with the attribute [WebMethod] -> System.Web.Services.

*In the page behind function, do your DB call and stuff.

*Return the Db results serialised in JSON. Use JavascriptSerialiser (System.Web.Script.Serialization)

*Then in the success of ajax, you show your result and do $.unblockUI();

Its gonna be little problem if you want to update some GridView or something :)


text:
Q: Fooling a c++ compiler. Passing int instead of a cont int into function How can i pass an int into a function that is expecting a const int.
Or is there a way of modifying cont int value?
Edit: I Should have mentioned this earlier, i am using ccs c compiler that is used to program pic microcontroller. fprintf function takes constant stream as its first argument. It will only accept a constant int and throw a compilation error otherwise "Stream must be a constant in the valid range.".
Edit 2: Stream is a constant byte.

A: A top level const in a function parameter list is completely ignored, so
void foo(const int n);

is exactly the same as
void foo(int n);

So, you just pass an int.
The only difference is in the function definition, in which n is const in the first example, and mutable in the second. So this particular const can be seen as an implementation detail and should be avoided in a function declaration. For example, here we don't want to modify n inside of the function:
void foo(int n); // function declaration. No const, it wouldn't matter and might give the wrong impression

void foo(const int n)
{
  // implementation chooses not to modify n, the caller shouldn't care.
}

A: This requires no fooling. A function that expects an argument of type const int will happily accept an argument of type int.
The following code will work fine:
void MyFunction(const int value);

int foo = 5;
MyFunction(foo);

Because the argument is passed by value, the const is really rather meaningless. The only effect is has is to ensure that the function's local copy of the variable is not modified. The variable you pass to the function will never be modified, regardless of whether the argument  is taken as const or not.