text:
Q: Javascript cache busting not yielding results in Firefox I'm relatively new to web programming, and I've searched tirelessly for 2 days for what I feel are relevant terms for this problem.
Currently I'm having an issue with a singular test client not loading the correct javascript file version from the server.
I'm cache busting this file with the server version in the query string, and it works for this person in chrome and IE but for some reason Firefox is using the old file.
When I look at the Web Console, I see it load the correct file (with correct server version in query string), and when I go into the file that is loaded, I see all the correct, updated code.
If anyone can shed light on this issue I would appreciate it greatly.


text:
Q: Invoking AsyncTask from an alert dialog in android I am trying to invoke a network laden task using async task in android.
Now the problem is that I want a confirmation on click of a button, say

*

*I want the user to ask if he really wants to fetch data from the
network.

*On clicking a button the user is asked if he would want to proceed(This is done by an alert dialog).

*Now the async task's do in background and pre execute is called from
a alert dialog yes confirmation.

Please suggest how do I do this, as the pre-execute is failing in my implementation.

A: Within the button click event, add a listener (Usually it will be a DialogInterface.OnClickListener()). A default onClick() function will be there. Call your Async task execute method inside the onClick(method).
If you have any error, kindly paste the LogCat message. That would help a lot.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Titanium Mobile Android: Memory not released when app is closed We have developed an app using Titanium Mobile. When we first run the app in an Android device it uses around 25MB of memory. But every time we exit the app by using the device back button and then relaunch the app, the memory usage goes up by 10MB. So if we exit and relaunch the app 5 times, the app ends up using 50MB of extra memory, for a total usage of 75MB. If we launch the app a few more times, the app will simply not start, and the following error is thrown:

Uncaught Error: Failed to load resource, Java exception was thrwon.
  Source = assets.readAsset(assetPath);

We initially thought it was a problem of our app, so we develop a simple app to test the issue. This test app just creates a window and adds a label to it. The app.js is the following:
function createView() {

    var win1 = Titanium.UI.createWindow({
        title:'Tab 1',
        backgroundColor:'#fff',
        exitOnClose: true
    });

    var label1 = Titanium.UI.createLabel({
        color:'#999',
        text:'I am Window 1',
        font:{fontSize:20,fontFamily:'Helvetica Neue'},
        textAlign:'center',
        width:'auto'
    });

    win1.add(label1);

    win1.open();
}

createView();

Well, the test app has the same problem as our original app. The first time it is launched it consumes 14MB of memory. After 5 restarts (using the device back button) it is consuming 21MB (150% of the inital memory).
We have also tried the sample app that is generated when you create a project in Titanium and the Kitchen Sink app developed by Titanium. The results are the same.
Our tests are done using Titanium 3.0.0.GA with two different devices:

*

*HTC Desire Z - Android 2.3

*Samsung Galaxy 2 - Android 4.0

We have searched for a solution to this problem with no results. We do not want to believe this is the normal behaviour of Titanium, because if so, Titanium is simply not an option for us. Has anyone found any solution/workaround for this issue?
Thanks in advance
UPDATE: added tiapp.xml of test app
<?xml version="1.0" encoding="UTF-8"?>
<ti:app xmlns:ti="http://ti.appcelerator.org">
    <id>com.cloudship.titanium.mobile.test</id>
    <name>titanium-mobile-test</name>
    <version>1.0</version>
    <publisher>Javier</publisher>
    <url>http://</url>
    <description>not specified</description>
    <copyright>2013 by Javier</copyright>
    <icon>appicon.png</icon>
    <persistent-wifi>false</persistent-wifi>
    <prerendered-icon>false</prerendered-icon>
    <statusbar-style>default</statusbar-style>
    <statusbar-hidden>false</statusbar-hidden>
    <fullscreen>false</fullscreen>
    <navbar-hidden>true</navbar-hidden>
    <analytics>true</analytics>
    <guid>18e506f3-02d4-4fb7-84b7-ff8d4c1fac82</guid>
    <property name="ti.ui.defaultunit" type="string">system</property>
    <iphone>
        <orientations device="iphone">
            <orientation>Ti.UI.PORTRAIT</orientation>
        </orientations>
        <orientations device="ipad">
            <orientation>Ti.UI.PORTRAIT</orientation>
            <orientation>Ti.UI.UPSIDE_PORTRAIT</orientation>
            <orientation>Ti.UI.LANDSCAPE_LEFT</orientation>
            <orientation>Ti.UI.LANDSCAPE_RIGHT</orientation>
        </orientations>
    </iphone>
        <android xmlns:android="http://schemas.android.com/apk/res/android">
        <manifest>
            <application android:debuggable="true"/>
            <supports-screens android:anyDensity="true"/>
        </manifest>
    </android>
    <mobileweb>
        <precache/>
        <splash>
            <enabled>true</enabled>
            <inline-css-images>true</inline-css-images>
        </splash>
        <theme>default</theme>
    </mobileweb>
    <modules/>
    <deployment-targets>
        <target device="iphone">false</target>
        <target device="ipad">false</target>
        <target device="blackberry">false</target>
        <target device="android">true</target>
        <target device="mobileweb">false</target>
    </deployment-targets>
    <sdk-version>3.0.0.GA</sdk-version>
</ti:app>

A: It is a bug in Titanium 3.0.0.GA. See jira ticket here. Fortunately it has been fixed in 3.0.2.
Answer was given in Titanium Q&A

A: i'm also developing Titanium. I checked my app and I'm not experiencing this problems on Android 2.2.2 on an HTC Desire. The app is closed correctly.
Can you test with the following code:
var win1 = Titanium.UI.createWindow({
    title:'Tab 1',
    backgroundColor:'#fff',
    exitOnClose: true
});

var label1 = Titanium.UI.createLabel({
    color:'#999',
    text:'I am Window 1',
    font:{fontSize:20,fontFamily:'Helvetica Neue'},
    textAlign:'center',
    width:'auto'
});

win1.add(label1);

win1.open();

so remove the surrounding function.

A: this is solution to memory woes..please go through this thread
https://developer.appcelerator.com/question/116867/this-is-a-solution-to-your-memory-woes


text:
Q: How to copy all files having the same name into another directory, with unique filenames, using bash? Say I have a directory structure like this:
├── Directory 1
│   ├── img.png
├── Directory 2
│   ├── imgx.png
├── Directory 3
│   ├── img.png
...
...
├── Directory n
│   ├── img.png
├── Images

I want to find and copy all the img.png files into the directory Images. Is there any way to:

*

*Find all the img.png files (not all directories have this file)

*Copy them into Images giving them unique filenames in the process (for example 2_img.png if it is being copied from Directory 2).

A: You're looking for something like this:
for dir in 'Directory '*; do
  src=$dir/img.png
  dest=Images/${dir#* }_img.png
  if test -f "$src"; then
    echo cp "$src" "$dest"
  fi
done

Remove echo if the output looks good.


text:
Q: Replace Notification Caused by Android Service I created a Notification for my app which gets displayed when the app runs in the background but I also get a Notification from Android System with the title MyAppName is using battery. I only want my Notification to be shown. How can I disable or replace the default notification when an app is run in the background.
I have a Class MyClass extends Service implements SensorEventListener, LocationListener {...} in which I record sensor and gps data. I create an ExecutorService, which  each time onSensorChanged(...) is triggered which does some stuff.
I also have a PowerManager.WakeLock so that the service runs in the background.


text:
Q: Using Spinners and have force close error - ANDROID ---- I have tried tomove the spinner and textview variables under setcontentview but then spinners are not known publicly so i could use them in void onitemselected  what should i do ??? ------
----- and also I am not sure if I have used spinners correctly -----
Ok So I want to use spinners to get my values from them and compare it with the randomly generated ones and if they are correct shows them in textview as green if not as red
and I only did this IF statement for one spinner just to test it but it force closes.
MainPage.java
package com.example.decrypter;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

public class MainPage extends Activity implements OnItemSelectedListener {
    double random1;
    int check1,check2,check3,check4,check5;

    EditText textbox;
    int guess;
    String s;
    Spinner spinner1 = (Spinner) findViewById(R.id.spinner01);
    Spinner spinner2 = (Spinner) findViewById(R.id.spinner02);
    Spinner spinner3 = (Spinner) findViewById(R.id.spinner03);
    Spinner spinner4 = (Spinner) findViewById(R.id.spinner04);
    Spinner spinner5 = (Spinner) findViewById(R.id.spinner05);
    TextView display1 = (TextView) findViewById(R.id.txtdisplay1);
    TextView display2 = (TextView) findViewById(R.id.txtdisplay2);
    TextView display3 = (TextView) findViewById(R.id.txtdisplay3);
    TextView display4 = (TextView) findViewById(R.id.txtdisplay4);
    TextView display5 = (TextView) findViewById(R.id.txtdisplay5);

    Integer[] numbers = {1,2,3,4,5,6,7,8,9};

    Button btnrandom = (Button) findViewById(R.id.btnrandom);
    Button btn1 = (Button) findViewById(R.id.btn1);
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        ArrayAdapter <Integer> adapter1 = new ArrayAdapter <Integer>(this,       android.R.layout.simple_spinner_item, numbers);

        setContentView(R.layout.activity_main_page);
        spinner1.setAdapter(adapter1);
        spinner1.setOnItemSelectedListener(this);
        spinner2.setAdapter(adapter1);
        spinner2.setOnItemSelectedListener(this);
        spinner3.setAdapter(adapter1);
        spinner3.setOnItemSelectedListener(this);
        spinner4.setAdapter(adapter1);
        spinner4.setOnItemSelectedListener(this);
        spinner5.setAdapter(adapter1);
        spinner5.setOnItemSelectedListener(this);

        btnrandom.setOnClickListener( new View.OnClickListener()
        {

           public void onClick(View v) {
            // TODO Auto-generated method stub
            random1 = Math.floor(Math.random()*10);
            //display.setText("random:" + random1);
            /*check1 = Integer.parseInt(spinner1.getSelectedItem().toString())     ;
            */
        }
       });

        btn1.setOnClickListener( new View.OnClickListener()
        {

           public void onClick(View v) {
            // TODO Auto-generated method stub

            if(check1==random1){
                display1.setTextColor(Color.GREEN);
                display1.setText(s);
            }
            else{
                display1.setTextColor(Color.RED);
                display1.setText(s);
            }
        }
       });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main_page, menu);
        return true;

    }

    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
            long arg3) {
        // TODO Auto-generated method stub

        check1 = Integer.parseInt(spinner1.getSelectedItem().toString());
        check2 = Integer.parseInt(spinner2.getSelectedItem().toString()) ;
        check3 = Integer.parseInt(spinner3.getSelectedItem().toString()) ;
        check4 = Integer.parseInt(spinner4.getSelectedItem().toString()) ;
        check5 = Integer.parseInt(spinner5.getSelectedItem().toString()) ;

    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

    }
}

AndroidManifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.decrypter"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="15" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainPage"
        android:label="@string/title_activity_main_page" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

A: public class MainPage extends Activity implements OnItemSelectedListener {
    double random1;
    int check1,check2,check3,check4,check5;

    EditText textbox;
    int guess;
    String s;
Spinner spinner1,spinner2,spinner3,spinner4,spinner5;
  TextView display1,display2,display3,display4,display5;
Button btnrandom,btn1;

    Integer[] numbers = {1,2,3,4,5,6,7,8,9};

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

              setContentView(R.layout.activity_main_page);
 spinner1 = (Spinner)findViewById(R.id.spinner01);
     spinner2 = (Spinner)findViewById(R.id.spinner02);
     spinner3 = (Spinner)findViewById(R.id.spinner03);
     spinner4 = (Spinner)findViewById(R.id.spinner04);
     spinner5 = (Spinner)findViewById(R.id.spinner05);
     display1 = (TextView)findViewById(R.id.txtdisplay1);
     display2 = (TextView)findViewById(R.id.txtdisplay2);
     display3 = (TextView)findViewById(R.id.txtdisplay3);
     display4 = (TextView)findViewById(R.id.txtdisplay4);
    display5 = (TextView)findViewById(R.id.txtdisplay5);
 btnrandom = (Button)findViewById(R.id.btnrandom);
    btn1 = (Button)findViewById(R.id.btn1);

        spinner1.setAdapter(adapter1);
        spinner1.setOnItemSelectedListener(this);
        spinner2.setAdapter(adapter1);
        spinner2.setOnItemSelectedListener(this);
        spinner3.setAdapter(adapter1);
        spinner3.setOnItemSelectedListener(this);
        spinner4.setAdapter(adapter1);
        spinner4.setOnItemSelectedListener(this);
        spinner5.setAdapter(adapter1);
        spinner5.setOnItemSelectedListener(this);

  ArrayAdapter <Integer> adapter1 = new ArrayAdapter <Integer>(this,       android.R.layout.simple_spinner_item, numbers);

        btnrandom.setOnClickListener( new View.OnClickListener()
        {

           public void onClick(View v) {
            // TODO Auto-generated method stub
            random1 = Math.floor(Math.random()*10);
            //display.setText("random:" + random1);
            /*check1 = Integer.parseInt(spinner1.getSelectedItem().toString())     ;
            */
        }
       });

        btn1.setOnClickListener( new View.OnClickListener()
        {

           public void onClick(View v) {
            // TODO Auto-generated method stub

            if(check1==random1){
                display1.setTextColor(Color.GREEN);
                display1.setText(s);
            }
            else{
                display1.setTextColor(Color.RED);
                display1.setText(s);
            }
        }
       });
    }

A: The force close is very likely being caused as a result of a null pointer exception on display1. You should look for the instance in your onCreate() after you have initialized your layout else android is not going to be able to find that spinner via the findViewById()
Refer to: http://developer.android.com/training/basics/activity-lifecycle/starting.html#Create

A: You are doing this Spinner spinner1 = (Spinner) findViewById(R.id.spinner01);
in your class when you declare the variables.  These declarations are outside any method in your class and are therefore evaluated when your class is loaded and before your method code (beginning with onCreate() is called.
findViewById searches the currently loaded layout for a view with the matching id and returns the instance of it if found.  If not found, or no layout is loaded, it will return null.
Because it returns null, the first time you try to use the instance, you get a null pointer exception.
In your case, you must use fndViewById after you've called setContentView() which you should do in onCreate().
To fix your problem, declare the variable at the class level like this Spinner spinner1; then after setContentView, set the instance like this spinner1 = (Spinner) findViewById(R.id.spinner01);
It's perfectly logical for findViewById to return null rather than cause an exception if a view doesn't exist because in some scenarios, complex dynamic layouts might be determined at runtime according to some user input so something like if (findViewById(R.id.someview)==null) is valid.


text:
Q: Serre functor on the category $Perf(A)$, $A$ - k-algebra Consider a finite-dimensional $k$-algebra $A$ of finite global dimension. Then it is known that the Serre functor on $D^b(mod-A)$ exists and is given by the Nakayama functor. The proof goes something like this:
The $k$-duality $(-)^*=R\underline{\text{Hom}}_k(-,k)$ gives an equivalence $D^b(mod-A)\to D^b(A-mod).$ The $A$-duality $(-)^\vee=R\underline{\text{Hom}}_A(-,A)$ maps the category of perfect complexes $Perf(A)$ to $Perf(A^{op})$, because $A^\vee$ is isomorphic to $A$ in $A-mod$. Then one proves that for $M\in Perf(A)$, $N\in D^b(mod-A)$ we have
$$Hom_{D(Mod-A)} (M,N)^*\cong Hom_{D(Mod-A)} (N,M^{\vee*}).$$
Finally, we notice that for finite-dimensional algebras of finite global dimension $Perf(A)=D^b(A-mod).$
But what if $\text{r.gl.dim}(A)=\infty$? The only reason I see why the above proof might not give us a Serre functor on $Perf(A)$ is that $(-)^*$ may not map $Perf(A)$ to $Perf(A^{op})$, since $A$ is not necessarily isomorphic to $A^*$ as a left $A$-module. In this case, is it enough to have $A\cong A^{op}$?

A: The assumption on the finite global dimension is just needed to have $Perf(A)=D^b(A-mod),$ which does not hold more generality.
It is indeed true that $Perf(A)$ has a Serre functor (given in the same way) when $A$ just is a Gorenstein algebra, that is the regular module $A$ has finite injective dimension as a left and right $A$-modules.
For example any selfinjective non-semisimple algebra (such as $K[x]/(x^n)$ for $n \geq 2$) is a Gorenstein algebra of infinite global dimension.
Good references are:
"Representation Theory: A Homological Algebra Point of View" by Zimmermann and the book by Happel on Triangulated Categories.


text:
Q: ¿Por qué no se guardan las imágenes en caché? Estoy usando Picasso para poder traer imágenes a una aplicación Android desde un servidor REST.
El problema es que sí trae las imágenes, pero no las está guardando en memoria caché. Esto es en una Lista personalizada ListView.
En dicha lista personalizada, para evitar sobrecargar el servidor, designo a Picasso la tarea de descargar las imágenes para cada ítem que encuentre en la lista. Todo bien con las primeras, pero solo cuando recién deslizo hasta los que no son visibles, recién los carga y las primeras imágenes desaparecen (como si volvieran a cargarse de nuevo).
Aquí os dejo el código:
ArticuloAdapter.java
package com.movil.tienda.listadapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.movil.tienda.R;
import com.movil.tienda.activity.ArticuloActivity;
import com.movil.tienda.pojo.Articulo;
import com.movil.tienda.util.AppSession;
import com.movil.tienda.util.Methods;
import com.squareup.picasso.Picasso;

import java.util.List;

/**
 * Adapter utilizado para la lista personalizada de artículos.
 * Created by Jose Maria on 01/08/2017.
 */

public class ArticuloAdapter extends BaseAdapter implements AdapterView.OnItemClickListener {

    protected Activity activity;
    protected List<Articulo> list;
    protected Picasso picasso;

    public ArticuloAdapter(Activity act, List<Articulo> list) {
        this.activity = act;
        this.list = list;
        this.picasso = Picasso.with(act);
    }

    @Override
    public int getCount() {
        return this.list.size();
    }

    @Override
    public Object getItem(int i) {
        return this.list.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    /**
     * Por ahora, no se implementa, hasta que se haga una conexión a un servidor.
     * @param i
     * @param view
     * @param viewGroup
     * @return
     */
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        Articulo item = this.list.get(i);
        TextView nombre, precio;
        ImageView foto;
        LayoutInflater inflater = (LayoutInflater) this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.item_articulo, null);
        nombre = (TextView) view.findViewById(R.id.item_article_name);
        precio = (TextView) view.findViewById(R.id.item_article_price);
        foto = (ImageView) view.findViewById(R.id.item_article_img);
        nombre.setText(item.getNombre());
        precio.setText(Methods.parsePrecio(item.getPrecio()));
        Log.i("Imagen de articulo", Methods.Parameters.ARTICULO_GET_IMAGEN + item.getId());
        this.picasso.load(Methods.Parameters.ARTICULO_GET_IMAGEN + item.getId()).into(foto);
        return view;
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Intent intent = new Intent(this.activity, ArticuloActivity.class);
        AppSession.getInstance().setAttribute(Methods.Parameters.SESSION_ARTICULO, this.list.get(i).getId());
        this.activity.startActivity(intent);
    }

    public void clear() {
        this.list.clear();
    }

}

A: Picasso optimiza de una muy buena forma el cargado de imágenes, crea un cache para evitar peticiones al servidor y descargar nuevamente las imágenes.
Pero este proceso de carga de la imagen de caché nuevamente al ImageView puede en ocasiones presentarse como si se estuviera cargando nuevamente la imagen, primeramente porque requiere un proceso de manipulación de los bits que conforman la imagen para agregarlo al ImageView y segundo por el proceso de reciclamiento de tus vistas, ya que por buena practica la imágenes no deberían quedarse siempre en el ListView, esto ocasionaría problemas de memoria.
Te sugiero habilites la opción setIndicatorsEnabled(true) para que puedas ver en realidad se esta cargando de caché la imagen:
Picasso.with(context).setIndicatorsEnabled(true);

Más información:
http://square.github.io/picasso/


text:
Q: How to make Silex\Debug return JSON inside Silex App I have a class that throws errors that extends from the base Exception.
The App's core is Silex Micro-Framework - but due to the fact that I am more fluent in Laravel than Symfony (despite Laravel being derived from it) I tend to use some packages from illuminate (hence the reason why you will see some use Illuminate\)
I want to throw an exception when an error occurs but I am getting the integrated Whoops instead. I would like to return JSON instead. (its not the full stack whoops but Symfony\component\debug instead)
Ideally array('status' => <code>, 'message_content');
Question is: a) how do i do it considering its silex with debug that looks like whoops (this service is on by default). b) is there a way to use my class that extends Exception bellow or am i in need of creating an entire new Exception class that suits my needs instead from scratch
namespace Api\Manager\Validation;

use Illuminate\Support\MessageBag;

class ValidationException extends \Exception {

/**
 * @var MessageBag
 */
protected $errors;

/**
 * @param string     $message
 * @param MessageBag $errors
 */
function __construct($message, MessageBag $errors)
{
    $this->errors = $errors;

    parent::__construct($message);
}

/**
 * Get form validation errors
 *
 * @return MessageBag
 */
public function getErrors()
{
    return $this->errors;
}

}

A: I'm assuming you're using the WhoopsServiceProvider to integrate into Silex - you should have the following in your app.php or index_dev.php.
$app->register(new WhoopsServiceProvider());

You can see the code for this here.
It appears to hardcode the PrettyPageHandler.
$app['whoops.error_page_handler'] = $app->share(function() {
    return new PrettyPageHandler;
});

