text:
Q: Problem to connect to MySQL server (error #2002) in PHP I installed ZWAMP 1.0.7 (on Windows 7), but I'm having a weird problem. I can't connect to my MySQL server from any PHP script. If I try to use MySQL command line everything works fine but PHPMyAdmin retruns error #2002. I'm not sure whether it's important or not but MySQL server is not able to create socket file. I don't know what's the problem but I think everything is configured in my.cnf properly.
Do you have any ideas?

A: That PHPMyAdmin error relates to a problem connecting to MySQL over a socket, maybe it's been configured to connect over a UNIX socket which Windows 7 doesn't support? See if you can configure it in the config file to connect to 127.0.0.1 instead of localhost as this should force a TCP/IP connection instead of a socket.

A: The MySQL CLI uses a named pipe to connect to the MySQL Server.  PHP (almost always) uses IP networking to connect to the server.
Is the MySQL server listening for TCP/IP connections?  Is your firewall allowing connections to port 3306 (The default MySQL port)?
Try to telnet localhost 3306 to see if you get any prompting or feedback from the MySQL daemon.

A: I had a similar problem after I migrated my local testing environment from Windows XP to Windows 7. Specifying the IP address instead of localhost in the config.inc.php file of the PHPMyAdmin did the trick.


text:
Q: Android: Android Build failed with an exception: error: attribute tagetAlpha y error: attribute depensOn I'm something new on Android.
You see when I run the application I get the following error.

"AAPT: error: attribute depensOn not found"
  "AAPT: error: attribute tagetAlpha not found".

I'm trying to use dependent behavior or plain sight, Simple View Behavior for Android Coordinatorlayout.
First add the dependency as explained, here is my Gradle dependency file.
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.android.material:material:1.0.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'

//LIBRERIA PARA BOTTOM BAR
implementation 'com.roughike:bottom-bar:2.3.1'

//LIBRERIA PARA IMAGEN REDONDA
implementation 'de.hdodenhof:circleimageview:3.0.1'

//LIBRERIA PARA IMAGEN DE INTERNET
implementation 'com.squareup.picasso:picasso:2.5.2'

//LIBRERIA COMPORTAMIENTO DEPENDIENTE
implementation 'com.zoonref:simple-view-behavior:1.0' }

Depending on the use of this behavior, you can configure the effect using only the xml option.

*

*
*

*set the layout behavior to this library class app:layout_behavior="com.zoonref.SimpleViewBehavior". (Just what I do in my Circleimageview and Textview.)

*

*set the dependency view by specify resource id by app:dependsOn="@+id/{your view id}".

*

*set the type of dependency  app:dependType="{x,y,width,height}".

*

*set the dependency view target value according to the type you choose app:dependTargetXXX="{value}".

*

*And finally, set the target appearance that you want your view to animate to.

Just what I'm doing.
<de.hdodenhof.circleimageview.CircleImageView
    android:layout_width="@dimen/dimen_circleimageprofile"
    android:layout_height="@dimen/dimen_circleimageprofile"
    android:src="@drawable/image2"
    android:layout_gravity="center|top"
    android:layout_marginTop="@dimen/margintop_circleimageprofile"
    android:elevation="@dimen/elevation_circleimageprofile"
    app:layout_behavior="com.zoonref.SimpleViewBehavior"
    app:depensOn="@+id/appBarProfile"
    app:dependType="y"
    app:dependTargetY="@dimen/limitY_circleimage"
    app:targetX="@dimen/activity_vertical_margin"
    app:targetY="@dimen/margintoptoolbar_circleimageprofile"
    app:targetWidth="@dimen/width_circleimagetoolbar"
    app:targetHeight="@dimen/width_circleimagetoolbar" />

 <androidx.appcompat.widget.AppCompatTextView
    android:id="@+id/usernameToolbarProfile"
    android:layout_width="wrap_content"
    android:layout_height="281dp"
    android:layout_marginLeft="@dimen/marginleft_usernametoolbarprofile"
    android:layout_marginTop="@dimen/margintop_usernametoolbarprofile"
    android:alpha="0"
    android:elevation="@dimen/elevation_circleimageprofile"
    android:gravity="center_vertical"
    android:text="@string/username_card"
    android:textColor="@android:color/white"
    android:textSize="@dimen/textsize_usernametoolbarprofile"
    app:layout_behavior="com.zoonref.SimpleViewBehavior"
    app:depensOn="@+id/appBarProfile"
    app:dependType="y"
    app:dependTargetY="@dimen/limitY_appcompattext_usernametoolbarprofile"
  app:targetY="@dimen/margintoptargety_appcompattext_usernametoolbarprofile"
    app:tagetAlpha="1" />

But when I run the program, I get the following error:

Task :app:processDebugResources FAILED
  AGPBI: {"kind":"error","text":"Android resource linking failed","sources":[{"file":"C:\Users\sebas\AndroidStudioProjects\PlatzigramSena\app\src\main\res\layout\fragment_profile.xml","position":{"startLine":70}}],"original":"C:\Users\sebas\AndroidStudioProjects\PlatzigramSena\app\src\main\res\layout\fragment_profile.xml:71: AAPT: error: attribute depensOn (aka platzi.com:depensOn) not found.\n    ","tool":"AAPT"}
  AGPBI: {"kind":"error","text":"Android resource linking failed","sources":[{"file":"C:\Users\sebas\AndroidStudioProjects\PlatzigramSena\app\src\main\res\layout\fragment_profile.xml","position":{"startLine":101}}],"original":"C:\Users\sebas\AndroidStudioProjects\PlatzigramSena\app\src\main\res\layout\fragment_profile.xml:102: AAPT: error: attribute depensOn (aka platzi.com:depensOn) not found.\n    ","tool":"AAPT"}
  AGPBI: {"kind":"error","text":"Android resource linking failed","sources":[{"file":"C:\Users\sebas\AndroidStudioProjects\PlatzigramSena\app\src\main\res\layout\fragment_profile.xml","position":{"startLine":101}}],"original":"C:\Users\sebas\AndroidStudioProjects\PlatzigramSena\app\src\main\res\layout\fragment_profile.xml:102: AAPT: error: attribute tagetAlpha (aka platzi.com:tagetAlpha) not found.\n    ","tool":"AAPT"}
  FAILURE: Build failed with an exception.
  What went wrong: Execution failed for task ':app:processDebugResources'.
  A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
  Android resource linking failed
  C:\Users\sebas\AndroidStudioProjects\PlatzigramSena\app\src\main\res\layout\fragment_profile.xml:71: AAPT: error: attribute depensOn (aka platzi.com:depensOn) not found.
  C:\Users\sebas\AndroidStudioProjects\PlatzigramSena\app\src\main\res\layout\fragment_profile.xml:102: AAPT: error: attribute depensOn (aka platzi.com:depensOn) not found.
  C:\Users\sebas\AndroidStudioProjects\PlatzigramSena\app\src\main\res\layout\fragment_profile.xml:102: AAPT: error: attribute tagetAlpha (aka platzi.com:tagetAlpha) not found.

This is all my xml file:
<androidx.coordinatorlayout.widget.CoordinatorLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context="view.fragment.ProfileFragment"
  android:fitsSystemWindows="true">

<com.google.android.material.appbar.AppBarLayout
    android:id="@+id/appBarProfile"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay"
    android:background="@color/colorPrimary">

    <com.google.android.material.appbar.CollapsingToolbarLayout
        android:id="@+id/collapsingToolbarProfile"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true"
        app:statusBarScrim="@color/colorPrimary"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingTop="200dp"
            android:paddingBottom="20dp"
            android:layout_gravity="center|top"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            android:gravity="center">

            <TextView
                android:id="@+id/usernameProfile"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/username_card"
                android:textColor="@android:color/white"
                android:textSize="@dimen/textsize_usernameprofile"/>
        </LinearLayout>

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/pictureProfileRecycler"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

<!-- IMAGEN EN CIRCULO, LIBRERIA EN GRADLE -->
<de.hdodenhof.circleimageview.CircleImageView
    android:layout_width="@dimen/dimen_circleimageprofile"
    android:layout_height="@dimen/dimen_circleimageprofile"
    android:src="@drawable/image2"
    android:layout_gravity="center|top"
    android:layout_marginTop="@dimen/margintop_circleimageprofile"
    android:elevation="@dimen/elevation_circleimageprofile"
    app:layout_behavior="com.zoonref.SimpleViewBehavior"
    app:depensOn="@+id/appBarProfile"
    app:dependType="y"
    app:dependTargetY="@dimen/limitY_circleimage"
    app:targetX="@dimen/activity_vertical_margin"
    app:targetY="@dimen/margintoptoolbar_circleimageprofile"
    app:targetWidth="@dimen/width_circleimagetoolbar"
    app:targetHeight="@dimen/width_circleimagetoolbar" />
    <!-- android:elevation TENDRA QUE EVR CON LA ANIMACION QUE VAYA TENER LA IMAGEN-->
    <!-- app:layout_behavior EL COMPORTAMIENTO QUE QUEREMOS DARLE-->
    <!--
        pp:depensOn="@+id/appBarProfile"  -> ESTA IMAGEN ESTA DEPENDIENDO DE "@+id/appBarProfile"
        app:dependType="y"                -> TYPO DE DEPENDENCIA, EN QUE SENTIDO VA TENER DEPENDENCIA
        app:dependTargetY="-256dp"        -> LIMITE HASTA DODNE QUEREMOS QUE SE MUEVA LA IMAGEN, QUE SUBA LA IMAGEN
        app:targetX="16dp"                -> UNA VEZ QUE LA IMAGEN SE POSICIONO, CUANDO MARGEN QUEREMOS DEJAR
        app:targetY="-16dp"               -> CUANTO QUEREMOS QUE SUBA
        app:targetWidth="40dp"            -> DE QUE DIMENSION VA QUEDAR LA IMAGEN
    -->

<!-- TextView QUE DEPENDE DE LA IMAGEN, QUEDA AL LADO DE LA IMAGEN -->
<androidx.appcompat.widget.AppCompatTextView
    android:id="@+id/usernameToolbarProfile"
    android:layout_width="wrap_content"
    android:layout_height="281dp"
    android:layout_marginLeft="@dimen/marginleft_usernametoolbarprofile"
    android:layout_marginTop="@dimen/margintop_usernametoolbarprofile"
    android:alpha="0"
    android:elevation="@dimen/elevation_circleimageprofile"
    android:gravity="center_vertical"
    android:text="@string/username_card"
    android:textColor="@android:color/white"
    android:textSize="@dimen/textsize_usernametoolbarprofile"
    app:layout_behavior="com.zoonref.SimpleViewBehavior"
    app:depensOn="@+id/appBarProfile"
    app:dependType="y"
    app:dependTargetY="@dimen/limitY_appcompattext_usernametoolbarprofile"
    app:targetY="@dimen/margintoptargety_appcompattext_usernametoolbarprofile"
    app:tagetAlpha="1" /><!--CANTIDAD DE TRANSPARENCIA QUE QUEREMOS EN NUETSROS ELEMENTOS-->

