text:
Q: Data only correctly updates when step through Currently when I run the application the recycler view shows data when logged in. When the application is recompiled and run again but logged in with a different person, the previous persons data is shown.
This is even after API token calls are made. However when using the debugger and stepping through, the debugger shows the correct information and when I just run through the whole thing the application shows the correct information.
Seems like I have to step through the debugger for my application to show the correct data.
Here is the fragment.
public class allFragment extends Fragment {

private RecyclerView usersListView;

ArrayList<MessageData> arrMessageData; //= new ArrayList<MessageData>();

allRecyclerViewAdapter adapter;

SwipeRefreshLayout refreshLayout;

ProgressDialog pd;

public allFragment() {
    // Required empty public constructor
}

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

    new Load().execute(null, null, null);

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_all, container, false);

    usersListView = (RecyclerView) rootView.findViewById(R.id.allListView);

    pd = ProgressDialog.show(getActivity(), "Loading messages",
            "Loading...", true);

    //new Load().execute(null, null, null);

    refreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipeRefreshLayout);

    refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            // Your code to refresh the list here.
            // Make sure you call swipeContainer.setRefreshing(false)
            // once the network request has completed successfully.
            new Load().execute(null, null, null);
        }
    });

    return rootView;

}

class Load extends AsyncTask<Void, Void, Void> {

    ProgressDialog pd;

    private Context context;

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

        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new BasicAuthInterceptor()).addNetworkInterceptor(new StethoInterceptor()).build();

        SharedPreferences settings = PreferenceManager
                .getDefaultSharedPreferences(getActivity());
        String auth_token_string = settings.getString("token", ""/*default value*/);
        String auth_token_type = settings.getString("tokenType", "");
        String userId = settings.getString("userId", "");

        Log.i("prefs", auth_token_string);

        String url = "https://vitalengine.com/portal-api/api/user/inbox/list?userId=" +
                userId +
                "&folderId=-1&tagId=0&page=1&itemPerPage=1000&showMsgInFolder=false";

        Request request = new Request.Builder().url(url)
                .addHeader("Authorization", auth_token_type + " " + auth_token_string)
                .addHeader("user-tz", "-330")
                //.addHeader("Content-Type", "application/json")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // Log.i(TAG, "call api error");
                Log.e("Volley", e.toString());
            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) {

                try {
                    if (!response.isSuccessful())
                        throw new IOException("Unexpected code " + response);
                    final String body = response.body().string();

                    JSONObject Jobject = new JSONObject(body);

                    JSONObject sub = Jobject.getJSONObject("response");
                    JSONArray Jarray = sub.getJSONArray("inboxMsgList");

                    Log.e("Array", String.valueOf(Jarray.length()));

                    arrMessageData = new ArrayList<>();

                    int i = 0;
                    Log.i("Orginal Count ", "All: " + Jarray.length());
                    while (i < Jarray.length()) {

                        // for (i = 0; i < Jarray.length(); i++) {
                        JSONObject object = Jarray.getJSONObject(i);

                        MessageData msg3 = new MessageData();
                        msg3.setName((String) object.get("fromUser"));
                        msg3.setMessage((String) object.get("message"));
                        // added null check
                        //if (object.getString("toUser").equals(null))
                            msg3.setToUser(object.getString("toUser"));

                        msg3.setRead((Integer) object.get("isRead"));
                        msg3.setPhotoURL((String) object.get("photo"));

                        if (object.get("messageType").equals("CONVERSATION")) {
                            msg3.setType("conversation");

                            msg3.setSubject((String) object.get("subject"));
                            msg3.setId((Integer) object.get("conversationId"));

                        } else if (object.get("messageType").equals("MESSAGE")) {
                            msg3.setType("message");
                            msg3.setId((Integer) object.get("conversationId"));
                            msg3.setType((String) object.get("messageType"));

                            // added message type referral.
                        } else if (object.get("messageType").equals("REFERRALS")) {
                            msg3.setType("referral");
                            msg3.setPatient((String) object.get("patient"));
                            msg3.setId((Integer) object.get("referralId"));
                        }

                        arrMessageData.add(msg3);
                        handler.sendEmptyMessage(1);
                        i++;
                    }
                    Log.i("Expected Count ", "All: " + arrMessageData.size());

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        });
        return null;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd = new ProgressDialog(getActivity());
        pd.setMessage("loading");
        pd.show();
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        if (pd != null) {
            pd.dismiss();
        }
    }
}

@Override
public void onResume() {
    super.onResume();
    new Load().execute(null, null, null);
}

private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case 1:
                adapter = new allRecyclerViewAdapter(getActivity().getBaseContext(), arrMessageData);
                usersListView.setAdapter(adapter);
                LinearLayoutManager layoutManager
                        = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
                usersListView.setLayoutManager(layoutManager);

                refreshLayout.setRefreshing(false);

                pd.dismiss();
                break;
            default:
                Log.d("TAG", msg.what + " ? ");
                break;
        }
    }
};

}

A: Load is an AsyncTask and is running on the background thread, there is no guarantee that the AsyncTasks's doBackground() is finished by the time refreshLayout.onRefresh() is called.
Instead, update the refreshLayout in onPostExecute() method of Load task.


text:
Q: question about calling Python script from jenkins and return value to pipeline I tried to invoke a Python script that I wrote in PyCharm from a groovy pipeline. The Python code runs and finds a relevant folder name as a string which I need to get back in groovy as a variable that I can put in a path in order to run a bat file in that relevant folder.
this is my jenkins pipeline stage that calls the python script.
    stage('Most Updated Version'){
            steps{
                script{
                    echo '------------------------------- RUN PYTHON SCRIPT -------------------------------'

                    def returnedVersion = bat """${python_27} "C:\\Desktop\\updatedDirectory.py" """

                    echo '------------------------------- PYTHON SCRIPT EXECUTED -------------------------------'

                    echo '------------------------------- ADD VERSION NUMBER TO PATH -------------------------------'
                    bat "call C:\\component\\returnedVersion\\Run_program.bat"
                }
            }
  }

I tried to store the result in returnVersion variable and then put returnVersion in the relevant place in that path. this doesn't work. is this the right way to do it? or is there a better way? (I'm new to groovy)
this is my python script. do I need to return or add there any specific thing?
import os
import glob

def receiveMostUpdatedFolderNumber():
   list_of_files = glob.glob('C:\component/[0-9]*')
   latest_file = max(list_of_files, key=os.path.getmtime)
   version = latest_file[11:]
   print(version)
   return version

res = receiveMostUpdatedFolderNumber()

I thought about storing version in a .txt file and then trying to open it with jenkins. is that a good way?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Matrix variable is not undefined in javascript I'm coding a maze generator using the backtracking algorithm and p5.js library, but when I was coding a loop to set random positions in the maze, I noticed an error in javascript: "maze[(x - 2)] is undefined", but this variable is declared! I tried to read about data structures, but I couldn't find a solution for this problem.
What is happening?
Can someone help me?
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset = "utf-8">
      <title>Maze</title>
  </head>
  <body>
  <script src = "https://cdn.jsdelivr.net/npm/p5@1.4.0/lib/p5.js"></script>
<script>

var width = 720;
var height = 400;
var x, y;
var maze = Array(39).fill(Array(71).fill(0));

function setup()
{
  createCanvas(720, 400);
}

function draw()
{
  //inicial position
  x = 1;
  y = 1;
  maze[x][y] = 1;
  //grid
  strokeWeight(1);
  stroke('BLACK');
  for (x = 0; x <= 720; x += 10) line(x, 0, x, 400);
  for (y = 0; y <= 400; y += 10) line(0, y, 720, y);

  found = 0;
  do
  {
    direction = Math.floor(Math.random() * 4);
    if (direction == 0 && (y != width - 2 && maze[x][y + 2] == 0))
    {
      x2 = x;
      y2 = y;
      y += 2;
      maze[x][y] = 1;
      maze[x][y-1] = 1;
      found = 1;
    }
      else if (direction == 1 && (x > 1 && maze[x - 2][y] == 0))
      {
        x2 = x;
        y2 = y;
        x -= 2;
        maze[x][y] = 1;
        maze[x + 1][y] = 1;
        found = 1;
      }
        else if (direction == 2 && (y > 1 && maze[x][y - 2] == 0))
        {
          x2 = x;
          y2 = y;
          y -= 2;
          maze[x][y] = 1;
          maze[x][y + 1] = 1;
          found = 1;
        }
      else if (direction == 3 && (x != height - 2 && maze[x + 2][y] == 0))
      {
        x2 = x;
        y2 = y;
        x += 2;
        maze[x][y] = 1;
        maze[x - 1][y] = 1;
        found = 1;
      }
  } while (found == 0);
  noLoop();
}
</script>
</body>
</html>

A: There a few issues with this code.
Lets start with why you getting that error. The issue is that you are reusing global x and y variables in for loop that draw lines, when the loop is done, it set these variables larger than your maze array.
This brings us to second issue: maze array is smaller than width/height of the canvas.
The code is not 100% working so I don't exactly understand what it supposed to do, but it seems x and y should not exceed width/height, however you have a condition y != width - 2 which will be true even if y is bigger than width (btw, shouldn't it be height instead??)
And finally, through out the code you have multiple places with 720 and 400, instead of using width and height variables. This is a bad practice.

const width = 720;
const height = 400;
var x, y;
var maze = Array(width+1).fill(Array(height+1).fill(0));
function setup()
{
  createCanvas(width, height);
}

function draw()
{
  //inicial position
  x = 1;
  y = 1;
  maze[x][y] = 1;
  //grid
  strokeWeight(1);
  stroke('BLACK');
  for (let x = 0; x <= width; x += 10) line(x, 0, x, height);
  for (let y = 0; y <= height; y += 10) line(0, y, width, y);

  found = 0;
  do
  {
    direction = Math.floor(Math.random() * 4);
    if (direction == 0 && (y <= height - 2 && maze[x][y + 2] == 0))
    {
      x2 = x;
      y2 = y;
      y += 2;
      maze[x][y] = 1;
      maze[x][y-1] = 1;
      found = 1;
    }
      else if (direction == 1 && (x > 1 && maze[x - 2][y] == 0))
      {
        x2 = x;
        y2 = y;
        x -= 2;
        maze[x][y] = 1;
        maze[x + 1][y] = 1;
        found = 1;
      }
        else if (direction == 2 && (y > 1 && maze[x][y - 2] == 0))
        {
          x2 = x;
          y2 = y;
          y -= 2;
          maze[x][y] = 1;
          maze[x][y + 1] = 1;
          found = 1;
        }
      else if (direction == 3 && (x <= width - 2 && maze[x + 2][y] == 0))
      {
        x2 = x;
        y2 = y;
        x += 2;
        maze[x][y] = 1;
        maze[x - 1][y] = 1;
        found = 1;
      }
  } while (found == 0);
  noLoop();
}
<script src = "https://cdn.jsdelivr.net/npm/p5@1.4.0/lib/p5.js"></script>


