text:
Q: Best practice: Spring Autowired, concrete class, and Builder We have an interface:
public interface NotifyService {

  public void send();

And a class that implements it
public class EmailNotifyService implements NotifyService {

  private EmailBuilder _builder;

  @Autowired
  PersonRepository _personRepository;

  ... other Autowired Repositories ...

  public EmailNotifyService(EmailBuilder builder) {
   this._builder = builder;
  }

  public void send() {
    // send mail using _builder.getRecipient().getEmailAddress(), etc.
  }

We used to instantiate EmailNotifyService with a builder:
public class EmailBuilder {

  private Person _recipient;

  private EmailType _type;

  private Event _event;

  public EmailNotifyService build() {
    return new EmailNotifyService(this);
  }

  public EmailBuilder recipient(Person recipient) {
    this._recipient = recipient;
    return this;
  }

... and so on. But now, instead of using build() to create a new EmailNotifyService, we are trying to use Autowire with Spring instead. The problem is that everywhere else in our app, we are Autowiring interfaces, not classes. And from what I've read it's a good idea in general. In fact, I've tried rewriting the NotifyService to be an Abstract class, and then have EmailNotifyService just extend it. But Spring isn't Autowiring it correctly, it doesn't create a Proxy like it does for interfaces, and all of my Autowired fields are null.
So it would seem we're stuck with Autowiring the NotifyService interface. Fine. What I can't get my head around is - how can I get the data I used to assign with the builder -- the Person, EmailType and Event -- into a Spring Autowired interface?
I suppose I could change the interface definition to have a setPerson(), setEmailType(), etc., but apart from being really ugly, it defeats the purpose of using an interface in the first place. A different NotifyService (WebServiceNotifyService or RestNotifyService for example) night not have need for that info.
Is there any elegant, best-practice way to do this?
Thanks.
EDIT
I am using annotations, very little xml. And I am also using transaction management, which might explain why the abstract class isn't properly autowired? This is the only pertitnent info I have in xml:
<context:annotation-config />
<context:component-scan base-package="com.myco.myapp" />
<tx:annotation-driven transaction-manager="transactionManager"/>

What I mean when I say "autowiring isn't working correctly" is that when I try to autowire the abstract class, Spring doesn't seem to be creating a Proxy like it does for interfaces, and all the Autowired fields in my EmailNotifyService (PersonRepository, others ...) are null. When I use an interface, all the Autowired fields are wired correctly.
But my main problem is that I used to work explicitly with a concrete class, using a builder to create a new EmailNotifyService() directly, and pass it info -- Person, EmailType and Event. These are just normal beans. There are no setters/getters for them in EmailNotifyService but there are the EmailBuilder, which used to live inside EmailNotifyService.
But now I am using the NotifyService interface, which knows nothing about Person, EmailType or Event. But I need this info in order for EmailNotifyService to work.
So my question is, if I use Spring to Autowire my EmailNotifyService like this:
@Autowired
@Qualifier("email") // so Spring knows I want to use the EmailNotifyService implementation
NotifyService _notifyService

How can I set the Person, EmailType and Event data, since NotifyService knows nothing about them?
Currently we are using the mailer service within a web app but theoretically the mailer service should be able to work stand-alone. Regardless, I don't see how request scoped beans can help me here.

A: Robert what do you mean by not autowiring correctly? Are you getting any error?
Generally both interface and class auto-wiring works in Spring unless you have some autoproxy configured example @Transactional.
You do not need to have setPerson(), setEmailType(), etc. in your interface but have them autowired in the concrete class which requires them.
But seems Person is not a service but a bean which holds data and its specific to a request. If yours is a web application then look at request scope proxy to inject Person like bean.

So you are using transactions which is why class based injection is failing. Add proxy-target-class="true" to tx:annotation-driven.
Regarding your injection of Person and EmailType then you have to do that to the bean EmailNotifyService. In EmailNotifyService I do not see any Person or EmailType variables defined. Also read what I said about Person bean above.

Your design is not correct. You should not make EmailBuilder a bean and look to autowire to the EmailNotifyService. Instead in EmailNotifyService you should have a method send(EmailBuilder builder) where you pass the builder which you created somewhere dynamically.


text:
Q: How to emulate a natural swipe in AngularJS All:
I am trying to use $swipe or ngSwipeLeft/Right, what I want to do is emulate a natural swipe like in Tinder or Okcupid:  If you fast swipe, it will lead to a remove of image, but if you slowly swipe, it still be able to cancel this swipe action?
Thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: galen: how to wait dynamic new page with same url I started working with Galen and I had this test that was working perfectly:
this.HomePage = $page('Welcome Page', {
    aboutButton: 'nav.navbar .about'
});

this.AboutPage = $page('About page', {
    modalContent: 'div.modal-content',
    supportLink: '.support-link',
    dismissButton: '.dismiss'
});

var homePage = new HomePage(driver);
homePage.waitForIt();
homePage.aboutButton.click();

var aboutPage = new AboutPage(driver);
aboutPage.waitForIt();

I understand that the waitForIt method waits for all the attributes defined by page so the framework knows when to execute the next statement.
Now, I want to run this as a grunt task and I've been using grunt-galenframework, and I configured it correctly, everything is working, but I can't make the previous test pass, the task code is as follows:
load('../gl.js');

forAll(config.getDevices(), function (device) {
    test('simple test on ' + device.deviceName, function () {
        gl.openPage(device, config.getProjectPage(), "Welcome Page", {
            aboutButton: 'nav.navbar .about'
        });

        elements.aboutButton.click();

        // MISSING WAIT FOR ABOUT_PAGE

        gl.runSpecFile(device, './test/responsive/galen/about.gspec');
    });
});

As you can see, I get into the Welcome Page and then I need to click a button, wait for a dialog to appear, and then check the about.gspec specs (they verify elements inside the dialog).
So how can I add a wait for new elements to appear on the same URL? it feels like grunt-galenframework only offers wait when entering a new url, with the openPage method.

A: you could try
elements.newElement.waitToBeShown()

The methods from here should be available.
PS: I'm the author of the grunt plugin for Galen and also involved in the development of the Galen Framework itself


text: Q: Configure Manifest To Suppress Webkitdirectory Warning in Chrome extension? When uploading files using the webkitdirectory option in an HTML <input> tag, chrome and other browsers warn a user of how many files they will be uploading. I am developing a chrome extension, and I was wondering if there is any permission that can be added to my extension's manifest that will suppress this warning, as the entire extension is based around this functionality and it gets annoying granting permission again and again to my own extension.


text:
Q: Visual Constraints in Objective-c Now I am developing an app, where I use visual constraints.
So question is how to make square subview?
For example:
I have superview with frame (320 width, 568 height) then I add subview. The frame of this subview should be (320 width, 320 height).
Thank you in advance

A: You can add a constraint for the view's width to equal it's superview's width and another constraint for the view to have a 1:1 ratio of width to height.

A: Sadly, this isn't possible to do visually in IB.  In old versions of Xcode, this was not possible in IB.
However, even in those cases, you can easily add a constraint in code (see the documentation here) to achieve it.
You want something like:
[NSLayoutConstraint constraintWithItem: self
                             attribute: NSLayoutAttributeWidth
                             relatedBy: NSLayoutRelationEqual
                                toItem: self
                             attribute: NSLayoutAttributeHeight
                            multiplier: 1
                               constant:0]


text:
Q: Removing a slot on a child button click I've been trying to remove a slot from a child button click, but I can't seem to get it to work.  E.G.
flow do
  button("X") {parent.remove}
end

Any suggestions?

A: Shoes' blocks are sometimes tricky.  The key here is to ask yourself, what is the parent method being called upon?  self, of course.  And self references the app (or window, or dialog), not the button.
There are two similar ways to get around this.  First, you can create a reference to the button to use in the block:
flow do
  a = button("X") {a.parent.remove}
end

Or, you could just reference the slot itself:
b = flow do
  button("X") {b.remove}
end


text:
Q: Why does system("cls") not work correctly in Python as writing some weird arrow character? So I have an odd bug which instead of making console clear writes that character.
That issue doesn't occur in C, and everything works normally when I write cls in command prompt window. (I am not an advanced programmer, but I suppose that system() is related with it.)
Edit: (When I use clear, it does completely nothing.) Perhaps that problem is not related to wrong keyword (I use Windows), it just didn't do what I was expecting because of drawing that weird arrow character.
Edit2: I reinstalled whole vs with phyton, and it doesn't worked
Edit3: resolved : "Windows Command Prompt shortcut doesn't work correctly (Ctrl + L)

from os import system

while True :
    print(" #")
    system("cls")

A: try this function to clear the screen regardless of OS
from os import system, name
def clear():
    if name == 'nt':
        x = system('cls')
    else:
        x = system('clear')

or you could try using subprocess:
from subprocess import call

def clear():
    x = call('clear' if os.name =='posix' else 'cls')

Other than that I think it would be some problem with your terminal


text:
Q: Checking multiple columns from a table against a column in another table Table A
Name,
Address,
...,
Item1,
Item2,
...,
Item10
Table B
ProductID
I want to run an SQL statement (in access) to Select all records where any item ([Item1] - [Item10]) that does not match a Product code found in [ProductID] in Table B. I am trying to catch all errors in the file before I export it into our inventory software and it can not find the item and we have to start over.
I have been trying to make a LEFT JOIN work but with no success.

A: For [TableA]...
ID  Name   Item1     Item2     Item3
--  -----  --------  --------  --------
 1  Name1  Product1  Product2  Product3
 2  Name2  Product2
 3  Name3  Product1  Product4
 4  Name4  Product1  Produtc2  Product3

...and [TableB]...
ProductID
---------
Product1
Product2
Product3

...the query...
SELECT * FROM TableA
WHERE IIf(IsNull(Item1), False, DCount("*", "TableB", "ProductID='" & Item1 & "'") = 0)
    Or IIf(IsNull(Item2), False, DCount("*", "TableB", "ProductID='" & Item2 & "'") = 0)
    Or IIf(IsNull(Item3), False, DCount("*", "TableB", "ProductID='" & Item3 & "'") = 0)

...produces:
ID  Name   Item1     Item2     Item3
--  -----  --------  --------  --------
 3  Name3  Product1  Product4
 4  Name4  Product1  Produtc2  Product3


text:
Q: Sum of columns in c# arrays static int[,] matrix ={
                          { 4, 6, 9, 2, 5, 7},
                          { 4, 7, 5, 3, 7, 5},
                          { 4, 2, 6, 9, 1, 6}

                         };

static int rowLength = matrix.GetLength(0);
static int colLength = matrix.GetLength(1);

public static void Main(string[] args) {
            displayMatrix();
            Console.ReadKey();

        }//end Main

static void displayMatrix() { // Display The matrix
for (int i = 0; i < rowLength; i++) {
                for (int j = 0; j < colLength; j++) {
                    Console.Write(string.Format("{0} ", matrix[i, j]));
                }
                Console.Write(Environment.NewLine + Environment.NewLine);
            }
        }// end displayMatrix

I'm stumped on how to calculate the sum of each column, I then want to display the column sum with maximum value.
I'm not sure whether to use a set of nested functions inside my already existing function, or create another array storing the column sum results? (matrix is also subject to modifications)

A: for each column I did this. Don't forget declare int iValue=0; and int y=0.
    public void TryThis()
    {
        for (int x = 0; x < matrix.GetLength(1); x++)
        {
            for (y = 0; y < matrix.GetLength(0); y++)
            {
                iValue = iValue + matrix[y, x];
            }
            textBox1.Text =textBox1.Text+ ("Colum " + x + " Sum=" + iValue);
            iValue = 0;
        }
    }


text:
Q: Bash code eliminacion de datos Tengo un código mas arriba en el que recojo los datos por pantalla y los añado a sus respectivos array, el problema surge cuando le digo que si que quiero volver a meter mas, llego a meter hasta 5 pero al meter 6 se me borran, el marcador de total de proceso me muestra  que hay 6 pero no me muestra los 6 procesos introducidos, se han borrado y al meter el Séptimos vuelve a empezar desde 1 proceso y así sucesivamente.
Acabo de añadir el código entero del método que lee por pantalla, el problema es que me hace la lectura bien me lo almacena bien pero al llegar a 6 se elimina todo
        lectura_datos(){
    # NOS SERVIRA PARA RECORRER TODOS LOS PROCESOS
    seguir=`expr 1`
    i=`expr 0`
    # PARA CREAR LA TABLA
    j=`expr 0`
    o=`expr 1`

    # PARA ALMACENAR EL NUMERO DE PROCESOS
    echo "      >> Numero de procesos: $numProcesos" >> informe.txt

    # PARA ALMACENAR EL QUANTUM
    read -p "Introduce el quantum de ejecución: " quantum

    while ! mayor_cero $quantum
    do
        echo "Entrada no válida"
        read -p "Introduce el quantum de ejecución: " quantum
    done
    echo -n $quantum >> entrada.txt
    printf '\n'>>entrada.txt

    echo "      >> Quantum de tiempo: $quantum" >> informe.txt
    clear
    while [[ seguir -eq 1 ]] ;
    do
        echo $COLOR
        if [ $o -eq 0 ];
        then
            read -p "Introduce Tiempo de llegada del P$o: " tiempollegada
        else
            if [ $o -lt 10 ];
            then
                read -p "Introduce Tiempo de llegada del P0$o: " tiempollegada
            else
                read -p "Introduce Tiempo de llegada del P$o: " tiempollegada
            fi
        fi
        if [ -z $tiempollegada ]; # Si la entrada está vacía, valor por defecto 0
            then
            tiempollegada=`expr 1`
            else
            # COMPROBACIÓN DE LECTURA
                while ! es_entero $tiempollegada
                do
                    echo "Entrada no válida"
                    if [ $o -eq 0 ];
                    then
                        read -p "Introduce Tiempo de llegada del P$o: " tiempollegada
                    else
                        if [ $o -lt 10 ];
                        then
                            read -p "Introduce Tiempo de llegada del P0$o: " tiempollegada
                        else
                            read -p "Introduce Tiempo de llegada del P$o: " tiempollegada
                        fi
                    fi
                    if [ -z $tiempollegada ]; then # Si la entrada está vacía, valor por defecto 0
                        tiempollegada=`expr 1`
                    fi
                done
            fi
        # Lo pasamos al array
        tiempo_llegada[$i]=`expr $tiempollegada`

        if [ $o -eq 0 ];
        then
            read -p "Introduce la rafaga de P$o: " raf
        else
            if [ $o -lt 10 ];
            then
                read -p "Introduce la rafaga de P0$o: " raf
            else
                read -p "Introduce la rafaga de P$o: " raf
            fi
        fi

        if [ -z $raf ]; then # Si la entrada está vacía, valor por defecto 0
                raf=`expr 1`
            else
            # COMPROBACIÓN DE LECTURA
                while ! es_entero $raf
                do
                    echo "Entrada no válida"

                    if [ $o -eq 0 ];
                    then
                        read -p "Introduce la rafaga de P$o: " raf
                    else
                        if [ $o -lt 10 ];
                        then
                            read -p "Introduce la rafaga de P0$o: " raf
                        else
                            read -p "Introduce la rafaga de P$o: " raf
                        fi
                    fi

                    if [ -z $raf ] # Si la entrada está vacía, valor por defecto 0
                    then
                        raf=`expr 1`
                    fi
                done

                while ! mayor_cero $raf
                do
                    echo "Entrada no válida"

                    if [ $o -eq 0 ];
                    then
                        read -p "Introduce la rafaga de P$i: " raf
                    else
                        if [ $o -lt 10 ];
                        then
                            read -p "Introduce la rafaga de P0$o: " raf
                        else
                            read -p "Introduce la rafaga de P$o: " raf
                        fi
                    fi

                    if [ -z $raf ] # Si la entrada está vacía, valor por defecto 0
                    then
                        raf=`expr 1`
                    fi
                done
            fi
        # Lo pasamos al array
        rafaga[$i]=`expr $raf`

        if [ $o -eq 0 ];
        then
            read -p "Introduce el tamaño P$o: " tam
        else
            if [ $o -lt 10 ];
            then
                read -p "Introduce el tamaño P0$o: " tam
            else
                read -p "Introduce el tamaño P$o: " tam
            fi
        fi

        if [ -z $tam ]; then # Si la entrada está vacía, valor por defecto 0
                tam=`expr 1`
            else
            # COMPROBACIÓN DE LECTURA
                while ! es_entero $tam
                do
                    echo "Entrada no válida"

                    if [ $o -eq 0 ];
                    then
                        read -p "Introduce el tamaño P$o: " tam
                    else
                        if [ $o -lt 10 ];
                        then
                            read -p "Introduce el tamaño P0$o: " tam
                        else
                            read -p "Introduce el tamaño P$o: " tam
                        fi
                    fi

                    if [ -z $tam ]; then # Si la entrada está vacía, valor por defecto 0
                        tam=`expr 1`
                    fi
                done
            fi

        # LO PASAMOS AL ARRAY
        tamano[$i]=`expr $tam`
        echo -n "$tiempollegada $raf $tam" >> entrada.txt
        printf '\n'>>entrada.txt
        clear
        ordenar $i
        i=`expr $i + 1`
        o=`expr $o + 1`
        numProcesos=`expr $i`
        iniciar_colores
        nProceso=`expr 1`
        echo "$NORMAL""$VERDE"
        echo "$NORMAL""$VERDE##################################"
        echo    ">>>>> Quantum: "$quantum
        echo    ">>>>> Total proceso: "$numProcesos
        echo "$NORMAL""$VERDE##################################"
            echo "$NORMAL""$VERDE Rej Tll Tej Mem $NORMAL"
            for (( j = 0 ; j <$i ; j++ ))do
                tiempos_ejecucion[$j]=`expr 0`
                enumProceso[$j]=$nProceso
                if [ ${enumProceso[$j]} -le 9 ] && [ ${enumProceso[$j]} -ge 0 ]; then
                        str="${colores_procesos[$j]} P0"${enumProceso[$j]}
                    else
                        str="${colores_procesos[$j]} P"${enumProceso[$j]}
                    fi
                    if [ ${tiempo_llegada[$j]} -le 9 ] && [ ${tiempo_llegada[$j]} -ge 0 ]; then
                        str=$str" "${tiempo_llegada[$j]}" "
                    else
                        str=$str" "${tiempo_llegada[$j]}
                    fi

                    if [ ${rafaga[$j]} -le 9 ] && [ ${rafaga[$j]} -ge 0 ]; then
                        str=$str"  "${rafaga[$j]}" "
                    else
                        str=$str"  "${rafaga[$j]}
                    fi

                    if [ ${tamano[$j]} -le 9 ] && [ ${tamano[$j]} -ge 0 ]; then
                        str=$str"  "${tamano[$j]}"$NORMAL"
                    else
                        str=$str"  "${tamano[$j]}"$NORMAL"

                    fi
                    echo -e "$str"
                nProceso=$((nProceso+1))
            done
            echo "$NORMAL""$VERDE##################################$NORMAL"
            echo

        error_seguir=1
        while [[ error_seguir -eq 1 ]]
        do
            read -t 300 -p "Añadir nuevo proceso  1-Si / 2-No "  seguir
            if [[ $seguir -eq 1 || $seguir -eq 2 ]]
            then
                error_seguir=0
            else
                echo "Error en la entrada de datos. Introduce un numero valido"
            fi
        done
    done

    #ORDEANR $i
    i=`expr $i - 1` # PARA QUE EN EL BUCLE DE ABAJO FUNCIONE EN EL INFORME
    #PARA EL INFORME
    echo "" >>informe.txt
    echo "               ----ORDEN DE ENTRADA EN LA MEMORIA----">>informe.txt
    echo "" >>informe.txt
    echo "                  Proceso  tiempo  rafaga  tamaño" >>informe.txt
    for (( j = 0; j <=$i ; j++ ))
    do
            echo "                  P"${orden[$j]}"        "${tiempo_llegada[orden[$j]]}"        "${rafaga[orden[$j]]}"       "${tamano[orden[$j]]} >>informe.txt
        done
  }


text:
Q: Deleted certificates keep returning in Key Chain I have deleted all developer and distribution certificates from the Developer site and from my Key Chain but some cerificates still keep returning into my Key Chain. Why might that be?

A: One thing I discovered with the keychain when removing a certificate is that if I remove it from the certificate section the certificate is not "really" removed, but if choose "all elements" and from there I delete the certificate then it works... maybe it does not work for you but you can try

A: The problem is most likely caused by keys, associated with those certs, that are still in your keychain.
If Using Xcode 4...
Xcode 4 was supposed to allow one to manage their signing certs, but it was always wonky for me. Here is how I handled this issue last May.
Go to Keychain Access -> My Certificates and search for "iPhone". Your Developer and Distribution certs will show-up, old and current. Expand the certs that you don't want and you'll see the keys associated with those certs. Deleting the keys associated with the certs you want to delete is....well, key.
I think you can delete the keys in "My Certificates". If not, just go to "Keys", find and delete those rogue keys.
If none of your signing certificates are valid after this, then you will have to regenerate the signing certificates. Creating Your Signing Certificates will show you how to do that.
If Using Xcode 5...
Xcode 5 is, according to Apple, the way to manage certificates. You can of course still do this manually, as detailed in Creating Your Signing Certificates. But in Xcode 5, Preferences, Account, signing-in to your dev account and then View Details... will take you to an area where you can manage your signing certs.
If someone has a better way of handling this, please chime-in.


text:
Q: Java android: Error when Pause and Resume MediaPlayer on AsyncTask in activity I am trying to Pause and Resume a mp3 playback using a MediaPlayer playing in the background using AsyncTask.
Here is the Activity code:
public class MainActivity extends Activity implements SensorEventListener
{
    private MyGLSurfaceView mGLSurfaceView2;
    private SensorManager mSensorManager;
    private Sensor mAccelerometer;
    private Sensor mGyro;