Any help is much appreciated.

A: your error is syntax, the names of the attributes have been misspelled, where you have put:
application: DepensOn = "@ + id / appBarProfile" is "Depends on"; this is the attribute: app: dependOn = "@ + id / appBarProfile"
and the other the same:
app: tagetAlpha = "1" "is" targetAlpha "; this is the attribute: app: targetAlpha =" 1 ", then it will give you an error with the targetHeigth variable from liberia (de.hdodenhof: circleimageview) that you are, but you can change it by creating this variable in a resource and calling this variable.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How Does FM Get Around the Gabor Limit? The Gabor Limit states that it's impossible to simultaneously localize a signal in both frequency and time.  FM communication modulates the instantaneous frequency of the carrier in step with changes in the signal.  This suggests it's impossible to perfectly determine the instantaneous signal even in a theoretical channel with zero noise, or that one has to assume that the signal is changing slowly (band-limited).  How is this overcome in practice?  If demodulation requires the assumption of a band-limited signal, what is the maximum spectral efficiency of frequency modulation for a given input bandwidth?
EDIT:  To clarify, this is a theoretical question.  The Gabor Limit seems to imply that "instantaneous frequency" isn't well-defined if I understand it correctly.  I'm not sure I do, though.  The question boils down to:

*

*Do I understand the Gabor Limit correctly?  Is "intantaneous frequency" an unmeasurable quantity?

*If I do understand the Gabor Limit correctly, how does FM modulation and demodulation work in spite of it?  Is there a requirement that the demodulator assume that the signal being transmitted is band-limited even on a theoretical noise-free channel?

A:
This suggests it's impossible to perfectly determine the instantaneous signal even in a theoretical channel with zero noise

I'd turn this around and say it's impossible to instantaneously determine the signal.

one has to assume that the signal is changing slowly (band-limited). How is this overcome in practice?

In practice, our message signals are bandlimited, so this is not a difficulty. In fact, our message signals generally have much less bandwidth than the carrier.
To approach your theoretical question, is a band limit strictly required,  Imagine trying to modulate a 1 Hz carrier with a 1 MHz signal --- the result would be unusable. So in fact there must be some kind of limit.

A: Maybe this link will help you. In short, scientists made experiments and found out that human hearing easily beats Gabor limit, so, as a conclusion, our brain does not use Fourier transform to process sound waves, it is much more complex. So no need to worry about it)

A: Kind of a while ... but ...
Remember that FM takes any input signal, even perfectly bandlimited, and sends sidebands out to infinity.  AM, by contrast, takes a perfectly bandlimited input and keeps it bandlimited, just shifted up to the carrier in frequency space.  This illustrates the Gabor Limit as applied to the fact that it is the frequency state (not amplitude state) of the modulated signal that is being analyzed, and takes the instantaneous nature of the baseband signal and transfers it to infinity in the frequency domain.  There is no practical way to observe an infinite bandwidth signal, therefore, the demodulated signal must be distorted compared to the original baseband signal.  That uncertainty is arbitrarily reduced only by approaching a zero-noise infinite bandwidth analysis capability.  This contrasts against AM where zero-noise is all that is needed. (non-linear distortion and channel phase distortion are left as an exercise ... :-)

A: FM waveforms are very delocalized in frequency -- they have more than enough bandwidth to locate features in time with the required resolution.
The instantaneous frequency is a different thing entirely.  If you have a waveform: \$v(t) = cos(\phi(t))\$, then the instantaneous frequency is by definition \$f(t) = \dot{\phi}(t)\$.
To make this clear, lets ignore the FM part, and just consider a simple waveform:
\begin{equation}
x(t) = \left\{ \begin{array}{cc}
0 & \mbox{if }t < 0\\
\sin(2\pi t) & \mbox{if }0<t<1\\
0 & \mbox{if }t > 1
\end{array}\right.
\end{equation}
You can describe this waveform as having an instantaneous frequency of 1 over the interval [0,1], and an instantaneous frequency of 0 elsewhere.  That isn't a statement about the frequency spectrum.  It is actually a time domain description in disguise!  If I Fourier transform this waveform, I find that as expected it is not perfectly localized, but has some spread, represented as a sinc function centered at 1.


text:
Q: NuGet: 'StructureMap' already has a dependency defined for 'System.Collections.Concurrent' Running Visual Studio 2012 and latest version of NuGet, version  3.5.0.1996.
When I try to add StructureMap as a dependency to my class project, I get this error:
PM> install-package structuremap
install-package : 'StructureMap' already has a dependency defined for 'System.Collections.Concurrent'.
At line:1 char:1
+ install-package structuremap
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Install-Package], InvalidOperationException
    + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand

I have ran nuget update -self, but no dice.

A: Overcome by adding this line to packages.config in the project directory:
<?xml version="1.0" encoding="utf-8"?>
<packages>
  ...
  <package id="StructureMap" version="4.4.2" targetFramework="net45" />
</packages>

And running this:
nuget update .\packages.config

I'm still in the dark as to why this is happening or which NuGet Visual Studio is actually using.


text:
Q: Magento move js scripts in footer from header Google PageSpeed Insights tell me, what I'm need move my js scripts in footer from header and this is improve speed of load my site.
Questions:

*

*This is true?

*And if is true, how me do this in magento?

A: *

*That's not the best idea.

*Here you can find how to do it + cons and pros: Move all Javascript includes to before .


text:
Q: Bash: Two for loops at once? I am not sure how to do this at all.
I have two text files, FILE1 and FILE2.
I would like to run a for loop for each file at the same time and display the
contents next to each other.
For example,
for $i in $(cat FILE1); do echo $i; done
for $j in $(cat FILE2); do echo $j; done
I would like to combine these two commands, so I can run both files at the same time and have an output like $i $j

A: Solution 1
Use the paste command
paste FILE1 FILE2
Details for paste command
Another resource
Solution 2
You can do this if they have the same number of lines.
#!/bin/bash
t=$(cat FILE1 | wc -l)
for i in `seq 1 $t`;
do
    cat FILE1|head -n $i|tail -n 1
    cat FILE2|head -n $i|tail -n 1
done

You can extend it to what you want for unequal number of lines.

A: You shouldn't be using for loops at all; see Bash FAQ 001. Instead, use two read commands in a single while loop.
while IFS= read -r line1 && IFS= read -r line2 <&3; do
  printf '%s | %s\n' "$line1" "$line2"
done < FILE1 3< FILE2

Each read command reads from a separate file descriptor. In this version, the loop will exit when the shorter of the two files is exhausted.

A: There are two different questions being asked here.  Other answers address the question of how to display the contents of the file in 2 columns.  Running two loops simultaneously (which is the wrong way to address the first problem) can be done by running them each asynchronously:  for i in ${seqi?}; do ${cmdi?}; done & for j in ${seqj?}; do ${cmdj?}; done & wait
Although you could also implement paste -d ' ' file1 file2 with something like:
while read line_from_file1; p=$?; read line_from_file2 <&3 || test "$p" = 0; do
    echo "$line_from_file1" "$line_from_file2"
done < file1 3< file2

A: Another option, in bash v4+ is to read the two files into 2 arrays, then echo the array elements side-by-side:
# Load each file into its own array
readarray -t f1 < file1
readarray -t f2 < file2

