text:
Q: How do I make a hidden, floating "loading" div hide again from a page after hitting the back button on mobile safari? Its an iOS problem only.
I have a floating hidden div with "...loading" appear in the current page upon following links within the application.  This is again hidden by default on the following page.
The problem is that when the user then hits the back button it appears again, unhidden, on mobile safari.  This is not a problem on desktop browsers.
This code below works on desktop Firefox, Chrome, and Safari, but not on mobile Safari on iO5 iPhone and iPad.
<body style="margin: 0; padding: 0" onunload="$('#loading').hide()"  onload="setTimeout(function() { window.scrollTo(0, 1) }, 100);">

Any thoughts?

A: For Safari on iOs you can do this:
window.addEventListener('popstate', function(e) {$('#loading').hide()});

Based on this answer:
Is there an alternative method to use onbeforeunload in mobile safari?


text:
Q: java thread synchronization problem, how to implements observable thread The problem is: class C controls class B in terms of whether or not to let B add the A to the queueOfA back again, but how can I make sure that when A notifies C and update immediately before B's queueOfA becomes empty, because class B is running so fast that may remove all the A's so becomes an empty queueOfA before C doing the update, which may leads to C's run method go to the end.
Please help me out!
class A extends Observable implements Runnable{
    //...
    void run(){
     //...
     if ( goBackToTheQueueAgain == true ){
         setChanged();
         notifyObservers();//notify C that to let B add itself back
     }
    //...
}

class B extends implements Runnable{
    Queue<A> queueOfA;// initialy, queueOfA contains several A's
    //...
    void run(){
       //...
       A retrieved = queueOFA.remove();
       Thread aThread = new Thread(retrieved);
       aThread.start();
       //...
    }
 }