    BackgroundSound mBackgroundSound = new BackgroundSound();

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        this.mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
        this.mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        this.mGyro = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
        mGLSurfaceView2 = new MyGLSurfaceView(this);

        setContentView(mGLSurfaceView2);
        mBackgroundSound.execute();
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
        mSensorManager.registerListener(this, mGyro, SensorManager.SENSOR_DELAY_NORMAL);
        if(mBackgroundSound.player != null)
            if(mBackgroundSound.player.isPlaying()==false)
                mBackgroundSound.player.start();
        mGLSurfaceView2.onResume();
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        mSensorManager.unregisterListener(this);
        if(mBackgroundSound.player.isPlaying())
        {
            mBackgroundSound.player.pause();
        }
        mBackgroundSound.player.release();
        //    mBackgroundSound.cancel(true);
        mGLSurfaceView2.onPause();
    }

    public class BackgroundSound extends AsyncTask<Void, Void, Void> {

        MediaPlayer player;

        @Override
        protected Void doInBackground(Void... params) {

            AssetFileDescriptor afd;
            player = new MediaPlayer();

            try {
                afd = getAssets().openFd("2/sound.mp3");

                if (afd != null) {
                    player.setDataSource(afd.getFileDescriptor());
                    player.prepare();
                    player.setLooping(true);
                    player.setVolume(1.0f, 1.0f);
                    //player.start();
                } else {
                    Log.i("Error", "afd is null.");
                }

            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }
    }
}

logcat Error:
E/MediaPlayer: start called in state 1
E/MediaPlayer: error (-38, 0)
E/MediaPlayer: Error (-38,0)

If I move the mBackgroundSound.execute(); to onResume() the mp3 starts playing but the onResume() obviously fails the second time it is executed (when resuming the app).
I need help putting the following commands in the correct method for it to work properly (MP3 pauses when APP is minimized and resumes or restarts when APP resumes again):
mBackgroundSound.execute();
mBackgroundSound.cancel(true);
mBackgroundSound.player.start();
mBackgroundSound.player.pause();
mBackgroundSound.player.release();

Thanks!

A: I figured it out right after asking. I guess I must recreate the AsyncTask everytime resuming. Working code (MP3 restart from beginning when resuming App):
public class MainActivity extends Activity implements SensorEventListener
{
    private MediaPlayer player;
    private volatile boolean mMediaPlayerStopped;