If you fork this provider/copy it into your own, then you should be able to replace this with the JsonRespondeHandler.
You will also need to remove some of the other code in the Provider. e.g. the whoops.silex_info_handler will not work for you as it includes some calls like addDataTable() which I think are specific to the PrettyPageHandler class.
$app['whoops'] = $app->share(function() use($app) {
    $run = new Run;
    $run->allowQuit(false);
    $run->pushHandler($app['whoops.error_page_handler']);
    $run->pushHandler($app['whoops.silex_info_handler']);
    return $run;
});

Without actually testing the above I believe that should mean all your exceptions caught by Whoops will be rendered in JSON, so you won't (and shouldn't) need to create individual exception classes that render JSON specifically.
Update
It's actually a lot more straightforward than that. Just put the below in your index_dev.php after "$app = new Silex\Application();".
$app->error(function (\Exception $e, $code) use($app) {
    return $app->json(array("error" => $e->getMessage()),$code);
});

Then exceptions will be output as JSON. The solution is actually from another SO question here.


text:
Q: SimpleMessageListenerContainer doesn't start on time Unable to start SimpleMessageListenerContainer in reasonable amount of time. What could cause this problem?
The broker is up and running ok.
Container blocks on the method that is shown bellow.

The log is cycling for all created queues but it takes to long, the sample is provided below.
https://gist.github.com/anonymous/d1a4339eb345eb0ce050
Spring AMQP v.1.4.4
Rabbit config is default (with several enabled plugins like x-consistent-hash)
And it worked pretty fast when we used on consumer per queue.


text:
Q: How do i set up proxy in selenium? I have been trying to implement proxy to my selenium webdriver. Have no idea what's wrong with my code. Any idea?
import os
from selenium import webdriver
def open_browser():
    chromeUrl= "C:/Users/Drivers/chromedriver.exe"
    firefoxUrl= "C:/Users/Drivers/geckodriver.exe"
    edgeUrl="C:/Users/Drivers/MicrosoftWebDriver.exe"
    print("Starting opening web browser")
    try:
        f= open('saved/proxy.txt','r')
        proxy_ip = f.read()
        f.close()
        PROXY= proxy_ip
        print("I have download a proxy: " + PROXY)

        if len(proxy_ip) <= 1:
            print("No Proxy will be used...")
            driver = webdriver.Firefox(executable_path= firefoxUrl)

        else:
             webdriver.DesiredCapabilities.Edge['proxy'] = {
            "httpProxy":PROXY,
            "ftpProxy":PROXY,
            "sslProxy":PROXY,
            "noProxy":None,
            "proxyType":"MANUAL",
            "class":"org.openqa.selenium.Proxy",
            "autodetect":False}
            driver = webdriver.Remote("http://localhost:4444/wd/hub", webdriver.DesiredCapabilities.Edge(EdgeUrl))

    except:
        os.system("python proxy_request.py")
        print("Warning: No proxy")
        driver = webdriver.Edge(executable_path= "C:/Users/Drivers/MicrosoftWebDriver.exe")
    driver.implicitly_wait(10)
    driver.set_page_load_timeout(300)
    return driver
driver = open_browser()
url = 'htttp://www.google.com'
driver.get(url)

I couldn't deal with the problem. Half of the code in from official webdriver documentation, although i couldn't find one for EDGE.

A: According to official docs, proxy isn't supported by edge webdriver. And it seems, MS hasn't wish to work on it.

A: There is nothing much written in official docs to add proxies in edge webdriver. However you can use edgeOptions.AddArgument("--user-agent=xxx") and edgeOptions.AddArgument("--proxy-server=xxx") to set the proxy and user agent.
options = EdgeOptions()
options.use_chromium = True
options.add_argument("headless")
options.add_argument("disable-gpu")
#Here we try to set Firefox user agent...
options.add_argument("--user-agent=mozilla/5.0 (windows nt 10.0; win64; x64; rv:78.0) gecko/20100101 firefox/78.0");
#Change the link below for adding proxy
options.add_argument("--proxy-erver=http://user:password@yourProxyServer.com:8080");

Reference:
https://learn.microsoft.com/en-us/answers/questions/376056/microsoftedgeseleniumtools-assign-a-custom-proxy.html


text:
Q: Method cannot resolved I am trying to send data to firebase.
I want to call the time and date in a method and the method is responsible for sending data to fire base.
When I try to call time and date it gives me this error.
getText.toString method cannot resolved

on this line:
myRef.setValue(ft1.getText().toString());

and other uses of .getText.
My code:
public class Room1 extends AppCompatActivity {
    boolean hasSetTime = false;
    boolean hasSetDate = false;
    boolean hasSetTime1 = false;

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.room1);

        final Calendar c = Calendar.getInstance();
        final int year = c.get(Calendar.YEAR);
        final int month = c.get(Calendar.MONTH);
        final int day = c.get(Calendar.DAY_OF_MONTH);
        final int hour = c.get(Calendar.HOUR_OF_DAY);
        final int minute1 = c.get(Calendar.MINUTE);
        final Calendar v = Calendar.getInstance();
        final int hour2 = v.get(Calendar.HOUR_OF_DAY);
        final int minute2 = v.get(Calendar.MINUTE);

        final String date;
        final EditText ft1;
        final EditText fd1;
        final EditText e1;

         ft1 = (EditText) findViewById(R.id.ft1);
        fd1 = (EditText) findViewById(R.id.fd1);
         e1 = (EditText) findViewById(R.id.e1);

        fd1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatePickerDialog datepick = new DatePickerDialog(Room1.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        fd1.setText(dayOfMonth + "/" + month + "/" + year);

                        SimpleDateFormat dateFormatter;
                        Date d;
                        String entered_dob;

                        d = new Date(year, month, day);
                        dateFormatter = new SimpleDateFormat("MM-dd-yyyy");
                        entered_dob = dateFormatter.format(fd1.getText());
                        hasSetDate = true;
                        sendDataToFireBase();
                    }
                },
                        year, month, day);
                datepick.setTitle("select date");
                datepick.show();

            }
        });

        e1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerDialog timepickend = new TimePickerDialog(Room1.this, new TimePickerDialog.OnTimeSetListener() {

                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        e1.setText(hourOfDay + ":" + minute);
                        hasSetTime = true;
                        sendDataToFireBase();
                    }
                }, hour2, minute2, true
                );
                timepickend.setTitle("select time");
                timepickend.show();

            }
        });

        ft1.setOnClickListener(new View.OnClickListener() {
                                   @Override
                                   public void onClick(View v) {
                                       TimePickerDialog timepick = new TimePickerDialog(Room1.this, new TimePickerDialog.OnTimeSetListener() {

                                           @Override
                                           public void onTimeSet(TimePicker view, int hourOfDay2, int minute2) {
                                               ft1.setText(hourOfDay2 + ":" + minute2);
                                               hasSetTime1=true;
                                               sendDataToFireBase();
                                           }
                                       }, hour, minute1, true
                                       );
                                       timepick.setTitle("select time");
                                       timepick.show();

                                   }
                               }
        );

    }

    public  void sendDataToFireBase() {

        if (hasSetTime == true && hasSetDate==true&&hasSetTime1==true) {
            FirebaseDatabase database = FirebaseDatabase.getInstance();
            DatabaseReference myRef = database.getReference("Date");
            myRef.setValue(ft1.getText().toString());
            DatabaseReference myRef2 = database.getReference("Time");
            myRef2.setValue(e1.getText().toString());
            DatabaseReference myRef3 = database.getReference("Timereserved");
            myRef2.setValue(fd1.getText().toString());
        }
    }
}