 class C implements Observer, Runnable {
    B b; //initially class C contains an instance of B
    //...
    void update(Observable o, Object arg){
       if(o instanceof A){
         A a = (A) o;
         b.queueOfA.add(a);
       }
    }
    //...
    void run(){
       //...
       Thread bThread = new Thread(b);
       bThread.start();
       while ( b.queueOfA.isEmpty() == false ){
          // if queueOfA is not empty loop for ever
       }
      //..
    }
 }

A: The problem is not that you have to notify the update as soon as possible - you cannot guarantee that. For example, consider that you have just one element in the queue to start with. That gets removed from the queue and then the queue is empty, yet the element is still being processed. The A thread can take as long as it likes - C should not terminate, even though the queue is empty.
The fix is that C should wait until all A's have been fully processed. That is, the A's reached the end of their run method without putting the A back on the queue. This can be done using a countdown latch. Initially set the latch to the size of the queue (the number of A's) and decrement this latch each time an A is fully processed. C will exit only when this latch becomes zero.
C looks something like this
CountdownLatch latch;

void run(){
   //...
   this.latch = new CountDownLatch(queueOfA.size());
   Thread bThread = new Thread(b);
   bThread.start();
   latch.await();
  //.. catch InterruptedException etc..
}

void notifyDone(A a) {
    this.latch.countDown();
}

And A's run method is
void run(){
     //...
     C c = ...; // passed in from somewhere
     if ( goBackToTheQueueAgain == true ){
         setChanged();
         notifyObservers();//notify C that to let B add itself back
     }
     else
         c.notifyDone(this);
}

A needs a reference to C, so that it can notify directly that it is done.
Personally, I would not use the Observer/Observable here, since your notification has a specific meaning - that the item can be requeued. The observer pattern is best suited to notify in changes of state, where that state is available from the instance being observed. that's not the case here, and there is no real gain from such abstract decoupling. If you want to keep it abstract and not couple A to C, you can introduce an additional interface, e.g.
interface QueueHandler<T>
{
    void requeue(T t);
    void completed(T t);
}

and implement this on C, and pass it to each A instead of the current Observer interface. But equally, the A and C classes are quite tightly coupled, so you could also just pass C into A and let it notify directly.

A: I answered this question with a working code example - It is very close. All you would need to do is add an Observer to the Thread that has the main.
Image processing in a multhithreaded mode using Java

redpajama_set_name: RedPajamaStackExchange


text:
Q: Style border and Title Bar cause NullReferenceException I want to change my form border and Title Bar and fount this solution.
So after add this into my XAML (i am using the first solution in the first answer) my application running and i can see the Style changed but after few seconds i can see this exception in the designer:

My application still run and show the new style but this is happening again and again, i try to remove and add changes several times but this error still jump after a while.
    Update
this is the code that added to XAML:
<Window x:Class="CSharpWPF.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" >
    <WindowChrome.WindowChrome>
        <WindowChrome CaptionHeight="{Binding ActualHeight,ElementName=titlebar}"/>
    </WindowChrome.WindowChrome>
    <DockPanel LastChildFill="True">
        <Border Background="LightBlue" DockPanel.Dock="Top" Height="25" x:Name="titlebar">
            <TextBlock Text="{Binding Title, RelativeSource={RelativeSource FindAncestor,AncestorType=Window},FallbackValue=Title}"
                       Margin="10,0,0,0"
                       VerticalAlignment="Center">
                <TextBlock.Effect>
                    <DropShadowEffect Color="White" ShadowDepth="3"/>
                </TextBlock.Effect>
            </TextBlock>
        </Border>
        <Border BorderBrush="LightGray" BorderThickness="1" Padding="4">
            <TextBlock Text="Window content"/>
        </Border>
    </DockPanel>
</Window>


text:
Q: Is there a design pattern to cut down on code duplication when subclassing Activities in Android? I've got a common task that I do with some Activities - downloading data then displaying it.  I've got the downloading part down pat; it is, of course, a little tricky due to the possibility of the user changing the orientation or cancelling the Activity before the download is complete, but the code is there.  There is enough code handling these cases such that I don't want to have to copy/paste it to each Activity I have, so I thought to create an abstract subclass Activity itself such that it handles a single background download which then launches a method which fills the page with data.
This all works.  The issue is that, due to single inheritance, I am forced to recreate the exact same class for any other type of Activity - for example, I use Activity, ListActivity and MapActivity.  To use the same technique for all three requires three duplicate classes, except each extends a different Activity.
Is there a design pattern that can cut down on the code duplication?  As it stands, I have saved much duplication already, but it pains me to see the exact same code in three classes just so that they each subclass a different type of Activity.
Edit: Since it seems I need to be a bit more specific...
Suppose I'm trying to solve the problem of an AsyncTask background download during orientation changes.  The solution I have right now is to use callbacks; there's download manager that I have which starts these downloads, and then I have the Activity attach a callback to it.  When the orientation changes the Activity is destroyed and then recreated; during this process I detach the old Activity's callback, then attach a new callback from the new Activity afterwards.
Orientation changes are a common problem, and in multiple Activities I start the Activity with a progress view while the data loads.  What I am trying to solve is not having to re-implement this orientation-handling logic ten times over; my initial solution was to subclass Activity, but then I got the problem above.

A: Prefer composition over inheritance.  Whatever is common, delegate to some class(es) that can be a member of Activity, ListActivity, and MapActivity.

A: The problem is that you are mixing view and the logic of your program.
A background thread like an AsyncTask will run as long as your application is not killed from the system. You could do the download everything in the async task and then save it somewhere on the SD-Card to retrieve it from there if it is ready.
You could subclass the application class to hold a reference to the task or a handler to communicate with the class from every Activity.
If this is not a solution to your problem at all maybe you could clarify the question a little bit. It would help to know what you are doing in the onCreate... methods.

A: I haven't used MapActivity, but I solved this problem by not using ListActivity and providing the functionality myself in Activity. There really isn't that much in ListActivity if you look: http://google.com/codesearch/p?hl=en#uX1GffpyOZk/core/java/android/app/ListActivity.java  Implement the functionality yourself you get more customization and more room to grow.

A: Any way for you to have a helper class with static methods to which you would pass your activities and have the common work done there instead of in each activity?


text:
Q: unable to read a tab delimited file into a numpy 2-D array I am quite new to nympy and I am trying to read a tab(\t) delimited text file into an numpy array matrix using the following code:
train_data = np.genfromtxt('training.txt', dtype=None, delimiter='\t')

File contents:
38   Private    215646   HS-grad    9    Divorced    Handlers-cleaners   Not-in-family   White   Male   0   0   40   United-States   <=50K
53   Private    234721   11th   7    Married-civ-spouse  Handlers-cleaners   Husband     Black   Male   0   0   40   United-States   <=50K
30   State-gov  141297   Bachelors  13   Married-civ-spouse  Prof-specialty  Husband     Asian-Pac-Islander  Male   0   0   40   India   >50K

what I expect is a 2-D array matrix of shape (3, 15)
but with my above code I only get a single row array of shape (3,)
I am not sure why those fifteen fields of each row are not assigned a column each.
I also tried using numpy's loadtxt() but it could not handle type conversions on my data i.e even though I gave dtype=None it tried to convert the strings to default float type and failed at it.
Tried code:
train_data = np.loadtxt('try.txt', dtype=None, delimiter='\t')

Error:
ValueError: could not convert string to float: State-gov

Any pointers?
Thanks

A: Actually the issue here is that np.genfromtxt and np.loadtxt both return a structured array if the dtype is structured (i.e., has multiple types).  Your array reports to have a shape of (3,), because technically it is a 1d array of 'records'.  These 'records' hold all your columns but you can access all the data as if it were 2d.
You are loading it correctly:
In [82]: d = np.genfromtxt('tmp',dtype=None)

As you reported, it has a 1d shape:
In [83]: d.shape
Out[83]: (3,)

But all your data is there:
In [84]: d
Out[84]:
array([ (38, 'Private', 215646, 'HS-grad', 9, 'Divorced', 'Handlers-cleaners', 'Not-in-family', 'White', 'Male', 0, 0, 40, 'United-States', '<=50K'),
       (53, 'Private', 234721, '11th', 7, 'Married-civ-spouse', 'Handlers-cleaners', 'Husband', 'Black', 'Male', 0, 0, 40, 'United-States', '<=50K'),
       (30, 'State-gov', 141297, 'Bachelors', 13, 'Married-civ-spouse', 'Prof-specialty', 'Husband', 'Asian-Pac-Islander', 'Male', 0, 0, 40, 'India', '>50K')],
      dtype=[('f0', '<i8'), ('f1', 'S9'), ('f2', '<i8'), ('f3', 'S9'), ('f4', '<i8'), ('f5', 'S18'), ('f6', 'S17'), ('f7', 'S13'), ('f8', 'S18'), ('f9', 'S4'), ('f10', '<i8'), ('f11', '<i8'), ('f12', '<i8'), ('f13', 'S13'), ('f14', 'S5')])

The dtype of the array is structured as so:
In [85]: d.dtype
Out[85]: dtype([('f0', '<i8'), ('f1', 'S9'), ('f2', '<i8'), ('f3', 'S9'), ('f4', '<i8'), ('f5', 'S18'), ('f6', 'S17'), ('f7', 'S13'), ('f8', 'S18'), ('f9', 'S4'), ('f10', '<i8'), ('f11', '<i8'), ('f12', '<i8'), ('f13', 'S13'), ('f14', 'S5')])

And you can still access "columns" (known as fields) using the names given in the dtype:
In [86]: d['f0']
Out[86]: array([38, 53, 30])

In [87]: d['f1']
Out[87]:
array(['Private', 'Private', 'State-gov'],
      dtype='|S9')

It's more convenient to give proper names to the fields:
In [104]: names = "age,military,id,edu,a,marital,job,fam,ethnicity,gender,b,c,d,country,income"

In [105]: d = np.genfromtxt('tmp',dtype=None, names=names)

So you can now access the 'age' field, etc.:
In [106]: d['age']
Out[106]: array([38, 53, 30])

In [107]: d['income']
Out[107]:
array(['<=50K', '<=50K', '>50K'],
      dtype='|S5')

Or the incomes of people under 35
In [108]: d[d['age'] < 35]['income']
Out[108]:
array(['>50K'],
      dtype='|S5')

and over 35
In [109]: d[d['age'] > 35]['income']
Out[109]:
array(['<=50K', '<=50K'],
      dtype='|S5')

A: Updated answer
Sorry, I misread your original question:

what I expect is a 2-D array matrix of shape (3, 15)
but with my above code I only get a single row array of shape (3,)

I think you misunderstand what np.genfromtxt() will return. In this case, it will try to infer the type of each 'column' in your text file and give you back a structured / "record" array. Each row will contain multiple fields (f0...f14), each of which can contain values of a different type corresponding to a 'column' in your text file. You can index a particular field by name, e.g. data['f0'].
You simply can't have a (3,15) numpy array of heterogeneous types. You can have a (3,15) homogeneous array of strings, for example:
>>> string_data = np.genfromtext('test', dtype=str, delimiter='\t')
>>> print string_data.shape
(3, 15)

Then of course you could manually cast the columns to whatever type you want, as in @DrRobotNinja's answer. However you might as well let numpy create a structured array for you, then index it by field and assign the columns to new arrays.

A: I do not believe Numpy arrays handle different datatypes within a single array. What can be done, is load the entire array as strings, then convert the necessary columns to numbers as necessary
# Load data as strings
train_data = np.loadtxt('try.txt', dtype=np.str, delimiter='\t')

# Convert numeric strings into integers
first_col = train_data[:,0].astype(np.int)
third_col = train_data[:,2].astype(np.int)


text:
Q: Using chrome devtools with browsersync & --inspect I can't for the life of me workout how to use the new --inspect with browser-sync
gulp.task('browser-sync', ['nodemon'], function () {
    browserSync({
        proxy: 'localhost:17230',
        port: 5000,
        notify: true,
        debug: true
    });
});

I have tried debug true, but this does nothing either :(

A: I had the same issue a few months back. You may use nodeArgs in order to use pass the appropriate parameters to node binary, alternatively, the exec option will work too.
const nodemon = require('gulp-nodemon');
const browserSync = require('browser-sync');

gulp.task('browser-sync', ['nodemon'], function () {
    browserSync({
        proxy: 'localhost:17230',
        port: 5000,
        notify: true,
        debug: true
    });
});

gulp.task('nodemon', function() {
  let started = false;
  nodemon({
    nodeArgs: ['--inspect=0.0.0.0:17230'], // localhost + port
    // You may also use {exec: 'node --inspect'}
    ext: 'js',
    ignore: ['.idea/*', 'node_modules/*'],
    script: 'server.js',
    tasks: ['lint'],
    verbose: true
    delay: 2000
  })
  .on('start', () => {
    // to avoid nodemon being started multiple times
    if (!started) {
      setTimeout(() => done(), 100);
      started = true;
    }
  });
});


text:
Q: Office web apps does not have access to content database I have issues with Office Web apps. After some logging search I found it's because of the service account of owa service application does not have access to the content DB.
I've read somewhere that the service account has to be member of db_owner role on the content databases, which is not the case for me.
The documentation states :

After you run the configuration wizards, SQL Server and database
  permissions include:

*

*Dbcreator fixed server role.

*Securityadmin fixed server role.

*db_owner for all SharePoint Server 2010 databases.

*Membership in the WSS_CONTENT_APPLICATION_POOLS role for the
  SharePoint Server 2010 server farm configuration database.

*Membership in the WSS_CONTENT_APPLICATION_POOLS role for the
  SharePoint Server 2010 SharePoint_Admin content database.

The WSS_CONTENT_APPLICATION_POOLS seems to be created only for some database, not for front apps content databases.
I have created a dedicated application pool, with a dedicated managed account. What is the correct way to grant access to all content DB for this user ?
Have I to manually set up the permissions in all content DB ?

A: The easiest way I have found is to use the [SPWebApplication.GrantAccessToProcessIdentity][1] method. It grants the specified user account access to the process identity and provides full control of the SharePoint Web Application. Office Web Apps can use this to access the content databases as the SharePoint Web Application's process identity, which already has access to the content databases.
You can do this with the following PowerShell:
$webApp = Get-SPWebApplication http://my.webapplication.com
$webApp.GrantAccessToProcessIdentity("domain\username")

[1]: http://msdn.microsoft.com/en-us/library/ms478270.aspx - notice that unfortunately, the description of this method on MSDN is incorrect.


text:
Q: Why modifying gravity to a fixed distance cant solve dark matter? I quote Sabine Hossenfelder:

"A modification becoming important at a fixed distance however could never explain the observed rotation velocities for spiral galaxies, whose constant asymptotic value depends on the luminosity of the galaxy, a relation which is known as the Tully-Fisher relation."

Why cant a theory of modified gravity be constructed based on distancce invariance instead of acceleration invariance (as MOND) to match the rotation curve dynamics of galaxies?

A: As Milgrom (MOND) showed, the v(r) data for spiral galaxies follows Newton until the radial acceleration
$$\frac{v^2}{r}=a(r)=\frac{GM}{r^2}=a_0$$
The data shows $a_0$ to be the same value for all spiral galaxies.  For a Newtonian acceleration much smaller than $a_0$, the acceleration is postulated to be equal the geometric mean of Newton and $a_0$.  That is
$$\frac{v^2}{r}=a(r)=\sqrt{\frac{GM}{r^2}a_0}$$  Notice that the $r$ on both sides cancel out and the tangential velocity becomes constant $v=\sqrt{GMa_0}\quad$ as is actually observed.
Now $M\approx2L$ where the galaxy mass $M$ is in solar masses, and the galaxy luminosity $L$ is in solar luminosities. Then we get the Tully-Fisher relation mentioned by Sabine
$$ v^4\propto L $$
As to your original question, spiral galaxy's data agree with modifying Newton at less than a universal acceleration $a_0$ rather than at greater than a universal radius. Stated differently, $v(r)$ does not flatten at a universal r, but instead flattens when the Newtonian acceleration equals a universal $a_0$.


text:
Q: Laravel not seeing user as logged in until after page load When a user logs in on my site, they are redirected back to the homepage but they are shown a guest view of the page, when they should be logged in. This testing snippet that I added shows that the user is not seen as logged in when the page is loaded.

@auth

{{ Auth::user()->email }}

@else

not logged in

@endauth

I wrote an endpoint that I gets hit after the page load to check if the user is logged in

public function checkAuth() {
    return json_encode(Auth::user());
}

And hitting this endpoint successfully returns the laravel user data of the logged in account. Does anyone have ideas on why the initial page load isn't seeing the user as logged in?

A: The fix for the issue was to set "same_site" to "lax" in session.php.


text:
Q: Limacon curve and its osculating circle Consider the Limacon: $\gamma(t)=((1+3cost)cost, (1+3cost)sint)$.
(i) Compute $A(\gamma)=\frac{1}{2}\int_\gamma (x\frac{dy}{dt}-y\frac{dx}{dt})dt$.
(ii) Determine the osculating circle $C$ at $(4,0)$.
(iii) Show that $\gamma$ lies entirely inside $C$.
(iv) Compare $A(C)$ and $A(\gamma)$ and explain what you find.
=###
For question (i) I've found the derivatives of $y=(1+3cost)sint)$ and $x=((1+3cost)cost$ respectively. Then plugged them into $A(\gamma)=\frac{1}{2}\int_\gamma (x\frac{dy}{dt}-y\frac{dx}{dt})dt$ and calculated the integral. But what makes me doubt is that I assumed $t∈[0,2\pi]$ to sort out the finite integral, which gave a result of $\frac{11}{2}\pi$.
For question (ii), the point $(4,0)$ gives $t=0$. Then I used $\kappa(0)=||\gamma''(0)||=7$ to get the curvature and $R=\frac{1}{\kappa(0)}=\frac{1}{7}$ for the radius of the osculating circle. The unit tangent vector is $T(0)=\frac{\gamma'(0)}{||\gamma'(0||}=(0,1)$ and the unit normal vector is $N(0)=(-1,0)$ by rotating $T$ for $\frac{\pi}{2}$ counter clockwisely. Then the centre of the circle is $\gamma_c(0)=\gamma(0)+RN(0)=(\frac{27}{7},0)$. Therefore the osculating circle is $(x-\frac{27}{7})^2+y^2=\frac{1}{49}$.
However, question (iii) asks to show that the curve $\gamma$ lies entirely inside C. From my results in (i) and (ii), $A(\gamma)=\frac{11}{2}\pi$ while $A(C)=\frac{\pi}{49}$, $A(\gamma)>A(C)$, which makes $\gamma$ less possible to lie entirely inside $C$. Also, I can find nothing from these results to answer question (iv).
Could someone please help me find out where I've gone wrong in (i) and (ii), and thus how to proof the statement in (iii)? Thanks heaps!!
===
The graph of the limacon is here

A: The question was sloppy not to specify the domain of the parametrization. You are correct to take $t\in [0,2\pi]$. You have the correct value for $A(\gamma)$. On the other hand, you have to be careful about interpreting it, since the curve intersects itself.
Your serious mistake, proceeding to (ii), is that $\gamma$ is not an arclength (speed one) parametrization, so your formula for curvature needs to be corrected by using the chain rule. (You can find lots of examples of that on posts here.) Once you do that, you should get an answer that makes sense.
Note that to check (iii), you're going to have to show that the distance from the center of the osculating circle to points on the curve is always (except for the single point $(4,0)$) less than the radius. The trigonometry (if you consider the square of radius minus the square of the distance) simplifies nicely.


text:
Q: Pass data from jsp to html So I have a form in my a.html file. I then pass these data to my b.jsp file and perform some queries (inserting to the database etc). Now I have another html file called "confirmation.html", which shows what were added to the database. How do I get the data from my b.jsp file?

A: HTML files are static. They can't display data dynamically. Use another JSP.
b.jsp should be a servlet instead. JSPs are view components, used to generate HTML markup. Servlets are controller components, used to contain Java code and, for example, insert and get data from the database.
The requests should that way:

*

*GET request for ShowFormServlet. The ShowFormServlet forwards to showForm.jsp, which displays the form

*POST request to InsertDataServlet to submit the form. The servlet inserts data in the database and sends a redirect to ShowDataServlet

*GET request to ShowDataServlet. The ShowDataServlet gets the data from the database, stores them in a request attribute, and forwards to displayData.jsp. displayData.jsp generates HTML markup to display the data stored in the request attribute.

This is the MVC pattern.
To redirect, use HttpServletResponse.sendRedirect(). To forward from a servlet to a JSP, use HttpServletRequest.getRequestDispatcher(...).forward().


text:
Q: What is a simple way to only grab dependancies from a Maven Artifactory Repository and run a Maven build in Jenkins Declarative Pipeline Syntax? For my pipeline's build step I am just looking to authenticate to Artifactory and run a simple mvn clean install, however I am getting "Not authorized , ReasonPhrase:Unauthorized" errors relating to Artifactory.  I am running my Maven build from within an isolated build container that I spin up via Kubernetes.  I have checked out the JFrog documentation but am so far unsuccessful with setting things up in my Jenkinsfile.  Essentially I want to be able to only grab the dependencies from my Maven Artifactory Repo and run my build. Here is what I'm currently trying but the build seems to skip right through everything once it hits the build step:
pipeline {
agent {
    kubernetes {
      cloud 'cloud-test'
      label 'label-test'
}

options {
    buildDiscarder(logRotator(numToKeepStr: '10'))
}

environment{
    def ART_CREDENTIALS = credentials('artifactory-connect')
    def ART_USR = "${env.ART_CREDENTIALS_USR}"
    def ART_PSW = "${env.ART_CREDENTIALS_PSW}"
}

stages {
    stage('Run in Build Container') {
        steps {
            container('build-container') {
                script{
                    sh 'echo Running Maven Build...'
                    // Look at how to authorize to Arty here
                    def server = Artifactory.server 'arty-server'
                    rtMaven.resolver server: server, releaseRepo: 'sysdse-maven-local', snapshotRepo: 'snapshots'
                }
                sh 'mvn clean install'
            }
        }
    }
    stage('Run Application') {
        steps {
            container('App-Container') {
                //Run App
            }
        }
    }
    stage('Run Tests'){
        steps {
            container('App-Container'){
                //Run Tests
                }
            }
        }
    }
}

A: I was able to accomplish what I was looking for by adding the following to my /path/to/.m2/conf/settings.xml in my docker build container and then committing that:
<server>
  <id>artifactory-repo-id</id>
  <url>https://artifactory.location/</url>
  <username>user@email.com</username>
  <password>secret-http-token</password>
</server>

So my resulting build stage in my Jenkinsfile looks like:
stage('Run in Build Container') {
    steps {
        container('build-container') {
            script{
            sh 'echo Running Maven Build...'
            sh 'mvn clean install'
        }
    }
}


text:
Q: Resizing a Flash loader after Event.COMPLETE doesn't work Google suggests that the following is not that uncommon a question: having loaded something into a Flash stage using a Loader, I want to resize it. However, if you do this before the content is loaded, resizing the image causes it to disappear.
The proposed solution is usually to use an Event listener for Event.COMPLETE. Here's my code:
public function FlixelTest()
    {
        super();

        // support autoOrients
        stage.align = StageAlign.TOP_LEFT;
        stage.scaleMode = StageScaleMode.NO_SCALE;

        myLoader = new Loader();
        myLoader.x = (stage.fullScreenWidth-640)/2;
        myLoader.y = (stage.fullScreenHeight-480)/2;
        addChild(myLoader);

        var url:URLRequest = new URLRequest("stuff.swf");
        myLoader.load(url);
        myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadProdComplete);

    }

    function loadProdComplete(e:Event):void{
        myLoader.height = 480;
        myLoader.width = 640;
    }

According to every posting I can find so far online, this solution should work. When the event fires, the Loader is done, and can be resized. However, it doesn't. Commenting out the lines that modify .height and .width cause the SWF to appear, uncommenting them and running again and the SWF never loads.
Could anything else be interfering here? This is using FlashBuilder to construct an Actionscript3 -> Android project.
EDIT - The solution here doesn't appear to work either: Problem resizing loader after loading swf
UPDATE - I have a working, and horrific, solution that is as followed:
function loadProdComplete(e:Event):void{
        if(myLoader.width != 0){
            myLoader.width = 640;
            myLoader.content.width = 640;
        }
        else{
            timer = new Timer(500);
            timer.addEventListener(TimerEvent.TIMER, timertick); // there should be a comma here but yahoo replaces it with ...
            timer.start();
        }
    }

    function timertick(e:TimerEvent){
        timer.stop();
        stage.dispatchEvent(new Event(Event.COMPLETE));
    }

It basically uses the content's width to see if it's finished loading. If it hasn't, it waits a half second and refires the COMPLETE event. This actually helps display it (although the width hasn't been adjusted, I assume that's a separate issue) - I can't believe this is the only way to get it working...

A: While not strictly a solution, the way I've circumvented this is by not resizing it at all - I am instead cropping an area over the window so all that's seen is the section I wanted to display.
function loadProdComplete(e:Event):void{
        var gameMask : Shape = new Shape;
        gameMask.graphics.beginFill(0xffcc00);
        gameMask.graphics.drawRect(myLoader.x,myLoader.y,640,480);
        gameMask.graphics.endFill();
        myLoader.content.mask = gameMask;
    }

Since the mask would've been necessary for me anyway to hide off-stage clutter, this solved two problems at once.
I won't accept this as the answer in case anyone has any alternative insights, but if anyone comes across this question, this is a posisble solution.


text:
Q: ASP.Net MVC Dropdown text generation using a Select List not populating the values and text Using the following code i generate a select list in my controller and feed it into my view model.
var SelectListItems = om_repo.List().Select(x => {
            var item = new SelectListItem();
            item.Value = x.id.ToString();
            item.Text = x.code;
            return item;
        });

createvm.allOccupations = new SelectList(SelectListItems);

Here is my view code
@Html.DropDownListFor(model => model.selectedOccupation,  Model.allOccupations, "Choose one")

The output im getting is
<option>System.Web.Mvc.SelectListItem</option>

Why isnt it picking up the select list items Text and Values that are being fed. In my debugger i can see the values are set in the locals under text and value.

A: Because the DropDownlist doesn't want a SelectList; it wants an IEnumerable of SelectListItems.
Try just:
createvm.allOccupations = SelectListItems;

Model Class also needs to be:
public IEnumerable<SelectListItem> allOccupations { get; set; }

Not
public SelectList allOccupations { get; set; }

Scott Allen expanded on the problem here: https://odetocode.com/Blogs/scott/archive/2010/01/18/drop-down-lists-and-asp-net-mvc.aspx


text:
Q: How to detect file copy over local network with C#? I've to create a simple application with .NET Framework that detects when a remote user copy some file from the machine that the application will run on.
Eg.

*

*Machine1 (The application will run here)

*Machine2
A user on the Machine2 access a shared directory on the Machine1 and copies some files to some Machine2 directory.
I need log the file name that was copied and the IP/DNS that request the copy.
Is there some Windows Message to do it?
Or even any IO class?

A requirement is that I have to do this through a custom application.

A: You can not detect from a C# program if a file has been accessed, there is no message or exposed API that will tell you when it happens. You need to go a lower level in the OS. The normal way of doing this is you set windows itself to do the monitoring via group policy under the Computer Configuration\Windows Settings\Security Settings\Advanced Audit Policy Configuration\Audit Policies\ then enable Object Access: File Share.
This will create a audit log entry like the following

Log Name:      Security
Source:        Microsoft-Windows-Security-Auditing
Date:          8/14/2013 2:08:25 AM
Event ID:      5145
Task Category: Detailed File Share
Level:         Information
Keywords:      Audit Success
User:          N/A
Computer:      RootMS01.Reskit.com
Description:
A network share object was checked to see whether client can be granted desired access.
Subject:
        Security ID:           RESKIT\Administrator
        Account Name:          Administrator
        Account Domain:               RESKIT
        Logon ID:              0x49199
Network Information:
        Object Type:           File
        Source Address:               10.10.10.11
        Source Port:           61361
Share Information:
        Share Name:            \\*\Shares
        Share Path:            \??\C:\Shares
        Relative Target Name:  UserHomeFolder\LSkywalker\Projects.txt
Access Request Information:
        Access Mask:           0x120089
        Accesses:              READ_CONTROL
                              SYNCHRONIZE
                              ReadData (or ListDirectory)
                              ReadEA
                              ReadAttributes
Access Check Results:
        READ_CONTROL:  Granted by Ownership
                              SYNCHRONIZE:   Granted by        D:(A;;FA;;;WD)
                              ReadData (or ListDirectory):  Granted by        D:(A;;FA;;;WD)
                              ReadEA: Granted by     D:(A;;FA;;;WD)

You can see the file that was accessed and the IP of the machine accessing it is in the log, all you need to do is write a C# program that reads the log and pulls out the information you need.
Here is a detailed technet article explaining how to set it up.


text:
Q: Arbitrary protobuf message as byte-array over Websocket - how to determine actual message type upfront Protobuf is nice and dandy, but it was not made with self-description in mind. Now this is totally okay if you're using a well-defined protocol and want to replace e.g. SOAP-messages or just want to replace a restful JSON API or the like.
However I would like to use it over a Websocket though and instead of closing and reopening it up again and again under different urls - which defeats the point of the websocket - I would like to keep it open and send different messages over the wire as Byte-arrays!
Now my problem is simple yet a bit complex to solve. I want to send an arbitrary message from client to the server (or vice versa) and the receiver should simple determine which type of message it got and how to interpret it.
In pseudocode this would look like so:
client:
Message m = new Auth().withUserName("Sorona").withPassword("TotallyNotMyActualPassword")

ws.send(m)

server:
Map[Type, Handler]

receiveMessage(Message m) {
   handlers.get(m.determineType()).handle(m)
}

handler:
trait Handler[T] {
  def handle()
}

So what I truly want is two things:
1) Be able to determine the actual type of Any message without (dramatically) increasing the message size.
2) Be robust and extendable
For a new message type I simply want to add a handler and be done.
No hardcoded enums I have to maintain, no switch-case structures I have to adopt etc.
In simple OOP this would be fairly easy but with Protobufs I am kind of stuck.
Any hints?

A: What I came up with so far:
message Root
{
    string type = 1;
    google.protobuf.Any content = 2;
}

message Dog
{
   string name = 1;
   string fav_food = 2;
}

message Cat
{
   string name = 1;
   uint32 colors = 2;
}

Then somewhere (shared file, database etc.) I create a map like this:
val mapper: Map[String, Class] = Map(
  "Dog" -> Dog,
  "Cat" -> Cat
)

On the sender I would do:
val nero = Dog().withName("Nero").withFavoriteFood("Raw meat")
val msg = Root().withType("Dog").withMessage(Any.pack(nero))

and on the receiver side:
val r = Root.parseFrom(msg)
val a = r.message.get.unpack(mapper(r.type))

That's basically the plan. I would then introduce my own builders that have the types (e.g. "Dog" or "Cat") hardcoded and would also add another mapper between a class/messagetype and a handler.
But I guess if I come that far and it works (currently it doesn't because I am using Scala.js and it looks like the Any.pack is not supported there right now) it will be a totally different story ;)

A: I can think of different approaches here:

*

*self describing messages (like in your proposal)

*message description outside of messages (meta-data)

*rpc framework (recommended for complex projects)

description in metadata
If you don't want to put a self describing property into each message, you could define them outside, and for example send them in between messages. For example
stream: ... "now comes a dog", { dog }, "now comes a cat", { cat }, ...

how you encode "now comes a dog" and how you map that to your message is up to you. Depending on how you structure your identifiers, this might be more complicated then having self describing message (if you use strings of arbritary length for example, you would also need to send along that number).
self describing messages
your custom protocol looks like this
stream: ..., { self-describing dog }, { self-describing cat }, ...

using an rpc framework
you could also try to use an rpc framework like gRPC which will give you a more sophisticated design. Here you can define service interfaces with different methods and parameters. The communication will be generated and you only need to provide the method implementations.
However I am not sure if websockets are fully supported


text:
Q: Checking of Newline char in input Code:
printf("Enter your data (5x10) of characters: \n");
for (i = 0; i < SIZE1; i++)
for (j = 0; j < SIZE2; j++)
    scanf("%c", &matrix2[i][j]);
compress(matrix2);
break;

My code is suppose to take in a 5 x 10 matrix of char. But currently my newline is being input into the matrix, how do I actually check for the newline char, and prevent it from going into matrix2[i][j]?
It reads a total of 4 newline char.
Input:
aaabbbcccd (press enter)
ababababab (press enter)
bcdbcdbcdb (press enter)
ababababab (press enter)
abbbcccdda

A: You can add a space before your %c specifier, like this
scanf(" %c", &matrix2[i][j]);

The blank space here in the format string is telling scanf() to skip any leading whitespace or newline character, thus consuming the next character typed with the %c conversion specifier.
Your situtation is happening because when you (press enter), the next scanf() call is consuming this newline character \n that was left behind, therefore making your statement fail.

A: Add a space:
scanf(" %c", &matrix2[i][j]);
       ^

The space (unintuitively) consumes any white-space, including the \n. But this change means you can't put a space into matrix, which may or may not be what you want.
But it is generally better to use e.g. fgets() and sscanf() rather than scanf() to parse input.

A: char matrix2[SIZE1][SIZE2];
int ch, count, end, i, j;
char  *p = &matrix2[0][0];

printf("Enter your data (5x10) of characters: \n");
count = 0; end = SIZE1 * SIZE2;
while (EOF!=(ch=fgetc(stdin)) && count < end){
    if(ch == '\n')
        continue;
    p[count++] = ch;
}

A: you can store the i/p character in a dummy variable and then check if it is a space or a /n .
ie.
printf("Enter your data (5x10) of characters: \n");
for (i = 0; i < SIZE1; i++)
for (j = 0; j < SIZE2; j++)
{
  d:  scanf("%c", &a);
      if(a!=' '||a!='\n')
          matrix2[i][j]=a;
      else
          goto d;
}

compress(matrix2);
break;


text:
Q: Ubuntu License for companies I'm really concerned because a need to know if Ubuntu is totally free for a company. I mean, if I use a private software, I have to pay that license package, but Have I to pay for use Ubuntu? Have I to get a license?

A: Yes. Simply put Ubuntu is open source and free for anyone to use, including commercial use. Nice, huh!?
However looking at it more closely, you see that Ubuntu consists of a lot of individual packages and each can have its own license. That's important to keep in mind about redistributing software as not all software in all repositories is fully FOSS. See also my answer to Why are some programs in the Ubuntu Software Center not open source?.
I suggest you to read up on Ubuntu Licensing.

A: Ubuntu is typically free to use.  Canonical (the backers of Ubuntu) provide enterprise support for the Desktop, Cloud, and Server OS which costs money.  However, that's just part of an enterprise maintenance agreement.


text:
Q: Docker containers running memory intensive processes are terminated - Exit code 1 I am using gitlab CI to run triggered jobs on AWS K8S (EKS) and while running a long and memory/process intensive job, the container spun up to run that job gets terminated with an exit code 1.

I looked at the logs in /var/log/messages on the worker nodes and the below logs are a minute before I got the error.
Feb  7 04:11:15 ip-10-226-44-109 kubelet: I0207 04:11:15.614914    4804 reconciler.go:301] Volume detached for volume "repo" (UniqueName: "kubernetes.io/empty-dir/b8f0c962-495f-11ea-b638-0673fa95f662-repo") on node "ip-10-226-44-109.ap-southeast-2.compute.internal" DevicePath ""
Feb  7 04:11:16 ip-10-226-44-109 kernel: docker0: port 1(veth94e5db0) entered blocking state
Feb  7 04:11:16 ip-10-226-44-109 kernel: docker0: port 1(veth94e5db0) entered disabled state
Feb  7 04:11:16 ip-10-226-44-109 kernel: device veth94e5db0 entered promiscuous mode
Feb  7 04:11:16 ip-10-226-44-109 kernel: docker0: port 1(veth94e5db0) entered blocking state
Feb  7 04:11:16 ip-10-226-44-109 kernel: docker0: port 1(veth94e5db0) entered forwarding state
Feb  7 04:11:16 ip-10-226-44-109 kernel: docker0: port 1(veth94e5db0) entered disabled state
Feb  7 04:11:16 ip-10-226-44-109 kernel: eth0: renamed from vethae08789
Feb  7 04:11:16 ip-10-226-44-109 kernel: docker0: port 1(veth94e5db0) entered blocking state
Feb  7 04:11:16 ip-10-226-44-109 kernel: docker0: port 1(veth94e5db0) entered forwarding state
Feb  7 04:11:16 ip-10-226-44-109 kubelet: W0207 04:11:16.401374    4804 kubelet_getters.go:284] Path "/var/lib/kubelet/pods/b8f0c962-495f-11ea-b638-0673fa95f662/volumes" does not exist
Feb  7 04:11:16 ip-10-226-44-109 kubelet: W0207 04:11:16.401410    4804 kubelet_getters.go:284] Path "/var/lib/kubelet/pods/b9edf486-495f-11ea-b638-0673fa95f662/volumes" does not exist
Feb  7 04:11:16 ip-10-226-44-109 kernel: docker0: port 1(veth94e5db0) entered disabled state
Feb  7 04:11:16 ip-10-226-44-109 kernel: vethae08789: renamed from eth0
Feb  7 04:11:16 ip-10-226-44-109 kernel: docker0: port 1(veth94e5db0) entered disabled state
Feb  7 04:11:16 ip-10-226-44-109 kernel: device veth94e5db0 left promiscuous mode
Feb  7 04:11:16 ip-10-226-44-109 kernel: docker0: port 1(veth94e5db0) entered disabled state
Feb  7 04:11:59 ip-10-226-44-109 kubelet: I0207 04:11:59.379996    4804 reconciler.go:207] operationExecutor.VerifyControllerAttachedVolume started for volume "default-token-r26dz" (UniqueName: "kubernetes.io/secret/fc5d9f2e-495f-11ea-b638-0673fa95f662-default-token-r26dz") pod "runner-u4zrz1by-project-12123209-concurrent-44rwnh" (UID: "fc5d9f2e-495f-11ea-b638-0673fa95f662")
Feb  7 04:11:59 ip-10-226-44-109 kubelet: I0207 04:11:59.380025    4804 reconciler.go:207] operationExecutor.VerifyControllerAttachedVolume started for volume "repo" (UniqueName: "kubernetes.io/empty-dir/fc5d9f2e-495f-11ea-b638-0673fa95f662-repo") pod "runner-u4zrz1by-project-12123209-concurrent-44rwnh" (UID: "fc5d9f2e-495f-11ea-b638-0673fa95f662")
Feb  7 04:11:59 ip-10-226-44-109 systemd: Started Kubernetes transient mount for /var/lib/kubelet/pods/fc5d9f2e-495f-11ea-b638-0673fa95f662/volumes/kubernetes.io~secret/default-token-r26dz.
Feb  7 04:11:59 ip-10-226-44-109 systemd: Starting Kubernetes transient mount for /var/lib/kubelet/pods/fc5d9f2e-495f-11ea-b638-0673fa95f662/volumes/kubernetes.io~secret/default-token-r26dz.
Feb  7 04:11:59 ip-10-226-44-109 dockerd: time="2020-02-07T04:11:59Z" level=info msg="shim docker-containerd-shim started" address="/containerd-shim/moby/1921d53d580fc451fd2801dffc196a67e2970acbfbf2604ddf96b925bb7ecb88/shim.sock" debug=false pid=24408
Feb  7 04:12:00 ip-10-226-44-109 dockerd: time="2020-02-07T04:12:00Z" level=info msg="shim docker-containerd-shim started" address="/containerd-shim/moby/b9afda2153670e1427b562c33bd173039cea4e9adcd5433709fcdc31068fd9ff/shim.sock" debug=false pid=24533
Feb  7 04:12:00 ip-10-226-44-109 dockerd: time="2020-02-07T04:12:00Z" level=info msg="shim docker-containerd-shim started" address="/containerd-shim/moby/c0f4dcfd74f4eb53ba486e0844bbdea82bc177084fca8faa005ef2a04e3bfaab/shim.sock" debug=false pid=24600
Feb  7 04:12:00 ip-10-226-44-109 dockerd: time="2020-02-07T04:12:00Z" level=info msg="shim docker-containerd-shim started" address="/containerd-shim/moby/d887b7a2f86900d378c709c64c32faec99935753ff6525bf1992f1efc53cf8b4/shim.sock" debug=false pid=24668
Feb  7 04:12:00 ip-10-226-44-109 kubelet: I0207 04:12:00.481851    4804 reconciler.go:207] operationExecutor.VerifyControllerAttachedVolume started for volume "repo" (UniqueName: "kubernetes.io/empty-dir/fcff51c0-495f-11ea-b638-0673fa95f662-repo") pod "runner-u4zrz1by-project-12123209-concurrent-5tcz7v" (UID: "fcff51c0-495f-11ea-b638-0673fa95f662")
Feb  7 04:12:00 ip-10-226-44-109 kubelet: I0207 04:12:00.481889    4804 reconciler.go:207] operationExecutor.VerifyControllerAttachedVolume started for volume "default-token-r26dz" (UniqueName: "kubernetes.io/secret/fcff51c0-495f-11ea-b638-0673fa95f662-default-token-r26dz") pod "runner-u4zrz1by-project-12123209-concurrent-5tcz7v" (UID: "fcff51c0-495f-11ea-b638-0673fa95f662")
Feb  7 04:12:00 ip-10-226-44-109 systemd: Started Kubernetes transient mount for /var/lib/kubelet/pods/fcff51c0-495f-11ea-b638-0673fa95f662/volumes/kubernetes.io~secret/default-token-r26dz.
Feb  7 04:12:00 ip-10-226-44-109 systemd: Starting Kubernetes transient mount for /var/lib/kubelet/pods/fcff51c0-495f-11ea-b638-0673fa95f662/volumes/kubernetes.io~secret/default-token-r26dz.
Feb  7 04:12:00 ip-10-226-44-109 dockerd: time="2020-02-07T04:12:00Z" level=info msg="shim docker-containerd-shim started" address="/containerd-shim/moby/1c6ce43191ef995ceab9d237327071b6b8e7a57165f458c9f11960d51e47a07e/shim.sock" debug=false pid=24798
Feb  7 04:12:00 ip-10-226-44-109 dockerd: time="2020-02-07T04:12:00Z" level=info msg="shim docker-containerd-shim started" address="/containerd-shim/moby/d15361ee161d0c66bf02a8e009f0d8441608b372a3d0b1f305c5b6bb2cc0f12a/shim.sock" debug=false pid=24977
Feb  7 04:12:01 ip-10-226-44-109 dockerd: time="2020-02-07T04:12:01Z" level=info msg="shim docker-containerd-shim started" address="/containerd-shim/moby/53baa9364337b3d3bbd7fff3606fc985ed20586c293bf9a28e353f48474e8085/shim.sock" debug=false pid=25203
Feb  7 04:12:01 ip-10-226-44-109 dockerd: time="2020-02-07T04:12:01Z" level=info msg="shim docker-containerd-shim started" address="/containerd-shim/moby/962a39cfda64405c73872a5d5945dea879aa87873d088925edf600b6f1b6b321/shim.sock" debug=false pid=25269
Feb  7 04:12:01 ip-10-226-44-109 dockerd: time="2020-02-07T04:12:01Z" level=info msg="shim docker-containerd-shim started" address="/containerd-shim/moby/cc4ef0c7f4c512033c55888770a0477d1a1afa02b7d9611adaa0a03b3388a6ba/shim.sock" debug=false pid=25340
Feb  7 04:12:01 ip-10-226-44-109 dockerd: time="2020-02-07T04:12:01Z" level=info msg="shim docker-containerd-shim started" address="/containerd-shim/moby/4d871dc03e766baa5707c0bd6502c24333aab9263d52443d31e19ac080054d9d/shim.sock" debug=false pid=25463
Feb  7 04:12:05 ip-10-226-44-109 dockerd: time="2020-02-07T04:12:05Z" level=info msg="shim reaped" id=28b82bf41cfa344d616118007a8b9ac2440148b65dd76afb4124504c404e65a8
Feb  7 04:12:05 ip-10-226-44-109 dockerd: time="2020-02-07T04:12:05.663819264Z" level=info msg="ignoring event" module=libcontainerd namespace=moby topic=/tasks/delete type="*events.TaskDelete"
Feb  7 04:12:06 ip-10-226-44-109 dockerd: time="2020-02-07T04:12:06Z" level=info msg="shim reaped" id=3dab6902724b6639dfbcb5b546eb9b9e8f3131ac5d63453303955d8412f9e23b
Feb  7 04:12:06 ip-10-226-44-109 dockerd: time="2020-02-07T04:12:06.475126364Z" level=info msg="ignoring event" module=libcontainerd namespace=moby topic=/tasks/delete type="*events.TaskDelete"
Feb  7 04:12:06 ip-10-226-44-109 dockerd: time="2020-02-07T04:12:06.590951867Z" level=info msg="Container 245af759c17645d8fbad6fa86c83812aaf109db19a6271037bfdc2ddec1975c2 failed to exit within 2 seconds of signal 15 - using the force"
Feb  7 04:12:06 ip-10-226-44-109 dockerd: time="2020-02-07T04:12:06.590959536Z" level=info msg="Container 7a21f68defc90bacdd8db3bc2660d18b06801f4ea312befef01e8eb95d115d3b failed to exit within 2 seconds of signal 15 - using the force"
Feb  7 04:12:06 ip-10-226-44-109 dockerd: time="2020-02-07T04:12:06.598126562Z" level=info msg="Container 7a21f68defc90bacdd8db3bc2660d18b06801f4ea312befef01e8eb95d115d3b failed to exit within 2 seconds of signal 15 - using the force"
Feb  7 04:12:06 ip-10-226-44-109 dockerd: time="2020-02-07T04:12:06.600480653Z" level=info msg="Container 245af759c17645d8fbad6fa86c83812aaf109db19a6271037bfdc2ddec1975c2 failed to exit within 2 seconds of signal 15 - using the force"
Feb  7 04:12:06 ip-10-226-44-109 dockerd: time="2020-02-07T04:12:06Z" level=info msg="shim reaped" id=7a21f68defc90bacdd8db3bc2660d18b06801f4ea312befef01e8eb95d115d3b
Feb  7 04:12:06 ip-10-226-44-109 dockerd: time="2020-02-07T04:12:06.680421611Z" level=info msg="ignoring event" module=libcontainerd namespace=moby topic=/tasks/delete type="*events.TaskDelete"
Feb  7 04:12:06 ip-10-226-44-109 dockerd: time="2020-02-07T04:12:06Z" level=info msg="shim reaped" id=245af759c17645d8fbad6fa86c83812aaf109db19a6271037bfdc2ddec1975c2
Feb  7 04:12:06 ip-10-226-44-109 dockerd: time="2020-02-07T04:12:06.692681358Z" level=info msg="ignoring event" module=libcontainerd namespace=moby topic=/tasks/delete type="*events.TaskDelete"