    BackgroundSound mBackgroundSound;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        startMediaPlayer();
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        stopMediaPlayer();
    }

    private void stopMediaPlayer() {
        Log.v("Music", "Stop MediaPlayer") ;
        mMediaPlayerStopped = true ;
        if (player != null) {
            player.stop() ;
            player.reset() ;
            player.release() ;
            player = null ;
            mBackgroundSound.cancel(true);
        }
    }

    private void startMediaPlayer() {
        Log.v("Music", "Start MediaPlayer") ;
        mMediaPlayerStopped = false;
        mBackgroundSound= new BackgroundSound();
        mBackgroundSound.execute();
    }

    public class BackgroundSound extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {

            AssetFileDescriptor afd;
            MediaPlayer mediaPlayer = new MediaPlayer();

            try {
                afd = getAssets().openFd("2/music.mp3");

                if (afd != null) {
                    mediaPlayer.setDataSource(afd.getFileDescriptor());
                    mediaPlayer.prepare();
                    mediaPlayer.setLooping(true); // Set looping
                    mediaPlayer.setVolume(1.0f, 1.0f);
                    mediaPlayer.start();

                    player = mediaPlayer ;

                    if (mMediaPlayerStopped) {
                        Log.v("Music", "MediaPlayer was stopped while preparing") ;
                        stopMediaPlayer();
                    }

                } else {
                    Log.i("Error", "afd is null.");
                }

            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }
    }
}


text:
Q: Algebraic way of checking if two rectangle overlap? In a 2d plane, there exists a few different algorithms checking if two rectangles overlap.
I'm wondering if there exists an algebraic way of doing so? Of course, it would matter a lot on how to represent the rectangles, let's assume there are top left and bottom right coordinates for each rectangle given: $(TL_{11}, TL_{12}), (BR_{11}, BR_{12}), (TL_{21}, TL_{22}), (BR_{21}, BR_{22})$.
Can one construct an algebraic way to determine if two rectangles overlap?

A: If the rectangles overlap you have two possible arrangements:

*

*They intersect in at least one edge

*One rectangle is contained in the other one

For 1. calculate the intersections of the lines defined by the coordinates and and vectors. If for two such lines the intersection parameters are between $0$ and $1$ you have such an intersection.
For 2. Note that this is exactly the case if all lines of the inner rectangule intersect the outer one outside of the inner one, but in two opposing places in the outer one.
So the algorithm would be: Suppose R1 is given by the nodes $a_1$, $a_2$, $a_3$, $a_4$ and let $v_1:=a_2-a_1,v_2=a_3-a_2,v_3=a_4-a_3,v_4=a_1-a_4$ and similarly R2 by $b_1,\ldots,b_4$ and $w_1,\ldots,w_4$.
For each pair of lines $l_i = a_i+tv_i$ and $r_j=b_j+hw_j$ calculate the intersection $t,h$. If for one such pair $0\leq t,h\leq 1$ they overlap, and if for all $i$ we have two $j$ with $0\leq h_j \leq 1$ and $\mathrm{sgn}(t_{j_1}) = -\mathrm{sgn}(t_{j_2})$ then R1 lies in  R2.


text:
Q: Code First Does not work I am trying to add code first,but the App_Data folder is empty.
Web.config
<connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-Movie-20170604111514.mdf;Initial Catalog=aspnet-Movie-20170604111514;Integrated Security=True"
          providerName="System.Data.SqlClient" />
    <add name="MovieDBContext" connectionString="Data Source=(localDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True"
          providerName="System.Data.SqlClient" />
</connectionStrings>

Model
public class MovieDBContext : DbContext
{
    public DbSet<Movie> Movies { get; set; }
}

Can anyone help me ? Thanks in advance.

A: You need to add a constructor in your MovieDBContext class as following:
public class MovieDBContext : DbContext
{
    public MovieDBContext () : base("Name=MovieDBContext")
    {
    }