text:
Q: Google Cloud Key Management Service to sign JSON Web Tokens First of all I tried the solution at: Using Google Cloud Key Management Service to sign JSON Web Tokens
But it doesn't work.
Creating signature:
const TimeStamp = Math.floor(new Date().getTime() / 1000)

let body = base64url(
    JSON.stringify({
        alg: 'RS256',
        typ: 'JWT'
    })
)
body += '.'
body += base64url(
    JSON.stringify({
        iss: 'some-iss',
        aud: 'some-aud',
        iat: TimeStamp,
        exp: TimeStamp + parseInt(process.env.TOKEN_EXPIRY, 10)
    })
)

const hashedMessage = crypto
                .createHash('sha256')
                .update(body)
                .digest('base64')
const digest = { sha256: hashedMessage }

const [signatureObj] = await client
    .asymmetricSign({ name, digest })
    .catch(console.error)

const signature = base64url(signatureObj.signature)
const token = `${body}.${signature}`

Then verifying:
const[publicKeyObject] = await client.getPublicKey({ name }).catch(console.error)
const publicKey = publicKeyObject.pem

const verify = crypto.createVerify('sha256')
verify.write(body)
verify.end()
verify.verify(publicKey, base64url.decode(signature), 'base64')

I'm not able to figure what is wrong with the code.

A: signatureObj.signature is a Buffer, not a String.  Sadly, the documentation is incorrect on this point.
Skipping the base64 encode/decode steps should yield the proper results (verify.verify can accept a Buffer as the signature argument).
For actually encoding the contents of the signature into your JWT, you'll want something like signatureObj.signature.toString('base64').


text:
Q: Submitting a link via iPhone -> Facebook Connect I'm trying to post links through the iPhone facebook connect without using the feed control. I want to simulate how the publish a story works on facebooks website, where I pass a link, and it returns back an image, story title, and a link. Right now I only know how to use the feed control, but I'm thinking there has to be a way to use possibly stream.Publish or showDialog, just not really sure which..
Anyone have any experience with this?

A: Use the facebook demo app.
in the SessionViewController, add this to get extended permission:
- (void)askPermission:(id)target {
  FBPermissionDialog* dialog = [[[FBPermissionDialog alloc] init] autorelease];
  dialog.delegate = self;
  dialog.permission = @"publish_stream";
  [dialog show];
}

Then you need a method to publish the stream.  They don't say exactly what data to send. But whateer it is you package it in a dictionary. Since it is a URL, a good guess would be an NSString. You can get more from the API page
I found 5 that might work:
Feed.publishActionOfUser
Feed.publishStoryToUser
Feed.publishTemplatizedAction
Feed.publishUserAction
Also there is:
Links.post
But you'll have to figure it out, depending on what you want to do. You also need to kow the key. I picked url
- (IBAction)sendURL:(id)target{

    NSMutableDictionary *args = [[[NSMutableDictionary alloc] init] autorelease];
    [args setObject:urlString forKey:@"url"];
    FBRequest *uploadPhotoRequest = [FBRequest requestWithDelegate:self];
    [uploadPhotoRequest call:@"Links.post" params:args];
}

I've left some args out, but you get the idea.  I;m not sure exactly what one you want, so you'll have to research the method calls.
Hope this helps.


text:
Q: Eclipse PDE: How to add java project's classpath to a plug-in's classpath? People,
I already searched a lot but I'm not finding my answer..
I did a eclipse plugin that writes junit test cases from source code.
By now, I'm starting to use reflection in my code, but the plugin can't find the classes in the java project being tested!
Is there a way to use the selected project classpath in my plug-in? How??
I've seen many questions like mine out there, but with no answers. Please someone help!

A: you could perhaps try to write programmatically a launch configuration that includes in the classpath both your plugin source code and the project source code.
By doing this way you should provide a valid entry point to your application.
this article explains how
Otherwise you could try to base your plugin on eclipse jdt using the Abstract Syntax Tree that jdt provides to generate the unit tests.
ref eclipsepedia


text:
Q: Change alignment of tree-boxes in Block Diagram using Forest package (or otherwise) I need to draw a tree-like diagram for a classification purpose. Getting a cue from this question, I came up with the following MWE
\documentclass{book}
\usepackage[tmargin=2in, bmargin=2in, lmargin=1.5in, rmargin=1.5in]{geometry}
\usepackage{showframe}
\usepackage[edges]{forest}
\usepackage{mathtools}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{varioref}
\usepackage{cleveref}
\usepackage{tikz}
\usetikzlibrary{arrows.meta}
\begin{document}
    \begin{enumerate}
        \item \label{usual metric on R}
        \item \label{usual metric on C}
        \item \label{usual metric on R2}
        \item \label{5}
        \item \label{6}
        \item \label{16}
        \item \label{17}
        \item \label{C_int}
        \item \label{C_sup}
        \item \label{norm}
        \item \label{extended R}
        \item \label{extended C}
        \item \label{discrete}
        \item \label{d/(1+d)}
        \item \label{product metric}
    \end{enumerate}
    \begin{figure}[h!]
        \centering
        \begin{forest}
            for tree={draw,
                where level=1{minimum height=8ex,anchor=north}{},
                align=center,
                %           font=\sffamily,
                edge+={thick, -{Stealth[]}},
                l sep'+=10pt,
                fork sep'=10pt,
            },
            forked edges,
            if level=0{
                inner xsep=0pt,
                tikz={\draw [thick] (.children first) -- (.children last);}
            }{},
            [
            \qquad Examples of metric spaces in this subsection \qquad
            [
            \Cref{usual metric on R,usual metric on C,usual metric on R2,5,6,16,17,C_int,C_sup,norm}:\\
            Normed Linear Spaces
            [
            \Cref{usual metric on R,usual metric on C,usual metric on R2,5,6}:\\
            Finite dimensional\\ vector spaces
            [\Cref{5,6}:\\ $ p $ metric and\\ \emph{sup} metric on $ \mathbb{R}^{n} $]
            [\Cref{usual metric on R,usual metric on C,usual metric on R2}:\\ usual metrics on \\ $ \mathbb{R} $\text{,} $ \mathbb{C} $ and $ \mathbb{R}^{2} $]
            ]
            [
            \Cref{16,17}:\\ Sequence spaces
            ]
            [
            \Cref{C_int,C_sup}:\\ Spaces of continuous \\ functions
            ]
            ]
            [
            \Cref{extended R,extended C}:\\ Extended set of real\\ and complex numbers
            ]
            [
            \Cref{discrete}:\\ Discrete metric
            ]
            [
            \Cref{d/(1+d),product metric}:\\ Derived metrics
            ]
            ]
        \end{forest}
        \caption{Examples of metric spaces in this subsection}
    \end{figure}
\end{document}

What I am looking for is to fit the diagram within the margin. For that, I want to left-align the boxes in the third and fourth level. Something like this:

How do I achieve this?
EDIT
To add more alternatives to achieve my goal, please consider the following options:

*

*the solution need not be using forest environment only. Any other way of giving the desired output is also welcome.

*In case it is easier, the following output also works for me as well:

Please help.

A: This is more an extended comment than a real answer. I tried to control the nodes via text width, and failed. Almost certainly I did something stupid. Just in case there is really a problem with text width, here is something that installs an equivalent style, and works.
\documentclass{book}
\usepackage[tmargin=2in, bmargin=2in, lmargin=1.5in, rmargin=1.5in]{geometry}
\usepackage{showframe}
\usepackage[edges]{forest}
\usepackage{mathtools}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
%\usepackage{varioref}
\usepackage{cleveref}
\usetikzlibrary{arrows.meta}
\begin{document}
    \begin{enumerate}
        \item \label{usual metric on R}
        \item \label{usual metric on C}
        \item \label{usual metric on R2}
        \item \label{5}
        \item \label{6}
        \item \label{16}
        \item \label{17}
        \item \label{C_int}
        \item \label{C_sup}
        \item \label{norm}
        \item \label{extended R}
        \item \label{extended C}
        \item \label{discrete}
        \item \label{d/(1+d)}
        \item \label{product metric}
    \end{enumerate}
\fbox{\begin{minipage}{5em}\centering
\Cref{usual metric on R,usual metric on C,usual metric on R2,5,6,16,17,C_int,C_sup,norm}:\\
Normed Linear Spaces
\end{minipage}}

\begin{figure}[h!]
        \centering
        \begin{forest}
            forked edges,
            for tree={draw,l sep'+=10pt,minimum height=8ex,anchor=north,
                where level=1{anchor=north,l sep+=1.5em}{},
                where level=2{fork sep=4.2em,calign=first}{fork sep=10pt},
                where level=0{}{execute at begin node={\begin{minipage}{6em}\centering},
                execute at end node={\end{minipage}}},
                %           font=\sffamily,
                edge+={thick, -{Stealth[]}},
            },
            [Examples of metric spaces in this subsection,text width=21em
            [%
            \Cref{usual metric on R,usual metric on C,usual metric on R2,5,6,16,17,C_int,C_sup,norm}:\\
            Normed Linear Spaces
            [%
            \Cref{usual metric on R,usual metric on C,usual metric on R2,5,6}:\\
            Finite dimensional\\ vector spaces
            [\Cref{5,6}:\\ $ p $ metric and\\ \emph{sup} metric on $ \mathbb{R}^{n} $]
            [\Cref{usual metric on R,usual metric on C,usual metric on R2}:\\ usual metrics on \\ $ \mathbb{R} $\text{,} $ \mathbb{C} $ and $ \mathbb{R}^{2} $]
            ]
            [%
            \Cref{16,17}:\\ Sequence spaces
            ]
            [%
            \Cref{C_int,C_sup}:\\ Spaces of continuous \\ functions
            ]
            ]
            [%
            \Cref{extended R,extended C}:\\ Extended set of real\\ and complex numbers
            ]
            [%
            \Cref{discrete}:\\ Discrete metric
            ]
            [%
            \Cref{d/(1+d),product metric}:\\ Derived metrics
            ]
            ]
        \end{forest}
        \caption{Examples of metric spaces in this subsection.}
    \end{figure}
