text:
Q: Overload with different return type in Java? Why is it not possible to overload a function just by changing the return type?  Will that change in a future version of Java?
By the way, just for reference, is this possible in C++?

A: Overloaded methods in java may have different return types given that the argument is also different.
Check out the sample code.
public class B {

    // Method to be overloaded
    public String greet() {
        return "Hello";
    }

    //This will work
    public StringBuilder greet(String name) {
        return new StringBuilder("Hello " + name);
    }

    //This will not work
    //Error: Duplicate method greet() in type B
    public StringBuilder greet() {
        return new StringBuilder("Hello Tarzan");
    }

}

A: The reason is that overloads in Java are only allowed for methods with different signatures.
The return type is not part of the method signature, hence cannot be used to distinguish overloads.
See Defining Methods from the Java tutorials.

A: Before Java 5.0, when you override a method, both parameters and return type must match exactly. In Java 5.0, it introduces a new facility called covariant return type. You can override a method with the same signature but returns a subclass of the object returned. In another words, a method in a subclass can return an object whose type is a subclass of the type returned by the method with the same signature in the superclass.

A: You can't do it in Java, and you can't do it in C++. The rationale is that the return value alone is not sufficient for the compiler to figure out which function to call:
public int foo() {...}
public float foo() {..}

...
foo(); // which one?

A: The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.

A: Return type does not matter while overloading a method. We just need to ensure there is no ambiguity!
The only way Java can know which method to call is by differentiating the types of the argument list. If the compiler allowed two methods with the same name and same argument types, there would be no way to determine which one it should call.

A: The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.
If you are aware of function execution then you will be aware that when we call a function the definition part executes and at last we require the return statement, hence we can say return comes after the function's whole defintion, thats why if there are two or more functions with same name and with same type and no. of arguments then at the time of calling how compiler will know about which one to be called, because function name and parameters are the same. At the time of calling firstly all the focus will be on arguments and function name and after the completion of function definition at last we deal with return statement.
Compile Time Error is better than Run Time Error. So, java compiler renders compiler time error if you declare the same method having same parameters.

A: The overloaded method is a completely different method from any other method of the same name. Overloading is not much more than name reuse.

A: public int division(int a, int b){
   int result = a/b;
   return result;
}
public double division (float a, float b){
   double result = a/b;
   return result;
}

i am pretty sure that in java 8
it is ok

A: no not really possible that way you can only overload by no of arguments or data type of the arguments


text:
Q: Uploading multiple images - Only one successful Android Volley I am trying to upload multiple images from android using volley. In android I checked many times there is no error between sending encoded string in the script. But I noticed that when the script processes the strings, only the last one is uploaded successfully, the rest failed. The error goes to the String Request in android volley and I receive a volley error.
UploadImages()
static BaseUrl baseUrl;
    AddPropertyImagesCommand command = new AddPropertyImagesCommand(this);
    private void UploadImages(){
        for (String imagePath: imageList){
            try {
                Bitmap bitmap = ImageLoader.init().from(imagePath).requestSize(256,256).getBitmap();
                final String encodedString = ImageBase64.encode(bitmap);
                String imageName = imagePath.substring(imagePath.lastIndexOf("/")+1);
                intent = getIntent();
                final int property_id = Integer.parseInt(intent.getStringExtra("property_id"));

                String ADD_IMAGE_REQUEST_URL = baseUrl.getBaseUrl() + "addPropertyImages.php";
                StringRequest stringRequest = new StringRequest(Request.Method.POST, ADD_IMAGE_REQUEST_URL,
                        new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
                        Log.d(TAG, "imagelist count: " + imageList.size());
                        progressDialog.dismiss();
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), "Error while uploading image", Toast.LENGTH_SHORT).show();
                        Log.d(TAG, "Volley Error: " + error.toString());
                        progressDialog.dismiss();
                    }
                }){
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> params = new HashMap<>();
                        params.put("encoded_string", encodedString);
                        params.put("image_name", image_name);
                        params.put("property_id", property_id + "");
                        return params;
                    }
                };
                command.add(stringRequest);
            } catch (FileNotFoundException e) {
                Toast.makeText(this, "File not found", Toast.LENGTH_SHORT).show();
                progressDialog.dismiss();
            }
        }
        //execute the singleton class from volley which is addtorequestqueue
        command.execute();
    }

Then it goes to my php script:
addPropertyImages.php
<?php

    include "connection.php";

    $response = array();
    $response["success"] = false;

    if(isset($_POST['property_id'])){
        $encoded_string = $_POST['encoded_string'];
        $image_name = $_POST['image_name'];
        $property_id = $_POST['property_id'];

        //method to upload images
        upload($encoded_string, $image_name, $property_id);
        exit;
    }else{
         echo "image not in";
         exit;
      }

    function upload($encoded_string, $img_name, $property_id){

        //create unique image file name based on micro time and date
         $date = date('Y:m:d H:i:s');
        $now = DateTime::createFromFormat('U.u', microtime(true));
        $id = $now->format('YmdHisu');

        $upload_folder = "listing_images";
        $image_path = "$upload_folder/$id_$img_name";
         $decoded_string = base64_decode($encoded_string);

         if(file_put_contents($image_path, $decoded_string) != false){
            echo "upload success";
         }else{
            echo "upload failed";
         }

    }
?>

Logcat:
01-24 10:29:02.229 23401-23401/homeseek.app.android.capstonehomeseek D/AddPropertyImages: Image name: P_20170122_220217.jpg
01-24 10:29:02.229 23401-23401/homeseek.app.android.capstonehomeseek D/AddPropertyImages: /storage/emulated/0/DCIM/Camera/P_20170122_220217.jpg
01-24 10:29:04.382 23401-23401/homeseek.app.android.capstonehomeseek D/AddPropertyImages: Image name: P_20170124_090947.jpg
01-24 10:29:04.382 23401-23401/homeseek.app.android.capstonehomeseek D/AddPropertyImages: /storage/emulated/0/DCIM/Camera/P_20170124_090947.jpg
01-24 10:29:07.745 23401-23401/homeseek.app.android.capstonehomeseek D/AddPropertyImages: Image name: P_20170121_131658.jpg
01-24 10:29:07.745 23401-23401/homeseek.app.android.capstonehomeseek D/AddPropertyImages: /storage/emulated/0/DCIM/Camera/P_20170121_131658.jpg
01-24 10:29:18.075 23401-23401/homeseek.app.android.capstonehomeseek D/AddPropertyImages: imagelist count: 3
01-24 10:29:26.888 23401-23401/homeseek.app.android.capstonehomeseek D/AddPropertyImages: Volley Error: com.android.volley.TimeoutError
01-24 10:29:27.329 23401-23401/homeseek.app.android.capstonehomeseek D/AddPropertyImages: imagelist count: 3

I am using Oum Saokosal's way of uploading image to server by android volley.
Youtube page: https://www.youtube.com/user/oumsaokosal/featured

redpajama_set_name: RedPajamaStackExchange


text:
Q: "Index was outside the bounds of the array" c# i write a program about customer registiriation. i saved customer inf. to txt file and i saved depts of customers in the access database.
I want to rank the borrowers from small to large or large to small.So, i transfered of data in the debt column and use with bubble sort. but I'm getting the error I specified in the title.how to fix it?
  private void button2_Click(object sender, EventArgs e)
    {
        listBox3.Items.Clear();
        OleDbCommand komut = new OleDbCommand();

       conn.Open();

        OleDbCommand cmd = new OleDbCommand(" SELECT  RemainingDept FROM Dept_Tbl  ", conn);

        OleDbDataReader dr = cmd.ExecuteReader();
        List<string> liste = new List<string>();
        List<string> liste1 = new List<string>();
        while ((dr.Read()))
        {

            liste.Add(dr["RemainingDept"].ToString());

        }

        int[] B;
        string[] A = liste.ToArray();

        B = Array.ConvertAll<string, int>(A, int.Parse);

        int tmp;
        for (int i = 0; i <A.Length ; i++)
        {
            for (int j=A.Length-1; j>i; j++)
            {
                if (B[j - 1] > B[j])
                {
                    tmp = B[j - 1];
                    B[j - 1] = B[j];
                    B[j] = tmp;
                listBox3.Items.Add(tmp.ToString());
                }
            }

        }

        conn.Close();
    }
}

    }

A: Your error in the for loop, as j will grow up forever. Also, it may be good to change A.Length to B.Length, although they have the same size, you're operating on B not A, so this make the code more understandable. Here is the code with an example:
string[] A = new string[]{"60","120","10","40","80","20"};
int[] B = Array.ConvertAll<string, int>(A, int.Parse);

int temp;
for (int i = 0; i < B.Length ; i++)
{
    for (int j = B.Length - 1; j > i; j--)
    {
        if (B[j - 1] > B[j])
        {
            tmp = B[j - 1];
            B[j - 1] = B[j];
            B[j] = tmp;
        }
    }
}
// Results in 10,20,40,60,80,120

Edit: If you want listBox3 to contain the sorted array, you must put after the sorting loop, like this :
listBox3.Items.Clear(); //Use this line if you need to clear the contents.
for(int i = 0; i < B.Length; i++)
{
    listBox3.Items.Add(B[i].ToString());
}


text:
Q: JPanel is not updating I have two panels. One of them is GamePanel and the other one is ControlPanel. When I press the launch button (which is added in the ControlPanel) the ball starts moving until it hits something. I have score, time and level labels in the ControlPanel and I expect them to update during the game but they don't.
ControlPanel
import java.awt.*;
import javax.swing.*;

public class ControlPanel extends JPanel {

    public static JLabel timeValue, scoreValue, levelValue;
    public static JButton launch;

    public static Timer timer;

    ControlPanel() {
        this.setLayout(null);
        this.setBounds(0, 600, 1200, 200);
    }