    public DbSet<Movie> Movies { get; set; }
}

For more detail you can read following link:
http://www.entityframeworktutorial.net/code-first/entity-framework-code-first.aspx


text:
Q: Where Do Xcode Default Flags Come From? Motivation
Xcode provides the ability to manipulate whatever compiler/linker toolchain is needed, but default Xcode configuration assumes Mac SDK and adds a number of default flags that do not appear anywhere in the project itself.
If these flags could be disabled/removed, Xcode's native build system could be used to control foreign compilers/toolchains such as xtensa-elf-gcc and surrounding tools, while gaining the benefit of Xcode's code highlighting and clang's analytics. This would be a strongly preferable option to the external makefile option that Xcode supports directly, which does not integrate particularly nicely with the rest of Xcode.
Motivation TL;DR
If Xcode's default flags could be disabled, Xcode could directly support compiling code for the ESP8266 (using CC=xtensa-elf-gcc).
The default flags (which assume Mac OS) are not supported by xtensa-elf-gcc and prevent its use.
The flags are the only reason this does not work.
Example
The most basic compilation produces a clang command with these flags:

-x c
-arch x86_64
-fmessage-length=0
-fdiagnostics-show-note-include-stack
-fmacro-backtrace-limit=0
-std=gnu99
-Wno-trigraphs
-fpascal-strings
-O0
-fno-common
-Wno-missing-field-initializers
-Wno-missing-prototypes
-Werror=return-type
-Wdocumentation
-Wunreachable-code
-Werror=deprecated-objc-isa-usage
-Werror=objc-root-class
-Wno-missing-braces
-Wparentheses
-Wswitch
-Wunused-function
-Wno-unused-label
-Wno-unused-parameter
-Wunused-variable
-Wunused-value
-Wempty-body
-Wconditional-uninitialized
-Wno-unknown-pragmas
-Wno-shadow
-Wno-four-char-constants
-Wno-conversion
-Wconstant-conversion
-Wint-conversion
-Wbool-conversion
-Wenum-conversion
-Wshorten-64-to-32
-Wpointer-sign
-Wno-newline-eof
-DDEBUG=1
-isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk
-fasm-blocks
-fstrict-aliasing
-Wdeprecated-declarations
-mmacosx-version-min=10.12
-g
-Wno-sign-conversion
-Winfinite-recursion
-iquote [generated-files.hmap]
-I[own-target-headers.hmap]
-I[all-target-headers.hmap]
-iquote [project-headers.hmap]
-I[Build/Products/Debug/include]
-I[Build/Intermediates/libESP8266.build/Debug/libESP8266.build/DerivedSources/x86_64]
-I[Build/Intermediates/libESP8266.build/Debug/libESP8266.build/DerivedSources]
-F[Build/Products/Debug]
-MMD
-MT dependencies
-MF [Build/Intermediates/libESP8266.build/Debug/libESP8266.build/Objects-normal/x86_64/main.d]
--serialize-diagnostics [Build/Intermediates/libESP8266.build/Debug/libESP8266.build/Objects-normal/x86_64/main.dia]
-c /Users/asher/Projects/Arduino/libESP8266/main.c
-o [main.o]

Obviously a few of these are more or less necessary (-c, -o, the various -Is, etc.) but most ought to be totally optional.
The Question
So where are they coming from? I've tried editing the basic template, and even after reducing all Mac related aspects, the result is the same. Are they added programmatically somewhere? If so, it is (presumably) in DevToolsCore or IDEFoundation?

A: They come from XCode "Build Settings". You could add your own compiler via "Build Options". Does that not work for you?

You could also configure Alternative Toolchains in XCode (never tried it).

A: There is an answer, but it's not a convenient one.
Xcode build implementation can be found at:
/Applications/Xcode.app/Contents/PlugIns/Xcode3Core.ideplugin

The core definition appears to be assembled from .xcspec files in various plugins that can be found in:
/Applications/Xcode.app/Contents/PlugIns/Xcode3Core.ideplugin/Contents/SharedSupport/Developer/Library/Xcode/Plug-ins

In particular, for clang and ld, check out:
/Applications/Xcode.app/Contents/PlugIns/Xcode3Core.ideplugin/Contents/SharedSupport/Developer/Library/Xcode/Plug-ins/Clang\ LLVM\ 1.0.xcplugin/Contents/Resources/Clang\ LLVM\ 1.0.xcspec
/Applications/Xcode.app/Contents/PlugIns/Xcode3Core.ideplugin/Contents/SharedSupport/Developer/Library/Xcode/Plug-ins/CoreBuildTasks.xcplugin/Contents/Resources/Ld.xcspec

Depending what you are looking for, you may have to dig. If you're looking for a specific build setting, find it in the Xcode build settings inspector and then search text contents for the corresponding variable name.
Theoretically the .xcspec files allow bundle identifiers and inheritance descriptions to assemble whatever build results you want. As far as I know, these details are not well documented / not documented at all.
Since Apple has restricted Xcode plugins to Apple only, it may not be possible to extend the build definition in a sensible way at the user level. It is possible to modify the default system, but then you end up with only the modified version.
Perhaps others have figured out or will later figure out more about how to take advantage of this setup, in which case I will update the answer to reflect our best knowledge.


text:
Q: Understanding the proof of the adjoint sensitivity method I have been trying to understand the proof of the adjoint sensitivity method to calculate the gradients $dJ/d\theta$ of a loss functional,
\begin{align*}
    J(\theta) &= L(x(T))+\int_{0}^{T}\ell(x(t))dt \\
    \text{s.t.}\quad &\dot{x}(t) = f(x(t),\theta), \quad x(0)=x_0.
\end{align*}
Using the adjoint method we get,
\begin{align*}
    \dfrac{dJ}{d\theta} &= \int_{0}^{T} \lambda^\top f_\theta\,dt\\
    \text{where }\,\dot{\lambda}^\top &= -\ell_x - \lambda^\top f_x,\quad \lambda(T)=L'(x(T)).
\end{align*}
The proof I usually encountered introduced the Lagrangian multiplier $\lambda$,
\begin{equation}
    \mathcal{L} = L\left(x(T)\right)+\int_{0}^{T}\ell(x(t))dt - \int_{0}^{T}\lambda(t)^\top\left(\dot{x}(t) - f(x(t),\theta)\right)dt.
\end{equation}
and then argued as follows,
\begin{align*}
    \dfrac{dJ}{d\theta} &= \dfrac{d\mathcal{L}}{d\theta} \stackrel{(i)}{=} \dfrac{dL}{d\theta} - \dfrac{d}{d\theta}\left[\lambda x\Big\rvert_{0}^{T}\right]+ \dfrac{d}{d\theta}\int_{0}^{T}\left[l+\dot{\lambda}^\top x + \lambda^\top f \right]dt\\
    &\stackrel{(ii)}{=} \left[ L'(x(T))-\lambda(T)\right]x_\theta(T)\\
    &+ \int_{0}^{T}\left[l_x+\dot{\lambda}^\top + \lambda^\top f_x \right]x_\theta\, dt
    + \int_{0}^{T} \lambda^\top f_\theta \,dt
\end{align*}
Here, in $(i)$ we integrated by parts and in $(ii)$ we rearranged terms and used the fact that $x_\theta(0)=0$. Now, if the adjoint equation is satisfied the result holds.
My questions are:

*

*To me the introduction of $\lambda$ looks a bit "magic" here. I understand that at an optimum we may use Lagrangian multipliers and then have a condition $d\mathcal{L}/d\theta = 0$. But here we are not at an optimum in general. Is there a better explanation for this trick?

*Why is it ok to assume that $\lambda$ doesn't depend on $\theta$ when we take the partial derivatives?

*Is there a more intuitive proof using functional derivatives instead?


text:
Q: Move an app to the sd card I have a Z667TV1.0.0B08 Android phone with a 16 gb sd card.
I have tried enabling debug mode and using the command "adb set-install-location 2" and "adb get-install-location" which outputs "2[external]."
How do I move an app to the sd card, or make it the default install location?

A: Beginning with API Level 8, you can allow your application to be installed on the external storage (for example, the device's SD card). you can declare for your application with the android:installLocation manifest attribute. for more details please visit http://developer.android.com/guide/topics/data/install-location.html


text:
Q: Preloading shared library with libVirt I am trying to load two shared libraries while running Qemu using libvirt. To preload the shared libraries I have added an environment variable in the $domain.xml file with the following command:
virt-xml generic --edit --confirm --qemu-commandline 'env=LD_PRELOAD=/home/probir/Downloads/kpv_temp/temp/kvmTest/build_kvm/libperform.so:/home/probir/Downloads/kpv_temp/temp/kvmTest/dependencies/libmonitor/installDir/lib/libmonitor.so'

However, while running the domain, I get the following message of failure to preload the shared files.
2019-07-17 17:35:22.939+0000: starting up libvirt version: 1.3.1, package: 1ubuntu10.27 (Marc Deslauriers <marc.deslauriers@ubuntu.com> Tue, 02 Jul 2019 09:22:37 -0400), qemu version: 2.5.0 (Debian 1:2.5+dfsg-5ubuntu10.39), hostname: probir-XPS-13-9343
LC_ALL=C PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin QEMU_AUDIO_DRV=spice LD_PRELOAD=/home/probir/Downloads/kpv_temp/temp/kvmTest/build_kvm/libperform.so:/home/probir/Downloads/kpv_temp/temp/kvmTest/dependencies/libmonitor/installDir/lib/libmonitor.so /usr/bin/kvm-spice -name generic -S -machine pc-i440fx-xenial,accel=kvm,usb=off -cpu Broadwell-noTSX-IBRS -m 4096 -realtime mlock=off -smp 2,sockets=2,cores=1,threads=1 -uuid 8f755c9c-adf8-4baf-8d6a-947ebdf61ff8 -no-user-config -nodefaults -chardev socket,id=charmonitor,path=/var/lib/libvirt/qemu/domain-generic/monitor.sock,server,nowait -mon chardev=charmonitor,id=monitor,mode=control -rtc base=utc,driftfix=slew -global kvm-pit.lost_tick_policy=discard -no-hpet -no-shutdown -global PIIX4_PM.disable_s3=1 -global PIIX4_PM.disable_s4=1 -boot strict=on -device ich9-usb-ehci1,id=usb,bus=pci.0,addr=0x6.0x7 -device ich9-usb-uhci1,masterbus=usb.0,firstport=0,bus=pci.0,multifunction=on,addr=0x6 -device ich9-usb-uhci2,masterbus=usb.0,firstport=2,bus=pci.0,addr=0x6.0x1 -device ich9-usb-uhci3,masterbus=usb.0,firstport=4,bus=pci.0,addr=0x6.0x2 -device virtio-serial-pci,id=virtio-serial0,bus=pci.0,addr=0x5 -drive file=/var/lib/libvirt/images/generic.img,format=qcow2,if=none,id=drive-ide0-0-0 -device ide-hd,bus=ide.0,unit=0,drive=drive-ide0-0-0,id=ide0-0-0,bootindex=1 -drive if=none,id=drive-ide0-0-1,readonly=on -device ide-cd,bus=ide.0,unit=1,drive=drive-ide0-0-1,id=ide0-0-1 -netdev tap,fd=26,id=hostnet0 -device rtl8139,netdev=hostnet0,id=net0,mac=52:54:00:82:62:ba,bus=pci.0,addr=0x3 -chardev pty,id=charserial0 -device isa-serial,chardev=charserial0,id=serial0 -chardev spicevmc,id=charchannel0,name=vdagent -device virtserialport,bus=virtio-serial0.0,nr=1,chardev=charchannel0,id=channel0,name=com.redhat.spice.0 -spice port=5900,addr=127.0.0.1,disable-ticketing,image-compression=off,seamless-migration=on -device qxl-vga,id=video0,ram_size=67108864,vram_size=67108864,vgamem_mb=16,bus=pci.0,addr=0x2 -device intel-hda,id=sound0,bus=pci.0,addr=0x4 -device hda-duplex,id=sound0-codec0,bus=sound0.0,cad=0 -chardev spicevmc,id=charredir0,name=usbredir -device usb-redir,chardev=charredir0,id=redir0 -chardev spicevmc,id=charredir1,name=usbredir -device usb-redir,chardev=charredir1,id=redir1 -device virtio-balloon-pci,id=balloon0,bus=pci.0,addr=0x7 -msg timestamp=on
Domain id=9 is tainted: custom-argv
ERROR: ld.so: object '/home/probir/Downloads/kpv_temp/temp/kvmTest/build_kvm/libperform.so' from LD_PRELOAD cannot be preloaded (cannot open shared object file): ignored.
ERROR: ld.so: object '/home/probir/Downloads/kpv_temp/temp/kvmTest/dependencies/libmonitor/installDir/lib/libmonitor.so' from LD_PRELOAD cannot be preloaded (cannot open shared object file): ignored.
ERROR: ld.so: object '/home/probir/Downloads/kpv_temp/temp/kvmTest/build_kvm/libperform.so' from LD_PRELOAD cannot be preloaded (cannot open shared object file): ignored.
ERROR: ld.so: object '/home/probir/Downloads/kpv_temp/temp/kvmTest/dependencies/libmonitor/installDir/lib/libmonitor.so' from LD_PRELOAD cannot be preloaded (cannot open shared object file): ignored.
char device redirected to /dev/pts/21 (label charserial0)

I further went ahead to verify the shared library with ldd and ls -l. Following results came out:
probir@probir-XPS-13-9343:~/Downloads/kpv_temp/temp/kvmTest/test/kvm$ ls -l /home/probir/Downloads/kpv_temp/temp/kvmTest/build_kvm/libperform.so
-rwxrwxr-x 1 probir probir 834240 Jun 13 17:53 /home/probir/Downloads/kpv_temp/temp/kvmTest/build_kvm/libperform.so
probir@probir-XPS-13-9343:~/Downloads/kpv_temp/temp/kvmTest/test/kvm$ ldd /home/probir/Downloads/kpv_temp/temp/kvmTest/build_kvm/libperform.so
    linux-vdso.so.1 =>  (0x00007ffdd97d5000)
    libxed.so => /home/probir/Downloads/kpv_temp/temp/kvmTest/dependencies/xed/kits/xed-install-base/lib/libxed.so (0x00007f706442e000)
    libmonitor.so.0 => /home/probir/Downloads/kpv_temp/temp/kvmTest/dependencies/libmonitor/installDir/lib/libmonitor.so.0 (0x00007f706420a000)
    libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f7063fed000)
    libbfd-2.26.1-system.so => /usr/lib/x86_64-linux-gnu/libbfd-2.26.1-system.so (0x00007f7063ca8000)
    libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f7063926000)
    libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f7063710000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f7063346000)
    /lib64/ld-linux-x86-64.so.2 (0x00007f7064f48000)
    libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f7063142000)
    libz.so.1 => /lib/x86_64-linux-gnu/libz.so.1 (0x00007f7062f28000)
    libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f7062c1f000)

and
probir@probir-XPS-13-9343:~/Downloads/kpv_temp/temp/kvmTest/test/kvm$ ls -l /home/probir/Downloads/kpv_temp/temp/kvmTest/dependencies/libmonitor/installDir/lib/libmonitor.so
lrwxrwxrwx 1 probir probir 19 Mar 28 13:45 /home/probir/Downloads/kpv_temp/temp/kvmTest/dependencies/libmonitor/installDir/lib/libmonitor.so -> libmonitor.so.0.0.0
probir@probir-XPS-13-9343:~/Downloads/kpv_temp/temp/kvmTest/test/kvm$ ldd /home/probir/Downloads/kpv_temp/temp/kvmTest/dependencies/libmonitor/installDir/lib/libmonitor.so
    linux-vdso.so.1 =>  (0x00007ffc5d12b000)
    libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007ff8ae23e000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007ff8ade74000)
    /lib64/ld-linux-x86-64.so.2 (0x00007ff8ae666000)