# Print elements of both arrays side-by-side
for ((i=0;i<${#f1[@]};i++)) ; do echo ${f1[i]} ${f2[i]}; done

Or change the echo to printf if you want the columns to line up:
printf "%-20s %-20s\n" ${f1[i]} ${f2[i]}

I'm not suggesting you do this if your files are 100s of megabytes.


text:
Q: implement Instagram like flatlist(grid) in react native I have a simple Flatlist with 3 columns and now I need to make some of the tiles larger than the others, exactly like Instagram explore page. does Flatlist support this kind of layout?
big tiles on left or right side of the flatlist rows, and two simple rows in between
how can I make it?


text:
Q: Are multiple 'IF Statements' correct to use? I have a two column page design in WordPress.
I would like to display a different widget based upon the allocated WordPress category in the right hand side column using a functions command.
My question is this: is my approach the 'correct method?' I have 3 sets of arrays in an "IF Statement"
I should add that it works!
But - I want to make sure that it is correctly done:
function my_custom_sidebar_display( $sidebar ) {
    // Return a different sidebar for different categories
    if ( in_category(array('Apples','Pears','Peaches')) ) {
        return 'sidebar-fruit';
    }
    if ( in_category(array('potatoes','carrots','celery')) ) {
        return 'sidebar-vegetables';
    }
  }
    if ( in_category(array('monkeys','rhino','cheetah')) ) {
        return 'sidebar-animals';
    }
    // Return theme defined sidebar area
    else {
        return $sidebar;
    }
}
add_filter( 'ocean_get_sidebar', 'my_custom_sidebar_display' );

A: For readability later and for other developers, else if highlights that only one statement can be true, which otherwise is not 100% obvious.
Your function would change to something like this:
function my_custom_sidebar_display( $sidebar ) {
    // Return a different sidebar for different categories
    if ( in_category(array('Apples','Pears','Peaches')) ) {
        return 'sidebar-fruit';
    } else if ( in_category(array('potatoes','carrots','celery')) ) {
        return 'sidebar-vegetables';
    } else if ( in_category(array('monkeys','rhino','cheetah')) ) {
        return 'sidebar-animals';
    } else { // Return theme defined sidebar area
        return $sidebar;
    }
}

Normally, else if has the advantage of being more efficient. Imagine, as suggested in the comments, you do not return immediately, but save the value in an intermediary variable and return that variable in the end:
if ($letter === 'a') { $value = "1";}
if ($letter === 'b') { $value = "2";}
if ($letter === 'c') { $value = "3"; }
return $value;

That way all 3 conditions will be checked, even though you know that only one of them can be true.
(This is just an illustration, I also think it's fine to just return immediately instead of populating another variable)


text:
Q: Troubleshooting auto vectorize reason '1200' MSVC 2013 Ultimate w/ Update 4
Not understanding why I am getting this error on this seemingly simple example
info C5002: loop not vectorized due to reason '1200'
which is
1200 Loop contains loop-carried data dependences
I don't see how the iterations of the loop could interfere with each other.
__declspec( align( 16 ) ) class PhysicsSystem
{
public:
    static const int32_t MaxEntities = 65535;

    __declspec( align( 16 ) ) struct VectorizedXYZ
    {
        double      mX[ MaxEntities ];
        double      mY[ MaxEntities ];
        double      mZ[ MaxEntities ];

        VectorizedXYZ()
        {
            memset( mX, 0, sizeof( mX ) );
            memset( mY, 0, sizeof( mY ) );
            memset( mZ, 0, sizeof( mZ ) );
        }
    };

    void Update( double dt )
    {
        for ( int32_t i = 0; i < MaxEntities; ++i ) <== 1200
        {
            mTmp.mX[ i ] = mPos.mX[ i ] + mVel.mX[ i ] * dt;
            mTmp.mY[ i ] = mPos.mY[ i ] + mVel.mY[ i ] * dt;
            mTmp.mZ[ i ] = mPos.mZ[ i ] + mVel.mZ[ i ] * dt;
        }
    }

private:
    VectorizedXYZ   mTmp;
    VectorizedXYZ   mPos;
    VectorizedXYZ   mVel;
};

Edit: Judging by http://blogs.msdn.com/b/nativeconcurrency/archive/2012/05/08/auto-vectorizer-in-visual-studio-11-rules-for-loop-body.aspx this would seem to be an example of "Example 1 – Embarrassingly Parallel", but it acts like it thinks the arrays are unsafe from aliasing, which is puzzling to me.
Edit2: It would be nice if someone could share the reasons why the auto vectorization fails on such a seemingly simple example, but after tinkering with it for some time, I opted instead to take the reigns myself
void PhysicsSystem::Update( Real dt )
{
    const __m128d mdt = { dt, dt };

    // advance by 2 since we can do 2 at a time at double precision in __m128d
    for ( size_t i = 0; i < MaxEntities; i += 2 )
    {
        __m128d posX = _mm_load_pd( &mPos.mX[ i ] );
        __m128d posY = _mm_load_pd( &mPos.mY[ i ] );
        __m128d posZ = _mm_load_pd( &mPos.mZ[ i ] );

        __m128d velX = _mm_load_pd( &mVel.mX[ i ] );
        __m128d velY = _mm_load_pd( &mVel.mY[ i ] );
        __m128d velZ = _mm_load_pd( &mVel.mZ[ i ] );

        __m128d velFrameX = _mm_mul_pd( velX, mdt );
        __m128d velFrameY = _mm_mul_pd( velY, mdt );
        __m128d velFrameZ = _mm_mul_pd( velZ, mdt );

        _mm_store_pd( &mPos.mX[ i ], _mm_add_pd( posX, velFrameX ) );
        _mm_store_pd( &mPos.mY[ i ], _mm_add_pd( posX, velFrameY ) );
        _mm_store_pd( &mPos.mZ[ i ], _mm_add_pd( posX, velFrameZ ) );
    }
}

A: Not sure if your compiler supports it, but for enforcing some proper vectorisation, you can portably do that:
void PhysicsSystem::Update( double dt ) {
    double *tx=mTmp.mX, *ty=mTmp.mY, *tz=mTmp.mZ;
    double *px=mPos.mX, *py=mPos.mY, *pz=mPos.mZ;
    double *vx=mVel.mX, *vy=mVel.mY, *vz=mVel.mZ;
    #pragma omp simd aligned( tx, ty, tz, px, py, pz, vx, vy, vz )
    for ( int i = 0; i < MaxEntities; ++i ) {
        tx[ i ] = px[ i ] + vx[ i ] * dt;
        ty[ i ] = py[ i ] + vy[ i ] * dt;
        tz[ i ] = pz[ i ] + vz[ i ] * dt;
    }
}

You need then to enable the OpenMP support for the directive to be taken into account.


text:
Q: How to change deckgl prop value(extruded) on button click? I am plotting a hex layer in my app, and I want to modify extruded prop to true on click of a button. Is there a way to do it without plotting the layer again?
I have tried to replicate the required scenario in this fiddle
Below is the layer invocation code,
new H3HexagonLayer({
        id: 'h3-hexagon-layer',
        data: 'https://raw.githubusercontent.com/visgl/deck.gl-data/master/website/sf.h3cells.json',
        pickable: true,
        filled: true,
        extruded: false,
        elevationScale: 20,
        getLineColor: [0, 0, 0],
        getLineWidth: 1,
        getHexagon: d => d.hex,
        getFillColor: d => [255, (1 - d.count / 500) * 255, 0],
        getElevation: d => d.count
      }),


text:
Q: Swiftmailler send the same email twice I have a problem when i want send a email after a registration, i realy send a email but i send it twice and dont know why,
this is my code, i created a service who send mail.
my mailerHandler :
> public function emailUserPassword(UserInterface $user) {
>     $message = (new \Swift_Message('********'))
>         ->setContentType('text/html')
>         ->setFrom('********')
>         ->setTo($user->getEmail())
>         ->setBody($this->twig->render('Mail/password.html.twig', array(
>             'user' => $user,
>         )));
>     $this->swiftmailler->send($message); }

my controller :
if (isset($lastName, $firstName, $email, $roles, $stations)) {
            $user = new User();
            try {
                $user->setFirstName($firstName);
                $user->setLastName($lastName);
                $user->setEmail($email);
                $user->setPassword($passwordEncoder->encodePassword($user, $passWordGenerator));
                $user->setRoles($roles);
                $user->setStations($stations->getValues());

                $entityManager->persist($user);
                $entityManager->flush();

                $event = new UserEvent($user);
                $this->eventDispatcher->dispatch(SecurityEvents::REGISTRATION_SUCCESS, $event);

            } catch (UniqueConstraintViolationException $e) {
                $dataError = [
                    'status' => 'errorException',
                    'message' => 'existe'
                ];
                return new JsonResponse($dataError, 500
                );
            }

            $dataValid = [
                'type' => 'Validation',
                'valid' => 'L\'utilisateur ' . $user->getFullName() . ' a été créé.'
            ];

            return new JsonResponse($dataValid, 201);

and my event:
public function __construct(MailerHandler $mailerHandler
) {
    $this->mailerHandler = $mailerHandler;
}

public static function getSubscribedEvents()
{
    return [SecurityEvents::REGISTRATION_SUCCESS => 'onRegistrationSuccess'];
}

/**
 * @param UserEvent $event
 */
public function onRegistrationSuccess(UserEvent $event) {
    $user = $event->getUser();
    $this->mailerHandler->emailUserPassword($user);
}

I cant see why i send 2 emails


text:
Q: find missing number buckets I was wondering if there's a better way
I need to find missing number buckets. There's a set of number buckets in which the weights are distributed. I want to make sure that if the user misses a number somewhere, his attention is drawn to it and hes told that he's missing some buckets, otherwise his data for these will not show.
I already found each missing number but it shows a line for each and the user is only interested in the entire bucket.
so, I need the thing on the left to become the thing on the right. The FROM and TO is what I have to work with.
I have a feeling there's some beautiful VBA solution for this, something with arrays :)
Besides all this ugliness that I wrote, to get the original missing weight, I had to create a table with all weights from 0 to 1000. there has to be a better way
Sub sbMissingBuckets()

    Dim vrQDF As Object
    Dim vrSQL As String
    Dim vrQueryName As String
    Dim vrCountsMissingBuckets As Long

    sbWOff

    DoCmd.RunSQL "DELETE FROM MissingServicesShippingWeightBuckets"

    Dim vrRs1   As DAO.Recordset
    Dim vrServicesShippingWeightCollectionID As Long

    Set vrRs1 = CurrentDb.OpenRecordset("SELECT ServicesShippingWeightBuckets.ServicesShippingWeightCollectionID FROM ServicesShippingWeightBuckets GROUP BY ServicesShippingWeightBuckets.ServicesShippingWeightCollectionID " & _
                                        ", ServicesShippingWeightBuckets.IsMultiweight HAVING (((ServicesShippingWeightBuckets.IsMultiweight)=False));")

    Do Until vrRs1.EOF

        vrServicesShippingWeightCollectionID = vrRs1("ServicesShippingWeightCollectionID")

        vrSQL = "SELECT ServicesShippingWeightBuckets.ServicesShippingWeightCollectionID, AllWeights.Weight FROM ServicesShippingWeightBuckets " & _
                ", AllWeights GROUP BY ServicesShippingWeightBuckets.ServicesShippingWeightCollectionID, AllWeights.Weight, IIf([WeightFromInequalitySymbolID]=1,IIf([WeightToInequalitySymbolID]=3,[Weight]>[WeightFrom] " & _
                "AND [Weight]<[WeightTo]) & IIf([WeightToInequalitySymbolID]=4,[Weight]>[WeightFrom] AND [Weight]<=[WeightTo]) & IIf(IsNull([WeightToInequalitySymbolID]),[Weight]>[WeightFrom] " & _
                "AND [Weight]<=999999999)) & IIf([WeightFromInequalitySymbolID]=2,IIf([WeightToInequalitySymbolID]=3,[Weight]>=[WeightFrom] AND [Weight]<[WeightTo]) & IIf([WeightToInequalitySymbolID]=4,[Weight]>=[WeightFrom] " & _
                "AND [Weight]<=[WeightTo]) & IIf(IsNull([WeightToInequalitySymbolID]),[Weight]>=[WeightFrom] AND [Weight]<=999999999)), ServicesShippingWeightBuckets.IsMultiweight " & _
                "HAVING (((ServicesShippingWeightBuckets.ServicesShippingWeightCollectionID)=" & vrServicesShippingWeightCollectionID & ") AND ((IIf([WeightFromInequalitySymbolID]=1,IIf([WeightToInequalitySymbolID]=3,[Weight]>[WeightFrom] " & _
                "AND [Weight]<[WeightTo]) & IIf([WeightToInequalitySymbolID]=4,[Weight]>[WeightFrom] AND [Weight]<=[WeightTo]) & IIf(IsNull([WeightToInequalitySymbolID]),[Weight]>[WeightFrom] " & _
                "AND [Weight]<=999999999)) & IIf([WeightFromInequalitySymbolID]=2,IIf([WeightToInequalitySymbolID]=3,[Weight]>=[WeightFrom] AND [Weight]<[WeightTo]) & IIf([WeightToInequalitySymbolID]=4,[Weight]>=[WeightFrom] " & _
                "AND [Weight]<=[WeightTo]) & IIf(IsNull([WeightToInequalitySymbolID]),[Weight]>=[WeightFrom] AND [Weight]<=999999999)))=-1) " & _
                "AND ((ServicesShippingWeightBuckets.IsMultiweight)=False)) ORDER BY AllWeights.Weight;"

        vrQueryName = "qMissingBucketsBase"
        fnDeleteObjectIfExists "Query", vrQueryName
        Set vrQDF = CurrentDb.CreateQueryDef(vrQueryName, vrSQL)

        'count qMissingBuckets
        vrCountsMissingBuckets = dCount("cTo", "qMissingBuckets")
        'if 0 do nothing
        If vrCountsMissingBuckets > 0 Then
            'loop thoruhg and onl add records to the table if the diff is more than 1
            DoCmd.OpenQuery "qMissingBuckets2"
            DoCmd.OpenQuery "qMissingBuckets3"

            Dim vrRs2   As DAO.Recordset
            Dim vrFrom As Long
            Dim vrTo As Long
            Dim vrDiff As Long
            Dim vrPlaceholder As Boolean
            Dim vrFromPlaceholder As Variant

            Set vrRs2 = CurrentDb.OpenRecordset("mtT")

            Do Until vrRs2.EOF

                vrFrom = vrRs2("cFrom")
                vrTo = vrRs2("cTo")
                vrDiff = vrRs2("cDiff")

                If vrDiff > 1 Then
                    If vrPlaceholder = False Then
                        If vrDiff < 99999 Then
                            DoCmd.RunSQL "INSERT INTO MissingServicesShippingWeightBuckets (ServicesShippingWeightCollectionID, ServicesShippingWeightBucket, WeightFromInequalitySymbolID, WeightFrom, WeightToInequalitySymbolID, WeightTo) SELECT " & vrServicesShippingWeightCollectionID & _
                                         ", '>=" & vrFrom & " and <" & vrTo & "', 2 as WeightFromInequalitySymbolID, " & vrFrom & " as WeightFrom, 3 as WeightToInequalitySymbolID, " & vrTo & " as WeightTo"
                        End If
                    Else
                        DoCmd.RunSQL "INSERT INTO MissingServicesShippingWeightBuckets (ServicesShippingWeightCollectionID, ServicesShippingWeightBucket, WeightFromInequalitySymbolID, WeightFrom, WeightToInequalitySymbolID, WeightTo) SELECT " & vrServicesShippingWeightCollectionID & _
                                     ", '>=" & vrFromPlaceholder & " and <" & vrTo & "', 2 as WeightFromInequalitySymbolID, " & vrFromPlaceholder & " as WeightFrom, 3 as WeightToInequalitySymbolID, " & vrTo & " as WeightTo"
                        vrPlaceholder = False
                        vrFromPlaceholder = Null
                    End If
                ElseIf vrDiff = 1 Then
                    If vrPlaceholder = False Then
                        vrFromPlaceholder = vrFrom
                        vrPlaceholder = True
                    End If
                End If

                vrRs2.MoveNext
            Loop

            vrRs2.Close
            Set vrRs2 = Nothing

        End If

        vrRs1.MoveNext
    Loop

    vrRs1.Close
    Set vrRs1 = Nothing

    sbWOn
End Sub


text:
Q: Get message from SMS content URI where message is not delivered I am developing a system application in which I have to send a message from device programmatically and delete the message after sending.Everything working properly except below point
If the message sent successfully then I am able to find it from SMS content URI but if the message failures then I am not getting it from Content URI.I am using below code for deleting message
 public void deleteTheMessage(Context context, String value) {
    Uri uri = Uri.parse("content://sms");
    Cursor c = context.getApplicationContext().getContentResolver().query(uri, null, null, null, null);
    try {

        if (c != null) {
            Log.i("deleteTheMessage-->", "  count : " + c.getCount());
        } else {
            Log.i("deleteTheMessage-->", " c null: ");
        }
        while (c.moveToNext()) {
            try {
                if (c != null && c.moveToFirst()) {
                    do {
                        String address = c.getString(2);
                        String id = c.getString(0);
                        long threadId = c.getLong(1);
                        Log.i("deleteTheMessage-->", " address: " + address + " body: " + "" + " threadId: " + threadId + " id: " + id);
                        try {
                            if (address.contains(value)) {
                                int deltedrowcount = context.getApplicationContext().getContentResolver().delete(uri, "thread_id = " + threadId, null);
                                if (deltedrowcount != 0) {
                                    Log.i("deleteTheMessage-->", " SMS has Deleted successfully " + deltedrowcount);
                                }
                                Log.i("deleteTheMessage-->", " body  " + address);
                            }
                        } catch (Exception e) {
                            Log.i("deleteTheMessage-->", "SmsWriteOpUtil Exception in deleting SMS  " + e.getMessage());
                        }

                    } while (c.moveToNext());
                }
            } catch (Exception e) {
                Log.i("deleteTheMessage-->", "c.moveToNext() Exception in deleting SMS" + e.getMessage());
            }
        }
    } catch (Exception e) {
        Log.i("deleteTheMessage-->", " try Exception in deleting SMS: " + e.getMessage());
    } finally {
        c.close();
    }
}

I want to delete message address by 11345 Please see below screenshot.

A: Finally, I got the solution to delete the undelivered message using below code.
        long threadId = Telephony.Threads.getOrCreateThreadId(context, phoneNumber);
        LogMgr.i("deleteByThreadID-->" + "  threadId : " + threadId);
        int threadIdDeletedCount = context.getContentResolver().delete(Uri.parse("content://sms"), "thread_id =?", new String[]{String.valueOf(threadId)});
        LogMgr.i("deleteByThreadID: --> threadIdDeletedCount " + threadIdDeletedCount);

phoneNumber this the number on which message was sent.


text:
Q: In sbt, how can I publish to a resolver defined in an external ivy settings file? We have numerous ant-based projects which depend on a single ivysettings.xml where our ivy resolvers are defined.  I'm creating a new sbt-based project, and according to the DRY principle, I'd like for sbt to also depend on this same ivysettings.xml file (rather than attempting to re-defining the resolvers within the sbt script).  This turned out to be really easy, using externalIvySettings() -- at least, for resolving dependencies.
However, we also need to publish to one of the resolvers defined in the file.  In ant, this is really easy:  <ivy:publish resolver="..." />", however with sbt I'm stumped.  Sbt has a publishTo setting which can be used to define a resolver to publish to, but I don't want to define a new resolver.  Instead, I want to pull a resolver out of the settings loaded by externalIvySettings(), and pass this to publishTo.  Is this possible?
Edit:
Here is the ivysettings.xml file as requested.  We want to publish to the "modules" resolver.
<ivysettings>

  <properties file="${ivy.settings.dir}/ivysettings.properties" />

  <settings defaultResolver="default" defaultResolveMode="dynamic"/>

  <property name="x1.resolver"           value="x1-fs" override="false"/>
  <property name="x2.resolver"           value="x2-fs" override="false"/>

  <property name="x1.ivy.pattern"        value="[organisation]/[module]/[revision]/[type]s/[artifact].[ext]" override="true"/>
  <property name="x1.artifact.pattern"   value="[organisation]/[module]/[revision]/[type]s/[artifact].[ext]" override="true"/>

  <property name="x2.ivy.pattern"        value="[organisation]/[module]/[revision]/[type]s/[artifact].[ext]" override="true"/>
  <property name="x2.artifact.pattern"   value="[organisation]/[module]/[revision]/[type]s/[artifact].[ext]" override="true"/>

  <property name="local.root"             value="${ivy.default.ivy.user.dir}/x1-local" override="true"/>
  <property name="local.ivy.pattern"      value="[organisation]/[module]/[revision]/[type]s/[artifact].[ext]" override="true"/>
  <property name="local.artifact.pattern" value="[organisation]/[module]/[revision]/[type]s/[artifact].[ext]" override="true"/>

  <property name="modules.root"             value="${ivy.settings.dir}/ivy/published" override="true"/>
  <property name="modules.ivy.pattern"      value="[organisation]/[module]/[revision]/[type]s/[artifact].[ext]" override="true"/>
  <property name="modules.artifact.pattern" value="[organisation]/[module]/[revision]/[type]s/[artifact].[ext]" override="true"/>

  <!-- some default values for paths to the x2 and x1 repositories; these should be overridden in ivysettings.properties -->
  <property name="x2.fs.root" value="${ivy.settings.dir}/ivy/x2root" override="false"/>
  <property name="x1.fs.root" value="${ivy.settings.dir}/ivy/x1root" override="false"/>

  <property name="ivy.cache.dir" value="${ivy.settings.dir}/ivy/cache"/>

  <caches defaultCacheDir="${ivy.cache.dir}"/>

  <resolvers>
    <filesystem name="x1-fs">
      <ivy pattern="${x1.fs.root}/${x1.ivy.pattern}" />
      <artifact pattern="${x1.fs.root}/${x1.artifact.pattern}" />
    </filesystem>

    <filesystem name="x2-fs">
      <ivy pattern="${x2.fs.root}/${x2.ivy.pattern}" />
      <artifact pattern="${x2.fs.root}/${x2.artifact.pattern}" />
    </filesystem>

    <chain name="x1">
     <resolver ref="${x1.resolver}"/>
    </chain>

    <chain name="x2">
     <resolver ref="${x2.resolver}"/>
    </chain>

    <filesystem name="local">
      <ivy pattern="${local.root}/${local.ivy.pattern}" />
      <artifact pattern="${local.root}/${local.artifact.pattern}" />
    </filesystem>

    <filesystem name="modules" checkmodified="true" changingPattern="*" changingMatcher="glob">
      <ivy pattern="${modules.root}/${modules.ivy.pattern}" />
      <artifact pattern="${modules.root}/${modules.artifact.pattern}" />
    </filesystem>

    <chain name="main" dual="true">
      <resolver ref="modules"/>
      <resolver ref="x1"/>
      <resolver ref="x2"/>
    </chain>

    <chain name="default" returnFirst="true">
      <resolver ref="local"/>
      <resolver ref="main"/>
    </chain>

  </resolvers>

</ivysettings>

A: found the answer in this link https://github.com/sbt/sbt/issues/1999
But the answer is to just reference the resolver by name. In your situation it would be
publishTo := Some(Resolver.file("modules"))

since you want to publish using the "modules" resolver


text:
Q: Observable not reacting to queue changed on different thread I have the following code:
static void Main()
    {
        var holderQueue = new ConcurrentQueue<int>(GetInitialElements());

        Action<ConcurrentQueue<int>> addToQueueAction = AddToQueue;
        var observableQueue = holderQueue.ToObservable();
        IScheduler newThreadScheduler = new NewThreadScheduler();

        IObservable<Timestamped<int>> myQueueTimestamped = observableQueue.Timestamp();

        var bufferedTimestampedQueue = myQueueTimestamped.Buffer(TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(3), newThreadScheduler);

        var t = new TaskFactory();
        t.StartNew(() => addToQueueAction(holderQueue));

        using(bufferedTimestampedQueue.SubscribeOn(newThreadScheduler).Subscribe(currentQueue =>
        {
            Console.WriteLine("buffer time elapsed, current queue contents is: {0} items.", currentQueue.Count);
            foreach(var item in currentQueue)
                Console.WriteLine("item {0} at {1}", item.Value, item.Timestamp);

            Console.WriteLine("holderqueue has: {0}", currentQueue.Count);
        }))
        {
            Console.WriteLine("started observing queue");

            Console.ReadLine();
        }
    }

    private static void AddToQueue(ConcurrentQueue<int> concurrentQueue)
    {
        while(true)
        {
            var x = new Random().Next(1, 10);
            concurrentQueue.Enqueue(x);
            Console.WriteLine("added {0}", x);
            Console.WriteLine("crtcount is: {0}", concurrentQueue.Count);
            Thread.Sleep(1000);
        }
    }

    private static IEnumerable<int> GetInitialElements()
    {
        var random = new Random();
        var items = new List<int>();
        for (int i = 0; i < 10; i++)
            items.Add(random.Next(1, 10));

        return items;
    }

The intention is as follows:
The holderQueue object is populated initially with a few elements (GetInitialElements) then changed on a different thread with further elements (by the method AddToQueue), and the observable is supposed to detect this change, and react accordingly when its time is elapsed (so each 3 seconds) by executing the method in its subscription.
So in short, what I expect is to have the code in the Subscribe body to execute each 3 seconds, and show me the changes in the queue (which was changed on a different thread). Instead the Subscribe body executes only once. Why?
Thanks

A: The ToObservable method takes an IEnumerable<T> and converts it into an observable. As a result, it will take your concurrent queue and enumerate it immediately, running through all available items. The fact that you later modify the queue to add additional items has no impact on the already enumerated IEnumerable<T> that is returned from the concurrent queue's GetEnumerator() implementation.

A: As per David Pfeffer's answer, just using .ToObserverable() will not get you what you need.
However, when I look at your code, I see several things:

*

*You are using a NewThreadScheduler

*You are adding to the queue via a Task

*You are using a ConcurrentQueue<T>
I think you can achieve what you set out to do here if you just change a few things. First I think you are actually looking for a BlockingCollection<T>. I know it seems unlikely, but you can get it to act just like a thread-safe queue.
Next you are already dedicating a thread to doing something with the NewThreadScheduler, why not make that do the polling/pulling from the queue?
Lastly, if you use the BlockingCollection<T>.GetConsumingEnumerable(CancellationToken) method, you actually can go back and use that .ToObservable() method!
So lets look at the rewritten code:
static void Main()
{
    //The processing thread. I try to set the the thread name as these tend to be long lived. This helps logs and debugging.
    IScheduler newThreadScheduler = new NewThreadScheduler(ts=>{
        var t =  new Thread(ts);
        t.Name = "QueueReader";
        t.IsBackground = true;
        return t;
    });

    //Provide the ability to cancel our work
    var cts = new CancellationTokenSource();

    //Use a BlockingCollection<T> instead of a ConcurrentQueue<T>
    var holderQueue = new BlockingCollection<int>();
    foreach (var element in GetInitialElements())
    {
        holderQueue.Add(element);
    }

    //The Action that periodically adds items to the queue. Now has cancellation support
    Action<BlockingCollection<int>,CancellationToken> addToQueueAction = AddToQueue;
    var tf = new TaskFactory();
    tf.StartNew(() => addToQueueAction(holderQueue, cts.Token));

    //Get a consuming enumerable. MoveNext on this will remove the item from the BlockingCollection<T> effectively making it a queue.
    //  Calling MoveNext on an empty queue will block until cancelled or an item is added.
    var consumingEnumerable = holderQueue.GetConsumingEnumerable(cts.Token);

    //Now we can make this Observable, as the underlying IEnumerbale<T> is a blocking consumer.
    //  Run on the QueueReader/newThreadScheduler thread.
    //  Use CancelationToken instead of IDisposable for single method of cancellation.
    consumingEnumerable.ToObservable(newThreadScheduler)
        .Timestamp()
        .Buffer(TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(3), newThreadScheduler)
        .Subscribe(buffer =>
            {
                Console.WriteLine("buffer time elapsed, current queue contents is: {0} items.", buffer.Count);
                foreach(var item in buffer)
                    Console.WriteLine("item {0} at {1}", item.Value, item.Timestamp);

                Console.WriteLine("holderqueue has: {0}", holderQueue.Count);
            },
            cts.Token);

    Console.WriteLine("started observing queue");

    //Run until [Enter] is pressed by user.
    Console.ReadLine();

    //Cancel the production of values, the wait on the consuming enumerable and the subscription.
    cts.Cancel();
    Console.WriteLine("Cancelled");
}

private static void AddToQueue(BlockingCollection<int> input, CancellationToken cancellationToken)
{
    while(!cancellationToken.IsCancellationRequested)
    {
        var x = new Random().Next(1, 10);
        input.Add(x);
        Console.WriteLine("added '{0}'. Count={1}", x, input.Count);
        Thread.Sleep(1000);
    }
}

private static IEnumerable<int> GetInitialElements()
{
    var random = new Random();
    var items = new List<int>();
    for (int i = 0; i < 10; i++)
        items.Add(random.Next(1, 10));

    return items;
}

Now I think you will get the results you were expecting:
added '9'. Count=11
started observing queue
added '4'. Count=1
added '8'. Count=1
added '3'. Count=1
buffer time elapsed, current queue contents is: 14 items.
item 9 at 25/01/2015 22:25:35 +00:00
item 5 at 25/01/2015 22:25:35 +00:00
item 5 at 25/01/2015 22:25:35 +00:00
item 9 at 25/01/2015 22:25:35 +00:00
item 7 at 25/01/2015 22:25:35 +00:00
item 6 at 25/01/2015 22:25:35 +00:00
item 2 at 25/01/2015 22:25:35 +00:00
item 2 at 25/01/2015 22:25:35 +00:00
item 9 at 25/01/2015 22:25:35 +00:00
item 3 at 25/01/2015 22:25:35 +00:00
item 9 at 25/01/2015 22:25:35 +00:00
item 4 at 25/01/2015 22:25:36 +00:00
item 8 at 25/01/2015 22:25:37 +00:00
item 3 at 25/01/2015 22:25:38 +00:00
holderqueue has: 0
added '7'. Count=1
added '2'. Count=1
added '5'. Count=1
buffer time elapsed, current queue contents is: 3 items.
item 7 at 25/01/2015 22:25:39 +00:00
item 2 at 25/01/2015 22:25:40 +00:00
item 5 at 25/01/2015 22:25:41 +00:00
holderqueue has: 0
Cancelled


text:
Q: Foreach loop group by XML element value I want to group them by agent
XML structured as follows
<library>
    <document>
        <ProductName>somename1</ProductName>
        <productAgent>Agent-01</productAgent>
        <productType>Goods</productType>
    </document>
        <ProductName>somename3</ProductName>
        <productAgent>Agent-02</productAgent>
        <productType>Services</productType>
    </document>
    ......
</library>

Expecting Output

Agent-01(productAgent)

somename1 - Goods

Agent-02(productAgent)

somename3 - Services

somename6 - Goods

What I tried

Agent-01(productAgent)

            <?php foreach($xml->document as $item){
                if ($item->productAgent == 'Agent-01' ) {
                    echo '
'.$item->ProductName.'-'.$item->ProductType.'
';
                }
            }
            ?>

Agent-02(productAgent)

            <?php foreach($xml->document as $item){
                if ($item->productAgent == 'Agent-02' ) {
                    echo '
'.$item->ProductName.'-'.$item->ProductType.'
';
                }
            }
            ?>

Problem
I have to modify my code every time the agent name change. My code doesn't seem to be a good solution when the number of agent increase.

A: Collect all data to array, where key is agent and value is array of products:
<?php
$values = [];
foreach($xml->document as $item){
    $agent = (string) $item->productAgent;
    if (!isset($values[$agent])) {
        $values[$agent] = [];
    }

    $values[$agent][] = (string) $item->ProductName;
    // add other tags as you need:
    //$values[$agent][] = [
    //    'name' => (string) $item->ProductName,
    //    'type' => (string) $item->ProductType,
    //];
}

// Then iterate over this array and output as needed
foreach ($values as $agent => $products) {
    echo $agent . ': ' . implode(', ', $products);
    // iterate over $products and output what you need
}?>

A: A more complete example with the output...
//  Build list of product names for each agent
$agents = [];
foreach ( $xml->document as $document ) {
    $agents [(string)$document->productAgent][] = (string)$document->ProductName;
}

?>

    <?php // Loop over the agents
           foreach($agents as $name => $agent){  ?>

<?php echo $name; ?>

            <?php // Loop over the the products for the agent
                  foreach($agent as $item){
                echo '
'.$item.'
';
            }
            ?>

    <?php } ?>


text:
Q: screenshot and printscreen is not working in eclipse I am unable to take screenshot / printscreen of my eclipse menu.
when I try to take screen shot of the eclipse menu file -> new -> Android project my print screen is not working.
when any of the menu is in clicked mode(i.e file,edit, run, ...)
Note: I am using ubuntu linux

A: Yes, any keypress will dismiss a menu.
General workaround to this issue is to delay the actual screenshot action.
In Gnome you can issue this command in command line:
$ gnome-panel-screenshot --window --delay 5
and it will take a screenshot after 5 seconds delay - of the window that is current at that time


text:
Q: Why does is the Boolean in this statement breaking the code? Very new to Python and don't understand the logic behind this not working.
I am trying to loop my main function if an input matches one of two strings, the code works just fine without the or (if i take everything between the "y" and the ending : away.
    main()
    if input("Do you want to play again?").strip().casefold() != "y" or "yes":
        break


text:
Q: Best way to threading when with/as is needed (python, pyqt) I'm trying to run a worker class using a qthread. I can do this without a problem if the worker is instantiated with workerObject = workerClass(). How can I do this if the worker class needs to execute always the exit?
Below is a sample code that tries to do that. Unfortunately, by running this, the exit function doesn't get executed and most probably this is because the thread is not aware about the with/as statement
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import QThread, QObject, pyqtSignal, pyqtSlot
import sys
import time

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName(_fromUtf8("Dialog"))
        Dialog.resize(400, 284)
        self.textEdit = QtGui.QTextEdit(Dialog)
        self.textEdit.setGeometry(QtCore.QRect(20, 20, 361, 191))
        self.textEdit.setObjectName(_fromUtf8("textEdit"))
        self.pushButton = QtGui.QPushButton(Dialog)
        self.pushButton.setGeometry(QtCore.QRect(170, 250, 75, 23))
        self.pushButton.setObjectName(_fromUtf8("pushButton"))

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))
        self.pushButton.setText(_translate("Dialog", "Print", None))

class UI_MainWindow(QtGui.QMainWindow, Ui_Dialog):
    def __init__(self, parent=None):
        super(UI_MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.pushButton.clicked.connect(self.run)

    def run(self):
        self.t = QThread()
        self.x = None
        with worker() as self.x:
            self.x.signal.connect(self.write)
            self.x.moveToThread(t)
            t.started.connect(self.x.run)
            t.start()

    @pyqtSlot(str)
    def write(self, text):
        self.textEdit.append("Running")
        qtObject.processEvents()

class worker(QObject):
    signal = pyqtSignal(str)

    def __init__(self, parent = None):
        super(worker, self).__init__(parent)

    def __enter__(self):
        return self

    def run(self):
        self.signal.emit("Running")
        time.wait(5)
        raise Exception

    def __exit__(self, exc_type, exc_value, traceback):
        if exc_type:
            self.signal.emit("Exception")

def main(qtObject, guiObj):
    guiObj.show()
    qtObject.exec_()
    qtObject.processEvents()

qtObject = QtGui.QApplication(sys.argv)
guiObj = UI_MainWindow()
main(qtObject, guiObj)

LE: The context involves the need to print in a QTextEdit window any failure message coming from the worker class. Any exception raised during the worker class execution is handled in its exit function so that whatever wrong happens, the script to end gracefully providing the user with meaningful information and instructions.

A: The __exit__ function does get executed, the issue is that due to the non-blocking nature of threads, the with construct immediately terminates (calling worker.__exit__) before the worker "completes" and raises the exception.
One way to achieve what you want is to surround the code in worker.run() with a try/except statement to catch any unhandled exceptions and perform any cleanup or emitting of signals.
def run(self):
    try:
        self.signal.emit("Running")
        time.sleep(5)
        raise Exception
    except:
        self.signal.emit("Exception")

A: Starting from user3419537 solution, I've come in the end with the following solution. A second signal (statusSignal) is used to carry back to the main class all the exception related information so that the exit function can be called.
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import QThread, QObject, pyqtSignal, pyqtSlot
import sys
import time

class err(Exception):
    def __init__(self, *args):
        self.args = [a for a in args]

mainThread = QtCore.QThread.currentThread()

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName(_fromUtf8("Dialog"))
        Dialog.resize(400, 284)
        self.textEdit = QtGui.QTextEdit(Dialog)
        self.textEdit.setGeometry(QtCore.QRect(20, 20, 361, 191))
        self.textEdit.setObjectName(_fromUtf8("textEdit"))
        self.pushButton = QtGui.QPushButton(Dialog)
        self.pushButton.setGeometry(QtCore.QRect(170, 250, 75, 23))
        self.pushButton.setObjectName(_fromUtf8("pushButton"))

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))
        self.pushButton.setText(_translate("Dialog", "Print", None))

class UI_MainWindow(QtGui.QMainWindow, Ui_Dialog):
    def __init__(self, parent=None):
        super(UI_MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.pushButton.clicked.connect(self.run)

    def run(self):
        self.t = QThread()
        self.x = worker()
        self.x.signal.connect(self.write)
        self.x.statusSignal.connect(self.runExit)
        self.x.moveToThread(self.t)
        self.t.started.connect(self.x.run)
        self.t.start()

    @pyqtSlot(str)
    def write(self, text):
        self.textEdit.append(text)
        qtObject.processEvents()

    @pyqtSlot(object, object, object)
    def runExit(self, exc_type, exc_value, exc_traceback):
        self.t2 = QThread()
        self.x.moveToThread(self.t2)
        self.t2.started.connect(lambda: self.x.__exit__(exc_type, exc_value, exc_traceback))
        self.t2.start()

class worker(QObject):
    signal = pyqtSignal(str)
    statusSignal = pyqtSignal(object, object, object)

    def __init__(self, parent = None):
        super(worker, self).__init__(parent)

    def run(self):
        try:
            self.signal.emit("Run")
            time.sleep(2)
            self.moveToThread(mainThread)
            raise err("err message")
        except err:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            self.statusSignal.emit(exc_type, exc_value, exc_traceback)

    def __exit__(self, exc_type, exc_value, traceback):
        if exc_type:
            self.signal.emit(exc_value.args[0])

def main(qtObject, guiObj):
    guiObj.show()
    qtObject.exec_()
    qtObject.processEvents()

qtObject = QtGui.QApplication(sys.argv)
guiObj = UI_MainWindow()
main(qtObject, guiObj)

Most probably there are still some tweaks to be made to the code, but as it stands at the moment, it works perfectly.


text:
Q: Where should I declare the server url for Rhodes Appl I have been using the server url at many places over the application. If I would need to change it then I need to go all over the place I have used to change it.
Where should be the best place to declare the url so it can be used every where and not much change is required?

A: You can declare the server URL in the RhoConfig.xml file as a property. And later, retrive the property value during the API calls.
So to delare the property in RhoConfig.xml, you need to add it as such,
   start_path = '/app'
   options_path = '/app/Settings'
   server_URL = 'http://somedomain.com/API/'

Now in the Controller to get the value of the server_URL, you need to call the Rho::RhoConfig class and use it as like below,
   if Rho::RhoConfig.exists?('server_URL')
       $server_url = Rho::RhoConfig.server_URL
   end

This makes the url to change on one place if required.


text:
Q: Scrape data from Statista site Python I'm trying to scrape the data behind this graph (when hovering over the bars (e.g. 2018, 78.16).
Option 1: Python & BS: I'm familiar with these libraries, however when inspecting I can't find the data
Option 2: Look for JSON file: Again, no luck. There does not seem to be a JSON datafile
Does anyone of you have an idea? (sorry for the open question, but the above two options are the only ones I'm aware of.
https://www.statista.com/statistics/264911/dells-net-revenue-since-1996/
Many thanks!

A: Looking at the page source, it turns out that the data in that graph is contained in a table element somewhere on the page. You can get the data you're looking for using Selenium and BeautifulSoup as below:
from bs4 import BeautifulSoup
from selenium import webdriver

driver = webdriver.Firefox()
driver.get("https://www.statista.com/statistics/264911/dells-net-revenue-since-1996/")

html = driver.page_source
soup = BeautifulSoup(html, "lxml")

chart = soup.find("tbody", {"role" : "alert"})
children = chart.find_all("tr")

data = []
for tag in children:
    data_tuple = (tag.text[:3],tag.text[3:])
    data.append(data_tuple)

print(data)

This produces the following output:
[("'96", '5.3'), ("'97", '7.8'), ("'98", '12.3'), ("'99", '18.2'), ("'00", '25.3'), ("'01", '31.9'), ("'02", '31.2'), ("'03", '35.3'), ("'04", '41.3'), ("'05", '49.1'), ("'06", '55.8'), ("'07", '57.4'), ("'08", '61.1'), ("'09", '61.1'), ("'10", '52.9'), ("'11", '61.5'), ("'12", '62.1'), ("'13", '56.9'), ("'14", '55.58'), ("'15", '54.1'), ("'16", '50.9'), ("'17", '61.6'), ("'18", '78.66')]

If you are still interested in scraping the tooltips from the chart, you might have to look at something like this where you'd have to get it to click on each of the elements so that the popup tooltip can be generated, then scrape the information as it's displayed.


text:
Q: Finding substring in string with forward slash in Powershell scripts I am trying to find sub-string in string using powershell script. Actually, I am reading a file line by line which contains thousands of paths. I am filtering each path coming from file. Path filters are finding sub-string in path.
But Contains function returns false when sub-string is Sroot or TRoot.
Following is my sample code.
foreach($line in Get-Content $filePath)
{
    # Line can contain
    # $line = $/Patil/TEMP/PRoot/Digvijay/Patil/1.png
    # $line = $/Patil/TEMP/SRoot/Digvijay/Patil/2.png
    # $line = $/Patil/TEMP/TRoot/Digvijay/Patil/3.png
    if($line)
    {
        if($line.Contains('RRoot')) # This condition works properly
        {
            # Process Rroot here
        }
        if($line.Contains('SRoot')) # This condition fails.
        {
            # Process SRoot here
        }
        if($line.Contains('TRoot')) # This condition fails.
        {
            # Process TRoot here
        }
    }
 }

Input file is like:
$/Patil/TEMP/PRoot/Digvijay/Patil/1.png
$/Patil/TEMP/SRoot/Digvijay/Patil/2.png
$/Patil/TEMP/TRoot/Digvijay/Patil/3.png
$/Patil/TEMP/WRoot/Digvijay/Patil/3.png

A: Instead of using multiple IFs

*

*you could use a switch controlled by the letter in front of Root determined by

*a RegEX storing the matched char in a capture group () recallable via $Matches[1]:

$filePath = '.\files.txt'
Get-Content $filePath | Where-Object {$_ -match '([PST])Root'} | ForEach-Object {
    $line = $_
    switch ($Matches[1]){
        'P' {'{0}={1}' -f $_,$line} # code in {} to execute on P
        'S' {'{0}={1}' -f $_,$line} # code in {} to execute on S
        'T' {'{0}={1}' -f $_,$line} # code in {} to execute on T
    }
}

Sample output:
P=P:/TEMP/PRoot/Digvijay/Patil/1.png
S=S:/TEMP/SRoot/Digvijay/Patil/2.png
T=T:/TEMP/TRoot/Digvijay/Patil/3.png

PS: the -match operator and the switch statement are by default case insensitive,
to change that behaviour use -cmatch resp. switch with the -CaseSensitive parameter.

A: I tried your code, and it works as expected (changed $line.Contains('RRoot') to $line.Contains('PRoot') to match the input example).
I think you might be struggling with a case sensitive problem.
I suggest that you try applying tolower() function to the string and then compare against a lower case string:
foreach($line in Get-Content $filePath)
{
    # Line can contain
    # $line = P:/TEMP/PRoot/Digvijay/Patil/1.png
    # $line = S:/TEMP/SRoot/Digvijay/Patil/2.png
    # $line = T:/TEMP/TRoot/Digvijay/Patil/3.png
    if($line)
    {
        $lineLower=$line.tolower()
        if($lineLower.Contains('proot')) # This condition works properly
        {
            Write-Host "PRoot"
        }
        if($lineLower.Contains('sroot')) # This condition fails.
        {
            Write-Host "SRoot"
        }
        if($lineLower.Contains('troot')) # This condition fails.
        {
            Write-Host "TRoot"
        }
    }
 }

A: Use the case-insensitive like operator -ilike
foreach($line in Get-Content $filePath)
{
    # Line can contain
    # $line = P:/TEMP/PRoot/Digvijay/Patil/1.png
    # $line = S:/TEMP/SRoot/Digvijay/Patil/2.png
    # $line = T:/TEMP/TRoot/Digvijay/Patil/3.png
    if($line)
    {
        if($line -ilike "*RRoot*")) # This condition works properly
        {
            # Process Rroot here
        }
        if($line -ilike "*SRoot*")) # This condition fails.
        {
            # Process SRoot here
        }
        if($line -ilike "*TRoot*")) # This condition fails.
        {
            # Process TRoot here
        }
    }
 }


text:
Q: jQuery, Add an increasing number to the end of a varaibles each click I am making a new object via my prototype. On click of an element I want to create a new object of the same name, but add a number that increase every time to the end of the name. here is my code:

click me

What is proper syntax for this part:
 myFather[i]

here is my fiddle https://jsfiddle.net/k75fbvfs/5/

A: Use an array, and define it, as well as the iterator i outside fo the click handler:

function person(first, last, age, eyecolor) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eyecolor;
}