\end{document}


text:
Q: How to create a Makefile or .pro file that runs a custom build event I currently use a small program to process Qt form (.ui) files and automatically generate classes which have a common base class and use virtual functions to access the form elements.
On windows, I run this tool as a custom build step on the ui form file. The only argument to the tool is the input filename.
To clarify, on Windows, Qt runs uic on the .ui file, creating a ui_filename.h file. I need to run my tool on that file.
How can/should I do this on linux? Ideally I'd build it into the .pro file, but I'm happy to edit the Makefile as well.
I'm not awesome at writing Makefiles so this may be very simple. I am happy to write the command manually for each ui_ or *.ui file but ideally it would happen automatically for all .ui files.

A: It is not needed to write Makefiles manually. Makefiles that call custom external tool can be generated by qmake from the project file .pro.
It is needed to create a custom target using QMAKE_EXTRA_TARGETS. Then the main target should be set as denendent on that custom target (custom target name should be added to PRE_TARGETDEPS), for example How to modify the PATH variable in Qt Creator's project file (.pro)
The tool should run after generation of the form headers, so the custom target should depend on that file customtarget1.depends = ui_mainwindow.h:
customtarget1.target = form_scanner
customtarget1.commands = tool_win_bat_or_linux_shell.sh
customtarget1.depends = ui_mainwindow.h
QMAKE_EXTRA_TARGETS += customtarget1
PRE_TARGETDEPS += form_scanner

The above qmake commands create the following Makefile rules:
# the form header depends on mainwindow.ui
ui_mainwindow.h: ..\test\mainwindow.ui
<tab>#build command...

# form scanner depends on ui_mainwindow.h
form_scanner: ui_mainwindow.h
<tab>tool_win_bat_or_linux_shell.sh

# the final target depends on form scanner
$(DESTDIR_TARGET): form_scanner ui_mainwindowm.h $(OBJECTS)

If there are many forms it is possible to create many custom targets or create one target that depends on all form files:
for (form, FORMS) {
    # autogenerated form headers are located in root of build directory
    FILE_NAME = $$basename(form)
    # prepend ui_ and replace ending .ui by .h
    FORM_HEADERS += ui_$$replace(FILE_NAME, .ui$, .h)
}

customtarget1.target = form_scanner
customtarget1.commands = tool_win_bat_or_linux_shell.sh
customtarget1.depends = $$FORM_HEADERS

QMAKE_EXTRA_TARGETS += customtarget1
PRE_TARGETDEPS += form_scanner

So, the command tool_win_bat_or_linux_shell.sh is executed only when all form headers are generated.
It is also possible to run the shell script from the project directory $$PWD and pass as command line arguments the form header file names:
customtarget1.commands = $$PWD/tool_win_bat_or_linux_shell.sh $$FORM_HEADERS

Now that shell script can run some command for each form header tool_win_bat_or_linux_shell.sh:
# for each command line argument
for file in "$@"
do
    echo "$file"
    ls -l $file
done


text:
Q: Why is a m x n matrix representation with a row of zeroes linearly independent? (in this case) Hope someone can clear up this small question for me: I had to show that a set of vectors (in my case polynomials) is linearly independent, so i calculated a system of equations with gauss elimination and came up with the augmented matrix:
$\begin{bmatrix}
1 & 0 & 0 &|0\\
0 & 1 & 0 &|0\\
0 & 0 & 1 &|0\\
0 & 0 & 0 & |0\\
\end{bmatrix}$
I can see that $x_1=x_2=x_3=0$, which shows us that the set of vectors is linearly independent. (which is the answer to the question). But, what i don't understand is that if i look at it in another way we have 3 linearly independent rows and 1 linearly dependent row (the row with zeros, so the zero vector, right?). And that must mean that the set of vectors is linearly dependent. (because, for a set of vectors to be independent, all vectors contained in the set have to be linearly independent, right?)
Can someone explain why i'm thinking wrong here? (must be i forgot something or just am not thinking clearly). Ok thanks!


text:
Q: Как получить размер вложенного массива Решил сделать сайт по всем правилам используя json, реализовываю корзину пользователя, после всех манипуляций с json получаю в конечном итоге массив следующего вида
$cart =
[
    "id_0001" => [
        1 => [
            "color"    => "#000000",
            "size"     => 92,
            "quantity" => 3
        ],
        2 => [
            "color"    => "#FFFFFF",
            "size"     => 92,
            "quantity" => 1
        ]
    ],
    "id_0002" => [
        1 => [
            "color"    => "#23684B",
            "size"     => 92,
            "quantity" => 3
        ],
        2 => [
            "color"    => "#5044C1",
            "size"     => 92,
            "quantity" => 1
        ]
    ],
    "id_0003" => [
        1 => [
            "color"    => "#06130C",
            "size"     => 92,
            "quantity" => 3
        ],
        2 => [
            "color"    => "#B83D96",
            "size"     => 92,
            "quantity" => 1
        ]
    ]
];

далее я измеряю размер массива с помощью функции count() и использую полученный размер в цикле, следующий планируемый шаг - это попытка измерить под массив, чтобы перебрать и его во вложенном цикле, проблема заключается в том что функция count() размер под массива не определяет (выдаёт ноль), как быть? Может существует какая нибудь php функция которая способна определить размер под массива? Пример моего незаконченного кода
$count_level_1 = count($cart);
$count_level_1--;

for ($i = 0; $i <= $count_level_1; $i++) {

    $count_level_2 = count($cart[$i]); //Получаю ноль

    for ($s = 0; $s <= $count_level_2; $s++) {

        //А этот цикл и вовсе не срабативает

    }

}

A: ноль получаете, потому что ключ используете $i, а у вас там какие-то id_0003.
Если вместо for будете использовать цикл foreach($cart as $entry) то count($entry) даст вам желаемый результат.
В целом если хотите получить общее число вложенных элементов, то логичным будет использование array_reduce, примерно так:
$result = array_reduce($data, $fn($acc, $v) =>  $acc + count($v), 0);

Либо что-то вроде такого
$result = array_sum(array_map('count', $data));


text:
Q: LED indicator for DC voltage I am planning to using a buck / boost converter to run a DSLR camera from my USB powerbank AND other power sources.
For that module I want to build with the buck / boost converter, I need a simple LED voltage indicator circuit, since I need to adjust the potentiometer from the converter whenever I change the source of power.
Example 1
input: 5V from regular USB powerbank
output: 8.4V to the camera coupler

Example 2
input: 9V from DIY battery pack
output: 12V to other application

What I want the circuit to do is, when I turn the potentiometer, I want a LED to light up when the output voltage is between 8.4V and 8.6V ( ready for camera ). And when it's in an other range, I want an other LED to light up.
I've heard something about a combination of resistors and z-diodes to do the trick ?
Additionally it would be perfect, if the indicator circuit is not depending on whether the output circuit is closed or not ( camera is pluged in or not ).
Simple sketch:

Pleas tell me your ideas and solutions.
EDIT
I've found this link that shows this circuit

How does that work and how do I calculate the values for the parts ? I didn't understand the text on the linked page.

A: As ox6d64, motioned, you can use a window comparator.  The trick is, what to compare to, since you have varying supply voltages.
Here I am using a LT1461 voltage reference that can handle input voltages up to 20V and  puts out 3.3V with 0.04% accuracy.  So it is like a very precise voltage regulator but lower current (50 mA).  That is still enough to drive a some LEDs besides serving as a reference.

It then uses two comparators.  The input voltage is fed into two voltage dividers; the top one yields 3.29 volts when fed an input of 8.6V:
$$\frac{6.04kΩ}{9.76kΩ + 6.04kΩ} \times 8.6V = 3.29V$$
and the bottom one yields 3.31V when fed an input of 8.4V:
$$\frac{6.49kΩ}{10kΩ + 6.49kΩ} \times 8.4V = 3.31V$$
I couldn't get exactly 3.3V with either divider since the exact resistor values weren't available.  The standard 1% resistor values are here.
So the bottom comparator will output a high when the voltage is above 8.4V, and the top comparator will output a high when the voltage is below 8.6V.  These two conditions are ANDed together using the NAND gate.  I use the latter so when it is asserted, it outputs a ground and turns on the LED.
You can modify the circuit to work with whatever other voltages you need to measure.


text:
Q: How to get multiple aggregation in a dataframe? cumsum and count columns I need a column which aggregates using the count() function and another field using the cumsum() function in a dataframe
I would like to group it only once and the cumsum should be grouped with Site almost just like the count. How can I do this?
#I get the count by grouping site and arrived
df_arrived_gby = df.groupby(['Site','Arrived']).size().reset_index(name='Count_X')

#I do the cumsum but it should be groupby Site and Arrived same as above
#How can I do this?
df_arrived_gby['Cumsum_X'] = df_arrived_gby['Count_X'].cumsum()
print(df_arrived_gby)

Data example (it is not grouped by Site, so it continues adding the others):
      Site  Arrived      Count   Cumsum
198    T  30/06/2020      146     22368
199    T  31/05/2020       76     22444
200    V  05/01/2020       77     22521
201    V  05/02/2020       57     22578

A: First you need to get the values from the Count_X column, then you can cumsum():
df_arrived_gby['Cumsum_X'] = df_arrived_gby.Count_X.values.cumsum()

Let me know if that helps

A: I was able to do it using groupby on a new dataframe column as shown below:
df_arrived_gby['Cumsum'] = df_arrived_gby.groupby(['Site'])['Count X'].apply(lambda x: x.cumsum())


text:
Q: Search for placeholder in word document I want to search for specific placeholder and replace it with text in word template using Apache POI with Java, I want something simple not to loop on all tables, rows, cells, and runs to search for each text in it.

A: Take a look at my project https://github.com/centic9/poi-mail-merge which does something similar already.
It basically retrieves an XML-representation of the word document, does the replacement and puts the result back into the document.
I.e. something like
    CTBody body = doc.getDocument().getBody();

    XmlOptions optionsOuter = new XmlOptions();
    optionsOuter.setSaveOuter();

    // read the current full Body text
    String srcString = body.xmlText();

    ... do the replacements in srcString

    XmlOptions optionsOuter = new XmlOptions();
    optionsOuter.setSaveOuter();
    String srcString = src.xmlText();
    String prefix = srcString.substring(0,srcString.indexOf(">")+1);

    final String mainPart;
    // exclude template itself in first appending
    if(first) {
        mainPart = "";
    } else {
        mainPart = srcString.substring(srcString.indexOf(">")+1,srcString.lastIndexOf("<"));
    }

    String sufix = srcString.substring( srcString.lastIndexOf("<") );
    String addPart = append.substring(append.indexOf(">") + 1, append.lastIndexOf("<"));
    CTBody makeBody = CTBody.Factory.parse(prefix+mainPart+addPart+sufix);
    src.set(makeBody);