A: public void sendDataToFireBase() {
    ft1 // <-----get rid of this
    if


text:
Q: Solr Highlight only in fields that have results I have a solr query where I search for (webpage_text:*test* OR company_text:*test*)
In my highlighting I set my fields to webpage_text, company_text. But now I always get BOTH fields in the highlighting result, even when the search term is only found in webpage_text, I also get a highlight result for company_text which is just the full field.
Is it possible to only return the highlights for the fields that had a match ?
I tried requireFieldMatch but that doesn't work.
@EDIT: Might be important information: the 2 fields, are actually empty fields that are filled by copy fields. Does this have an impact ?
<field name="company_text" type="text_general" indexed="true" stored="true" multiValued="true" default="" termVectors="true" termPositions="true" termOffsets="true"/>
<field name="webpage_text" type="text_general" indexed="true" stored="true" multiValued="true" default="" termVectors="true" termPositions="true" termOffsets="true"/>

<dynamicField name="*company_*" type="string" indexed="true" stored="true" multiValued="true"/>
<dynamicField name="*talent_*" type="string" indexed="true" stored="true" multiValued="true"/>

<copyField source="company_*" dest="company_text" maxLength="30000000"/>
<copyField source="webpage_*" dest="webpage_text" maxLength="30000000"/>

@EDIT2: It appears that the copyfields ALWAYS appear in the highlight, even if they have no matches.

A: I believe that the requireFieldMatch option is what you need to use. However, for this to work, you will need to also enable usePhraseHighlighter and then make sure you are doing PhraseQueries by wrapping your terms in quotes. (eg. webpage_text:"*test*")
So an example might be the following:
http://localhost:8983/solr/select/q=webpage_text%3A"*test*"+OR
  +company_text%3A"*test*"&wt=xml&hl=true&hl.fl=webpage_text%2Ccompany_text
  &hl.simple.pre=<em>&hl.simple.post=<%2Fem>
  &hl.requireFieldMatch=true&hl.usePhraseHighlighter=true

You will need to adjust the server settings as needed and additional parameters for your scenario.

A: Solr always returns ALL fields if not specified otherwise. It does not matter whether the field is included in the search query. Fields with a match are highlighted.
If you have only two field, so these two/all fields are returned and one of them is highlighted.


text:
Q: Which value should be returned by a apollo graphql mutation? I'm using apollo graphql to call some mutation to change db data. I need some advice which value should be returned usually.
For insertOne() I would return the ID of the new document and for removing a dataset I would also return the ID, to remove the dataset on the client cache.
But what about updateOne - as it could be a very simple task as shown below, but sometimes it can do some complex update? I'm not quite sure which would be the most useful returning value.
In this simple example I'm just updating some content of a specific mongodb document. Right now the WriteResult of this method is returned. But is this really useful?
I see the follwing options:

*

*Returning writeResult object - which has the need to be defined in the backend

*Check writeResult and return boolean, e.g. result.nModified > 0

*Return the content result - which would be at the end just the input content

*Returning the updated document - which would need a findOne({ _id: id })

*Just returning true, which maybe is not very useful?!

I know there is not a single solution for all use cases, but maybe someone could explain which way to go in general...
server
async updateContent(id, name, value) {
  const Content = this.db.collection('content')
  return Content.updateOne(
    { _id: id },
    { $set: { [name]: value } }
  )
}

client
updateContent({
  variables: { id, name, value }
})
  .then((response) => {
    // response.data.updateContent
  })
  .catch((error) => console.error(error))

graphql
mutation updateContent($id: ID!, $name: String, $value: String) {
  updateContent(id: $id, name: $name, value: $value) {
    nModified
  }
}

schema
type WriteResult {
  nModified: Int,
  nRemoved: Int,
  nInserted: Int,
  n: Int
  ok: Int
}

type Mutation {
  updateContent(id: ID!, name: String, value: String): ContentString
}

A: extending earlier comment ...

usually mutation resolver returns ... mutated type (but it's a graphql, you don't have to query for all fields/props; response will be filtered out; returning data = success) ... even deleted ones, surprise! :D

Returning mutated object type can be important for more advanced FE techniques like optimistic response. This helps you avoid refetching entire item list when you're updating one element.
in this case
Types are not defined properly - this is your source of concerns
Probably you should define it more like (input types are more manageable):
type ContentType {
  id: ID!
  content: String!
  author: User!
  createdAt: Date!
  updatedAt: Date!
}
type ContentCreateInputType {
  name: String!
  value: String!
}
type ContentUpdateInputType {
  id: ID!
  name: String!
  value: String!
}

type Stats {
  nModified: Int,
  nRemoved: Int,
  nInserted: Int,
  n: Int
  ok: Int
}
type ContentUpdatePayload {
  content: ContentType
  stats: Stats
}

type Mutation {
  updateContent(input: ContentUpdateInputType!): ContentUpdatePayload
}

This is a bit similiar idea to popular relay style cursor pagination.
Your mutation can be:
mutation updateContent($input: ContentUpdateInputType) {
  updateContent(input: $input) {
    stats {
      nModified
    }
  }
}

... in this case your resolver must return only stats object, no findOne required ... but in practice it should return at least:
{
  content: {
    id
  }
  stats: {
    nModified
    nRemoved
    // etc.
  }
}

... because your mutation can be also:
mutation updateContent($input: ContentUpdateInputType) {
  updateContent(input: $input) {
    content {
      id
      content
      author {
        id
        name
      }
    }
    stats {
      nModified
    }
  }
}

Returning { content: { id } stats: {....} } (js object, the minimal mutation response) is neccessary (very important) to resolve entire query. Server resolver will know it has not complete ContentType object (mutation ContentUpdatePayload element) and it will call ContentType resolver (with known/already resolved id as arg) to populate it (of course it will call Author type resolver, too).
As you can notice/see above, returning only a content { id } (from this mutation, part of ContentType) can be a part of the optimization - no overfetching - because id can be taken from mutation args and the entire content is resolved/read from DB/service only when required.
conclusion
Returning not typed responses simply doesn't allow this kind of 'GraphQL magic'.


text:
Q: C++ - Speed up installs using vcpkg I am new to C++ and needed to download a package, so I thought I would use vcpkg. The problem is vcpkg was slower than I expected. Here is my syntax:
vcpkg install <PACKAGE>

Vcpkg takes a lot of time, which makes me wonder if there is a flag to speed up the vcpkg download speed.

A: vcpkg does not download pre-built binaries; it downloads source files and does the builds on your machine.
Therefore, it is most likely not the download that is taking up a lot of time, but the build itself. There is no flag that can speed up the builds, but it is possible to export binaries, so you really only have to build a specific set of libraries only once.
If you are interested in why vcpkg chooses to be source-based as opposed to binary-based, you can consult this


text:
Q: Silently handle errors in powershell I am writing a troubleshooting script to determine which IP addresses in our Domain are accessible by WMI, and which are not. The script will read a list of input parameters (about 18,000 lines), and will output to a file the IP address and the username
IP address, Username

Problem is, when the WMI error is thrown, it writes to the file
IP address, Get-WmiObject : The RPC server is unavailable. .....numerous lines of error

I would like to make it such that when a WMI error it thrown, it writes the following
IP address, "WMI ERROR"

And here is the modified code for reference
#script_modified.ps1

$abc = $args
$startInfo = $NULL
$process = $NULL
$standardOut = $NULL

<#Previously created password file in C:\Script\cred.txt, read-host -assecurestring | convertfrom-securestring | out-file C:\Script\cred.txt#>
$password = get-content C:\Script\cred.txt | convertto-securestring

$a = Get-Content "C:\Script\test_input.txt"

foreach ($b in $a){

    $startInfo = New-Object System.Diagnostics.ProcessStartInfo
    $startInfo.FileName = "powershell.exe"
    $startInfo.Arguments = "C:\script\script2.ps1 " + $b

    $startInfo.RedirectStandardOutput = $true
    $startInfo.UseShellExecute = $false
    $startInfo.CreateNoWindow = $false
    $startInfo.Username = "service.infosec"
    $startInfo.Domain = "Central"
    $startInfo.Password = $password

    $process = New-Object System.Diagnostics.Process
    $process.StartInfo = $startInfo
    $process.Start() | Out-Null
    $standardOut = $process.StandardOutput.ReadToEnd()
    $process.WaitForExit()

    # $standardOut should contain the results of "C:\script\script2.ps1"

   Add-Content C:\script\list_of_computers_in_DOMAIN.log $b","$standardOut
}

EDIT
@Hyper Anthony
I updated my code to the following
try{
    $process.StartInfo = $startInfo
}
catch{
    $message = "WMI ERROR"
}
finally{
    $process.WaitForExit()
    Add-Content C:\script\list_of_computers_in_DOMAIN.log $b","$message
}

And I get following errors:
Exception calling "WaitForExit" with "0" argument(s): "No process is associated with this object."
At C:\script\script_modified.ps1:36 char:29
+         $process.WaitForExit <<<< ()
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

How to fix?
EDIT:
Below is the updated code:
foreach ($b in $a){

    $startInfo = New-Object System.Diagnostics.ProcessStartInfo
    $startInfo.FileName = "powershell.exe"

    ...More Code...

    $process = New-Object System.Diagnostics.Process
    $process.StartInfo = $startInfo

    try{
        $process.Start() | Out-Null
        $standardOut = $process.StandardOutput.ReadToEnd()
    }
    catch{
        $standardOut = "WMI ERROR"
    }
    finally{
        $process.WaitForExit()
        Add-Content C:\script\list_of_computers_in_DOMAIN.log $b","$standardOut
    }

}

There are no longer any errors that get output to the console, BUT, the output file is not as I wish.
When there is an WMI error, I would like the following line to be written

'sender-ip=10.10.10.10', WMI Error

But instead, the following is written

'sender-ip=10.10.10.10',Get-WmiObject : The RPC server is unavailable.
  (Exception from HRESULT: 0x800706BA) ...many lines of error

or any other error may be printed instead of WMI Error.
Thanks once again!


text:
Q: Check DB int field against timestamp iam saving a date to my database as timestamp ( int field )
Now i have an external date in my php which i convert also into timestamp to compare it later.
I must make the check in the query, i cant select the date from the db before to compare them afterwards
What i need:
I wanna see if the external date is same date as the stored int value. the compare should only cover yyyy-mm-dd
little example.
my external date is 2011-02-23, which is only present without hours, the stored timestamp is lets say 123747382
What would a mysql query where clause look like, or what php am i missing in order to know that both stamps are the same date?
$r_date = '2011-02-23';
$stamp_day = strtotime($r_date);

WHERE addtime = '{$stamp_day}'

addtime would be the stored timestamp in the int field
Thank you

A: try this:
"WHERE DATE( FROM_UNIXTIME( `addtime` ) ) = '$r_date'"

or:
"WHERE DATE( FROM_UNIXTIME( `addtime` ) ) = DATE( FROM_UNIXTIME( '$stamp_day' ) )"


text:
Q: Android resolution always using x-large drawables in any device I am developing an Android application. I am trying to deploy it in 3 devices with different resolutions and these are Samsung pocket GT-S5300 android 2.3.6, Samsung young GT-S6310 android 4.1.2, PIpo M8 tablet android 4.1.1. I am having a big problem when it comes to deploying the app because in my 2 samsung devices they're using the layout-xlarge instead of my default layout. Icons appears bigger and I think that they are all using the xlarge instead of the normal one. I don't know why. Please help me. I really want these 3 different resolutions to have different layout and drawables sizes.
Here is my manifest
   android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="8" />
<uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

<supports-screens
    android:largeScreens="false"
    android:smallScreens="true"
    android:resizeable="true"
    android:normalScreens="true"
    android:anyDensity="true" />

all of this layout folder contains same layouts
samsung pocket appearance

Pipo M8 appearance

A: Here's some general tips and ideas:
firstly, why are you targeting API 8? you should be targeting current versions of android, which is while writing 19 (you can still have minSDK 8).
Use dp qualifiers such as layout-sw600dp layout-sw720dp to cover small and large tablets.
Also I'm noticing there's nothing in your xhdpi folder which is getting pretty standard on most new devices. I'm hoping you know how to format these images in qualifier folders? for example mdpi is basically 72dpi as your computer monitor hdpi resources should be around 1.5 times larger than mdpi resources and so forth. This is probably where your problem lies.


text:
Q: How do I download Stack Overflow's data? I heard that Stack Overflow's Question/Answer data is downloadable.
How can I get it?

A: The data dump used to be hosted on Clearbits, which was shut down at some point.
Stack Exchange is now hosting the data dump  in the Internet Archive: https://archive.org/details/stackexchange
For more details, you can read the official blog post.


text:
Q: How to add a SearchBar to the top of page like toolbaritems icon with Xamarin.Forms I am using masterdetail page within this page i am using tabbed page now i want to show toolbar icon and search bar on the top of page.i am able to place toolbar icon but struggling with search bar.how to place it at the top its behavior should match with the search bar in whatsapp app and in youtube app

A: The WhatsApp search bar is just that, a SearchBar control which you can add to your XAML layout as follows:
<StackLayout>
    <SearchBar Placeholder="Search" Text="{Binding Filter}" />
    <ListView ItemSource="{Binding Items}">
        ...
    </ListView>
</StackLayout>

Ensure you have a backing property for the filter. You can use the setter of this property to intercept people filtering the data and filter the Items property accordingly.
The YouTube search behaves a bit differently. The toolbar item pops a new screen modally where the search is handled similar to a UISearchController (on iOS). There is no Xamarin Forms drop-in control (that I'm aware of) that does this for you so you'll probably have to roll your own.

A: We can create a custom renderer on both Xamarin.iOS and Xamarin.Android to accomplish it.
Here's a sample application for reference:
https://github.com/brminnick/GitTrends
And here's a blog post that shows how to add a search bar to a Xamarin.Forms app for both Xamarin.iOS & Xamarin.Android: https://www.codetraveler.io/2019/08/10/adding-a-search-bar-to-xamarin-forms-navigationpage/
App.cs
Use a Xamarin.Forms Platform-Specific to use LargeTitles on the Xamarin.iOS app.
using Xamarin.Forms.PlatformConfiguration;
using Xamarin.Forms.PlatformConfiguration.iOSSpecific;

public class App : Xamarin.Forms.Application
{
    public App()
    {
        var navigationPage = new Xamarin.Forms.NavigationPage(new MyContentPage());

        navigationPage.On<iOS>().SetPrefersLargeTitles(true);

        MainPage = navigationPage;
    }
}

ISearchPage Interface
Create an Interface that can be used across the Xamarin.Forms, Xamarin.Android and Xamarin.iOS projects.
public interface ISearchPage
{
    void OnSearchBarTextChanged(in string text);
    event EventHandler<string> SearchBarTextChanged;
}

Xamarin.Forms Page
public class MyContentPage : ContentPage, ISearchPage
{
    public MyContentPage()
    {
        SearchBarTextChanged += HandleSearchBarTextChanged
    }

    public event EventHandler<string> SearchBarTextChanged;

    public void OnSearchBarTextChanged(in string text) => SearchBarTextChanged?.Invoke(this, text);

    void HandleSearchBarTextChanged(object sender, string searchBarText)
    {
        //Logic to handle updated search bar text
    }
}

iOS Custom Renderer
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UIKit;
using MyNamespace;
using MyNamespace.iOS;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(MyContentPage), typeof(SearchPageRenderer))]
namespace MyNamespace.iOS
{
    public class SearchPageRenderer : PageRenderer, IUISearchResultsUpdating
    {
        readonly UISearchController _searchController;

