text:
Q: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $ Есть такой интерфейс:
BackendlessAPI.java
    String BASE_URL = "https://api.backendless.com/" + APP_ID + "/" + API_KEY +"/";
    String IMAGES_FOLDER = "shops_images";
    String IMAGES_URL = BASE_URL + "files/" + IMAGES_FOLDER + "/";

    @GET("data/Shop")
    Observable<Shop> listShops();

Делаю REST запрос вот так:
DataManager.java
@Override
public Observable<Shop> loadShopsFromWeb() {
    Log.d(DEFAULT_TAG, "Try to load from web");
    final IDatabaseHelper databaseHelper = DatabaseHelper.getInstance();
    BackendlessAPI backendlessAPI = backendlessRetrofit.create(BackendlessAPI.class);
    Observable<Shop> shopsList = backendlessAPI
            .listShops()
            .timeout(LOAD_SHOPS_TIMEOUT, TimeUnit.SECONDS)
            .subscribeOn(Schedulers.io())
            .map(shop -> {
                databaseHelper.cacheShop(shop);
                return shop;
            });

    return shopsList;
}

Ожидается примерно такой JSON в ответ на запрос:
[
    {
        "created": 1500137157543,
        "imageUrl": "pekarnya.png",
        "name": "Пекарня на Патриотов",
        "___class": "Shop",
        "coordinates": [
            {
                "lng": 60.673511,
                "city": "Yekaterinburg",
                "street": "Патриотов 70",
                "created": 1500111228678,
                "city_ru": "Екатеринбург",
                "___class": "ShopGeoPoint",
                "lat": 56.782548,
                "objectId": "75F88D38-F831-1828-FF44-7CA466868F00"
            }
        ],
        "description": "Хотите качественную и вкусную выпечку? Заказывай наисвежайшие булочки в \"Пекарне на Патриотов\"",
        "type": "Пекарня",
        "objectId": "C97EDFBC-04BB-D59A-FFE0-A45138B1ED00"
    }
]

А вот мои POJO
Shop.java
public class Shop extends RealmObject {

    public Shop() {
    }

    public Shop(RealmList<ShopGeoPoint> coordinates, String name, String objectId, String imageUrl,
                String description, String type) {
        this.coordinates = coordinates;
        this.name = name;
        this.objectId = objectId;
        this.imageUrl = imageUrl;
        this.description = description;
        this.type = type;
    }

    public RealmList<ShopGeoPoint> getCoordinates() {
        return  coordinates;
    }