Note that the implementation is confused if the replacement is split across multiple formatings, e.g. if part of the replacement-tag is bold, this is inherent in the way that it works.


text:
Q: Python lambda function times out on failed elasticache connection So I have a python handler like this:
redisClinet = redis.StrictRedis(host = environ['REDIS_ENDPOINT'], port=6379, db=0)

def handler(event, context):
    // some logic

    lastEvent = redisClinet.get('lastEvent')

    // rest of the logic

I have:

*

*lambda vpc properly setup to be on the same vpc as Elasticache cluster, the security group allows everyting inbound/outbound

*lambda execution role has access to all actions of all resources, including vpc, elasticache, etc.

When I run the function locally on my own machine, it properly exits quickly because Elasticache obviously refuses ip address of my machine, but the problem is that I can't even see the error message when I run it on lambda to see what's going on.
The Actual Question: So aside from the reason my lambda fails to connect to redis, how to get lambda properly log the error and quit on an error instead of waiting for 60 seconds and timing out?

A: Information provided is less.
Lambda might be timing out due to redis connection. You can increase lambda timeout(must be greater than timeout set in redis client) Or set your own connection timeout value in redis-py.
I think you can also  move Redis connection part into lambda handler and pass it around. Put a try catch and print the logs in catch.
Something like this:
def handler(event, context):
    try:
       redisClinet = redis.StrictRedis(host = environ['REDIS_ENDPOINT'], port=6379, db=0)
    except Exception as e:
        print e
    // some logic
    lastEvent = redisClinet.get('lastEvent')
    // rest of the logic


text:
Q: Why can't I include Win32 in my chef recipe? This code at the beginning of my chef recipe:
require "win32/service"
include Win32

results in the following error:
No resource or method named `include' for `Chef::Recipe "install"'

This works in ruby, why doesn't it work in a chef recipe?
Thanks!

A: Following code will work(in a recipe without the include/require),
target_service = "FreeSSHDService"
if ::Win32::Service.exists?(target_service)
 Chef::Log.info target_service + "Found!"
else
 Chef::Log.info target_service + "NOT Found!"
end
The leading :: tells it not to look in the Chef namespace.
Reason for include not working,
In normal, non-Chef Ruby, you can include other classes in your own by using the include syntax; for example, include Opscode::OpenSSL::Password. Used in a recipe, however, the recipe compiler will try to find a provider for a resource of type "include" and it will fail.


text:
Q: How to concatenate multiple json columns in panda I have a df with the following format:
id json_1 json_2 json_3
1  {a:b}  {a:c}  {c:d}
2  {a:b}  {b:c}  null
3  {a:c}  {c:d}  {a:g}

I want to create a new column which concatenates (i.e., takes union) json_1, json_2, and json_3 columns.
json_1, json_2, and json_3 are dictionary text.
Desired output:
 id json_1 json_2 json_3 final_json
 1  {a:b}  {a:c}  {c:d}   [{a:b}, {a:c}, {c:d}]
 2  {a:b}  {b:c}  null    [{a:b}, {b:c}]
 3  {a:c}  {c:d}  {a:g}   [{a:c}, {c:d}, {a:g}]

A: Depending on the type of data and additional requirements, this should do the work
df['final_json'] = df[['json_1', 'json_2', 'json_3']].apply(lambda x: set(x) - set(['null']), axis=1)

[Out]:
   id json_1 json_2 json_3             final_json
0   1  {a:b}  {a:c}  {c:d}  {{c:d}, {a:c}, {a:b}}
1   2  {a:b}  {b:c}   null         {{b:c}, {a:b}}
2   3  {a:c}  {c:d}  {a:g}  {{a:g}, {c:d}, {a:c}}

As per OP's new Edit, if the goal is just to get that desired output, assuming one is proceeding from the previous operation, then that can be achieved through various methods, such as:

*

*Using js.dumps()
import json as js

df['final_json'] = df['final_json'].apply(lambda x: js.dumps(x))

*Using list()
df['final_json'] = df['final_json'].apply(lambda x: list(x))

*Using str()
df['final_json'] = df['final_json'].apply(lambda x: str(x))

They all give the following dataframe
   id json_1 json_2 json_3                   final_json
0   1  {a:b}  {a:c}  {c:d}  ["{c:d}", "{a:c}", "{a:b}"]
1   2  {a:b}  {b:c}   null           ["{b:c}", "{a:b}"]
2   3  {a:c}  {c:d}  {a:g}  ["{a:g}", "{c:d}", "{a:c}"]

It would be a matter of selecting the approach that better fits OPs use case, noting that there might be other ways to do that.

As an alternative, here is a one liner that will give OP the same output as the updated desired output, but by starting from OP's dataframe in the question
df['final_json'] = df[['json_1', 'json_2', 'json_3']].apply(lambda x: [i for i in x if i != 'null'], axis=1)

[Out]:
   id json_1 json_2 json_3             final_json
0   1  {a:b}  {a:c}  {c:d}  [{a:b}, {a:c}, {c:d}]
1   2  {a:b}  {b:c}   null         [{a:b}, {b:c}]
2   3  {a:c}  {c:d}  {a:g}  [{a:c}, {c:d}, {a:g}]

If the columns can hold values that are NaN, one might consider either the following operation (or jezrael's answer)
df['final_json'] = df[['json_1', 'json_2', 'json_3']].apply(lambda x: [i for i in x if i != 'null' and i != np.nan], axis=1)

A: If need filter out missing values and join dictionaries use list comprehension with pd.notna:
If need filter columns with json substrings:
df['final_json'] = df.filter(like='json').apply(lambda x: [y for y in x if pd.notna(y)], axis=1)

If need filter columns by list:
df['final_json'] = df[['json_1', 'json_2', 'json_3']].apply(lambda x: [y for y in x if pd.notna(y)], axis=1)


text:
Q: Phone Number Validation MVC I am trying to use a regular expression to validate a phone number and return an error when an invalid number or phone number is submitted.
MVC Code:

Phone Number:

        @Html.TextBoxFor(model => model.PhoneNumber, new { @class = "textbox" })
        @Html.ValidationMessageFor(model => model.PhoneNumber)

C# Code:
[DataType(DataType.PhoneNumber)]
[Display(Name = "Phone Number")]
[Required(ErrorMessage = "Phone Number Required!")]
[RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$",
                   ErrorMessage = "Entered phone format is not valid.")]
public string PhoneNumber { get; set; }

However, the input box will not show a message to the user indicating that the phone number which was submitted is not valid.

A: Try for simple regular expression for Mobile No
[Required (ErrorMessage="Required")]
[RegularExpression(@"^(\d{10})$", ErrorMessage = "Wrong mobile")]
public string Mobile { get; set; }