    public void addUnits() {

        launch = new JButton("Launch");
        launch.setBounds(450, 70, 90, 65);

        launch.addChangeListener(new ChangeListener() {
            int start = 0;

            public void stateChanged(ChangeEvent e) {
                if (ControlPanel.launch.getModel().isPressed()) {

                    ActionListener taskPerformer = new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            timeValue.setText(++start + " sec");
                        }
                    };

                    timer = new Timer(1000, taskPerformer);
                    timer.setRepeats(true);
                    timer.start();

                    GamePanel.ball.moveBall();
                }
            }
        });

        add(launch);

        JLabel timeLabel = new JLabel("Time");
        timeLabel.setBounds(615, 70, 90, 25);
        add(timeLabel);

        timeValue = new JLabel("0 sec");
        timeValue.setBounds(690, 70, 90, 25);
        add(timeValue);

        JLabel scoreLabel = new JLabel("Score");
        scoreLabel.setBounds(605, 110, 90, 25);
        add(scoreLabel);

        scoreValue = new JLabel(String.valueOf(Score.score));
        scoreValue.setBounds(690, 110, 90, 25);
        add(scoreValue);

        JLabel levelLabel = new JLabel("Level");
        levelLabel.setBounds(800, 110, 90, 25);
        add(levelLabel);

        levelValue = new JLabel(String.valueOf(GamePanel.status));
        levelValue.setBounds(860, 110, 90, 25);
        add(levelValue);
    }
}

This is my moveBall method
public void moveBall() {

    // calculate move

    ActionListener taskPerformer = new ActionListener() {
        public void actionPerformed(ActionEvent evt) {

            // initiate move

            if(hit()) {
                ControlPanel.timer.stop();

                level = getLevel() + 1;
                score = // calculate score;

                timer.stop();

                ControlPanel.levelValue.setText(String.valueOf(level));
                ControlPanel.scoreValue.setText(String.valueOf(score));

                ControlPanel.levelValue.revalidate();
                ControlPanel.scoreValue.revalidate();

                ControlPanel.levelValue.repaint();
                ControlPanel.scoreValue.repaint();
            }

            paintingComponent.repaint();
        }
    };
    timer = new Timer(10, taskPerformer);
    timer.start();
}


text:
Q: Как правильно упорядочить данные по сумме полей из другой таблицы? У таблицы games есть counters (счетчики). Их может быть несколько. у счетчиков есть поле sent:bigint.
Как отсортировать игры по порядку по кол-во этих отправленных (sent) счетчиков?
У Компании #1 есть два счетчика. у одного поле sent=3, у другого sent=2, т.е. всего отправленных счетчиков 5.
У Компании #2 - 1 счетчик. у него значение sent=4.
т.е. если сделать порядок по возрастанию, то должно получится так: компания 2, компани 1
Делаю как-то криво, вот так:
SELECT games.*, counters.game_id
FROM games INNER JOIN counters
ON games.id = counters.game_id
GROUP BY counters.sent
ORDER BY sum(counters.sent) asc


text:
Q: React native custom webview prevent SSL errors while developing Issue
Trying to connect to my local development server using react-native-webview on Android.
You can use http://10.0.0.2 as the default gateway to connect to your local machine on the emulator. Alternatively, I ran the build on my phone and connected to the IPV4 address of my machine.
I need the Crypto API and that's only available on HTTPS, which meant I needed to connect to https://10.0.0.2.
I didn't get the self signed certificate to work.
Quick & dirty solution
Call handler.proceed() on the first line of the onReceivedSslError method of the com.reactnativecommunity.webview package.
Although this might work, it's not the preferred way because it's not under source control and needs to be removed each time a release build is made or the project is freshly installed.
Solution
See answers below
Create a custom webview on development builds to circumvent the SSL error (or any other webview method).

A: My solution
1. Create a debug only class CustomWebviewManager.java
We don't want our custom webview manager ending up in release builds.
package nl.myapp;

import android.webkit.WebView;
import android.webkit.SslErrorHandler;
import android.net.http.SslError;

import com.facebook.react.module.annotations.ReactModule;
import com.facebook.react.uimanager.ThemedReactContext;
import com.reactnativecommunity.webview.RNCWebViewManager;

@ReactModule(name = CustomWebViewManager.REACT_CLASS)
public class CustomWebViewManager extends RNCWebViewManager {
    protected static final String REACT_CLASS = "RNCCustomWebView"; // React native import name

    protected static class CustomWebviewClient extends RNCWebViewClient {
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error){
            // Prevent SSL errors
            handler.proceed();
        }
    }

    @Override
    public String getName() {
        return REACT_CLASS;
    }

    @Override
    protected void addEventEmitters(ThemedReactContext reactContext, WebView view) {
        // Set our custom client as webview client
        view.setWebViewClient(new CustomWebviewClient());
    }
}

2. Create a new class to register React Packages MyappAppPackage.java
We should register our debug class only on debug mode and as a ViewManager.
React Native will call createViewManagers automatically after registering our package in the next step
Use BuildConfig.DEBUG to only execute in debug builds.
We cannot instantiate our class directly, as it will cause errors in productions builds. That's why we use Class.forName
package nl.myapp;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MyappAppPackage implements ReactPackage {

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        List<ViewManager> viewManagers = new ArrayList<>();

        if (BuildConfig.DEBUG) {
            // Add custom webview manager to circumvent SSL errors
            try {
                Class<ViewManager> c = (Class<ViewManager>) Class.forName("nl.myapp.CustomWebViewManager");
                viewManagers.add(c.newInstance());
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
        }

        return viewManagers;
    }

    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }
}

3. Register our package
package nl.myapp;

import android.app.Application;

import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import java.util.List;

public class MainApplication extends Application implements ReactApplication {
    private final ReactNativeHost mReactNativeHost =
        new ReactNativeHost(this) {
          @Override
          public boolean getUseDeveloperSupport() {
              return BuildConfig.DEBUG;
          }

          @Override
          protected List<ReactPackage> getPackages() {
              @SuppressWarnings("UnnecessaryLocalVariable")
              List<ReactPackage> packages = new PackageList(this).getPackages();

              packages.add(new MyappAppPackage());

              return packages;
          }

          @Override
          protected String getJSMainModuleName() {
              return "index";
          }
        };

    @Override
    public ReactNativeHost getReactNativeHost() {
        return mReactNativeHost;
    }

    ...
}

4. And finally use our custom webview while developing
Put it in separate file, otherwise hot-reloading won't work because requireNativeComponent would try to register the ViewManager again
src/components/native/RNCCustomWebView.js
import {requireNativeComponent} from 'react-native';

module.exports = requireNativeComponent('RNCCustomWebView');

src/components/webview.js
import React from 'react';
import { WebView } from 'react-native-webview';
import RNCCustomWebView from './native/RNCCustomWebView';

// ...

const renderWebView = () => {
  // ...

  const nativeConfig = {};
  if (__DEV__) { // __DEV__ is set by RN on debug builds
    // Set custom component to circumvent SSL errors
    nativeConfig.component = RNCCustomWebView;
  }

  return (
    <WebView
      nativeConfig={nativeConfig}
      source="https://10.0.0.1"
    />
  );
};


text:
Q: Using the adjunction formula Consider a smooth curve $C$ with a base point free linear system $|D|$ on it.
Let $\pi_1: C \times \mathbb{P}^2 \to C$ and $\pi_2: C \times \mathbb{P}^2 \to \mathbb{P}^2$ be the projections.
*What do elements of the linear system $|\pi_1^*\mathcal{O}_C \otimes \pi_2^*\mathcal{O}_{\mathbb{P}^2}(3)|$ look like geometrically? These are surfaces, but I would like to know how to interpret this complicated tensor product geometrically.
*The adjunction formula should imply that $K_S = \pi_1^*(K_C + D)$. I don't see how...
*If $\deg(D) > 2 - 2 \cdot g(C)$, then $\deg(K_C + D) > 0$. This should imply that  $\kappa(S) \geq 1$.
Is the following attempt at a proof correct? If we have $\deg(K_C + D) > 0$, then $K_C + D$ is an ample divisor. Hence some multiple $\ell(K_C + D)$ is  very ample and hence linearly equivalent to a non-zero effective divisor. Hence $\ell K_S = \pi_1^*(\ell(K_C + D))$ is linearly equivalent to the pullback of an effective divisor, therefore itself linearly equivalent to an non-zero effective divisor (not sure about this), so that the linear system $|\ell K_S|$ is non-empty and at least one-dimensional. This means by definition of Kodaira dimension that $\kappa(S) \geq 1$.


text:
Q: How to send a json file with HttpClient in C#? I'm trying send a JSON file with postman and it's working. But when I'm trying to send the same contents via HttpClient it's not working.
System.IO.File.WriteAllText(dirName + "\\importproduct.json", jsonitems);
var fileByteArray = File.ReadAllBytes(dirName + "\\importproduct.json");

using (var _client = new HttpClient())
{
    using (var content = new MultipartFormDataContent())
    {
        content.Add(new StreamContent(new MemoryStream(fileByteArray)), "file");
        var url = $"{firmInfo.ServiceUrl}/product/api/products/import";
        _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearer_token.id_token);

        var response = _client.PostAsJsonAsync(url, content).Result;
        var result = response.Content.ReadAsStringAsync().Result;
    }
}

PostMan:

A: Instead of using PostAsJsonAsync(); method you should use PostAsync(); So your code should be looking something like that
using (var _client = new HttpClient())
{
    using (var content = new MultipartFormDataContent())
    {
        content.Add(new StreamContent(new MemoryStream(fileByteArray)), "file");
        var url = $"{firmInfo.ServiceUrl}/product/api/products/import";
        _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearer_token.id_token);

        var response = _client.PostAsync(url, content).Result;
        var result = response.Content.ReadAsStringAsync().Result;
    }
}

A: PostAsJsonAsync method is a generic method, it expects as the second parameter the object that will be serialized and sent in the POST body.
var obj = JsonConvert.DeserializeObject<SomeModelClass>(jsonString);
var response = await _client.PostAsJsonAsync(url, obj).Result;

A: This is based on efecetir's post above. It works for me. BTW, I also upvoted his post.
My issue was I needed to set the content type at the content-based level.
var fileByteArray = File.ReadAllBytes(filePath);

HttpContent bytesContent = new ByteArrayContent(fileByteArray);
using (var httpClient = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
    var RequestUri = new Uri($"http://whatever.com/");
    //client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearer_token.id_token);

    formData.Headers.Add("super-secret-key", "blah");
    bytesContent.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json");

    //httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //("multipart/form-data")); // Not needed
    formData.Add(bytesContent, "file", "blah.json");
    var response = httpClient.PostAsync(RequestUri, formData).Result;
    return await HandleResponse(response);
}