What I did notice is that whenever a process is being terminated, I can see the below in the log:
Feb 10 01:30:42 ip-10-226-44-109 kernel: docker0: port 1(veth81ae14c) entered disabled state
Feb 10 01:30:42 ip-10-226-44-109 kernel: veth59985b4: renamed from eth0
Feb 10 01:30:42 ip-10-226-44-109 kernel: docker0: port 1(veth81ae14c) entered disabled state
Feb 10 01:30:42 ip-10-226-44-109 kernel: device veth81ae14c left promiscuous mode
Feb 10 01:30:42 ip-10-226-44-109 kernel: docker0: port 1(veth81ae14c) entered disabled state
Feb 10 01:30:43 ip-10-226-44-109 kernel: docker0: port 1(vethab14b48) entered disabled state
Feb 10 01:30:43 ip-10-226-44-109 kernel: veth43de279: renamed from eth0
Feb 10 01:30:43 ip-10-226-44-109 kernel: docker0: port 1(vethab14b48) entered disabled state
Feb 10 01:30:43 ip-10-226-44-109 kernel: device vethab14b48 left promiscuous mode
Feb 10 01:30:43 ip-10-226-44-109 kernel: docker0: port 1(vethab14b48) entered disabled state
Feb 10 01:30:43 ip-10-226-44-109 kernel: docker0: port 1(veth9b33ebc) entered blocking state
Feb 10 01:30:43 ip-10-226-44-109 kernel: docker0: port 1(veth9b33ebc) entered disabled state
Feb 10 01:30:43 ip-10-226-44-109 kernel: device veth9b33ebc entered promiscuous mode
Feb 10 01:30:43 ip-10-226-44-109 kernel: docker0: port 1(veth9b33ebc) entered blocking state
Feb 10 01:30:43 ip-10-226-44-109 kernel: docker0: port 1(veth9b33ebc) entered forwarding state
Feb 10 01:30:43 ip-10-226-44-109 kernel: docker0: port 1(veth9b33ebc) entered disabled state
Feb 10 01:30:44 ip-10-226-44-109 kernel: eth0: renamed from veth61422d0
Feb 10 01:30:44 ip-10-226-44-109 kernel: docker0: port 1(veth9b33ebc) entered blocking state
Feb 10 01:30:44 ip-10-226-44-109 kernel: docker0: port 1(veth9b33ebc) entered forwarding state
Feb 10 01:30:44 ip-10-226-44-109 kernel: docker0: port 1(veth9b33ebc) entered disabled state
Feb 10 01:30:44 ip-10-226-44-109 kernel: veth61422d0: renamed from eth0
Feb 10 01:30:44 ip-10-226-44-109 kernel: docker0: port 1(veth9b33ebc) entered disabled state