A: Model
[Required(ErrorMessage = "You must provide a phone number")]
[Display(Name = "Home Phone")]
[DataType(DataType.PhoneNumber)]
[RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Not a valid phone number")]
public string PhoneNumber { get; set; }

View:
@Html.LabelFor(model => model.PhoneNumber)
@Html.EditorFor(model => model.PhoneNumber)
@Html.ValidationMessageFor(model => model.PhoneNumber)

A: You don't have a validator on the page. Add something like this to show the validation message.
@Html.ValidationMessageFor(model => model.PhoneNumber, "", new { @class = "text-danger" })

A: Along with the above answers
Try this for min and max length:
In Model
[StringLength(13, MinimumLength=10)]
public string MobileNo { get; set; }

In view

           @Html.TextBoxFor(m => m.MobileNo, new { @class = "form-control" , type="phone"})
           @Html.ValidationMessageFor(m => m.MobileNo,"Invalid Number")
           @Html.CheckBoxFor(m => m.IsAgreeTerms, new {@checked="checked",style="display:none" })

A: Try this:
[DataType(DataType.PhoneNumber, ErrorMessage = "Provided phone number not valid")]

A: Or you can use JQuery - just add your input field to the class "phone" and put this in your script section:
$(".phone").keyup(function () {
        $(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d)+$/, "($1)$2-$3"));

There is no error message but you can see that the phone number is not correctly formatted until you have entered all ten digits.

A: [DataType(DataType.PhoneNumber)] does not come with any validation logic out of the box.
According to the docs:

When you apply the DataTypeAttribute attribute to a data field you must do the following:

*

*Issue validation errors as appropriate.

The [Phone] Attribute inherits from [DataType] and was introduced in .NET Framework 4.5+ and is in .NET Core which does provide it's own flavor of validation logic.  So you can use like this:
[Phone()]
public string PhoneNumber { get; set; }

However, the out-of-the-box validation for Phone numbers is pretty permissive, so you might find yourself wanting to inherit from DataType and implement your own IsValid method or, as others have suggested here, use a regular expression & RegexValidator to constrain input.
Note: Use caution with Regex against unconstrained input per the best practices as .NET has made the pivot away from regular expressions in their own internal validation logic for phone numbers

A: The phone number data annotation attribute is for the data type, which is not related to the data display format. It's just a misunderstanding. Phone number means you can accept numbers and symbols used for phone numbers for this locale, but is not checking the format, length, range, or else. For display string format use the javascript to have a more dynamic user interaction, or a plugin for MVC mask, or just use a display format string properly.
If you are new to MVC programming put this code at the very end of your view file (.cshtml) and see the magic:

This format is currently used for mobile phones in Brazil. Adapt for your standard.
This will add the parenthesis and spaces to your field, which will increase the string length of your input data. If you want to save just the numbers you will have to trim out the non-numbers from the string before saving.


text:
Q: TypeScript - trouble with some advanced Type Inferrence; trying to build better types for Rematch I am currently playing around with advanced TypeScript types -- my quest is (in the mid-term) to improve the types for rematch.
So, what I did so far is:
interface ModelDefinition<TState> {
    state: TState;
    reducers: TReducers<TState>;
}
interface TReducers<TState> {
    [reducerName: string]: TReducer<TState>;
}
type TReducer<TState> = (state: TState, payload: any) => TState;

function createModel<TModelDefinition extends ModelDefinition<TModelDefinition["state"]>>(modelDefinition: TModelDefinition): void {
     // ...
}

// Now, this can be used as follows:
createModel({
    state: 42,
    reducers: {
        setValueTo21: (oldState: number, payload: any) => 21
    }
});

The system automatically checks at this point if the state matches the first parameter of each reducer; and that the reducer returns the correct state type.
Note: I am deliberately not using a simple TState generic parameter, as when the types would not match, the errors are shown not at the non-matching reducer, but at the state definition.
With the types above, I am not able to add a new property effects which is a method. It works if I use lambda syntax.
Works:
createModel({
    state: 42,
    reducers: {
        setValueTo21: (oldState: number, payload: any) => 21
    },
    effects: () => {}
});

breaks:
createModel({
    state: 42,
    reducers: {
        setValueTo21: (oldState: number, payload: any) => 21
    },
    effects() {}
});

The error message is shown at setValueTo21 and is:
Type '(oldState: number, payload: any) => number' is not assignable to type 'TReducer<unknown>'.
  Types of parameters 'oldState' and 'state' are incompatible.
    Type 'unknown' is not assignable to type 'number'. [2322]

works again:
funnily, when I extract the function definition outside of the body, no type inference error occurs:
const effects = function() {
}
createModel({
    state: 42,
    reducers: {
        setValueTo21: (oldState: number, payload: any) => 21
    },
    effects
});

Summary
This seems really weird to me. BTW - I am running the newest TypeScript version. Anybody has any hints, maybe what bug I am hitting? (to me it's hard to find even the bug in the TypeScript bug tracker which might have this issue).
Thanks,
Sebastian

A: This indeed seems like a bug (probably worth reporting), but the problem is in the way you constrain generic parameter onto itself via accessing ["state"]. You actually don't need this constraint and can use any which has a meaning of "unconstrained" and not literally "any" when used inside an extends clause. This works:
function createModel<TModel extends ModelDefinition<any>>(modelDefinition: TModel): void {
    // ...
}


text:
Q: RAID0 ; Need to restore configuration I have a Dell Poweredge workstation with Ubuntu server installed in it. Hard disks are configured with RAID0. While using the RAID controller setup (after restart), I removed one of the six hard disks, and now it says that one physical disk is offline, and that a foreign configuration is present. How do I recover it back to the previous configuration?
(Just to be clear, all that I did was to pull a disk during the RAID configuration prompt).

A: The big danger of using a RAID0 configuration is that if a disk fails (or the storage controller loses its configuration), you can say goodbye to all your data.
If you removed a drive, automatically the storage controller will mark it as foreign because a priori it doesn't know what is that disk (even if it's the same you removed just for a second).
However, nowadays RAID controllers are smart enough to import a configuration. It's important that any data weren't written to a disk at any time, though.
If at boot time you are propmpted by the RAID controller to import configuration, try to do it. That's the process where the controller identifies foreign disks and try to add them to an array. If you're not prompted, try entering the RAID controller configuration with Ctrl+R (if I remember right for PowerEdge systems).
If it doesn't work, bad luck. It's always recommendable to use a RAID-5 minimally for these cases.


text:
Q: Is there any solution to execute binary in container that mount from host? In my case , I have installed ssmtp package on my Unix based host .
Because of some reason , the best way in my situation is using ssmtp binary(under /usr/sbin) on my host to send mail (html file) in my APP container .
I attemp to mount the host directory /usr/bin into container:
docker run -v /usr/sbin:/host_sbin --name=myapp -ti -p 889:80 -p 890:5432 myimage

and try to execute ssmtp , here are some awkward tries and their results :
In my APP container and under /host_sbin
 ssmtp   --->  bash: ssmtp: command not found
./ssmtp  --->  bash: ./ssmtp: No such file or directory

So it seems that things are not simple as I think .
Could anyone have done something like this share the solution with me ?
And I'd appreciate if someone can explain me why that not work .

A: Simply mounting the binary into your container does not work as the ssmtp binary is probably not statically linked. Instead it is linked dynamically to a set of shared libraries that are present in your host system, but not in your container. You can verify this using the ldd command, whilch will print all libraries that the ssmtp binary is linked against:
> ldd /usr/sbin/ssmtp

If you wanted to use your host ssmtp binary, you would also have to mount all required shared libraries into your container (and adjust the library path and so on; I'd recommend not to).

Here's my suggestion: The important bit is probably not the ssmtp binary, but SSMTP's configuration files (depending on your distribution, but typically found in /etc/ssmtp). I'd suggest...

*

*Installing ssmtp inside your container using the image's native package manager. Do not mount the binary from the host into the container.

*Mount the hosts SSMTP configuration files into your container (using the -v /etc/ssmtp:/etc/ssmtp flag on container creation)


text:
Q: Has the post-closing grace period gone? I was writing an answer to this a moment ago and, perhaps 10 seconds before I submitted it, I saw a notification in the corner of my eye. It turns out that this notification was for the question having been closed as a dup. Well, fair enough, we shouldn't be posting on dups and, generally speaking, we can't.
But in this case it was annoying. I'd just spent my time writing a nice little post, for free, only to find a fatal block at the final hurdle.
I'm sure the "Post your Answer" button used to remain enabled and you'd still be able to submit the post, within a short grace period, to avoid this rude annoyance. But this time the "Post your Answer" button, I think, was disabled as soon as that notification came up.
What's changed?


text:
Q: html canvas shape blur filter There must be a way to do this. I have drawn a shape with the html5 canvas and I would like to blur it. As far as I know there is no native method so I assume a js library is needed. The problem is most libraries only blur images like this one for example. Is this possible?

A: For a fast blur that is almost Gaussian I'd recommend StackBlur:
http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html
Alternatively you could use this Superfast Box Blur with 2 iterations:
http://www.quasimondo.com/BoxBlurForCanvas/FastBlurDemo.html

A: The pixastic library example you've linked to should actually work with a canvas element as the first argument rather than an image.
By default the pixastic library will try to replace the node you pass in with the canvas element that it creates. To prevent it from doing so you can include an option to specify to leave the DOM node and include a callback to handle the returned data yourself. Something like this:
Pixastic.process(canvas, "blur", { leaveDOM: true }, function(img) {
    canvas.getContext('2d').drawImage(img, 0, 0);
});

Alternatively, if you don't want to depend on a library, you can implement a blur yourself using getImageData(), manipulating the returned pixel data and using putImageData() to draw the blurred image back to the canvas.
One other thing to note is that individual pixel manipulation is slow and may not work well for large images. If that's a problem, you might try scaling the image down and scaling back up for a quickly done blur like effect. Something like this:
ctx.drawImage(canvas, 0, 0, canvas.width / 2, canvas.height / 2);
ctx.drawImage(canvas, 0, 0, canvas.width / 2, canvas.height / 2, 0, 0, canvas.width, canvas.height);

A: https://github.com/nodeca/glur - it implements gaussian blur via IIR filter. See demos.

A: myContext.filter = 'blur(10px)';

The CanvasRenderingContext2D.filter property of the Canvas 2D API provides filter effects like blurring or gray-scaling. It is similar to the CSS filter property and accepts the same functions. https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/filter

it's still experimental but is supported by chrome & firefox atm.

A: You can use CSS to blur the canvas. If it's just the shape you want to blur then the shape will need to be on its own separate layer (canvas), which you could create on the fly.
Example:
canvas.style.webkitFilter = "blur(3px)";

You can un-blur the canvas again with:
canvas.style.webkitFilter = "blur(0px)";

This is probably the fastest (and simplest) way to blur a canvas – especially for mobile devices.


text:
Q: clickonce deployment Given to following default security zones

Internet Zone
Intranet Zone
Trusted Site Zone
My Computer Zone

Which security zone is appropiate to the following deployment locations?
1) web
2) web using ssl
3) password protected network share
4) cd-rom

A: *

*Internet zone (Partial Trust)

*Internet zone (Partial Trust)

*Trusted Site Zone (Partial Trust)

*My Computer Zone (Full Trust)


text:
Q: SQL error, Conversion failed when converting date and/or time from character string declare @StartDate varchar(30), @myStartDate date, @iterate int, @DaysDiff int, @NoOfDays varchar (200) , @username varchar(30), @StaffID int
select @DaysDiff = 6, @iterate =0, @StartDate = '2015-04-29', @username = 'itdsnm'
select @StaffID = StaffID from Staff where LoginName = @username
select @myStartDate = cast(@StartDate as DATE)
begin
Create Table #Temp8(Dates date,MyDay int)
    While @iterate < @DaysDiff +1
    Begin
        Insert Into #Temp8(Dates,MyDay)
        Select @myStartDate,DATEPART(dw,@myStartDate)
        Select @myStartDate = dateadd(dd,1,@myStartDate)
        IF (Select COUNT(*) from #Temp8 where Dates In(Select StartDate From Holidays Where Username = @StaffID )) >0
        Begin
            Select @NoOfDays = 'One of your days fall between a holiday already taken, please review'
            Return
        End
        Else
            Select @iterate = @iterate + 1
        End
;With Temp2(Dates,MyDay)
As
(Select Dates,MyDay from #Temp8 Where MyDay not in (1,7))

Select @NoOfDays = COUNT(*) from Temp2 Where Dates Not In (Select Date From BankHolidays)
   end

Everything works fine in the above procedure, but when it comes to the With statement, it throws me an error "Conversion failed when converting date and/or time from character string." Can Some one help me with this. Thanks in advance

A: I agree with Tanner that the schema is required to be able to assess the issue (i.e. the column datatypes).
At first glance, though it appears to me that perhaps [Date] in [BankHolidays] is some sort of string datatype and that column contains certain string values that cannot be converted to a DATE type.


text:
Q: How Do I list the oauth2 scopes of a service account using the google python sdk? I have a service account with oauth2 scopes assigned to him (from scopes list) in my Domain Wide Delegation (For example, https://www.googleapis.com/auth/admin.chrome.printers, https://www.googleapis.com/auth/admin.chrome.printers.readonly).
How would I be able to list those scopes using the python sdk / rest api with only the information about the service account (I have a CLIENT ID and the rest of the information about that service acccount)


text:
Q: Google Cloud I can't find my Audit Logs, are they deleted? I had my audit logs (firestore) on Google Cloud a month ago. I needed to check something again today and they are gone and I'm not getting any more audit logs even though they are all enabled. What can be the issue?

A: Turns out I was missing permissons, when I contacted the project owner and he gave me Logging > Logs Admin role then I was able to see the logs again.


text:
Q: Add dynamic height horizontal list-view inside vertical list in Flutter I am adding horizontal listview inside the vertical list.its not showing any content
 @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: new ListView.builder(
            itemCount: 3,
            scrollDirection: Axis.vertical,
            itemBuilder: (context, position) {
              if (position == 0) {
                return Container(
                  child: Text("First rwo"),
                );
              } else if (position == 1) {
                return Container(
                  child: Text("second  rwo"),
                );
              } else if (position == 2) {
                return Container(
                    child: ListView.builder(
                        scrollDirection: Axis.horizontal,
                        itemCount: 4,
                        shrinkWrap: true,
                        itemBuilder: (context, pos) {
                          return Text("List ");
                        }));
              }
            }));
  }

when I add the height attribute to position 2 container it works.
but I want dynamic height.
SingleChildScrollView is another option but it won't be suitable for an infinite list.

A: Switch to a Row inside a SingleChildScrollview:
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: new ListView.builder(
        itemCount: 3,
        scrollDirection: Axis.vertical,
        itemBuilder: (context, position) {
          if (position == 0) {
            return Container(
              child: Text("First rwo"),
            );
          } else if (position == 1) {
            return Container(
              child: Text("second  rwo"),
            );
          } else if (position == 2) {
            return SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Row(
                children: [Text("List"), Text("List"), Text("List"), Text("List")],
              ),
            );
          }
        },
      ),
    );
  }