I cannot figure out what is causing the failure of preload. Previously, I manually preloaded the same shared libraries for other application.

A: May be apparmor blocking ld_preload libraries.
Check: is libvirt controlled by apparmor:
apparmor_status | grep libvirt

If so, you can stop apparmor:
systemctl stop apparmor
systemctl restart libvirtd

Or create permission for your libs in apparmor configuration file:
/etc/apparmor.d/abstractions/libvirt-qemu


text:
Q: How to change the icon of .bat file programmatically? I'd like to know what's the way to actually set the icon of a .bat file to an arbitrary icon.
How would I go about doing that programmatically, independently of the language I may be using.

A: The icon displayed by the Shell (Explorer) for batch files is determined by the registry key
HKCR\batfile\DefaultIcon

which, on my computer is
%SystemRoot%\System32\imageres.dll,-68

You can set this to any icon you like.
This will however change the icons of all batch files (unless they have the extension .cmd).

A: If you want an icon for a batch file,
first create a link for the batch file as follows
Right click in window folder where you want the link
select New -> Shortcut, then specify where the .bat file is.
This creates the .lnk file you wanted.
Then you can specify an icon for the link,
on its properties page.
Some nice icons are available here:
%SystemRoot%\System32\SHELL32.dll
Note For me on Windows 10:
%SystemRoot% == C:\Windows\
More Icons are here:
C:\Windows\System32\imageres.dll
Also you might want to have the first line
in the batch file to be "cd .."
if you stash your batch files in a bat subdirectory
one level below where your shortcuts,  are supposed to execute.

A: Assuming you're referring to MS-DOS batch files: as it is simply a text file with a special extension, a .bat file doesn't store an icon of its own.
You can, however, create a shortcut in the .lnk format that stores an icon.

A: One of the way you can achieve this is:

*

*Create an executable Jar file

*Create a batch file to run the above jar and launch the desktop java application.

*Use Batch2Exe converter and covert to batch file to Exe.

*During above conversion, you can change the icon to that of your choice.(must of valid .ico file)

*Place the short cut for the above exe on desktop.

Now your java program can be opened in a fancy way just like any other MSWindows apps.! :)

A: Try BatToExe converter. It will convert your batch file to an executable, and allow you to set an icon for it.

A: You can just create a shortcut and then right click on it -> properties -> change icon, and just browse for your desired icon.
Hope this help.
To set an icon of a shortcut programmatically, see this article using SetIconLocation:
How Can I Change the Icon for an Existing Shortcut?:
https://devblogs.microsoft.com/scripting/how-can-i-change-the-icon-for-an-existing-shortcut/
Const DESKTOP = &H10&
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.NameSpace(DESKTOP)
Set objFolderItem = objFolder.ParseName("Test Shortcut.lnk")
Set objShortcut = objFolderItem.GetLink
objShortcut.SetIconLocation "C:\Windows\System32\SHELL32.dll", 13
objShortcut.Save

A: You could use a Bat to Exe converter from here:
https://web.archive.org/web/20190304134631/http://www.f2ko.de/en/b2e.php
This will convert your batch file to an executable, then you can set the icon for the converted file.

A: I'll assume you are talking about Windows, right? I don't believe you can change the icon of a batch file directly. Icons are embedded in .EXE and .DLL files, or pointed to by .LNK files.
You could try to change the file association, but that approach may vary based on the version of Windows you are using. This is down with the registry in XP, but I'm not sure about Vista.

A: try with shortcutjs.bat to create a shortcut:
call shortcutjs.bat -linkfile mybat3.lnk -target "%cd%\Ascii2All.bat" -iconlocation "%SystemRoot%\System32\SHELL32.dll,77"

you can use the -iconlocation switch to point to a icon .

A: You may use a program like BAT to EXE converter for example that one: link

This program permits you to add your custom icon.

A: i recommand to use BAT to EXE converter for your desires


text:
Q: How to fix "The following resource(s) failed to update: [Cloudfront]." Update
There are other errors that show up after this error, but it seems clear to me (based on the timestamps, descriptions and affected resources) that they're just failures that happen because they depend on this first failing step. They are:
UPDATE_FAILED: Resource update cancelled
UPDATE_ROLLBACK_IN_PROGRESS: [OtherResource1, OtherResource2,...]
UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS (no associated message)
UPDATE_ROLLBACK_COMPLETE (no associated message)

I'm getting this error

The following resource(s) failed to update: [Cloudfront].

when trying to redeploy my cloudformation stack. This is the template file:
AWSTemplateFormatVersion: "2010-09-09"
Description: 'Cloudfront stack'
Parameters:
  ViewerRequestFunctionVersionArn:
    Type: String
    Description: S3bucketStack Name that your want to import the DNSDomainName from.
  OringResponseFunctionVersionArn:
    Type: String
    Description: S3bucketStack Name that your want to import the DNSDomainName from.
  LambdaVideoPathEdgeVersionArn:
    Type: String
    Description: S3bucketStack Name that your want to import the DNSDomainName from.
  DNSDomainName:
    Type: String
    Description: S3bucketStack Name that your want to import the DNSDomainName from.
    MaxLength: 150
    MinLength: 5
  S3VideoDNSDomainName:
    Type: String
    Description: S3bucketStack Name that your want to import the DNSDomainName from.
    MaxLength: 150
    MinLength: 5
  IdParam:
    Type: String
    Description: S3bucketStack Name that your want to import the DNSDomainName from.
    MaxLength: 150
    MinLength: 5
  IdVideoOriginParam:
    Type: String
    Description: S3bucketStack Name that your want to import the DNSDomainName from.
    MaxLength: 150
    MinLength: 5
  OrigingAccessIdentityID:
    Type: String
    Description: S3bucketStack Name that your want to import the DNSDomainName from.
    MaxLength: 450
    MinLength: 5
  OrigingAccessIdentityVideoID:
    Type: String
    Description: S3bucketStack Name that your want to import the DNSDomainName from.
    MaxLength: 450
    MinLength: 5
  SSLCertificate:
    Type: String
    Description: SSLCertificate ARN .
    MaxLength: 150
    MinLength: 5
  Comment:
    Type: String
    Description: SSLCertificate ARN .
    MaxLength: 450
    MinLength: 5
  CommentOrigin:
    Type: String
    Description: SSLCertificate ARN .
    MaxLength: 450
    MinLength: 5
  AllowedMethodsParam:
    Type: CommaDelimitedList
    Description: Buket Name for website config( eg exemple.com).
  CachedMethodsParam:
    Type: CommaDelimitedList
    Description: Buket Name for website config( eg exemple.com).
  AliasesParam:
    Type: CommaDelimitedList
    Description: Buket Name for website config( eg exemple.com).
  defaultTTLParam:
    Type: Number
    Description: SSLCertificate ARN .
Resources:
  CloudFrontDistribution:
    Type: AWS::CloudFront::Distribution
    Properties:
      DistributionConfig:
        Aliases: !Ref AliasesParam
        Comment: !Ref Comment
        CacheBehaviors:
          - AllowedMethods: !Ref AllowedMethodsParam
            CachedMethods: !Ref CachedMethodsParam
            Compress: false
            DefaultTTL: !Ref defaultTTLParam
            PathPattern: 'public/*'
            ForwardedValues:
              Headers:
                - Access-Control-Request-Headers
                - Access-Control-Request-Method
                - Origin
              QueryString: true
            MaxTTL: 31536000
            MinTTL: 0
            SmoothStreaming: false
            TargetOriginId: !Ref IdParam
            ViewerProtocolPolicy : "redirect-to-https"
          - AllowedMethods: !Ref AllowedMethodsParam
            CachedMethods: !Ref CachedMethodsParam
            Compress: false
            DefaultTTL: !Ref defaultTTLParam
            PathPattern: 'images/*'
            ForwardedValues:
              Headers:
                - Access-Control-Request-Headers
                - Access-Control-Request-Method
                - Origin
              QueryString: true
              QueryStringCacheKeys:
                - w
                - h
                - t
                - q
                - v
            LambdaFunctionAssociations:
              - EventType: 'viewer-request'
                LambdaFunctionARN: !Ref ViewerRequestFunctionVersionArn
              - EventType: 'origin-response'
                LambdaFunctionARN: !Ref OringResponseFunctionVersionArn
            MaxTTL: 31536000
            MinTTL: 0
            SmoothStreaming: false
            TargetOriginId: !Ref IdParam
            ViewerProtocolPolicy : "redirect-to-https"
          - AllowedMethods: !Ref AllowedMethodsParam
            CachedMethods: !Ref CachedMethodsParam
            Compress: false
            PathPattern: 'videos/thumbnails/*'
            DefaultTTL: !Ref defaultTTLParam
            ForwardedValues:
              QueryString: true
              QueryStringCacheKeys:
                - w
                - h
                - t
                - q
                - v
            LambdaFunctionAssociations:
              - EventType: 'viewer-request'
                LambdaFunctionARN: !Ref ViewerRequestFunctionVersionArn
              - EventType: 'origin-request'
                LambdaFunctionARN: !Ref LambdaVideoPathEdgeVersionArn
              - EventType: 'origin-response'
                LambdaFunctionARN: !Ref OringResponseFunctionVersionArn
            MaxTTL: 31536000
            MinTTL: 0
            SmoothStreaming: false
            TargetOriginId: !Ref IdParam
            ViewerProtocolPolicy : "redirect-to-https"
          - AllowedMethods: !Ref AllowedMethodsParam
            CachedMethods: !Ref CachedMethodsParam
            Compress: false
            PathPattern: 'videos/*'
            DefaultTTL: !Ref defaultTTLParam
            ForwardedValues:
              QueryString: true
              QueryStringCacheKeys:
                - codex
            LambdaFunctionAssociations:
              - EventType: 'viewer-request'
                LambdaFunctionARN: !Ref ViewerRequestFunctionVersionArn
              - EventType: 'origin-request'
                LambdaFunctionARN: !Ref LambdaVideoPathEdgeVersionArn
              - EventType: 'origin-response'
                LambdaFunctionARN: !Ref OringResponseFunctionVersionArn
            MaxTTL: 31536000
            MinTTL: 0
            SmoothStreaming: false
            TargetOriginId: !Ref IdVideoOriginParam
            ViewerProtocolPolicy : "redirect-to-https"
          - AllowedMethods: !Ref AllowedMethodsParam
            CachedMethods: !Ref CachedMethodsParam
            Compress: false
            PathPattern: 'gifs/*'
            DefaultTTL: !Ref defaultTTLParam
            LambdaFunctionAssociations:
              - EventType: 'viewer-request'
                LambdaFunctionARN: !Ref ViewerRequestFunctionVersionArn
              - EventType: 'origin-request'
                LambdaFunctionARN: !Ref LambdaVideoPathEdgeVersionArn
            MaxTTL: 31536000
            MinTTL: 0
            SmoothStreaming: false
            TargetOriginId: !Ref IdParam
            ViewerProtocolPolicy : "redirect-to-https"
        DefaultCacheBehavior:
          ForwardedValues:
            QueryString: false
          AllowedMethods: !Ref AllowedMethodsParam
          CachedMethods: !Ref CachedMethodsParam
          Compress: false
          DefaultTTL: !Ref defaultTTLParam
          MaxTTL: 31536000
          MinTTL: 0
          SmoothStreaming: false
          TargetOriginId: !Ref IdParam
          ViewerProtocolPolicy : "redirect-to-https"
          LambdaFunctionAssociations:
            - EventType: 'viewer-request'
              LambdaFunctionARN: !Ref ViewerRequestFunctionVersionArn
        DefaultRootObject: index.html
        Enabled: true
        HttpVersion: http2
        IPV6Enabled: true
        Origins:
          - DomainName: !Ref DNSDomainName
            Id: !Ref IdParam
            S3OriginConfig:
              OriginAccessIdentity: !Sub "origin-access-identity/cloudfront/${OrigingAccessIdentityID}"
          - DomainName: !Ref S3VideoDNSDomainName
            Id: !Ref IdVideoOriginParam
            S3OriginConfig:
              OriginAccessIdentity: !Sub "origin-access-identity/cloudfront/${OrigingAccessIdentityVideoID}"
        ViewerCertificate:
          AcmCertificateArn: !Ref SSLCertificate
          MinimumProtocolVersion: "TLSv1.1_2016"
          SslSupportMethod: "sni-only"
      Tags:
        - Key: Application
          Value: Testing
        - Key: Distribution
          Value: Coudfront HTTPS