Could anyone help me understand the reason for this and a potential solution?
Thank you.


text:
Q: Is it normal that the component gets rendered twice when two state variables are updated? In my test app, every time a certain function is called, a call to my API is made (axios.get) and then two state variables are updated with the data received from the database. These two state variables both change a part of what is shown on the screen.
The things is, I added a useEffect hook to "debug" the amount of re-renders and I noticed that the component is re-rendered twice, I guess because it is once for one state variable and once for the other one. I thought using useReducer would change this, but it doesn't.
Is this a normal React behaviour or is there something I should be doing differently in order for the component is re-rendered only once?
Edit: I am editing to add the code:
(It's a trivia kind of test app, I'm new to React, so I am practicing)
import React, { useEffect, useReducer } from 'react'
import axios from 'axios'
import './App.css';
import reducer from './Reducer.js'

const initialState = {
    question: '',
    id: 1,
    choices: []
}

const Questions = () => {

    const [state, dispatch] = useReducer(reducer, initialState)

    useEffect(() => {
        console.log('executed');
    })

    const getQuestion = async (e) => {

        try {
            e.preventDefault()

            const res = await axios.get(`/questions/${state.id}`)

            dispatch({
                type: 'set_question',
                payload:
                    res.data.question
            })
            dispatch({
                type: 'set_choices',
                payload:
                    [res.data.correct_answer,
                    res.data.incorrect_answer1,
                    res.data.incorrect_answer2]
            })

        } catch (err) {
            console.log(err);
        }
    }

    return (

            <form onSubmit={getQuestion}>
                <button>Get next question</button>
            </form>

 {state.question ? state.question : null}

            <button> {state.choices ? `${state.choices[0]}` : null}</button>
            <button> {state.choices ? ` ${state.choices[1]}` : null}</button>
            <button> {state.choices ? ` ${state.choices[2]}` : null}</button>

    )
}