text:
Q: AWS - EC2, is there application health check like ELB? [Edited]
How do I check my application(web server)'s health check in EC2?
Say, I have 2 ec2 instances, ec2-webApp1 and ec2-webApp2. Both of them are listening to port 80.
webApp1 is connected with ELB which I can use "health check" whether if the application is running or not.
http://webApp1.internal.ip/myApp:80 ==> send a Get request, and the application returns 200 OK response.
I put this URL as health check URL in ELB setting.
whereas ec2-webApp2 is not connected with ELB and I want to set up monitoring alarm so when the app is not running, I can get the notification.
In the ec2-webApp2 instance, I checked "Status Checks" tab / "Monitoring" tab -> "Create Alarm," but I couldn't find like one in ELB status check where I can configure custom URL to tell AWS how to check if myApp is running.
I wonder how other people setup application monitoring.
TIA

A: The Amazon EC2 service provides a virtual machine that can run Linux or Windows. You can then install whatever software you like on that computer. Amazon EC2 never 'knows' what you are running on an instance — it could be a web application, a database, a Bitcoin miner, etc.
The EC2 status checks merely check that the virtual machine is working, such as whether it has network access and whether it has RAM. It does not know anything about your application. So, it will detect a failure of the virtual machine, but not of your application.
Amazon Route 53 Health Checks can monitor a web page to determine the health of an application. This is primarily done to redirect traffic to an alternate server in case of failure, but can also be used to trigger an alert via Amazon CloudWatch.

A: See this link there describe How to Use Amazon CloudWatch to Monitor Application Health without EBL.
https://aws.amazon.com/blogs/security/how-to-use-amazon-cloudwatch-events-to-monitor-application-health/


text:
Q: Block does not appear when using custom type, but appears with core/template New to Magento. Trying to write a custom block and just make it show up at the most basic level. Been going crazy for two days, comparing my work to those of the other modules we are using plus research.
I think the issue lies somewhere with Magento not recognizing the block as being part of the global config. I need the block just to appear when I place it in local.xml!
At app\code\local\Csos\Spuritem\etc\config.xml:
<?xml version="1.0"?>
<config>
    <modules>
        <Csos_Spuritem>
            <version>0.1.0</version>
        </Csos_Spuritem>
    </modules>

    <global>
        <blocks>
            <spuritem>
                <class>Csos_Spuritem_Block</class>
            </spuritem>
        </blocks>
    </global>
</config>

The block definition app\code\local\Csos\Spuritem\Block\Item.php:
<?php

class Csos_Spuritem_Block_Item extends Mage_Core_Block_Abstract {

}

When I use print_r(Mage::getConfig()->getNode()->xpath('//global//blocks')); shows that my module is active:
[spuritem] => Mage_Core_Model_Config_Element Object
                (
                    [class] => Csos_Spuritem_Block
                )

In frontend\base\default\layout\local.xml,
<layout version="1.0">
    <default>
        <reference name="content">
            <block type="spuritem/item" name="spuritem.forever" template="csos/spuritem/spuritem.phtml"/>
            <block type="core/template" name="showit" template="csos/showme.phtml" />
        </reference>
    </default>
</layout>

and finally, app\design\frontend\base\default\template\csos\spuritem\spuritem.phtml

This is where my stuff will go.

In the current state, this produces nothing on the homepage. However, if in the local.xml I change
I have allowed block permissions in the back end for "spuritem/item".
<block type="spuritem/item" name="spuritem.forever" template="csos/spuritem"/>
to
<block type="core/templatem" name="spuritem.forever" template="csos/spuritem"/>
The homepage will produce the text as expected.
What am I doing wrong?

A: Change your block to extend from Mage_Core_Block_Template and not from Mage_Core_Block_Abstract. In Mage_Core_Block_Abstract::_toHtml() looks like this
/**
 * Override this method in descendants to produce html
 *
 * @return string
 */
protected function _toHtml()
{
    return '';
}

So your block is rendered but the output is empty string. Mage_Core_Block_Template has the following code which renders the template file:
/**
 * Render block HTML
 *
 * @return string
 */
protected function _toHtml()
{
    if (!$this->getTemplate()) {
        return '';
    }
    $html = $this->renderView();
    return $html;
}

Alternatively you can create _toHtml() method in your block and prepare your own code for rendering content in case default one is for some reasons not suitable.


text:
Q: Where should infrastructure services contracts live? I have UI, Application, Domain and Infrastructure Layers.
In my Infrastructure Layer take reference of Domain and Application Layer to register services interfaces of both using Ninject.
But I need in my Application Layer a service in Infrastructure Layer, then i need to reference the Infrastructure Layer in my Application Layer.
The problem is Infrastructure Layer take reference to Application Layer and when I'll reference Infrastructure Layer in Application Layer the following error is show:
A reference to 'Infrastructure' could not be added. Addind this project as a reference would cause a circular dependency.
How I solve this? Put the Ninject Configuration of Application Layer in the Application Layer? I think this is not correct, because I'll have Infrastructure implementation in my Application Layer.

A: Infrastructure services contracts should be defined in the layers that consume them (Domain and Application), but implemented in Infrastructure. Take a look at Dependency Inversion Principle and Onion Architecture. Infrastructure layer should depend on App and Domain. Your Domain and App should not depend on Infrastructure. They should depend on abstraction defined in their own terms. You may find this answer interesting. The actual implementation of this abstraction should be injected at the application startup in a so called Composition Root.
For example in your Application you can define and interface like:
ICanNotifyUserOfSuccessfullRegistration

The Infrastructure layer will reference Application and will implement this interface using SMTP or SMS classes:
class SmsNotificator : ICanNotifyUserOfSuccessfullRegistration { ... }

Later on this implementation will be injected into Application by DI container. Application will not have a dependency on Infrastructure but will still use it, hence Dependecny Inversion. I recommend reading Dependency Injection in .NET, even if you use Java or other stacks.

A: Sounds like your layers are either too tightly coupled or have the wrong boundaries. You can decouple the layers by introducing interfaces that live in their own project and can be referenced by the others.


text:
Q: Match substring with regex Is there a way to match the following:
var text = 'this is a simple text \d oh yeah';
var find = 'text 4';

I now want find to be found in text because it fills the pattern obviously ("this is a simple text 4 oh yeah")
I don't really care which language (Java or JavaScript preferred) but is this possible?

A: JS:
var someRegExp = new RegExp('text \d', 'g');
var someString = "text 4";
someRegExp.test(someString);

A: you can use this in java
"text \\d+"

you can see too demo
    String s="your string";
    Pattern pattern = Pattern.compile("text \d+");
    Matcher m = pattern.matcher(s);
    while( m.find() ) {
    System.out.println( matcher.group(0) );}


text:
Q: Is there a way to call Angular Controller function from Javascript written inside
A: (if you read my previous answer, sorry, I read your question wrong)
What I'd suggest is to use a custom event on for instance the window object. At the location where you want your controller function to be called do something like this (using jQuery for this example)
<script>
    $(window).trigger('mySuperDuperEvent');
</script>

Then in your controller, listen for the event like this:
angular.module('app').controller('myController', function($scope) {
    $(window).on('mySuperDuperEvent', eventHandler);
    $scope.$on('$destroy', function() {
        $(window).off('mySuperDuperEvent', eventHandler);
    });

    function eventHandler() {
        $scope.$apply(function() {
            // Handle event here!
        });
    }
});

Just keep the following in mind:

*

*Make sure to do your work in the eventhandler in a $scope.$apply() to make sure Angular runs a digest after it's done

