text:
Q: Android MPChart - how to update the stackLabel? I am using MPChart and have multiple charts for different tabs and therefore when switching tabs, the stacked barchart and its label should be refreshed.
Code:
BarDataSet set1;
    if (chart_stacked.getData() != null && chart_stacked.getData().getDataSetCount() > 0)
    {
        set1 = (BarDataSet) chart_stacked.getData().getDataSetByIndex(0);
        set1.setValues(yVals1);
        chart_stacked.getData().notifyDataChanged();
        chart_stacked.notifyDataSetChanged();
    }
    else
    {
        // set1 = new BarDataSet(yVals1, "Toilet Statistics");
        set1 = new BarDataSet(yVals1, "");
        set1.setDrawIcons(false);
        set1.setColors(getColors());

        if (chart_type.equals("feed"))
        {
            set1.setStackLabels(new String[]{"A", "B"});
        }
        if (chart_type.equals("pump"))
        {
            set1.setStackLabels(new String[]{"C", "D"});
        }

        ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
        dataSets.add(set1);

        BarData data = new BarData(dataSets);
        data.setValueTextColor(Color.BLACK);

        chart_stacked.setData(data);
    }
    chart_stacked.invalidate();
    Utilities.custom_toast(Stat.this, "chart type = " + chart_type, "gone", "short");

Question:
The toast at the end shows that when pressing different tabs, the variable chart type is updated successfully. the bars are updated. However, the stacklabel is still showing A and B instead of C and D when pressing to the C&D page.
How could the stacklabel be refreshed? Thank you.

A: Replace this:
chart_stacked.invalidate();
Utilities.custom_toast(Stat.this, "chart type = " + chart_type, "gone",
"short");

with:
chart_stacked.notifyDataSetChanged();
chart_stacked.invalidate();
Utilities.custom_toast(Stat.this, "chart type = " + chart_type, "gone", "short");


text:
Q: Powershell Chrome Zoom I have the below code working on my PS1. How do i change the zoom of the chrome window which is opened.
start chrome --app="data:text/html,"

A: There isn't a programmatic way to do this to my knowledge and so your PowerShell script will have to pretend to be a user that brings the Chrome window to the foreground and presses the required keys.
In the script below, I find windows that matches the phrase "Google Chrome", takes the first one and then sends Ctrl+0 and the two Ctrl+= keypresses so that it zooms in twice from the default.
Those key strokes are expressed as ^0^=^= in the script. Similarly, you could use ^0^-^- to zoom out. For more information about how to specify the keys to send into a window, see https://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys(v=vs.110).aspx.
$titleMatch = "Google Chrome"
$keys = "^0^=^="

[Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null

# This C# fragment makes available a class that can set the foreground window
# since this is not a built-in feature in PowerShell.

Add-Type @"
  using System;
  using System.Runtime.InteropServices;
  public class SelectWindow {
    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool SetForegroundWindow(IntPtr hWnd);
  }
"@

# Find the processes where the main window has a title that matches our query.

$processes = Get-Process | Where-Object { $_.MainWindowTitle -match $titleMatch }

if ($processes) {

  # Get the main window handle of the first matching process.

  $windowHandle = $processes[0].MainWindowHandle

  # Bring that window to the front and send the keys to it.

  [SelectWindow]::SetForegroundWindow($windowHandle) | Out-Null
  [System.Windows.Forms.SendKeys]::SendWait($keys)
}

A: As an alternative to Don Cruickshank's method using p\invoke, you could also use the AppActivate method from Microsoft.VisualBasic.Interaction to make Chrome the active window.
 Add-Type -AssemblyName Microsoft.VisualBasic
 Add-Type -AssemblyName 'System.Windows.Forms'
 $ID = (Start-Process chrome.exe -PassThru).id
 Sleep 1
 [Microsoft.VisualBasic.Interaction]::AppActivate([Int32]$ID)
 [System.Windows.Forms.SendKeys]::SendWait("^0^=^=")

A: If you just need a temporary size change then you can press Ctrl + / - to zoom and Ctrl 0 to reset.
If you want to increase the font size in the Javascript console, you need add some specific size like:
.source-code {
    font-size: 16px !important;
    font-family: monospace;
}

.console-prompt {
    font-size: 16px !important;
    font-family: monospace;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: doctrine2 inner join data in object So I am doing two inner joins:
<?php

$q->select('o, pic.path pic1, pic_.path pic2');

$q->innerJoin('\TestBundle\Entity\UserImages', 'pic', 'WITH', 'o.id = pic.user');
$q->where('pic.keyname = \'pic1\'');

$q->innerJoin('\TestBundle\Entity\UserImages', 'pic_', 'WITH', 'o.id = pic.user');
$q->where('pic_.keyname = \'pic2\'');

This works but the returned result is this:
array (size=1)
  0 =>
    array (size=3)
      0 =>
        object(TestBundle\Entity\user)[1359]
          private 'name' => string 'test' (length=12)
          private 'created' =>
            object(DateTime)[1347]
              ...
          private 'modified' => null
          private 'deleted' => null
          private 'id' => int 1

      'pic1' => string 'pic1.png' (length=8)
      'pic2' => string 'pic2.png' (length=8)

Is there any way to have the pic1 and pic2 be set in the object?
I tried adding setPic1/Pic2 to the Users entity but that didn't work.
What do I have to do to get this to work in the result of the query?
Thanks

A: I didn't find a way to do what I wanted using just doctrine  but since I am using sonota and this is the reason I needed the pic1 and pic2 I created a DataGrid Decorator and intercepted the getResult() method.
In the admin class I override the buildDataGrid (don't have the source code now but I think that was the method) and it will create the datagrid but then I will do something like:
$this->datagrid = new DataGridDecorator($this->datagrid)

The decorator will then change the result given by the method getResult() to what sonata expects and so I don't have to override I don't know how many templates.
Thanks for the help!


text:
Q: Does the MARS instruction counter work with Static or Dynamic Instructions? I found this thread regarding the instruction counter, but wanted a bit more info on how the counter works within MARS4. Are the instructions displayed Static or Dynamic? If so, is there a way to find the other one? Thank you!

A: It's not the instructions that are dynamic or static, it's the count.
A count of instructions executed is a dynamic instruction-count, and the Q&A you linked says that's what MARS's counter gives you.
A static instruction-count is just code-size: look at the binary window after assembling, and subtract the last - first addresses.  Instructions = bytes/4.  (Minus any padding for alignment if you don't want to count that, but often you do because what really matters is code footprint in the I-cache, and size to be loaded from disk.  An instruction that never runs is basically indistinguishable from padding for alignment.)
(So static I-count is pretty trivial, like line count of disassembly.
But the dynamic count depends on how the program runs; that's why it's useful to have a dynamic instruction counter in a simulator.)


text:
Q: I'm getting an error message: _tkinter.TclError: bad event type or keysym "ButtonLeft" My code:
def left():
    a.bk(25)
def right():
    a.fd(25)
def up():
    a.lt(90)
    a.fd(25)
    a.rt(90)
def down():
    a.rt(90)
    a.fd(25)
    a.lt(90)
while True:
    a.onrelease(left,"Left")
    a.onrelease(right,"Right")
    a.onrelease(up,"Up")
    a.onrelease(down,"Down")
    a.listen()

How do I fix this? I'd also prefer to use onkey instead of onrelease but it gives me an error message: 'Turtle' object has no attribute 'onkey'

A: onrelease(), onclick(), ondrag() are for mouse's buttons - and it needs numbers 1 (left button), 2 (middle button), 3 (right button). Probably it may also use 4 and 5 if mouse has more buttons. They are assigned to turtles and they need a.onrelease()
onkey(), onkeyrelease(), onkeypress() are for keyboard's keys - but keys are not assigned to turtles and you should use directly turtle.onkey() or you should create screen = turtle.Screen() and use screen.onkey()
And you don't have to run code in while-loop but use turtle.mainloop() or turtle.done().
import turtle

# --- functions ---  # PEP8: all functions before main code

def left():
    a.bk(25)

def right():
    a.fd(25)

def up():
    a.lt(90)
    a.fd(25)
    a.rt(90)

def down():
    a.rt(90)
    a.fd(25)
    a.lt(90)

def turle_clicked(x, y):
    print('turtle:', x, y)

def screen_clicked(x, y):
    print('screen:', x, y)

# --- main ---

a = turtle.Turtle()

a.onrelease(turle_clicked, 1)  # left button (clicked on turtle)
a.onrelease(turle_clicked, 2)  # middle button (clicked on turtle)
a.onrelease(turle_clicked, 3)  # right button (clicked on turtle)

turtle.onscreenclick(screen_clicked, 1)  # left button  (clicked in any place in window)

turtle.onkey(left,"Left")
turtle.onkey(right,"Right")
turtle.onkey(up,"Up")
turtle.onkey(down,"Down")

turtle.listen()

turtle.mainloop()

PEP 8 -- Style Guide for Python Code


text:
Q: В чём ошибка в последней строке? Питон выводит ошибку, написано следующее:"TypeError: 'str' object is not callable", что делать?     what = input ('Что делаем? : (+, -)')

    if what == '+':
      a = float(input('Первое число:'))
      b = float(input('Второе число:'))
      c = a + b
      print("Результат:" + str(c))

A: Где то выше имени str или print присвоена какая-то строка. Нельзя использовать зарезервированные имена для своих переменных.

A: Приведённый код рабочий:
In [2]:  a = float(input('Первое число:'))
   ...:  b = float(input('Второе число:'))
   ...:  c = a + b
   ...:  print("Результат:" + str(c))
Первое число:1
Второе число:2
Результат:3.0

Если ошибка, то она в другом месте

A: str - строковый тип, а выводится значение c с типом int.


text:
Q: how to use browserify in windows I am trying browserify and I have the following files in my project directory

*

*node_models/.bin - where browserify is located

*sample.js
module.exports = 'Hello, world';

*index.js
window.alert(require('./sample'));

Can somebody help me how to run it using browserify? I'm using Windows.

A: All you should need to do is run this command in the project directory:
node_modules\.bin\browserify index.js > bundle.js

However, you can make things a little more convinient by adding an entry under scripts in your package.json:
{
    ...
    "scripts": {
        "bundle": "browserify index.js > bundle.js"
    }
}

You can then build the bundle with this command:
npm run bundle


text:
Q: Get the line number in Edit control how can you get the current line number in a multi-line edit control?

A: From the docs for EM_LINEFROMCHAR, if you pass -1 as wParam, you get the line number of the line containing the caret (or the start of the selection if there is one).

A: Look at the EM_LINEFROMCHAR window message.

A: Did you try checking the MSDN index for anything beginning with EM_*. If you did, you'd find EM_LINEFROMCHAR, EM_LINEINDEX, EM_LINELENGTH, etc, which can probably solve your problem


text:
Q: Remove even numbers from a vector in c++ can somebody help me with this function: suppose that I need to remove all even numbers from a vector using reference: can I do that? Is the push_back correct or should I use something else?
void evenRemoe(vector<int>& arr) {
    for(int i = 0; i < arr.size(); i++) {
        if(arr[i] % 2 != 0) {
            push_back(arr[i]);
        }
    }
}

A: Using push_back adds elements so that's not going to work.
You can use std::erase_if with a functor, like a lambda or other function acting as a unary predicate, to decide what elements that should be removed.
void evenRemoe(std::vector<int>& arr) {
    std::erase_if(arr, [](int i) { return i % 2 == 0; });
}

Prior to C++20 you could implement the erase–remove idiom
#include <algorithm>
void evenRemoe(std::vector<int>& arr) {
    arr.erase(std::remove_if(arr.begin(), arr.end(),
                             [](int i) { return i % 2 == 0; }),
              arr.end());
}

A: No, push_back() is not the correct thing to use.  That is meant for adding values, not removing them.
Also, your code is actually looking for odd values, not even values.
You can use std::vector::erase() to remove individual values, eg:
void evenRemoe(vector<int>& arr){
    for(size_t i = 0; i < arr.size();){
        if (arr[i] % 2 == 0){
            arr.erase(arr.begin()+i);
        }else{
            ++i;
        }
    }
}

Alternatively, consider using the Erase-Remove idiom via std::remove_if() and std::vector::erase(), eg:
#include <algorithm>

void evenRemoe(vector<int>& arr){
    arr.erase(
        std::remove_if(arr.begin(), arr.end(),
            [](int value){ return (value % 2) == 0; }
        ),
        arr.end()
    );
}

Or, in C++20, via std::erase_if(), eg:
void evenRemoe(vector<int>& arr){
    std::erase_if(arr,
        [](int value){ return (value % 2) == 0; }
    );
}

A: push_back is a method of std::vector for appending an element to the end of the vector, not removing. What you need is one of the erase methods.
However, you should be careful while erasing elements of the vector you're iterating over. Care must be taken to avoid incrementing the index when you remove the element.
The better way to do this is to use std::remove_if algorithm instead of iterating the vector yourself.
void evenRemove(vector<int>& arr) {
    auto it = std::remove_if(arr.begin(), arr.end(),
        [](int n) { return (n % 2) == 0; });
    arr.erase(it, arr.end());
}

Despite the name, std::remove_if doesn't actually remove any elements from the vector. Instead, it moves the elements that match the predicate (in our case - all even integers) to the end of the vector and returns an iterator pointing to the first of such elements. Therefore, to actually remove the elements you need to call erase with the iterators denoting the tail of the vector that contains the even integers.

A: From C++20 onwards you can use std::erase_if() , Prior to c++20 erase-remove idiom used to be the solution of this problem.
v.erase(std::remove_if(v.begin(), v.end(), is_even), v.end());

Where is_even is a functor

A: Remove multiple element from vector using iterator.
Just take care that when we erase using iterator,it goes invalid.
int main(){
        vector<int> vec={1,2,3,4,5,6,7,8,9};
        for(auto it=vec.begin();it!=vec.end();){
           if(*it%2==0)
               vec.erase(it);
           else
               it++;
        }
        for(auto i:vec){
            cout<<i<<" ";
        }
        return 0;
    }

output:1 3 5 7 9
2nd method
int main(){
    vector<int> vec={1,2,3,4,5,6,7,8,9};
    vec.erase(remove_if(vec.begin(),vec.end(),[](int i){
        return i%2==0;
    }),vec.end());

    for(auto i:vec)
        cout<<i<<" ";

    return 0;
}


text:
Q: initialization discards 'const' qualifier from pointer target type I'm still new to C, so I don't have a great understanding of it. Right now I'm trying to figure out pointers.
I want to load the parameters of a structure amqp_connection_info through the argv variables. How can I change the load of parameters in the structure?
int main(int argc, const char **argv) {
    amqp_connection_state_t conn;

    // char const *user;
    // char const *password;
    // char const *host;
    // int port;
    // char const *vhost;

    int debit_limit;
    int message_count;
    char const *new_queue = NULL;
    char const *new_echange;
    char const *echangetype;
    char const *cle_liaison;
    char const *contenu_message;

    static int durable = 1; // La durabilité du queue

    if (argc < 13) {
    printf("Usage: amqp_producteur utilisateur mdp nom_hote port vhost debit_limit message_count new_queue \
    new_echange echangetype cle_liaison contenu_message\n");
    return 1;
    }
    struct amqp_connection_info ci;
    // ci : variable globale contenant les paramètres de configuration de connexion
    struct amqp_connection_info ci = {
    argv[1],
    argv[2],
    argv[3],
    atoi(argv[4]),
    argv[5]};

    debit_limit = atoi(argv[6]);
    message_count = atoi(argv[7]);
    new_queue = argv[8]; /* exp:"unroutable" */
    new_echange = argv[9];   /* exp:"amq.direct" */
    echangetype = argv[10];
    cle_liaison = argv[11]; /* exp:"test" */
    contenu_message = argv[12]; /* exp:"Message à envoyer" */

    // Les routines AMQP
    if ((conn = amqp_connexion(&ci)) != NULL)
    {
        amqp_creation_queue (conn, new_queue, durable);
        amqp_creation_echange (conn, new_echange, echangetype, durable);
        amqp_production(conn, new_queue, debit_limit, message_count, contenu_message, new_echange, cle_liaison);
        amqp_deconnexion(conn);
    }
    else
    {
        printf("connexion impossible\n");
    }
    return 0;
}

When compiling, I had this problem:
amqp_producteur.c: In function 'main':
amqp_producteur.c:60:5: error: initialization discards 'const' qualifier from pointer target type [-Werror]
     argv[1],
     ^
amqp_producteur.c:61:5: error: initialization discards 'const' qualifier from pointer target type [-Werror]
     argv[2],
     ^
amqp_producteur.c:62:5: error: initialization discards 'const' qualifier from pointer target type [-Werror]
     argv[3],
     ^
amqp_producteur.c:63:5: error: initialization makes pointer from integer without a cast [-Werror]
     atoi(argv[4]),
     ^
amqp_producteur.c:63:5: error: (near initialization for 'ci.vhost') [-Werror]
amqp_producteur.c:64:5: error: initialization makes integer from pointer without a cast [-Werror]
     argv[5]};
     ^
amqp_producteur.c:64:5: error: (near initialization for 'ci.port') [-Werror]
cc1: all warnings being treated as errors

A: argv is declared as const: const char **argv. This means that each element of argv is a const char * (you can view argv as an array of const pointers). You are assigning that const char * to a non-const char *, which discards the const qualifier. This is what prompts the warning.
You can avoid this problem by chaning the signature of main to int main(int argc, char **argv). Note that argv is not, in fact, const so it is perfectly safe to remove the const from the signature, see Why is main() argument argv of type char*[] rather than const char*[]?.

A: Aside from icebp's correct answer regarding the const issue, there are two type mismatches where you try to initialize ci.vhost and ci.port. According to DocsForge, struct amqp_connection_info is
struct amqp_connection_info {
  char *user; /**< the username to authenticate with the broker, default on most
                 broker is 'guest' */
  char *password; /**< the password to authenticate with the broker, default on
                     most brokers is 'guest' */
  char *host;     /**< the hostname of the broker */
  char *vhost; /**< the virtual host on the broker to connect to, a good default
                  is "/" */
  int port;    /**< the port that the broker is listening on, default on most
                  brokers is 5672 */
  amqp_boolean_t ssl;
};

So, if you keep the different order in the usage port vhost, you have to also swap the initializers
    atoi(argv[4]),
    argv[5]


text:
Q: Apis are working locally but not on deployed react app I have deployed the admin panel to heroku, the apis working correctly on local but not on heruko. I have been using http://144.76.103.235:5010/admin/api/auth/login for login, but its not working, also not giving any error or warning. The server is currently hosted on ftp server.
here is the heroku log tail
2022-05-17T22:13:45.647119+00:00 heroku[web.1]: Restarting
2022-05-17T22:13:45.663555+00:00 heroku[web.1]: State changed from up to starting
2022-05-17T22:13:46.279939+00:00 heroku[web.1]: Stopping all processes with SIGTERM
2022-05-17T22:13:46.328528+00:00 app[web.1]:
2022-05-17T22:13:46.328538+00:00 app[web.1]: INFO: Gracefully shutting down. Please wait...
2022-05-17T22:13:46.443883+00:00 heroku[web.1]: Process exited with status 143
2022-05-17T22:13:53.145125+00:00 heroku[web.1]: Starting process with command `npm start`
2022-05-17T22:13:54.136688+00:00 app[web.1]:
2022-05-17T22:13:54.136699+00:00 app[web.1]: > autoscan-admin-panel@0.0.1 start
2022-05-17T22:13:54.136700+00:00 app[web.1]: > serve -s build
2022-05-17T22:13:54.136700+00:00 app[web.1]:
2022-05-17T22:13:54.386028+00:00 app[web.1]: INFO: Accepting connections at http://localhost:45373
2022-05-17T22:13:54.765468+00:00 heroku[web.1]: State changed from starting to up
2022-05-17T22:13:58.000000+00:00 app[api]: Build succeeded
2022-05-17T22:14:06.912668+00:00 heroku[router]: at=info method=GET path="/" host=scan-app-admin.herokuapp.com request_id=c8f4ddf7-5788-480e-af79-622ab9d9331c fwd="119.160.3.145" dyno=web.1 connect=0ms service=11ms status=200 bytes=1527 protocol=https
2022-05-17T22:14:07.264071+00:00 heroku[router]: at=info method=GET path="/static/css/main.47b071b3.chunk.css" host=scan-app-admin.herokuapp.com request_id=0c8ed474-4a2c-416f-856f-ac9b1c9c364e fwd="119.160.3.145" dyno=web.1 connect=0ms service=3ms status=304 bytes=85 protocol=https
2022-05-17T22:14:07.274740+00:00 heroku[router]: at=info method=GET path="/static/js/main.9b5b3e47.chunk.js" host=scan-app-admin.herokuapp.com request_id=7ab2fdf6-270f-41c7-bc8a-be3d5d1b679a fwd="119.160.3.145" dyno=web.1 connect=0ms service=9ms status=200 bytes=41303 protocol=https
2022-05-17T22:14:07.311507+00:00 heroku[router]: at=info method=GET path="/static/js/2.7c9ee254.chunk.js" host=scan-app-admin.herokuapp.com request_id=40c7f436-72d4-4691-8238-8a73d3394115 fwd="119.160.3.145" dyno=web.1 connect=0ms service=49ms status=200 bytes=298573 protocol=https
2022-05-17T22:14:08.951134+00:00 heroku[router]: at=info method=GET path="/static/media/showPassword.a1ba73da.svg" host=scan-app-admin.herokuapp.com request_id=b826e546-c4a2-4ac8-9fc0-b3981f3f929e fwd="119.160.3.145" dyno=web.1 connect=0ms service=2ms status=304 bytes=85 protocol=https
2022-05-17T22:14:09.281507+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=scan-app-admin.herokuapp.com request_id=0a9fefca-1ab5-4737-a10f-01fc9ad4fc45 fwd="119.160.3.145" dyno=web.1 connect=0ms service=2ms status=304 bytes=85 protocol=https
2022-05-17T22:14:10.400133+00:00 heroku[router]: at=info method=GET path="/manifest.json" host=scan-app-admin.herokuapp.com request_id=6b5dc01d-1434-4e87-bcc1-ed24983519ff fwd="119.160.3.145" dyno=web.1 connect=0ms service=2ms status=304 bytes=85 protocol=https
2022-05-17T22:14:10.671324+00:00 heroku[router]: at=info method=GET path="/logo192.png" host=scan-app-admin.herokuapp.com request_id=42bc281f-0bad-45a7-9d9e-a2e89ed6a857 fwd="119.160.3.145" dyno=web.1 connect=0ms service=1ms status=304 bytes=85 protocol=https

package.js
{
  "name": "autoscan-admin-panel",
  "version": "0.0.1",
  "private": true,
  "dependencies": {
    "@material-ui/core": "^4.12.3",
    "@material-ui/lab": "^4.0.0-alpha.60",
    "@react-google-maps/api": "^2.4.0",
    "@reduxjs/toolkit": "^1.6.1",
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "@types/jest": "^26.0.15",
    "@types/node": "^12.0.0",
    "@types/react": "^17.0.0",
    "@types/react-dom": "^17.0.0",
    "@types/react-geocode": "^0.2.0",
    "@types/react-redux": "^7.1.18",
    "@zhigamovsky/styled-console-log": "^1.0.0",
    "actions-util": "github:AkeleyUA/actions-util",
    "axios": "^0.21.1",
    "fast-xml-parser": "^4.0.0-beta.8",
    "lodash": "^4.17.21",
    "moment": "^2.29.1",
    "query-string": "^7.0.1",
    "rc-table": "^7.17.1",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-geocode": "^0.2.3",
    "react-google-places-autocomplete": "^3.3.2",
    "react-modal": "^3.14.3",
    "react-query": "^3.31.0",
    "react-redux": "^7.2.4",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.3",
    "react-select": "^5.2.1",
    "react-table": "^7.7.0",
    "redux-devtools-extension": "^2.13.9",
    "redux-logger": "^3.0.6",
    "redux-persist": "^6.0.0",
    "redux-saga": "^1.1.3",
    "serve": "^13.0.2",
    "styled-components": "^5.3.0",
    "typescript": "^4.1.2",
    "web-vitals": "^1.0.1"
  },
  "scripts": {
    "build": "react-scripts build",
    "start": "serve -s build",
    "dev": "react-scripts start",
    "start-lint-disable": "DISABLE_ESLINT_PLUGIN=true  react-scripts start"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@types/lodash": "^4.14.172",
    "@types/react-modal": "^3.13.1",
    "@types/react-router-dom": "^5.1.8",
    "@types/react-table": "^7.7.7",
    "@types/redux-logger": "^3.0.9",
    "@types/styled-components": "^5.1.12",
    "@typescript-eslint/eslint-plugin": "^4.22.0",
    "eslint-config-airbnb-typescript": "^12.3.1",
    "eslint-config-prettier": "^8.2.0",
    "eslint-plugin-import": "^2.22.1",
    "eslint-plugin-jsx-a11y": "^6.4.1",
    "eslint-plugin-no-loops": "^0.3.0",
    "eslint-plugin-no-use-extend-native": "^0.5.0",
    "eslint-plugin-optimize-regex": "^1.2.0",
    "eslint-plugin-prettier": "^3.4.0",
    "eslint-plugin-promise": "^5.1.0",
    "eslint-plugin-react": "^7.23.2",
    "eslint-plugin-react-hooks": "^4.2.0",
    "eslint-plugin-sonarjs": "^0.6.0",
    "prettier": "^2.2.1"
  }
}

server.js
import * as rateLimit from 'express-rate-limit';
import * as mongoose from 'mongoose';
import * as express from 'express';
import * as helmet from 'helmet';
import * as dotenv from 'dotenv';
import * as morgan from 'morgan';
import * as cors from 'cors';
import * as path from 'path';

import { errorHandler } from './helpers';
import { config } from './config';
import router from './routes';
import './processes';

dotenv.config();

const serverRequestLimit = rateLimit({
  windowMs: config.serverRateLimits.period,
  max: config.serverRateLimits.maxRequests
});

class App {
  public readonly app: express.Application = express();

  constructor() {
    (global as any).appRoot = path.resolve(process.cwd(), './');

    this.app.use(morgan('dev'));
    this.app.use(helmet());
    this.app.use(serverRequestLimit);
    this.app.use(cors());

    this.app.use(express.json());
    this.app.use(express.urlencoded({extended: true}));

    this.mountRoutes();
    this.setupDB();

    this.app.use(errorHandler);
  }

  private setupDB(): void {
    mongoose.connect(config.MONGODB_URL, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      useFindAndModify: false
    });

    const db = mongoose.connection;
    console.log('connected')
    db.on('error', console.log.bind(console, 'MONGO ERRROR'));
  }

  private configureCors = (origin: any, callback: any) => {
    const whiteList = config.ALLOWED_ORIGIN.split(';');

    if (!origin) { // FOR POSTMAN
      return callback(null, true);
    }

    if (!whiteList.includes(origin)) {
      return callback(new Error('Cors not allowed'), false);
    }

    return callback(null, true);
  }

  private mountRoutes(): void {
    this.app.use('/', router);
    this.app.use('/images', express.static(path.resolve((global as any).appRoot, 'public') ));
  }
}

export const app = new App().app;

A: Heroku was using https protocol i.e. https://app.herokuapp.com while my end point was on http protocol, which was blocking the request. Interestingly the heroku app can run on both protocols, So I switched the app url to http i.e. http://app.herokuapp.com and it started working.


text:
Q: error in installing Package Microsoft.AspNet.SignalR I am trying to install Microsoft.AspNet.SignalR from NuGet and get the following error:

'Microsoft.Owin.Security 2.0.2'. You are trying to install this
  package into a project that targets '.NETFramework,Version=v4.0', but
  the package does not contain any assembly references or content files
  that are compatible with that framework. For more information, conta
  ct the package author.

Has anyone encountered this, and knows what the solution is?

A: SignalR 2.0 does not support .net 4.0. Either do a upgrade of .net or use a 1.x version of SignalR.
>Install-Package Microsoft.AspNet.SignalR -Version 1.1.3

source

A: Another option is upgrading from Framework 4.0 to Framework 4.5.
Go to the "WEBSITE > Start Options" in the Visual Studio menu, and then change your "Target Framework" to 4.5.
Also make sure that controlRenderingCompatibilityVersion (if used) is also 4.5 in your web.config.
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <pages controlRenderingCompatibilityVersion="4.5" />
  </system.web>


text:
Q: Convert date with nanoseconds in java I have a date in this format "2017-05-17 00:31:16.227", I need to convert it to "17-MAY-17 12.31.16.227000000 AM".
String convertTimestamp(Timestamp date) {

    String newstring = null;
    try {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSSSSS");
        java.util.Date date1 = dateFormat.parse(date.toString());
        DateFormat sdf = new SimpleDateFormat("dd-MMM-yy hh.mm.ss.SSSSSSSSS aa");
        newstring = sdf.format(date1);

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

    System.out.println("new string" + newstring);

    return newstring;
}

but I am getting the value like this **"17-MAY-17 12.31.16.000000227 AM"

A: You are using the troublesome old legacy date-time classes that are now supplanted by the java.time classes.  These legacy classes are limited to milliseconds which means three decimal places in the fraction of a second. So the legacy classes cannot handle the nine digits you desire.
The nine digits of decimal fraction you want means a resolution of nanoseconds rather than milliseconds. Fortunately, the java.time classes have a resolution of nanoseconds.
Parse your input as a LocalDateTime object as it lacks any indication of time zone or offset-from-UTC. Replace the SPACE in middle with a "T" to comply with standard ISO 8601 format.
String input = "2017-05-17 00:31:16.227".replace( " " , "T" ) ;
LocalDateTime ldt = LocalDateTime.parse( input );

You should be able to force the trailing zeros you desire in the decimal fraction in a string representing the value of this LocalDateTime object. Use either a DateTimeFormatter or a DateTimeFormatterBuilder.


text:
Q: How to configure xampp on Windows Server 2012 R2 I've configured xampp on my server but when I try to access it remotely via browser it doesn't work. Localhost works fine.

A: You need to have Apache enabled, and listening on port 80.


text:
Q: Посчитать количество каждой цифры и создать объект У меня есть функция, которая извлекает числа из аргументов и возвращает его в виде строки:

function countNumber(smth) {
    return String(smth.match(/\d+/));
}

console.log(countNumber('123098h76gfdd')); //=>12309876

countNumbers('erer384jj4444666888jfd123');
// => {'1': 1, '2': 1, '3': 2, '4': 5, '6': 3, '8': 4}
countNumbers('jdjjka000466588kkkfs662555');
// => {'0': 3, '2': 1, '4': 1, '5': 4, '6': 4, '8': 2}
countNumbers(''); // => {}

Теперь мне нужно посчитать количество каждой цифры и создать объект. например, в конце это должно выглядеть так, как показано выше:
Как это сделать правильно? Есть идеи? Помогите пожалуйста!

A:

const countDigits = str => (str.match(/\d/g) || []).reduce(
  (rslt, digit) => ((rslt[digit] = ~~rslt[digit] + 1), rslt)
, {});

const printObj = obj => console.log(
  JSON.stringify(obj).replace(/[,:]/g, '$& ')
);

printObj(countDigits('erer384jj4444666888jfd123'));
// => {'1': 1, '2': 1, '3': 2, '4': 5, '6': 3, '8': 4}
printObj(countDigits('jdjjka000466588kkkfs662555'));
// => {'0': 3, '2': 1, '4': 1, '5': 4, '6': 4, '8': 2}
printObj(countDigits('')); // => {}

Вместо (str.match(/\d/g) || []) можно [...str.replace(/\D/g, '')] - результат будет одинаков, но у второго варианта возможен +1 проход по символам строки (зависит от внутренней реализации строк, и спред-оператора).

A: Или так.
var allowed = /\d+/;
var results = Array.prototype.reduce.call("123099998h76gfdd", function (data, letter) {
    if (allowed.test(letter)) {
        letter = letter.toLowerCase();
        if (data[letter] === undefined) {
            data[letter] = 0;
        }
        data[letter] += 1;
    }
    return data;
}, {});

var o = new Object();
for (var letter in results) {
    o[letter] = results[letter]
}
console.log(o);

A: Можно просто создать еще один объект, перевести строку в массив, и пробежаться по массиву:
var res = new Object();
"ssd243fs20324fs".split("").filter(char => char >= '0' && char <= '9')
  .forEach(d => res[d] = (res[d] || 0) + 1)

Сначала выпоняется фильтрация символов: проверка, что символ -- цифра. Далее для каждой цифры инкриментируется счётчик в res.
Результат: { 0: 1, 2: 3, 3: 2, 4: 2 }
Как я писал выше в комментарии, функция (автора вопроса) получения цифр не верная (нет цифр 76):
String('123098h76gfdd'.match(/\d+/)) == "123098"

PS: в старых браузерах или IE может не заработать. Но это поправить легко, и это касается и других ответов.
PPS: на мой взгяд, всякие reduce, используемые в других ответах, мало понятны новичку. Зато каждый, изучающий язык, знает про циклы, т.е. понять forEach должно быть не сложно.


text:
Q: Cronjob script trouble launching application I started with cronjobs a while ago, but up until yesterday I've run into a problem I can't figure/find out.
@reboot me /etc/application/start-script.sh

I have Raspbian Jessie (minimal) installed on a Raspberry Pi Zero. One of the users has a cronjob command @reboot. When I check "sudo /etc/init.d/cron status", I can see the cronjob is picked up after a reboot and executed. The only thing is that any output is dropped, the "No MTA installed"-message, (care?).
#!/bin/bash
# My start script

logfile=/home/me/logfile.log

echo "Starting program..." >> $logfile
application
echo "Program started!" >> $logfile

As you can see, it should create a log file, and it does this after a reboot when the script is called as a cronjob. This script works perfectly fine when you manualy execute it, it writes the output to the logfile AND starts the program.
The problem is: the program is not launched when the .sh script is called as a cronjob.
Why is only the application not started when the script is executed???
"sudo /etc/init.d/cron status" output
Mar 17 22:14:45 pizza-pi systemd[1]: Starting Regular background program processing daemon...
Mar 17 22:14:45 pizza-pi systemd[1]: Started Regular background program processing daemon.
Mar 17 22:14:45 pizza-pi cron[292]: (CRON) INFO (pidfile fd = 3)
Mar 17 22:14:45 pizza-pi cron[292]: (CRON) INFO (Running @reboot jobs)
Mar 17 22:14:45 pizza-pi CRON[296]: pam_unix(cron:session): session opened for user me by (uid=0)
Mar 17 22:14:45 pizza-pi CRON[318]: (me) CMD (etc/application/start-script.sh)
Mar 17 22:14:45 pizza-pi CRON[296]: (CRON) info (No MTA installed, discarding output)
Mar 17 22:14:45 pizza-pi pam_unix(cron:session): session closed for user me

A: Edit the /etc/rc.local file and add the following line in /etc/init.d/cron/start  be sure that it should before exit 0.
Follow this link https://rahulmahale.wordpress.com/2014/09/03/solved-running-cron-job-at-reboot-on-raspberry-pi-in-debianwheezy-and-raspbian/
Hope answer is useful for you


text:
Q: Why is player 2's turn skipped after an incorrect input instead of being allowed another input (2p tictactoe game java) Basically if player 1 puts in an incorrect move (outside of 1-9) then "Incorrect Input" will be printed and they'll be allowed to try again. I have the same code for player 2 but after printing the error message their turn is skipped and it's back to player one. I'm extremely puzzled on how to solve this
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class TicTactoe3 {

    static ArrayList<Integer> playerPositions = new ArrayList<Integer>();
    static ArrayList<Integer> playerPositions2 = new ArrayList<Integer>();

    public static void main(String[] args) {

        char[][] gameBoard = {{' ', '|', ' ', '|', ' '},
                              {'-', '+', '-', '+', '-'},
                              {' ', '|', ' ', '|', ' '},
                              {'-', '+', '-', '+', '-'},
                              {' ', '|', ' ', '|', ' '}};

        printGameBoard(gameBoard);

        while(true) {
            Scanner move = new Scanner(System.in);

            System.out.println("Enter your move (1-9) player one ");
            int playerPos = move.nextInt();
            while(playerPositions.contains(playerPos) || playerPositions2.contains(playerPos)) {
                System.out.println("Position taken");
                playerPos = move.nextInt();
            }

            if(playerPos >= 10 || playerPos <= 0) {
                System.out.println("Incorrect Input");
                continue;
            }

            placePiece(gameBoard, playerPos, "player 1");
            printGameBoard(gameBoard);

            String result = checkWinner();
            if(result.length() > 0) {
                System.out.println(result);
                break;
            }

            System.out.println("Enter your move (1-9) player two ");
            int playerPos2 = move.nextInt();
            while(playerPositions.contains(playerPos2) || playerPositions2.contains(playerPos2)) {
                System.out.println("Position taken");
                playerPos2 = move.nextInt();
            }

            if(playerPos2 >= 10 || playerPos2 <= 0) {
                System.out.println("Incorrect Input");
                continue;
            }

            placePiece(gameBoard, playerPos2, "player 2");
            printGameBoard(gameBoard);

            result = checkWinner();
            if(result.length() > 0) {
                System.out.println(result);
                break;
            }
        }
    }

    public static void printGameBoard(char[][] gameBoard) {
        for(char[] row : gameBoard) {
            for(char c : row) {
                System.out.print(c);
            }
            System.out.println();
        }
    }

    public static void placePiece(char[][] gameBoard, int pos, String user) {

        char symbol = ' ';

        if(user.equals("player 1")) {
            symbol = 'X';
            playerPositions.add(pos);
        } else if(user.equals("player 2")) {
            symbol = 'O';
            playerPositions2.add(pos);
        }

        switch(pos) {
        case 1:
            gameBoard[0][0] = symbol;
            break;
        case 2:
            gameBoard[0][2] = symbol;
            break;
        case 3:
            gameBoard[0][4] = symbol;
            break;
        case 4:
            gameBoard[2][0] = symbol;
            break;
        case 5:
            gameBoard[2][2] = symbol;
            break;
        case 6:
            gameBoard[2][4] = symbol;
            break;
        case 7:
            gameBoard[4][0] = symbol;
            break;
        case 8:
            gameBoard[4][2] = symbol;
            break;
        case 9:
            gameBoard[4][4] = symbol;
            break;
        default:
            break;
        }
    }
    public static String checkWinner() {

        List topRow = Arrays.asList(1, 2, 3);
        List midRow = Arrays.asList(4, 5, 6);
        List botRow = Arrays.asList(7, 8, 9);
        List leftCol = Arrays.asList(1, 4, 7);
        List midCol = Arrays.asList(2, 5, 8);
        List rightCol = Arrays.asList(3, 6, 9);
        List cross1 = Arrays.asList(1, 5, 9);
        List cross2 = Arrays.asList(7, 5, 3);

        List<List> winning = new ArrayList<List>();
        winning.add(topRow);
        winning.add(midRow);
        winning.add(botRow);
        winning.add(leftCol);
        winning.add(midCol);
        winning.add(rightCol);
        winning.add(cross1);
        winning.add(cross2);

        for (List l : winning) {
            if(playerPositions.containsAll(l)) {
                return "Congrats, player 1 wins!";
            }
            else if(playerPositions2.containsAll(l)) {
                return "Congrats, player 2 wins";
            }
        }

        for (List l : winning) {
            if(playerPositions.size() + playerPositions2.size() == 9) {
                return "NOBODY WINS";
            }
        }

        return "";
    }
}

I'm still very much a beginner at java, apologies if this is very basic. I've found multiple other tictactoe questions on here but none to solve my specific issue.


text:
Q: Re-wrote git history with bfg but not reflected in earlier commits A huge folder in my repository has filled up my LFS. As instructed here, I wish to remove the folder from the remote repository and then re-write history to drop it from all previous commits. That should free up lots of space in my LFS, but is not. What am I missing?
Say the repository is repo and the folder in question is repo/unwantedFolder.
I did the following steps:

*

*Removed the unwantedFolder and re-committed:
$ git rm -r --cached unwantedFolder/
$ git commit -a -m 'Drops folder'
$ git push origin

*Mirror-cloned the repo:
$ git clone --mirror https://github.com/emagar/repo.git

*Re-wrote history:
$ java -jar bfg.jar --delete-folders unwantedFolder repo.git/

*Moved into the manipulated cloned repo: $ cd repo.git/

*Used the git gc command:
$ git reflog expire --expire=now --all && git gc --prune=now --aggressive

*Pushed the clean repository: $ git push origin

*Moved back to the original repository: $ cd repo/

*Pulled from github: $ git pull origin master
While all seemed to work well, when I inspect old commits in github, the unwantedFolder/ still appears there!
What am I missing?


text:
Q: Is it correct to say "She had never been sick since she started staying at home until she started going to school"? Look at this diagram

As shown in the diagram, my children had been staying home for a year due to Covid-19. Within that year, they had never been sick.
A week ago, they started going back to school. A first few days within that week, they were well not sick but now they are sick.
Can we use this structure?:
Past perfect or past perfect continuous + since a point of time in the past + until another point of time in the past
Is it correct to say "She had never been sick since she started staying at home until she started going to school"?
I have a feeling that "until" should be replaced by "by the time"
"She had never been sick since she started staying at home by the time she started going to school"

A: First, "never" is absolute, and while you can qualify it by specifying certain circumstances, it only makes sense when speaking about a the circumstance in general. For example "She never got sick when her grandmother was around" makes sense, or "She never got sick when she was home from school" (because "being home from school" is general, not speaking about a particular time period). But in this case, since you are speaking about a specific time period when she was home rather than all times that she was home, "She had not been sick" is much more idiomatic.
Second, "since" usually is used as "Since [some time] until now", with the "until now" implied. If you are specifying an end date, then "from [start time] until [end time]" is usually the construct you would use.
In your case, the most idiomatic way of saying this would be something like "She had not been sick from the time she started staying home until she went back to school." Even better would be the more-concise "She had not been/gotten sick the entire time she was home from school [due to Covid]." You don't need the "from ... until" construct if you can just use one phrase to describe the time period.


text:
Q: Как быстро найти файл, который отправляет на сервер форму? Здравствуйте ещё раз.
Нет ли быстрого метода для поиска файлов .js которые делают POST?
Их тут тысячи, как найти нужный?
Может расширения Chrome?...

A: Как вариант можете воспользоваться средствами отладки Google Chrome. Откройте инструменты отладки нажатием f12, после чего выберите вкладку network, отфильтруйте запросы, оставив только xhr запросы. И в столбце Initiator увидите тот файл, который делает запрос.

Для того, чтобы понять POST или GET запрос, нажмите на него и вы получите описание на вкладке Header.


text:
Q: Custom ImageView with rounded corners not working on some Android devices I'm using this custom ImageView class to basically simulate an image having rounded corners:
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.widget.ImageView;

public class CustomImageView extends ImageView {

    public static float radius = 18.0f;

    public CustomImageView(Context context) {
        super(context);
    }

    public CustomImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Path clipPath = new Path();
        RectF rect = new RectF(0, 0, this.getWidth(), this.getHeight());
        clipPath.addRoundRect(rect, radius, radius, Path.Direction.CW);
        canvas.clipPath(clipPath);
        super.onDraw(canvas);
    }
}

and this is the usage:
    <com.example.sixerstrivia.CustomImageView
        android:id="@+id/customIV"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:scaleType="centerCrop"
        android:src="@drawable/button_background" />

This worked on another device I had previously which was running Android 3.x.x. I'm running it now on Android 4.2.2 and the corners are no longer rounded. My question is: what is causing this not to work on my current device running 4.2.2? And is there a way to fix this? Thanks!


text:
Q: T-SQL to get consecutive Rows I'm trying to write a query that will give all the SensorID and LocID that have five consecutive datetime rows, i.e. the difference between them is 1 hour and voltage is >= 6. I can use LAG and get the difference in minutes, but how to select the consecutive rows?
Input table:
SensorID LocID DateTime Voltage
-------------------------------
    100 200 1/23/2019 13:00 6
    100 200 1/23/2019 12:00 8
    100 200 1/23/2019 11:00 6
    100 200 1/23/2019 10:00 7
    100 200 1/23/2019 9:00 8
    101 201 1/23/2019 10:00 8
    101 201 1/23/2019 9:00 1
    101 201 1/23/2019 8:00 2
    101 201 1/23/2019 6:00 8
    101 201 1/23/2019 5:00 1
    103 203 1/23/2019 11:00 10
    103 203 1/23/2019 10:00 11
    103 203 1/23/2019 9:00 8
    103 203 1/23/2019 8:00 9
    103 203 1/23/2019 7:00 9

Required output:
SensorID LocID DateTime Voltage
-------------------------------
    100 200 01/23/19 1 PM 6
    100 200 01/23/19 12 PM  8
    100 200 01/23/19 11 AM  6
    100 200 01/23/19 10 AM  7
    100 200 01/23/19 9 AM 8
    103 203 01/23/19 11 AM  10
    103 203 01/23/19 10 AM  11
    103 203 01/23/19 9 AM 8
    103 203 01/23/19 8 AM 9
    103 203 01/23/19 7 AM 9

use tempdb
go

Create Table #Input
(
    SensorID int
    , LocID int
    , DateTime datetime
    , Voltage float
)

Insert Into #Input
Select 100,200,'1/23/2019 13:00',6 Union All
Select 100,200,'1/23/2019 12:00',8 Union All
select 100,200,'1/23/2019 11:00',6 Union All
Select 100,200,'1/23/2019 10:00',7 Union All
Select 100,200,'1/23/2019 9:00',8 Union All
Select 101,201,'1/23/2019 10:00',8 Union All
Select 101,201,'1/23/2019 9:00',1 Union All
Select 101,201,'1/23/2019 8:00',2 Union All
Select 101,201,'1/23/2019 6:00',8 Union All
Select 101,201,'1/23/2019 5:00',1 Union All
Select 103,203,'1/23/2019 11:00',10 Union All
Select 103,203,'1/23/2019 10:00',11 Union All
Select 103,203,'1/23/2019 9:00',8 Union All
Select 103,203,'1/23/2019 8:00',9 Union All
Select 103,203,'1/23/2019 7:00',9

Select * from #Input

drop table #Input
go

A: You can use the OFFSET argument of LAG to check 4 rows back to make it a 5 row window (counting the current). EG: lag(Column,Offset,Default) where column is the column, offset is the number of rows back, and default is what to return if the condition fails (NULL by default).
;with cte as(
select
    *
    ,LogicCheck = abs(datediff(hour,[DateTime],lag([DateTime],4) over (partition by SensorID order by [DateTime])))
from #Input
)

select *
from #Input
where SensorID in (select SensorID from cte where LogicCheck = 4)

This works with your sample data but if there are larger windows, you'll want to account for that. See this added sample data and method for taking care of the larger windows.
use tempdb
go
Create Table #Input
(
    SensorID int
    , LocID int
    , DateTime datetime
    , Voltage float
)

Insert Into #Input
Select 100,200,'1/23/2019 13:00',6 Union All
Select 100,200,'1/23/2019 12:00',8 Union All
select 100,200,'1/23/2019 11:00',6 Union All
Select 100,200,'1/23/2019 10:00',7 Union All
Select 100,200,'1/23/2019 9:00',8 Union All
Select 101,201,'1/23/2019 10:00',8 Union All
Select 101,201,'1/23/2019 9:00',1 Union All
Select 101,201,'1/23/2019 8:00',2 Union All
Select 101,201,'1/23/2019 6:00',8 Union All
Select 101,201,'1/23/2019 5:00',1 Union All
Select 103,203,'1/23/2019 11:00',10 Union All
Select 103,203,'1/23/2019 10:00',11 Union All
Select 103,203,'1/23/2019 9:00',8 Union All
Select 103,203,'1/23/2019 8:00',9 Union All
Select 103,203,'1/23/2019 7:00',9 Union All
Select 103,203,'1/23/2019 6:00',9 Union all --added this row which should be included
Select 103,203,'1/23/2019 4:00',9           --added this row which is a break in the time and shouldn't be returned

;with cte as(
select
    *
    ,Seq = row_number() over (partition by SensorID order by [DateTime])
    ,LogicCheck = abs(datediff(hour,[DateTime],lag([DateTime],4) over (partition by SensorID order by [DateTime])))
from #Input
)

select
    c.SensorID
    ,c.LocID
    ,c.DateTime
    ,c.Voltage
    --,c.Seq
    --,c.LogicCheck
from
    cte c
where exists
    (
        select SensorID
        from cte
        where LogicCheck = 4
        and cte.SensorID = c.SensorID
        and c.Seq <= cte.Seq
        and c.Seq >= cte.Seq - 4
    )

drop table #Input


text:
Q: NoSuchMethod:'cast, Dynamic call with incorrect number type argument I am trying to get data from an API to my flutter, but I keep getting this error:

Please help have spend days on this single error!
Here is my code
welcome_screen.dart
// ignore_for_file: prefer_const_constructors, unused_import
import 'dart:html';
import 'package:barakh_sooq/components/foot_navigation_bar.dart';
import 'package:barakh_sooq/components/custom_drawer.dart';
import 'package:barakh_sooq/config.dart';
import 'package:barakh_sooq/constants.dart';
import 'package:barakh_sooq/data.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'dart:convert'; // for using json.decode()
import 'dart:developer';
import 'package:http/http.dart' as http;
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:barakh_sooq/models/home.dart';
// import 'package:barakh_sooq/repos/home_repo.dart';

Future<List<Ads>> getAds() async {
  final response = await http.get(Uri.parse("http://localhost:4000/home"));
  //  log(response.body);
  if (response.statusCode == 200) {
    final parsed = jsonDecode(response.body).cast<Map<String, dynamic>>();
    log(parsed);
    return parsed.map<Ads>((json) => Ads.fromJson(json)).toList();
  } else {
    throw Exception('Failed to load album');
  }
}

class WelcomeScreen extends StatelessWidget {
  const WelcomeScreen({Key? key}) : super(key: key);

  static String routeID = 'welcome_screen';

  @override
  Widget build(BuildContext context) {
    return WelcomeScreenView();
  }
}

class WelcomeScreenView extends StatefulWidget {
  const WelcomeScreenView({Key? key}) : super(key: key);

  @override
  _WelcomeScreenViewState createState() => _WelcomeScreenViewState();
}

class _WelcomeScreenViewState extends State<WelcomeScreenView> {
  final GlobalKey<ScaffoldState> _key = GlobalKey<ScaffoldState>();
  late bool _navIsVisible;
  late ScrollController _hideBottomNavController;
  late Future<List<Ads>> futureAds;

  @override
  void initState() {
    super.initState();
    futureAds = getAds();
    _navIsVisible = true;
    _hideBottomNavController = ScrollController();
    _hideBottomNavController.addListener(() {
      if (_hideBottomNavController.position.userScrollDirection ==
          ScrollDirection.reverse) {
        if (_navIsVisible) {
          setState(() {
            _navIsVisible = false;
          });
        }
      }
      if (_hideBottomNavController.position.userScrollDirection ==
          ScrollDirection.forward) {
        if (!_navIsVisible) {
          setState(() {
            _navIsVisible = true;
          });
        }
      }
    });
  }

  @override
  void dispose() {
    _hideBottomNavController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    SizeConfig().screenSizeInit(context);
    return Scaffold(
        key: _key,
        drawer: CustomDrawer(),
        body: FutureBuilder<List<Ads>>(
          future: futureAds,
          builder: (context, snapshot) {
            if (snapshot.hasError) {
              return Container(
                child: Text(snapshot.error.toString()),
              );
            } else if (snapshot.hasData) {
              return ListView.builder(
                itemCount: snapshot.data!.length,
                itemBuilder: (context, index) => ListTile(
                  title: Text(snapshot.data![index].itemTitle),
                  subtitle: Text(
                    "Here",
                    softWrap: false,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              );
            }
            return Center(
              child: CircularProgressIndicator(),
            );
          },
        ));
  }
}

home_repo.dart
    import 'dart:developer';

import 'package:http/http.dart' as http;
import 'package:barakh_sooq/models/home.dart';
import 'dart:convert';

class HomeRepository {
  Future<List<Ads>> getAds() async {
    final response = await http.get(Uri.parse("http://localhost:4000/home"));
    //  log(response.body);
    if (response.statusCode == 200) {
      final parsed = jsonDecode(response.body).cast<Map<String, dynamic>>();
      log(parsed);
      return parsed.map<Ads>((json) => Ads.fromJson(json)).toList();
    } else {
      throw Exception('Failed to load album');
    }
  }
}

home.dart(model)
import 'dart:convert';

import 'dart:convert';

List<Ads> adsFromJson(String str) =>
    List<Ads>.from(json.decode(str).map((x) => Ads.fromJson(x)));

class Home {
  Home({
    required this.category,
    required this.state,
    required this.ads,
  });
  late final List<Category> category;
  late final List<Region> state;
  late final List<Ads> ads;

  Home.fromJson(Map<String, dynamic> json) {
    category =
        List.from(json['category']).map((e) => Category.fromJson(e)).toList();
    state = List.from(json['state']).map((e) => Region.fromJson(e)).toList();
    ads = List.from(json['ads']).map((e) => Ads.fromJson(e)).toList();
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['category'] = category.map((e) => e.toJson()).toList();
    _data['state'] = state.map((e) => e.toJson()).toList();
    _data['ads'] = ads.map((e) => e.toJson()).toList();
    return _data;
  }
}
class Ads {

Ads({
    required this.id,
    required this.location,
    required this.category,
    required this.subcategory,
    required this.itemTitle,
    required this.itemPrice,
    required this.negotiable,
    required this.phoneNumber,
    required this.condition,
    required this.address,
    required this.description,
    required this.owner,
    required this.createdAt,
    required this.updatedAt,
    required this.V,
    required this.images,
  });
  late final String id;
  late final String location;
  late final String category;
  late final String subcategory;
  late final String itemTitle;
  late final int itemPrice;
  late final bool negotiable;
  late final String phoneNumber;
  late final String condition;
  late final String address;
  late final String description;
  late final String owner;
  late final String createdAt;
  late final String updatedAt;
  late final int V;
  late final List<Images> images;

  Ads.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    location = json['location'];
    category = json['category'];
    subcategory = json['subcategory'];
    itemTitle = json['item_title'];
    itemPrice = json['item_price'];
    negotiable = json['negotiable'];
    phoneNumber = json['phone_number'];
    condition = json['condition'];
    address = json['address'];
    description = json['description'];
    owner = json['owner'];
    createdAt = json['createdAt'];
    updatedAt = json['updatedAt'];
    V = json['__v'];
    images = List.from(json['images']).map((e) => Images.fromJson(e)).toList();
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['id'] = id;
    _data['location'] = location;
    _data['category'] = category;
    _data['subcategory'] = subcategory;
    _data['item_title'] = itemTitle;
    _data['item_price'] = itemPrice;
    _data['negotiable'] = negotiable;
    _data['phone_number'] = phoneNumber;
    _data['condition'] = condition;
    _data['address'] = address;
    _data['description'] = description;
    _data['owner'] = owner;
    _data['createdAt'] = createdAt;
    _data['updatedAt'] = updatedAt;
    _data['__v'] = V;
    _data['images'] = images.map((e) => e.toJson()).toList();
    return _data;
  }
}

class Images {
  Images({
    required this.id,
    required this.filename,
    required this.contentType,
    required this.adid,
    required this.createdAt,
    required this.updatedAt,
    required this.V,
  });
  late final String id;
  late final String filename;
  late final String contentType;
  late final String adid;
  late final String createdAt;
  late final String updatedAt;
  late final int V;

  Images.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    filename = json['filename'];
    contentType = json['contentType'];
    adid = json['adid'];
    createdAt = json['createdAt'];
    updatedAt = json['updatedAt'];
    V = json['__v'];
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['id'] = id;
    _data['filename'] = filename;
    _data['contentType'] = contentType;
    _data['adid'] = adid;
    _data['createdAt'] = createdAt;
    _data['updatedAt'] = updatedAt;
    _data['__v'] = V;
    return _data;
  }
}

This is the structure of my file:
Structure of file :

Here is the JSON Response
{
    "category": [
    {
    "_id": "616ed1bb0b784e17e4fefc67",
    "name": "Food",
    "createdAt": "2021-10-19T14:10:03.361Z",
    "updatedAt": "2021-10-19T14:40:50.115Z",
    "__v": 0,
    "subcategory": []
    },
    {
    "_id": "616ed7e92bacf63664f36eec",
    "name": "car",
    "createdAt": "2021-10-19T14:36:25.567Z",
    "updatedAt": "2021-10-19T14:36:25.567Z",
    "__v": 0,
    "subcategory": [
    {
    "_id": "616ee646d7f5732acc905693",
    "name": "Toyota",
    "category": "car",
    "createdAt": "2021-10-19T15:37:42.858Z",
    "updatedAt": "2021-10-19T15:37:42.858Z",
    "__v": 0
    },
    {
    "_id": "617008c79c4eb53b20573889",
    "name": "Honda",
    "category": "car",
    "createdAt": "2021-10-20T12:17:11.467Z",
    "updatedAt": "2021-10-20T12:17:11.467Z",
    "__v": 0
    }
    ]
    }
    ],
    "state": [
    {
    "_id": "616ff4a9220ea7072892985d",
    "name": "الرياض",
    "createdAt": "2021-10-20T10:51:21.962Z",
    "updatedAt": "2021-10-20T10:51:21.962Z",
    "__v": 0,
    "city": [
    {
    "_id": "616ff533220ea70728929861",
    "name": "الخرج",
    "state": "الرياض",
    "createdAt": "2021-10-20T10:53:39.139Z",
    "updatedAt": "2021-10-20T10:53:39.139Z",
    "__v": 0
    },
    {
    "_id": "616ff547220ea70728929865",
    "name": "الدرعية",
    "state": "الرياض",
    "createdAt": "2021-10-20T10:53:59.096Z",
    "updatedAt": "2021-10-20T10:53:59.096Z",
    "__v": 0
    },
    {
    "_id": "616ff552220ea70728929869",
    "name": "الدلم",
    "state": "الرياض",
    "createdAt": "2021-10-20T10:54:10.287Z",
    "updatedAt": "2021-10-20T10:54:10.287Z",
    "__v": 0
    },
    {
    "_id": "616ff559220ea7072892986d",
    "name": "الدوادمي",
    "state": "الرياض",
    "createdAt": "2021-10-20T10:54:17.834Z",
    "updatedAt": "2021-10-20T10:54:17.834Z",
    "__v": 0
    },
    {
    "_id": "616ff562220ea70728929871",
    "name": "الحريق",
    "state": "الرياض",
    "createdAt": "2021-10-20T10:54:26.079Z",
    "updatedAt": "2021-10-20T10:54:26.079Z",
    "__v": 0
    },
    {
    "_id": "616ff56c220ea70728929875",
    "name": "الزلفي",
    "state": "الرياض",
    "createdAt": "2021-10-20T10:54:36.334Z",
    "updatedAt": "2021-10-20T10:54:36.334Z",
    "__v": 0
    }
    ]
    },
    {
    "_id": "616ff57e220ea70728929879",
    "name": "الشرقية",
    "createdAt": "2021-10-20T10:54:54.271Z",
    "updatedAt": "2021-10-20T10:54:54.271Z",
    "__v": 0,
    "city": [
    {
    "_id": "616ff589220ea7072892987d",
    "name": "الدمام",
    "state": "الشرقية",
    "createdAt": "2021-10-20T10:55:05.258Z",
    "updatedAt": "2021-10-20T10:55:05.258Z",
    "__v": 0
    },
    {
    "_id": "616ff5a5220ea70728929881",
    "name": "حفر الباطن",
    "state": "الشرقية",
    "createdAt": "2021-10-20T10:55:33.224Z",
    "updatedAt": "2021-10-20T10:55:33.224Z",
    "__v": 0
    }
    ]
    }
    ],
    "ads": [
    {
    "_id": "616d9af509dfe63ac8c44447",
    "location": "lagos",
    "category": "car",
    "subcategory": "toyota",
    "item_title": "Big Daddy",
    "item_price": 2000,
    "negotiable": true,
    "phone_number": "09033536548",
    "condition": "New",
    "address": "Lagos",
    "description": "Good car",
    "owner": "6169e4aa2265f9405c4de4cb",
    "createdAt": "2021-10-18T16:04:05.611Z",
    "updatedAt": "2021-10-18T16:04:05.611Z",
    "__v": 0,
    "images": [
    {
    "_id": "616d9af509dfe63ac8c44449",
    "filename": "images-1634573045577.png",
    "contentType": "image/png",
    "adid": "616d9af509dfe63ac8c44447",
    "createdAt": "2021-10-18T16:04:05.611Z",
    "updatedAt": "2021-10-18T16:04:05.611Z",
    "__v": 0
    },
    {
    "_id": "616d9af509dfe63ac8c44448",
    "filename": "images-1634573045562.png",
    "contentType": "image/png",
    "adid": "616d9af509dfe63ac8c44447",
    "createdAt": "2021-10-18T16:04:05.611Z",
    "updatedAt": "2021-10-18T16:04:05.611Z",
    "__v": 0
    }
    ]
    },
    {
    "_id": "616ea77e384b2f2f60c3ff38",
    "location": "abuja",
    "category": "car",
    "subcategory": "honda",
    "item_title": "Big Daddy",
    "item_price": 2000,
    "negotiable": true,
    "phone_number": "09033536548",
    "condition": "New",
    "address": "Lagos",
    "description": "Good car",
    "owner": "6169e4aa2265f9405c4de4cb",
    "createdAt": "2021-10-19T11:09:50.236Z",
    "updatedAt": "2021-10-19T11:09:50.236Z",
    "__v": 0,
    "images": [
    {
    "_id": "616ea77e384b2f2f60c3ff39",
    "filename": "images-1634641780856.png",
    "contentType": "image/png",
    "adid": "616ea77e384b2f2f60c3ff38",
    "createdAt": "2021-10-19T11:09:50.237Z",
    "updatedAt": "2021-10-19T11:09:50.237Z",
    "__v": 0
    }
    ]
    }
    ]
    }

A: It's working now,
I modify my home_repo.dart as below:
class HomeRepository {
  Future<List<Ads>> getAds() async {
    List<Ads> _loadAds = [];
    final response = await http.get(Uri.parse("http://localhost:4000/home"));
    if (response.statusCode == 200) {
      // List<Ads> getAdsHere = response.body["ads"] as List<Ads>;
      final parsed = jsonDecode(response.body);
      for (var i = 0; i < parsed["ads"].length; i++) {
        Map<String, dynamic> map = parsed["ads"][i];
        _loadAds.add(Ads.fromJson(map));
        // _loadAds.add(parsed["ads"][i]);
      }
      log("Location ---------${_loadAds[0].location} ");
      return _loadAds;
    } else {
      throw Exception('Failed to load album');
    }
  }
}

A: You should use
(jsonDecode(response.body) as Map<String, dynamic>) in places where you are using .cast<Map<String,dynamic>


text:
Q: Optional anonymity to hide ignorance I know that a couple of questions regarding anonymous posts have been discussed recently, but they've been in the spirit of encouraging impartiality when voting.
However, sometimes we just have a burning question about something we might think is embarassingly simple or easy.  We might have given our SO username to prospective employers, or generally don't want to lose our street cred with the community.  However, these could be questions that add real value to the site... through search and such.
There could be a "anonymous" questions section of the profile that simply gave the number of questions and Rep earned, without naming and linking to the questions.

A: I feel like 'Anonymous posting area' would end up becoming a bathroom wall of posts. Anyone who is frustrated or angered by something could seek refuge there.
If your question is embarrassingly easy, you should think long and hard about whether or not it is worth being on stack overflow. If you aren't willing to attach your name to it, then why would you want to subject everyone else to reading it?
Socrates: I only know that I know nothing.
If I have a dumb question, at least I'm smart enough to know that I don't know the answer.

A: Since the anonymity part can be achieved by clicking "logout", it seems like kinda a low-return-on-investment use of developer time to make a whole set of mechanics for associating semi-anonymous postings with a registered account.

A: You could always just post your potentially embarrassing questions under another account. Also, if you're worried about looking dumb to potential employers, Joel said in Podcast #58 that, for good employers, this is a non-issue.
I do, however, think that if a person cannot delete their post (usually because there are upvoted answers) that they should have the ability to 'disown' the post, so that it stays visible on the site but unassociated with that particular user.

A: I think this is a great idea to allow your profile info to be hidden from a question or answer...  But how  would this work in the data dumps that are accessible to the public?  Would the user still receive upvote and downvote credit?

A: People can and do ask questions based only on wanting to contribute and add content to the site. In many cases they do know the answer.
If you phrase your question in such a way so that it doesn't necessarily indicate ignorance there is no reason to worry about employers finding it and thinking you are clueless.
In the unlikely event they do and question you on it, you can just explain that even knowledgeable people contribute questions for the sake of content and encouraging community participation.
As stated above, in any case, asking questions is likely to be valued by employers and most would understand the above concept.
For this reason I don't think you need to worry about looking foolish or ignorant - just post! :)

A: I'd like to point out that preventing users from disowning their questions is arguably illegal in some countries (typically, under the French Law, nobody can use your name unless without your explicit consent. I only gave a license to use the content I provided)
I say arguably because my login is associated with my questions, not my name. However, my login can be my real name, my login is associated with my email, etc.


text:
Q: Why can't my Perl script see the our() variables I defined in another file? I have a question relating to Perl and scoping. I have a common file with lots of various variables. I require the common file in my main script, but I cannot access the variables; they seem to be outside of its scope. I assumed that an our declaration would overcome that problem, but it doesn't seem to work.
Script 1: common.pl
#!/usr/bin/perl

our $var1 = "something";
our $var2 = "somethingelse";

Script 2: ftp.pl
#!/usr/bin/perl

use strict;
use warnings;

require('common.pl');

print $var1;

I get the error: Global symbol "$var1" requires explicit package name

A: There's no require statement in your second example, but it wouldn't work anyway. What our does is declare a lexically-scoped package variable. Since you have no package statement, it uses the default package main.  So your first script sets up the variable $main::var1, but this will only be available within that file's scope.
A better way to provide common variables for other scripts is to use Exporter. You can define package symbols in one place and Exporter will take care of copying them to the requesting script or class's namespace when needed.

A: I would put the config in a module instead.
File: MyConfig.pm
package MyConfig;
require Exporter;
use strict;

our @ISA                = qw(Exporter);
our @EXPORT             = qw( getconfig );

my %confighash = (
            thisone => 'one',
            thatone => 2,
            somthingelse => 'froboz',
                   );

sub getconfig {
 return  %confighash;
 }

1;

Example usage:
#!/usr/bin/perl
use strict;
use warnings;

use MyConfig;

my %config = getconfig();

print $config{ somthingelse };

This should print froboz

A: It looks like you need a proper configuration file there. I'd go for a non-code configuration file that you can read when you need to setup things. There are modules on CPAN to handle just about any configuration format you can imagine.
If you want to do it the way you have it, get rid of our and declare them with use vars. Don't let the PBP police scare you off that. :) You only really need our to limit a scope of a package variable, and that's exactly the opposite of what you are trying to do.

A: our() does something a little different than you think.  Its sole purpose is to work with strict in requiring you to declare package variables that you are going to use (unless they are fully-qualified or imported).  Like strict, its effect is lexically-scoped.  To use it to allow accessing a global $main:var1 from multiple files (which are separate scopes) as just $var1, you need to say our $var1 in each file.
Alternatively, you would change your required file to be a module with its own package that exports the variables to any package that uses it.

A: Try this. I am new at Perl but this is how I got it to work on a script I made
#!/usr/bin/perl

$var1 = "something";
$var2 = "somethingelse";
Script 2: ftp.pl

#!/usr/bin/perl

use strict;
use warnings;

our $var1;
our $var2;

require('common.pl');

print $var1;


text:
Q: Telerik WinForm problems in Windows Server 2008 R2 I build wcf ,and it run's on Windows Server 2008 R2.Now i updated my program , and add Scheduler(telerik).
After this my aplication is start's to  crash.
Do any one know how to fix it?
Here my code that works
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.ServiceModel;
using System.Threading;
using System.Windows.Forms;

namespace WindowsFormsApplication
{
    static class Program
    {
       // public static SchedulerForm Scheduler = new SchedulerForm(); here Scheduler disabled
        private static NotifyIcon trayIcon;
        static void Main()
        {
           using (ServiceHost host = new ServiceHost(typeof(SimpleService.SimpleService)))
            {
                host.Open();
                SysTrayApp();
                Application.Run();
 }
        }

        public static void SysTrayApp()
        {
            /* tmNowActions = new ContextMenu();
            tmNowActions.MenuItems.Add("....
            my other function (not important)
            */

           // Scheduler.ShowDialog();

        }
    }
}

And here after i remove comments and enable scheduler
namespace WindowsFormsApplication
{
    static class Program
    {
        public static SchedulerForm Scheduler = new SchedulerForm();
        private static NotifyIcon trayIcon;
        static void Main()
        {
           using (ServiceHost host = new ServiceHost(typeof(SimpleService.SimpleService)))
            {
                host.Open();
                SysTrayApp();
                Application.Run();
 }
        }

        public static void SysTrayApp()
        {
            /* tmNowActions = new ContextMenu();
            tmNowActions.MenuItems.Add("....
            my other function (not important)
            */
           Scheduler.ShowDialog();

        }
    }
}

After this my aplication is crashed
Here the image from win server 2008 R2

Do any one know how to fix it?
UPDATE
I found that i was missing some telerik dll's,after i add them i get a new error.
If  i will make empty WinForm all works fine,and i will see empty form ,but if i add telerik element(Scheduler in my case),i will get this error

Here another error that says i am missing Scheduler version,but you can see the dll and properties of this dll,and it is there it is not missing.

A: I resolved this problem like this:
1:Clean project and delete old files from Degub/bin.
2:Make sure all telerik dll's have the same version(end's .20 or .40)  !!IMPORTANT!!.
3:In Telerik dll's click properties, and then make Copy Local = true  !!IMPORTANT!!.
4:Rebuild the project.
After all this steps all start to work.


text:
Q: Visual Studio 2015 does not install Android SDK tools for Api 19,21,23 etc for Xamarin I am moving towards Xamarin for cross-platform application development. I already had VS2015 installed, I downloaded Xamarin tools(vstoolsforxamarin.exe) from their website and when I install them after a long wait VS says "setup completed with errors"and it does not download and install Android SDK for API 19,20,23, It always say:"Please check your internet connection and try again" and i am sure that my internet connection doesn't get disturbed during all this process. I have tried this 3 times now, tried by uninstalling VS2015, installing it again but got the same error. What is the problem that is causing this? I already have Android Studio installed, with its SDK manager. Any help would be appreciated, that to get Xamarin running in VS2015.
EDIT:
Solution:
I already had Android Studio and its SDK on my system, going to Tools>Options>Xamarin from Visual Studio and giving path of the Android SDK solved my problem. Read this answer on StackOverflow somewhere!

A: Seems like this issue is caused because Visual Studio is trying to download thrid-party libraries (Android SDK). You can fix this from Control-Panel

Have a look at this post.

A: Make sure you have installed Java JDK, I had similar issue reported here
Visual Studio 2015 Enterprise Reports Internet Connectivity Issue while there is no issues with networking

A: As mwilson64 answered in response to Android SDK Setup API not installed (same as linked above on "Have a look at this post."), my steps to resolve:

*

*Create file %USERPROFILE%.android\androidtool.cfg

*Paste the following into new file (created in step 1):
# Settings for Android Tool
# Last updated: Wed May 19 17:09:27 UTC 2017
http.proxyPort=8888
sdkman.enable.previews=false
http.proxyHost=127.0.0.1
sdkman.ask.adb.restart=false
sdkman.show.update.only=true
sdkman.force.http=false
sdkman.use.dl.cache=true

Replace values in proxyPort and proxyHost with your company's proxy settings.


text:
Q: c# operator overloading usage public static ListOfPeople operator +( ListOfPeople x, Person y)
    {
        ListOfPeople temp = new ListOfPeople(x);
        if(!temp.PeopleList.Contains(y))
        {
            temp.PeopleList.Add(y);
        }
        temp.SaveNeeded = true;
        return temp;
    }

So, I've never used the overload functionality of operators, and I'm trying to make sense of how to add objects from my class (Person) to my Collection class (ListOfPeople).
ListOfPeople contains an attribute List<Person> PeopleList;
My difficulty is in how to get a pre-existing List inside of this method to add a new Person to. ListOfPeople temp = new ListOfPeople(x);
I have an error on this line because I have no constructor that takes a ListOfPeople argument. If I were to make it ListOfPeople temp = new ListOfPeople(); then Temp would just call my default constructor where I simply create a new, empty list, and that doesn't allow me to add to a pre-existing list either.
I'm just not sure how I get 'temp' to actually reference my pre-existing list.

A: Use as follows:
public static ListOfPeople operator +( ListOfPeople x, Person y)
{
    ListOfPeople temp = x;
    if(!temp.PeopleList.Contains(y))
    {
        temp.PeopleList.Add(y);
    }
    temp.SaveNeeded = true;
    return temp;
}

public static ListOfPeople operator +( Person y, ListOfPeople x)
{
    ListOfPeople temp = x;
    if(!temp.PeopleList.Contains(y))
    {
        temp.PeopleList.Add(y);
    }
    temp.SaveNeeded = true;
    return temp;
}

*

*1st allows you to use: list = list + person

*2nd allows you to use: list = person + list
You may also want to overload += operator (non-static) so that you can use list += person
EDIT
Though I solved the problem mentioned. But, then, I agree with others on the operands of '+' being immutable.
Below is update to existing code (assuming ListOfPeople.PeopleList is List<Person>):
public static ListOfPeople operator +( ListOfPeople x, Person y)
{
    ListOfPeople temp = new ListOfPeople();
    temp.PeopleList.addRange(x);
    if(!temp.PeopleList.Contains(y))
    {
        temp.PeopleList.Add(y);
    }
    temp.SaveNeeded = true;
    return temp;
}

public static ListOfPeople operator +( Person y, ListOfPeople x)
{
    ListOfPeople temp = new ListOfPeople();
    temp.PeopleList.addRange(x);
    if(!temp.PeopleList.Contains(y))
    {
        temp.PeopleList.Add(y);
    }
    temp.SaveNeeded = true;
    return temp;
}


text:
Q: Externalize configuration Akka I am new in Akka and I faced the problem below.
I want to externalize the configuration in my App. More specifically, I have some variables that are different per each environment. So I think that I can have specific environment variables (secrets, etc) for each environment.
But what I can do with some variables (non-secrets) which are different per each environment?
What is the difference between, dev.properties, application.conf, deploy.json files?
What is the proper way to load variables from those files?

A: There's a few options:

*

*Environment variables and using the support for substitution (there is also support for having default in the file and only use the environment vars if they are set). - https://github.com/lightbend/config#optional-system-or-env-variable-overrides

*System properties, if you set a system property when you start the JVM, and that system property matches a path in the config file, it overrides the setting

*You can point to an alternative application.conf file using a system property - https://github.com/lightbend/config#standard-behavior
If that is not enough you could also do completely custom logic around selecting logic by programmatically creating a Config instance and passing that to the ActorSystem when you create it.
The dev.properties and deploy.json is AFAIK not related to Akka, unless something specifically done in your application.


text:
Q: Hibernate Session.save() doesn't return a value? Below code throws a casting error

Long newID = (Long)session.save(object);

I am new to hibernate. Don't know why.

A: There are two methods:

*

*public Serializable save(Object object) throws HibernateException
Persist the given transient instance, first assigning a generated identifier. (Or using the current value of the identifier property if the assigned generator is used.) This operation cascades to associated instances if the association is mapped with cascade="save-update".
Parameters: object - a transient instance of a persistent class
Returns: the generated identifier

*public Serializable save(String entityName, Object object) throws HibernateException
Persist the given transient instance, first assigning a generated identifier. (Or using the current value of the identifier property if the assigned generator is used.) This operation cascades to associated instances if the association is mapped with cascade="save-update".
Parameters: object - a transient instance of a persistent class
Returns: the generated identifier

A: The return value of session.save() depends on your mapping. Most likely you have a type of ID that isn't a Long. Try doing this:
System.out.println(session.save(object).getClass().getName());

Then you'll see the type name.


text:
Q: Character counting bug when flagging a post If you flag a post as 'requires moderator attention', you have to enter a reason of at least 10 characters. Padding out the reason with spaces reduces the number in the "enter at least X characters" visual feedback label, but submitting the reason then (correctly) fails.
The "Please enter at least X" characters count should ignore leading, trailing, or consecutive whitespace characters.

A: This is by design. Don't pad with spaces, and enter a valid comment of the required length.


text:
Q: How to debug a java heap OutOfMemory error in a production environment? Our web app is running in tomcat7 and we're using java 1.7.0_55....In the past when we've had problems we've been able to debug in our development environments using Eclipse and a profiler (the name escapes me at the moment).
Now we're getting an OutOfMemory exception in our production environment.  I'm quite leery of running a profiler in a production environment so my question is...Is there any way to debug this problem in the production environment without using a profiler or is there something that is light-weight enough that I could run it in production?

A: Just take a heap dump of production server & analyse it with Eclipse Memory analysis tool. You can copy the heapdump to your local. Eclipse Memory Analyzer is the best tool for this job. However, trying to get the UI to run remotely is very painful. Launching Eclipse and updating the UI is an extra load on the JVM that is already busy analyzing a 30G heap dump. Fortunately, there is a script that comes with MAT to parse the the heap dump and generate HTML reports without ever having to launch Eclipse!
Check this out.

A: If you want to profile your application on production you can use jConsole for real histogram from your production system. If you can pay, you should try jProfiler (https://www.ej-technologies.com/products/jprofiler/overview.html). Its really helpful for dumping data of JVM on production enviroment.

A: If you are very much concern with running a profiler in production environment run the jmap -histo:live pid
histogram is the summary of the heap, its very lite weight and will take very less time to generate data for you. This will be of good use if you dont have HeapDumpOnOutOfMemoryError is not set.
Its always better to take a heap dump on OOME
Java provides a system switch to do this by flag -XX:+HeapDumpOnOutOfMemoryError this will generate heap dump file.
Heap dump file contain all the objects related information in it. It can be easily analysed using jhat . This will open the dump file and analyze the data and listen to a port that will be displayed in console.
If the GC logs are configured have a look at the GC logs and identify the time from when the memory consumption increased significantly. From the logs try to identify the actions done/requests processed by your tomcat, go through the code and try to identify if there are any memory leaks caused in the code. You can use the histogram as reference since histo provides the objects count as well.
If you are using some cache in your application check what is the max size configured for cache, or is cache is cleared at regular intervals ....
Hope this is helpful.

A: Set a higher Xmx limit.
-Xmx2048M or more if needed.


text:
Q: Why does adding Action cause Fatal Error in Delphi I'm using Delphi 2009. My program has been compiling and running fine. I use Action lists and have them built into my program - although I haven't changed them in a while.
So today I go to simply add a new action to my ActionList in the normal manner that it is done. Without doing anything else, I now build and run my program and I get the following error:
[DCC Fatal Error] Userface.pas(1): F2092 Program or unit 'Userface' recursively uses itself.
I have done nothing to change any of the uses clauses. I can't find any instances of my Userface unit calling itself or calling another unit that calls Userface. I place potentially recursive calls in the Implementation section as they should be.
If I exit Delphi without saving, rebuild and run it, it runs fine. If I attempt again to add a new action to the action list, the fatal error happens again.
I'm at a loss to figure out what is happening. I would appreciate any help to figure out how to get around this.

Edit: After Uwe's answer, I double checked to make sure it was still happening. Sure enough, I did it again as I described in my comment to Uwe. After building, it happened again.
... But then, by accident under the Project Menu I missed picking "Build" and selected "Compile" instead. It compiled fine. Then I tried building and now the build works correctly. No Fatal Error! Everything seems fine for me again.
If I try to add another action and then build, the error comes up again. But if I compile, then I can build it successfully - so at least I have a workaround.
This must be some sort of a glitch. I don't know what happened. Does anybody know what this is or why it might be happening?

Followup. As Marjan states, it can occur in other circumstances, and one of those happened to me. So it is probably NOT directly related to the adding an action, which my question asks.
None-the-less, it is a relatively rare happening so far for me and has only turned into a minor annoyance. It may already have been fixed in Delphi 2010, and my ultimate solution will be when I next upgrade to Delphi 2011 or 12 once they add either 64-bit or multi-platform.

A: Sometimes adding a component automatically changes the uses clause. This can either be done by Delphi itself or by a third-party plugin like ModelMaker CodeExplorer. You can use the history tab to quickly identify any changes.
Without the source nothing more say I can...
EDIT: Taken into account your additional info I suggest to check the project for

*

*cyclic dependencies

*units with the same name somewhere in the search path

For the cyclic dependencies you can use the free Unit Dependency Analyzer from ModelMakerTools. You can find the download link at the bottom of that page.

A: If you are absolutely sure that you compile the right source (.dpr paths!) and the uses parts are the same, it might be that Delphi can eliminate mutual references if very simple or unused.
IOW maybe the compiler lets it pass if A and B import eachother, but one of them doesn't use symbols from the other. As soon as you start using symbols (because of previously dead code becoming reachable by selecting the action), it turns into a mutual reference conflict.

A: As per request my comment as an answer.
Don't know why it may be happening, but if its any consolation, I have seen it happen in other situations as well. A build immediately following a change would fail, a compile, then a build would succeed.
What sometimes also helps in these situations is an explicit Save All before the compile/build.
I guess it may have something to do with timing and caching in the IDE. Possibly the compilation thread(s) that enable code-insight, error red lining etc are involved as well.


text:
Q: Problem with missing info from the wikipedia API this is my first question on StackOverflow so if I'm doing something wrong please tell me...
I've been doing some webscraping and am looking in particular for all the "Categories" certain music groups belong to in wikipedia. I am still very novice so I might be overlooking something extremely basic...
For this I am using the wikipedia API. It works great with some bands. For example if i look for Maroon 5
r = http.get("https://en.wikipedia.org/w/api.php?action=query&format=json&prop=categories&titles=Maroon_5")
r.json()

it returns this JSON file
{'continue': {'clcontinue': '512449|Articles_with_permanently_dead_external_links',
  'continue': '||'},
 'query': {'normalized': [{'from': 'Maroon_5', 'to': 'Maroon 5'}],
  'pages': {'512449': {'pageid': 512449,
    'ns': 0,
    'title': 'Maroon 5',
    'categories': [{'ns': 14,
      'title': 'Category:1994 establishments in California'},
     {'ns': 14, 'title': 'Category:222 Records artists'},
     {'ns': 14, 'title': 'Category:A&M Records artists'},
     {'ns': 14, 'title': 'Category:Adam Levine'},
     {'ns': 14,
      'title': 'Category:All Wikipedia articles needing words, phrases or quotes attributed'},
     {'ns': 14, 'title': 'Category:All articles with dead external links'},
     {'ns': 14, 'title': 'Category:American pop rock music groups'},
     {'ns': 14, 'title': 'Category:American soul musical groups'},
     {'ns': 14,
      'title': 'Category:Articles with dead external links from February 2020'},
     {'ns': 14, 'title': 'Category:Articles with hCards'}]}}}}

but with a lot of other bands, like "Active Child" for example, this file is returned:
r = requests.get("https://en.wikipedia.org/w/api.php?action=query&format=json&prop=categories&titles=Acid_Casuals")
r.json()

{'batchcomplete': '',
 'query': {'pages': {'-1': {'ns': 0, 'title': 'Acid Casuals', 'missing': ''}}}}

I have tried replacing the "%20" with "_" and nothing changes. Can someone tell me what is going on and how to fix it?
On a sidenote I've also noticed, that even for Maroon 5 a lot of categories are missing in the json. This is probably a related issue I'm guessing.
I would try delving into Beautifulsoup if all else fails, but I would still prefer to get this method working.
thanks a lot for your help

A: English Wikipedia does have an article named Maroon 5 but does not have any article titled Acid Casuals. The 'missing' key in response is an indicator of that. No article, no categories.


text:
Q: Create a table matrix with 2d arrays C# I am trying to create a program where you ask the user for a number, Create an array that is as close to square as you can and fill it with 1 to the user's specified number. You have to use a 2d array. Here is an example of what it would look like:
user input: 16
output:  1  2  3  4
        5  6  7  8
        9  10 11 12
        13 14 15 16
I have tried to do it by running it trough loops but it has not worked, I hope someone can guide me on how to do this

A: First let's get the user input:
int num;
while(!int.TryParse(Console.ReadLine(), out num) || num < 1)
{
    Console.WriteLine("Invalid number!");
}

after this calculate the side of the square:
var sideLength = (int)Math.Ceiling(Math.Sqrt(num));

then create the 2D array:
var array = new int[sideLength, sideLength];

and write the numbers into it:
for (int row = 0; row < sideLength; row++)
{
    for (int column = 0; column < sideLength; column++)
    {
        var value = row * sideLength + (column + 1);
        if (value > num)
            break;
        array[row, column] = value;
    }
}

but don't write anything higher then the user input, this will leave them 0, which is great because you want to display it from 1 so you can use the 0 to detect the end in case the user input is not a square number.
Now let's prepare a string to format the numbers. If you want all numbers to be the exact same length you can format it with int.ToString("0") where the number of 0s will set the length. Let's create a string which will make all number the same length. The user input is the longest possible number so you can use that to create the string:
var format = new string('0', num.ToString().Length);

Now print the array:
for (int row = 0; row < sideLength; row++)
{
    for (int column = 0; column < sideLength; column++)
    {
        var value = array[row, column];
        if (value == 0)
        {
            Console.WriteLine("");
            goto breakBoth;
        }
        Console.Write($"{value.ToString(format)} ");
    }
    Console.WriteLine("");
}
breakBoth:

This will put the same number of numbers in a line and there will the same amount of rows unless it finds a 0, then it will stop and the last line won't be a full line, this happens if the input wasn't a square number.
Let's look at the outputs:
Input: 16
Output:
01 02 03 04
05 06 07 08
09 10 11 12
13 14 15 16

Input: 14
Output:
01 02 03 04
05 06 07 08
09 10 11 12
13 14

If you want to display the 0s if it's not a full line you can remove the 0 check from the print part.
Can this be optimized?
Yes! The array is useless, it just contains incrementing numbers. If 2d arrays are not a requirement you can completely remove it and make some modifications to the print function.
int num;
while(!int.TryParse(Console.ReadLine(), out num))
{
    Console.WriteLine("Invalid number!");
}

var sideLength = (int)Math.Ceiling(Math.Sqrt(num));
var format = new string('0', num.ToString().Length);
for (int row = 0; row < sideLength; row++)
{
    for (int column = 0; column < sideLength; column++)
    {
        var value = row * sideLength + (column + 1);
        if (value > num)
        {
            Console.WriteLine("");
            goto breakBoth;
        }
        Console.Write($"{value.ToString(format)} ");
    }
    Console.WriteLine("");
}
breakBoth:

This code does the same thing but without 2d arrays.


text:
Q: IndexOutOfBounds using Javas imageio.write() to create byte array in png format I am using javax.imageio.ImageIO to write a BufferedImage b into a byte array and finally to a file. 1 out of 10 times when creating the byte array, a java.lang.IndexOutOfBoundsException is thrown. It is not reproducible by just using the same image though.
BufferedImage img = ...
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// the next line will lead to the exception being thrown
ImageIO.write(img, "png", baos);
byte[] byteArray = baos.toByteArray()

Result is:
java.lang.IndexOutOfBoundsException
Line | Method
->>  166 | seek                       in
javax.imageio.stream.FileCacheImageOutputStream
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|    227 | close                      in     ''
|   1570 | write . . . . . . . . . .  in javax.imageio.ImageIO

I found a bug report, seemingly describing the same problem. But I cannot find a fix though it's from 2010.
Any ideas? Work arounds? Links to ressources?
Help is highly appreciated!

A: It is indeed a bug.
Though, if you read through the report you'll see...

CUSTOMER SUBMITTED WORKAROUND :
Use a memory cache.

Try to utilize a MemoryCacheImageOutputStream instead, until the bug is squashed eventually.
ImageIO.write(img, "png", new MemoryCacheImageOutputStream(baos));


text:
Q: CFML - query row to structure I would like to handle a row from a query by a function, where I pass the row as a structure.
ideally...
<cfloop query="myquery">
 #myfunction(#row#)#
</cfloop>

I could set it up like this too...
<cfloop query="myquery">
 #myfunction(#col1#,#col2#,#col3#,#col4#)#
</cfloop>

but I don't want to. I haven't been able to finda simple way of extracting a row, But I thought I'd ask.

A: Ben Nadel has posted a blog post about this where he gives an example UDF that converts a query to a struct, and it accepts an optional row argument that allows you to turn an single row in that query to a struct.  Take a look here.

A: This is the Class from Ben's site without the comments
<--- --------------------------------------------------------------------------------------- ----

    Blog Entry:
    Ask Ben: Converting A Query To A Struct

    Author:
    Ben Nadel / Kinky Solutions

    Link:
    http://www.bennadel.com/index.cfm?event=blog.view&id=149

    Date Posted:
    Jul 19, 2006 at 7:32 AM

---- --------------------------------------------------------------------------------------- --->

<cffunction name="QueryToStruct" access="public" returntype="any" output="false"
    hint="Converts an entire query or the given record to a struct. This might return a structure (single record) or an array of structures.">
    <cfargument name="Query" type="query" required="true" />
    <cfargument name="Row" type="numeric" required="false" default="0" />

    <cfscript>
        var LOCAL = StructNew();
        if (ARGUMENTS.Row){
            LOCAL.FromIndex = ARGUMENTS.Row;
            LOCAL.ToIndex = ARGUMENTS.Row;
        } else {
            LOCAL.FromIndex = 1;
            LOCAL.ToIndex = ARGUMENTS.Query.RecordCount;
        }
        LOCAL.Columns = ListToArray( ARGUMENTS.Query.ColumnList );
        LOCAL.ColumnCount = ArrayLen( LOCAL.Columns );
        LOCAL.DataArray = ArrayNew( 1 );
        for (LOCAL.RowIndex = LOCAL.FromIndex ; LOCAL.RowIndex LTE LOCAL.ToIndex ; LOCAL.RowIndex = (LOCAL.RowIndex + 1)){
            ArrayAppend( LOCAL.DataArray, StructNew() );
            LOCAL.DataArrayIndex = ArrayLen( LOCAL.DataArray );
            for (LOCAL.ColumnIndex = 1 ; LOCAL.ColumnIndex LTE LOCAL.ColumnCount ; LOCAL.ColumnIndex = (LOCAL.ColumnIndex + 1)){
                LOCAL.ColumnName = LOCAL.Columns[ LOCAL.ColumnIndex ];
                LOCAL.DataArray[ LOCAL.DataArrayIndex ][ LOCAL.ColumnName ] = ARGUMENTS.Query[ LOCAL.ColumnName ][ LOCAL.RowIndex ];
            }
        }
        if (ARGUMENTS.Row){
            return( LOCAL.DataArray[ 1 ] );
        } else {
            return( LOCAL.DataArray );
        }
    </cfscript>
</cffunction>

usage...
<!--- Convert the entire query to an array of structures. --->
<cfset arrGirls = QueryToStruct( qGirls ) />

<!--- Convert the second record to a structure. --->
<cfset objGirl = QueryToStruct( qGirls, 2 ) />

A: found a little more elegant looking solution, for single row
<cfscript>
    function GetQueryRow(query, rowNumber) {
        var i = 0;
        var rowData = StructNew();
        var cols    = ListToArray(query.columnList);
        for (i = 1; i lte ArrayLen(cols); i = i + 1) {
            rowData[cols[i]] = query[cols[i]][rowNumber];
        }
        return rowData;
    }
</cfscript>

A: Adobe ColdFusion 11 introduced QueryGetRow which converts a row from a query into a struct.

A: Another solution would be:
function QueryToStruct(query){
    var cols    = ListToArray(query.columnList);
    var salida  = query.map(function(v=0,i,a){
                       return {'#cols[1]#':v};
                  });
    return ValueArray(salida,'#cols[1]#');
}