export default Questions

Reducer:
const reducer = (state, action) => {

    switch (action.type) {

        case 'set_question':
            return {
                ...state,
                question: action.payload
            }

        case 'set_choices':
            return {
                ...state,
                choices: action.payload
            }

        default:
            return state

    }
}

export default reducer

A: React only batches state updates in event handlers and lifecycle methods. If the state updates happen in an async function e.g. in response of a successful call to fetch or a setTimeout they will not be batched. This is announced to change in a future version of react.
Also see this answer from Dan Abramov about this:
https://stackoverflow.com/a/48610973/5005177

However, both in React 16 and earlier versions, there is yet no batching by default outside of React event handlers. So if in your example we had an AJAX response handler instead of handleClick, each setState() would be processed immediately as it happens. In this case, yes, you would see an intermediate state.
promise.then(() => {
    // We're not in an event handler, so these are flushed separately.
    this.setState({a: true}); // Re-renders with {a: true, b: false }
    this.setState({b: true}); // Re-renders with {a: true, b: true }
    this.props.setParentState(); // Re-renders the parent
});

If you want your component to re-render only once you have to keep all the data in a single state object so that you only have to call setState once (or dispatch if you want to use useReducer) with the new data.
Another workaround is to wrap your block of state updates in ReactDOM.unstable_batchedUpdates(() => {...}), which will most likely not be required anymore in a future version of react. Also see the answer of Dan Abramov from above for details.


text:
Q: Flask-SQLAlchemy: Update a One to Many Relationship I have two Models:
class Project(db.Model):
    __tablename__ = 'project'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64))
    timestamp = db.Column(db.DateTime)
    info = db.Column(db.Text(255))

    post = db.relationship('Post', backref=db.backref('projects'))

class Post(db.Model):
    __tablename__ = 'post'

    id = db.Column(db.Integer, primary_key=True)
    headline = db.Column(db.String(64))
    content = db.Column(db.Text(255))
    timestamp = db.Column(db.DateTime)

    projectId = db.Column(db.Integer, db.ForeignKey('project.id'))

If I, e.g., create an instance of post and append it to a project via projectInstance.append(post(headline="...", content="..."))
 Now  I want to update the project to which the post should belong to. Is there an easier way besides querying the desired project, append the post to it and remove it from the old project?
oldProject.remove(post)
newProject.append(post)

A: Do it the other way around: use the back reference in Post:
post.projects = newProject

This'll handle the required session management. Here's a minimal example:
In [2]: class A(Base):
   ...:     __tablename__ = 'a'
   ...:     id = Column(Integer, primary_key=True, autoincrement=True)
   ...:     bs = relationship('B', backref='a')
   ...:

In [3]: class B(Base):
   ...:     __tablename__ = 'b'
   ...:     id = Column(Integer, primary_key=True, autoincrement=True)
   ...:     a_id = Column(Integer, ForeignKey('a.id'))
   ...:

In [5]: a1 = A()

In [6]: a2 = A()

In [7]: b = B()

In [8]: a1.bs.append(b)

In [9]: a1.bs
Out[9]: [<__main__.B at 0x7f7322fb52b0>]

In [10]: b.a = a2

In [11]: a1.bs, a2.bs
Out[11]: ([], [<__main__.B at 0x7f7322fb52b0>])

Also just appending the post instance to the newProject.post collection handles removing automatically, as can be seen with our as and bs:
In [9]: a1.bs.append(b)

In [10]: a1.bs, a2.bs
Out[10]: ([<__main__.B at 0x7f26702565f8>], [])

In [11]: a2.bs.append(b)

In [12]: a1.bs, a2.bs
Out[12]: ([], [<__main__.B at 0x7f26702565f8>])


text:
Q: Adding a generic parameter to an Action delegate I'm adding a new feature to an existing code base and I can see the following line,
public class Consumer
{
    private readonly Dictionary<string, List<Action<byte[], ulong, int>>> _source = new Dictionary<string, List<Action<byte[], ulong, int>>>();
    public void RegisterSource(string source, Action<byte[], ulong, int> onEvent)
    {
        lock (source)
        {
            List<Action<byte[], ulong, int>> sources;

            if (this._source.TryGetValue(source, out sources))
            {
                sources.Add(onEvent);
            }
            else
            {
                var subscriptionList = new List<Action<byte[], ulong, int>>();
                subscriptionList.Add(onEvent);

                this._source.Add(source, subscriptionList);
            }
        }
    }
}