        public SearchPageRenderer()
        {
            _searchController = new UISearchController(searchResultsController: null)
            {
                SearchResultsUpdater = this,
                DimsBackgroundDuringPresentation = false,
                HidesNavigationBarDuringPresentation = false,
                HidesBottomBarWhenPushed = true
            };
            _searchController.SearchBar.Placeholder = string.Empty;
        }

        public override void ViewDidAppear(bool animated)
        {
            base.ViewDidAppear(animated);

            if (ParentViewController.NavigationItem.SearchController is null)
            {
                ParentViewController.NavigationItem.SearchController = _searchController;
                DefinesPresentationContext = true;

                //Work-around to ensure the SearchController appears when the page first appears https://stackoverflow.com/a/46313164/5953643
                ParentViewController.NavigationItem.SearchController.Active = true;
                ParentViewController.NavigationItem.SearchController.Active = false;
            }
        }

        public override void ViewWillDisappear(bool animated)
        {
            base.ViewWillDisappear(animated);

            ParentViewController.NavigationItem.SearchController = null;
        }

        public void UpdateSearchResultsForSearchController(UISearchController searchController)
        {
            if (Element is ISearchPage searchPage)
                searchPage.OnSearchBarTextChanged(searchController.SearchBar.Text);
        }
    }
}

Xamarin.Android Menu XML

*

*In the Xamarin.Android project, in the Resources folder, create a new folder called menu  (if one doesn't already exist).

*

*Note: the folder, menu, has a lowercase 'm'

*In the Resources > menu folder, create a new file called MainMenu.xml.

*Open Resources > menu > MainMenu.xml

*In MainMenu.xml add the following code:
<?xml version="1.0" encoding="utf-8" ?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">
  <item android:id="@+id/ActionSearch"
        android:title="Filter"
        android:icon="@android:drawable/ic_menu_search"
        app:showAsAction="always|collapseActionView"
        app:actionViewClass="android.support.v7.widget.SearchView"/>
</menu>

Xamarin.Android CustomRenderer
Uses the Plugin.CurrentActivity NuGet Package.
using Android.Content;
using Android.Runtime;
using Android.Support.V7.Widget;
using Android.Text;
using Android.Views.InputMethods;
using Plugin.CurrentActivity;
using MyNamespace;
using MyNamespace.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof(MyContentPage), typeof(SearchPageRenderer))]
namespace MyNamespace.Droid
{
    public class SearchPageRenderer : PageRenderer
    {
        public SearchPageRenderer(Context context) : base(context)
        {

        }

        protected override void OnAttachedToWindow()
        {
            base.OnAttachedToWindow();

            if (Element is ISearchPage && Element is Page page && page.Parent is NavigationPage navigationPage)
            {
                //Workaround to re-add the SearchView when navigating back to an ISearchPage, because Xamarin.Forms automatically removes it
                navigationPage.Popped += HandleNavigationPagePopped;
                navigationPage.PoppedToRoot += HandleNavigationPagePopped;
            }
        }

        //Adding the SearchBar in OnSizeChanged ensures the SearchBar is re-added after the device is rotated, because Xamarin.Forms automatically removes it
        protected override void OnSizeChanged(int w, int h, int oldw, int oldh)
        {
            base.OnSizeChanged(w, h, oldw, oldh);

            if (Element is ISearchPage && Element is Page page && page.Parent is NavigationPage navigationPage && navigationPage.CurrentPage is ISearchPage)
            {
                AddSearchToToolbar(page.Title);
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (GetToolbar() is Toolbar toolBar)
                toolBar.Menu?.RemoveItem(Resource.Menu.MainMenu);

            base.Dispose(disposing);
        }

        //Workaround to re-add the SearchView when navigating back to an ISearchPage, because Xamarin.Forms automatically removes it
        void HandleNavigationPagePopped(object sender, NavigationEventArgs e)
        {
            if (sender is NavigationPage navigationPage
                && navigationPage.CurrentPage is ISearchPage)
            {
                AddSearchToToolbar(navigationPage.CurrentPage.Title);
            }
        }

        void AddSearchToToolbar(string pageTitle)
        {
            if (GetToolbar() is Toolbar toolBar
                && toolBar.Menu?.FindItem(Resource.Id.ActionSearch)?.ActionView?.JavaCast<SearchView>().GetType() != typeof(SearchView))
            {
                toolBar.Title = pageTitle;
                toolBar.InflateMenu(Resource.Menu.MainMenu);

                if (toolBar.Menu?.FindItem(Resource.Id.ActionSearch)?.ActionView?.JavaCast<SearchView>() is SearchView searchView)
                {
                    searchView.QueryTextChange += HandleQueryTextChange;
                    searchView.ImeOptions = (int)ImeAction.Search;
                    searchView.InputType = (int)InputTypes.TextVariationFilter;
                    searchView.MaxWidth = int.MaxValue; //Set to full width - http://stackoverflow.com/questions/31456102/searchview-doesnt-expand-full-width
                }
            }
        }

        void HandleQueryTextChange(object sender, SearchView.QueryTextChangeEventArgs e)
        {
            if (Element is ISearchPage searchPage)
                searchPage.OnSearchBarTextChanged(e.NewText);
        }

        Toolbar GetToolbar() => CrossCurrentActivity.Current.Activity.FindViewById<Toolbar>(Resource.Id.toolbar);
    }
}

Sample App
Here's a sample app for reference:
https://github.com/brminnick/GitTrends
And a blog post that shows how to add a search bar for both Xamarin.iOS and Xamarin.Android: https://www.codetraveler.io/2019/08/10/adding-a-search-bar-to-xamarin-forms-navigationpage/

A: Used User Control for Navbar. and hide Navigarionbar using
NavigationPage.SetHasNavigationBar (this, false);

A: Check following link may be it's help you. and i think it's for your requirement.
http://blog.xhackers.co/xamarin-forms-contentpage-with-searchbar-in-the-navigation-bar/
Placing a SearchBar in the top/navigation bar
How to include view in NavigationBar of Xamarin Forms?
install or update Android support repository, google play service and Google USB driver

A: if you'r using shell app you can use Shell.TitleView instead of Navigation.TitleView as the following :
        <Shell.TitleView>

        <SearchBar x:Name="search"  Margin="10,10,10,10"
                   HorizontalOptions="FillAndExpand"/>