*Make sure to remove the event handler when the controller is removed (by looking at the scope's $destroy event. Otherwise you'll create a slow memory leak by keeping the event handlers there forever.

A: Essentially that long piece of code is DOM manipulation code. Directives/components are the part of Angular that deals with that. I would suggest putting the code inside a directive.
Then, in order for the suggested directive/component to have access to the controller function, simply hand over a reference to it. The directive/component can just call the function whenever it needs it. The end usage would be something in your template that looks like:
<ej-ribbon onsomething="yourFunction"></ej-ribbon>

Read more about directives and components for a bit more detail.


text:
Q: Annyang in react - Best practices I'm looking to integrate speech recognition into my React project, I'll likely be seperating each feature that can be controlled by speech recognition into services of sorts but currently I'm extremely confused on how to approach this.
I'm able to get Annyang to work by placing the code in my index and running something like this:
const annyang = require('annyang');
if (annyang) {
// Let's define a command.
annyang.debug();
var commands = {
  'hello world': function() { alert('Hello'); }
};

// Add our commands to annyang
annyang.addCommands(commands);

annyang.addCallback('soundstart', function() {
  console.log('sound detected');
});

annyang.addCallback('result', function() {
  console.log('sound stopped');
});
// Start listening.
annyang.start();
}

But I'm really confused on how this code would interact with the Components I already have? I'm new to React and would love to know the best practice for something like this.
I'm thinking about running this code in its own file and maybe exporting the Module and requiring it in my components, would this be good practice or am I missing something?
If I have been unclear let me know and I'll do my best to explain

A: This really depends on what your goal is.
A good practice would be to put all your Annyang commands in the top level component (e.g. <App/>) and set the state (or dispatch actions) when a voice command is executed. Here's a very basic example of that, without any flux implementation or many components:

class App extends React.Component {
  constructor() {
    super();
    this.state = { hello: false };
  }
  componentDidMount() {
    if (annyang) {
      // Let's define a command.
      var commands = {
        'hello': () => this.setState({ hello: true })
      };

      // Add our commands to annyang
      annyang.addCommands(commands);

      // Start listening.
      annyang.start();
    }
  }
  render() {
    return this.state.hello ? <SaidHello /> : <Welcome />;
  }

}

class Welcome extends React.Component {
  render() {
    return
Say "hello"!
;
  }
}

class SaidHello extends React.Component {
  render() {
    return
Well, hello! How are you?
;
  }
}

ReactDOM.render(<App/>, document.getElementById('View'));

Remember to allow microphone access in your browser, or otherwise it won't work. If this example doesn't work on StackOverflow, check it out on JSBin.

A: If you want to use this library
useEffect(() => {
if (annyang) {
var commands = {
 "Hello": function,
 "Bye": function,
 "Let's have ours": function,
 "Turn on the nursery": function,
 "Who are you": function,
 "What can you do": function,
 "What are you written on": function,
 "Come on fresh": function,
"Raspberry Lada": function
 "The heat has gone": function
"Open": () => function(true),
"Close": () => function(false)
}


text:
Q: Testing the router for invalid routes I want to test all twig files, and controllers--basically everything that uses the Router to test the helper functions for invalid route calls.
Things such as {{ path('fails_right_here') }} and $controller->generateUrl('nope_again');
You could say that this belongs to the functional tests, which i got--but.. it doesnt make sense to write scenarios for every single link thats out there. It makes more sense to write one scenario that leads to editing a article for example, and all the other 10+ routes that lead to this same scenario to be automatically validated. Or else i need to write 100's of tests for something silly :)
Any way to do this currently?

A: You don't need to test all the paths like that. Simply trying to render a link to a broken path in Twig will trigger an error, so you're already testing in just crawling any page that does that.


text:
Q: Why my login form in python is not working properly? I have a problem with a Login Form. I used Flask and Bcrypt.
When i try to login, with a user and password, the login page is not returning anything, i stay in the same login page, the only difference is the url returns this:
http://127.0.0.1:5000/?csrf_token=IjgwZTRhZmI4NWM2MTExNTdiM2I1NmM2YTYzZjIxZTdhMmI4M2JkZTgi.YYwLuQ.bYG6VKjMZ65p4i86S9-U23L9c_A&username=alexcar&password=1234Ab&submit=Login

This is the login form def:
@app.route('/', methods=['GET','POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user:
            if bcrypt.check_password_hash(user.password, form.password.data):
                login_user(user)
                return redirect(url_for('admin'))
    return render_template('login.html', form=form)

When the user is authenticated returns the page admin, in Def admin is:
@app.route('/admin', methods=['GET','POST'])
@login_required
def admin():
    return render_template('admin.html')

On Login.html form is:

      <form action="" method="post">
      {{ form.hidden_tag() }}
      {{ form.username }}

     {{ form.password }}
    {{ form.submit }}
      </form>

The register form is working well but the login page not.

A: The problem lies in your return statement after signing in.
Note: The url_for takes in the name of the route function (def admin) not (def .admin)
return redirect(url_for('.admin'))

should be:
return redirect(url_for('admin'))


text:
Q: How do I eliminate the black border on a georeferenced map layer? I have geo-referenced several scanned maps.  Theses are placed side by side on separate layers in QGIS. They overlay other older maps of the same areas. Georeferencing caused the maps to have black borders.  How can I change these black borders to transparent, or eliminate them, so that the underlying maps' data shows through the gaps in detail between the maps? Here is a screen shot:

A: Go to Layer Properties. In the Transparency tab, set the transparency of your borders to 0, which should make the border transparent. You can either add values manually (type them in) or add values from the map using the color picker (click on black border of your raster). As @Zoltan notes, however, this may cause some loss of black pixels in your raster. For future georeferencing, you can do as Zoltan suggests and use 0 for transparency.
Are these tif files? What version of QGIS are you using?

A: There are three options :

*

*The first one is create a mask then use it in gdalwarp to cut it or
add an alpha mask to your raster

*The third one is far more complicated. It consists in
updating the raster border values to a certains value X the use this
value as a nodata value with gdal utilities.

A: Thanks to all for advice. I have now found a simple workaround for this problem that will eliminate the black borders between adjacent maps and restore the detail lost in the black borders:  Make georeferenced rasters as usual, but leave the "Transparency/"No Data Value" box "checked".  This will leave lots of drop out in the map detail.  Then create a duplicate layer, but this time "uncheck" the "No Data Value Box".  Do this for all the adjacent map layers. Group the Unchecked layers together below the grouped checked layers.  The Unchecked layers will fill in the missing drop out data from the checked layers and the Checked layers will prevent the black borders from showing through.  There is no apparent loss of quality in the finished result.

A: Are these GeoTIFFs or normal tiffs with a .tfw file?  I usually use GIMP to do extensive editing on images after georeferencing them.  This works no problem if you:

*

*have a world file (.tfw)... I'm not sure if GIMP will retain the geotiff header information when you export the edited image.

*DO NOT crop the image... the .tfw file needs the size/extent of the image to remain the same to retain the correct georeferencing information.

But if those two things are under control, using GIMP to edit scanned and georeferenced maps is exceptionally useful.

A: Go to Properties on the raster image; go to the transparency tab; where it says "Transparency band" add bands red, green, and blue with a 100% transparency on them and then click apply.


text:
Q: Accessing ActionScript3 Nested Movie Clips from Class I'm trying to write a very simple/minimal custom video player in Flash CS3
I have a .fla file with 2 MovieClips in my library, Player and PlayButton.  The PlayButton movieclip is found on the first frame inside the Player movieclip.  Player is exported to actionscript and linked to a Player.as class which dynamically creates a video object.
My document class is MPlayer.as and it adds an instance of Player to the stage. This works well, and the video will play automatically.  However, the PlayButton movieclip that is inside my library item Player does not show up...and I have no idea how to access it or get it to show.  it is not in the same position as the video, so it shouldn't be under it...I tried addChild(playbutton_instance_name) from Player.as but I get errors.  The Player movieclip is exported for actionscript, but the PlayButton movieclip is not since it's inside Player.
Am I setting this up correctly?

A: Sounds about right. If it's in your Player MovieClip, it will be exported inside of that. Are you sure it's in the Player clip? You can access it like you would a variable of your Player.as class, i.e. if the PlayButton has an instance name of "playBtn" you could (in the constructor function) try
public function Play()
{
    trace(this.playBtn);
}

And if the clip is in the class properly, it should trace something like [PlayButton]. If you want, post your code in your question or I can take a look at your files if you like.


text:
Q: Why **should** I have CORS issues when requesting a localhost source from browser extensions/plugins? I have recently experienced an issue when using the ElasticVue Chrome browser extension.
I configured the extension to connect to http://localhost:9200/, where my local Elasticsearch server is running. When I connect to the address directly from the browser address bar, it works as expected, there is a response 200 with correct data. However when I try to connect to the very same address from the extension in the very same browser, I get CORS issues.
See https://github.com/cars10/elasticvue/issues/14.
The working "solution" is to configure the Elasticsearch server so it allows CORS:
  elasticsearch:
    container_name: elastic
    image: elasticsearch:7.16.2
    environment:
      ...
      - http.cors.enabled=true
      - http.cors.allow-origin=/.*/
      - http.cors.allow-headers=X-Requested-With,Content-Type,Content-Length,Authorization
    ports:
      - "9200:9200"
    ...

My question
Why do the browsers treat the requests from plugins as not coming from localhost and thus force you to hack the server configuration with extra stuff? Is there any deeper reason behind, or is it just a logical error? When I request the same page directly from the browser, there is no CORS issue. Why should there suddenly be a CORS error when I run the very same request from within a browser plugin?
I think I fully understand what CORS mean and why the modern browsers introduced the security feature, but I do not get how "protecting" the browser extensions from localhost should increase your security.


text:
Q: Autofit columns starting with a specific worksheet below is the formula I want to use.  I'm just not sure how to add the command to start from a specific worksheet.
Dim sh As Worksheet
For Each sh In ThisWorkbook.Worksheets
sh.Columns.AutoFit
Next sh
End Sub

A: Sure, use an Index instead:
Dim nIndex As Integer
For nIndex = 1 To ThisWorkbook.WorkSheets.Count
  ThisWorkbook.WorkSheets(nIndex).Columns.AutoFit
Next

Change the 1 to whichever one you want to start with.
Or you could check the name of the worksheet in the loop instead, and process all of them after and including that one:
Dim bFlag As Boolean ' default value is False
Dim sh As Worksheet
For Each sh In ThisWorkbook.Worksheets
  If sh.Name = "First One" Then bFlag = True
  ' once the flag is set to True, it stays True til the end
  If bFlag Then sh.Columns.AutoFit
Next


text:
Q: Looking for Bernoulli Equation that would describe how a hair drier, pointed nozzle up, could keep a ping pong ball suspended in mid-air I'm trying to find a specific equation from Bernoulli and the type of math required to work with/explain it. It's from fluid dynamics. The fluid is air and the equation(s) would describe how a hair drier, pointed nozzle up, could keep a ping pong ball suspended in mid-air.
Bernoulli wrote a lot of great stuff, however, since I lack an engineering background, I believe I have found only equations (and other work) that are not applicable.
Does someone recall the name of this equation and the type of math required to solve it?


text:
Q: Project Euler number 45 From Project Euler, problem 45:

Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
Triangle T_(n)=n(n+1)/2 1, 3, 6, 10, 15, ...
Pentagonal P_(n)=n(3n−1)/2 1, 5, 12, 22, 35, ...
Hexagonal H_(n)=n(2n−1) 1, 6, 15, 28, 45, ...
It can be verified that T_(285) = P_(165) = H_(143) = 40755.
Find the next triangle number that is also pentagonal and hexagonal.

Here's the question.
It's pretty simple and straightforward, but the thing is, my program runs into a glitch, the moment the value of the triangle number exceeds the maximum value that you can have in int data type. I've tried searching for the net for other data types but no success.
Code
     #include<stdio.h>
     int main(void)
     {
        int i,j,t,h,p,k;
        int n=10000;
        for(i=0;i<n;i++)
        {
            t=(i*(i+1))/2;
            for(j=0;j<n;j++)
            {
                h=j*(2*j-1);
                if(h>t)
                break;
                if(h==t)
                {
                    //printf("%d %d\n",h,t);
                    for(k=0;k<n;k++)
                    {
                        p=(k*(3*k-1))/2;
                        if(p>h)
                        break;
                        if(p==h)
                        {
                            printf("%d %d\n",p,i);
                            break;
                        }
                    }
                }

            }
        }
        printf("done\n");
        return(0);
     }

A: Try unsigned long long. It should work.


text:
Q: How to get data out of JQuery.post function I'm kind of new at JS but I can't believe I've been unable to figure this out...
myerr is defined globally.
I set myerr=to the returned value from the post.
Once I get outside the function it looses it's value.
myerr="";
$.post("/rpc/validate_song_entry", {'title':$('#title').val()}, function(data){
  alert(data.title); //----> Alerts expected result.
  myerr=data.title;
  alert(myerr); //-----> Alerts expected result.
}, "json");
alert(myerr); //-------> Nothing. Blank dialog.

It seems to me it's a variable scope issue but I can't see how...
Edit:
I posted this below but don't know how to delete it...
I now understand that the post is done asynchronously. This makes sense. What does not make sense is that the alerts pop up in the order you see. I would expect the last alert (blank one) to appear first. It does not. It appears last.
I would expect the alerts inside the post function to appear last. Can anyone explain this?

A: you neesd to use jQuery.ajax  and you need to set async :false
because your $.post is a asynchronous request , the functions after an asynchronous request not waiting for the asynchronous function to complete . that ' s why your alert prints with nothing , because it executes before the $.post complete . so you need to make the request synchronize , then after your function executes the alert will run
myerr="";

    $.ajax({
          url:  "/rpc/validate_song_entry",
          type: "POST",
          data: {'title':$('#title').val()},
          async:false,
          success: function(data){
             myerr=data.title;
          }
       }
    );

alert(myerr);

A: It is because the post is done asynchronously. You will have to use $.ajax for your issue and set it to to asynchronous.
//edit: Also have a look at that: Using $.post within a javascript function, cannot assign value to a variable?

A: function inside $.post(...) executes AFTER as it's done asynchronously. Your alert(myerr) executes right away before myerr was set.


text:
Q: How to delete matching rows in two tables in ms access? Here is my sql code in ms access:
DELETE Table1.*
FROM Table1
INNER JOIN Table2 ON Table1.Field1  = Table2.Field1

I want to notice here that Table1 has many columns but Table2 just one column.
I want to delete all rows in Table1 where Table1.Field1 = Table2.Field1.
But when I execute the code I get this error: Could not delete from specified tables.
However if I use SELECT instead of DELETE it works fine for displaying rows:
SELECT Table1.*
FROM Table1
INNER JOIN Table2 ON Table1.Field1  = Table2.Field1

But I would like to DELETE these rows.

A: Consider a subquery. DELETE queries in MS Access should have the delete set of rows as the full, standalone result set. In your attempt the result set is two tables even though you only view the first with SELECT clause:
DELETE Table1.*
FROM Table1
WHERE Field1 IN (SELECT Field1 FROM Table2)

And aligning to ANSI, the asterisk is not needed:
DELETE FROM Table1
WHERE Field1 IN (SELECT Field1 FROM Table2)

A: I would select select the rows ids of the rows into a helper table.
Then
delete from Table1 where table1.rowid = helpertable.rowid;

then
delete from Table2 where table2.rowid = helpertable.rowid;

Then
drop helpertable;

A: Access has weird issues when joining fields in action queries.
Try the following to avoid the join:
DELETE *
FROM Table1
WHERE DCount('Field1', 'Table2', 'Field1 = "' & Field1 & '"') <> 0


text:
Q: How to parse html and access chinese strings? This is my proxy.php file:

$url = urldecode($_GET['url']);
$url = 'http://' . str_replace('http://', '', $url);
echo file_get_contents($url);

And this is my reader.js file:
    var site = 'http://wanteddomain.com/index.aspx?lang=34&team1=0&team2=0&next_turn=1'

    var url = 'http://localhost/mydomain.pl/admin/proxy.php?url=' + encodeURIComponent(site)

    $.ajax({
        url      : url,
        type     : 'GET',
        contentType: "text/html;charset=utf-8",
        dataType : 'html'
    }).done(function(res) {

        //when I access special dom element, I have for example æ³°æå°å¡ instead of 广告
    });

What to do to have chinese characters?


text:
Q: What is the best way to synchronize a Timeline clock in JavaFX? I am trying to display a synchronized clock in my Java FX GUI with the function given below.
This also includes a timer function which runs if Timer=true
private Calendar cal;
private int minute;
private int hour;
private int second;
private String am_pm;

private boolean Timer;
private Integer tseconds;
private void startClock() {
    Timeline clock = new Timeline(new KeyFrame(Duration.millis(Calendar.getInstance().get(Calendar.MILLISECOND)), new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {

            cal = Calendar.getInstance();
            second = cal.get(Calendar.SECOND);
            minute = cal.get(Calendar.MINUTE);
            hour = cal.get(Calendar.HOUR);
            am_pm = (cal.get(Calendar.AM_PM) == 0) ? "AM" : "PM";
            time.setText(String.format("%02d : %02d : %02d %s", hour, minute, second, am_pm));
            if (Timer) {
                if (tseconds == 0) {
                    Timer = false;
                    //timer.setText("Time Out");
                } else {
                    //timer.setText(tseconds.toString());
                    tseconds--;
                }
            }
        }
    }), new KeyFrame(Duration.millis(Calendar.getInstance().get(Calendar.MILLISECOND))));
    clock.setCycleCount(Animation.INDEFINITE);
    clock.play();
}

I tested this few times and found that many a times the clock updates at a variable speed.
Solved
Look for the solution below.

A: Use an AnimationTimer to listen for updates:
class MyClass extends AnimationTimer {
   private final static long INTERVAL = 1000L;
   private long nextUpdate;
   public void handle(long now) {
      if (now >= nextUpdate) {
        ....
        nextUpdate = now + INTERVAL;
   }
}

...
MyClass foo = new MyClass();
foo.start();

A: Solved the issue.
I was setting the duration as the current milliseconds instead of milliseconds remaining for the next second.
Only the first KeyFrame should have the duration (1000-current millisecond) as the KeyFrame will run for a duration which is equal to the milliseconds left in the current second.
The following KeyFrames will be running at an interval of 1 second.
private void startClock() {
    Timeline clock = new Timeline(new KeyFrame(Duration.millis(1000 - Calendar.getInstance().get(Calendar.MILLISECOND)), new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {

            cal = Calendar.getInstance();
            second = cal.get(Calendar.SECOND);
            minute = cal.get(Calendar.MINUTE);
            hour = cal.get(Calendar.HOUR);
            am_pm = (cal.get(Calendar.AM_PM) == 0) ? "AM" : "PM";
            time.setText(String.format("%02d : %02d : %02d %s", hour, minute, second, am_pm));
            if (Timer) {
                if (tseconds == 0) {
                    Timer = false;
                    //timer.setText("Time Out");
                } else {
                    //timer.setText(tseconds.toString());
                    tseconds--;
                }
            }
        }
    }), new KeyFrame(Duration.seconds(1)));
    clock.setCycleCount(Animation.INDEFINITE);
    clock.play();
}


text:
Q: iOS build with expiry date I have to distribute a iOS build with a validity period such as validity for 3 week or 1 month. Before that I have to revoke the access of that build. Is possible to do this in fabric? Or there is any other methods to do this other than Testflight?

A: Though its not clear by the question I am considering that you want to do this programatically by the virtue of the tags used in your question.
You can write code which would check the date/number of app launches till date and would show an alert message with no buttons to close it which will block the access of the user from the app. This may be frustrating but would be effective.
If you want to do this from app store then you can remove the app from sale, check more of it here.
Also there are some other options like Diawi which creates a installable link for a specific duration with free and paid versions available.


text:
Q: Assign Java syntax to Blackberry tag Programming questions tagged blackberry will normally relate to Java (since BlackBerry applications are written in Java).
Can we adjust the syntax highlighting so that blackberry questions are syntax-highlighted as Java?

A: While "old school" Blackberry OS development happens mostly in Java (you can write pure native applications as well), the new BlackBerry 10 release does not natively support Java applications (it can run Android applications however).
Blackberry 10 does not currently seem to have lots of questions (probably because the devices are still pretty new, but I suspect it to overtake the classical BlackBerry questions in volume rather quickly.

A: I think the real question is whether the blackberry tag will, or should be, reserved for legacy BlackBerry (OS 4 - 7) development.  Or, will it now be used to cover BlackBerry 10 development, too.
If it's only going to be used for legacy BB Java development (which is by far the dominant BB development model, pre-BB10), then I vote for making Java syntax highlighting automatic.  I can't tell you how often I edit BlackBerry questions just to add the <!-- language-all: lang-java --> markup, because unhighlighted code is almost unreadable, especially when sloppy posters clutter it up with a bunch of stuff that's commented out ... the code prettify function nicely identifies commented-out code.
If the tag, however, should be used for BB-10, and beyond, then Java syntax highlighting should not be activated.
Note that there is already a blackberry-10 tag, and it seems to be getting some use.
I think I would cast my vote for making Java highlighting automatic for blackberry, and a comment here by another Top-10 BlackBerry answerer, Richard, seems to agree (with the part about blackberry being for BB Java).


text:
Q: How to connect to either one of multiple elasticsearch cluster at runtime depending on request? I am currently using
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.0.RELEASE</version>
</parent>

and following dependency for elasticsearch
<dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-high-level-client</artifactId>
    </dependency>

I am connecting to single elastic cluster now, but now I need to connect to either of the multiple elasticsearch clusters. This should happen at runtime using spring cloud config. Can this be achieved and how?


text:
Q: How to execute a JavaScript file on local machine? I am having issues getting my JavaScript to run on my local machine and I am not using Node.js, I am looking for a way to run the JavaScript code with setting up a VM with a webserver etc. But if that is needed I will. Is it possible to run the JavaScript file without a webserver?

A: You can run it directly into a HTML file.
For that, create a simple html page, like the example below and put your script into  tags.
<!DOCTYPE html>

My First Heading

My first paragraph.

Put this code into any text editor and save the file as .html extension, it can be runned on any modern web browser like Chrome, Firefox or IE/Edge.
Note that the  tag pauses the page rendering till it ends the execution.
Also google jsfiddle if you need to run more complex codes.