There are adding to this dictionary on an event. My requirement is that this _source dictionary should also allow adding Actions of different parameters like Action<byte[], ulong, List<string>>. I tried declaring the dictionary like below,
private readonly Dictionary<string, List<Action<byte[], ulong, object>>> _source = new Dictionary<string, List<Action<byte[], ulong, object>>>();

But I'm still facing issues. Is it possible to do this?


text:
Q: Queue using several processes to launch bash jobs I need to run many (hundreds) commands in shell, but I only want to have a maximum of 4 processes running (from the queue) at once. Each process will last several hours.
When a process finishes I want the next command to be "popped" from the queue and executed.
I also want to be able to add more process after the beginning, and it will be great if I could remove some jobs from the queue, or at least empty the queue.
I have seen solutions using makefile, but this only work if I have all my list of commands before the beginning. Also tried using mkfifo sjobq, and others, but I never could reach my needs...
Does anyone have code to solve this problem?
Edit: In response to Mark Setchell
The solution with tail -f and parallel is almost perfect, but when I do it, it always keep not launching the last 4 commands until I add more, and so on, I don't know why, and it is quite troublesome...
As for Redis, good solution also, but it takes more time to master all of it.
Thanks !

A: Use GNU Parallel to make a job queue like this:
# Clear out file containing job queue
> jobqueue

# Start GNU Parallel processing jobs from queue
#   -k   means "keep" output in order
#   -j 4 means run 4 jobs at a time
tail -f jobqueue | parallel -k -j 4

# From another terminal, submit 40 jobs to the queue
for i in {1..40}; do echo "sleep 5;date +'%H:%M:%S Job $i'"; done >> jobqueue

Another option is to use REDIS - see my answer here Run several jobs parallelly and Efficiently


text:
Q: I want to find the reason why my soft keyboard will not dismiss In my android application, I have a dialog in one fragment and this dialog contains a edittext, I use showSoftInput to let soft keyboard showing. But when I tap outside the dialog(not tap the keyboard button or edittext), the dialog should dismiss and it does. The weird thing is when the phone in portrait view the softkeybaord will not dismiss following the dialog but in landscape view the softkeyboard dismiss.
Anyone meets this case? And I find this in the android developer website:Note: Once the input method is visible, you should not programmatically hide it. The system hides the input method when the user finishes the task in the text field or the user can hide it with a system control (such as with the Back button)

A: I got one more solution to hide keyboard
InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
Add this on tap outside

A: I have found my root reason, it is because the host activity set:
android:windowSoftInputMode="stateHidden|adjustResize".
After I remove this, my problem is solved.


text:
Q: Python/selenium webscraping for link in data_links:
    driver.get(link)
review_dict = {}
# get the size of company
size = driver.find_element_by_xpath('//[@id="EmpBasicInfo"]//span')

#location = ??? need to get this part as well.
my concern:
I am trying to scrape a website. I am using selenium/python to scrape the "501 to 1000 employees" and "Biotech & Pharmaceuticals" from the span, but I am not able to extract the text element from the website using xpath.I have tried getText, get attribute everything. Please, help!
This is the output for each iteration:I am not getting the text value.
Thank you in advance!

A: It seems you want only the text, instead of interacting with some element, one solution is to use BeautifulSoup to parse the html for you, with selenium getting the code built by JavaScript, you should first get the html content with html = driver.page_source, and then you can do something like:
html ='''

Industry
Woodcliff

Size
501 to 1000 employees

'''  # Just a sample, since I don't have the actual page to interact with.
soup = BeautifulSoup(html, 'html.parser')
>>> soup.find("div", {"id":"EmpBasicInfo"}).findAll("div", {"class":"infoEntity"})[2].find("span").text
'501 to 1000 employees'

Or, of course, avoiding specific indexing and looking for the Size, it should be more readable:
>>> [a.span.text for a in soup.findAll("div", {"class":"infoEntity"}) if (a.label and a.label.text == 'Size')]
['501 to 1000 employees']

Using selenium you can do:
>>> driver.find_element_by_xpath("//*[@id='EmpBasicInfo']/div[1]/div/div[3]/span").text
'501 to 1000 employees'


text:
Q: Read Cyrillic Characters I have an xml file.
This file has attributes and the values are in Cyrillic.
How I can read this xml file?
Ex Xml:
<Ships>
    <Ship X="3" Y="Г" Length="3" Orientation="vertical" />
    <Ship X="7" Y="А" Length="2" Orientation="horizontal" />
    <Ship X="10" Y="Ж" Length="1" />
</Ships>

A: How about using Linq To Xml
var xDoc = XDocument.Parse(xmlstring);//or XDocument.Load(filename);
var ships = xDoc.Descendants("Ship")
                .Select(s => new
                {
                    X = (string)s.Attribute("X"),
                    Y = (string)s.Attribute("Y"),
                    Orientation = (string)s.Attribute("Orientation"),
                    Length = (string)s.Attribute("Length"),
                })
                .ToList();

A: use xsd.exe as already described here
you can find it under

C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\xsd.exe

or

C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\xsd.exe

A: This just worked for me:
        var doc = new XmlDocument();
        XmlReader reader = XmlReader.Create(new StreamReader(@"..\..\filename.xml", Encoding.UTF8));
        doc.Load(reader);

        var ships = doc.SelectNodes(@"//Ship");


text:
Q: SharePoint list exported from access always shows datasheet list view web part I have exported data from the access table to SharePoint 2010 list.
I have created different views of the same list and want to put on the Site Page. When I am adding the list view web part to the page it always shows up in the datasheet view. The views are not appearing in the standard view pattern on the page.
What should I do to get the data in standard view?


text:
Q: How to get coordinates of field within the visible screen when scroll is used? ( Blackberry, BB, Java ) 1)the field placed in manager has fixed position in that manager.
2)when user scrolls the screen the field is moving along the visible screen, (although his position within manager remains fixed).
How to get these visible-screen-coordinates of the field when user scrolls the view and sets focus on the field?
P.S. They might be called 'absolute coordinates'
Thanks!

A: Not sure if it can help you. Have you looked at getFocusRect(XYRect xyrect)? When child field gets foucs, retreive extent of the manager's focus region. API says that

getFocusRect

public void getFocusRect(XYRect rect)
Retrieves current extent of the focus.
Invoke this method to retrieve the extent of the current focus region. Notice that the coordinates expressed are local to this manager, and take scrolling into account (that is, the coordinates are local to the manager's visible region, not the virtual region).
Overrides:
getFocusRect in class Field
Parameters:
rect - Rect to contain extent of focus.
http://www.blackberry.com/developers/docs/5.0.0api/net/rim/device/api/ui/Manager.html#getFocusRect(net.rim.device.api.ui.XYRect)

A: found solution:
XYRect rc = new XYRect(0,0,1,1);
_myField.getScreen().getFocusRect(rc);


text:
Q: Declaring two-dimensional array locally and storing on heap with non-constant size In C when you declare e.g. int ar[x][y]; it actually is int[x*y], and you calls are compiled in needed manner.
But this array is stored on stack if made inside a function.
I'm looking for a way to have it stored on heap, while having the same functionality. Because when I was looking for a way to do is, the only thing I found was make int** and then each of element (type int*) would be pointer to another array. (Correct me if I'm wrong) It seems legit but the second way doesn't store the values one after another and also uses more memory. For ar[x][y] first method is just x*y*sizeof(int), but for second it's x*y*sizeof(int)+x*sizeof(int*).
Summarizing is having two-dimensional array stored on heap possible, while maintaining functionality of int ar[x][y]?
EDIT: I'm sorry for misleading everyone, but ar[3][4] was just en example, I'm actually looking for a way to do this with non-constant size.
EDIT2: Actually I'm even looking for sth that will also work in raw C.

A: If at least one of the sizes is known at compile time, you can use standard C++ containers:
 using my2daraytype  = std::array<std::array<int, N>, M>; // both N and M are compile time constants
 // allocate this on the heap normally (e.g. with std::make_unique)
 // example
 auto myarray = std::make_unique<my2daraytype>();

Note that myarray above is a (smart) pointer to a 2d array, so you access it as (*myarray)[i][i].
 using my2daraytype = std::vector<std::array<int, N>>; // inner size N is known
 // data already lives on the heap, no need to allocate
 // example
 my2darraytype myarray(M);

This one is not a pointer so you use myarray[i][j].
When both sizes are determined at run time, this is not so easy. std::vector<std::vector<int>> memory is organised similarly to int** so it is not suitable. You may want to create your own class that stores std::vector<int> of size M*N internally, and provide a two-argument int& operator()(size_t, size_t) for indexing. The familiar syntax with two levels of square brackets is possible but too complicated and potentially inefficient, so it's rarely worth the trouble. myarray(i,j) works perfectly so just use that.
Here's one possible basic outline of the class (unfinished, unteated) templatized for convenience:
template <class T>
class my2darray {
    std::vector<T> values;
    size_t m, n;
   public:
     my2darray(size_t m, size_t n) : values(m*n), m(m), n(n) {}
     T& operator()(size_t i, size_t j) {
          return values[i*n+j];
      }
};

It needs more code to be fully functional but this is the basis.


text:
Q: Find row in dataframe including index and output as an arrray Simple Example with df dataframe:
df=

    A    B    C
0  1.4 -0.2 -1.9
1 -0.2 -0.3  0.1
2  0.5 -0.6  0.2
3  1.9  0.4  1.9

I want now to generate the desired output in array form of a specific row, for example the first row:
out = [0, 1.4, -0.2, -1.9]

With df.values[0] I get the first data row in an array form, but loose the index:
out = [1.4, -0.2, -1.9]

Is there a command to generate directly the desired output?


text:
Q: Ordinals: Is $0^\beta = 0?$ Let $\beta$ be a (non-empty) ordinal.
Is $0^\beta = 0?$ Or is it $1$?
My definition is the following: let $\alpha, \beta$ ordinals
$\alpha^0= 1$, $\alpha^{\beta+1} = \alpha^\beta \alpha, \alpha^\beta = \bigcup_{\eta < \beta} \alpha^\eta$ if $\beta$ is a non-zero limit ordinal.
From this definition, it would seem that $0^0 = 1$, $0^1 = 1. 0=0, \dots$
$$0^\omega= \bigcup_{\eta <\omega}\alpha^\eta= 1$$???
These results don't seem to make sense.


text:
Q: Layout Alignment Issues For Device to Device
*

*When I try to run my project on LG Android Mobile then there is no alignment issues come with this device it is a 3.2 HVGA but when I try to run it on Motorola it is a 3.7 WVGA then it gives complete layout alignment issues so can you tell me suggestion to implement layouts uniquely to every device.

*I don't know is it possible or not to make a unique layout design for all devices.

A: You can't create custom layouts for different devices, but you can for different screen densities and sizes, Supporting Multiple Screens has all of the information you should need.

A: Sometimes back I was having this type of problem. Because I was using Pixels as my unit to specify height, width or any layout specific dimensions. But I changed those px to dp and it worked for me. I got same layout for all the screens. Hope if this may help you anyways...