var fathers = [],
    i = 0; // Start counting at 0

$(".clickMe").click(function(event) { // $ was missing
  fathers.push(new person("John", "Doe", 50, "blue"));
  console.log(fathers[i], i, fathers.length); // Also log `i`
  i++; // You don't need to assign `i`, `++` modifies the variable.
});
//^ missing `);`

click me

Here's an updated fiddle.


text:
Q: Linking kernel voids without CPU parse (Compute shaders) Is it possible to parse data between compute shader voids without having to create a new buffer and cpu link (Using unity with C# interface).
For example I have a kernel with position data on a set of vector arrays.
I then want to adjust those positions after that kernel has sent them to my shader and rendered.
Edit:
Temporary solution:
Combined all data types to one int and dispatch to one kernal - this is an issue however , as I can't run efficient thread distribution - currently running 512 (1D).

A: After a bit more research and gaining a greater understanding of GPU architecture (it really helps if you have an electronic/microprocessor studies background here).
Simple answer no: you cannot parse between kernals without CPU managment , which causes bottlenecking...and defeats the purpose of GPU calculations.
However you can run functions external to the main Kernal function as long they return a valid HLSL data type (so no GPU localised structs - use CGING file for that one.)
So thanks again stack exchange for pointing in the right direction : Alcohol.
E.g:
http://www.reedbeta.com/blog/2013/01/12/quick-and-easy-gpu-random-numbers-in-d3d11/


text:
Q: addBooks() got an unexpected keyword argument 'name' I want to take data from user and save it to database by using django. Have tried to solve it. But I am not able to solve this problem and didn't find any working solution on internet.
I am getting this error:-

My views.py file is:-
from django.shortcuts import render, HttpResponse
from home.models import addBooks

def index(request):
return render(request, "index.html")

def checkBooks(request):
    return render(request, "checkBooks.html")

def contactUs(request):
    return render(request, "contactUs.html")

 def addBooks(request):

    name = request.POST.get('name', False)
    email = request.POST.get('email', False)
    bookName = request.POST.get('bookName', False)
    authorName = request.POST.get('authorName', False)
    desc = request.POST.get('desc', False)
    book = addBooks(name=name, email=email,bookName = bookName, authorName = authorName, desc = desc)
    book.save()

    return render(request, "addBooks.html")

And my models.py file is:-
from django.db import models

class addBooks(models.Model):
    name = models.CharField(max_length=122)
    email = models.CharField(max_length=122)
    bookName = models.CharField(max_length=122)
    authorName = models.CharField(max_length = 122)
    desc = models.TextField()

This is addBooks.html(Here I am getting the data from user by using from):-

<form method="POST" action = "/addBooks">
    {% csrf_token %}

 Add Books

    Your Name
    <input type="text" name = "name" class="form-control">

    Email Address
    <input type="email" name = "email" class="form-control">

We'll never share your email with anyone else.

    Book Name
    <input type="text" name = "bookName" class="form-control">

    Author Name
    <input type="text" name = "authorName" class="form-control">

    Description Of The Book
    <input type="text" name = "desc" class="form-control">

        <button type="submit" class="btn btn-primary">Submit</button>

</form>

Here is the full error traceback:-

A: The issue is with your function name it is the same as the model name.
addBooks is your model name also your function name.
both can't be the same
def addBooks_add(request):   #change function name

    name = request.POST.get('name', False)
    email = request.POST.get('email', False)
    bookName = request.POST.get('bookName', False)
    authorName = request.POST.get('authorName', False)
    desc = request.POST.get('desc', False)
    book = addBooks(name=name, email=email,bookName = bookName, authorName = authorName, desc = desc)
    book.save()

    return render(request, "addBooks.html")

or try this
from home.models import addBooks as addBooksCreate

def addBooks(request):

    name = request.POST.get('name', False)
    email = request.POST.get('email', False)
    bookName = request.POST.get('bookName', False)
    authorName = request.POST.get('authorName', False)
    desc = request.POST.get('desc', False)
    book = addBooksCreate(name=name, email=email,bookName = bookName, authorName = authorName, desc = desc)
    book.save()

A: In addBooks function, you are taking value of name in the wrong way You have to try this
name = request.POST['name']

And Do this for all input fields.


text:
Q: how to draw trees in tikz
I started but lost after few steps, could anyone help me? I was trying to learn from https://latexdraw.com/draw-trees-in-tikz/, but was somehow not able to generate after 2 steps.
\documentclass[border=0.2cm]{standalone}

\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
    [
        level 1/.style = {teal, sibling distance = 4cm},
        level 2/.style = {teal, sibling distance = 4cm},
        level 3/.style = {teal, level distance = 1cm},
        edge from parent fork down
    ]
    \node {\textcolor{teal}{1}}
        child {node [draw]{2}
        edge from parent [left]}
        child {node [draw] {3}
        child {node [draw] {4}
        child {node [draw] {5}}}
        child {node [draw] {6}}
        edge from parent node [right] {}};
    \end{tikzpicture}
\end{document}

A: Like this?

With forest package is easy:
\documentclass[border=0.2cm]{standalone}
\usepackage[edges]{forest}

\begin{document}
\begin{forest}
for tree={
% style of nodes in the tree
draw, semithick,
       minimum height = 3ex,
        minimum width = 2em,
% style of tree (edges, distances, direction)
     grow = south,
forked edge,        % for forked edge
    s sep = 3mm,    % "sibling" distance
    l sep = 6mm,    % "level" distance
 fork sep = 3mm,    % distance from parent to branching point
           }
[1
    [2]
    [3,fit=band
        [1
            [5
                [9]
                [10]
            ]
            [6
                [11]
                [12]
            ]
        ]
        [5
            [7
                [13]
                [14]
            ]
            [8
                [15]
                [16]
            ]
        ]
    ]
]
    \end{forest}
\end{document}

Edit:
If you like to have more colorful diagram, you only need to add desired colors to node elements (like draw=<desired color>, fill=` etc. You can also change appearance of conected lines (edges). See MWE below:

\documentclass[border=0.2cm]{standalone}
\usepackage[edges]{forest}
\usetikzlibrary{arrows.meta}    % <---

\begin{document}
    \begin{forest}
for tree={
% style of nodes in the tree
draw=blue,      % <---
thick,
fill=blue!10,   % <---
text=red,       % <---
       minimum height = 3ex,
        minimum width = 2em,
% style of tree (edges, distances, direction)
edge={semithick, -{Straight Barb[scale=0.8]},draw=teal},    % <---
forked edge,        % for forked edge
    l sep = 9mm,    % "level" distance
    s sep = 3mm,    % "sibling" distance
    where level = 4{s sep=1mm}{},
 fork sep = 3mm,    % distance from parent to branching point
           }
[1
    [2]
    [3,fit=band
        [1
            [5
                [9]
                [10]
            ]
            [6
                [11]
                [12]
            ]
        ]
        [5
            [7
                [13]
                [14]
            ]
            [8
                [15]
                [16]
            ]
        ]
    ]
]
    \end{forest}
\end{document}


text:
Q: TinyMCE and Laravel 5.3 TokenMismatchException I'm trying to implement TinyMCE image uploads, using Laravel 5.3 on the server side:
here is my JS for TinyMCE, which is currently in a blade template:
<script src="{{ URL::to("/tinymce/tinymce.min.js") }}"></script>
<script>
    tinymce.init({
        selector: 'textarea',
        plugins: [
            "advlist autolink lists link image charmap print preview hr anchor pagebreak",
            "searchreplace wordcount visualblocks visualchars code fullscreen",
            "insertdatetime media nonbreaking save table contextmenu directionality",
            "emoticons template paste textcolor colorpicker textpattern"
        ],
        toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image media",
        relative_urls: false,

        image_title: true,

        automatic_uploads: true,

        images_upload_url: '/discussions/save_images/',

        file_picker_types: 'image',

        images_upload_credentials: true,

        file_picker_callback: function(cb, value, meta) {
            var input = document.createElement('input');
            input.setAttribute('type', 'file');
            input.setAttribute('accept', 'image/*');
            input.onchange = function() {
                var file = this.files[0];
                var id = 'blobid' + (new Date()).getTime();
                var blobCache = tinymce.activeEditor.editorUpload.blobCache;
                var blobInfo = blobCache.create(id, file);
                blobCache.add(blobInfo);
                cb(blobInfo.blobUri(), { title: file.name });
            };
            input.click();
        }
    });
</script>

My route to handle the POST request made by TinyMCE:
Route::post("/discussions/save_images/", 'Discussion\DiscussionController@saveImages');

My action to handle each upload:
public function saveImages(Request $request) {
    $filename = sha1(uniqid()).'.'.request()->file("name")->getClientOriginalExtension();
    $request->file("name")->move('/images/discussions/', $filename);
    return json_encode(["location"=>"/images/discussions/".$filename]);
}

Laravel throws a TokenMismatchException. How can I pass the CSRF token into the POST request that TinyMCE makes?
I know that in general this token can be accessed in a template via {{ csrf_token }}, but I'm not sure about the correct configuration in regards to TinyMCE.

A: Doing a custom handler with images_upload_handler and setting the X-CSRF-Token in the request header worked. Here is what the complete JS code ended up looking like:
tinymce.init({
        plugins: [
            "advlist autolink lists link image charmap print preview hr anchor pagebreak",
            "searchreplace wordcount visualblocks visualchars code fullscreen",
            "insertdatetime media nonbreaking save table contextmenu directionality",
            "emoticons template paste textcolor colorpicker textpattern"
        ],
        selector: 'textarea',
        images_upload_handler: function (blobInfo, success, failure) {
            var xhr, formData;
            xhr = new XMLHttpRequest();
            xhr.withCredentials = false;
            xhr.open('POST', '/discussions/save_images');
            var token = document.getElementById("_token").value;
            xhr.setRequestHeader("X-CSRF-Token", token);
            xhr.onload = function() {
                var json;
                if (xhr.status != 200) {
                    failure('HTTP Error: ' + xhr.status);
                    return;
                }
                json = JSON.parse(xhr.responseText);

                if (!json || typeof json.location != 'string') {
                    failure('Invalid JSON: ' + xhr.responseText);
                    return;
                }
                success(json.location);
            };
            formData = new FormData();
            formData.append('file', blobInfo.blob(), blobInfo.filename());
            xhr.send(formData);
        },
        file_picker_callback: function(cb, value, meta) {
            var input = document.createElement('input');
            input.setAttribute('type', 'file');
            input.setAttribute('accept', 'image/*');
            input.onchange = function() {
                var file = this.files[0];
                var id = 'blobid' + (new Date()).getTime();
                var blobCache = tinymce.activeEditor.editorUpload.blobCache;
                var blobInfo = blobCache.create(id, file);
                blobCache.add(blobInfo);
                cb(blobInfo.blobUri(), { title: file.name });
            };
            input.click();
        }
    });

A: Using jquery you can add csrf token to any xhr request using code below:
  $.ajaxPrefilter(function (options, originalOptions, xhr) {
      var token = '{{ csrf_token() }}';

      if (token) {
          return xhr.setRequestHeader('X-CSRF-TOKEN', token);
      }
  });


text:
Q: Getting "Index was outside the bounds of the array" exception in server, local works fine I am getting this exception in Server:
"Index was outside the bounds of the array."

[IndexOutOfRangeException: Index was outside the bounds of the array.]
   pcdirectory.facultyPage.Page_Load(Object sender, EventArgs e) +2340
   System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
   System.Web.UI.Control.OnLoad(EventArgs e) +91
   System.Web.UI.Control.LoadRecursive() +74
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2207

But while running code in local I don't get any exception or error. Any idea what would be causing this?
Here is the copy of code for Page_Load method:
Sub Page_Load(sender As Object, e As EventArgs)
    if not isPostBack then
        dim smsDBConnection as new SqlConnection(AppSettings("smsDBconnection"))
        dim SQL as new stringBuilder()
        dim command as new sqlCommand()
        dim reader as sqldataReader
        dim directoryGlobal as new directoryGloablFunctions()

        try
            command.connection = smsDBConnection
            command.commandType = commandType.storedProcedure
            smsDBConnection.open()

            SQL.append("get_all_Numbers")
            command.commandText = SQL.toString()

            reader = command.executeReader()

            drpClass.datasource = reader
            drpClass.dataTextField = "Number"
            drpClass.dataValueField = "Number"
            drpClass.dataBind()
        catch ex as exception
            directoryGlobal.sendErrorMessageEmail(ex.message,SQL.toString(),ex.stackTrace,"DIRECTORY ERROR")
            directoryGlobal.messageBox("An error has occurred on this page and been reported to the administrator." & vbcrlf & "Please try again later or contact technical support",me)
            smsDBConnection.close()
        end try

        smsDBconnection.Close()
    end if
end sub

A: Well, your stacktrace points to Page_Load event and because I can see only one reference to a dictionary/array, the problem is most likely there.
This line
dim smsDBConnection as new SqlConnection(AppSettings("smsDBconnection"))

is most probably the problem. Please check your AppSettings and maybe create a test file that will serve only one purpose - access the AppSettings and display a value assigned to key "smsDBconnection" to be sure it works. If it works, there's something different you're not showing us at the moment.
The error you're getting is a typical error message when you try to access an element of an array by an index that doesn't exist. For instance when your collection has 5 elements and you try to reference the 6th.


text:
Q: Is it possible to hide the nodes/slaves in jenkins view? we are using Jenkins LTS 2.150.1, Is it possible to hide the nodes/slaves list (by default at the lower left side of the screen) from "regular" users (i.e - not admins).
Is it even possible?
Am I missing something?
I tried:

*

*looking in the configuration of the server, couldn't find any "switch" or anything of that sort to hide it.

*looking for a plugin to do that, but couldn't find anything that isn't changing the entire "look and feel" of the basic jenkins theme.

A: Seems to be that this feature is not added yet. See this ticket.


text:
Q: Creating a recordset in Access with VBA From the title, i know it seems like this has been answered too many times over, but I have a series of incomprehensible problems with it.  This is also my first time asking for help through posts, so I might forget to mention some stuff.
Function update_location_id()

    Dim rs As DAO.Recordset
    Dim db As Database
    Dim strSQL As String

    Set db = CurrentDb
    strSQL = "select id from location"

    Set rs = db.OpenRecordset(strSQL)

    MsgBox (rs.RecordCount)

End Function

I removed almost all the code from this function just to try to figure out why i couldn't get a record.  this code generates a "too few parameters. expected one on the 'set rs = ...' line.
However if i change the select query's id to *, it works fine.  However it returns 1.  This is somewhat confusing seeing as there are a total of 3 records in the locations table right now.
Just incase its needed the location table looks like
id    description
1     "Location 1"
2     "Location 2"
3     "Location 3"

This is causing me to pull my hairs out and i can't really move on with my project if i can't do such a basic database action as...getting information from it.
References: Visual Basic for Applications, Microsoft Access 14.0 Object Library, OLE Automation, Microsoft Office 14.0 Access database engine object, Microsoft Internet Controls.

A: Typically, the error "too few parameters" comes up when you use a column name that does not exist in the table, so it is interpreted as a parameter.
So, despite your given table data, I'd really check again the table name (location) and the column name (id).
As for the "1", yes, you have to insert
rs.MoveLast
rs.MoveFirst
after opening the recordset to get the correct RecordCount. Before moving to the last one, the recordset does not know how many records it yields (there are some more details to this problem, which I don't remember exactly right now, concerning recordset-type or so).


text:
Q: Configure URLs with prefix in Mojolicious behind Reverse Proxy (ProxyPass) I'm looking for a reliable way to configure Mojolicious running behind an Apache reverse proxy under /app, so that url_for('/foo') actually returns /app/foo instead of just /foo (otherwise all the links would be broken).
The documentation shows a reverse proxy example for everything under /. But that's not what I need, since the application should be under /app.
Turning ProxyPass / http://localhost:8080/ into ProxyPass /app http://localhost:8080/ will cause the issue as the /app prefix would be missing from all urls generated by the application.
The documentation also has a section on rewriting, which has an example of a before_dispatch hook that will take the first part of the request url and use it as base. This requires the prefix to be appended to the ProxyPass url (ProxyPass /app http://localhost:8080/app/ with trailing slash) in the Apache config, which does not seem to be mentioned on that page but maybe it does not need to be ("Move first part and slash from path to base path") because it's obvious. That makes it possible to call http://localhost/app/page, which turns into http://localhost:8080/app/page ('app' removed by the hook), where url_for('/foo') will return '/app/foo' (http://localhost/app/foo), so the links will be correct (without trailing slash in the ProxyPass rule, that would make /apppage/foo).
However, in this example, the url modification is always made in production mode (if app->mode eq 'production'). So calling the backend server directly (http://localhost:8080/testpage) won't work anymore, since all the urls would be broken.
So I thought, I'd check if the X-Forwarded-For header is set (by mod_proxy_http) instead, which would always be set for reverse proxy requests. And since the Apache mod_proxy documentation mentions that this header might already be set in the client request (and end up containing more than one value), I'd remove it from the request first - because a client sending this header should not cause the url base modification.
Apache VirtualHost configuration:
# ProxyPreserveHost: Mojo::URL::to_abs() not 127.0.0.1
ProxyPreserveHost On
<Location "/app/">
    # ProxyPass: prefix pass-thru
    ProxyPass http://localhost:3000/app/
    # RequestHeader: must not be set externally
    RequestHeader unset X-Forwarded-For
</Location>

Hook in Mojolicious startup():
$self->hook('before_dispatch' => sub {
    my $c = shift;
    my $behind_proxy = !!$c->req->headers->header('X-Forwarded-Host');
    if ($behind_proxy) {
        push @{$c->req->url->base->path->trailing_slash(1)},
            shift @{$c->req->url->path->leading_slash(0)};
        $c->req->url->path->trailing_slash(0) # root 404
            unless @{$c->req->url->path->parts};
    }
});

This seems to work...
Question: Will my approach work reliably in the "real world" or is it flawed?
Edit:
Requesting the root address (http://localhost:3000/app/) through the reverse proxy always resulted in an error 404. So I've added two lines to turn the trailing slash off in that case. Since I can't find that in the docs, there may be a better way.

A: You need to set base path for each request url in before_dispatch hook
$app->hook(before_dispatch => sub {
  my $c = shift;
  $c->req->url->base->path('/app/');
});

Example:
use Mojolicious::Lite;

app->hook(before_dispatch => sub {
  shift->req->url->base->path('/app/');
});

get '/' => sub {
  my $c = shift;
  $c->render(text => $c->url_for('test'));
};

get '/test/url' => sub { ... } => 'test';

app->start;

And result:
$ curl 127.0.0.1:3000
/app/test/url

A: I'm now answering my own question as I'm getting more suggestions (not just here) from people who would put a hard-coded prefix in their application code. It should be obvious that prefixing all generated urls manually isn't a solution. Just imagine two instances of the same application deployed on the same server, one under /app1 and the other under /app2. The whole point of the suggested code in my question is that the application works and produces correct urls if accessed through a reverse proxy without breaking requests going directly to the application server. A developer would run Morbo, but a hard-coded prefix would break that. Also, I made at least one mistake in my question, but nobody seems to have noticed.
Flaws in code
I had too many slashes in my example in the question.
The way the Location block is defined, requests to /app without trailing slash would fail. It might be better to write it like that:
<Location "/app">
...

Next, I wrote that I check for the X-Forwarded-For header but I actually checked for X-Forwarded-Host. That wouldn't be a problem if I were also clearing that header but I cleared X-Forwarded-For instead. With that awkward mistake, the safety mechanism wouldn't work, so if you'd set this header while working with your application server at localhost:3000, the app would try to repair the manipulated url even though it's not supposed to do that.
It should've been:
RequestHeader unset X-Forwarded-Host

Example:
ProxyPreserveHost On
<Location /app>
    ProxyPass http://localhost:3000/app
    RequestHeader unset X-Forwarded-Host
</Location>

The ProxyPreserveHost directive isn't required as long as the application uses relative urls everywhere. If the application wants to generate an absolute url, for example url_for('/page')->to_abs, ProxyPreserveHost should be enabled, otherwise external clients would get http://localhost:3000/app/page.
Reverse proxy detection
When I wrote that question, I saw the before_dispatch hook in the Mojolicious documentation and, as pointed out in the question, I wanted to use it for an application running under /app. However, I didn't want to break Morbo. The example assumes that the application is in production mode ($app->mode) while running behind a reverse proxy but not when access directly through Morbo, but I didn't want to change the mode for every other request.
That's why I added a condition to check if the request came through a reverse proxy. As this header is only set by Apache (by the mod_proxy_http module) and not by Mojo::Server::Morbo, it can be used as reverse proxy detection. Together with the right directive to clear the X-Forwarded-Host, I believe the answer to my question would be that yes, that should work reliably.
(Although that last part isn't strictly necessary as long as direct access to the app server is limited to the developer.)
Manipulated url
To show why I've added the /app prefix to the ProxyPass line in the Apache configuration, I'd like to point out that this approach manipulates the url to allow the application to work under the given prefix. There's another question of someone who forgot to add the prefix in the Apache configuration and I wrote an answer explaining what the hook does.
Morbo: localhost:3000
Apache reverse proxy: host.com/app or localhost/app

# Browser > Apache:
http://host.com/app
# Apache (ProxyPass http://localhost:3000/) > Mojolicious sees:
GET /
url_for '/test' = /test
(or even //test if the hook pushes undef, see the other answer linked above)
# Apache (configured as described above) > Mojolicious sees:
GET /app
# Hook:
base = /app
request = /
url_for '/test' = /app/test

Normally, the local target argument in the ProxyPass directive would not have the prefix, it would just be something like ProxyPass http://...:3000/. In that case, the application doesn't know about the prefix, which is why all generated urls and links are incomplete.
This approach requires you to let Apache pass the prefix through to the application server. The application doesn't know about the prefix, so it wouldn't know what to do with a request to /app/page. This is where the hook comes in. It assumes that the first level of the path is always the prefix, so it turns /app/page into /page and it conveniently appends the /app prefix to the url base, which is used when generating urls, making sure that a link to /test actually points to /app/test.
Obviously, this modification should not be done for any request sent directly to Morbo.
Alternative
Alternatively, a custom request header could be set by the reverse proxy and then used by the hook to produce working urls. The Mojolicious::Plugin::RequestBase module works that way. It expects you to define the prefix in the X-Request-Base header, not in the url:
RequestHeader set X-Request-Base "/app"

In that case, the application should only receive requests for urls relative to that prefix:
ProxyPass http://localhost:3000/

All that module really does is pick up the header and use it as url base:
$c->req->url->base($url); # url = X-Request-Base = /app

Example:
<Location /app>
    ProxyPass http://localhost:3000
    RequestHeader set X-Request-Base "/app"
</Location>

This is a nice and simply solution. Note that the /app prefix appears twice in that case. And of course, the hook implemented by that module only does its work if the X-Request-Base header is set, just like the hook shown above does nothing if the X-Forwarded-Host header is not set.

A: You should mount your application under required path.
In your startup you should do:
$r =  $app->routes;
$r =  $r->any( '/api' )->partial( 1 );

$r->get( '/test' );

You should not configure specially your apache. When GET /api/test will come your app will get /api/test route. This route partially matched to /api and the rest route /test will be assigned into ->stash->{ path }.
So rest routes will be checked against /test (source)