    public void setCoordinates(RealmList<ShopGeoPoint> coordinates) {
        this.coordinates = coordinates;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getObjectId() {
        return objectId;
    }

    public void setObjectId(String objectId) {
        this.objectId = objectId;
    }

    public String getImageUrl() {
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    private RealmList<ShopGeoPoint> coordinates;
    @Required
    private String name;
    @Required
    @PrimaryKey
    private String objectId;
    private String description;
    @Required
    private String imageUrl;
    private String type;

}

ShopGeoPoint.java
public class ShopGeoPoint extends RealmObject {

    public ShopGeoPoint(double lat, double lng, String street, String objectId) {
        this.lat = lat;
        this.lng = lng;
        this.street = street;
        this.objectId = objectId;
    }

    public ShopGeoPoint() {
    }

    public double getLat() {
        return lat;
    }

    public void setLat(double lat) {
        this.lat = lat;
    }

    public double getLng() {
        return lng;
    }

    public void setLng(double lng) {
        this.lng = lng;
    }

    public String getObjectId() {
        return objectId;
    }

    public void setObjectId(String objectId) {
        this.objectId = objectId;
    }

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    private double lat;
    private double lng;
    @Required
    private String street;
    @PrimaryKey
    private String objectId;

}

POJO кешируются вот так:
DatabaseManager.java
@Override
    public void cacheShop(final Shop shop) throws NullPointerException {
        if(realm == null){
            throw new NullPointerException("Realm didn't init. Use getInstance() to get DatabaseHelper");
        }
        Log.d(DEFAULT_TAG, "Shop is cached");
        realm.executeTransactionAsync(new Realm.Transaction() {
            @Override
            public void execute(Realm bgRealm) {
                bgRealm.copyToRealm(shop);
            }
        });
    }

Почему вылетает такой Exception? Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

A: Дословно ошибка расшифровывается/переводится так:
Ожидалось начало объекта, но имеем начало массива, падаю.
Т.е. в JSON у вас массив объектов, а вы пытаетесь парсить весь ответ как один объект.
Вам надо просто указать, что вы ожидаете массив.
@GET("data/Shop")
Observable<List<Shop>> listShops();


text:
Q: Firebase Auth SignOut() - nodejs I'm using firebase to manage users. I'm using firebase.auth().signInWithEmailAndPassword() method to sign in the users. It works fine. But when i try to signout using the firebase.auth().signOut() method it gives response but the nodejs just throws the following error.

[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
Server running on port: 3000
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:485:11)
    at ServerResponse.header (D:\web-server\TellMe-API\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (D:\web-server\TellMe-API\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (D:\web-server\TellMe-API\node_modules\express\lib\response.js:267:15)
    at Object.next (D:\web-server\TellMe-API\api\routes\firebaseAuth.js:29:36)
    at D:\web-server\TellMe-API\node_modules\@firebase\util\dist\index.node.cjs.js:1226:22
    at D:\web-server\TellMe-API\node_modules\@firebase\util\dist\index.node.cjs.js:1336:21
    at processTicksAndRejections (internal/process/task_queues.js:93:5) {
  code: 'ERR_HTTP_HEADERS_SENT'
}

This is the code i used to logout the user.

router.post('/signout', (req, res) => {
    const user = firebase.auth().currentUser;
    if (user) {
        firebase.auth().signOut().then(() => {
            res.status(200).json({
                status: 'success',
                message: 'Successfully logged/signed out'
            });
        }).catch(error => console.log('Something went wrong! ', error))
    } else {
        res.status(403).json({
            status: 'failure',
            message: 'user already logged out.'
        });
    }
});

I also tried using the async/await method it doesn't work too. Wherever i make a call to firebase.auth().signOut() method it gives the above error.

A: The error
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

occurs when you try to send a response after one has already been sent.
I'm not a firebase expert but my guess is firebase.auth().signOut() already sends a response to the user when called.
So the code
res.status(200).json({
  status: 'success',
  message: 'Successfully logged/signed out'
});

tries to send a response after one has already been sent and generates the error.
You can simplify your code this way
router.post('/signout', (req, res) => {
    const user = firebase.auth().currentUser;
    if (user) {
        firebase.auth().signOut().then(() => {
            console.log("User successfully logged out"); // Just for the example.
        }).catch(error => console.log('Something went wrong! ', error))
    } else {
        res.status(403).json({
            status: 'failure',
            message: 'user already logged out.'
        });
    }
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Hide custom controls group on ribbon in word Some background first. Im creating VBA script to transform one Word document into another one. I developed a script and put it into dotm template file.
First appication is using this template to export data. Next script in this template transforms exported data into new document. This template is also used to create result document. This means that all styles, scripts and custom ribbon UI is available in result document.
What I need is to remove scripts and custom ribbon UI from result document.
I was able to remove scripts but I don't know how to access and remove or hide custom ribbon UI from result document.
Any hints? Btw I don't want to put any script in result document which means that script from template have to delete or hide custom robbin UI from result document.

A: When you create the target document  Word will use the current attached template. You need to specify a different template e.g. Normal.dotm. (assuming you are not developing your scripts in Normal.dotm.


text:
Q: reading TCP in java issue I am reading TCP packets that I use to display an image. Each packet is supposed to have a 1025 length. And each time, I get 128 lines, I draw an image.
SO I begin by initializing
s = new Socket(ip, port);
stream = s.getInputStream();
byte[] tmpBuffer = new byte[1025];
byte[] finalBuffer = new byte[128 * 1025];
int count_lines =0

and then I read stream by stream of length 1025,
while((read = stream.read(tmpBuffer, 0, tmpBuffer.length)) != -1){
    System.arraycopy(tmpBuffer, 1, finalBuffer, count_lines * 1025, 1025);
    count_lines++;
    if(count_lines == 128) break;
}

The problem is when I log the read integer, I get a bunch of 1025 but sometimes (apparently randomly) 423 or 602 (noticing that 423+602=1025)
Am I going wrong with the TCP reading or is there a problem on the server side ?

A:
Am I going wrong with the TCP reading or is there a problem on the server side ?

In TCP you have only a stream of bytes.  You have messages nor control over packets which are typically no more than 1532 bytes long.
You have to have your own protocol to handle sending of messages.
inputStream.read(buffer) will read between 1 byte and buffer.length and you can't ignore the actual length read as you are doing.
If you want to read into a buffer of a known length, you can use
DataInputStream dis = new DataInputStream(socket.getInputStream());
byte[] finalBuffer = new byte[128 * 1025];
dis.readFully(finalBuffer);

The readFully reads as much as it can at a time until the byte[] has been fully read.
A more flexible protocol is to send the length first.
public static void write(DataOutputStream out, byte[] bytes) {
    out.writeInt(bytes.length());
    out.write(bytes);
}

public static byte[] read(DataInputStream in) {
    int length = in.readInt();
    byte[] bytes = new byte[length];
    in.readFully(bytes);
    return bytes;
}

This way, whatever length of data you send, you will recieve in the same manner.


text:
Q: MQTT callback client Reconnection logic I am unable to find a logic for reconnection of mqtt call back client. There is method onDisconnected() but I am unable to find documentation or any sample example on internet.
My Listener
public class MyListener implements Listener
{
    public MyListener()
    {

    }

    @Override
    public void onConnected()
    {
        System.out.println("Connected ....");
    }

    @Override
    public void onDisconnected()
    {
        System.out.println("Disconnected");
    }

    @Override
    public void onPublish(UTF8Buffer topic, Buffer body, Runnable ack)
    {
        System.out.println("Entered Onpublish");

        try
        {
         System.out.println("received msg:" + msg);
        }
        catch (HikeException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally{
            ack.run();
        }

    }

    @Override
    public void onFailure(Throwable value)
    {
        value.printStackTrace();
    }

}

Create Connection
private void createConnection(String host, int port,String id, String token) throws Exception
{

    this.disconnect();
    MQTT mqtt = new MQTT();
    mqtt.setHost(host, port);
    mqtt.setUserName(id);
    mqtt.setPassword(token);
    CallbackConnection callbackConnection = null;
    callbackConnection = mqtt.callbackConnection();
    callbackConnection.listener(new MyListener());
    callbackConnection.connect(new MyCallback<Void>("CONNECT"));
    callbackConnection.subscribe(new Topic[] { new Topic(uid + "/u", QoS.AT_MOST_ONCE) }, new MyCallback<byte[]>("EVENT SUBSCRIBE"));
    callbackConnection.subscribe(new Topic[] { new Topic(uid + "/s", QoS.AT_LEAST_ONCE), new Topic(uid + "/a", QoS.AT_LEAST_ONCE) }, new MyCallback<byte[]>("MSG SUBSCRIBE"));

    this.callbackConnection = callbackConnection;
}

MyCallback
class MyCallback<T> implements Callback<T>
{
    public MyCallback(String tag)
    {
        super();
        this.tag = tag;
    }

    String tag;

    @Override
    public void onSuccess(T value)
    {
        System.out.println("TAG:" + tag + " =SUCCESS value=" + value);
    }

    @Override
    public void onFailure(Throwable value)
    {
        System.out.println("TAG:" + tag + "Fail");
        value.printStackTrace();
    }

}

My question is how to implement mqtt reconnection to server logic ? If I should use onDisconnect() method, then how I can use it ?

A: Here is how i implemented Mqtt reconnect on connection lost, starts a thread to try to connect to MqttServer which will be destroyed on successful connection.
  boolean retrying = false;
   public void reConnect(){
        if (!retrying) {
            retrying = true;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (;;) {
                        try {
                            if (isInetAvailable() && !mqttClient.isConnected()) {
                                if(isPasswdProtected) {
                                     //connect with MqttConnectionOptions
                                    Connect_with_passwd();
                                } else {
                                    Connect();
                                }
                                Thread.sleep(MQTT_RETRY_INTERVAL);
                            } else if (isConnected()) {
                                List<String> topics = topicsSubscribed;
                                topicsSubscribed.clear();
                                for (String topic : topics) {
                                    try {
                                        subscribeToTopic(topic);
                                    } catch (MqttException e) {
                                    }
                                }
                                retrying = false;
                                break;
                            } else if (!Internet.isAvailable()) {
                                Thread.sleep(INET_RETRY_INTERVEL);
                            }
                        } catch (MqttException | InterruptedException e) {
                            try {
                                Thread.sleep(MQTT_RETRY_INTERVAL);
                            } catch (InterruptedException ex) {
                            }
                        }
                    }
                }
            }).start();
        }
}
 /*Check internet connection*/

 public static boolean isInetAvailable() {
    boolean connectivity;
    try {
        URL url = new URL(GOOGLE);
        URLConnection conn = url.openConnection();
        conn.connect();
        connectivity = true;
    } catch (IOException e) {
        connectivity = false;
    }
    return connectivity;
}

A: I have implemented this way
        //check when network connectivity is back and implement the connection logic again
        System.out.println("Connection Lost\n trying to re-connect");
        int tries=0;
        while(true){
            Thread.sleep(MQTT_RETRY_INTERVAL);
            if(checkIfNetworkAvailable()&& !MQTTClient.getInstance().mqttClient.isConnected()){
                try{
                    tries++;
                MQTTClient.getInstance().mqttClient.connect(MachineDetails.getInstance().getMACDetails(), true, (short) 1000);
                //register handler
                MQTTClient.getInstance().mqttClient.registerAdvancedHandler(ApplicationPublishHandler.getInstance());
                String[] topics={Constants.PUBLIC_BROADCAST_TOPIC};
                int[] qos={1};
                MQTTClient.getInstance().mqttClient.subscribe(topics, qos);
                }catch(Exception e){
                    //Service down  and give an alert
//                  break;
                }
                if(tries>No of retries on network available)
                break;
            }
        }

    private boolean checkIfNetworkAvailable() {
        try {
            InetAddress.getByName("<<your host name>>");
            return true;
        } catch (UnknownHostException e) {
            return false;
        }

    }


text:
Q: How to response Well formatted errors as JSON Hi I'm new in C# currently I'm building my first web API. The requirement is to display any error that happen as a response in JSON format
This is my ResponseData Class
public class ResponseData
{
    public List<AccountDTO> AccountList { set; get; }
    public string ReturnMessage { set; get; }
    public string error { get; set; }
    public string code { get; set; }
    public string message { get; set; }
    public string innererror { get; set; }
    public string type { get; set; }
    public string stacktrace { get; set; }

}

This is my Controller
As an example, If my code execute the catch block, I'll will gather all the information of the exception and return this in a formatted JSON.
[HttpGet]
    public ResponseData getAllAccounts(string BRN, string CompanyName)
    {

        ResponseData response = new ResponseData();
        List<AccountDTO> accountlist = null;
        IAccountInterface usecase = new AccountDAO();
        try
        {
            if (BRN != null && CompanyName != null)
            {
                accountlist = usecase.getAccountbyBRNCompanyName().Where(p => p.BRN.ToLower().Equals(BRN.ToLower()) && p.CompanyName.ToLower().Contains(CompanyName.ToLower())).ToList();
                response.ReturnMessage = "Data filter by BRN and CompanyName.";
            }

            else
            {
                response.ReturnMessage = "Data filter cannot be null.";
            }
            response.AccountList = accountlist;
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: " + e.Message + ", Stack: " + e.StackTrace);
            response.code = "sample code";
            response.message = e.Message;
            response.innererror = "{";
            response.message = e.Message;
            response.type = "ExceptionType + ...";
            response.stacktrace = e.StackTrace;

            //response.ReturnMessage = JsonConvert.SerializeObject(errorFormat);

        }

        return response;
    }

After run this web APi the response is as per picture below if catch block is executed.

So far, It's almost similar to what I want. However regardless errors or not, my WEB API response will be in this format. I know this is because I return a response object so all my object properties will be displayed.
This is a sample response that I want to achieve. Details about errors are included as JSON in the response. Errors will be in this format. Any help and guide greatly appreciate.
{
 "error":{
  "code": "<This code is not related to..>",
  "message": "<A message describing the error..>",
  "innererror": {
   "message": "<A message describing the error..>",
   "type": "Microsoft.Crm.CrmHttpException",
   "stacktrace": "<Details from the server about where the
                  error occurred>"
    }
   }
}

A: The desired JSON error response model does not match the class used.
The current object model is serving multiple responsibilities.
Consider refactoring the class models to serve a single responsibility
public class ResponseData {
    public List<AccountDTO> AccountList { set; get; }
    public string ReturnMessage { set; get; }
}

The API action can also be refactored to return the appropriate response based on the flow of the action.
[HttpGet]
public IHttpActionResult getAllAccounts(string BRN, string CompanyName) {
    try {
        ResponseData response = new ResponseData();
        List<AccountDTO> accountlist = null;
        IAccountInterface usecase = new AccountDAO();
        if (BRN != null && CompanyName != null) {
            accountlist = usecase.getAccountbyBRNCompanyName().Where(p => p.BRN.ToLower().Equals(BRN.ToLower()) && p.CompanyName.ToLower().Contains(CompanyName.ToLower())).ToList();
            response.ReturnMessage = "Data filter by BRN and CompanyName.";
        } else {
            response.ReturnMessage = "Data filter cannot be null.";
        }
        response.AccountList = accountlist;
        return Ok(response);
    }
    catch (Exception e) {
        Console.WriteLine("Error: " + e.Message + ", Stack: " + e.StackTrace);
        var response = new {
            error = new {
                code = "sample code",
                message = e.Message,
                innererror = new {
                    message = e.Message,
                    type = e.GetType().Name,
                    stacktrace = e.StackTrace
                }
            }
        }
        var responseMessage = Request.CreateResponse(HttpStatusCode.InternalServerError, response);
        return ResponseMessage(responseMessage);
    }
}

A:         Console.WriteLine("Error: " + e.Message + ", Stack: " + e.StackTrace);
        response.error.code = "sample code";
        response.error.message = e.Message;
        response.error.innererror = "{";
        response.error.message = e.Message;
        response.error.type = "ExceptionType + ...";
        response.error.stacktrace = e.StackTrace;

This should get you your desired result.  response object would also have to be refactored.


text:
Q: How to choose the family in Generalized Linear Model in R I would like to know how to choose the family in generalized linear models in R. Roughly, I have learned that family=binomial or family=poisson should be used if dependent variable (y) is binary or count data. How about others here?
Especially,
in which situation of dependent variable(y), can I apply family=Gamma or family=inverse.gaussian?

A: A good guide is to look at the relationship between the mean and the variance. If the variance does not vary with the mean - Gaussian. If it varies proportional to the mean - Poisson. As mean squared - gamma. As mean cubed - inverse Gaussian.


text:
Q: Laravel: How do I make route helper return urls with trailing slashes? How do I make Laravel 5.3 create route URLs with trailing slashes?
The route is defined as
 Route::get('/home/', ['as' => 'home', 'uses' => 'HomeController@index']);

I then create the url with the route helper function in a view:
{{ route('home') }}

This creates http://localhost:8000/home instead of http://localhost:8000/home/.
This question is very similar to Laravel - append a trailing slash in routes, but that question doesn't have an answer either and it seems to me that my description is a tat shorter.
Edit:
The two possible naming methods from the docs don't make a difference:
Route::get('/home/', ['as' => 'home', 'uses' => 'HomeController@index']);
Route::get('/home/', 'HomeController@index')->name('home');

A: The marked variant is more similar to a crutch than to the decision as URL is in sitemap.xml and still anywhere therefore in this case, it is better to edit everything only in the directory routes/*.php, That is all same the variant with UrlGenerator census will be the most correct. In this case, there is a very useful package (illuminatech/url-trailing-slash) that essentially should solve this problem. All changes will be only at the routing level.

A: Because Laravel will remove slash at the end of URL so you just can do it by using {{ route('home') }}/.
Reference: https://github.com/laravel/framework/blob/5.3/src/Illuminate/Routing/UrlGenerator.php#L308-L345


text:
Q: How to find maximum running pod over last 24 hour using prometheus I have deploy my kubernetes cluster in AWS EKS. I have setup prometheus and grafana to monitor the EKS cluster. How to find Max no of running pods throughout the day ??

A: This one will return the name of the pods that have been run in the last 24 hours. Note there can be exited pods also, that doesn't exist now.
sum by (pod) (min_over_time(kube_pod_start_time[24h]))

The following query should return the number of pods that existed in the last 24 hours:
count(last_over_time(kube_pod_created[24h]))

The last_over_time(kube_pod_created[24h]) returns time series for pods that existed in the last 24 hours
For more information follow pod metrics.

A: The following query should return the maximum number of running pods during the last 24 hours:
max_over_time(
  count(kube_pod_status_phase{phase="Running")[1m:24h]
)

It uses subquery feature, max_over_time() function and count() function.


text:
Q: Is it considered as impolite to say, what's up when someone asks you to help I was in a fashion shop for some clothing, and a man in the same shop suddenly came to ask me if I could help him fill in a short questionnaire.
Because I didn't expect such thing to happen in a fashion shop, I was surprised and said this without thinking:

what's up

Is it impolite to say what's up when someone asks you to help?

A: No, I don't think it's impolite. For instance:
"Excuse me, can you help me please?"
"Sure - what's up?" - seems like a polite enough way to ask what the problem is, although certainly very informal.
But as a response to someone asking you to fill out a questionnaire, it doesn't seem to make much sense. It seems like your response just needed to be yes or no at this point.

A: If I were greeted by anyone with "What's up?" I would immediately suspect the interrogator of hostile intent.
It reeks of suspicion and hostility, or at least purveys the notion that the interrogator assumes the upper hand or a position of superiority.
It may be fashionable and in vogue, but it is definitely not friendly.
I would be tempted to respond with "Mind your own damned business!"
Sadly a similar form, also unfriendly, used to be in fashion, was, "What's the problem?" whenever approaching the likes of a customer service situation, also nasty and unnecessary and assumes a superior status.
Both convey a gross lack of respect and are not acceptable.


text:
Q: How to check if client device has a rear camera? Is there a reliable way to check via JavaScript if the user is visiting a website with a device that has a rear camera?
My use case is this: I have AR content on my page. When the user has a desktop or laptop, I want to display a QR code containing a link that he can scan with a mobile device to use the AR feature. But when he uses a tablet or phone I want to directly open the link because his device is already AR capable.
I know I could check the screen resolution. But I think that would not work reliably for different browser window sizes.
The best option so far seems to be to parse the user agent for the string "mobile". But isn't there a cleaner way?


text:
Q: Dynamic Image grid arrangement in Android I'm working on an app that receives random amount of images and should show them to the user in a grid. Grid cells depends on the amount of Images.  Max is 5. Something like what Facebook does:

Notice how the grid changes based on the image dimensions but still in a fixed image space. I tried using staggered grid but it just creates a long list and I'm not exactly good at staggered grid layout myself. Another option is to use grid view but I couldn't programmatically change the dimensions of the grid cells. Any help would be appreciated
I should Mention I'm using Xamarin.Android


text:
Q: JSON - simple get an Integer instead of Long How to get an Integer instead of Long from JSON?
I want to read JSON in my Java program, but when I get a JSON value which is a number, my parser returns a number of type Long.
I want to get an Integer. I tried to cast the long to an integer, but java throws a ClassCastException (java.lang.Long cannot be cast to java.lang.Integer).
I tried several things, such as first converting the long to a string, and then converting with Integer.parseInt(); but also that doesn't work.
I am using json-simple
Edit:
I still can't get it working. Here is an example:
jsonItem.get("amount"); // returns an Object
I can do this:
(long)jsonItem.get("amount");

But not this:
(int)jsonItem.get("amount");

I also can't convert it with
Integer newInt = new Integer(jsonItem.get("amount"));

or
Integer newInt = new Integer((long)jsonItem.get("amount"));

A: Please understand that Long and Integer are object classes, while long and int are primitive data types.  You can freely cast between the latter (with possible loss of high-order bits), but you must do an actual conversion between the former.
Integer newInt = new Integer(oldLong.intValue());

A: I tried
(int)(long)jsonItem.get("amount");

and it worked for me


text:
Q: Enabling In-browser elevated trust I'm trying to get in-browser elevated trust to work and having an issue.  I've:

*

*Purchased a certificate

*Signed the xap with that certificate

*Added AllowElevatedTrustAppsInBrowser=1 in the registry

Yet the app still doesn't think it is running in elevated trust.  Any ideas on what I might be missing?
Running off localhost, of course, works because it doesn't require any of the above.
Screenshots included below as proof.

A: So you have your certificate from a trusted publisher.
You have signed the XAP.
You have installed the certificate on the client computers.
Have you configured the registry on the client as described in this post?
You can also configure the registry settings using Group Policy

A: Make sure to put the AppManifest.xaml along with the .xap file. I got the same problem, and it solved by having the .xaml. This is an old post, but hope it will help some one having the same problem.


text:
Q: Is it possible to warn in visual studio if linq is used on objects without equals and hashcode overridden I just ran into a really annoying bug, that took all morning to fix. It turns out linq was evaluating my objects by comparing them using Equals() since I had not overridden that method it was not grouping my objects correctly.  I want to make it so my whole team will see build server warning messages if they add linq statements that evaluate Types that  have not had their Equals and GetHashCode() overridden.
I'm working in Vb.net but eventually we will be switching to C# an answer for either language would be great.


text:
Q: Uniqueness of a Solution for a Convex Optimization Problem I have the following convex optimization problem:
$$\begin{array}{ll} \text{maximize}_{{f,g}} & \displaystyle\int_{\Omega} g^u{f}^{1-u}\mathrm{d}\mu\\ \text{subject to} & \displaystyle\int_{\Omega} f \mathrm{d}\mu= 1,\quad \displaystyle\int_{\Omega} g\mathrm{d}\mu =1 \\  & f_L \leq {f} \leq f_U\\ & g_L \leq g \leq g_U\end{array}$$
where $u\in(0,1) $ and
$$\int_{\Omega}f_L \mathrm{d}\mu< 1,\quad\int_{\Omega}g_L \mathrm{d}\mu< 1$$
$$\int_{\Omega}f_U \mathrm{d}\mu> 1,\quad\int_{\Omega}g_U \mathrm{d}\mu> 1$$
Here, $f$ and $g$ are distinct density functions and $f_L,f_U,g_L,g_U$ are some known positive functions on $\Omega$.

Claim: The solution is unique and it is the same for every $u\in(0,1)$, if  $f_U=\infty$ and $g_U=\infty$, i.e., if there are only lower bounds, or $f_L=0$ and $g_L=0$, i.e., if there are only upper bounds. Else, the solution is also unique but it is not the same for all $u$.
Question: Are these claims true, especially the last one?

$\mu$ can be the Lebesgue measure, although I believe the same holds for the counting measure and the discrete sets. The set $\Omega$ can be $\mathbb{R}$ or an interval of real numbers.
I am especially interested in the last ''not'' case, and for this case if necessary $g_U$ and $f_U$ can be assumed to be integrable over $\Omega$.
I had previously asked this question at math.stackexchange but with no answers.
Addendum: For $f_U=\infty$ and $g_U=\infty$ I know that $$\frac{g}{f}(y)=\begin{cases}c_1\quad\mbox{if}\quad g/f<c_1\\ h(y)\quad\mbox{if}\quad c_1\leq g/f \leq c_2\\
c_2\quad\mbox{if}\quad g/f>c_2\\\end{cases}$$
where $c_1$ and $c_2$ are some constants and $h$ is a function of the bounding functions for example $g_L/f_L$. I think the same is true for the case $f_L=0$ and $g_L=0$.
I have some work on the solution of the problem with KKT multipliers, which may help solving this problem too.

A: I tried to work on the problem and I think I am able to resolve some points. Here is my work:
Consider the Lagrangians:
$$L_0=\int_{\mathbb{R}} g^u{f}^{1-u}\mathrm{d}\mu+\int_{\mathbb{R}}\left(\lambda_0(f-f_L)+\lambda_{00}(f_U-f)\right)\mathrm{d}\mu+\mu_0\left(\int_{\mathbb{R}} f\mathrm{d}\mu-1\right)$$
$$L_1=\int_{\mathbb{R}} g^u{f}^{1-u}\mathrm{d}\mu+\int_{\mathbb{R}}\left(\lambda_1(g-g_L)+\lambda_{11}(g_U-g)\right)\mathrm{d}\mu+\mu_1\left(\int_{\mathbb{R}} g\mathrm{d}\mu-1\right)$$
Taking the Gateux derivatives of the Lagrangians, at the direction of funtions $\psi_0$ and $\psi_1$, respectively, leads to
$$\frac{\partial L_0}{\partial f}=\int\left((1-u)\left(\frac{g}{f}\right)^u+\lambda_0-\lambda_{00}+\mu_0\right)\psi_0\mathrm{d}\mu=0\quad\quad(1)$$
$$\frac{\partial L_1}{\partial g}=\int\left(u\left(\frac{g}{f}\right)^{u-1}+\lambda_1-\lambda_{11}+\mu_1\right)\psi_1\mathrm{d}\mu=0\quad\quad\quad\,\,\,(2)$$
Here according to Gateux derivative, $\psi_0$ and $\psi_1$ are arbitrary functions. I take them as integrable functions with $\int \psi_0 \mathrm{d}\mu=1$ and $\int \psi_1 \mathrm{d}\mu=1$
There are actually $3$ cases for each Lagrangian $L_0$ and $L_1$. For $L_0$ we have $$f=f_L, \quad f=f_u, \quad f_L<f<f_U$$ and for $L_1$ we have $$g=g_L, \quad g=g_u, \quad g_L<g<g_U$$
The conditions above $\partial L_0/\partial f=0$ and $\partial L_1/\partial g=0$ make sense only for the conditions $f_L<f<f_U$ and $g_L<g<g_U$.
Hence, I can write the maximizing functions as
$$f(y)=\begin{cases}f_L\quad y\in E_0\\ f_U\quad y\in E_1\\h_0\quad y\in E_2\\\end{cases}\quad g(y)=\begin{cases}g_L\quad y\in E_3\\ g_U\quad y\in E_4\\h_1\quad y\in E_5\\\end{cases}$$
Based on this result I have following conclusions:

$1.$ For the general case, namely if $g_L\neq \infty$ and $g_U\neq \infty$, the sets $E_k$ and functions $h_0$ and $h_1$ are necessarily dependent on $u$, although there may be special cases. This is because there is no simplification which can show that $E_k$ and functions $h_0$ and $h_1$ may be written independent of $u$.
$2.$ if $g_L= \infty$ and $g_U= \infty$, the results are independent of $u$ and I can confirm this with experiments. In order to show this analytically, first, I should  be able to show that $g/f$ is constant in (1) and (2).
I am trying to explain this: $\lambda_{00}$ and $\lambda_{11}$ are zero, $\lambda_{0}$ and $\lambda_{1}$ are some positive functions. $\mu_0$ and $\mu_1$ must be negative constants, if not the equations (1) and (2) above wont be $0$. My problem is that $(1−u)(g/f)^u+\lambda_0$ can also be a constant function which is equal to $-\mu_0$, if $\lambda_0$ is carefully chosen. Then, the integral equation will hold while $g/f$ is not a constant. However, this is never the case. Am I wrong?

Please feel free to comment and post a new anwer based on mine. Because still there are missing points.


text:
Q: Is Xcode 4.2 compatible with both OS4 and iOS5? I am developing my app in Xcode 4.2. I would like to know if the app which I'm developing in Xcode 4.2 will work on both iOS4 and iOS5.

A: Yes it support for both.
You just need to change you Deployment target to lowest one
Project->Target->summary->Deployment target
change it with lower one
then it will work

A: You can declare what iOS versions your app supports in your project 'Info'. Also make sure that you select "NO" for "Build Active Architecture Only" in your project 'Settings'.


text:
Q: Gatsby build time error - WebpackError: TypeError: isRedirect is not a function Ever since I tried protected routes with this on login.js
    <Router basepath="/">
            <PrivateRoute path="/edit" />
        </Router>

and this on edit.js
useEffect(() => {
    // ... some code here

    getEscritos();
    if (!user && location.pathname !== `/login`) {
        navigate("/login");
        return null;
    }
}, []);

I can no longer build it... the error was:
the window is not defined
Though locally it runs fine. Everything works.
Then I tried this on gatsby-node.js after research
exports.onCreateWebpackConfig = ({ stage, loaders,
actions, getConfig }) => {
if (stage === "build-html" || stage === "develop-html") {
actions.setWebpackConfig({
  module: {
    rules: [
      {
        test: /reach-router/,
        use: loaders.null(),
      },
    ],
  },
});
externals: getConfig().externals.concat(function (
  context,
  request,
  callback
) {
  const regex = /^@?firebase(\/(.+))?/;
  // exclude firebase products from being bundled, so
  they will be loaded using require() at runtime.
  if (regex.test(request)) {
    return callback(null, "commonjs " + request); // <-
   use commonjs!
    }
  callback();
  });
 }

};
and the error now is:
WebpackError: TypeError: isRedirect is not a function
I have no idea what to do...
Here is the repo, if it's to any help.
Thank you in advance for your time.

A: You need to wrap your Firebase use and initialization inside the following condition:
if(typeof window !== 'undefined')

You have multiple instances of Firebase triggered in the SSR (Server-Side Rendering.
Applied in your escritos.js:
  if(typeof window !== 'undefined'){
    const db = getFirestore(app);
    const escritosColRef = collection(db, "escritos");
  }

The same applies to index.js (line 31) and so on...
The references that are inside a useEffect hook (with empty deps, []) should work without the window condition since they are triggered on the DOM tree is loaded, so won't break the SSR. If the error persists, try also wrapping them.


text:
Q: Espresso test fails due to Data binding This is my viewmodel class :
class MainViewModel(
    private val schedulerProvider: BaseSchedulerProvider,
    private val api : StorytelService
) : BaseViewModel() {

    private val _posts = MutableLiveData<List<Post>>()
    val posts: LiveData<List<Post>>
        get() = _posts

    private val _status = MutableLiveData<Status>()
    val status: LiveData<Status>
        get() = _status

    init {
        showPhotos()
    }

    fun showPhotos() {
        EspressoIdlingResource.increment() // App is busy until further notice
        _status.postValue(Status.LOADING)
        compositeDisposable.add(api.getPhotos()
            .subscribeOn(schedulerProvider.io())
            .observeOn(schedulerProvider.ui())
            .doFinally {
                if (!EspressoIdlingResource.countingIdlingResource.isIdleNow) {
                    EspressoIdlingResource.decrement() // Set app as idle.
                }
            }
            .subscribe({
                _status.postValue(Status.SUCCESS)
                showPosts(it)
            }) {
                _status.postValue(Status.ERROR)
                Timber.e(it)
            })
    }

    private fun showPosts(networkPhotos: List<NetworkPhoto>) {
        EspressoIdlingResource.increment() // App is busy until further notice
        _status.postValue(Status.LOADING)
        compositeDisposable.add(api.getPosts()
            .subscribeOn(schedulerProvider.io())
            .observeOn(schedulerProvider.ui())
            .doFinally {
                if (!EspressoIdlingResource.countingIdlingResource.isIdleNow) {
                    EspressoIdlingResource.decrement() // Set app as idle.
                }
            }
            .subscribe({ networkPosts ->
                _status.postValue(Status.SUCCESS)
                _posts.postValue(
                    PostAndImages(networkPosts, networkPhotos).asDomaineModel()
                )
            }) {
                _status.postValue(Status.ERROR)
                Timber.e(it)
            })
    }

This is my recyclerView in layout :
<androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recycler_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            app:showData="@{vm.status}"
            tools:listitem="@layout/post_item" />

And here is binding adapter :
@BindingAdapter("showData")
fun View.showData(status: Status) {
    visibility = if (status == Status.SUCCESS) View.VISIBLE else View.GONE
}

As you notice I am using EspressoIdlingResource, but when I run following espresso test, it fails :
    @Test
    fun shouldBeAbleToLoadList() {
        onView(withId(R.id.recycler_view)).check(matches(isDisplayed()))
    }

If I add Thread.sleep(5000) in the beginning of the test, it works. How to resolve it?

A: It should be possible with Idling Resource however they are a little bit tedious.
I've just updated an old viewMatcher code:
/**
 * Perform action of waiting for a specific view id to be displayed.
 * @param viewId The id of the view to wait for.
 * @param millis The timeout of until when to wait for.
 */
public static ViewAction waitDisplayed(final int viewId, final long millis) {
    return new ViewAction() {
        @Override
        public Matcher<View> getConstraints() {
            return isRoot();
        }

        @Override
        public String getDescription() {
            return "wait for a specific view with id <" + viewId + "> has been displayed during " + millis + " millis.";
        }

        @Override
        public void perform(final UiController uiController, final View view) {
            uiController.loopMainThreadUntilIdle();
            final long startTime = System.currentTimeMillis();
            final long endTime = startTime + millis;
            final Matcher<View> matchId = withId(viewId);
            final Matcher<View> matchDisplayed = isDisplayed();

            do {
                for (View child : TreeIterables.breadthFirstViewTraversal(view)) {
                    if (matchId.matches(child) && matchDisplayed.matches(child)) {
                        return;
                    }
                }

                uiController.loopMainThreadForAtLeast(50);
            }
            while (System.currentTimeMillis() < endTime);

            // timeout happens
            throw new PerformException.Builder()
                    .withActionDescription(this.getDescription())
                    .withViewDescription(HumanReadables.describe(view))
                    .withCause(new TimeoutException())
                    .build();
        }
    };
}

then you should only do:
@Test
    fun shouldBeAbleToLoadList() {
        onView(isRoot()).perform(waitDisplayed(R.id.recycler_view, 5000));
    }

the 5000 is a timeout of 5 secs (5000 millis), you can change it if you want to.
After waitDisplayed is executed it could happen that the element is shown or the timeout has been reached. In the last case an Exception will be thrown.

A: You will need to create an Idling Resource for the binding.
You can check Android Architecture Components sample which have a similar implementation. Here's what you will need to look for:

*

*Firstly, you will need to add an Idling Resource class which checks if there are any bindings pending (you can find an implementation here)

*Now you can create a rule which will automatically register/unregister Idling Resource for you (you can find an implementation here).

*And now you can add this rule to your test and check if it works (sample test implementation you can find here).


text:
Q: Magento compiler broken. Compiler doesnt work even via SSH I deleted the includes/src folder to disable the compiler mode.
Then the site broke and all we can see is the following.

Warning: include_once(Varien/Autoload.php): failed to open stream: No
  such file or directory in /home2/hotelhome/public_html/app/Mage.php on
  line 51
Warning: include_once(): Failed opening 'Varien/Autoload.php' for
  inclusion
  (include_path='/home2/hotelhome/public_html/app/code/local:/home2/hotelhome/public_html/app/code/community:/home2/hotelhome/public_html/app/code/core:/home2/hotelhome/public_html/lib:.:/usr/lib/php:/usr/local/lib/php')
  in /home2/hotelhome/public_html/app/Mage.php on line 51
Warning: include(Varien/Autoload.php): failed to open stream: No such
  file or directory in
  /home2/hotelhome/public_html/app/code/core/Mage/Core/functions.php on
  line 68
Warning: include(Varien/Autoload.php): failed to open stream: No such
  file or directory in
  /home2/hotelhome/public_html/app/code/core/Mage/Core/functions.php on
  line 68
Warning: include(): Failed opening 'Varien/Autoload.php' for inclusion
  (include_path='/home2/hotelhome/public_html/app/code/local:/home2/hotelhome/public_html/app/code/community:/home2/hotelhome/public_html/app/code/core:/home2/hotelhome/public_html/lib:.:/usr/lib/php:/usr/local/lib/php')
  in /home2/hotelhome/public_html/app/code/core/Mage/Core/functions.php
  on line 68
Fatal error: Class 'Varien_Autoload' not found in
  /home2/hotelhome/public_html/app/Mage.php on line 54

When we tried to run the compiler from the shell, the same errors. Uncommenting the include path in the config.php file does not work either.
Can not log into admin. Same errors.

A: Somehow the folder     lib/varien was not present. Copied it from a fresh Magento installation and everything worked.


text:
Q: .htaccess добавление в исключение поддомен Пытаюсь отправить POST запрос с одного поддомена на другой но появляется ошибка:
Failed to load https://sub2.site.com/query.php: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://sub1.site.com' is therefore not allowed access.

Вот .htaccess поддомена на которого идёт запрос.
DirectoryIndex index.html

RewriteEngine On

RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1%{REQUEST_URI} [R=301,QSA,NC,L]

RewriteCond %{ENV:HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteCond %{REQUEST_URI} !^\/query.php
RewriteRule ^(.*)$ index.html?%{REQUEST_URI} [QSA,L]

Пытался добавить исключения, но устранить ошибку никак не удается.

A: Вам нужно добавить в исключение поддомены сайта и разрешить отправлять им заголовки.
<ifmodule mod_headers.c="">
SetEnvIf Origin "^(.*\.site\.com)$" ORIGIN_SUB_DOMAIN=$1
Header set Access-Control-Allow-Origin "%{ORIGIN_SUB_DOMAIN}e" env=ORIGIN_SUB_DOMAIN
Header set Access-Control-Allow-Methods: "*"
Header set Access-Control-Allow-Headers: "Origin, X-Requested-With, Content-Type, Accept, Authorization"
</ifmodule>


text:
Q: How can I auto-insert a comment header in Coda? Whenever I create a new file, I would like to be able to include a comment header that has me as the author and some copyright info. How can I automatically generate this?

A: You could create a "Clip". A clip is basically a pre-defined snippet of code that can be quickly inserted.
The Clips button is along the bottom of the Coda window next to "Hints".
Clips make it really easy to insert a block of code quickly (like <!Doctype ...>).


text:
Q: how to combine pygame and tkinter? I have python snake game which is written by pygame and i have a start window(like the ones you see at the start of games) which is written with tkinter.I want to combine them;first the tkinter window come, and the users clicks on play,then the pygame window show up.

A: A Tk window's mainloop function will delay execution of the rest of the script until the window is destroyed. So, for example:
import Tkinter as Tk
import pygame

root = Tk.Tk()
root.title('Intro')

playButton = Tk.Button(root, text='Play', command=root.destroy)
playButton.pack()

root.mainloop() # Rest of the script won't execute until playButton pressed

# Initialize pygame window


text:
Q: Fibonacci's rabbits variation In this variation on Fibonacci rabbits the growth of mature rabbits in a period has to be less than 10%.

*

*After one period the rabbits are called "young rabbits", after two periods the rabbits will be mature rabbits.

*Each pair of mature rabbits will give birth to a pair of newborn rabbits.

*Only 80% of the rabbits survive at birth.

*After the mature rabbits gave birth, hunters have to kill $p \cdot 100$% of the rabbits such that the growth of mature rabbits in a period is less than 10%.

What must the value $p$ at least be to meet this criterium? Can I solve this using a recurrence relation just like in the normal version of Fibonacci's rabbits?

A: As tomi—whose notation I shall adopt—shows in his answer,
$$
y_{n+1}=0.8x_n\ ,
$$
and
\begin{align}
x_{n+1}&=(1-p)x_n+y_n\\
&=(1-p)x_n + 0.8x_{n-1}\ .
\end{align}
The solution of this recurrence relation is given by
$$
x_n= \left(\frac{x_1-\lambda_-x_0}{\lambda_+-\lambda_-} \right)\lambda_+^n- \left(\frac{x_1-\lambda_+x_0}{\lambda_+-\lambda_-} \right)\lambda_-^n\ ,
$$
where
$$
\lambda_\pm=\frac{1-p\pm\sqrt{(1-p)^2+3.2}}{2}\ .
$$
Since $\ -1<\lambda_- < 0\ $, the term $\ \left(\frac{x_1-\lambda_+x_0}{\lambda_+-\lambda_-} \right)\lambda_-^n\ $ in the expression for $\ x_n\ $ oscillates between positive and negative values of ever decreasing magnitude which converges to $0$ as $\ n\rightarrow\infty\ $.  The asymptotic growth rate of the population per period (or the constant actual growth rate, if $\ x_1=\lambda_+x_0\ $) is therefore $\ \lambda_+\ $, which is required to be less than $\ 1.1\ $. That is
\begin{align}
&&\frac{1-p+\sqrt{(1-p)^2+3.2}}{2}<1.1\\
&\iff&\sqrt{(1-p)^2+3.2}<p+1.2\\
&\iff& (1-p)^2+3.2<(p+1.2)^2\\
&\iff& \frac{69}{110}< p\ .
\end{align}

A: Let $x_n$ be the number of mature rabbits at time $n$.
Let $y_n$ be the number of young rabbits at time $n$.
Let $z_n$ be the number of newborn rabbits at time $n$.
The number of newborn rabbits is equal to the number of mature rabbits, so $z_{n}=x_n$
80% of newborn rabbits survive to become young rabbits. This is equivalent to $y_{n+1}=0.8z_n$
With no intervention from hunters, all young rabbits would become mature rabbits and all mature rabbits would stay alive as mature rabbits. This is equivalent to $x_{n+1}=x_n+y_n$
Killing a proportion of the mature rabbits means that $x_{n+1}=(1-p)x_n+y_n$
We could create a recurrence relationship using the above, but we are told that the hunters kill enough rabbits so that in fact $x_{n+1}=1.1x_n$
This has the straightforward solution $x_n=(1.1)^nx_0$
To find out how many need to be killed to achieve this rate of growth, let's look again at the earlier equations.
$z_{n}=x_n \Rightarrow z_{n}=(1.1)^nx_0 $
$y_{n+1}=0.8z_n \Rightarrow y_{n+1}=0.8 \times (1.1)^{n}x_0 \Rightarrow y_{n}=0.8 \times (1.1)^{n-1}x_0$
Since we have both $x_{n+1}=(1-p)x_n+y_n$ and $x_{n+1}=1.1x_n$,
$1.1x_n=(1-p)x_n+y_n \Rightarrow 1.1(1.1)^nx_0=(1-p)(1.1)^nx_0+0.8 \times (1.1)^{n-1}x_0$
$(1.1)^{n+1}x_0=(1-p)(1.1)^nx_0+0.8 \times (1.1)^{n-1}x_0$
$(1.1)^{n+2}x_0=(1-p)(1.1)^{n+1}x_0+0.8 \times (1.1)^{n}x_0$
$(1.1)^2=(1-p)(1.1)+0.8$
$1.21=1.1-1.1p+0.8$
$1.1p=0.69$
$p=0.627$
So you need to kill about 63% of the mature rabbits.


text:
Q: Real-Time Figure Matlab I have an rgb matrix rgb = imread('Map.jpg');
I'm changing its pixel colors in a while loop. Is it possible to see the changes real-time?
I'm tested this script, but not working!
rgb = imread('Map.jpg');
figure
image(rgb);
axis image;
while (conditions)
    pause(0.001)
    % Change rgb matrix
    drawnow
end

A: The image command places an image on the figure from the rgb matrix. If you change the matrix after using the image command the figure will not change. Try calling image(rgb) after you change the matrix but before the drawnow command


text:
Q: How to create a variable name made up of a concatenated functions parameter value and a string? I have a simple function for adding animations to an element: addAnimation(). The main issue I'm having is with the function it calls: updateAnimationProperties(). This function takes up to 4 parameters and at least 3 of them will use the same word, such as:
updateAnimationProperties( name, element, 'animationName', nameStr );

the string name is used 3 times. This is how it will be every time this function is called. Another example:
updateAnimationProperties( duration, element, 'animationDuration', durationStr );

duration is repeated 3 times. So I want to make a function that takes the base word: name or duration and automatically concatenates the rest with a string. such as 'animation' + baseVariable or baseVariable + 'Str'.
I've tried using the window method like this:
function updateAnimationProperties( target, element, property ){
  if( target === '' ){
    element.style[ property ] = window[ target + 'Str' ];
  }
  else {
    element.style[ property ] += ', ' + window[ target + 'Str' ];
  }
}

But it doesn't seem to help. Any idea how I can reduce the number of parameters this function needs by using dynamic variables instead?
Below is the normal code with 4 parameters. I want to reduce these to possibly just 2 parameters.

//\ \ \ \ \ \ \ UPDATE ANIMATION PROPERTIES / / / / / / / / / / / / / / / / / /
function updateAnimationProperties( target, element, property, result ){
  if( target === '' ){
    element.style[ property ] = result;
  }
  else {
    element.style[ property ] += ', ' + result;
  }
}
/// / / / / / / UPDATE ANIMATION PROPERTIES \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \

//\ \ \ \ \ \ \ \ \ \ ADD ANIMATION / / / / / / / / / / / / / / / / / / / / / /
function addAnimation( element, nameStr, durationStr ){
  element.classList.add( 'animation' );

  var name = element.style.animationName,
      duration = element.style.animationDuration;

  updateAnimationProperties( name, element, 'animationName', nameStr );
  updateAnimationProperties( duration, element, 'animationDuration', durationStr );
}
/// / / / / / / / / / ADD ANIMATION \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \

var p = document.querySelector( 'p' );

addAnimation( p, 'blur', '100s' );
/* \ \ \ \ \ \ \ \ \ \ \ \ \ ANIMATION DEFINITIONS / / / / / / / / / / / / / */
.animation {
  animation-duration: 1s;
  animation-delay: 0s;
  animation-iteration-count: 1;
  animation-timing-function: ease;
  animation-direction: normal;
  animation-fill-mode: forwards;
  animation-play-state: running;
}
.blur {
  animation-name: blur;
}

/*\ \ \ \ \ \ \ \ \ \ \ \ \ \ ANIMATION KEYFRAMES / / / / / / / / / / / / / /*/
@keyframes blur {
  100% {
    filter: blur( 5rem );
  }
}

Blur this paragraph

A: Your problem is not how to access those variables dynamically, your problem is that you created these many similar variables in the first place. You should remove the target parameter and compute it inside the function, simplifying your code considerably already.
function updateAnimationProperty(element, property, value) {
  var style = element.style;
  property = 'animation' + property.charAt(0).toUpperCase() + property.slice(1);
  if (style[property] === ''){
    style[property] = value;
  } else {
    style[property] += ', ' + value;
  }
}

function addAnimation(element, name, duration){
  element.classList.add('animation');
  updateAnimationProperty(element, 'name', name);
  updateAnimationProperty(element, 'duration', duration);
}

You might also use a structure so that you can iterate the key-value pairs:
function addAnimation(element, name, duration){
  element.classList.add('animation');
  var props = {name, duration}; // short for {"name": name, "duration": duration}
  for (var p in props)
    updateAnimationProperty(element, p, props[p]);
}

(not that it's really worth here)

A: I found this, hope it works for you.
Using the arguments object:
function foo() {
  for (var i = 0; i < arguments.length; i++) {
    alert(arguments[i]);
  }
}

Here the source
Here's the documentation of it from Mozilla:
source
===============================================
Or you can use this, the apply function.
source 2
Hope that can help.


text:
Q: flutter reference to unspecified seems stuck at 0.3.4 I'm trying to add a reference to openid_client in my flutter app.
I add a dependency to openid_client: ^0.1.3 in my pubspec.yaml and save.  This runs flutter packages get, which reports the following error:
Package unscripted has no versions that match >=0.6.2 <0.7.0 derived from:
- openid_client 0.1.0 depends on version >=0.6.2 <0.7.0

Indeed, the openid_client package does depend on unscripted version 0.6.2, but my flutter app cannot reference 0.6.2.  It appears the highest version of unscripted my flutter app can reference is 0.3.4.  Does anyone know what I'm doing wrong?
This is my pubspec.yaml as it currently stands:
name: flit
description: A new Flutter project.

dependencies:
    flutter:
      sdk: flutter

cupertino_icons: ^0.1.0
english_words: ^3.1.0
openid_client: ^0.1.3

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter:
  uses-material-design: true


text:
Q: How to show an image for few seconds in QML? I have an image that i need to show for few seconds. How to do it in QML ?
Does anyone has an an example ?
i have this one with state but its doest not appear . I need also to make ir repetitive
     Item {
         id: myimageanimation
         x:0
         y:0
          z:2000

Image {
        id: rect
        x: 293
        y: 242
        source: "assets/ic_sound_popup_off.png"
    }

states: [
        State {
            name: "actif"
            PropertyChanges {
                target: rect
                visible:true

            }
    },
        State {
            name:"inactif"
            PropertyChanges {
                target:rect
                visible : false
            }
    }
    ]

    transitions:  [
        Transition {
            NumberAnimation {
                property: "visible"
                duration:2000
                easing.type: Easing.InOutQuad
            }
        }
    ]

A: You can use an PropertyAnimation on visible
Window {
    id: root
    visible: true
    width: 1200
    height: 1000
    Image {
        id: rect
        anchors.fill: parent
        source: 'qrc:/Pics/mypic.png'
    }

    PropertyAnimation {
        running: true
        target: rect
        property: 'visible'
        to: false
        duration: 5000 // turns to false after 5000 ms
    }
}

Or, as @ddriver mentioned, use the Timer-Object, e.g. like this:
Window {
    id: root
    visible: true
    width: 1200
    height: 1000
    Image {
        id: rect
        anchors.fill: parent
        source: 'qrc:/Pics/mypic.png'
    }

    Timer {
        interval: 5000 // triggers every 5000 ms
        onTriggered: rect.visible = false
        running: true
    }
}

You can also use the Animation to fade it away:
Window {
    id: root
    visible: true
    width: 1200
    height: 1000
    Rectangle {
        id: rect
        anchors.fill: parent
        color: 'red'
        visible: opacity > 0
    }

    SequentialAnimation {
        running: true
        PauseAnimation {
            duration: 4000 // Wait for 4000ms
        }
        NumberAnimation {
            target: rect
            property: 'opacity'
            to: 0
            duration: 1000 // Then fade away for 1000ms
        }
    }
}

With the Timer, you can use a Behavior on opacity to achive the same.


text: Q: How to enable CBA for EWS managed API authentication Microsoft has provided a class named ClientCertificateCredentials in EWS library. What exactly is needed for anyone to start using it? For example, is there any Exchange server side configuration required to enable CBA for EWS? Also, what should be the certificate passed to the ExchangeService object in order to authenticate the user? Should it be only the public key or both public-private keys of the cert? Not able to find any example for CBA with EWS managed API


text:
Q: Check a mathematical string for syntax errors in Matlab As an example I have this string: "12+8*(23+4)*cos(0.813)" which would be correct.
In this: "12+8*)23+4)*co(0.813)" I should get an error for the first brace ")" and "co".
Is there a way to filter such problems by checking with regular expression or regular language analyser like Coco/R for c#? There you can declare a grammar, tokens etc. and check if a string matches your language.
Only Matlab itself should be used.


text:
Q: Generate SQL from Spark SQL I have a Scala code with Spark DataFrame with a join of few frames and filter and dynamic part.
Is it possible to generate and write to log a classic SQL code to control the process?
        val target = List(
            ("0", "0", "Orange", "2020-03-10")
        ).toDF("id", "new_id", "name", "process_date")

    ....
    dynamic part of code
    ....

    increment.as("i")
            .join(target.as("t"), $"t.id" === $"i.id", "left")
            .select(selectFields: _*)

I want to get in logs something like this
    select field1, field2, ....
    from increment i join target t where t.id = i.id

A: Maybe you could try to write in the log itself just after the query's execution.
Something like this example:
import org.apache.log4j.{Level, Logger}

Logger.getRootLogger.setLevel(Level.ERROR)
// your code here
increment.as("i")
        .join(target.as("t"), $"t.id" === $"i.id", "left")
        .select(selectFields: _*)
Logger.getRootLogger.error("""SELECT column1, column2, column3 FROM table JOIN table1 ON(id = id1) WHERE column3 = .....GROUP BY ....""")


text:
Q: What is the fastest way to load a large CSV file into core data Conclusion
Problem closed, I think.
Looks like the problem had nothing to do with the methodology, but that the XCode did not clean the project correctly in between builds.
It looks like after all those tests, the sqlite file that was being used was still the very first one that wasn't indexed......
Beware of XCode 4.3.2, I have nothing but problems with Clean not cleaning, or adding files to project not automatically being added to the bundle resources...
Thanks for the different answers..
Update 3
Since I invite anybody to just try the same steps to see if they get the same results, let me detail what I did:
I start with blank project
I defined a datamodel with one Entity, 3 attributes (2 strings, 1 float)
The first string is indexed

In did finishLaunchingWithOptions, I am calling:
[self performSelectorInBackground:@selector(populateDB) withObject:nil];

The code for populateDb is below:
-(void)populateDB{
NSLog(@"start");
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
NSManagedObjectContext *context;
if (coordinator != nil) {
    context = [[NSManagedObjectContext alloc] init];
    [context setPersistentStoreCoordinator:coordinator];
}

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"input" ofType:@"txt"];
if (filePath) {
    NSString * myText = [[NSString alloc]
                               initWithContentsOfFile:filePath
                               encoding:NSUTF8StringEncoding
                               error:nil];
    if (myText) {
        __block int count = 0;

        [myText enumerateLinesUsingBlock:^(NSString * line, BOOL * stop) {
            line=[line stringByReplacingOccurrencesOfString:@"\t" withString:@" "];
            NSArray *lineComponents=[line componentsSeparatedByString:@" "];
            if(lineComponents){
                if([lineComponents count]==3){
                    float f=[[lineComponents objectAtIndex:0] floatValue];
                    NSNumber *number=[NSNumber numberWithFloat:f];
                    NSString *string1=[lineComponents objectAtIndex:1];
                    NSString *string2=[lineComponents objectAtIndex:2];
                    NSManagedObject *object=[NSEntityDescription insertNewObjectForEntityForName:@"Bigram" inManagedObjectContext:context];
                    [object setValue:number forKey:@"number"];
                    [object setValue:string1 forKey:@"string1"];
                    [object setValue:string2 forKey:@"string2"];
                    NSError *error;
                    count++;
                    if(count>=1000){
                        if (![context save:&error]) {
                            NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
                        }
                        count=0;

                    }
                }
            }

        }];
        NSLog(@"done importing");
        NSError *error;
        if (![context save:&error]) {
            NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
        }

    }
}
NSLog(@"end");
}

Everything else is default core data code, nothing added.
I run that in the simulator.
I go to ~/Library/Application Support/iPhone Simulator/5.1/Applications//Documents
There is the sqlite file that is generated
I take that and I copy it in my bundle

I comment out the call to populateDb
I edit persistentStoreCoordinator to copy the sqlite file from bundle to documents at first run
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
@synchronized (self)
{
    if (__persistentStoreCoordinator != nil)
        return __persistentStoreCoordinator;

    NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"myProject" ofType:@"sqlite"];
    NSString *storePath = [[[self applicationDocumentsDirectory] path] stringByAppendingPathComponent: @"myProject.sqlite"];

    NSError *error;
    if (![[NSFileManager defaultManager] fileExistsAtPath:storePath])
    {
        if ([[NSFileManager defaultManager] copyItemAtPath:defaultStorePath toPath:storePath error:&error])
            NSLog(@"Copied starting data to %@", storePath);
        else
            NSLog(@"Error copying default DB to %@ (%@)", storePath, error);
    }

    NSURL *storeURL = [NSURL fileURLWithPath:storePath];

    __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                             [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                             [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

    if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error])
    {

        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return __persistentStoreCoordinator;
}
}

I remove the app from the simulator, I check that ~/Library/Application Support/iPhone Simulator/5.1/Applications/ is now removedI rebuild and launch again
As expected, the sqlite file is copied over to ~/Library/Application Support/iPhone Simulator/5.1/Applications//Documents
However the size of the file is smaller than in the bundle, significantly!
Also, doing a simple query with a predicate like this predicate = [NSPredicate predicateWithFormat:@"string1 == %@", string1];   clearly shows that string1 is not indexed anymore

Following that, I create a new version of the datamodel, with a meaningless update, just to force a lightweight migration
If run on the simulator, the migration takes a few seconds, the database doubles in size and the same query now takes less than a second to return instead of minutes.
This would solve my problem, force a migration, but that same migration takes 3 minutes on the iPad and happens in the foreground.
So hat's where I am at right now, the best solution for me would still be to prevent the indexes to be removed, any other importing solution at launch time just takes too much time.
Let me know if you need more clarifications...
Update 2
So the best result I have had so far is to seed the core data database with the sqlite file produced from a quick tool with similar data model, but without the indexes set when producing the sqlite file. Then, I import this sqlite file in the core data app with the indexes set, and allowing for a lightweight migration. For 2 millions record on the new iPad, this migration stills take 3 minutes. The final app should have 5 times this number of records, so we're still looking at a long long processing time.
If I go that route, the new question would be: can a lightweight migration be performed in the background?
Update
My question is NOT how to create a tool to populate a Core Data database, and then import the sqlite file into my app. I know how to do this, I have done it countless times. But until now, I had not realized that such method could have some side effect: in my case, an indexed attribute in the resulting database clearly got 'unindexed' when importing the sqlite file that way.
If you were able to verify that any indexed data is still indexed after such transfer, I am interested to know how you proceed, or otherwise what would be the best strategy to seed such database efficiently.

Original
I have a large CSV file (millions of lines) with 4 columns, strings and floats.
This is for an iOS app.
I need this to be loaded into core data the first time the app is loaded.
The app is pretty much non functional until the data is available, so loading time matters, as a first time user obviously does not want the app to take 20 minutes to load before being able to run it.
Right now, my current code takes 20 min on the new iPad to process a 2 millions line csv file.
I am using a background context to not lock the UI, and save the context every 1,000 records
The first idea I had was to generate the database on the simulator, then to copy/paste it in the document folder at first launch, as this is the common non official way of seeding a large database. Unfortunately, the indexes don't seem to survive such a transfer, and although the database was available after just a few seconds, performance is terrible because my indexes were lost. I posted a question about the indexes already, but there doesn't seem to be a good answer to that.

So what I am looking for, either:

*

*a way to improve performance on loading millions of records in core data

*if the database is pre-loaded and moved at first startup, a way to keep my indexes

*best practices for handling this kind of scenario. I don't remember using any app that requires me to wait for x minutes before first use (but maybe The Daily, and that was a terrible experience).

*Any creative way to make the user wait without him realizing it: background import while going through tutorial, etc...

*Not Using Core Data?

*...

A: Pre-generate your database using an offline application (say, a command-line utility) written in Cocoa, that runs on OS X, and uses the same Core Data framework that iOS uses. You don't need to worry about "indexes surviving" or anything -- the output is a Core Data-generated .sqlite database file, directly and immediately usable by an iOS app.
As long as you can do the DB generation off-line, it's the best solution by far. I have successfully used this technique to pre-generated databases for iOS deployment myself. Check my previous questions/answers for a bit more detail.

A: I'm just starting out with SQLite and I need to integrate a DB into one of my apps that will have a lot of indexed data in a SQLite database.  I was hoping I could do some method where I could bulk insert my information into a SQLite file and add that file to my project.  After discovering and reading through your question, the provided answer and the numerous comments, I decided to check out the SQLite source to see if I could make heads or tails of this issue.
My initial thought was that the iOS implementation of SQLite is, in fact, throwing out your indices.  The reason is because you initially create your DB index on x86/x64 system.  The iOS is an ARM processor, and numbers are handled differently.  If you want your indexes to be fast, you should generate them in such a way that they are optimized for the processor in which they will be searched.
Since SQLite is for multiple platforms, it would make since to drop any indices that have been created in another architecture and rebuild them.  However, since no one wants to wait for an index to rebuild the first time it is accessed, the SQLite devs most likely decided to just drop the index.
After digging into the SQLite code, I've come to the conclusion that this is most likely happening.  If not for the processor architecture reason, I did find code (see analyze.c and other meta-information in sqliteint.h) where indices were being deleted if they were generated under an unexpected context.  My hunch is that the context that drives this process is how the underlying b-tree data structure was constructed for the existing key.  If the current instance of SQLite can't consume the key, it deletes it.
It is worth mentioning that the iOS Simulator is just that-- a simulator.  It is not an emulator of the, hardware.  As such, your app is running in a pseudo-iOS device, running on an x86/x64 processor.
When your app and SQLite DB are loaded to your iOS device, an ARM-compiled variant is loaded, which also links to the ARM compiled libraries within iOS.  I couldn't find ARM specific code associated with SQLite, so I imagine Apple had to modify it to their suit.  The could also be part of the problem.  This may not be an issue with the root-SQLite code, it could be an issue with the Apple/ARM compiled variant.
The only reasonable solution that I can come up with is that you can create a generator application that you run on your iOS machine.  Run the application, build the keys, and then rip the SQLite file from the device.  I'd imagine such a file would work across all devices, since all ARM processors used by iOS are 32-bit.
Again, this answer is a bit of an educated guess.  I'm going to re-tag your question as SQLite.  Hopefully a guru may find this and be able to weigh in on this issue.  I'd really like to know the truth for my own benefit.


text:
Q: HTML CSS: Button- Wrap Container Directly Around it How do I wrap these boxes directly around the button? Right now I getting these horizontal long boxes spacing. I want to wrap directly around the bell button. This way user cannot utilize button without directly touching it. Using Chrome inspector, ctrl-shift-i
Currently using  text-align center, display:flex, align-items: center, justify-content: center, and its still not working. Red box below is ideal around

.grid-container.toolsetbutton {
    display: grid;
    grid-template-columns: repeat(1, 100px);
    grid-template-rows: repeat(2, 100px);
    grid-gap: 1px;
    padding: 0px;
    align-items: center;
}

.mdc-button.toolsetbutton {
    background:transparent;
    border:none;
}

.material-icons.mdc-button__icon.toolsetbutton {
    text-align: center;
    background:transparent;
    border:none;
    display:flex;
    border:none;
    align-items: center;
    justify-content: center;
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

  <button class="mdc-button toolsetbutton">
    notifications
  </button>
  <button class="mdc-button toolsetbutton">
    delete
  </button>

A: So if I'm understanding your intent correctly, just need to override the left/right margins with auto as shown. However, I'd advise you to not use your selectors in such a way as you do with all the .blah.blah.toolsetbutton stuff as the order of inception you're currently implementing will only become less performant and more difficult to maintain the more the it's propagated within a project.
Anyway, hope this helps, cheers!

.grid-container.toolsetbutton {
    display: grid;
    grid-template-columns: repeat(1, 100px);
    grid-template-rows: repeat(2, 100px);
    grid-gap: 1px;
    padding: 0px;
    align-items: center;
}

.mdc-button.toolsetbutton {
    background:transparent;
    /*border:none; - removed so there's a visual aid of hit area */

    margin: 0 auto;
    padding: 0;
}

.material-icons.mdc-button__icon.toolsetbutton {
    text-align: center;
    background:transparent;
    border:none;
    display:flex;
    border:none;
    align-items: center;
    justify-content: center;
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

  <button class="mdc-button toolsetbutton">
    notifications
  </button>
  <button class="mdc-button toolsetbutton">
    delete
  </button>

So as requested, here's another approach more aligned with how I'd probably accomplish the same personally. Reasoning being that since HTML doesn't minify; well I'd rather write a tiny bit more CSS, and far less HTML over and over. This helps a lot with rendering speed and file sizes for less traffic on the wire. Anyway, a quick PoC learning example since we've all been there is below. Feel free to remove the tooltips and tinker obviously. Also I wouldn't use grid at all in this scenario in lieu of good 'ol box model instead. Have a great weekend!

.btn-grid-container {
  display: grid;
  grid-template-columns: repeat(1, 100px);
  grid-template-rows: repeat(2, 100px);
  grid-gap: 1px;
}

.btn-grid-container > button {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: transparent;
  border: 0;
  outline: 0;
  font-size: 2rem;
  margin: auto;
  padding: 0;
}

.btn-grid-container > button:before {
  font-family: 'Material Icons';
  content: attr(data-icon);
  border-radius: 6px;
  border: transparent 1px solid;
  cursor: pointer;
  transition: color .25s ease, background-color .25s ease, border-color .25s ease;
}

.btn-grid-container button:hover:before, .btn-grid-container button:focus:before {
  color: green;
  border-color: green;
  background-color: rgba(0,255,0,.1);
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

  <button data-icon="" title="Notifications"></button>
  <button data-icon="" title="Delete"></button>


text:
Q: How to use multiple supply options in the easiest way for STM32? I designed a custom board with STM32, ADC, and RS422 transceivers.
The estimated current consumption of all the IC on the circuit is not more than 200 mA on 3.3 V.
in the operational mode, the board should be powered with a power supply with an output of 5 V with enough current.
I want to add options when the software engineer works on my board that he doesn't need to connect the power supply, and could use in the power from USB which in any case is connected for debugging purposes.
The main problem is that when we set the board to the system we are supposed to use the USB connection to the computer for debugging only anyway, but the voltage from the USB is not required due to safety issues, and the voltage should be received from the power source.
Simply put:
In the lab for debugging and bringing up work - use the power from the USB and communications to the computer.
In an operational system - power from the power source and communications to the computer without power from the USB. How to do it?


text:
Q: git - forced update. What happened? When I do git push --force I see next output from git:
$ git push --force
Counting objects: 21, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (21/21), done.
Writing objects: 100% (21/21), 2.36 KiB | 1.18 MiB/s, done.
Total 21 (delta 14), reused 0 (delta 0)
To repo:/v1/repos/DB-Hooks
 + 7b4eaa2...1295174 reimplement -> reimplement (forced update)

$ git log --graph --decorate --pretty=oneline --abbrev-commit 7b4eaa2...1295174
* 1295174 (HEAD -> reimplement) TEMPORARY
* 0f477bf Prettify code
* 09630ef Setup $DB::single
* 7b4eaa2 TEMPORARY

How can I check what happened here from this log?

*

*Which commits are mine? (under "mine" I mean the changes done in my local repository, including amended commits)

*Which commits are replaced and what replaced in those commits?

*Which commits are gone from remote? (what changes I introduce in my local repository)

A:

*

*Which commits are mine?

You need to define "mine".  What does it mean for a commit to be "yours"?
Edit: you added under "mine" I mean the changes done in my local repository, including amended commits.  First, always remember that commits are snapshots; to turn a snapshot into a change-set, you must pick some other commit and run git diff to compare the two commits.  The result of the comparison is a set of instructions for turning the first snapshot into the second snapshot.  That's not necessarily something you, or even anyone, did: it's just a set of changes that produce the same result.  (This is why sometimes git diff says "delete the close brace of a previous block, plus most of this block" rather than "delete all of this block".)
Git isn't really about where a commit was made: if you connect two Git repositories, any commit with hash ID a1b2c3d, for instance, in either repo is the same commit as a commit with hash ID a1b2c3d in the other repo.  What git push and git fetch do is connect two Git repositories, and transfer commits between them.  A push operation means connect my repo to someone else's and attempt to give the someone-else some commits I have in my repo, which I assume they don't have yet.  A fetch operation means connect my repo to someone else's repo and attempt to get commits they have, that I assume I don't have yet.
If you fetch from Alice's repository, then push to Bob's repository, this allows you to transfer commits that originally were only in Alice's repository, over to Bob's repository.  So the fact that you gave Bob commit a1b2c3d doesn't mean that commit a1b2c3d is something you wrote yourself, it just means Bob didn't have a1b2c3d—he had not yet obtained it directly from Alice, or from anyone else either.
Last, if you run git commit --amend, that doesn't change any existing commit.  Instead, it just makes a new (different, presumably better) commit whose parent is the same as the --amended commit's parent:
...--o--o--0bad   <-- branch

becomes:
          0bad   [abandoned]
         /
...--o--o--1337   <-- branch

if the old commit's hash begins with 0bad and the new one's begins with 1337.

*Which commits are replaced ...

None.  Commits are identified by hash IDs.  Those hash IDs continue to identify the same commits.
However, we do know from the git push output that the name reimplement in the other Git used to represent the commit whose hash ID is 7b4eaa2, and now represents the commit whose hash ID is 1295174.  This factors into your question 3:

*Which commits are gone from remote?

We also know two more things from your own git log output:

*

*The string 7b4eaa2...1295174 selects the four displayed commits.  Since A...B means "commits reachable from either A or B but not from both A and B", that means those four commits are reachable from one of those two commits, but not from both of them.

*The output from git log --graph is further restrained to occur in topological order:

Show no parents before all of its children are shown, and avoid showing commits on multiple lines of history intermixed.

Since 7b4eaa2 came out last, this means all of its children have been shown before that point.  Since 1295174 came out first, it has no children.  The intermediate commits must either be children of 7b4eaa2 (i.e., 7b4eaa2 is their parent or grandparent), or parents of 1295174.
Putting these all together
We know that 1295174 is the new tip of reimplement in the remote (since the push was accepted and it is the tip of reimplement in your own repository):
... <-1295174   <-- reimplement

We know that the remote's old reimplement, before the git push, ended with:
... <-7b4eaa2

What we must consider is whether we should draw what is now in your own repository like this:
?--09630ef--0f477bf--1295174   <-- reimplement
 \
  7b4eaa2   [abandoned]

or like this:
?--1295174   <-- reimplement
 \
  09630ef--0f477bf--7b4eaa2   [abandoned]

or even like this:
?--09630ef--1295174   <-- reimplement
 \
  0f477bf--7b4eaa2   [abandoned]

Your git log 1295174...7b4eaa2 would show the first one as what we've seen.  It would show the second, though, as:
* 1295174 (HEAD -> reimplement) TEMPORARY
* 7b4eaa2 TEMPORARY
* 09630ef Setup $DB::single
* 0f477bf Prettify code

and the third in yet another form.  (If 1295174 were a merge commit with both 0f477bf and 09630ef as parents, we'd see yet a different graph output: we know for certain that all the commits shown here are linearly related or unrelated.)  Hence, going back to Q3:

*Which commits are gone from remote?

we can say for certain that 7b4eaa2 is no longer reachable, in that Git, by the name reimplement.  The name reimplement instead names 1295174, and the parent of 1295174 is 0f477bf and the parent of 0f477bf is 09630ef.
If 7b4eaa2 is completely unreachable by branch or tag or similar names in the remote Git, and the remote Git has no reflogs, and a garbage collection pass has completed, commit 7b4eaa2 will have been collected and removed.

A: Try this:

To display last commit diff

git diff HEAD~1

To display last commit modified files

git diff HEAD~1 --name-only

A: I have found these two options helpful to see what is comming on --left-right --cherry-pick  --cherry-mark --boundary:

--left-right
  Mark which side of a symmetric difference a commit is reachable from. Commits from the
             left side are prefixed with < and those from the right with >

--boudary I need it to show parent root

--cherry-pick
     Omit any commit that introduces the same change as another commit on the "other side" when the set of commits are limited with symmetric difference.

$ git log --graph --decorate --pretty=oneline --abbrev-commit --left-right --cherry-pick --boundary 8cb6531...1295174
> 1295174 (HEAD -> reimplement) TEMPORARY
> 0f477bf Prettify code
> 09630ef Setup $DB::single
> 1e1b4a3 Wrap whole DB::DB into &dbcall by moving DB::db into DB::interact
| < 8cb6531 TEMPORARY
| < e348241 Wrap whole DB::DB into &dbcall by moving DB::db into DB::interact
|/
o 6086d62 Code comment

Or with --cherry-mark we can see not touched commits:
$ git log --graph --decorate --pretty=oneline --abbrev-commit --left-right --cherry-mark --boundary 8cb6531...1295174
> 1295174 (HEAD -> reimplement) TEMPORARY
> 0f477bf Prettify code
> 09630ef Setup $DB::single
= 3e4cc19 Debugger debugging is finished. Remove mark
= 3df5e8c Fix doc
> 1e1b4a3 Wrap whole DB::DB into &dbcall by moving DB::db into DB::interact
| < 8cb6531 TEMPORARY
| = 5b1ce15 Debugger debugging is finished. Remove mark
| = 8588e00 Fix doc
| < e348241 Wrap whole DB::DB into &dbcall by moving DB::db into DB::interact
|/
o 6086d62 Code comment

Here we can understand that:

*

*commits 3e4cc19 and 3df5e8c are not touched and same as 5b1ce15, 8588e00 correspondingly

*commits marked by > sign were added in your local repository

*commits marked by < sign were removed from remote repository

Because the commit Wrap whole DB::DB into &dbcall by moving DB::db into DB::interact has same name on local and remote repos we can suppose that the e348241 commit was changed and amended. And can see what was changed there:
$ git diff e348241 1e1b4a3
diff --git a/lib/DB/Commands.pm b/lib/DB/Commands.pm
index cb5b237..4f664fa 100644
--- a/lib/DB/Commands.pm
+++ b/lib/DB/Commands.pm
@@ -250,7 +250,7 @@ sub cmd_stepout {

     if( $sharp ) {
         my $frames;
-        1 while caller( 11 + $frames++ );
+        1 while caller( 12 + $frames++ );
         $frames_left =  $frames -$frames_left +1;

         return -2   if $frames_left <= 0; # Do nothing for unexisting frame

But I do not know the option that will show output like this:
$ git log --graph --decorate --pretty=oneline --abbrev-commit --left-right --cherry-mark --boundary --XX-OPTION 8cb6531...1295174
> 1295174 (HEAD -> reimplement) TEMPORARY
--- a/lib/file.pm
+++ b/lib/file.pm
@@ -250,7 +250,7 @@ sub zzzz {

 if( $code ) {
     my $frames;
-        code was
+        code now
     $var;

     return
> 0f477bf Prettify code
> 09630ef Setup $DB::single
= 3e4cc19 Debugger debugging is finished. Remove mark
= 3df5e8c Fix doc
> 1e1b4a3 Wrap whole DB::DB into &dbcall by moving DB::db into DB::interact
--- a/lib/DB/Commands.pm
+++ b/lib/DB/Commands.pm
@@ -250,7 +250,7 @@ sub cmd_stepout {

     if( $sharp ) {
         my $frames;
-        1 while caller( 11 + $frames++ );
+        1 while caller( 12 + $frames++ );
         $frames_left =  $frames -$frames_left +1;

         return -2   if $frames_left <= 0; # Do nothing for unexisting frame

o 6086d62 Code comment


text:
Q: Non-normality and heterogeneity in ANCOVA I am performing an ANCOVA. My dependent variable is the number of days a student is absent from school. As one can imagine, this variable is not normal, so I performed a log10 transformation. When I run the analysis with the transformed variable, I find no significant relationship with my variable of interest. However, when I run it with the original dependent variable the relationship is significant. Also, the homogeneity assumption is violated with the original dependent variable, but not with the transformed variable. Given the violations, I was under the impression that statistical power should be reduced. Why is it that I only find significant results when these assumptions are violated? Can someone help explain this to me? I should also mention that my sample sizes are quite unequal and in this case the smaller cell has a smaller variance on the dependent variable.

A: First, without seeing the data, it is difficult, if not impossible, to tell exactly why you get significance with the model that violates the assumptions but not with the one that doesn't. However, one possible (likely) reason is that you had some students with a large number of absences that also had an unusual value on the independent variable (whatever it is - you could tell us). This would then be an influential point and cause a strange relationship.
Second, it is not the dependent variable that has to be normal, it is the residuals from the model. Have you tested those?
Third, days absent is a count variable. Therefore, unless the mean number of days absent is fairly high, you should not be doing ANCOVA at all, you should be doing some form of count regression. Possibly Poisson but more likely negative binomial regression. If this is over a relatively short time period, then you might even need a zero-inflated model, but it's hard to tell without the data.
Fourth, how did you take the log of the number of days absent? Surely some students had no days absent? Log(0) is undefined.

A: The dependent variable is not required to have an (unconditional) normal distribution, even if you're using it for inference.
Its conditional distribution should be close to normal unless the sample size is fairly large, or the inference will be somewhat affected.
Note that the linearity assumption and the homoscedasticity assumption are both affected by your transformation - you can't just transform variables without consideration for your other assumptions. Even the additivity of the error term is affected.
Perhaps worst of all -- taking logs of counts will lose all the cases where the count is zero. In some cases this can totally screw up your analysis. Indeed, that loss of points could even be one explanation (of a bunch of possible ones) for the significant/non-significant issue.
You should probably be using a model appropriate for count data, such as a GLM with a binomial response (assuming constant probability of absence within each case), or a Poisson (probably what I'd try first), or quasi-Poisson or even negative binomial.
If you must use linear regression, and see equality of variance as most important, approximate variance-stabilizing transformations include the Anscombe and Freeman-Tukey. These used to be used more often before GLM software became widespread. These all improve the normal approximation quite well as long as the counts tend not to be low.
However, the assumption of linearity is to my mind generally the more central assumption; you must consider whether any transformation is making that worse rather than better.


text:
Q: How to check for Jupyter active notebooks through command line I have an AWS EMR running Jupyterhub version 0.8.1+ that I want to check if there are any active notebooks that are running any code.
I've tried the below commands but they don't seem to output what I'm looking for here since the users server is always running and notebooks can be running without any code being executed.
# only lists running servers and jovyan is always running.
sudo docker exec jupyterhub jupyter notebook list
# No useful information outputted
curl -k -i -H "Accept: application/json" "https://localhost:9443/api/sessions"
# always lists processes regardless of running notebooks
ps aux | grep ipykernel
# The last_activity only updates when a user creates a new file or folder in the ui.
curl -k https://localhost:9443/hub/api/users/$user -H "Authorization: token $admin_token" | jq -r .last_activity
curl -k https://localhost:9443/hub/api/users -H "Authorization: token $admin_token" | jq -r .last_activity

Im following this AWS blog to check if the entire EMR is idle before terminating the cluster but they never seemed to have fully implemented the jupyter checks.
https://aws.amazon.com/blogs/big-data/optimize-amazon-emr-costs-with-idle-checks-and-automatic-resource-termination-using-advanced-amazon-cloudwatch-metrics-and-aws-lambda/
Most of the files referenced can be found in Github https://github.com/septian-putra/emr-monitoring

A: To see if a notebook is "idle" for "busy" you can run curl -ks https://localhost:9443/user/jovyan/api/kernels -H "Authorization: token ${admin_token}"
With this command all you need to do is put it in a simple if statement with a grep -q in order to get a true false idle value.
if [ $(curl -ks https://localhost:9443/user/jovyan/api/kernels -H "Authorization: token ${admin_token}" | grep -q "busy") ]; then
    JUPYTER_BUSY_NOTEBOOKS=1
else
    JUPYTER_BUSY_NOTEBOOKS=0
fi

(curl -ks For a silent output and to ignore ssl. jovyan being my admin user)
Documentation
https://jupyter-kernel-gateway.readthedocs.io/en/latest/websocket-mode.html#http-resources
/api/sessions might also be useful to look at.


text:
Q: Batch Script Reads in File but returns Empty String I've come across a weird issue on Windows 10 with Batch Scripts.
This code reads in a file called manifest.yaml and compares its content to another file.
set EXECUTABLE_DIR=C:\some\path
set version=qqq

set /p oldversion=<%EXECUTABLE_DIR%\%version%\manifest.yaml
echo "%oldversion%"
set /p newversion=<%EXECUTABLE_DIR%\%version%\tmp\manifest.yaml
if "%oldversion%"=="%newversion%" (
   echo "equal"
) else (
   echo "not equal"
)

This code works on its own. But if I include this into a larger batch script, the oldversion and newversion variables are empty and I cannot find reasons why.
Things I have double checked:

*

*both files exist and do have content

*both files are not blocked for reading (no other program is currently writing those files)

*oldversion and newversion are both never used or overwritten somewhere else

*EXECUTABLE_DIR and version both contain the correct path to the file

*the short script does infact work with the original file locations the large file would use

This code is included in the larger batch script inside an if block like this:
IF exist %EXECUTABLE_DIR%\%version%\ (
  REM Code goes here
)

A: This error occurred because of variable behaviours in windows batch files as described here Variable behaviour in Windows batch files
Variables inside IF code blocks are evaluated before execution if referenced like so: %variable%
If variables are changed inside that IF code block, you need to reference variables with the "delayed expansion syntax" like so !variable! as well as enabling the delayed expansion as a secondary argument in setlocal enabledelayedexpansion.
This is answered here: How do SETLOCAL and ENABLEDELAYEDEXPANSION work?
aswell as a perfect explanation how the batch line parser works: How does the Windows Command Interpreter (CMD.EXE) parse scripts?
The final code should look like this:
setlocal enabledelayedexpansion
set "EXECUTABLE_DIR=C:\some\path"
set "version=qqq"
IF exist "%EXECUTABLE_DIR%\%version%\" (
  set /p oldversion=<%EXECUTABLE_DIR%\%version%\manifest.yaml
  echo "%oldversion%"
  set /p newversion=<%EXECUTABLE_DIR%\%version%\tmp\manifest.yaml
  if "!oldversion!"=="!newversion!" (
     echo "equal"
  ) else (
     echo "not equal"
  )
) ELSE echo No such directory

Thanks to @jeb on pointing in the correct direction and @Gerhard for pointing out good coding formats.


text:
Q: Correct process for performing multiple git remote pushes My project consists of:

*

*A git repository stored on bitbucket

*A local copy

*A development copy on a server

On my server, I ran the following command to create a bare repo
git init --bare project.git

To create the ability to push to my server, I ran the following commands out of the repository on my local machine:
git remote add serverrepo username@serverip:/path/to/repo/project.git
git remote set-url serverrepo --push --add username@serverip:/path/to/repo/project.git

If I try to push to the server by executing
git push serverrepo master

I get a
fatal: '/path/to/repo/project.git' does not appear to be a git repository
fatal: Could not read from remote repository.
Please make sure you have the correct access rights and the repository exists.

I've been searching for days, and I can't seem to figure out what the issue is. Can anybody help me?

A: Skip the second git remote command (the one with remote set-url serverrepo --push --add).
You don't need it.
If you already typed that command, make sure to clean every remote entry in your local .git/config, and start over.
Simply type:
git remote add serverrepo username@serverip:/path/to/repo/project.git
git push -u serverrepo master