A: Here is a quick checklist about how you can ensure that your application displays properly on different screens:
1.Use wrap_content, fill_parent, or dp units when specifying dimensions in an XML layout file
2.Do not use hard coded pixel values in your application code
3.Do not use AbsoluteLayout (it's deprecated)
4.Supply alternative bitmap drawables for different screen densities

A: You can create custom layouts by reading the device layout screen like this
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();

There are two ways you can create your layout. You can create your own algorithm that checks the difference between the resolution you have made your layout for, and gets the difference for the current screen size, and adjust all those values progmatically (long and tedious, but DEFINETELY will work on all devices)
Or, you can define a layout for each of the common devices in your layout folder. This requires alot more space and time though.


text:
Q: Remove inline styles from Create React App I am working on a React application which is built using Create React App. I am having some trouble with CSS in my application. The CSS in dev mode is not consistent with CSS in production mode. Some CSS is inline in dev mode, under multiple <style> tags under <head>. But the same CSS is in a separate file in prod mode. This is causing some unexpected over-rides, which in turn is causing some CSS issues in production. Is there a way to completely remove all inline CSS from both dev and prod so that the behaviour is consistent everywhere?
I believe the issue is with how webpack is bundling the application in these modes.
Note: I don't want to eject my create-react-app.


text:
Q: ODBC SQL Server driver error I have a VB6 app that access's a database thru a ODBC Connection.  It will run fine for a few hours then I get the following Error. Any Ideas?
[Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionWrite(WrapperWrite())

A: Does your program have to reach across a network to get to the Access file?
If so I'd look into any intermittent network connectivity issues, especially if your program is always connected to the data source.
Check any logs you can to see what's happening on your network at the time of the error.
If possible change your app to connect to the data source only when you need to access it and then disconnect when done.
Is there more than one instance of the program running on the same and/or different machines?  If so, do they all get the error at the same time?
If possible try to have more than one instance of you program running on the same machine and see if they all get the error at the same time.
Also:
Does the error happen about the same amount of time after initial connection?
Does the error happen about the same amount of inactivity in your application?

A: From Googling the error, it sounds like that's just ADO's way of saying it can't connect - that the server is unreachable. Are there are any other services on that server or that use the database that become unavailable at the same time as this error? It sounds like the client is just losing its connection, so I'd look for anything around that - dropped network connectivity, or a downed/overwhelmed server, to name a few examples.


text:
Q: GUID Generation When is the GUID generated for a VB6 DLL? I believe it is generated automatically when a DLL is registered.  However, I have found references online to APIs that allow you to generate GUIDs in code.

A: Interface, type, and class GUIDs are created by the compiler.  But GUIDs are used for lots of things in Windows besides component registration, including unique ID values for rows in database tables.


text:
Q: Probability of Jar containing Balls type question with replacement A jar has 50 balls 1 to 50 each one having distinct number written on it. Bob, owner of the jar,each day he takes out one ball out of the jar randomly ( with equal probability) and put it back.
Q1. How many days on average  will it take until all 50 balls are taken out? (Note that the same ball can be picked on more than one days)
Q2. Assume that 3 months after Bob started this activity, how many distinct balls will have been taken out by Bob?

A: Q1 is known on Wikipedia as the Coupon collector's problem
This is a Geometric distribution with variable rate.  It can be considered as a sequence of independent processes with stepped rate, i.e. with the rate constant changing only after each 'unique' ball is drawn.
Q1. When K balls are known, the rate of discovery of "new" balls with replacement is rate=(N-K)/N and the expected time to a "new ball" event is 1/rate = N/(N-K).
We need to set N=50 and sum the expected times from K=0..(N-1)
Expected time to complete = 50/50 + 50/49 + 50/48 + ... + 50/1
In python this is: sum([50.0/(k+0.0) for k in range(1,51)])
I get ~ 224.96
As for Q2, I would suggest Monte Carlo simulation.


text:
Q: PHP select statement with bind I'm trying to validate a sign-up form through PHP, with prepared statements and bind parameters, like this:
$email = $_POST['email'];
$password = $_POST['password'];
$selectStatement = "SELECT id FROM users WHERE email = ? ";
$stmts = mysqli_prepare($dbc, $selectStatement);
mysqli_stmt_bind_param($stmts,'s', $email);
mysqli_stmt_execute($stmts);
$count = mysqli_stmt_num_rows($stmts);

if (!$stmts){
    die('mysqli error: '.mysqli_error($dbc));
}
while($row = mysqli_stmt_fetch($stmts)){
    if($row != null){
        echo('User already registered!');
    }
    }else{
        $insertQuery = "INSERT INTO users(email, password) VALUES(?, ?)";
        $stmtI = mysqli_prepare($dbc, $insertQuery);
        mysqli_stmt_bind_param($stmtI, "ss", $email, $password);
        mysqli_stmt_execute($stmtI);
        echo('Registration completed!');
}
}
mysqli_stmt_close($stmts);
mysqli_stmt_close($stmtI);
mysqli_close($dbc);

But when no user is found in the database, it's supposed to go on the else branch, yet, apparently it's not getting there, not even in the while loop. What am i doing wrong?

A: While loop is only execute when records found from database (mysqli_stmt_fetch($stmts))
You have to change your code like this
$email = $_POST['email'];
$password = $_POST['password']; $selectStatement = "SELECT id FROM users WHERE email = ? ";
$stmts = mysqli_prepare($dbc, $selectStatement);
mysqli_stmt_bind_param($stmts,'s', $email);
mysqli_stmt_execute($stmts);
$count = mysqli_stmt_num_rows($stmts);
if (!$stmts){ die('mysqli error: '.mysqli_error($dbc));
}
    if($count){
            echo('User already registered!');
    }else{
            $insertQuery = "INSERT INTO users(email, password) VALUES(?, ?)";
            $stmtI = mysqli_prepare($dbc, $insertQuery);
            mysqli_stmt_bind_param($stmtI, "ss", $email, $password);
            mysqli_stmt_execute($stmtI);
            echo('Registration completed!');
    }

A: Your code is Wrong ... at
}
}else{

only write
}else{

try this
$email = $_POST['email'];
$password = $_POST['password'];
$selectStatement = "SELECT id FROM users WHERE email = ? ";
$stmts = mysqli_prepare($dbc, $selectStatement);
mysqli_stmt_bind_param($stmts,'s', $email);
mysqli_stmt_execute($stmts);
$count = mysqli_stmt_num_rows($stmts);

if (!$stmts){
    die('mysqli error: '.mysqli_error($dbc));
 }
while($row = mysqli_stmt_fetch($stmts)){
if($count == 1){
    echo('User already registered!');
}else{
    $insertQuery = "INSERT INTO users(email, password) VALUES(?, ?)";
    $stmtI = mysqli_prepare($dbc, $insertQuery);
    mysqli_stmt_bind_param($stmtI, "ss", $email, $password);
    mysqli_stmt_execute($stmtI);
    echo('Registration completed!');
    }
}
mysqli_stmt_close($stmts);
mysqli_stmt_close($stmtI);
mysqli_close($dbc);


text:
Q: Why this simple web server is called even number times? I'm trying to learn Go web programming, and here is a simple web server: it prints out the times being called.
package main

import (
  "fmt"
  "net/http"
)

var calls int

// HelloWorld print the times being called.
func HelloWorld(w http.ResponseWriter, r *http.Request){
    calls++
    fmt.Fprintf(w, "You've called me %d times", calls)
}

func main() {
  fmt.Printf("Started server at http://localhost%v.\n", 5000)
  http.HandleFunc("/", HelloWorld)
  http.ListenAndServe(":5000", nil)
}

When I refresh the page, I got:
You've called me 1 times
You've called me 3 times
You've called me 5 times
....

Question: Why it is 1, 3, 5 times, rather than 1,2,3...? What's the order of the function HelloWorld being called?

A: It is because every incoming request is routed to your HelloWorld() handler function, and the browser makes multiple calls under the hood, specifically to /favicon.ico.
And since your web server does not send back a valid favicon, it will request it again when you refresh the page in the browser.
Try it with Chrome: open the Developer tools (CTRL+SHIFT+I), and choose the "Network" tab. Hit refresh, and you will see 2 new entries:
Name          Status   Type
--------------------------------------------------------
localhost     200      document
favicon.ico   200      text/plain

Since your counter starts with 0 (default value for type int), you increment it once and you send back 1. Then the request for favicon.ico increments it again (2), but the result is not displayed. Then if you refresh, it gets incremented again to 3 and you send that back, etc.
Also note that multiple goroutines can serve requests concurrently, so your solution has a race. You should synchronize access to the calls variable, or use the sync/atomic package to increment the counter safely, for example:
var calls int64

func HelloWorld(w http.ResponseWriter, r *http.Request) {
    count := atomic.AddInt64(&calls, 1)
    fmt.Fprintf(w, "You've called me %d times", count)
}

A simple "fix" to achieve what you want would be to check the request path, and if it is not the root "/", don't increment, e.g.:
func HelloWorld(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path != "/" {
        return
    }
    count := atomic.AddInt64(&calls, 1)
    fmt.Fprintf(w, "You've called me %d times", count)
}

You may also choose to only exclude requests for favicon.ico, e.g.:
if r.URL.Path == "/favicon.ico" {
    return
}


text:
Q: Incorrect Reputation Calculation in Achievements Dialog The reputation gain shows +1, when I really gained +35.  Is this a timing bug?

Potentially related: Mobile Web shows wrong Reputation earned in Recent Achievements
This is not a duplicate of Recent achievements shows +1, but nothing listed.  That question is about getting +1 back from deleted posts.  While this may have been the case, it does not explain the missing "new" rep gained.  As I understand it, the dialog should show +36 if that were the case.

A: I figured out what happened.
A question was deleted where I had a positively-scoring answer (+2 and an accept, for 35 reputation).  I also had downvoted one of the other answers (-1).
I had earned +35 rep this morning, but that rep was cancelled out by the -35 from the deleted post.  The only remaining rep was the +1 from the removal of the downvoted post, yielding a +1 net for the day so far.

(the +10 for the NSUserDefaults question occurred after these events, and was not part of the original calculation of +1)
Not a bug, just an interesting order of events.


text:
Q: How can I combine different AndroidManifest.xml files to use different plugins/libraries? I'm making a Unity application for Android and I'm using Vuforia and Easy Code Scanner. Their Unity packages both come with iOS and Android compiled libraries. For the Android version of the libraries, both of them have a proper AndroidManifest.xml file. As far as I know, only one manifest per app is allowed, but to be able to use both of them I need in some way to combine them.
Having the plugins in the proper place but using just one manifest, will generate an activity not found exception.
I tried to combine the 2 xml files by myself but I failed. Can you please give me some hints in how to perform this action?
Thank you very much.

A: As suggested by the Android Developers here's the general scheme.
<?xml version="1.0" encoding="utf-8"?>

<manifest>

    <uses-permission />
    <permission />
    <permission-tree />
    <permission-group />
    <instrumentation />
    <uses-sdk />
    <uses-configuration />
    <uses-feature />
    <supports-screens />
    <compatible-screens />
    <supports-gl-texture />

    <application>

        <activity>
            <intent-filter>
                <action />
                <category />
                <data />
            </intent-filter>
            <meta-data />
        </activity>

        <activity-alias>
            <intent-filter> . . . </intent-filter>
            <meta-data />
        </activity-alias>

        <service>
            <intent-filter> . . . </intent-filter>
            <meta-data/>
        </service>

        <receiver>
            <intent-filter> . . . </intent-filter>
            <meta-data />
        </receiver>

        <provider>
            <grant-uri-permission />
            <meta-data />
            <path-permission />
        </provider>

        <uses-library />

    </application>

</manifest>

Well... in my case the same application was defined 2 times but with different configurations. What I did is to give priority to QCAR. I have merged the configurations by adding everything that were missed in the application defined for Vuforia.
After that I copied all the activities from both the manifests and past them into the application. You should check that every activity is defined only once: if the same activity is defined in both the manifests, just proceed to merge them as done for the application.
Hope those hints could be useful for someone else  :)