Outputs:
  DomainName:
    Value: !GetAtt CloudFrontDistribution.DomainName
    Description: Cloudfront DomainName

I've reviewed the cloudfront troubleshooting guide and the closest thing that I thought may be a cause was differences between the deployed resources and what the template specifies. So I reverted all the changes I'd made in the dashboard and tried redeploying, but the error persisted. What else can I try? Or is there more info I can provide to shed more light on the problem?


text:
Q: An inequality regarding convex functions For a convex function $f(\cdot)$ for $x_4 \ge x_3 \ge x_2 \ge x_1 \ge 0$ and $t,t^{'}\ge 0$ we are given that
\begin{equation}
\frac{f(x_4)-f(x_3)}{f(x_2)-f(x_1)} \ge \frac{f(x_4-t)-f(x_3-t^{'})}{f(x_2-t^{'})-f(x_1-t)}.
\end{equation}
I need to prove that $t\ge t^{'}$.
For a linear function or a quadratic function this works well as we can prove that $t^{'}>t$ is impossible. However, I am not sure how to generalize this result for any convex function.


text:
Q: Change directory in a shell script, and using expr I am just starting out with shell scripting (sh), and I have two issues.
Issue 1: I'm trying to make a very simple script that creates a directory and immediately goes into it. This is the script I currently have:
#!/bin/sh
mkdir -p "$1"
cd "$1"

For some reason, this does not work. It creates the directory, but does not go into it. Am I missing something obvious here?
Issue 2: I'm writing a very simple calculator that uses expr. But for the multiplication, I use x instead of *. So this is what I have right now:
#!/bin/sh

if test $# -lt 3
then
   echo "Usage calc [operand1] [operator] [operand2]"
   exit
fi

if test $2 = x
then
   op='\*'
else
   op=$2
fi

ret=`expr $1 $op $3`
echo $ret

This works for all the operations except multiplication. Calling calc 100 x 10, for example, gives a syntax error. I tried different combinations, but I can't seem to get the right way of assigning \* to op. What's the right way of doing it?

A: a) the script is run in a new shell. The cd doesn't apply to the outer. Try a shell alias instead of this script.
b) Quote parameters differently, in particular in expr


text:
Q: Add Multiple items of a List to one line in another List Imagine I've this following List:
List<string> thirdList = new List<string> {"0","0","56'BCD"}

I need to add all of its items to a new list as one value i.e., "0 0 56'BCD. Please note that there is space between the items in the new string. Thanks in advance.

A: So you want a list with a single string? You can use String.Join:
var result = new List<string>{ String.Join(" ", thirdList) };


text:
Q: How get language details through REST API call? i am developing multi language android app  my question is how to get the language details  through REST api call without using string.xml in android

A: If you don't want get the device current language details, you can use Locale. You can use the following method:
Locale locale;
// ctx is your application context
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
    locale = ctx.getResources().getConfiguration().getLocales().get(0);
} else {
   locale = ctx.getResources().getConfiguration().locale;
}

or the following code if you're using Support library ConfigurationCompat:
Locale locale = ConfigurationCompat.getLocales(
                        ctx.getResources().getConfiguration()).get(0);

then you can use the following method from Locale:

*

*getISOLanguages()

*getISOCountries()

*getISO3Language()


text:
Q: How to designate start point and end point of line graph I have a matrix having three columns. The first column represents chromosome fragment start site. The second column represents chromosome fragment end site. The last column represents each fragments' log 2 ratio.
I want to reflect start and end value in R plot and make my plot similar to the below picture.

dat <- structure(list(V2 = c(10000L, 131335L, 176031L, 352723L, 530564L,
568797L, 659000L, 732902L, 770670L, 825228L, 865581L, 874488L,
879156L, 880557L, 886632L, 889175L, 891333L, 893991L, 894333L,
896833L, 897469L, 898224L, 898959L, 899619L, 901876L, 905842L,
907466L, 908851L, 911760L, 914600L, 915421L, 916640L, 934743L,
948948L, 949722L, 967266L, 976796L, 978877L, 979677L, 981147L,
981756L, 982280L, 982971L, 984604L, 985495L, 986917L, 987423L,
993585L, 1015923L, 1019671L, 1022611L, 1026296L, 1060070L, 1078501L,
1104425L, 1114964L, 1117599L, 1120290L, 1132927L, 1139342L, 1140646L,
1147128L, 1148860L, 1152936L, 1154097L, 1158629L, 1163994L, 1168587L,
1178339L, 1179751L, 1190685L, 1192397L, 1196601L, 1201279L, 1216003L,
1217387L, 1221435L, 1222353L, 1223037L, 1226038L, 1227307L, 1230245L,
1231304L, 1233228L, 1235465L, 1238226L, 1242363L, 1244719L, 1245194L,
1246878L, 1247763L, 1248398L, 1249133L, 1250230L, 1254308L, 1256077L,
1257363L, 1262230L, 1266735L, 1267789L), V3 = c(131334L, 175999L,
352633L, 530522L, 568792L, 658998L, 732892L, 770612L, 825195L,
865580L, 874488L, 879155L, 880555L, 886629L, 889175L, 891333L,
893990L, 894332L, 896833L, 897468L, 898223L, 898958L, 899619L,
901876L, 905841L, 907466L, 908851L, 911760L, 914599L, 915419L,
916640L, 934742L, 948945L, 949722L, 967263L, 976795L, 978877L,
979677L, 981146L, 981755L, 982279L, 982971L, 984603L, 985494L,
986917L, 987423L, 993580L, 1015884L, 1019671L, 1022608L, 1026296L,
1060025L, 1078501L, 1104424L, 1114964L, 1117594L, 1120289L, 1132922L,
1139342L, 1140645L, 1147127L, 1148860L, 1152935L, 1154097L, 1158629L,
1163993L, 1168586L, 1178336L, 1179751L, 1190685L, 1192397L, 1196600L,
1201277L, 1216001L, 1217387L, 1221435L, 1222352L, 1223037L, 1226036L,
1227307L, 1230244L, 1231304L, 1233228L, 1235465L, 1238225L, 1242363L,
1244719L, 1245194L, 1246878L, 1247763L, 1248397L, 1249133L, 1250229L,
1254308L, 1256077L, 1257363L, 1262229L, 1266734L, 1267789L, 1268314L
), V6 = c(0.8906, 0.564571, 0.517607, 0.828888, 2.340412, 0.947814,
0.622437, 0.353472, 0.679258, 0.270922, 0.439973, -0.160465,
-0.160465, 0.314315, 0.411712, 0.00946, 0.516281, -0.272939,
-0.324303, 0.081196, -0.275235, -0.241181, 0.375588, 0.218047,
-0.466568, 0.371192, -0.078003, -0.252443, -0.650992, 0.498923,
0.188368, 0.066769, -0.266075, 0.492191, 0.208222, -0.141495,
0.173296, 0.242322, 0.221307, 0.317365, 0.226184, -0.054156,
0.028197, -0.345854, -0.046294, -0.382504, 0.48407, 0.088356,
-0.404949, 0, 0.398811, 0.403124, 0.140951, 0.079401, 0.281893,
0.130584, 0.043013, 0.64689, 0.121888, 0.291231, 0.199982, -0.445734,
0.052196, 0.311258, 0.423083, 0.264615, 0.537361, 0.401688, -0.068018,
-0.03458, -0.503766, 0.176659, 0.357922, 0.28657, 0.037475, 0.394485,
0.028197, 0.288125, 0.754325, 0.229426, -0.131064, -0.120707,
0.387246, 0.340037, 0.245528, 0.250323, 0.046693, -0.044335,
0.420248, 0.492191, 0.306661, 0.113139, -0.0019, 0.09014, 0.195016,
0.424498, 0.360882, 0.538669, 0.529492, 0.794279)), .Names = c("V2",
"V3", "V6"), row.names = 102381:102480, class = "data.frame")

A: Using ggplot2 you can do the following:
mydat <- data.frame(V2 = c(10, 20, 15),
                    V3 = c(15, 30, 25),
                    V6 = c(10, 20, 30))
library(ggplot2)

ggplot(data = mydat) + geom_segment(aes(x = V2, xend = V3, y = V6, yend = V6))

Which results in this plot:

Does that look similar to what you want?
EDIT with given data
Using the same code but the dataset from above:
mydat <- structure(list(V2 = c(10000L, 131335L, 176031L.....

ggplot(data = mydat) + geom_segment(aes(x = V2, xend = V3, y = V6, yend = V6))

A: You only need to use segments, no external library needed.
Like in this simple example:
plot(NULL,xlim=c(-1,1),ylim=c(-1,1))
m <- matrix(rnorm(30),10,3)
segments(m[,1],m[,3],m[,2],m[,3])


text:
Q: How to populate Imagelist dynamically (data from database) C# I need to populate an ImageList dynamically. Means I stored image names in a database table. But images are in categories folder inside project folder (1.jpg, 2.jpg...) using a while loop I tried to add image into ImageList and bind to the ListView.
Here is my code and TABLE. No errors but images are not loading. I am not sure image path is correct or not. What is wrong with my code and how to do that?
public void show()
{
    ImageList imgs = new ImageList();
    imgs.ImageSize = new Size(50,50);

    MySqlConnection con = cn.connection();
    MySqlCommand cmd = new MySqlCommand();
    cmd.Connection = con;
    cmd.CommandText = "SELECT * FROM categories";
    MySqlDataReader rd;
    con.Open();
    rd = cmd.ExecuteReader();
    while (rd.Read())
    {
        try
        {
            imgs.Images.Add(Image.FromFile("./categories/" + rd.GetString(2)));
        }
        catch (Exception e) {
            MessageBox.Show(e.Message);
        }
    }
    listView1.SmallImageList = imgs;
    while (rd.Read())
    {
        listView1.Items.Add("asas",rd.GetString(0));
    }
}

TABLE

IMAGE PATH
C:\vb\nishantha\pos3\categories

PROJECT FOLDER
enter image description here
IMAGE FOLDER
enter image description here

A: Try this
imgs.Images.Add(Bitmap.FromFile("\\categories\\" + rd.GetString(2)));

might help you achieve it And the next while loop might be a problem since running the first loop already read all the records from the DB. So if you want you can include the same in the first loop itself.
listViewItem lvi = new listViewItem();
while (rd.Read())
{
    try
    {
        imgs.Images.Add(Bitmap.FromFile("\\categories\\" + rd.GetString(2)));
        lvi.SubItems.Add(rd.GetString(0));
    }
    catch (Exception e) {
        MessageBox.Show(e.Message);
    }
}
listView1.Items.Add(lvi);
listView1.SmallImageList = imgs;

A: Make sure categories folder with files is available in root directory.
e.g. if you are building the application in  debug mode, then categories folder and files should be in ~/debug/categories/..jpg. for doing this take below steps:
Expand categories folder, select all files --> Right click --> Property --> CopyToOutputDirectory to Copy always.
Finally in last line for adding the items in the listview change the below code:
while (rd.Read())
{
   listView1.Items.Add("asas",rd.GetString(0));
}

To
for (int j = 0; j < imgs.Images.Count; j++)
{
    ListViewItem item = new ListViewItem();
    item.ImageIndex = j;
    item.Text = "asdf";

    this.listView1.Items.Add(item);
}


text:
Q: Rails not able to render page as json I have a URL like this : localhost/events/show?eId=12345.json
When I perform : model.find(params[:eId])
It considers .json part of eId and says no id found for 12345.json. To resolve this issue, I excluded .json from eId and it then shows the html page. But I need to be able to also see the .json page.
So it doesn't recognize that I need to view page as json.

A: Try localhost/events/show.json?eId=12345.


text:
Q: Twitter widget went from working to not working on an unhosted website I was editing the files at college, and the widget was working, but now that I have the file open at home it isn't working.
Here is the code:

  Tweets by @bethesda

UPDATE:
I fixed it by removing it and adding it again.  No idea what was wrong, but probably accidentally deleted or added something.

A: Double check the Widgets settings on your Twitter account. The widget might be missing or it could be a permission issue like for some reasons, someone might have revoked that particular widget.


text:
Q: How to reference abstract method from an implemented class in C# I have a base class (A), below, that I always want to inherited from
class A
{
   abstract protected int foo();

   public int foo2()
   {
      //do some stuff

      foo();
   }

}

This will not work because I can't have an abstract method in non-abstract class. But how can I accomplish the follow goals:
classes that inherit class A will have foo2 already implemented but classes that inherit MUST implement foo? It would also be preferable that foo2 is overridable.
Update: Class A did NOT have to be non-abstract

A: Just make the class A abstract. Abstract classes can have some methods implemented.
Make foo2() virtual, then classes derived from A can override it.

A: I expect that you have a valid reason to not make A abstract. The prefered way to change the behaviour of an existing non abstract class is to inject that behaviour.
interface IFoo
{
    int Foo();
}

class A
{
    private IFoo foo;

    public A(IFoo foo)
    {
        this.foo = foo;
    }

    public int Foo2()
    {
        //...
        return foo.Foo();
    }
}

A: you will receive errors when you build the project
you can't define abstract method in non-abstract class
Exception
Error   1   ' .A.foo()' is abstract but it is contained in non-abstract class


text:
Q: Is it ok to have two Table Views on the same window/view as master-detail concept on iPad? I have a UITabBar in my iPad app, and I need to have a Master-Detail concept on one of my UITabBarviews.
I can't use UISplitViewController because Apple says:
 The split view controller's view should always be installed as the root view
 of your  application window. You should never present a split view inside of
 a navigation or tab bar interface.

Is it ok to have two UITableViews on same view as Master-Detail concept on iPad? Is there any other approach for this idea?

A: I don't know of any limitation about having two table views in a tab. I'd approach it like this:

*

*for that tab, have an overall UIViewController that can run things when the user switches to that tab

*it sets up the master detail table views as appropriate.


text:
Q: Why doesn't Clang merge these consecutive and adjacent calls to memcpy or memset? When compiling this with Clang 10.0.0 and current Clang-trunk it seems to be missing some pretty obvious optimization oppertunities:
struct A {
    int x[16] {0}; // Everything zero init by default
    int y[16] {0};
    int z[16] {0};
};

int foo(A* a, A* b); // dummy function in external translation unit
                     // to block any constant folding and unused variable
                     // elimination, etc.

int func() {

    A a[1024],b[1024]; // clang calls memset for each of a and b
                       // could be optimized to single call

    foo(a,b);

    for( int i = 0 ; i < 1024 ; i++ ) {
        a[i] = b[i]; // clang calls memcpy here 1024 times with
                     // consecutive addresses, could be optimized
                     // to single call.
    }

    return foo(a,b);
}

The output generated by Clang for x64 at -O3 is as follows:  https://godbolt.org/z/taKi4G
func():                               # @func()
        push    r15
        push    r14
        push    rbx
        sub     rsp, 393216
        lea     r14, [rsp + 196608]
        xor     ebx, ebx
        mov     edx, 196608
        mov     rdi, r14
        xor     esi, esi
        call    memset
        mov     r15, rsp
        mov     edx, 196608
        mov     rdi, r15
        xor     esi, esi
        call    memset
        mov     rdi, r14
        mov     rsi, r15
        call    foo(A*, A*)
.LBB0_1:                                # =>This Inner Loop Header: Depth=1
        lea     rdi, [rsp + rbx]
        add     rdi, 196608
        lea     rsi, [rsp + rbx]
        mov     edx, 192
        call    memcpy
        lea     rdi, [rsp + rbx]
        add     rdi, 196800
        lea     rsi, [rsp + rbx]
        add     rsi, 192
        mov     edx, 192
        call    memcpy
        add     rbx, 384
        cmp     rbx, 196608
        jne     .LBB0_1
        lea     rdi, [rsp + 196608]
        mov     rsi, rsp
        call    foo(A*, A*)
        add     rsp, 393216
        pop     rbx
        pop     r14
        pop     r15
        ret

I think that the two calls to memset could be merged into a single memset and the 1024 calls to memcpy could be merged, leaving a single memset and a single memcpy. The memset improvement might be marginal, but I'm pretty sure a single call to memcpy would be significantly faster.
I was trying to convince someone that they shouldn't need to use mempcy and memset in their code to copy and zero init arrays of POD structs and should just use constructors and let the compiler handle it. My argument somehwat fell apart when I actually looked at what clang had generated.
Is doing this merging somehow not valid or is clang just missing a trick?
Edit: I checked against GCC 10, and it seems to do the large mempcy as I expected, but still doesn't merge the memsets.


text:
Q: Python - Gathering File Information Recursively Leads to Memory Error I am writing a script to recurse over all directories and subdirectories of a starting folder but I'm running into memory errors (the error is MemoryError). My guess would be that maybe my data_dicts list is getting too big but I'm not sure. Any advice would be appreciated.
import os

# example data dictionary
data_dict = {
    'filename': 'data.csv',
    'folder':   'R:/',
    'size':     300000
}

def get_file_sizes_folder(data_dicts, starting_folder):
# Given a list of file information dictionaries and a folder, iterate over the files
# in the folder to get their information and append it to the list.
# Also recurse through subdirectories
    for entry in os.scandir(starting_folder):
        if not entry.name.startswith('.'):
            if entry.is_file():
                size = entry.stat().st_size
                filename = entry.name
                folder = os.path.dirname(entry.path)
                temp_dict = {'filename': filename, 'size': size, 'folder': folder}
                data_dicts.append(temp_dict.copy())
            else:
                print(entry.path)
                data_dicts.extend(get_file_sizes_folder(data_dicts, entry.path))

    return data_dicts

d = get_file_sizes_folder([], 'R:/')

A: You shouldn't supply data_dicts as an argument to your function get_file_sizes_folder(). Doing so will produce many, many duplicates of your entries, at a rate that is probably nearly factorial. No wonder that your computer runs out of memory very quickly!
Instead, use only starting_folder as an argument, and simply create a new list data_dicts in the first line of your function, like so:
def get_file_sizes_folder(starting_folder):
# Given a list of file information dictionaries and a folder, iterate over the files
# in the folder to get their information and append it to the list.
# Also recurse through subdirectories
    data_dicts = []
    for entry in os.scandir(starting_folder):
        if not entry.name.startswith('.'):
            if entry.is_file():
                size = entry.stat().st_size
                filename = entry.name
                folder = os.path.dirname(entry.path)
                temp_dict = {'filename': filename, 'size': size, 'folder': folder}
                data_dicts.append(temp_dict)
            else:
                print(entry.path)
                data_dicts.extend(get_file_sizes_folder(entry.path))

    return data_dicts

A: You shouldn't perform a recursion at all. Use os.walk
Example:
def get_file_sizes_folder(starting_folder):
    data_dicts = list()
    for root, _, files in os.walk(starting_folder):
        data_dicts.extend({
            'filename': f,
            'size': os.path.getsize(os.path.join(root, f)),
            'folder': root,
        } for f in files)

    return data_dicts

d = get_file_sizes_folder('R:/')


text:
Q: How Does Google Site Directory Exactly Work? Google Sites, in my opinion, has the best page arrangement. It has a hierarchical tree-like setting where it has both fast loading time and as well as it is very effective in creating URLs automatically. The user need not think anymore about page categories. It is just simply a list of pages and sub-pages. All you need to do is click and drag and Voila! You get your url!
But, how does the database design exactly work on Google Sites? Is this just pure XML? Is this stored in a Datastore? Is it a file system? is this pulled from a SQL Database? Or Is it just a json file arranged hierarchically?
Can anybody explain how complicated this design is?

A: Here is my best guess:
URL Path

*

*The unique ID for each page in Google Sites is the URL path.

*The URL Path is also a dynamic string. It changes through javascript drag and drop. The URL is saved through AJAX on a single table as the primary key.

*The pages can not be constructed if there is no parent page.

*The pages URL path are automatically changed in web.xml/app.yaml copied from the Unique ID.

*Each page contains title, content, etc.

Hypothesis: Google Sites is stored in BigQuery and/or Datastore. Then, manipulated by AJAX/GWT. (But, I think this can be done in just AJAX Javascript)


text:
Q: Multiple records not repeated I have a table called TABLE_SCREW where I want to get the latest records for each code.
For example, in the table below you should obtain the records with ids 3 and 7.
I am a newbie in sql and I hope you can help me.

A: You could use:
SELECT TOP 1 WITH TIES *
FROM TABLE_SCREW
ORDER BY ROW_NUMBER() OVER(PARTITION BY CODE ORDER BY Date DESC);

Another approach(may have better performance):
SELECT *  -- here * should be replaced with actual column names
FROM (SELECT *,ROW_NUMBER() OVER(PARTITION BY CODE ORDER BY Date DESC) AS rn
      FROM TABLE_SCREW) sub
WHERE sub.rn = 1;


text:
Q: xPath Traversing I am trying to use xPath to traverse through the code of a newspaper (for the sake of practice) right now I'd like to get the main article, it's picture and the small description I get of it. But I'm not that skilled in xPath so far and I can't get to the small description.
withing this code:

Un tubo de 12 pulgadas al lado de la Vialidad Sacramento que provocó el corte del servicio durante toda la mañana y hasta alrededor de las cuatro de la tarde. Foto: El Heraldo de Chihuahua

Sin agua 8 mil usuarios

La ruptura de una línea en el tanque de rebombeo de agua Sacramento dejó sin servicio a ocho mil usuarios, en once colonias del sur de la ciudad.

I've want to get the picture (with or without caption) and then the title of the article. These 3 things I can get by using:
//div[@class='fondoprincipal'] <-- gives me the main image and caption
//a[@class='cabezaprincesto']/text() <-- gives me the article's title
but I can't get ahold of the small description which is the div with class="resumenesto", I haven't tried getting anything by that id because the same id is used over and over through the rest of the HTML so it returns lots of extra items.
How can I get this particular one? and then would any of you recommend me a good way of parsing it to another webpage? I was thinking maybe php writing some html using those values but I'm not sure really...

Edit
What I mean by "this particular one" is how do I get this div class="resumenesto", the one residing within div class="fondoprincipal"...

Edit 2
Thank you, now xPath Traversing is a little bit more clear. But then about my second question, would any of you recommend me a good way of parsing it to another webpage? I was thinking maybe php writing some html using those values but I'm not sure really..

A: You say "id" of resumenesto, but in your code example the div you're talking about has a class of resumenesto.
Further, when you use an xpath of something like this:
//div[@class='resumenesto']

What you're getting is a list of nodes matching that xpath.
So if you want to specifically refer only to a single item in that list, you need to specify which item in the list:
//div[@class='resumenesto'][1]

Further, what do you mean by "this particular one"? The only way to tell xpath specificity is to give it context, for instance "the div with class resumenesto that resides within some other div", or "the first of the divs with class resumenesto".
Read W3Schools' overview of XPath syntax for some more info.
Edit:
To get the div residing within "fondoprincipal":
//div[@class='fondoprincipal']//div[@class='resumenesto']

This tells xpath to find any descendant div with class fondoprincipal within the document, and within that div, find any descendant div with class resumenesto.

A: And to narrow your search you can add the div too:
//div[@class='resumenesto']/a[@class='resumenesto']/text()

A: To get it to the test you need to:
//div[@class='fondoprincipal']//a[@class='resumenesto']

Note that you want to get the a (isntead of the div as Raul suggested), since its in that element that you get the text.
Regarding putting it on a page, you can do it in asp.net. Use the XElement to load the values and then the XPathSelectElement to get the values (http://msdn.microsoft.com/en-us/library/bb156083.aspx).


text:
Q: Temporary DNS / Internet outages in ECS containers App is running on ECS and it processes SQS messages in some intervals. 2-3 times a day we are seeing errors originated in AWS SQS SDK with code EAI_AGAIN. Generally it looks like few times a day there is DNS / Internet outage in ECS containers for some reason. It works again few seconds after error occurs so it lasts just few seconds I suspect.
From ECS logs / events it seems that containers are not restarting / stopped / starting during time when those errors occur.
My question is where should I look for a cause of this behaviour? Our VPC config is quite complicated, generally EC2 instances (on which ECS cluster operates) are in a private network (not visible from outside). However service running on ECS only polls SQS and processes tasks.
Maybe someone encountered similar issues on AWS?
Note: it is not related to SQS service - other services which connect to RDS / external APIs and so on also report similar errors. So this must be some DNS / Internet level issue I guess.

Dockerfile:
FROM node:8-alpine
ENV NODE_ENV production
WORKDIR /app
RUN apk update && apk upgrade && \
    apk add --no-cache bash git openssh && \
    apk add --no-cache -t build-dependencies make gcc g++ python libtool autoconf automake
COPY package.json /app
COPY yarn.lock /app
RUN \
    mkdir -p /aws && \
    apk -Uuv add groff less python py-pip && \
    pip install awscli && \
    apk --purge -v del py-pip && \
    rm /var/cache/apk/*
RUN yarn
COPY . /app

Here is exact error:
SQS receive message failed: getaddrinfo EAI_AGAIN sqs.eu-central-1.amazonaws.com:443


text:
Q: CarouFREDSel plugin: Media query triggered resizable images in the carousel I have this carousel as a wordpress plugin which looks like this (full browser window width):

When I resize the browser window the size of the images are the same until a media query is triggered:
@media screen and (min-width: 1470px) {
    #image-carousel { height: 500px; }
    #carousel-images img { width: 980px; height: 500px; }

    #prev, #next { height: 500px; }
    #prev { left: -490px; }
    #next { right: -490px; }
}

@media screen and (min-width: 500px) and (max-width: 1470px) {
    #image-carousel { height: 383px; }
    #carousel-images img { width: 750px; height: 383px; }

    #prev, #next { height: 383px; }
    #prev { left: -375px; }
    #next { right: -375px; }
}

Then I resize the divs that needs resizing, and the images scales down correctly, but this happens:

The images are "uncentered". Some process that happens in the creation of the carousel isn't triggered (naturally). The way I've solved this now is this: (I know the javascript isn't DRY, this is just an example)
onCreate: function (data) {
    $(window).resize( function () {
        if( $(window).width() > 1470 ) {
            $(".dev7-caroufredsel-carousel").carouFredSel({
                // Create the carousel again...
            });
        } else if ( $(window).width() <= 1470 ) {
            $(".dev7-caroufredsel-carousel").carouFredSel({
                // Create the carousel again...
            });
        }
    });
}

In the onCreate event for the carousel I bound the window resize event up to recreate the carousel when the browser window passes the given limit. This works, and I don't think it'll be a problem, but...
This seems like a bad thing to do, and not the proper way, and I am wondering how do I do this properly?


text:
Q: Error when accessing ASP.NET Core WebApi from Ionic I have some issues with calling my ASP.NET Core WebAPI from my Ionic app.
I can see in the developer tools that the data get's loaded correctly, but Ionic is giving me an error:
error message from Ionic:

data loaded from the api:

CORS is enabled in the api:
 public class Startup
 {
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors();
        services.AddDbContext<TodoContext>(opt =>
            opt.UseInMemoryDatabase("TodoList"));
        services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseCors(builder => builder.WithOrigins("http://localhost"));
        app.UseMvc();
    }
}

I think the error is caused by Ionic or Angular. When I'm loading the data from a public api, everything works fine. I've also tried accessing the api with ssl and without.
When you have any questions, feel free to ask me in the comments.
Edit
This is how I call the api:
@Injectable()
export class RestProvider {

apiUrl = 'https://localhost:5001/api';

constructor(public http: HttpClient) { }

getTodoItems() {
  return new Promise(resolve => {
    this.http.get(this.apiUrl + '/todo').subscribe(data => {
        resolve(data);
      }, err => {
        console.log(err);
      });
    });
  }
}

and this is my controller:
[Route("api/[controller]")]
[ApiController]
public class TodoController : ControllerBase
{
    private readonly TodoContext _context;

    public TodoController(TodoContext context)
    {
        _context = context;

        if (_context.TodoItems.Count() == 0)
        {
            _context.TodoItems.Add(new TodoItem { Title = "Item1" });
            _context.TodoItems.Add(new TodoItem { Title = "Item2" });
            _context.SaveChanges();
        }
    }

    [HttpGet]
    public ActionResult<List<TodoItem>> GetAll()
    {
        return _context.TodoItems.ToList();
    }
}

A: fixed it by adding the port number:
public void Configure(IApplicationBuilder app)
{
    app.UseCors(builder => builder.WithOrigins("http://localhost:8100").AllowAnyMethod());
    app.UseMvc();
}

A: You can use the ionic.config.json file to configure a proxy in your app:
{
  "name": "proxy-example",
  "app_id": "",
  "proxies": [
    {
      "path": "/api",
      "proxyUrl": "http://cors.api.com/api"
    }
  ]
}

Then when doing the http call:
httpClient.get(proxyHost + '/api');

More info Ionic Blog


text:
Q: When I start this code, i found a problem with error Traceback (most recent call last) in my code with pygame module I have problem with function. I starting learn pygame with video course, and this is my first pygame code. My .py code:
import pygame

pygame.init()

win = pygame.display.set_mode((1280, 720))

pygame.display.set_caption("text.")

walkaniml = pygame.image.load('left1.png')
walkanimr = pygame.image.load('right1.png')
stickmanStand = pygame.image.load('stickman.png')

clock = pygame.time.Clock()

x = 250
y = 400
widht = 271
height = 293
speed = 5

jump = False
jumplov = 10

left = False
right = False
animcount = 0

def drawcube():

    global animcount

    win.fill((255, 218, 185))

    if animcount + 1 >= 24:
        animcount = 0

    if left:
        win.blit(walkaniml(animcount // 1, (x, y)))

    elif right:
        win.blit(walkanimr(animcount // 1, (x, y)))

    else:
        win.blit(stickmanStand, (x, y))

    pygame.display.update()

run = True

while run:
    clock.tick(24)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()

    if keys[pygame.K_LEFT] and x > 1:
        x -= speed
        left = True
        right = False

    elif keys[pygame.K_RIGHT] and x < 1280 - widht - 1:
        x += speed
        left = False
        right = True

    else:
        left = False
        right = False
        animcount = 0

    if not(jump):

        if keys[pygame.K_DOWN] and y < 720 - height - 1:
            y += speed

        if keys[pygame.K_SPACE]:
            jump = True
    else:

        if jumplov >= -10:
            if jumplov < 0:
                y += (jumplov ** 2) / 3

            else:
                y -= (jumplov ** 2) / 3
            jumplov -= 1

        else:

            jump = False
            jumplov = 10

enter image description here
drawcube()
I wanna do a mini-game with stickman, and i found a very big problem, when I start game in cmd and I'm going to web to found decision, but.. I don't find him. Please guys, I realy need help((

A: walkaniml and walkanimr are pygame.Surface objects. You can't call an object:
win.blit(walkaniml(animcount // 1, (x, y)))
win.blit(walkaniml, (x, y))

If walkaniml and walkanimr are a list of Surfaces, you can get an element from the lists by it's index with subscription (even if the list contains only 1 element):
walkaniml = [ pygame.image.load('left1.png') ]
walkanimr = [ pygame.image.load('right1.png') ]

if left:
    if animcount >= len(walkaniml):
        animcount = 0
    win.blit(walkaniml[animcount], (x, y))

elif right:
    if animcount >= len(walkanimr):
        animcount = 0
    win.blit(walkanimr[animcount], (x, y))