A: Thanks for your comments.
I fixed it and convert my codes as below. Now it's working and much more clean.
HttpContent bytesContent = new ByteArrayContent(fileByteArray);
        using (var client = new HttpClient())
        using (var formData = new MultipartFormDataContent())
        {
            var url = $"{firmInfo.ServiceUrl}/product/api/products/import";
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearer_token.id_token);

            formData.Add(bytesContent, "file", "importproduct.json");
            var response = client.PostAsync(url, formData).Result;
            var result = response.Content.ReadAsStringAsync().Result;

        }

A: Here's code I'm using to post form information and a file
using (var httpClient = new HttpClient())
{

    var surveyBytes = ConvertToByteArray(surveyResponse);

    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var byteArrayContent =   new ByteArrayContent(surveyBytes);

    byteArrayContent.Headers.ContentType = MediaTypeHeaderValue.Parse("text/csv");
       var url = $"{firmInfo.ServiceUrl}/product/api/products/import";
    var response = await httpClient.PostAsync(url , new MultipartFormDataContent
    {
        {byteArrayContent, "\"file\"", dirName + "\\importproduct.json"}
    });

    return response;
}

This is for .net 4.5.


text:
Q: Moving files to different folder in various commits using git This may be a noob question; using Android Studio I made multiple commits creating new files in each commit.
In the last three commits, the new files were placed in wrong directories. Can I go to those commits and place them in right folders with creating new commits?

*

*Commit 4 --> move /file3 to /sample/file3

*Commit 3 --> move /file2 to /sample/file2

*Commit 2 --> move /file1 to /sample/file1

*Commit 1 --> all fine

A: You cannot change any existing commit.  But you can stop using existing commits.
Because commits save the full state of everything (well, everything committed), you can also, in effect, "go back in time" by checking out an older commit.
If you give each commit a unique ID, and draw them out in their sequence, you get something like this:
A <-B <-C <-D   <--master

That is, the latest commit, D, remembers the ID of its previous—or parent—commit C.  Meanwhile C remembers its parent, B, which remembers its parent A.  (If A is the very first commit in the repository, it has no parent, since it can't have one.  Otherwise A remembers whichever commit came before A.)
The way Git finds these is that the name master records the hash ID of the last commit.  Since that was D, master finds D.  Since D records C's ID, it's D itself that finds C, which finds B, and so on.
So, given all of this, suppose you:

*

*Check out commit A.  Now A is the current commit and you have all files the way they were when you made A.

*Proceed by copying all the files from B, but then move one of them.  Then you make a new commit that's just like B except that the file is moved (and the internal saved date for when new-improved-B is made is "now" rather than "back then").  You will get a new commit, which we can call B':
A--B--C--D
 \
  B'

The parent of B' is A: the backwards-pointing arrow that Git uses to work backwards from each commit to the one that came before, points to commit A, just as B's points to commit A.  The difference between B and B' is that you moved the file (and, of course, that B' has a different Git hash ID—our letters here stand in for the actual big ugly hash IDs that Git makes up for each new commit).
There's something missing from this diagram, though: what name points to B'?  Well, let's not worry about that yet.  Instead, let's move on to...

*Now, copy C to C', renaming one file along the way just as you did when making B'.  The parent of C' will be B':
A--B--C--D
 \
  B'-C'

*Repeat for D to make D':
A--B--C--D
 \
  B'-C'-D'

*Have Git write the hash ID of D' into the name master.  This is the particularly sneaky part: you now have:
A--B--C--D   [abandoned]
 \
  B'-C'-D'  <-- master (HEAD)

That is, now the name master identifies this new-and-improved D' instead of the old D.
The only problem with doing all this is that if any other Git user has a copy of the repository that has the commit sequence A-B-C-D in it.  They may build their own commits atop D, not atop your new D'.  This kind of process will make their lives difficult, if they are not ready for it.  So if you do have someone else using a clone of this repository, and they do have these three commits, consider not doing any of this.  But if no one else has the B-C-D chain, you're free to replace them with the new-and-improved B'-C'-D' chain.  Or, if everyone else involved in this project expects this kind of rewrite, you're still free to do it.  (If there's no one else involved, it's easy to see that of all the other people involved, none of them will object.)
OK, so, how can we achieve this rewrite?
The easy way is to use git rebase -i.  This interactive rebase lets you stop and change what will go into each new commit, before it actually makes the commit.  You simply find the actual hash ID of the commit you want to keep—in this case, commit A—and, while on branch master, run:
git rebase -i <hash>

This brings up your favorite editor—or at least, the one you have told Git is your favorite, by setting core.editor—on a file with three pick commands.  Change each to edit, save the file of instructions, and exit the editor.
Git will now proceed to start making B' atop A, but then stop and let you edit the commit.  Run:
git mv file1 sample/file1

(first making directory sample if needed), then:
git commit --amend --no-edit

to establish B' as the desired result, then:
git rebase --continue

That will loosely cement B' in place and begin the process of copying C, then stop, so now you git mv file2 sample/file2 and git commit --amend --no-edit and git rebase --continue to move to the copy-D step.  Repeat as before.
Once the updated commits are all done and in place, git rebase will do the last step, of yanking the branch name master over to point to D' instead of D.
Just for completeness: here's how the intermediate commits work
While Git is building this new replacement B'-C'-D' chain, the name that finds each of these commits is just HEAD itself.  This uses the mode that Git calls a detached HEAD.  While it sounds scary, it just means that the special name HEAD, that Git requires at all times, is not attached to any branch name at all.
For instance, in the middle of the rebase, you have:
A--B--C--D  <-- master
 \
  B'  <-- HEAD

As more commits get added, you get:
A--B--C--D  <-- master
 \
  B'-C'  <-- HEAD

and so on.  When git rebase -i runs out of instructions—the picks that you changed to edits are the instructions—the rebase is done and Git yanks the name master into place, re-attaching HEAD to it and getting us the diagram shown in step 5.

A: It was suggested in a comment, but it worths an answer.
You can't edit the directory of past commits,
usually in this situation you should prefer to change the directory and commit the change. unless you really wish to do it in past commit, which then you'll need to revert to the first commit you want to change, and start changing it while recommitting everything.
To revert to a commit you could do git reset --hard <commit sha1> or instead of sha1 use HEAD~3 for the third commit from the current one.
Then recommit your changes.
If you're afraid of losing the changes you made, you could make a revese commit, making a commit to go back to a certain commit, and then recommit you changes one by one, reverse commit, then change directory, then commit, and so on.
git revert HEAD~3
change directory.
git commit -a -f "directory fix1"
git revert HEAD~2
change directory.
git commit -a -f "directory fix2"
git revert HEAD~1
change directory.
git commit -a -f "directory fix3"


text:
Q: Как передать name и из JSON в JS объект? Имею такую структуру JSON
[
  { "name": "foo",
    "status": "success" }, {
    "name": "bar",
    "status": "success"}, {
    "name": "biz",
    "status": "success"
  }
]

Нужно выбрать все значения полей name.
Заранее спасибо.

A:

var data = [
  { "name": "foo", "status": "success" },
  { "name": "bar", "status": "success" },
  { "name": "biz", "status": "success" }
];

var res = data.map(item => { return { name: item.name }; });
console.log(JSON.stringify(res));


text:
Q: SKShapeNode stroke not drawing in Swift I have this code:
    self.shapeNode = SKShapeNode(rect: CGRect(origin: CGPointMake(-0.5*size.width, -0.5*size.height), size: size))
    self.shapeNode.fillColor = UIColor.lightBlueColor()
    self.shapeNode.strokeColor = UIColor.brownColor()

The shapeNode appears and its fill color is drawn, though its stroke isn't. Back in iOS 7 in Obj-C, the same code works to draw the stroke.

A: Indeed, this turned out to be just a bug in the simulator. Yesterday, I installed the public version of iOS 8 on an iPad, ran my game on it and the strokes appeared. Apple should provide a fix for this soon, though.


text:
Q: mysql adding /dropping indexes and foreign key in one statement I have the following code:
alter table a
add index a_idx1(a1,b1,c1),
add index a_idx2(d1),
add index b_idx(d3),
add constraint fk_1 foreign key(f1) references b(f2) on update restrict on delete restrict,
drop primary key,
add primary key(e2)

I initially had done it in separate steps, but to avoid locking issues etc, I did it in one, but it tends to sometimes degrade performance and weirdly sometimes bring down the database.
Is there anything in this statement that might do something to the db?


text:
Q: CSS background changing color - gradients This is my code
-webkit-animation: AnimationName 30s ease infinite;
-moz-animation: AnimationName 30s ease infinite;
animation: AnimationName 30s ease infinite;

@-webkit-keyframes AnimationName {
    0%{background-position:0% 50%}
    50%{background-position:100% 50%}
    100%{background-position:0% 50%}
}
@-moz-keyframes AnimationName {
    0%{background-position:0% 50%}
    50%{background-position:100% 50%}
    100%{background-position:0% 50%}
}
@keyframes AnimationName {
    0%{background-position:0% 50%}
    50%{background-position:100% 50%}
    100%{background-position:0% 50%}
}

So thats just basically a color changing background.
Whenever i run it on my html like this...
#navBar
{
font-family: "Century Gothic";
-webkit-animation: AnimationName 30s ease infinite;
-moz-animation: AnimationName 30s ease infinite;
animation: AnimationName 30s ease infinite;

@-webkit-keyframes AnimationName {
0%{background-position:0% 50%}
50%{background-position:100% 50%}
100%{background-position:0% 50%}
}
@-moz-keyframes AnimationName {
0%{background-position:0% 50%}
50%{background-position:100% 50%}
100%{background-position:0% 50%}
}
@keyframes AnimationName {
0%{background-position:0% 50%}
50%{background-position:100% 50%}
100%{background-position:0% 50%}
}
}

I want it so that the background changes the color, but that doesnt happen. I think i have to add a background tag? Can someone make a codepen or something to make it work, i tried experimenting background tags and got nowhere.
Basically i want an animated navigation bar with the code (1st section).
Thank you very much.
If possible please only CSS and HTML! (Also make it simple too :D)