text:
Q: How to render a option of select element - reactjs I wrote this function to make a tree options.
makeTreeOption(tree) {
    let ouput = `<optgroup label="${tree.title}">`;
    if (tree['children']) {
      tree.children.forEach(children => {
        if (children['children']) {
          ouput += this.makeTreeOption(children);
        } else {
          ouput += `<option>${children.title}</option>`;
        }
      });
    }
    ouput += `</optgroup>`;
    return ouput;
  }

but when I want to render it:
  <select>
       {this.makeTreeOption(data)}
  </select>

it returns this:

A: Rather than building a string you need the makeTreeOption method to return JSX. Something like:
function makeTreeOption(tree) {
    return <optgroup /*...optgroup props */>{
        tree.children.map(
            child => child.children
                ? makeTreeOption(child)
                : <option /* ...option props */>{ child.title }</option>
        )
    }</optgroup>
}


text:
Q: Default Content Type + Deserialization errors I have configured my AppHost with JSON as the default content type. Unfortunately in situations when ServiceStack fails to deserialize the request into the corresponding DTO it responds with an application/xml content. Here's an example response (I've omitted most of the message and stacktrace element values for brevity):
<UpsertResponse xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="">
    <ResponseStatus>
        <ErrorCode>SerializationException</ErrorCode>
        <Message>Could not deserialize 'application/xml' request using ...</Message>
        <StackTrace>at ServiceStack.WebHost.Endpoints.Support.EndpointHandlerBase.CreateContentTypeRequest(IHttpRequest httpReq, Type requestType, String contentType)...</StackTrace>
    </ResponseStatus>
</UpsertResponse>

I guess the response is encoded that way because the request was sending 'application/xml' content. Is there a way to force (or hook into) ServiceStack to use the default content type?
A bit more conext - not only does my service uses JSON as the default content type, but it (tries to) ensures that JSON is the only accepted content type via a global request filter, which checks Accept/Content-type headers during each read/write and short-circuits the request with a 400 response when the content type is not 'application/json'.


text:
Q: Azure Mobile Services: no data tab I am trying to create a simple table in Azure Mobile Services so that my c# Windows Phone App can utilize a high score table. However, though it appears in every example I find online, there is no "Data" tab inside my mobile service I created on Azure where I can create that table. They removed it or something, but there is no documentation whatsoever. Anyone know what's going on?
Thanks.

A: You probably chose to use a .NET backend (as opposed to JavaScript).  When you do so, the DATA and API tabs are not visible in the portal.  This is because both your data access and custom API's are part of your Visual Studio solution and have to be deployed from there.  If you want to use the Javascript backend where you create your tables, APIs, and edit their scripts in the portal, you'll need to create a new Mobile Service and choose Javascript as the backend.

A: When you first create a mobile service, you won't have [any data in the] data tab. The easiest way to get started is to choose one of the sample app templates (iOS, Android, Windows Phone, Windows 8, HTML, Xamarin, PhoneGap). You should see an option then, to download the client app. There should also be an option to set up a default bit of data (the todoitem table). Once this is done, you should see the Data tab.
This isn't the only way to create data, but it's the simplest, especially when first starting out.


text:
Q: How to disable the blue lines in Firefox, when developer tools are ON When we turn on dev tools in Firefox, especially the 'inspector', and we select some element, Firefox marks the element in the main view. This also happens, when we console.log(someHtmlElement) and then we hover over it in the console.
This is usually useful but not always. So my question is, how to tell Firefox to not show the highlight/guides for those elements?
Here is a screenshot to illustrate what I mean:


text:
Q: Replication between three servers I have a 2 way replication (merge) between 2 servers, Let's say between server A and server B
Can i add another server and make another 2 way replication (between server A and the new server c) ?

A: Yes. The canonical use case for merge replication is a set of disconnected clients that need to synchronize with a master database at corporate headquarters. In your example, A is the headquarters and B & C are the disconnected clients.


text:
Q: Finding transformation matrix given the image vector and pre-image vector For $$A = \begin{bmatrix}a&-b\\ b&a\end{bmatrix}$$
find $a$ and $b$ such that $T(12,5) = (13,0)$.
I can't figure out how to set this problem up to solve it. I've tried row reducing an augmented matrix after I made a system of linear equations but that didn't work.
Update
I used the system of equations
a - b = 12
a + b = 5
and then row reduced the augmented matrix of that system. When I plugged those solutions into the original transformation matrix A and multiplied it by (12,5), it didn't give me the (13,0) result.

A: Hint 1: What is $T(12,5)$? Can you write down a formula for it, in terms of $a$ and $b$?
Hint 2: Now set
$$T(12,5) = \left[\begin{array}{c}13\\0\end{array}\right].$$
This is a pair of equations with two unknowns. Can you solve it?


text:
Q: Angular state management - Store or Stateful services? We currently have a medium-large Angular 6 (prod bundle = 5MB) application with ngrx/store as state management implemented.
We choose ngrx/store because at the time (NG2) everybody used it and it seemed like a good idea to store state and access state this way.
In other words: the wrong reasons.
It feels more and more like a layer of indirection which isn't required, since services can hold state and return streams to access parts of the application state with much less boilerplate (even with NGXS).
Question
From an architectural point of view, why would we choose ngrx/store or NGXS over plain stateful services?
Please only real-world arguments, no theoretical or purist arguments.
If handled properly a few plain @Injectable services with a few streams result in clean code, no boilerplate code, and full responsibility of state. Even immutability can easily be handled ourselves.
(Yes I know there are some technical advantages if you get them working properly like restoring state in HMR and inspecting state, but we never got that consistently and properly working )

A: There are several good reasons to use NgRX:
1) It prevents you from needing lots of little services all over, which are much harder to manage and track than the single NgRx store.
2) The store provides a client-side cache so you don't need to re-get the data from the server every time ... only when you need to. And yes, you can do that in your own service as well, just with more code.
3) Using selectors, any component can be easily notified of any change to a specific piece of data, making notifications across the system easy ... even when changing to multiple pages. Again, you can do this in your own service using Subject/BehaviorSubject, but why reinvent the wheel.
4) There is a standard pattern and flow that can be generated using the Angular CLI, making it easier to ensure that all of the code of your application remains consistent.
5) You can use the debugging tools to easily see what's going on. At my last several talks many devs wanted to move to NgRX just for this feature. :-) You said you had trouble getting that to work properly?


text:
Q: How to prove the proportionality of a scalene triangle that fits inside another scalene triangle? I'm trying to help my son prepare for an exam. I am many years out of school. How can I prove the below proportionality assertion, and explain the solution coherently? Any outside references are welcome, such as YouTube videos, etc. I need to relearn this material too if I am to be of any help.
I believe we are dealing with scalene triangles! One nested inside another.

A: Notice that $\vec{HE}=a-b$ and $\vec{HX}=\frac14 \vec{HE}$.
So we have $\vec{DX}=\vec{DH}+\vec{HX}=b+\frac14(a-b)=\frac14a+\frac34b$.


text:
Q: ARM Darwin assembly -- looking for system calls (tutorial perhaps) So I took up assembly programming. It's quite simple on my Ubuntu box: using NASMamd GNU ld, I were able to write more or less complicated HelloWorld-style programs in half an hour.
But when it comes to the iPhone, it's so complicated. First of all, I have a JB'en iPhone 3G on 4.2.1 firmware, which means that I use the ARM port of the Darwin kernel v10.
Second. I have to use GNU as, as there's no NASM for iPhone: the native toolchain (both Xcode on Mac OS X and the opensource tooolchain on linux) use GCC.
So I have gathered together basic info about:
 - how to write assembly in GNU as language;
 - what are the basic ARM instructions, registers, memory access.
But even HelloWorld requires kernel calls for writing to stdout. My question is: what kernel call to use and how (what arguments go where); I should use the swi # ARM instruction, shouldn't I?
So, can you please post some info/links to tutorials, or somebody with an ARM Darwin Hello world asm code?
As of now, I could do this:
;Hello World for Linux and NASM
section data
hello db "Hello World"
helloLen equ $ - hello

section text
global _start
_start:
    mov eax, 4 ; sys_write
    mov ebx, 1 ; to stdout
    mov ecx, hello ; address of string
    mov edx, helloLen ; value (because of eq!!!) of strLen
    int 0x80 ; call awesome Linux kernel

    mov eax, 1 ; sys_exit
    mov ebx, 0 ; "return 0; " if you like C
    int 0x80 ; call kernel to end program

on ARM, however, I could only do like this:
.text
start:
    mov r0, #0
    mov r1, #234
    add r2, r0, r1
@all mov and add and other stuff works fine
    swi #0xc00
@all that I get is Bad system call error

So, anybody please?

A: Here's how libc (libSystem) does it:
; ssize_t read(int, void *, size_t)
                EXPORT _read
_read
                MOV     R12, #3         ; SYS_read
                SVC     0x80 ; 'А'      ; do a syscall
                BCC     _ok             ; carry clear = no error
                LDR     R12, =(cerror_ptr - . - 8) ; otherwise call error handler
                LDR     R12, [PC,R12]   ; load pointer
                B       _call_error
                DCD cerror_ptr - .
_call_error
                BX      R12 ; cerror    ; jump to it (error number is in R0)
_ok
                BX      LR              ; return to caller
; End of function _read

I.e.:

*

*System call number is in R12 (see sys/syscall.h).

*System call instruction is SVC 0x80 (SWI 0x80).

*Other parameters are according to the ABI (R0-R3, then stack).

*On error, carry flag is set and error number is returned in R0.

A: Best I can find right quick and yea I realize the initial post is old
http://blog.softboysxp.com/post/7888230192/a-minimal-168-byte-mach-o-arm-executable-for-ios
.text
.globl start

start:
mov r2, #14
adr r1, hello_str
mov r0, #1
mov r12, #4
swi 0x80

mov r0, #0
mov r12, #1
swi 0x80

hello_str:
.ascii  "Hello, World!\n"

compile:
as new.asm -o new.o
ld new.o -o new
./new


text:
Q: Graphing Inequalities in matplotlib python I'm looking to create a program that will randomly generate lines (that are inequalities) and that will show the area that satisfies the constraints. If possible axes would go from 10 to -10 but I'm not too bothered if this is not possible.
I've tried a few things but I have no code that is really worth showing but I will show some code that I found that shows the kind of thing I'm looking for.
Let me know if you want anymore infomation.
import numpy as np
import matplotlib.pyplot as plt

x_1 = np.linspace(0, 30, 1000)
x_2 = np.linspace(0, 30, 1000)

# plot
fig, ax = plt.subplots()
fig.set_size_inches(14.7, 8.27)

# draw constraints
plt.axvline(7, color='g', label=r'$x_1 \geq 7$') # constraint 1
plt.axhline(8, color='r', label=r'$x_2 \geq 8$') # constraint 2
plt.plot(x_1, (2*(x_1)), label=r'$x_2 \leq 2x_1$') # constraint 3
plt.plot(x_1, 25 - (1.5*x_1), label=r'$1.5x_1 + x_2 \leq 25$') # constraint 4

plt.xlim((0, 25))
plt.ylim((0, 30))
plt.xlabel(r'Number of keyboards ($x_1$)')
plt.ylabel(r'Number of mice ($x_2$)')

# fill in the feasible region
plt.fill_between(x_1, np.minimum(25 - (1.5*x_1), (2*(x_1))), np.minimum(25 - (1.5*x_1), 8),
where=x_1 >= 7,
color='green', alpha=0.25)
plt.legend(bbox_to_anchor=(1, 1), loc=1, borderaxespad=0.)

# Hide the right and top spines
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
plt.grid()
plt.show()