        </Shell.TitleView>


text:
Q: Insert ")" to complete Expression error while new HashMap as parameter I get the error: Syntax error, insert ")" to complete Expression when I am trying to do this:
public interface IConectorT extends Library {
HashMap<String, String> xx= new HashMap<>();
IConectorT INSTANCE = (IConectorT) Native.loadLibrary("Eloqua API", IConectorT.class, new
HashMap{{
      put("DeleteCustomObjectRecord", "DeleteCustomObjectRecord@8");
      }});
}

Why is that? I thought its because it isnt JRE 1.7 but changing to that didn't help.

A: HashMap constructor missing the parenthesis
new HashMap{{

should be
 new HashMap(){{


text:
Q: IDX10500: Signature validation failed. Unable to resolve SecurityKeyIdentifier What might the reason be that I get the exception below when trying to validate a token.
TokenValidationParameters validationParameters = new TokenValidationParameters();

validationParameters.ValidIssuers = new List<string>() { "http://www.company.com" };

validationParameters.IssuerSigningToken = new RsaSecurityToken(
  (System.Security.Cryptography.RSACryptoServiceProvider) Certificate.Get().PublicKey.Key);

SecurityToken securityToken = null;

var claimsPrincipal =
    (FederatedAuthentication
      .FederationConfiguration
      .IdentityConfiguration
      .SecurityTokenHandlers
      .First() as JwtSecurityTokenHandler)
      .ValidateToken(tokenString, validationParameters, out securityToken);

Error:
IDX10500: Signature validation failed. Unable to resolve SecurityKeyIdentifier:
          'SecurityKeyIdentifier
    (
      IsReadOnly = False,
      Count = 2,
      Clause[0] = X509ThumbprintKeyIdentifierClause(
                    Hash = 0x6B7ACC520305BFDB4F7252DAEB2177CC091FAAE1),
    Clause[1] = System.IdentityModel.Tokens.NamedKeySecurityKeyIdentifierClause
    )
',
token: '{"typ":"JWT","alg":"RS256","

A: From the error, I think you need to add an x509  Security key or credentials, something like this:
var credentials = new X509CertificateCredentials(
    Certificate.Get(),
    new SecurityKeyIdentifier(
        new NamedKeySecurityKeyIdentifierClause(
            "kid",
            "6B7ACC520305BFDB4F7252DAEB2177CC091FAAE1")));

eg this part:
new SecurityKeyIdentifier(
        new NamedKeySecurityKeyIdentifierClause(
            "kid",
            "6B7ACC520305BFDB4F7252DAEB2177CC091FAAE1")

Also, make sure your certificate is installed in your root store.


text:
Q: What part of the electron mass is due to Yukawa coupling? Sorry if this question is wrong - then please correct it.
A particle mass can be due to a Dirac mass term or due to a Yukawa mass term. In the standard model, which percentage of the electron mass is due to which term?
Added after the comments came in:
The comments explain that Yukawa coupling generate Dirac terms. So allow me to ask the question in this way.
Could there be an intrinsic Dirac mass and a Yukawa-induced mass? Or, again differently: Does really all mass derive from Yukawa coupling or could it be that only a part of the mass comes from coupling to the Higgs?
I remember that I read (serious) papers explaining that both an intrinsic and a Yukawa aspect of the mass could exist. But I just cannot remember where...

A: First let's consider this in the context of a very simple toy model, which however is not the Standard Model. In particular, we will just imagine one fermion and one scalar field with a Yukawa coupling
\begin{equation}
S = \int {\rm d}^4 x \left( - \frac{1}{2}(\partial \phi)^2 -V(\phi )+ i\bar{\psi} \gamma^\mu \partial_\mu \psi - m \bar\psi \psi - g \bar\psi \phi \psi \right)
\end{equation}
Now if the scalar field has a VEV $\bar\Phi$, so $\phi = \bar\Phi+\varphi$, then the fermions have a physical mass
\begin{equation}
m_{\rm phys} \equiv m + g \bar{\Phi}
\end{equation}
This physical mass is the quantity that is actually observed, since it corresponds to a pole in the fermion propagator.
Meanwhile, three point scattering between the scalar particles $\varphi$ and the fermions will lead to a three point interaction, with a scattering amplitude
\begin{equation}
\mathcal{A}_{\bar\psi \varphi \psi} \propto i g + ...
\end{equation}
where the $...$ refers to higher order corrections, and I've been lazy with delta functions and spin traces. Therefore, the Yukawa couplings can be determined via scattering processes with the Higgs.
Since the VEV is a constant, if the Dirac mass is zero, this implies that there is a relationship between the scattering amplitudes between fermions and the Higgs, and the fermion masses. In particular, with multiple generations of fermions, the ratio of top-quark-higgs scattering amplitudes to bottom-quark-higgs scattering amplitudes, should be related to the ratio of the top and bottom quark physical masses. If each fermion had its own Dirac mass unrelated to the Yukawa couplings, this would break the relationship between the scattering amplitudes and physical masses.
That's how things work in the toy model. However, in the Standard Model, there is an extra wrinkle. In particular, there the weak interactions are a chiral gauge symmetry $SU(2)_L$ which only acts on left-handed fermions. A Dirac mass term couples left and right handed fermions, and so necessarily break the chiral gauge symmetry. Therefore in the Standard Model, the Dirac mass must be exactly zero. Of course, that doesn't stop people from checking if the Yukawa couplings are consistent with the masses, since of course finding any violation of predictions from the Standard Model would be very exciting and important.
To summarize, our current state of knowledge is that the Dirac masses must be exactly zero, to preserve the chiral gauge invariance. However, there are experimental tests that can be done to check this. Measuring the interaction strengths between particles and the Higgs is one of the goals of the proposed next generation colliders, in part for this reason.


text:
Q: Use Wildcard / Regex in filter settings of SSMS object explorer to find an object Is there a way to fine tune the SQL Server Management Studio Filter Settings results (in the Object Explorer) by using wildcards to find objects like XYZ_unknown_abc using a Contains operator?
I tried (XYZ*abc) or (XYZ abc) with no luck.

A: Coming a bit late, but %XYZ%abc% in the search box shows db object with names containing XYZ and abc, in that order.

A: Wildcards are still not allowed in the filter setting within Object Explorer in SSMS. BTW .. you can check this new set of Operators: https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2005/ms181166(v=sql.90)


text:
Q: why evaluateJavascript crashes? I'm trying to use the new evaluateJavascript method in Android 4.4, but when i try to evaluate this javascript code
browser.evaluateJavascript("(function() { document.getElementById('login').value='"+username+"'; document.getElementById('password').value='"+password+"'; document.getElementsByTagName('input')[2].click(); return '';})();",new ValueCallback<String>() {
    @Override public void onReceiveValue(String s) {

    }
});

the app crashes  returning:
Fatal signal 6 (SIGABRT) at 0x00006225 (code=-6), thread 25125

the javascript code is correct, because with the old way
browser.loadUrl("javascript:(function() { ...

it works.
doing some tests, i've found that the problem is when is executed the function
 document.getElementsByTagName('input')[2].click();

the input is a submit button, that sends a form.
how can i do to fill the form and send it?

A: As per the Trigger form submission in chrome javascript console question it might be simpler to call submit() on the form. I have tried reproducing your problem but didn't get a crash - using both click() on the submit button and submit() on a form worked fine for me.
The SIGABRT looks quite bad though, are you calling the API from the UI thread? If no, then try that first. If it's called from the UI thread then you definitely should file a bug on the Android Open Source Project Issue Tracker. Ideally you'd include the the output of adb bugreport immediately after the crash and a sample app demonstrating the issue.


text:
Q: How to find out why my DLL has grown so much A DLL I've been working on has recently grown a lot in size. Are there any tools that will tell my what is responsible for this? For instance, is it a template that is being instantiated too many times, or perhaps a 3rd party lib, or maybe boost?
I'm looking for a kind of profiler that looks at size rather than performance.

A: Are you talking about size of the DLL in bytes?  Try using the dumpbin utility.  This can show you what's inside your DLL.  /ARCHIVEMEMBERS should show you the individual object modules.
http://support.microsoft.com/kb/177429

A: If your DLL has other dependencies and you are using STATIC linking to link your DLL to them, you can expect your DLL to grow larger:
Static linking vs dynamic linking

*

*Static linking can make binaries easier to distribute to diverse user environments (at the cost of sending a large and more resource hungry program).

EDIT:
I found the answers in this thread quite interesting for your problem: Profiling DLL/LIB Bloat
But an interesting experiment would be to verify if for each template instantiation, the resulting executable size grows linearly. If it does, you know your problem is template instantiation. There's a decent article here that talks about this type of problem and presents a technique to refactor it.
EDIT:
There's a big chance that your problem is a consequence of using boost headers. Check this thread to find out why: Why does using boost increase file size so much?


text:
Q: Android: доступ к API VK Как правильно достать данные авторизованного пользователя из ВКонтакте?
Код ниже вылетает с ошибкой в логе:
public class MainActivity extends AppCompatActivity {

    private String[] scope = new String[]{VKScope.MESSAGES, VKScope.FRIENDS, VKScope.WALL, VKScope.STATUS};
    private TextView textView1, textView2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String[] fingerprints = VKUtil.getCertificateFingerprint(this, this.getPackageName());
        System.out.println(Arrays.asList(fingerprints));

        VKSdk.login(this, scope);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (!VKSdk.onActivityResult(requestCode, resultCode, data, new VKCallback<VKAccessToken>() {
            @Override
            public void onResult(VKAccessToken res) {
                // Пользователь успешно авторизовался
                textView1 = (TextView) findViewById(R.id.textView1);
                textView2 = (TextView) findViewById(R.id.textView2);

                VKRequest request = VKApi.users().get(VKParameters.from(VKApiConst.FIELDS, "first_name,last_name"));

                request.executeWithListener(new VKRequest.VKRequestListener() {
                    @Override
                    public void onComplete(VKResponse response) {

                        //VKList list = (VKList) response.parsedModel;
                        VKUsersArray list = (VKUsersArray) response.parsedModel;

                        for (VKApiUserFull userFull : list) {
                            textView1.setText(userFull.first_name);
                        }

                    }
                });
                Toast.makeText(getApplicationContext(), "Хорошо!", Toast.LENGTH_LONG).show();
            }
            @Override
            public void onError(VKError error) {
                // Произошла ошибка авторизации (например, пользователь запретил авторизацию)
                Toast.makeText(getApplicationContext(), "Плохо!", Toast.LENGTH_LONG).show();
            }
        })) {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
 }

Лог:

FATAL EXCEPTION: main
                                                                          Process: com.example.gukov.testvk, PID: 4149
                                                                          java.lang.ClassCastException: com.vk.sdk.api.model.VKList cannot be
  cast to com.vk.sdk.api.model.VKUsersArray
                                                                              at
  com.example.gukov.testvk.MainActivity$1$1.onComplete(MainActivity.java:57)
                                                                              at com.vk.sdk.api.VKRequest$3.run(VKRequest.java:482)
                                                                              at android.os.Handler.handleCallback(Handler.java:739)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                              at android.os.Looper.loop(Looper.java:135)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5221)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at java.lang.reflect.Method.invoke(Method.java:372)
                                                                              at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Если заменить VKUsersArray на VKList, то VKApiUserFull перестает работать (подчеркивает красным). Что написать вместо VKApiUserFull?

A: Согласно en-SO надо так:
//Get user info
VKApi.users().get().executeWithListener(new VKRequest.VKRequestListener() {
    @Override
    public void onComplete(VKResponse response) {
        VKApiUser user = ((VKList<VKApiUser>)response.parsedModel).get(0);
        Log.d("User name", user.first_name + " " + user.last_name);
    }
});


text:
Q: Sqlalchemy select condition I have a mapper on a table and I want to define a column_property which should select True or False whether the entity has some propertie or not:
mapper( Person, persons_table, properties = {
    'administrator': column_property(
        select(
            [True if roles_table.c.is_admin or roles_table.c.id == 1 else False],
            roles_table.c.id == persons_table.c.role_id
        ).label( 'administrator' )
        )
} )

Is this something I can do? I'm more interested in this part: [True if roles_table.c.is_admin or roles_table.c.id == 1 else False], which lets me set a value to the column based on the condition.

A: Your SELECT-expression is actually a Python expression:
select([True if roles_table.c.is_admin or roles_table.c.id == 1 else False],
       roles_table.c.id == persons_table.c.role_id)

sqlalchemy.select() will see this as:
select([True], some_expression_object)

since the column object roles_table.c.is_admin will evaluate to True in Boolean context.  I don't know from the top of my head how SQLAlchemy will interpret this, but it will surely not work as you intended.
You will have to rewrite this expression so that it will correspond to plain SQL, using sqlalchemy.sql.expression.case() instead of if ... else ...:
column_property(
    select([case([(roles_table.c.is_admin, 1),
                  (roles_table.c.id == 1, 1)], else_=0)],
           roles_table.c.id == persons_table.c.role_id))

In your case, however, there might be a much simpler solution.  Person and Role seem to have a N:1 relation (one person has exactly one role).  I assume there is a orm.relationship Person.role to get a person's role.
Why don't you just add a plain Python property:
class Person:
    # ...

    @property
    def administrator(self):
        return self.role and (self.role.is_admin or self.role.id == 1)


text:
Q: Relational Proofs with Fitch Systems I need to prove:
$\forall x.p(x) \Rightarrow \neg \exists x.\neg p(x)$
I know I probably have to assume $\exists x.\neg p(x)$ to reach a contradiction. However, I am not quite sure about how to reach the contradiction.
The premise is that $\forall x.p(x)$, so maybe I had to prove $\exists x.\neg p(x) \Rightarrow \neg \forall x.p(x)$ in this case. However, to get $\neg \forall x.p(x)$ required assuming $\forall x.p(x)$ in advance, which is the same as the premise. Is it feasible? Whether such scenario would cause a endless loop?
I am not sure how could I get a contradiction for this case, any help would be appreciated, thanks!

A: Different systems define the Existential Elimination (or Existential Instantiation) differently, but here is a proof in the Fitch system I use:

EDIT
OK, so your system is indeed a good bit different from the one I use above.  Here is a proof in your system:

*

*$\forall x P(x)$ Premise

*$\quad \exists x \neg P(x)$ Assumption

*$\quad \quad \neg P(x)$ Assumption

*$\quad \quad \quad \forall x P(x)$ Reiteration 1

*$\quad \quad \quad \neg P(x)$ Reiteration 3

*$\quad \quad \forall x P(x) \rightarrow \neg P(x)$ $\rightarrow \: I$ 4-5

*$\quad \quad \quad \forall x P(x)$ Assumption

*$\quad \quad \quad P(x)$ $\forall \: E$ 7

*$\quad \quad \forall x P(x) \rightarrow P(x)$ $\rightarrow \: I$ 7-8

*$\quad \quad \neg \forall x P(x)$ $\neg \: I$ 6,9

*$\quad \neg P(x) \rightarrow \neg \forall x P(x)$ $\rightarrow \: I$ 3-10

*$\quad \forall x (\neg P(x) \rightarrow \neg \forall x P(x))$ $\forall \: I$ 11

*$\quad \neg \forall x P(x)$ $\exists \: E$ 2,12

*$\exists x \neg P(x) \rightarrow \neg \forall x P(x)$ $\rightarrow \: I$ 2-13

*$\quad \exists x \neg P(x)$ Assumption

*$\forall x P(x)$ Reiteration 1

*$\exists x \neg P(x) \rightarrow \forall x P(x)$ $\rightarrow \: I$ 15-16

*$\neg \exists x \neg P(x)$ $\neg \: I$ 14,17

A: I may be misunderstanding the question, but it seems like the contradiction follows almost directly from supposing the negation of the conclusion. By negating the conclusion, we have $\exists x$ such that $\neg p(x)$, call it $x_0$. So, by using that particular $x_0$ we have a contradiction to the premise that $p(x)$ for any $x$.


text:
Q: Facebook Sharing Debugger gives the wrong result in spite of correct og:image I was trying to share something on my Facebook and I noticed Facebook crawler cannot get the og:image correctly.
https://singlebeep.com/
When you check the Scraped URL you can also see the information does not match the stuff that's being shared by Facebook.
https://developers.facebook.com/tools/debug/sharing/?q=http%3A%2F%2Fsinglebeep.com
Also it appears that the behaviors of http and https are different. What I do for http is redirect it to https with cloudfront. But somehow the results are different.

A: Do not omit the protocol in the og tags, add http or https to og:url and og:image and scrape it again.

A: I setup my static website on S3 and have Cloudfront to redirect requests to this websote. It appears that Cloudfront causes the 404 there for some reason. But when I try to crawl using the FB debugger using the following link
http://singlebeep.com?q=123
and it works.


text:
Q: Java - Print First and Last date for each month within specified given month-year range How can I print all months first and the last date which falls within the given specified Month-Year range?
So far I have the code which prints for 1 complete year example, if in the input year 2019 is provided then the first and the last date of all 12 months is printed. But what I want is it should print values within the specified Month-Year range.
Example,
String input_StartMonthYear = "1-2019";
String input_EndMonthYear = "6-2020";

Expected Output:

firstDay-> 2019-1-1
lastDay-> 2019-1-31

firstDay-> 2019-2-1
lastDay-> 2019-2-28

---
---

firstDay-> 2020-6-1
lastDay-> 2020-6-30

Code:
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;

public class GetDate_Firt_Last {

    static String input_Year = "2019";
    static String completeinput;
    static int totalmonths[] = {1,2,3,4,5,6,7,8,9,10,11,12};

    public static void main (String args[]) throws Exception
    {

        int m;
        for (m = 1;m <= totalmonths.length;m++)
        {
            completeinput = m + "-" + input_Year;

            SimpleDateFormat sdf = new SimpleDateFormat("MM-yyyy");
            Date date = sdf.parse(completeinput);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);

            getFirstDayOfTheMonth(cal);
            getLastDayOfTheMonth(cal);
            System.out.println();
        }

    }

    public static String getFirstDayOfTheMonth(Calendar cal) throws Exception {
        String firstDay;

        try {

            int firstDate = cal.getActualMinimum(Calendar.DATE);

            int month = cal.get(Calendar.MONTH) +1;
            int year = cal.get(Calendar.YEAR);
            firstDay = year + "-" + month + "-" + firstDate;
            System.out.println("firstDay-> " +firstDay);

        } catch (Exception e) {
            throw new Exception("Exception in getFirstDayOfTheMonth." + e.getMessage());
        }
        return firstDay;
    }

    public static String getLastDayOfTheMonth(Calendar cal) throws Exception {
        String lastDay;
        try {

            int lastDate = cal.getActualMaximum(Calendar.DATE);
            int month = cal.get(Calendar.MONTH)+1;
            int year = cal.get(Calendar.YEAR);

            lastDay = year + "-" + month + "-" + lastDate;
            System.out.println("lastDay-> "+ lastDay);
        } catch (Exception e) {
            throw new Exception("Exception in getLastDateOfTheMonth." + e.getMessage());
        }
        return lastDay;
    }

}

Actual Output:
firstDay-> 2019-1-1
lastDay-> 2019-1-31

firstDay-> 2019-2-1
lastDay-> 2019-2-28

---
---

firstDay-> 2019-12-1
lastDay-> 2019-12-31

A: If you use java 8 or higher something like this could be a first approach
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;

public class GetDate_Firt_Last {

    public static void main(String[] args) {
        String input_StartMonthYear = "1-2019";
        String input_EndMonthYear = "6-2020";

        DateTimeFormatter df = DateTimeFormatter.ofPattern("d-M-yyyy");
        LocalDate start = LocalDate.parse("1-" +input_StartMonthYear, df);
        LocalDate end   = LocalDate.parse("1-" + input_EndMonthYear, df);
        for(LocalDate d = start; d.isBefore(end.plusMonths(1)); d = d.plusMonths(1)){
            System.out.println("firstDay -> " + d.with(TemporalAdjusters.firstDayOfMonth()));
            System.out.println("lastDay -> " + d.with(TemporalAdjusters.lastDayOfMonth()));
            System.out.println();
        }
    }
}

A: Eritrean's answer is fine. In case you fancy a stream solution, here's one:
    DateTimeFormatter monthYearFormatter = DateTimeFormatter.ofPattern("M-u");
    Period step = Period.ofMonths(1);

    String inputStartMonthYear = "1-2019";
    String inputEndMonthYear = "6-2020";

    LocalDate startDateInclusive
            = YearMonth.parse(inputStartMonthYear, monthYearFormatter).atDay(1);
    LocalDate endDateExclusive = YearMonth
            .parse(inputEndMonthYear, monthYearFormatter)
            .plusMonths(1)
            .atDay(1);

    startDateInclusive.datesUntil(endDateExclusive, step)
            .forEach(d1 -> {
                System.out.println("firstDay-> " + d1);
                LocalDate endOfMonth = d1.with(TemporalAdjusters.lastDayOfMonth());
                System.out.println("lastDay-> " + endOfMonth);
            });

The output is longish, so I am giving you just the first and the last lines:

firstDay-> 2019-01-01
lastDay-> 2019-01-31
firstDay-> 2019-02-01
lastDay-> 2019-02-28
firstDay-> 2019-03-01
lastDay-> 2019-03-31
firstDay-> 2019-04-01
lastDay-> 2019-04-30
(... cut ...)
firstDay-> 2020-05-01
lastDay-> 2020-05-31
firstDay-> 2020-06-01
lastDay-> 2020-06-30


text:
Q: How to convert a csv file to a dataframe in Python 3.6 Im trying to tackle the Kaggle Titanic challenge. Bear with me, as Im fairly new to data science.  I was previously struggling to get the following syntax to work: my previous question(Reading CSV files in Python 3.6, using IntelliJ IDEA)
Reading CSV files in Python, using Jupyter Notebook through IntelliJ IDEA
import numpy as np
import pandas as pd
from pandas import Series,Dataframe

titanic_df = pd.read_csv('train.csv')
titanic.head()

However, using the below code, I am able to open the file and read it/print its contents, but i need to convert the data to a dataframe so that it can be worked with.  Any suggestions?
file_path = '/Volumes/LACIE SETUP/Data_Science/Data_Analysis_Viz_InPython/Example_Projects/train.csv'

with open(file_path) as train_fp:
    for line in train_fp:
#         print(line)

This above code was able to print out the data but when I tried passing
'file_path' to:
titanic_df = pd.read_csv('file_path.csv')

i received the same error as before. Not sure what Im doing wrong. I KNOW the file 'train.csv' exists in that location because 1) i put it there and 2) its contents can be printed when pointed to its location.
So what the heck am I doing wrong??? :/

A: read_csv will create a Pandas DataFrame. So, as long as your file path is right, this following code should work. Also, make sure to use the file_path variable and not the string "file_path.csv"
import pandas as pd

file_path = '/Volumes/LACIE SETUP/Data_Science/Data_Analysis_Viz_InPython/Example_Projects/train.csv'

titanic_df = pd.read_csv(file_path)
titanic_df.head()


text:
Q: Bluemix message hub ACLs I am using Bluemix message hub service. I need to provide read only access to specific topics to specific users. Question is how can I define ACLs in Bluemix message hub? Apache kafka does provide the means (http://kafka.apache.org/documentation.html#security_authz), but that involves interacting with zookeeper. And I haven't been able to find details to connect to underlying zookeeper behind Bluemix message hub service. Appreciate the responses.

A: ACLs are currently not supported with MessageHub. As you've correctly noted, we don't give users access to Zookeeper. So at the moment, there is no way to only provide read or write access to a topic.
That said, we isolate each service instance. So if you provision 2 MessageHub instances in different Bluemix spaces, they will be fully isolated and won't be able to see each other topics. That way you could have guaranties that users from instance1 won't be able to read or write from/to topics from instance2. Not what you've asked for but that might help.


text:
Q: What are integration tests containing and how to set them up I'm currently learning about unit tests and integration testing and as I understood it, unit tests are used to test the logic of a specific class and integration tests are used to check the cooperation of multiple classes and libraries.
But is it only used to test multiple classes and if they work together as expected, or is it also valid to access databases in an integration test? If so, what if the connection can't be established because of a server sided error, wouldn't the tests fail, although the code itself would work as expected? How do I know what's valid to use in this kind of tests?
Second thing I don't understand is how they are set up. Unit tests seem to me have a quite common form, like:
public class  classTest {

    @BeforeEach
    public void setUp(){
    }

    @Test
    public void testCase(){
    }
}

But how are integration tests written? Is it commonly done the same way, just including more classes and external factors or is there another way that is used for that?

A:
[... ] is it also valid to access databases in an integration test? [...] How do I know what's valid to use in this kind of tests?

The distinction between unit-tests and integration tests is not whether or not more than one component is involved: Even in unit-testing you can get along without mocking all your dependencies if these dependencies don't keep you from reaching your unit-testing goals (see https://stackoverflow.com/a/55583329/5747415).
What distinguishes unit-testing and integration testing is the goal of the test.  As you wrote, in unit-testing your focus is on finding bugs in the logic of a function, method or class.  In integration testing the goal is then, obviously, to detect bugs that could not be found during unit-testing but can be found in the integrated (sub-)system.  Always keeping the test goals in mind helps to create better tests and to avoid unnecessary redundancy between integration tests and unit-tests.
One flavor of integration testing is interaction testing: Here, the goal is to find bugs in the interaction between two or more components.  (Additional components can be mocked, or not - again this depends on whether the additional components keep you from reaching your testing goals.)  Typical questions in the interactions of two components A and B could be, for example if B is a library: Is component A calling the right function of component B, is component B in a proper state to be accessed by A via that function (B might not be initialized yet), is A passing the arguments in the correct order, do the arguments contain the values in the expected form, does B give back the results in the expected way and in the expected format?
Another flavor of integration testing is subsystem testing, where you do not focus on the interactions between components, but look at the boundaries of the subsystem formed by the integrated components.  And, again, the goal is to find bugs that could not be found by the previous tests (i.e. unit-tests and interaction tests).  For example, are the components integrated in the correct versions, can the desired use-cases be exercised on the integrated subsystem etc.
While unit-tests form the bottom of the test pyramid, integration testing is a concept that applies on different levels of integration and can even focus on interfaces orthogonal to the software integration strategy (for example when doing interaction testing of a driver and its corresponding hardware device).

Second thing I don't understand is how they are set up.  [...] how are integration tests written?

There is an extreme variation here.  For many integration tests you can just use the same testing framework that is used for unit-tests: There is nothing unit-test specific in these frameworks.  You will, certainly, in the test cases have to ensure that the setup actually combines the components of interest in their proper versions.  And, whether or not additional dependencies are just used or mocked needs to be decided (see above).
Another typical scenario is to perform integration tests in the fully integrated system, using a system-test-like setup.  This is often done out of convenience, just to avoid the trouble to create different special setups for the different integration tests: The fully integrated system just has them all combined.  Certainly, this has also disadvantages, because it is often impossible or at least impractical to perform all integration tests as desired this way.  And, when doing integration testing this way the boundaries between integration testing and system testing get fuzzy.  Keeping focused in such a case means you really have to have a good understanding of the different test goals.
There are also mixed forms, but there are too many to describe them here.  Just one example, there is a possibility to mock some shared libraries with the help of LD_PRELOAD (What is the LD_PRELOAD trick?).

A: It would be valid to access a database as part of an integration test, as integration tests are supposed to show whether a feature is working correctly.
If a feature were to not work because of a failed connection to a server side error, you would want the test to fail to inform you that this feature is not working. Integration tests are not there to inform you where the fault lies, just that a feature is not working.
See https://stackoverflow.com/a/7876055/10461045 as this helps to clarify the widely accepted difference.

A: Using a database (or an external connection to a service you are using) in an integration test is not only valid, but should be done. However, do not rely on integration tests heavily. Unit test every logic element you have and set up integration tests for certain flows.
Integration tests can be written in the same way, except (as you mentioned) they include more methods etc. In fact, the code snippet you've shown above is a common start write-up of an integration test.
You can read up more on tests here: https://softwareengineering.stackexchange.com/questions/301479/are-database-integration-tests-bad


text:
Q: paste header and first 2 rows with a new line in R I have 3 rows
first <- LETTERS[1:9]
second <- c(1:9)
third <- letters[1:9]
> first
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I"
> second
[1] 1 2 3 4 5 6 7 8 9
> third
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i"

I want the output vector of 9 elements with new line like that
"A    "B
 1     2
 a"    b"  and so on

I try to use loop but it doesn't work
y <-c()
z <-c()

 for(i in 1:length(first)){
  y <- paste(first, second, sep = "\n")
  z <- paste(y, third, sep = "\n")
}

I got out put
[1] "A\n1\na" "B\n2\nb" "C\n3\nc" "D\n4\nd"
[5] "E\n5\ne" "F\n6\nf" "G\n7\ng" "H\n8\nh"
[9] "I\n9\ni"

This is not give me a newline. The format of my colnames(data) for report need to be like that. Thanks for advance.

A: Am I understanding you correctly that you are looking for this:
first <- LETTERS[1:9]
second <- c(1:9)
third <- letters[1:9]

cat(c(first, "\n", second, "\n", third))

A B C D E F G H I
1 2 3 4 5 6 7 8 9
a b c d e f g h i

?
EDIT:
Will this solve your problem?
Printing R data frame with column names in multiple lines


text:
Q: ¿Como puedo rotar este hexagono, sin rotar la imagen? Como puedo rotar este hexágono, sin rotar la imagen.
También me gustaría saber cómo cambiar de tamaño la imagen ya genera, osea que el tanto el hexágono como la imagen cambien de tamaño.
Este es el script que utilizo.
<?php
// doge.jpg is a squared pic
$raw = imagecreatefromjpeg('img.jpg');

/* Simple math here

        A_____F
        /     \
      B/       \E
       \       /
       C\_____/D

*/
$w = imagesx($raw);
$points = array(
.25 * $w, .067  * $w, // A
0, .5   * $w, // B
.25 * $w, .933  * $w, // C
.75 * $w, .933  * $w, // D
$w, .5  * $w, // E
.75 * $w, .067  * $w  // F
);

// Create the mask
$mask = imagecreatetruecolor($w, $w);
imagefilledpolygon($mask, $points, 6, imagecolorallocate($mask, 255, 0, 0));

// Create the new image with a transparent bg
$image = imagecreatetruecolor($w, $w);
$transparent = imagecolorallocatealpha($image, 0, 0, 0, 127);
imagealphablending($image, false);
imagesavealpha($image, true);
imagefill($image, 0, 0, $transparent);

// Iterate over the mask's pixels, only copy them when its red.
// Note that you could have semi-transparent colors by simply using the mask's
// red channel as the original color's alpha.
for($x = 0; $x < $w; $x++) {
for ($y=0; $y < $w; $y++) {
    $m = imagecolorsforindex($mask, imagecolorat($mask, $x, $y));
    if($m['red']) {
        $color = imagecolorsforindex($raw, imagecolorat($raw, $x, $y));
        imagesetpixel($image, $x, $y, imagecolorallocatealpha($image,
                          $color['red'], $color['green'],
                          $color['blue'], $color['alpha']));
    }
}
}

// Display the result
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);

A: Esta pregunta está dividida en dos partes:

*

*Cómo rotar el hexágono

*Cómo escalar la imagen

La primera es una simple cuestión de matemáticas (como se indica en el mismo código que compartes), la segunda es sólo cuestión de aplicar una función más.
Cómo rotar el hexágono
Ahora mismo el hexágono se crea porque se copian los píxeles dentro del área especificada en el array $points, entonces lo único que tienes que hacer es recalcular los puntos.
Esto es lo que tienes ahora:
/* Simple math here

        A_____F
        /     \
      B/       \E
       \       /
       C\_____/D

*/
$w = imagesx($raw);
$points = array(
.25 * $w, .067  * $w, // A
0, .5   * $w, // B
.25 * $w, .933  * $w, // C
.75 * $w, .933  * $w, // D
$w, .5  * $w, // E
.75 * $w, .067  * $w  // F
);

Para que sea un hexágono con la punta arriba cambie esa parte, por este código:
/* Simple math here

           A
          /\
       B /  \ F
        |    |
       C|    |E
         \  /
          \/
          D
*/
$w = imagesx($raw);
$points = array(
0.5 * $w, 0, // A
0.1* $w, 0.25 * $w, // B
0.1 * $w, 0.75 * $w, // C
0.5 * $w, $w, // D
0.9 * $w, 0.75 * $w, // E
0.9 * $w, 0.25 * $w // F
);

Las coordinadas son un poco a ojo y tendrás que recalcularlas si quieres que sea un hexágono perfecto, pero funcionan (más o menos bien) en mi local:

Cómo escalar la imagen
Para escalar la imagen sólo necesitas la función imagescale(), que funciona así:
imagescale(imagen, nuevo_ancho, nuevo_alto);

Así en tu caso podrías hacer algo como esto para redimensionar/escalar  la imagen a 400 x 400:
$image = imagescale($image, 400, 400);

Una nota importante: cuando se escala la imagen es importante y no es trivial porque afectará tanto la calidad de la imagen como el rendimiento de tu código:

*

*Si escalas la imagen una vez que se haya generado el hexágono, tendrás que redefinir la transparencia y además el resultado terminaría pixelado. Pero la imagen se generará rápido.

*Si escalas la imagen al principio nada más leerla el resultado será más limpio y se verá mejor, pero tardará más en generar la imagen resultado (porque tendrá que procesar el doble de píxeles)


text:
Q: Android show only part of camera preview
I'm trying to show only part of the image preview in a viewPager in Android, something like this mockup where the light blue would be the entire preview from the camera and the darker square would be the visible part.
Right now I only have been capable of showing the entire preview, what would be the light square, squash in the area of the darker one.
I'm running short of ideas and none of the related answers around solves the problem.
Has someone manage to achieve this king of behavior? If so how?

A: @cwbowron comment end up been a fitting solution, I'll post it in case it could be useful for someone.
Basically I use TextureView to display my camera preview and add mTextureView.setScaleY(2f); inside the method onSurfaceTextureAvailable
May not be the better solution but so far it solve my problem.


text:
Q: Boolean comparison of two Series objects I have two Series which have a format equal to this:
0    False
1    False
2    False
3    True
4    True
Name: foo, dtype: bool

0    True
1    False
2    False
3    True
4    True
Name: bar, dtype: bool

I want to create a new Series with the resulting boolean comparison from these. Something like this:
result = foo and bar
>>> print result
0    False
1    False
2    False
3    True
4    True
Name: result, dtype: bool

Using the obvious result = foo and bar simply results in the following error:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I looked at those functions, but neither seem to do what I wish.
How can I do an element-to-element boolean comparison of a Series resulting in a new Series?

A: You need to use the bitwise and operator &.
result = foo & bar


text:
Q: jQuery UI DatePicker date convert to RFC 3339 format Currently working on the Google Calendar API and basically my end will provide Start and End date for user to pick the date and time. But would like anyone to advise how to convert them from (DatePicker/TimePicker/input field) to RFC 3339 format (e.g. 2013-07-24T10:00:00.000-07:00).

A: var date = new Date();
var timeZone = date.getTimezoneOffset();
alert(date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + "T" + date.getHours() + ":" + date.getMinutes()  + ":" + date.getSeconds() + "." + date.getMilliseconds() + (timeZone > 0 ? "-" : "+") + Math.floor(Math.abs(timeZone) / 60) + ":" + Math.abs(timeZone) % 60);