A: Your CSS is malformed, the keyframes goes outside of the selector like below. I'm unsure of what colors you want to change to but how keyframes works, you want to describe the state of the element at that moment... otherwise its just like css (also only syntax you need left is the -webkit-, unless you plan on supporting firefox back to v ~30 or so. So what the below says is: at 0 percent, move the background position 50% to the right at halfway through the animation you move down all the way and then at the last moment, move back to the original position it started off at
#navBar {
    font-family: "Century Gothic";
    -webkit-animation: AnimationName 30s ease infinite;
    -moz-animation: AnimationName 30s ease infinite;
    animation: AnimationName 30s ease infinite;
}

@-webkit-keyframes AnimationName {
   0%{background-position:0% 50%}
   50%{background-position:100% 50%}
   100%{background-position:0% 50%}
}
@-moz-keyframes AnimationName {
   0%{background-position:0% 50%}
   50%{background-position:100% 50%}
   100%{background-position:0% 50%}
}
@keyframes AnimationName {
   0%{background-position:0% 50%}
   50%{background-position:100% 50%}
  100%{background-position:0% 50%}
}

with html

A: correct your syntax as @Deamedaor said
use background-color instead of background-position.
to try https://jsfiddle.net/vkbdtc47/
#navBar {
    font-family: "Century Gothic";
    -webkit-animation: AnimationName 30s ease infinite;
    -moz-animation: AnimationName 30s ease infinite;
    animation: AnimationName 30s ease infinite;
    background-color: #fff;
}
@-webkit-keyframes AnimationName {
   0%{background-color: #fff}
   50%{background-color:#f00}
   100%{background-color: #fff}
}
@-moz-keyframes AnimationName {
   0%{background-color: #fff}
   50%{background-color:#f00}
   100%{background-color: #fff}
}
@keyframes AnimationName {
   0%{background-color: #fff}
   50%{background-color:#f00}
  100%{background-color: #fff}
}


text:
Q: The extension of smooth function If $U$ is a bounded domain in $\mathbb R^n$ whose boundary is smooth, and $f$ is a smooth function on $U$ whose partial derivatives of all orders have a continuous extensions to $\bar U$. For an arbitrary domain $V \supseteq \bar U$, is there a smooth function $\tilde f$ on $V$ extending $f$?

A: We can take $V=\mathbb R^n$ without losing anything. The answer is yes, but this is nontrivial and I'm not going to prove it here. Here are some sources:
1) Short paper by Seeley (1964) covers the case of half-space. If you are interested in local matters, then straighten out a piece of $\partial U$ and apply this reflection-based extension.
http://www.ams.org/journals/proc/1964-015-04/S0002-9939-1964-0165392-8/home.html
2) Whitney's classic paper of 1934 treats general closed sets (!) but is not an easy reading.
http://www.ams.org/journals/tran/1934-036-01/S0002-9947-1934-1501735-3/home.html
3) In between there was a paper by M.R. Hestenes, "Extension of the range of a differentiable function" (Duke Math. J. 8, (1941) 183--192). Unfortunately, Duke is less generous with old articles than the AMS; the article is behinds a paywall.
4) A very recent 2-volume book by A. Brudnyi and Yu. Brudnyi "Methods of Geometric Analysis in Extension and Trace Problems" is an encyclopedia of extension theorems. See Chapter 2 of volume 1.


text:
Q: ERROR event: Not Found; when triggering event from another event : probot app built in nodejs I am building a GitHub app in probot and nodejs and trying to update the PR whenever a pull_request.synchronize event occurs. I know that doesn't make much sense, but the point is I want to be able to update the PR upon the occurrence of a certain event.
app.on('pull_request.synchronize', async context => {
    console.log('---------------------- on pull_request.synchronize, body of PR : ', context.payload.pull_request)
    console.log('State of PR after pull_request.synchronize event :---------------', context.payload.pull_request.state)
    await context.github.pulls.update({
      owner:context.payload.repository.owner,
      repo :context.payload.repository.name,
      pull_number :context.payload.pull_request.number,
      title:'updated Pull Request Title: Success',
      body:'updated Pull Request Body: Success',
    })

  })

I get below error every time :
    ERROR event: Not Found (id=ssjsk-dd-sdfsdfs-fsfs-fsfsfsffsd)
  HttpError: Not Found
      at response.text.then.message (C:\GitWorkspace\user\GitHubApps\github-app-name\node_modules\@octokit\request\dist-node\index.js:66:23)
      at process._tickCallback (internal/process/next_tick.js:68:7)
  --
  event: {
    "event": "pull_request.synchronize",
    "id": "2332-3131-131-31231313-1313232144142",
    "installation": 3352243,
    "repository": "user/Demo-Repo"
  }
06:24:58.460Z ERROR probot: Not Found
  HttpError: Not Found
      at response.text.then.message (C:\GitWorkspace\user\GitHubApps\github-app-name\node_modules\@octokit\request\dist-node\index.js:66:23)
      at process._tickCallback (internal/process/next_tick.js:68:7)
06:24:58.472Z  INFO http: POST / 500 - 519.93 ms (id=3424234-43242-42423478a-4242-42342342)
06:24:58.476Z ERROR probot: Internal Server Error
  Error: Internal Server Error
      at Request.callback (C:\GitWorkspace\user\GitHubApps\github-app-name\node_modules\superagent\lib\node\index.js:706:15)
      at IncomingMessage.parser (C:\GitWorkspace\user\GitHubApps\github-app-name\node_modules\superagent\lib\node\index.js:916:18)
      at IncomingMessage.emit (events.js:203:15)
      at IncomingMessage.EventEmitter.emit (domain.js:448:20)
      at endReadableNT (_stream_readable.js:1129:12)
      at process._tickCallback (internal/process/next_tick.js:63:19)

Why is it unable to get the detail out of context, when in fact the context does get printed out by my console statement and contains the pull_request details.
I am just a beginner in both probot and nodejs so I am not sure if this has anything to to do with the syntax.

A: The problem is that context.payload.repository.owner is an object, compare the example payload at https://developer.github.com/v3/activity/events/types/#webhook-payload-example-28
Try to replace it with context.payload.repository.owner.login.
Probot also provides a convenience method which returns and { owner, repo } object based on the context, and you can pass extra parameters to it
Try the following
await context.github.pulls.update(context.repo({
  pull_number: context.payload.pull_request.number,
  title:'updated Pull Request Title: Success',
  body:'updated Pull Request Body: Success',
}))


text:
Q: Alternative colloquial expressions for "I thought" When expressing how we misunderstand the others's expressions we often say "I thought ...". But, out of curiosity, I want to know are there any other expressions equivalent to the meaning of "I thought" and colloquial?

A: You can always go for - "I was under the impression".
Per dictionary.reference.com:

Thinking, assuming, or believing something, as in I was under the impression that they were coming today. This idiom often suggests
  that the idea or belief one had is mistaken. [ Mid-1800s ]


text:
Q: Switch style property on element hover using JQuery/Reactjs I made a mistake on my original question (my code was not working after I changed), so I changed this
I create some radial-element dynamically at father component, always pairs (element, element-hover)
render: function() {
    var gradientID = "gradient" + this.props.c.id;
    var gradientID_hover = gradientID +"-hover"

    return (
        <g className={this.props.c.id}>
            <defs>
                <radialGradient id={gradientID} fx="50%" fy="50%" r="65%" spreadMethod="pad">
                  <stop offset="0%"   stopColor={this.props.c.color[0]} stopOpacity="0.8"/>
                  <stop offset="100%" stopColor={this.props.c.color[1]} stopOpacity="1" />
                </radialGradient>

                <radialGradient id={gradientID_hover}   fx="50%" fy="50%" r="65%" spreadMethod="pad">
                  <stop offset="0%"   stopColor={this.props.c.color[3]} stopOpacity="0.8"/>
                  <stop offset="100%" stopColor={this.props.c.color[4]} stopOpacity="1" />
                </radialGradient>
            </defs>
        </g>
    )
}

And at son element, I use that id on path element, as following:
render: function() {
    var fillURL = "url(#"+this.props.gradientID+")";
    return (
        <g className={this.props.country.id}>
            <path stroke="#000000" fill={fillURL} d={this.props.country.path} strokeOpacity="0.25" strokeWidth="1.5"></path>
        </g>
    );
}

How can I change fill property of path on hover? I Tryed something like this:
componentDidMount: function() {
    var element = this.getDOMNode().firstChild;
    $(element).hover(function(){
        element.backup = element.style.fill;
        element.style.fill = element.backup+"-hover";

    }, function(){
        element.style.fill = element.backup;
    });
},

And did not work because that property contais whole url "url(#gradientID)" and with hover it will be
"url(#gradientID)-hover".
I know I can parse old property to new be "url(#gradientID-hover)", but I want if there are a better way to do this

A: $('yourID').hover(function(){ $('targetID').css('targetAttr','attrVal') });

Have you tried something like this?


text:
Q: What does the "-s" mean in "doxygen -s -g ini"? Any guesses?
When generating the configuration file, is there a reason to use
"doxygen -s -g ini"
instead of just
"doxygen -g ini"?

A: From the online doxygen manual:

If -s is specified the comments in the config file will be omitted. If configName is omitted 'Doxyfile' will be used as a default.


text:
Q: change the nickname of the user using id I want to change the nickname of the user using id. I tried to do it like this:
for (id in users) {
      message.guild.members.fetch(id).setNickname(users[id]["name"])
      .catch(error => { message.channel.send("ok"); })};
};

TypeError: message.guild.members.fetch(...).setNickname(users[id]["name"]) is not a function

A: Fetch returns a promise (as does setNickname which you are catching), so at the time you are calling setNickname, it hasn't finished yet.  You need to wait on it using async/await or .then.
message.guild.members.fetch(id).then(member => {
    member.setNickname(users[id]["name"])
        .catch(error => message.channel.send("ok"));
}).catch(error => message.channel.send('fetch error'));


text:
Q: Apache server on win7 cannot be accessed outside of localhost I have installed the apache-tomcat server on my local win7. The port I specified is 9999.
I can access my service by http://localhost:9999 and http://myIPAddress:9999
But I cannot access my apache server from other computers. I searched on the internet, and found I should add a firewall inbound rule in its advanced settings.

*

*Right click "Inbound Rules" on the left pane

*Choose "New Rule"

*Choose "Port"

*Under "Specific ports" enter your port number (9999)

*Continue with "Next" until the end of the wizard, naming the rule when asked.

After doing this, it still doesn't work!!
Then only method I find by far is turning off my windows firewall!
But this is not preferred since the potential security risk.
Some online post refers to httpd.conf file. But my apache-tomcat have no such kind of fire.
Could someone give me some hints?

A: If you haven't already, make sure your modem and/or router are not blocking the connection. They have built in firewalls which will block the connections if not properly configured to allow access to your computer.
You may also want to try another firewall option such as Comodo which gives much more control over what settings/connections/programs are allowed.


text:
Q: Regex for parsing SQL parameters If I have a query such as SELECT * from authors where name = @name_param, is there a regex to parse out the parameter names (specifically the "name_param")?
Thanks

A: This is tricky because params can also occur inside quoted strings.
SELECT * FROM authors WHERE name = @name_param
  AND string = 'don\'t use @name_param';

How would the regular expression know to use the first @name_param but not the second?
It's a problem that can be solved, but it's not practical to do it in a single regular expression.  I had to handle this in Zend_Db, and what I did was first strip out all quoted strings and delimited identifiers, and then you can use regular expressions on the remainder.
You can see the code, because it's open-source.
See functions _stripQuoted() and _parseParameters().
https://github.com/zendframework/zf1/blob/136735e776f520b081cd374012852cb88cef9a88/library/Zend/Db/Statement.php#L200
https://github.com/zendframework/zf1/blob/136735e776f520b081cd374012852cb88cef9a88/library/Zend/Db/Statement.php#L140

A: Given you have no quoted strings or comments with parameters in them, the required regex would be quite trivial:
@([_a-zA-Z]+)       /* match group 1 contains the name only */

I go with Bill Karwin's recommendation to be cautious, knowing that the naïve approach has its pitfalls. But if you kow the data you deal with, this regex would be all you need.


text:
Q: How can I email one of the cronjob lines to a different email address? I have the MAILTO setting set in crontab to a certain email address, eg
a@ab.com
There are about 10 entries in the cron on different lines, running at different times and I want to add an 11th line but have it sent to a different email address.
How can I do this from within the crontab?
awk 'last ~ "<cert>" && $0 ~ "</cert>" {print FILENAME; nextfile} {last=$0}' *

I have tried using an output command but it is only outputting to a file.

A: Just add a different MAILTO line preceeding your 11th line - that setting will remain in effect for all subsequent cron lines:
MAILTO='a@ab.com'
* * * * * /cmd1
# other crontab jobs here, all emailing to 'a@ab.com'
* * * * * /cmd10

MAILTO='someone_else@ab.com'
# following crontab jobs emailing to 'someone_else@ab.com'
* * * * * /cmd11


text:
Q: How do I get the route for a path, in a rails application? Given a method and path, I want to ask Rails how that request would be routed, and i want to be able to do this from console, and/or from a rake task.  I figure this should be straightforward - ActionDispatch does this for every request, and the route testing methods obviously also do it.
(Currently: Rails 3.0.x, but for the gem I'm writing I will need to be able to do this in Rails 3.0 through 4.1, at minimum, and possibly in older versions as well.)
I've been trying a few things like this:
routes = ActionDispatch::Routing::RouteSet.new
routes.recognize_path('/my/path/23/edit')

or
Rails.application.routes.recognize_path('/my/path/23/edit')

In both cases, I get back "RuntimeError: route set not finalized".
I'm diving through the ActionDispatch code working it out slowly, but if anyone knows the answer off the top of their head it would save me considerable time.  So, thank you!

A: The canonical answer is actually as given in my question:
# GET request
Rails.application.routes.recognize_path('/some/path/63')

# POST request
Rails.application.routes.recognize_path('/some/path', {:method => :post })

It looks like that wasn't working because I'd previously tried initializing RouteSet manually, which had interfered with the environment's ability to properly load the routes.  When I restarted the console session, the above commands worked fine.


text:
Q: How do I disable one of the multiple backgrounds in CSS? I am setting multiple backgrounds on element and then would like to disable one of the backgrounds without repeating the other ones. Can I do that somehow?
I would like to achieve exactly the same effect as below, but without repeating B, C, D in :hover, :focus selectors.
.selector {
  background: A, B, C, D;
}

.selector:hover,
.selector:focus {
  background: none, B, C, D;
}

Something like that:
.selector {
  background: A, B, C, D;
}

.selector:hover,
.selector:focus {
  background: none,;
}

A: background:none is a keyword and will override all other statements.
Unfortunately, there is no solution without repeating the declarations. you can't overide part of a multiple declaration.
Use transparent instead.
.selector {
  background: A, B, C, D;
}

.selector:hover,
.selector:focus {
  background: transparent, B, C, D;
}

or just remove the first background all together.
.selector:hover,
.selector:focus {
  background: B, C, D;
}

Advanced CSS Custom Properties (also known as CSS variables) can help here though if you define your backgrounds as "variables" you only need to change the definiton of that variable on `:hover.

:root {
  --background-a: url(http://www.placebacon.net/100/100);
}

div {
  width: 100px;
  height: 100px;
  background: var(--background-a);
}

div:hover {
  width: 100px;
  height: 100px;
  --background-a: red;
}

A: You could simply set the background-size property to 0 for the background(s) you wish to hide like so:
background-size: 0, auto, auto, auto;

Reference: https://www.designcise.com/web/tutorial/how-to-hide-one-or-more-background-images-when-using-multiple-backgrounds-in-css


text:
Q: myisam place table-lock on table even when dealing with 'select' query? i am reading the book High Performance MySQL, it mentions:
performing one query per table uses table locks more efficiently: the queries
will lock the tables invididually and relatively briefly, instead of locking
them all for a longer time.

MyISAM places table-lock even when selecting something? can someone explain a little bit?

A: MyISAM has different kinds of locks. A SELECT operation places a READ LOCK on the table. There can be multiple active read locks at any given time, as long as there are no active WRITE LOCKS. Operations that modify the table, eg. INSERT, UPDATE, DELETE or ALTER TABLE place a WRITE LOCK on the table. Write lock can only be placed on a table when there are no active read locks; If there are active read locks, MyISAM queues the write lock to be activated as soon as all active read locks are expired.
Likewise when there's an active write lock, attempting to place a read lock on a table will queue the lock (and the associated query) until write locks have expired on the table.
Ultimately this all means that:

*

*You can have any number of active read locks (also called shared locks)

*You can only have one active write lock (also called an exclusive lock)

For more information see: http://dev.mysql.com/doc/refman/5.5/en/internal-locking.html

A: reko_t provided a good answer, I will try to elaborate on it:
Yes.

*

*You can have EITHER one writer or several readers

*Except there is a special case, called concurrent inserts. This means that you can have one thread doing an insert, while one or more threads are doing select (read) queries.

*

*there are a lot of caveats doing this:

*it has to be "at the end" of the table - not in a "hole" in the middle

*Only inserts can be done concurrently (no updates, deletes)

*There is still contention on the single MyISAM key buffer. There is a single key buffer, protected by a single mutex, for the whole server. Everything which uses an index needs to take it (typically several times).

Essentially, MyISAM has poor concurrency. You can try to fake it, but it's bad whichever way you look at it. MySQL / Oracle has made no attempts to improve it recently (looking at the source code, I'm not surprised - they'd only introduce bugs).
If you have a workload with lots of "big" SELECTs which retrieve lots of rows, or are hard in some way, they may often overlap, this may seem ok. But a single row update or delete will block the whole lot of them.


text:
Q: Exploration Algorithm Massively edited this question to make it easier to understand.
Given an environment with arbitrary dimensions and arbitrary positioning of an arbitrary number of obstacles, I have an agent exploring the environment with a limited range of sight (obstacles don't block sight). It can move in the four cardinal directions of NSEW, one cell at a time, and the graph is unweighted (each step has a cost of 1). Linked below is a map representing the agent's (yellow guy) current belief of the environment at the instant of planning. Time does not pass in the simulation while the agent is planning.
http://imagizer.imageshack.us/a/img913/9274/qRsazT.jpg
What exploration algorithm can I use to maximise the cost-efficiency of utility, given that revisiting cells are allowed? Each cell holds a utility value. Ideally, I would seek to maximise the sum of utility of all cells SEEN (not visited) divided by the path length, although if that is too complex for any suitable algorithm then the number of cells seen will suffice. There is a maximum path length but it is generally in the hundreds or higher. (The actual test environments used on my agent are at least 4x bigger, although theoretically there is no upper bound on the dimensions that can be set, and the maximum path length would thus increase accordingly)
I consider BFS and DFS to be intractable, A* to be non-optimal given a lack of suitable heuristics, and Dijkstra's inappropriate in generating a single unbroken path. Is there any algorithm you can think of? Also, I need help with loop detection, as I've never done that before since allowing revisitations is my first time.
One approach I have considered is to reduce the map into a spanning tree, except that instead of defining it as a tree that connects all cells, it is defined as a tree that can see all cells. My approach would result in the following:
http://imagizer.imageshack.us/a/img910/3050/HGu40d.jpg
In the resultant tree, the agent can go from a node to any adjacent nodes that are 0-1 turn away at intersections. This is as far as my thinking has gotten right now. A solution generated using this tree may not be optimal, but it should at least be near-optimal with much fewer cells being processed by the algorithm, so if that would make the algorithm more likely to be tractable, then I guess that is an acceptable trade-off. I'm still stuck with thinking how exactly to generate a path for this however.

A: Your problem is very similar to a canonical Reinforcement Learning (RL) problem, the Grid World. I would formalize it as a standard Markov Decision Process (MDP) and use any RL algorithm to solve it.
The formalization would be:

*

*States s: your NxM discrete grid.

*Actions a: UP, DOWN, LEFT, RIGHT.

*Reward r: the value of the cells that the agent can see from the destination cell s', i.e. r(s,a,s') = sum(value(seen(s')).

*Transition function: P(s' | s, a) = 1 if s' is not out of the boundaries or a black cell, 0 otherwise.

Since you are interested in the average reward, the discount factor is 1 and you have to normalize the cumulative reward by the number of steps. You also said that each step has cost one, so you could subtract 1 to the immediate reward rat each time step, but this would not add anything since you will already average by the number of steps.
Since the problem is discrete the policy could be a simple softmax (or Gibbs) distribution.
As solving algorithm you can use Q-learning, which guarantees the optimality of the solution provided a sufficient number of samples. However, if your grid is too big (and you said that there is no limit) I would suggest policy search algorithms, like policy gradient or relative entropy (although they guarantee convergence only to local optima). You can find something about Q-learning basically everywhere on the Internet. For a recent survey on policy search I suggest this.
The cool thing about these approaches is that they encode the exploration in the policy (e.g., the temperature in a softmax policy, the variance in a Gaussian distribution) and will try to maximize the cumulative long term reward as described by your MDP. So usually you initialize your policy with a high exploration (e.g., a complete random policy) and by trial and error the algorithm will make it deterministic and converge to the optimal one (however, sometimes also a stochastic policy is optimal).
The main difference between all the RL algorithms is how they perform the update of the policy at each iteration and manage the tradeoff exploration-exploitation (how much should I explore VS how much should I exploit the information I already have).
As suggested by Demplo, you could also use Genetic Algorithms (GA), but they are usually slower and require more tuning (elitism, crossover, mutation...).
I have also tried some policy search algorithms on your problem and they seems to work well, although I initialized the grid randomly and do not know the exact optimal solution. If you provide some additional details (a test grid, the max number of steps and if the initial position is fixed or random) I can test them more precisely.


text:
Q: Detecting and Preventing Overflow I am fairly new to programming and want to understand how to detect and prevent numeric overflows in a program. I am wanting to learn how to:
1.) detect when an overflow will happen
2.) prevent it from happening and return the correct value when not overflowing and finally,
3.) how to return something to my test method to test the program.
for my add_numbers method, would it be best to run IF/ELSE statements and check for the max integer? or is there a better way to do this? To prevent the overflow would I just end the program or rely on the wraparound?
How can I use my test function to test for this?
#include <iostream>
#include <limits>

template <typename T>
T add_numbers(T const& start, T const& increment, unsigned long int const& steps)
{
    T result = start;

    for (unsigned long int i = 0; i < steps; ++i)
    {
        result += increment;
    }

    return result;
}

template <typename T>
void test_overflow()
{
    // I don't change here (start)
    const unsigned long int steps = 5;
    const T increment = std::numeric_limits<T>::max() / steps;
    const T start = 0;

    std::cout << "Overflow Test of Type = " << typeid(T).name() << std::endl;
    // I don't change the above block of code (end)

    std::cout << "\tAdding Numbers Without Overflow (" << +start << ", " << +increment << ", " << steps << ") = ";
    T result = add_numbers<T>(start, increment, steps);
    std::cout << +result << std::endl;

    std::cout << "\tAdding Numbers With Overflow (" << +start << ", " << +increment << ", " << (steps + 1) << ") = ";
    result = add_numbers<T>(start, increment, steps + 1);
    std::cout << +result << std::endl;
}

void do_overflow_tests(const std::string& star_line)
{
    std::cout << std::endl << star_line << std::endl;
    std::cout << "*** Running Overflow Tests ***" << std::endl;
    std::cout << star_line << std::endl;

    test_overflow<char>();
    test_overflow<wchar_t>();
    test_overflow<short int>();
    test_overflow<int>();
    test_overflow<long>();
    test_overflow<long long>();

    // unsigned integers
    test_overflow<unsigned char>();
    test_overflow<unsigned short int>();
    test_overflow<unsigned int>();
    test_overflow<unsigned long>();
    test_overflow<unsigned long long>();

    // real numbers
    test_overflow<float>();
    test_overflow<double>();
    test_overflow<long double>();
}

int main()
{
    const std::string star_line = std::string(50, '*');

    std::cout << "Starting Numeric Underflow / Overflow Tests!" << std::endl;

    do_overflow_tests(star_line);

    do_underflow_tests(star_line);

    std::cout << std::endl << "All Numeric Underflow / Overflow Tests Complete!" << std::endl;

    return 0;
}


text:
Q: Key column X doesn't exist in table while trying to drop X from table I need some help. I'm trying to run some migrations scripts on a NEW docker instance (the old one and local works fine). Mariadb, Innodb engine.
I have a migrations like this:
ALTER TABLE userinfo DROP COLUMN barcode

that gives me error:
StatementEnd Error Code: 1072. Key column 'barcode' doesn't exist in table
The column exist! This is my SHOW CREATE TABLE:
CREATE TABLE userinfo (
  id int(11) unsigned NOT NULL AUTO_INCREMENT,
  barcode varchar(45) NOT NULL,
  store_id int(11) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY store_id_barcode_UNIQUE (`store_id`,`barcode`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4

I tried something like ALTER TABLE userinfo ADD KEY "barcode" ("barcode") but the DROP statement still does not work.
P.S. i removed a lot of columns from the CREATE statement or this thread would be too long to read.

A: From ALTER TABLE/DROP COLUMN:

MariaDB starting with 10.2.8
Dropping a column that is part of a
multi-column UNIQUE constraint is not permitted...

First, drop the unique key in which barcode is part of and then you will be able to drop it:
ALTER TABLE userinfo DROP KEY store_id_barcode_UNIQUE;
ALTER TABLE userinfo DROP COLUMN barcode;

See the demo.


text:
Q: it is possible to detect entities from another project? Im using hibernate for establish connection with database. I found in web property for persistence.xml:
property name="hibernate.archive.autodetection" value="class"
It works fine when entities are in the same project with persistence.xml. But in my architecture i have another project for entities. I linked this two projects in my .pom file. And here is the problem. Entities are not detected by hibernate. There is any way to work around?
Technology stack of my project:
java se 8
maven
hibernate
pesistance

A: Regarding this post Is it possible to scan Entities in jar files using JPA and hibernate you need to explicitly list the entities or you scan the classpath yourself and register the entities programmatically.

A: I found a way around. Helped me jar-file tag. When I added it before properties tag then entities has been loaded. Still problem is that it need to be absolute path but, one problem is solved.


text:
Q: Node.js "Error: channel closed" on .send when child_process forked for the second time I'm having some issues whent trying to send data to a child process when it is forked for the second time.
Here's an sample code of what I'm trying to do:
var child_process = require("child_process");
var io = require("socket.io")(app); //app contains http server

var pageSocket = io.of('/somePage');

io.on("connection", function(socket){
    var child = child_process.fork('./sample.js');

    socket.on('some:event', function(){
        child.send({key: value});
    });

    child.on('message', function(data){
        //Do something
    });

    child.on('exit', function(code, signal){
        if (signal === 'SIGTERM') {
            socket.emit('page:closed');
        }
    });

    socket.on('page:close', function(){
        child.kill("SIGTERM");
    });
});

I made a really simple example because all the socket thing is working. After I call the event page:closed on the client side, my application disconnect from socket and changes page. When I Come back to that pageSocket, it connects again,the child are forked (I made an console.log on the child, just to be sure) but, when some:event are emmited and the server tries to call child.send I got the following error:
Error: closed channel

I already tried to pass SIGHUP, SIGKILL and SIGINT as signals to the .kill method and tried to close the child from itself with process.exit(0)


text:
Q: People deleting their own questions once they have an answer This has happened to me at least 3 times in the past few weeks. Basically, a user asks a question. I put some time and thought in an answer and reply to their question. I come back a bit later to see if they have commented on my answer and I don't have any notifications. Fine then, I check my list of recent answers but I can't find it in there. Perplexed, I check my browser history and retrace the question only to find that it's been deleted by the author.
I'm not sure what the purpose of this is, but perhaps someone could clear it up for me? Why do people do that? Is it because they realized what the answer was themselves? In this case, they should probably post an answer and accept it, to help other people who will encounter the same problem? Maybe from the answers they were given, they realized that the question's answer was obvious, and are ashamed of having asked it? Even in this case, I still don't think they should delete the question, but instead accept an answer and thus reward those who gave time answering their question, and maybe help others with the same problem in the future.
Am I the only one seeing this or is this a common problem? I wish I could retrace all the times this has happened to me. Is there something that can be done against this?

A: If I'm not mistaken, the OP can't delete a post unilaterally if there are any upvoted answers.  If this is becoming a widespread problem, people need to vote more.

From the FAQ:

You can't delete your question if it has more than one answer, if an answer has been upvoted, or it has been closed for less than 48 hours.


text:
Q: ASP.NET MVC Redirect Old URL to New URL I have a website with set of html files and now i am migrating to MVC application. I tried to use the code mentioned in the blog
http://www.bloggersworld.com/index.php/redirecting-old-urls-to-new-in-aspnet-mvc/
for redirecting old URLs to new MVC but getting 404 error.
Here is the RouteConfig.cs code
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.Add(new LegacyUrlRoute());

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

I created a similar class like mentioned in the blog and set the redirection as mentioned.
Sample code from LegacyUrlRoute
new RedirectRule ("oldpage.html", "", "/department/letter/july")

Here department is my controller and letter is the action and july is the ID.
If i directly give this /department/letter/july in URL it works.
I noticed the issue is with .html in URL and not with .aspx.
If i give URL as localhost/oldpage.aspx then it works correctly but if i give localhost/oldpage.html it goes to 404
Can you please advice?

A: HTML Handler has to be added in web.config which would resolve the issue related to redirecting HTML URLs.
Here is the code snippet which is almost same as the link given in the question.
RouteConfig.cs
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.Add(new LegacyUrlRoute());

        routes.MapRoute(
          name: "Default",
          url: "{controller}/{action}/{id}",
          defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
      );

    }
}

LegacyUrlRoute class:
      public class RedirectRule
        {
            public string OldUrlContains;
            public string OldUrlContainsNot;
            public string NewUrl;

            public RedirectRule(string strOldUrlContains, string
 strOldUrlContainsNot, string strNewUrl)
            {
                OldUrlContains = strOldUrlContains;
                OldUrlContainsNot = strOldUrlContainsNot;
                NewUrl = strNewUrl;
            }
        }

    public class LegacyUrlRoute : RouteBase
    {
        RedirectRule[] RedirectRules =
        {
            new RedirectRule("oldhtmlurlvalue", "", "/controller/action"),
        };

        public override RouteData GetRouteData(HttpContextBase httpContext)
        {
            const string status = "301 Moved Permanently";
            var request = httpContext.Request;
            var response = httpContext.Response;
            var legacyUrl = request.Url.ToString();
            var newUrl = "";

            foreach (RedirectRule rule in RedirectRules)
            {
                //if we don't have to check for a string that does not exist in the url
                if (rule.OldUrlContainsNot.Length == 0)
                {

                    //this does a case insensitive comparison
                    if (legacyUrl.IndexOf(rule.OldUrlContains, 0, StringComparison.CurrentCultureIgnoreCase) >= 0)
                    {
                        newUrl = rule.NewUrl;
                    }
                }
                else
                {
                    //if we don't have to check for a string that does not exist in the url
                    if ((legacyUrl.IndexOf(rule.OldUrlContains, 0, StringComparison.CurrentCultureIgnoreCase) >= 0)
                        //so that it doesn't go in infinite loop since the end part of both urls are same
                        && (!(legacyUrl.IndexOf(rule.OldUrlContainsNot, 0, StringComparison.CurrentCultureIgnoreCase) >= 0)))
                    {
                        newUrl = rule.NewUrl;
                    }
                }

                //found anything?
                if (newUrl.Length > 0)
                {
                    break;
                }

            }

            if (newUrl.Length > 0)
            {
                response.Status = status;
                response.RedirectLocation = newUrl;
                response.End();
            }

            return null;
        }

        public override VirtualPathData GetVirtualPath(RequestContext requestContext,
                    RouteValueDictionary values)
        {
            return null;
        }
    }

Web.Config
<system.webServer>
   <handlers>
      <add name="HtmlScriptHandler" path="*.html" verb="*"
         preCondition="integratedMode" type="System.Web.StaticFileHandler" />
    </handlers>
  </system.webServer>

If the above config handler is not written then when we type https://localhost/sample/page.html then the browser throws 404 error.


text:
Q: Why isn't this working in internet explorer 9? Hey, I'm having trouble with this side bar I'm trying to make. It wont look right when I look at it in interent explorer.
Heres a link, check it out in chrome of firefox then look at it in IE so you can see what I'm talking about. http://sickassvideos.com/player.php?id=1
Here is the code that creates those side bar boxes:

What we're about...

Our mission is to provide you with a continous and reliable stream of sick ass videos.

                        <fb:like-box href="http://www.facebook.com/pages/SickAssVideoscom/123296977742117" width="292" show_faces="false" stream="false" header="true"></fb:like-box>

Coming soon!

iPad and iPhone app

Here is the style for id="social"
#content div#sidebar {
float: right;
}
#content div#social {
    float: right;
    width: 250px;
    height:;
    padding: 10px 10px;
    margin:0 0 15px 0;
    background: #FFF url() no-repeat;
    /* DROP Shadow
    -moz-box-shadow: 3px 3px 4px #ccc;
    -webkit-box-shadow: 3px 3px 4px #ccc;
    box-shadow: 3px 3px 4px #ccc;
    */
}

Thanks for taking a look.

A: its badly coded css! but the issue for the boxes out of place is the facebook like button expanding too wide for the amount of margin your specifying.
also dont put analytics at top you put it at bottom, plus your missing a doctype
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>


text:
Q: compress uploaded images in magento Is it possible to compress the original product image on upload in magento?
Magento saves the original uploaded image in full size.
The store admin have 3MB images and 20K products.
I want to automatically resize the images to ~150K.
Thanks

A: Magento automatically re-compresses product images before displaying them on the frontend.
Due to the nature of compression techniques you cannot easily target a specific file size as it depends a lot on the amount of detail in a picture. A plain "large" (wide and tall) image can result in a smaller file than a complex "small" (narrow and short) image. First check the file sizes being served to customers and then decide if it's worth pursuing.

A: If you really have to do the resizing through the admin, you might be able to tie into the event observer for the product save and write a script to reduce the size of the original image.

A: It may be fastest to use Photoshop or some related to resize the images to the largest useful size for the store. This should be a relatively small JPG, and will largely obviate the issue. As a side benefit, uploading new images will be many times faster.


text:
Q: How i replace the content between begin{document} and end{document} How i replace the content between begin{document} and end{document}. while using my code the whole content are replaced.In below code i am using wordOffset but it's not working
on mouseUp
    put wordOffset("begin{document}",fld "MytextField") into tBegin
    put wordOffset("end{document}",fld "MytextField") into tEnd
    put the htmlText of field "MytextField" into myHtml
    --put wordOffset("begin{document}",fld "myHtml") into tBegin
    --put wordOffset("begin{document}",fld "myHtml") into tEnd
     set the caseSensitive to true
     put the field SRText into myArrayToBe
     split myArrayToBe by CR
     --enable the field "SRText"
     --put "red,RED" & CR & "green,GREEN" & CR & "blue,BLUE" into myArrayToBe
     --split myArrayToBe by CR
     put the number of lines of (the keys of myArrayToBe) into myArraylength
     repeat with i = 1 to myArraylength
        --return i
        put  myArrayToBe[i] into y
        split y by colon
        put y[1] into searchStr
        put y[2] into replaceStr
        if searchStr is empty then
           put the  0 into m
        else
           --put (word tBegin to tEnd of fld "MytextField")
           --put replaceText(word tBegin to tEnd of fld "MytextField","searchStr","good") into word tBegin to tEnd of fld "MytextField"
           put wordOffset("begin{document}",fld "MytextField") into tBegin
           put wordOffset("end{document}",fld "MytextField") into tEnd
           --put holder into  myHtml
           --put replaceText(word tBegin to tEnd of fld "MytextField",searchStr,replaceStr)of fld "MytextField"
          replace searchStr  with  "" & searchStr & "" & replaceStr & "" in myHtml

      end if
    end repeat
    --enable me
    set the htmlText of fld "MytextField" to myHtml

end mouseUp

A: You need to use htmlText to both get and set the text, otherwise your offsets are off (e.g. if the first line of the field is bold, htmlText would give something like
foo
begin{document}

whereas just 'fld "MytextField"' would give
foo
begin{document}

so offset("begin{document}",...) of the first gives 16, while for the second it gives 5. What I'd do is something like
put the htmlText of fld "MytextField" into theHTML
put offset("begin{document}", theHTML) into tBegin
put offset("end{document}", theHTML) into tEnd
add length of "begin{document}" to tBegin
put character tBegin to tEnd of theHTML into textToChange

-- now do your search/replace on textToChange, not the field

put textToChange into character tBegin to tEnd of theHTML
set the htmlText of fld "MytextField" to theHTML

I use offset() here, which gives a character offset, but wordOffset as you had it should work, too, if you keep in mind that it gives you word numbers, so you'd have to replace word tBegin to tEnd of theHTML.


text:
Q: Get custom error message with Ajax form I'm using an ajax form with this initialization on the view:
@using (Ajax.BeginForm("EditUser", "Admin", new AjaxOptions()
{
    HttpMethod = "POST",
    OnSuccess = "AddEditSuccessul",
    OnFailure = "AddEditFailed",
    OnBegin = "HideModalEditUser"
}, new { @id = "MainForm" }))

And it works quite well. I would like to add a message to the AddEditFailed to warn the user about why the operation failed. I tried to edit the code to:
OnFailure = "AddEditFailed(message)",

And put return new HttpStatusCodeResult(code, "Custom message."); in the controller. I also adapted the JS to:
function AddEditFailed(message)
{
    swal({
        title: "Error",
        text: "Details : " + message,
        type: "error",
        showCancelButton: false,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "OK",
        closeOnConfirm: true
    });
}

But I get the error:

ReferenceError: message is not defined

Is there a way to do it without changing the whole mechanism or am I in the obligation to refactor the process?

A: The signature for the function is OnFailure(xhr, status, error).
It is strange that message is undefined. There should be your xhr request.
Oh it seems that you should change your code to
OnFailure = "AddEditFailed(xhr, status, 'Person')"
Check out this post


text:
Q: Accessing the first business day of a Month I need to know the first business day of a given month, is there some package in R containing a relevant function?

A: The timeDate package has a function isBizday that will help you here. There will be more elegant ways to convert the dateTime object to other formats, but this should at least get you started.
library(timeDate)

## Example data
dates <- as.Date("2013-01-01") + 0:364
Dates <- as.timeDate(dates)

## Extract the first business day of each month
bizDates <- dates[isBizday(Dates, holidays=holidayLONDON())]
firsts <- tapply(bizDates, months(bizDates), min)
sapply(firsts, function(X) as.character(as.Date(X)))
#            1            2            3            4            5            6
# "2013-01-02" "2013-02-01" "2013-03-01" "2013-04-01" "2013-05-01" "2013-06-03"
#            7            8            9           10           11           12
# "2013-07-01" "2013-08-01" "2013-09-03" "2013-10-01" "2013-11-01" "2013-12-02"

A: Assuming that you want first day of the month that isn't Saturday or Sunday:
businessDay<-function(month,year){
  #3 first dates of the month is sufficient
  d <- as.POSIXlt(paste(year,month,1:3,sep="-"))
  #POSIXlt object contains the info about the weekday as number 0-6 (starting Sunday)
  d[which(d$wday>0 & d$wday<6)[1]]
}

businessDay(3,2013)
[1] "2013-03-01"

Or if you want the name of the day:
businessDay<-function(month,year){
  d <- as.POSIXlt(paste(year,month,1:3,sep="-"))
  weekdays(d[which(d$wday>0 & d$wday<6)[1]])
}

businessDay(1,2013)
[1] "friday"

A: You can use isBusinessDay  from RQuantLib , which check if a day is a busniess day given a calendar. One idea is to give the first days of the month and take the min busniess day
For example here the first business day of April 2009 is :
library(RQuantLib)
dates <- seq(from=as.Date("2009-04-01"), to=as.Date("2009-04-05"), by=1)
min(dates[isBusinessDay("UnitedKingdom", dates)])
"2009-04-01"


text:
Q: Facebook graphAPI get id of friend posts with python I am using python facebook-sdk (modified example code) to get feed from my facebook wall. That means my posts and my friends' posts. My scripts works just fine until there is more then 2 friend's posts - facebook starts grouping those posts and I can no longer get that post's ID - only of the first one.
This is what I mean by "grouped posts":
fb grouped wall posts
Here is my code:
import facebook
import requests

def get_it(post):

    print(post['message'])
    print(post)

access_token = '<mytoken>'
user = 'me'
graph = facebook.GraphAPI(access_token)

posts = graph.get_connections(user, 'feed', limit=20)
print(posts)

while True:
    try:
        [get_it(post=post) for post in posts['data']]

        posts = requests.get(posts['paging']['next']).json()
    except KeyError:
        break

Now the prints give me successful results if there isn't more than 2 friend's posts and they aren't grouped.
the  dict looks like this
print(posts):
 {'paging': {'previous': 'https://graph.facebook.com/v2.5/XXX&access_token=XXX&__paging_token=XXX&__previous=1', 'next': 'https://graph.facebook.com/v2.5/XXX/feed?limit=20&access_token=XXX&__paging_token=XXX'}, 'data': [{'id': 'XXXXXX_XXXX', 'created_time': '2016-03-31T23:58:41+0000', 'message': 'test'}, {'id': 'XXX_XXX', 'created_time': '2016-03-31T23:33:43+0000', 'message': 'hehe'}]}

And everything goes fine, I can use the post IDs for the get_it method.
However, once there are more then 2 friend's posts, it gets grouped and suddenly
a new thing 'story' appears in the dict:
'data': [{'created_time': '2016-04-01T02:32:37+0000', 'story': 'XXX wrote on your Timeline.', 'id': '123_456'}, {'created_time': '2016-03-31T23:58:41+0000', 'message': 'test', 'id': '6666_6666'}

The 'story' ID works only for the LAST comment made in grouped wall posts.
Additionally, the next dict fields for some reason don't get passed in the get_it() method and print(post['message']) and print(post) return blank results.
How to solve this, so I get IDs and messages of all friends' posts on my wall as well as mine, please? I am really lost, tried everything. Thank you.

A: This was an intentional update by facebook to stop automating scripts and spamming.
It will not be rolled back unfortunately.


text:
Q: How to get elements with a unique number from a json array in PostgreSQL? I have a table bank_accounts:
    Column     |         Type          |                                Modifiers                                | Storage  | Stats target | Description
---------------+-----------------------+-------------------------------------------------------------------------+----------+--------------+-------------
 id            | integer               | not null default nextval('bank_accounts_id_seq'::regclass)              | plain    |              |
 name          | character varying(50) |                                                                         | extended |              |
 bank_accounts | jsonb                 | not null                                                                | extended |              |

And it has some JSON in the jsonb column:
 id | name  |                              bank_accounts
----+-------+--------------------------------------------------------------------------
  1 | test1 | [{"name": "acct1", "balance": -500}, {"name": "acct2", "balance": -300}]

And I am using jsonb_array_elements to get a list of the accounts for one user:
select jsonb_array_elements(bank_accounts)->>'name' as name, jsonb_array_elements(bank_accounts)->>'balance' as balance from bank_accounts;
 name  | balance
-------+---------
 acct1 | -500
 acct2 | -300

That's all great. But how do I get each row to have a unique id? I'd like to map each row to a hibernate object, but I'm having trouble doing that because I can't find a way to get each row to have a unique id.

A: Try a different, clean approach with JOIN LATERAL:
SELECT b.id, t.rn
     , t.account->>'name' AS name
     , t.account->>'balance' AS balance
FROM   bank_accounts b
LEFT   JOIN LATERAL jsonb_array_elements(b.bank_accounts)
                    WITH ORDINALITY AS t (account, rn) ON true;

If you don't care for rows with empty or null values in bank_accounts, use a simpler CROSS JOIN:
SELECT ...
FROM   bank_accounts b
     , jsonb_array_elements(b.bank_accounts) WITH ORDINALITY AS t (account, rn);

The key ingredient is WITH ORDINALITY to produce row numbers for set-returning functions on the fly. It was introduced with Postgres 9.4 - just like jsonb.
rn is unique per underlying row in bank_accounts.
To be unique across the whole result set, combine it with b.id.
About WITH ORDINALITY:

*

*PostgreSQL unnest() with element number
Related:

*

*Query for array elements inside JSON type

*How to turn a simple json(b) int array into an integer[] in PostgreSQL 9.4+


text:
Q: Jenkins JNLP build agent - HOME is not set I have a Jenkins instance running that has the kubernetes cloud plugin.  I'm trying to spin up a new pod, and simply run an echo command to test out my environment.  However, the jnlp container will fail immediately after posting the following to my logs:
Jun 28, 2022 7:33:55 AM WARNING hudson.plugins.gradle.injection.GradleBuildScanInjection inject
Error: HOME is not set
Jun 28, 2022 7:33:55 AM INFO org.csanchez.jenkins.plugins.kubernetes.KubernetesLauncher launch
Created Pod: kubernetes jenkins/jenkins-agent-h3znz
Jun 28, 2022 7:33:55 AM INFO hudson.slaves.NodeProvisioner update
jenkins-agent-h3znz provisioning successfully completed. We have now 2 computer(s)
Jun 28, 2022 7:33:56 AM INFO org.csanchez.jenkins.plugins.kubernetes.pod.retention.Reaper$TerminateAgentOnContainerTerminated lambda$onEvent$1
jenkins/jenkins-agent-h3znz Container jnlp was just terminated, so removing the corresponding Jenkins agent

The first line is the first thing that pops up when I trigger a build


text:
Q: Next.js getStaticProps not returning data I am creating a blog in Next.js and using Strapi headless CMS as backend.
I was trying to get data from the API I made from Strapi.
For fetching data I made
./client.js
export default class StrapiClient{
constructor(){}
/*API_URL = "http://localhost:1337/api/"*/
async fetchData(path){
   const url = `${process.env.API_URL}${path}`
   const res = await fetch(url)
   const posts = await res.json()

  return posts
}}

and imported it to ./components/blog.js
import StrapiClient from '../client'

const Client = new StrapiClient

export const getStaticProps = async () => {
const posts = await Client.fetchData(`articles`)

return{
  props: {
    posts,
  }
    }
};

  const Blog = ({posts}) => {

  return (

          {posts.data.map((element) => {
            return(

{element.attributes.title}

            )
          })}

  );

};

export default Blog;

but I got error
TypeError: Cannot read properties of undefined (reading 'data')

and here is the structure of data I was using
 {
      "data" : [
       "id" /*string*/
    ]

 }

A: You need to await the async function to get data from Promise
export const getStaticProps = async () => {
 const posts = await Client.fetchData(`articles`)
 return{
  props: {
    posts,
  }
 }
};

Async functions always return a promise

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

A: const posts = Client.fetchData(`articles`)
I think you need to await for the fetchData.
Edit:
I just noticed you are using getStaticPaths function instead of getStaticProps. Can you please change the name and try again?

A: From next.js documentation the getStaticPaths method is used to define a list of paths to be statically generated but to fetch data for page you need to use getStaticProps:
export async function getStaticProps() {
  const posts = await Client.fetchData(`articles`);

  return {
    props: {
      posts,
    },
  }
}

Or fetch data using getServerSideProps without use getStaticPaths:
export async function getServerSideProps() {
  const posts = await Client.fetchData(`articles`);
  return { props: { posts } }
}


text:
Q: Dynamically fetch content inside accordion from database in php When i click on one accordion button they all expand. i want to expand one accordion's data at a time when i click on it and all other collapsed at the same time.
here is my code
<?php
$i = 1;
$user = $_SESSION['auth_user']['user_id'];
$query = "SELECT * FROM task WHERE user_id = '$user' ORDER BY datetime DESC";

$query_run = mysqli_query($con, $query);
while ($res = mysqli_fetch_array($query_run))
{
?>

                                        <button class="btn btn-link btn-block text-left" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">

                                            <?php echo $i++ ?>. <?php echo $res['domain']; ?> (<?php echo $res['datetime']; ?>)

                                        </button>

                            <?php
}
?>

A: You need to use something unique in your accordion id
E.G.

    <?php
        $i = 1;
        $user = $_SESSION['auth_user']['user_id'];
        $query = "SELECT * FROM task WHERE user_id = '$user' ORDER BY datetime DESC";

        $query_run = mysqli_query($con, $query);
        while ($res = mysqli_fetch_array($query_run))
    {
    ?>

        <div class="card-header" id="headingOne<?php echo $i ?>">

                <button class="btn btn-link btn-block text-left" type="button" data-toggle="collapse" data-target="#collapseOne<?php echo $i ?>" aria-expanded="true" aria-controls="collapseOne<?php echo $i ?>">

                            <?php echo $i ?>. <?php echo $res['domain']; ?> (<?php echo $res['datetime']; ?>)

                </button>

        <div id="collapseOne<?php echo $i ?>" class="collapse" aria-labelledby="headingOne<?php echo $i ?>" data-parent="#accordionExample">

    <?php $i++; } ?>

A: You are creating .accordion class with same id #accordionExample for every iteration. This is why they are not working as they should be. Considering your PHP code is working fine and $i is incrementing as it should be, the following code should work. Just FYI, notice the data-parent attribute, if you set that to the unique id of the accordion, it will only open a single accordion at a time, so you can remove that if you want the ability to have all of them open at once.
<?php
$i = 1;
$user = $_SESSION['auth_user']['user_id'];
$query = "SELECT * FROM task WHERE user_id = '$user' ORDER BY datetime DESC";
echo '
';
$query_run = mysqli_query($con, $query);
while ($res = mysqli_fetch_array($query_run))
{ ?>

    <div class="card-header" id="heading<?php echo $i; ?>" data-toggle="collapse" data-target="#collapse<?php echo $i; ?>" aria-expanded="true" aria-controls="collapse<?php echo $i; ?>">
      Some Text

    <div id="collapse<?php echo $i; ?>" class="collapse" aria-labelledby="heading<?php echo $i; ?>" data-parent="#uniqueAccordionId">

        Collapse Body Text

<?php } echo '
'; $i++; ?>