text:
Q: MVC Parameter Binding from JSON into multiple parameters I'm receiving JSON data from this method:
function CallAPI(controllerName, functionName, sendData, callback) {
    var ajax = new XMLHttpRequest();
    ajax.onreadystatechange = function () {
        if (ajax.readyState == 4) {
            if (ajax.status == 200) {
                var response = JSON.parse(ajax.responseText);
                callback(response);
            }
            else {
                callback();
            }
        }
    }
    ajax.open("POST", "http://" + window.location.host + "/API/" + controllerName + "/" + functionName, true);
    ajax.setRequestHeader('Content-Type', 'application/json');
    ajax.send(JSON.stringify(sendData));
}

function someRequest() {
    var data = {};
    data.userID = 1;
    data.someValue = 20;
    CallAPI("Home", "Add", data, function (response) {
        if(response) {
            alert(response.Message); //This property always exist
        }
        else {
            alert("internet/connection error.");
        }
    });
}

And my Controller is:
[System.Web.Http.HttpPost]
public HttpResponseMessage Add(int userID, int someValue)
{
    //Here!
    return Request.CreateResponse(HttpStatusCode.OK, new GenericResponseAPI() { Status = false, Message = "Generic Message." });
}

I can create a model and MVC would bind it accordingly, but I have so many of these requests that I don't want to create various models (or a big one containing all of the properties), but instead have these simple functions with basic type parameters like this.
What do I need to do to be able to work with the controller function above, without changing the content-type of the incoming message?
Edit: I found a workaround with this:
[System.Web.Http.HttpPost]
public HttpResponseMessage Add(JObject jObject)
{
    int userID = (int)jObject.getValue("userID").ToObject(typeof(Int32));
    int someValue = (int)jObject.getValue("someValue").ToObject(typeof(Int32));

    return Request.CreateResponse(HttpStatusCode.OK);
}

A: I imagine the reason is that your function signature is:
function CallAPI(controllerName, functionName, sendData, callback)

and you're calling
CallAPI("Home", "Add", function (response) { ... })

So you're never actually sending data in the format MVC is expecting.
I'd double check this by using something like Fiddler and by debugging your JavaScript code using your browsers dev-tools.


text:
Q: SQL Server 2016 Log shipping restore job stuck SQL server 2016 log shipping restore job will run every 15mins, Database size is 1TB, Job will not take two minutes, Yesterday job was running for last 13 hours and the database is in "InRecovery" state, The job status is InProgress, couldn't see any blocking on the server and SPID of the restore is in suspended state, anyhow killed the restore job reconfigured the log shipping, I just want to know the possible reasons to create RCA to this issue, I do not see any info in event or SQL error logs since i killed the job manually.We do not have IO or storage issues also.

A: It probably could be for various reasons-

*

*Compare the volume of data that might would have generated additional log backup size as compared to normal days. Compare the difference between good and bad durations vs amount of data u see.

*I am not sure what is the recovery mode- do you allow secondary in read mode by keeping standby ? If yes I have seen issues and slowness based on LS logic to keep switching between no recovery mode and standby mode.

*You need to have baseline for other metrics like CPU memory and storage numbers for good vs bad run.

redpajama_set_name: RedPajamaStackExchange


text:
Q: MySQL to not return same results I have a table with list of customers:
customer

c_id    c_name      c_email     c_role
1       abc1        a1@abc.com  Dev
2       abc2        a2@abc.com  Dev
3       abc3        a3@abc.com  Dev
4       abc4        a4@abc.com  Dev
5       abc5        a5@abc.com  Dev
6       abc6        a6@abc.com  Dev
7       abc7        a7@abc.com  Dev
8       abc8        a8@abc.com  Dev
9       abc9        a9@abc.com  Dev

I query the table in the following way:
select * from customer where c_role = 'Dev' order by c_id limit 2;

So, I get the results with:
c_id    c_name      c_email     c_role
1       abc1        a1@abc.com  Dev
2       abc2        a2@abc.com  Dev

The business requirements says that if any records are accessed by a set of users for last 3 days, then those should not return in the subsequent query output.
So, if the user runs a query again for the next 3 days:
select * from customer where c_role = 'Dev' order by c_id limit 2;

The result should be:
c_id    c_name      c_email     c_role
3       abc3        a3@abc.com  Dev
4       abc4        a4@abc.com  Dev

Can anyone help me how to create this kind of rule in MySQL?

A: Adding a new column in current table is not going to help you.
You will have to create another table where you store all c_ids a user has accessed and the datetime when the query was executed.
CREATE TABLE IF NOT EXISTS `access_record` (
    `id` INT(11) NOT NULL AUTO_INCREMENT ,
    `c_id` INT(11) NOT NULL , // id of the record which user accessed
    `user_id` INT(11) NOT NULL , // id of the user who accessed the record
    `accessed_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
    PRIMARY KEY (`id`)
);

So whenever the user runs the next query you can use this table to know if user has already accessed a record or not and then use those c_ids to exclude them from next result set.
SELECT
    c.c_id, c.c_role,c.c_name,c.c_email
FROM
    customer AS c
WHERE
    c.c_role = 'Dev'
    AND c.c_id NOT IN (
        SELECT
            ar.c_id
        FROM
            access_record AS ar
        WHERE ar.user_id = 1  // ofcourse this will change with each user (current user in your case I assume)
            AND ar.accessed_at > DATE_SUB(NOW(), INTERVAL 3 DAY)
     )
     ORDER BY c.c_id LIMIT 2;

This will give you all records which were not accessed by specific user within last 3 days.
I hope this helps.
Answering @dang's question in comment

How do I populate access_record when a query runs?

When you have fetched all the records then you extract c_ids from those records then you insert those c_ids into the access_record table.
In MYSQL this query should do the trick
INSERT INTO access_record (c_id,user_id)

SELECT
    c.c_id, 1 // user_id of the user who is fetching records
FROM
    customer AS c
WHERE
    c.c_role = 'Dev'
    AND c.c_id NOT IN (
        SELECT
            ar.c_id
        FROM
            access_record AS ar
        WHERE ar.user_id = 1  // ofcourse this will change with each user (current user in your case I assume)
            AND ar.accessed_at > DATE_SUB(NOW(), INTERVAL 3 DAY)
     )
     ORDER BY c.c_id LIMIT 2;

You can also fetch those c_ids with one query then use second query to insert those c_ids into the access_record table.
If you have all your records fetched in $records then
$c_ids = array_column($temp, 'c_id'); // get all c_ids from fetched record array

Now run a query to insert all those c_ids.

A: I would add an extra table with users and accessdate. And make the business logic update those on access. For example:
user | accessdate | c_id

A: Your 'customer' table is data about customers. That is all it should have.
However, your selection criteria is really not what it appears to be. What business requirements want you to implement is a feed, or pipeline, with the selection acting as a consumer, being fed by un-accessed customers.
Each user (or group of users, ie: 'set of users') needs it's own feed, but that can be managed by a single table with a distinguishing field. So we need a user_group table to group your 'set of users'.
// user_group
g_id    g_data
201     abc1
202     abc2
203     abc3

We will need to populate customer_feed with the access timestamps for each customer. We can add a foreign keys to delete customers and user_groups when they are deleted, but we will need update the customer feed when we use it.
create table customer_feed (
  c_id int(11) not null,
  g_id int(11) not null,
  at timestamp not null,
  primary key (c_id, g_id),
  constraint customer_fk foreign key (c_id) references customer on delete cascade
  constraint user_group_fk foreign key (g_id) references user_group on delete cascade,
);

// customer_feed
c_id    g_id   at
101     201    2018-11-26 07:40:21
102     201    2018-11-26 07:40:21
103     201    2018-11-26 07:40:22

When we want to read the customer data, we must do three queries:

*

*Update the feed for the current user-group.

*Get the users from the feed

*Mark the users in the feed as consumed.

So, let's say we are using user_group 201.
When we update the feed, any new users to the feed are available to be read straight away,we give them a timestamp which is very early. So we can commemorate the battle of hastings...
// 1. update the customer_feed for user_group 201
insert into customer_feed(select c.c_id,201,TIMESTAMP('1066-10-14')
from customer c left join customer_feed f
on c.c_id = f.c_id and f.g_id=201 where f.c_id is null);

we select from the customer and the feed... We only accept records whose access dates are less than three days ago. This is the query you originally had, but with the feed restrictions.
// 2. read from feed for user_group 201
select c.* from customer c,customer_feed f where c.c_role='Dev'
and f.g_id=201 and f.c_id=c.c_id
and f.at < date_sub(now(), interval 3 day) limit 2

..and now we need to mark the values from the feed as being consumed. So, we gather the c_id we have selected into a list of c_id, eg: '102,103', and we mark them as consumed.
// 3. Mark the feed as consumed for user_group 201
update customer_feed set at=now() where g_id=201 and c_id in '102,103'

A: Add a new column in your customer table like start_accessing and then you can run the query:
SELECT *
    FROM   customer
    WHERE  c_role = 'Dev'
           AND Date_add(start_accessing, INTERVAL 3 day) >= Curdate()
    ORDER  BY c_id
    LIMIT  2;

start_accessing  will be the column that will save when the user started accessing the resource.

A: Add a datetime stamp to the table and query from that.

A: There might be a way to get a 3 day rotation without  having to change the tables.
By calculating batches of devs.
And calculate the current dev batch based on the current date.
The example below is for MySql 7.x (no window functions)
set @date = current_date;
-- set @date = date('2020-07-04');

set @dayslimit = 3;
set @grouplimit = 2;
set @devcnt = (select count(*) cnt
       from test_customer
        where c_role = 'Dev');
set @curr_rnk = ((floor(datediff(@date, date('2000-01-01')) / @dayslimit)%floor(@devcnt / @dayslimit))+1);

select c_id, c_name, c_email, c_role
-- , rnk
from
(
   select t.*,
    case when @rn := @rn +1 then @rnk := ceil((@rn/@grouplimit)%(@devcnt+1/@grouplimit)) end as rnk
   from test_customer t
   cross join (select @rn:=0, @rnk:= null) vars
   where c_role = 'Dev'
   order by c_id
) q
where rnk = @curr_rnk
order by c_id
limit 2;

A test on rextester here


text:
Q: android check heap memory in run time I have an android app, this application connect to server to download images, but this images  has more than one copy, first copy 1600 * 1080 pixel and the second is 800 * 540 ...
so the device should send tag to server to download the good images for this device
I used many ways to check the device memory or density but the results was not clear enough to make a decision, here some code I used:
 float density = getResources().getDisplayMetrics().density;
 long mem = Runtime.getRuntime().freeMemory();
 long heap = Debug.getNativeHeapAllocatedSize();

the results was for 3 devices like this:
samsumg tab 10 inch = 1.0 , 745464 , 3249552 byte
china tab 7 inch = 1.0 , 559944 , 2789016 byte
htc moble 3.4 inch = 1.5 , 1760904 , 8942736 byte
as the result showed the htc is the better but it was not because I can't view the highest resolution on it, but on the other devices it was very good
the error msg:
java.lang.OutOfMemoryError: bitmap size exceeds VM budget(Heap Size=7687KB, Allocated=3356KB, Bitmap Size=25092KB)
Any help in this issue ?

A: Your decision should depend on two factors:

*

*Screen density.

*Screen Size.
In your case you had received hdpi drawables on htc, but it's small device, so it's not required to show large image with more details on small device.
for more information for loading large bitmaps efficiently:
http://developer.android.com/training/displaying-bitmaps/load-bitmap.html


text:
Q: Google Cloud - Load Balancer / Global Static IP blocked by China We have recently experienced two incidents, where Global Static IPs are blocked in China. Out of 12, only two IPs are blocked while remaining are working fine. These two IPs have been working fine for more than 8 months now.
I don't know How Chinese Govt interprets these IPs (probably thinking Google Search Engine).
Any clues ? Why 2 out of 12 Ips are blocked? Is there a criteria? How do we keep ourselves not blocked in China ?
Can google support help with this? Can we get the global static IPs moved into our company name (whois info on the IPs) ?
We would have to go back to AWS if we cant get around this problem.
Thanks!


text:
Q: How to change Google account after signed in I use javascript API because i want fully customized button, themes from Google not enough for my needs. I wrote small example sandbox. Problem is after sucessfull signed in, i cant choose another account. I try change configuration, but without result.

A: I read more about this, and found answer there Google identity docs: How it works:

*

*One Tap and Automatic sign-in are triggered only when users have
signed in to Google before loading your web pages.

*With the Sign In With Google button flow, users are prompted to
sign-in to Google when the button is pressed, establishing an active Google session

My conclusion: in order for the user to choose another account that does not have a current session in the browser, you need to use Google button instead of On tap. You can create a button using google.accounts.id.renderButton. Setting up Google button can only be done within the framework of the API described in section GsiButtonConfiguration, because render creates a button inside an iframe and there is no access to it.
i changed my sandbox for demonstrate this


text:
Q: Android - Spinner async download does not function correctly Upon activation of any button in the spinner the progress dialog comes up but nothing happens.  I had this working perfectly with buttons but don't understand what is wrong here when transitioning to spinners.  Anyone spot the reason why the download doesn't start up correctly?
public class SpinnerActivity extends Activity {

public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private ProgressDialog mProgressDialog;

Spinner spDownloadFrom;
private ArrayAdapter<CharSequence> spinnerArrayAdapter;
String url[] = {"http://www.becker.cl/bases.pdf",
        "http://www.pitt.edu/documents/campusmap0607.pdf", "http://www.aara.ca/reg3317/web_page_doc.pdf",
        "www.dataprotection.ie/documents/guidance/GuidanceFinance.pdf", "http://www.fmbb2012.com/JumpingQualifica1.pdf",
        "http://www.consulatdumaroc.ca/coloniefh22012.pdf", "http://www.rgrdlaw.com/media/cases/140_Complaint.pdf" };
String name[] = { "bases.pdf", "campusmap0607.pdf", "web_page_doc.pdf", "GuidanceFinance.pdf",
        "JumpingQualifica1.pdf", "coloniefh22012.pdf", "140_Complaint.pdf", };

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mProgressDialog = new ProgressDialog(SpinnerActivity.this);
    mProgressDialog.setMessage("Please be patient, file downloading...");
    mProgressDialog.setIndeterminate(false);
    mProgressDialog.setMax(100);
    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

    spDownloadFrom = (Spinner) findViewById(R.id.Spinner01);

    spinnerArrayAdapter = new ArrayAdapter<CharSequence>(this,
            android.R.layout.simple_spinner_item, name);
    spinnerArrayAdapter
            .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spDownloadFrom.setAdapter(spinnerArrayAdapter);

    spDownloadFrom.setOnItemSelectedListener(new SpinnerListener(
            spDownloadFrom));
}

public class SpinnerListener implements OnItemSelectedListener {
    Spinner sp;

    public SpinnerListener(View v) {
        sp = (Spinner) findViewById(v.getId());
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View v, int arg2,
            long arg3) {
        // Call to download class
        startDownload(arg2);

    }

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

    }
}

private void startDownload(Integer... url) {
    DownloadFile downloadFile = new DownloadFile();
    downloadFile.execute();

}

class DownloadFile extends AsyncTask<String, Integer, String> { // put your
                                                                // download
                                                                // code

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mProgressDialog.show();
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        super.onProgressUpdate(progress);
        mProgressDialog.setProgress(progress[0]);
    }

    @Override
    protected String doInBackground(String... aurl) {
        try {

            URL url = new URL(aurl[0]);
            URLConnection connection = url.openConnection();

            connection.connect();
            int fileLength = connection.getContentLength();
            int tickSize = 2 * fileLength / 100;
            int nextProgress = tickSize;

            Log.d(

            "ANDRO_ASYNC", "Lenght of file: " + fileLength);

            InputStream input = new BufferedInputStream(url.openStream());

            String path = Environment.getExternalStorageDirectory()
                    + "/Android/Data/"
                    + getApplicationContext().getPackageName() + "/files/" + name;
            File file = new File(path);
            file.mkdirs();
            File outputFile = file;

            OutputStream output = new FileOutputStream(outputFile);

            byte data[] = new byte[1024 * 1024];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                total += count;
                if (total >= nextProgress) {
                    nextProgress = (int) ((total / tickSize + 1) * tickSize);
                    this.publishProgress((int) (total * 100 / fileLength));
                }
                output.write(data, 0, count);
            }

            output.flush();
            output.close();
            input.close();
            mProgressDialog.dismiss();

        } catch (Exception e) {
        }
        return null;
    }

    protected void onProgressUpdate(String... progress) {
        Log.d("Downloading", progress[0]);

    }

    @Override
    protected void onPostExecute(String unused) {

        File file = new File(Environment.getExternalStorageDirectory()
                + "/Android/Data/"
                + getApplicationContext().getPackageName()
                + "/files/" + name);
        Intent testIntent = new Intent(Intent.ACTION_VIEW);
        testIntent.setType("application/pdf");
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        Uri uri = Uri.fromFile(file);
        intent.setDataAndType(uri, "application/pdf");
        try {
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(SpinnerActivity.this,
                    "No Application Available to View PDF",
                    Toast.LENGTH_LONG).show();
        }
    }
}
}

A: In your startDownload method, you are passing in url, which is an array of String type. In doInBackground of your AsyncTask, you are only using the first index of url, which you have set as "", so you're passing in an empty String.
To pass in the URL you are expecting, change the startDownload method to accept an int value. Then in the onItemSelected method, pass in the position, which you have named as arg2 (The parameter names should be parent, view, position, and id, in that order. Easier to understand what they mean). Then when you call downloadFile.execute, pass in url[position].
Edit
Change your download method to like this:
private void startDownload(int position) {
    DownloadFile downloadFile = new DownloadFile();
    downloadFile.execute(url[position]);
}

That should give you the expected results, assuming the URLs you are using are valid. Also, your dialog isn't going away because you forgot to call mProgressDialog.dismiss() in onPostExecute.


text:
Q: How to get result in IResultFilter in MVC 4? I have a custom filter action:
void IResultFilter.OnResultExecuting (ResultExecutingContext filterContext)
{
      // code
      var result = ((JsonResult)filterContext.Result).Data;
      // code
}

The action controller returns a JsonResult and I can't take the values that are displayed in the view, when I inspect 'result' I can see the values, the JsonResult is a record modified from a database, I want take these values to build a log in other table.
result is a type of: object {ProjectName.Models.ModelName}

A: Something like this?
void IResultFilter.OnResultExecuting (ResultExecutingContext filterContext)
{
      // code
      var jsonResult = (JsonResult)filterContext.Result;
      var model = (ProjectName.Models.ModelName)jsonResult.Data;
      var propertyValue = model.PropertyName;
      // code
}


text:
Q: How to update and return a record using an interface in F# In C#, I am using the following function which I want to move into F#:
public virtual void BringToTop(LayersEnum _TopMostLayer)
        {
            if (LayerName == _TopMostLayer)
            {
                ZIndex = 10;
                Visibility = Visibility.Visible;
            }
            else
            {
                ZIndex = DefaultZIndex;
                Visibility = Visibility.Hidden;
            }
        }

Assuming I have the following F# definitions, how is this implemented in F#:
type DocumentRadioButtons = ChartLayer | WritingLayer | ImageLayer | TranscriptionLayer | PublisherLayer

module WritingLayer=

type Model =
    {  Name: string
       Visibility: bool
       DefaultZIndex: int
       ZIndex: int
    }
    interface ILayer with
         member this.Name with get() = this.Name
         member this.Visibility with get() = this.Visibility
         member this.DefaultZIndex with get() = this.DefaultZIndex
         member this.ZIndex with get() = this.ZIndex

type ProgressNoteWin = {
       ConfirmState: ConfirmState option
       Encounter: view_doctor_encounter
       LastName: string
       DocumentLayer: DocumentRadioButtons
       WritingLayer: WritingLayer.Model
       ImageLayer: ImageLayer.Model
       ChartLayer: ChartLayer.Model
      }

My very FAILED attempt is:
let BringToTop rb (layer:ILayer) =

                     if rb.ToString() = layer.Name then {layer with Visibility =true} else {layer with Visibility = false }

                { m with WritingLayer = BringToTop documentRadioButton m.WritingLayer},

Error: The record label "Visibility" is not defined
Thank you for any help.
#Addendum:
Ultimately, I would like to implement the interface on the different record types of WritingLayer.Model, ImageLayer.Model, and ChartLayer.Model to be used as:
{m with WritingLayer = BringToTop rb m.WritingLayer;
  ImageLayer = BringToTop rb m.ImageLayer;
  ChartLayer = rb m.ChartLayer}

Thank you for your consideration.

A: This code won't work as-is:
let BringToTop rb (layer:ILayer) =
    if rb.ToString() = layer.Name then
        { layer with Visibility =true }
    else
        { layer with Visibility = false }

This is because F# doesn't implicitly downcast to a type that implements the interface.
First potential solution:
Switch from being passed an ILayer to just being passed a Model directly. Then your code will work.
Second potential solution:
I'm assuming that since you have an interface, you want to pass that around as the data type rather than the model type itself. If that is the case, then I'd recommend using an Object Expression to update the data like so:
let mkILayer visible (layer: ILayer) =
    { new ILayer with
         member this.Name = layer.Name
         member this.Visibility = visible
         member this.DefaultZIndex = layer.DefaultZIndex
         member this.ZIndex = layer.ZIndex }

let BringToTop rb (layer:ILayer) =
    if rb.ToString() = layer.Name then
        mkILayer true layer
    else
        mkILayer false layer

Third potential solution
If you're fine with downcasting, you can shadow your first layer definition like so:
let BringToTop rb (layer:ILayer) =
    if rb.ToString() = layer.Name then
        let layer = layer :?> Model
        { layer with Visibility =true }
    else
        let layer = layer :?> Model
        { layer with Visibility = false }

But usually whenever a downcast is involved that's a code smell, so I'd really recommend constructing a new instance of the interface instead.

A: I never could do this the way I wanted to--by using the ILayer interface to update and return the record type it was associated with. I would be most interested in a better way to do this.
What I did end up doing was simply to define three specific functions, one for each type as:
let BringToTopWritingLayer rb layer:WritingLayer.Model =
                    if rb.ToString() = (layer :>ILayer).Name
                    then
                       {layer with Visibility = true}
                    else
                       {layer with Visibility = false}

                let BringToTopImageLayer rb layer:ImageLayer.Model =
                    if rb.ToString() = (layer :>ILayer).Name
                    then
                       {layer with Visibility = true}
                    else
                       {layer with Visibility = false}

                let BringToTopChartLayer rb layer:ChartLayer.Model =
                    if rb.ToString() = (layer :>ILayer).Name
                    then
                       {layer with Visibility = true}
                    else
                       {layer with Visibility = false}

with usage as:
{ m with DocumentLayer = documentRadioButton;
                      WritingLayer = BringToTopWritingLayer documentRadioButton m.WritingLayer;
                      ImageLayer = BringToTopImageLayer documentRadioButton m.ImageLayer;
                      ChartLayer = BringToTopChartLayer documentRadioButton m.ChartLayer}

This seems highly redundant, but it does seem to compile correctly.
A better answer would be most appreciated.


text:
Q: Relação muitos para muitos entre várias tabelas Eu sei que entre duas tabelas numa relação de muitos para muitos 'precisamos' (não é obrigatório, mas facilita) de uma terceira tabela pivot que é o que relaciona convencionalmente os ids de uma com os ids de outra. Até aí tudo bem. Então e por exemplo para fazer uma árvore geneológica? Teriamos de criar uma tabela pivot por cada duas tabelas?  Em baixo está uma imagem para exemplificar uma relação entre pais/filhos em que existe uma tabela pivot (pais_filhos) no 'apoio':
Tabelas: pais, filhos, pais_filhos respetivamente. E por fim o INNER JOIN entre elas

E agora se quisessemos adicionar uma tabela avos teriamos de criar outra pivot para relacionar os ids dos pais com os ids dos avós? E depois para adicionar bisavós também? Ou existe uma maneira 'mais fácil' de conseguir isto? Ou seja, sem 'precisar' de criar uma tabela pivot por cada duas tabelas? Eu sei que poderia nem utilizar uma tabela pivot, bastava arranjar um separador entre ids, por ex na tabela dos filhos criar uma coluna id_pais e aí inseria os ids no formato 1|2 e para os avós seria uma coluna ids_avos com 1|2|3|4, e bisavos também faria o mesmo? Parece-me quase igualmente 'trabalhoso' se tivessemos tri, tetra, penta... avos.
Existe outra maneira que eu não mencionei aqui e desconheço para fazer isto? Qual a melhor maneira para fazer isto?

A: Com auto-relacionamento você pode chegar a uma solução melhor e mais enxuta, desde que seja por "paternidade". Se você continuar nesse modelo e nessa solução, a cada nível, surgirá uma nova tabela.
DROP TABLE IF EXISTS PESSOA;

CREATE TABLE PESSOA (
    CODIGO BIGINT NOT NULL,
    NOME VARCHAR(200) NOT NULL,
    ANCESTRAL BIGINT DEFAULT NULL,
    PRIMARY KEY (CODIGO),
    KEY ANCESTRAL (ANCESTRAL),
    CONSTRAINT FK_ANCESTRAL FOREIGN KEY (ANCESTRAL) REFERENCES PESSOA(CODIGO)
);

INSERT INTO PESSOA VALUES (1, 'SEU AVO', NULL);
INSERT INTO PESSOA VALUES (2, 'SEU PAI', 1);
INSERT INTO PESSOA VALUES (3, 'VOCE', 2);

Você poderia ter mais um atributo que seria grau (em relação ao ancestral). Trabalhando com consultas específicas você conseguirá bons resultados. Não sei se atende o que precisa.

A: Sim existe várias outras maneiras.
Uma delas: faz uma tabela pessoas com os nomes e dados das pessoas e uma tabela para os relacionamentos, em que tu tens o tipo do relacionamento, se pai ou filho e quem são as pessoas no relacionamento.
Por exemplo:
André (filho de) Francisco (pai de) Luiz
Francisco (avo de) Luiz

Então:
pessoas            relacionamento
-------            --------------
oid nome           oid id1 id2 tipo
1   André          1   1   2   filho
2   Francisco      2   1   3   pai
3   Luiz           3   2   3   avo
etc.               4   3   2   neto
                   etc.

Obviamente que coloquei aqui o tipo como varchar diretamente, mas pode/deve ser colocada em uma tabela separada para manter a forma normal e tudo o mais.


text:
Q: APScheduler store job in custom database of mongodb I want to store the job in mongodb using python and it should schedule on specific time.
I did googling and found APScheduler will do. i downloaded the code and tried to run the code.
It's schedule the job correctly and run it, but it store the job in apscheduler database of mongodb, i want to store the job in my own database.
Can please tell me how to store the job in my own database instead of default db.

A: Simply give the mongodb jobstore a different "database" argument. It seems like the API documentation for this job store was not included in what is available on ReadTheDocs, but you can inspect the source and see how it works.


text:
Q: AWS RDS for PostgreSQL Connection attempt timed out error I created postgresql rds in aws with terraform. I'm checking from the aws console, everything seems normal. But I'm trying to connect to database with DBeaver but I can't connect. Likewise, I can't make the ssh connection for the ec2 I created, maybe there is a connection.
The terraform codes I wrote:
# postgres-db/main.tf
resource "aws_db_instance" "default" {
  allocated_storage      = 20
  storage_type           = "gp2"
  engine                 = var.engine
  engine_version         = var.engine-version
  instance_class         = var.instance-class
  db_name                = var.db-name
  identifier             = var.identifier
  username               = var.username
  password               = var.password
  port                   = var.port
  publicly_accessible    = var.publicly-accessible
  db_subnet_group_name   = var.db-subnet-group-name
  parameter_group_name   = var.parameter-group-name
  vpc_security_group_ids = var.vpc-security-group-ids
  apply_immediately      = var.apply-immediately
  skip_final_snapshot    = true
}

module "service-db" {
  source = "./postgres-db"

  apply-immediately      = true
  db-name                = var.service-db-name
  db-subnet-group-name   = data.terraform_remote_state.server.outputs.db_subnet_group
  identifier             = "${var.app-name}-db"
  password               = var.service-db-password
  publicly-accessible    = true # TODO: True for now, but should be false
  username               = var.service-db-username
  vpc-security-group-ids = [data.terraform_remote_state.server.outputs.security_group_allow_internal_postgres]
}

resource "aws_security_group" "allow_internal_postgres" {
  name        = "allow-internal-postgres"
  description = "Allow internal Postgres traffic"
  vpc_id      = aws_vpc.vpc.id

  ingress {
    from_port   = 5432
    to_port     = 5432
    protocol    = "tcp"
    cidr_blocks = [aws_vpc.vpc.cidr_block, "0.0.0.0/0"] # TODO: Remove public IP
  }
}

In the research I did, it was written things like edit the security rules or set it to public, it seems like that anyway.
Security group inbound rules
Public accessible
How can I solve this problem can you please help?

A: I solved my problem by setting the subnet group to public.
module "service-db" {
  source = "./postgres-db"

  apply-immediately      = true
  db-name                = var.service-db-name
  db-subnet-group-name   = data.terraform_remote_state.server.outputs.db_subnet_group_public
  identifier             = "${var.app-name}-db"
  password               = var.service-db-password
  publicly-accessible    = true # TODO: True for now, but should be false
  username               = var.service-db-username
  vpc-security-group-ids = [data.terraform_remote_state.server.outputs.security_group_allow_internal_postgres]
}

resource "aws_db_subnet_group" "private" {
  name       = "${var.server_name}-db-subnet-group-private"
  subnet_ids = aws_subnet.private.*.id

  tags = {
    Name = "${var.server_name} DB Subnet Group Private"
  }
}

resource "aws_db_subnet_group" "public" {
  name       = "${var.server_name}-db-subnet-group-public"
  subnet_ids = aws_subnet.public.*.id

  tags = {
    Name = "${var.server_name} DB Subnet Group Public"
  }
}


text:
Q: Is there way to parse tr returned by 'this'? Each row of my table has a button at the end of the row, which has an addEventListener like this,
button.addEventListener ("click", function() {
   deleteSummary(this);
});

function deleteSummary(oButton)
{
    console.log(oButton.parentNode.parentNode.innerHTML)
}

the console.log shows like this,
966	TypeA	1234	10,000	9,861	139	2021-01-02	3	7	8	7	89	9	8	7	1	<button>delete</button>

But I have no idea how to parse(?) it.
I always found answers you use document.getElementById() when googling.
Thanks

A: You should not aim to parse HTML. You have access to the DOM, so stick with that. You already found the tr element successfully, and then you can for instance use its cells property to get access to all the td elements, and you could map that list of cells to their text content. That way you get a standard array with all the cell texts of that particular row.

let buttons = document.querySelectorAll("td>button");
for (let button of buttons) {
    // Your code:
    button.addEventListener ("click", function() {
       deleteSummary(this);
    });
}

function deleteSummary(oButton) {
   let tr = oButton.parentNode.parentNode;
   let data = Array.from(tr.cells, cell => cell.textContent);
   data.pop(); // Optional: get rid of the column with the delete button
   console.log(data);
}

     966
     TypeA
     1234
     10,000
     2021-01-02
     <button>delete</button>

     123
     TypeB
     9988
     29,999
     2020-09-20
     <button>delete</button>


text:
Q: Android - How to target different architectures with Affective SDK? I've been playing around with the Affective Android SDK and found that once the apk is built it only contains the native library for armeabi-v7 architecture

does it mean that if we use this SDK we are going to be only targeting users with only this type of phones?
Have anyone managed to use Affective SDK on x86 and mips architectures?

A: Affectiva's SDKs are packaged differently depending on the OS being used. At the moment Android support is limited to the arm architecture.
Linux on the other had as both x86 and arm architecture support:
https://affectiva.readme.io/docs/getting-started-with-the-affectiva-sdk-for-linux


text:
Q: How to I relate the signature algorithms of a Windows certificate, with the parameters for signing with SignTool? We have a PowerShell script written years ago by someone who has moved on, to sign our ClickOnce deployments. This has worked well, until recently when the certificate expired. I'm tasked with updating the PowerShell script to incorporate the new signing certificate we recently purchased.
I put the new certificate into the Certificate store, per the instructions from the previous maintainer. I've made modifications to the PowerShell script, fixing other bugs as they've come along, but I'm at a place where I don't know how to relate the details of the certificate with the parameters for SignTool.exe. Looking at the properties of the certificate, from the Details view, I see the following relevant values:

*

*Signature algorithm: sha384RSA

*Signature hash algorithm: sha384

*Thumbprint algorithm: sha1

Looking at Microsoft's SignTool documentation page for the sign command I see values used by the PowerShell such as /td and /fd, but I don't know which relates to the values displayed in the properties for the certificate. Also, I'm not certain that I need the thumbprint algorithm. According to the Microsoft page I referenced it should be used if working with multiple certificates, which the PowerShell script is not.
Here is what is currently in the PowerShell script for signing the ClickOnce app:
Get-AuthenticodeSignature *.exe,*.dll | ? Status -eq NotSigned | % Path | %{&$signtool sign /tr $timestamp /td sha384 /fd sha384 $hash $_ }
That now gives me an error of, "##[error]SignTool Error: No certificates were found that met all the given criteria."


text:
Q: Perl Regular Expression simplification I want to simplify the following statement.
if($_=~/^([0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F])/)

Is there an alternate way I can write the above statement without repeating [0-9a-fA-F] n times ?

A: Try this
if($_=~/^([0-9a-fA-F]{5})/)

A: You can use Quantifiers

{n}    Match exactly n times

if (/^([0-9a-fA-F]{5})/)

Similarly, you can use a POSIX character class

xdigit Any hexadecimal digit
  ("[0-9a-fA-F]").

if (/^([[:xdigit:]]{5})/)

A: or even
if( /^([0-9a-fA-F]{5})/ )


text:
Q: Should a new node process be spawned for handling more than 100 requests? I'm building a website where a user can upload their CSV file which contains certain id's. My application will lookup those id's using AJAX requests. The amount of id's in the CSV file may be between 100 - 50000.
I'm wondering if it's a best practice to spawn a new node.js process to handle each such CSV because else the event loop will be full of thousands of such AJAX requests and responses. So if the user needs to trigger an AJAX request somewhere in the website for some small task (not related to the CSV) that request will be queued after potentially tens of thousands of other requests which will result in bad user experience.

A: Don't worry. Nodejs can handle that much API requests.
If you're using pm2 to start processes, you can use pm2 start <entry-file.js> -i max to start the processes according to CPU cores you have.
To avoid bad user experience, you can immediately send user a response that your work is in progress and notify your user about completion of work later.
what's your thought ?


text:
Q: Firebase error Function CollectionReference.doc() The following project in react connecting with firebase is having the following issues code. Once the enter button is clicked to submit the message it bring back the error from the database.(picture bellow) . I created the collection "rooms" and I am trying to access with  db.collection("rooms").doc(channelId).collection({ }) line 17 which is bringing back the error from firebase.
what does this error message means?
FirebaseError: Function CollectionReference.doc() requires its first argument to be of type non-empty string, but it was: true
I removed firebase.ps1 file an logged back.
created a new db.collection still the same.

import React, { useState } from "react";
import "./ChatInput.css";
import db from "./firebase";
import { useStateValue } from "./StateProvider";
import firebase from "firebase";
import { Button } from "@material-ui/core";

function ChatInput({ channelName, channelId }) {

    const [input, setInput] = useState("");
    const [{ user }] = useStateValue();

    const sendMessage = (e) => {
        e.preventDefault();

        if (channelId) {
              db.collection("rooms").doc(channelId).collection({
                message: input,
                timestamp: firebase.firestore.FieldValue.serverTimestamp,
                user: user.displayName,
                userImage: user.photoURL,
             });
         }

         setInput("");

    };

    return (

            <form>

                <input
                value={input}
                onChange={(e) => setInput(e.target.value)}
                placeholder={`Message #${channelName?.toLowerCase()}`} />

                    <Button type="submit" onClick={sendMessage}>
                        SEND</Button>

            </form>

    );
}

export default ChatInput;

**also added the following code and still getting the same issue
Changes made changes made 2
function collectionreference-error
firebase error

A:
what does this error message means? FirebaseError: Function
CollectionReference.doc() requires its first argument to be of type
non-empty string, but it was: true

It means that you need to pass a String as argument of the doc() method.
You are passing channelId to the doc() method and it seems it is a boolean with value true. You need to pass a String which represents the ID of the Firestore Document. I guess it is channelName, isn't it?

In addition, there is another problem in your code: you are passing a JavaScript object to the collection() method.

If you want to "submit a message", you need, for example, to call the add() method on the CollectionReference.
Something like the following (we don't know the subcollection name you want to use, let's take 'messages'):
db.collection("rooms").doc(channelName).collection('messages')
  .add({
       message: input,
       timestamp: firebase.firestore.FieldValue.serverTimestamp,
       user: user.displayName,
       userImage: user.photoURL,
  });

I would suggest that you have a look at the doc: https://firebase.google.com/docs/firestore/manage-data/add-data

A: import React, { useState } from "react";
import "./ChatMsg.css";
import db from "./firebase";
import firebase from "firebase";
import { useStateValue } from "./stateProvider";

function ChatMsg({ channelName, channelId }) {
  const [input, setInput] = useState("");
  const [{ user }] = useStateValue();
  const sendMessage = (e) => {

    e.preventDefault();
    if (channelId) {
      db.collection("rooms").doc(channelId).collection('messages').add({
        message: input,
        user: user.displayName,
        timestamp: firebase.firestore.FieldValue.serverTimestamp(),
        userimage:user.photoURL

      });

    }
  };

  return (

      <form>
        <input
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder={`Message # ${channelName}`}
        />
        <button type="submit" onClick={sendMessage}>
          SEND
        </button>
      </form>

  );
}
export default ChatMsg;


text:
Q: Comparing 2 arrays and pushing missing values to an Array - Javascript Its quite a simple problem but I am unable to figure out the logic.
I have Arr1 = [1,2,3,4] and Arr2 = [3,4,5,6]
I would like compare Arr2 with Arr1 and add missing values to
MissingArr = [];
my code
let missing = [];
 arrOfNum.forEach( (number) => {

  // Arr2 = 3,4,5,6
  console.log("number: "+number);
  for(let i = 0; i < this.numbers.length; i++){

      // Arr1 = 1,2,3,4
      console.log("this.numbers: "+this.numbers[i]['number']);

      if(number == this.numbers[i]['number'])
      {
        //Do Nothing
      }else{
        missing.push(this.numbers[i]['number']);
      }
  }
});

I am not sure how to do a check of Arr2 to Arr1 (complete entire forloop) and only if Arr2 value does not exist in Arr1 then add it to missing array.
Update
Arr1 = [{id:1, number:1}, {id:2, number:2},{id:3, number:3}, {id:4, number:4}]
Arr2 = [3,4,5,6]

so missing array should be: Missing= [5,6]

A: You can do this with filter and some methods.

const Arr1 = [{id:1, number:1}, {id:2, number:2},{id:3, number:3}, {id:4, number:4}],
Arr2 = [3,4,5,6]

const result = Arr2.filter(e => !Arr1.some(o => o.id == e));
console.log(result)

A: You can use Array.filter to achieve this. Array.filter returns an array containing items matching the predicate.
var arr1 = [{key: 1},{key: 2},{key: 3},{key: 4}];
var arr2 = [3,4,5,6];

//This will return all values in array2 missing in array1
var missing = arr1.filter(function(arr1_item){
    return arr2.indexOf(arr1_item.key) === -1;
});


text:
Q: Fortran calls C++ pointer function I have a problem with connecting Fortran program with C++ function.
My task is to call C++ function pointer from fortran, example:
// C++ function pointer
double* GetSplinePtr()
{
    return sp;
}

I use iso_c_binding procedure and fortran interface.
For non-pointer function i usually use this declaration:
real(kind=c_double) function Name(x,y) bind(c, name='Name')
use iso_c_binding
implicit none
real(c_double), intent(in), value :: x,y
end function Name

But what should I use for function which returns a pointer?
Thanks!

A: As Ross comments, you must make the Fortran interface to return the C pointer and do the conversion to a Fortran pointer yourself.
interface
  function GetSplinePtr() result(res) bind(C, name="GetSplinePtr")
    use iso_c_binding
    type(C_ptr) :: res
  end function
end interface

In the calling code you have to call c_f_pointer() from the iso_c_binding module:
  use iso_c_binding

  type(c_ptr) :: p
  real(c_double), pointer :: x

  p = GetSplinePtr()

  call c_f_pointer(p, x)


text:
Q: PostgreSQL and Perl: violates foreign key constraint I have table lv and referenced table pozemek, that contains:
"pozemek_lv_id_fkey" FOREIGN KEY (lv_id) REFERENCES lv(id)

and I want create record in lv and subsequently in pozemek:
my $lv_ins = $kadadbh->prepare("INSERT INTO lv ...");
my $poz_ins= $kadadbh->prepare("INSERT INTO pozemek (lv_id,...) VALUES (?,...)");
$lv_ins->execute(...);
$lv_id = $kadadbh->last_insert_id(undef,undef,'lv','id');
print "lv_id=$lv_id\n";
$poz_ins->execute($lv_id,...);

It returns a new lv_id, but consequently fails:

lv_id=8990
ERROR:  insert or update on table "pozemek" violates foreign key constraint "pozemek_lv_id_fkey"
DETAIL:  Key (lv_id)=(8990) is not present in table "lv". at ./dznxml.pl line 121


text:
Q: Swift 4 change string to URL I'm fairly new to swift, but I've tried everything and can't get this to work.
var itemValue: String!
var itemURL: URL!

override func viewDidLoad() {
    super.viewDidLoad()

    print("itemValue is", itemValue!)
    guard let itemURL = URL(string: itemValue) else {
        return
    }

itemURL is not getting a value, even though I have verified that the itemValue string is set correctly (in a previous vc, prepare for segue).

A: When you write guard let itemURL = URL(string: itemValue), you create a new local constant named itemURL, that has nothing to do with the global variable that has the same name. Moreover, this new local constant has not the same type than the global variable. The global variable is an implicitly unwrapped optional, so this is an optional, but the local constant is not an optional.
This is why you say that itemURL is not getting a value: you want the global variable named itemURL to get a value, but you only set a value to the local constant that has the same name. Those two similar identifiers do not store their content in the same memory location.

A: let url : String = "url string here"
let urlStr : String = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let convertedURL : URL = URL(string: urlStr)!
print(convertedURL)

try to put your URL string in this code and I hope it will work for you .


text:
Q: Reading a barcode using OpenCV QRCodeDetector I am trying to use OpenCV on Python3 to create an image with a QR code and read that code back.
Here is some relevant code:
def make_qr_code(self, data):
    qr = qrcode.QRCode(
        version=2,
        error_correction=qrcode.constants.ERROR_CORRECT_H,
        box_size=10,
        border=4,
    )

    qr.add_data(data)
    return numpy.array( qr.make_image().get_image())

# // DEBUG
img = numpy.ones([380, 380, 3]) * 255
index = self.make_qr_code('Hello StackOverflow!')
img[:index.shape[0], :index.shape[1]][index] = [0, 0, 255]
frame = img
# // DEBUG

self.show_image_in_canvas(0, frame)
frame_mono = cv.cvtColor(numpy.uint8(frame), cv.COLOR_BGR2GRAY)
self.show_image_in_canvas(1, frame_mono)

qr_detector = cv.QRCodeDetector()
data, bbox, rectifiedImage = qr_detector.detectAndDecode(frame_mono)
if len(data) > 0:
    print("Decoded Data : {}".format(data))
    self.show_image_in_canvas(2, rectifiedImage)
else:
    print("QR Code not detected")

(the calls to show_image_in_canvas are just for showing the images in my GUI so I can see what is going on).
When inspecting the frame and frame_mono visually, it looks OK to me

However, the QR Code Detector doesn't return anything (going into the else: "QR Code not detected").
There is literally nothing else in the frame than the QR code I just generated. What do I need to configure about cv.QRCodeDetector or what additional preprocessing do I need to do on my frame to make it find the QR code?

A: OP here; solved the problem by having a good look at the generated QR code and comparing it to some other sources.
The problem was not in the detection, but in the generation of the QR codes.
Apparently the array that qrcode.QRCode returns has False (or maybe it was 0 and I assumed it was a boolean) in the grid squares that are part of the code, and True (or non-zero) in the squares that are not.
So when I did img[:index.shape[0], :index.shape[1]][index] = [0, 0, 255] I was actually creating a negative image of the QR code.
When I inverted the index array the QR code changed from the image on the left to the image on the right and the detection succeeded.

In addition I decided to switch to the ZBar library because it's much better at detecting these codes under less perfect circumstances (like from a webcam image).

A: import cv2
import sys

filename = sys.argv[1]
# Or you can take file directly like this:
#   filename = f'images/filename.jpg' where images is folder for files that you trying to read

# read the QRCODE image
# in case if QR code is not black/white it is better to convert it into grayscale
# Zero means grayscale
img = cv2.imread(filename, 0)
img_origin = cv2.imread(filename)

# initialize the cv2 QRCode detector
detector = cv2.QRCodeDetector()

# detect and decode
data, bbox, straight_qrcode = detector.detectAndDecode(img)

# if there is a QR code
if bbox is not None:
    print(f"QRCode data:\n{data}")
    # display the image with lines
    # length of bounding box
    # Cause bbox = [[[float, float]]], we need to convert fload into int and loop over the first element of array
    n_lines = len(bbox[
                      0])
    bbox1 = bbox.astype(int)  # Float to Int conversion
    for i in range(n_lines):
        # draw all lines
        point1 = tuple(bbox1[0, [i][0]])
        point2 = tuple(bbox1[0, [(i + 1) % n_lines][0]])
        cv2.line(img_origin, point1, point2, color=(255, 0, 0), thickness=2)

    # display the result
    cv2.imshow("img", img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

else:
    print("QR code not detected")

A: To re-state the accepted answer, the background of the QRcode must be white and the foreground must be black. So if the generated QRcode has a white foreground you must invert the colors, e.g.:
from cv2 import cv2

img = cv2.imread('C:/Users/N/qrcode.jpg')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Invert colors so foreground is black
img_invert = cv2.bitwise_not(img_gray)

cv2.imshow('gray', img_gray)
cv2.imshow('inverted', img_invert)
cv2.waitKey(1)

qr_detector = cv2.QRCodeDetector()

text, _, _ = qr_detector.detectAndDecode(img_invert)

print(text)


text:
Q: Precompiled Azure function and CloudTable binding output doesn't work I'm using a precompiled Azure Function that looks:
public static async Task Run(Stream inputBlob, Stream outputJson, Stream outputXml, CloudTable schedulerTable)

The output binding looks:
{
  "name": "schedulerTable",
  "type": "table",
  "direction": "out",
  "tableName": "SchedulerTable",
  "connection": "SchedulerTable"
}

When i remove the parameter schedulerTable from my function, it's works. ´The message that the host throws in my face is:
Microsoft.Azure.WebJobs.Host: Error indexing method 'Functions.InputFileAdaptorAF'. Microsoft.Azure.WebJobs.Host: Can't bind Table to type 'Microsoft.WindowsAzure.Storage.Table.CloudTable'.

Really, when i add a table output binding trying with diferent alternatives, nothing works. Alternatives that doesn't work are:

*

*Parameter schedulerTable with type SchedulerRegister. The class SchedulerRegister inherits from TableEntity.

*Parameter schedulerTable  with type ICollector.

*Parameter schedulerTable  with type CloudTable. (the case above).

Please, ¿How I can fix it? (Use an output binding to azure table)

A: You're likely running into type mismatch issues. What version of the storage SDK are you using? You need to make sure storage SDK references match what the runtime expects, which currently is 7.2.1.
Please make sure that you're referencing the storage SDK version 7.2.1.

A: According to your description, I have tested this issue about binding to the table output, I could make it work as expected. Here is my code snippet, you could refer to it.
function.json
{
  "bindings": [
    {
      "name": "inputBlob",
      "type": "blobTrigger",
      "direction": "in",
      "path": "input/{name}",
      "connection": "AzureStorageConnectionString"
    },
    {
      "type": "table",
      "name": "outTable",
      "tableName": "UploadFile",
      "connection": "AzureStorageConnectionString",
      "direction": "out"
    }
  ],
  "disabled": false
}

*

*ICollector<T>
#r "Microsoft.WindowsAzure.Storage"

using Microsoft.WindowsAzure.Storage.Table;
using Microsoft.WindowsAzure.Storage.Blob;

public static void Run(CloudBlockBlob inputBlob, ICollector<UploadFile> outTable, TraceWriter log)
{
    string blobUri=inputBlob.StorageUri.PrimaryUri.ToString();
    log.Info($"C# Blob  trigger function triggered, blob path: {blobUri}");

    outTable.Add(new UploadFile()
    {
        PartitionKey = "Functions",
        RowKey = Guid.NewGuid().ToString(),
        Name = blobUri
    });
}

public class UploadFile : TableEntity
{
    public string Name { get; set; }
}

*

*CloudTable
#r "Microsoft.WindowsAzure.Storage"

using Microsoft.WindowsAzure.Storage.Table;
using Microsoft.WindowsAzure.Storage.Blob;

public static void Run(CloudBlockBlob inputBlob,CloudTable outTable, TraceWriter log)
{
    string blobUri=inputBlob.StorageUri.PrimaryUri.ToString();
    log.Info($"C# Blob  trigger function triggered, blob path: {blobUri}");

    outTable.Execute(TableOperation.Insert(new UploadFile()
    {
        PartitionKey = "Functions",
        RowKey = Guid.NewGuid().ToString(),
        Name = blobUri
    }));
}

public class UploadFile : TableEntity
{
    public string Name { get; set; }
}

Modify your code and click Save, if the compilation executes successfully, then when the function is triggered, you could see the following log and the record is added to Azure Table Storage.

For more details, you could refer to this official document about storage table binding for Azure function.

A: Really, this answer is from someone (i don't remember de name) in the team of Azure Functions, here in this question, but he delete her response. He says that surely the problem is from having diferent version of the dll that expected. I can confirm that these was the problem.
The solution is to check the version of dlls used in AppData\Local\Azure.Functions.Cli\1.0.0-beta.91 and use the same in the solution.


text:
Q: Can't change or add keyborad layout in Ubuntu I am a new in Ubuntu and still learning to use it. But in some ways I get the error as below and I can't Google it to find an answer. If someone please see this error:

Error activating XKB configuration.
There can be various reasons for that.
If you report this situation as a bug, include the results of
xprop -root | grep XKB
gsettings get org.gnome.libgnomekbd.keyboard model
gsettings get org.gnome.libgnomekbd.keyboard layouts
gsettings get org.gnome.libgnomekbd.keyboard options

A: sudo dpkg-reconfigure keyboard-configuration
sudo dpkg-reconfigure kbd


text:
Q: CSS, Bootstrap: make element auto arrange position to fit the screen I have series of element which should look like this in a big screen:
[-1-][---2----][-3-][-4-]

However when the screen is smaller,the elements should auto adjust its position to fit the screen (each element width and height cannot change):
[-1-][-3-]
[---2----]
[-4-]

How can I do this?

A: You should add classes:
col-xs-6 to 1

col-xs-12 to 2

col-xs-6 to 3

col-xs-6 to 4

But height won't be equal because elements must change height to fit to screen size. Of course You can add max-height in CSS but it's hard to say how this will looks like.


text:
Q: How to specify app version in pm2 start via Yarn? I have a Node.js + Express application, let's call myapp v0.3.0, that I start with Yarn scripts, such as:
yarn prod

I've deployed my production application with PM2, using:
pm2 start yarn --name myapp -- prod

This works and the app is properly deployed, but when I look at pm2 list, the version of the PM2 application is Yarn's version (0.39.1), not myapp's version (0.3.0):
┌────┬───────┬───────────┬─────────┬──────┬────────┬────────┬───┬────────┬─────┬────────┬──────┬──────────┐
│ id │ name  │ namespace │ version │ mode │ pid    │ uptime │ ↺ │ status │ cpu │ mem    │ user │ watching │
├────┼───────┼───────────┼─────────┼──────┼────────┼────────┼───┼────────┼─────┼────────┼──────┼──────────┤
│ 1  │ myapp │ default   │ 0.39.1  │ fork │ 124777 │ 43h    │ 1 │ online │ 0%  │ 49.2mb │ pm2  │ disabled │
└────┴───────┴───────────┴─────────┴──────┴────────┴────────┴───┴────────┴─────┴────────┴──────┴──────────┘

My CI/CD tool uses the version field from PM2 to manage automatic deployments. Is there a way to make the version track the application version (e.g. 0.3.0) instead of Yarn's version?

A: Add yarnwrapper bash script in the same directory of your package.json:
#!/bin/bash
eval "/${HOME}/.nvm/versions/node/$(node -v)/bin/yarn prod"

Launch it with pm2:
pm2 start yarnwrapper --name myapp --interpreter bash


text:
Q: Negative Testing Paypal DoExpressCheckoutPayment without code change I would like to test DoExpressCheckoutPayment without changing my code (otherwise I'm not really testing the proper code).  It seems I need to set the token to a certain error code, but that means changing the code and therefore not a proper test in my opinion.
Are there any alternative methods?  I am using NVP interface.

A: As per the PayPal Sandbox User Guide (page 46), in order to test the DoExpressCheckoutPayment API, you can also set the AMT (or PAYMENTREQUEST_0_AMT) parameter to a certain value to trigger an error condition.

A: I also had same error and after some debugging with paypal employees we found out that it might be related to 'Digital' products and that correct place to put the error code is PAYMENTREQUEST_0_AMT and format is 100.01 for DoExpressCheckoutPayment
So try setting PAYMENTREQUEST_0_AMT=106.23 for your error. Hope that helps.

A: To enable negative testing:

*

*Login @ http://developer.paypal.com

*Applications > Sandbox Accounts. You will have 1 Business type account and 0 or more Personal type accounts.

*Under the Business account, click Profile > Settings, switch Negative Testing to On

*When you send a request, send the relevant error code. See https://developer.paypal.com/docs/classic/lifecycle/sb_error-conditions/


text:
Q: В чем разница git push -u origin master и git push? Ну вот собственно, такой простой вопрос... Создал ветку, внес изменения, добавил файлы в отслеживаемые, закомитил, смержил с веткой master и вот теперь хочу отправить изменения на сервер...
Как это сделать просто
git push

или
git push -u origin master

?

A: Второй вариант явно показывает, куда вы пушите коммит, первый - неявно.
В большинстве случаев достаточно указать первый вариант, в крайнем случае вам появится (git 2.0 - 2.8) нотификация типа:
[ak@server abc]$ git push
warning: push.default is unset; its implicit value is changing in
Git 2.0 from 'matching' to 'simple'. To squelch this message
and maintain the current behavior after the default changes, use:

  git config --global push.default matching

To squelch this message and adopt the new behavior now, use:

  git config --global push.default simple

See 'git help config' and search for 'push.default' for further information.
(the 'simple' mode was introduced in Git 1.7.11. Use the similar mode
'current' instead of 'simple' if you sometimes use older versions of Git)

Counting objects: 5, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 367 bytes | 0 bytes/s, done.
Total 3 (delta 2), reused 0 (delta 0)
To abc@asdf:/asdfasddf.git
   b41acb4..b8c32bd  master -> master

Цитирую:

Одним из самых главных изменений является поведение команды git push.
  Теперь по умолчанию (если не указана ветка) push будет осуществлен
  только в текущую ветку. Git 1.* по умолчанию делал push во все ветки,
  которые были изменены локально. Конечно же можно вернуться к прежнему
  поведению, для этого служит опция push.default.

Это очень популярный вопрос на английском so, там тоже самое написано:

*

*matching означает, что git push отправит все ваши локальные ветки в такие же на удалённом сервере.

*simple означает, что git push отправит только текущую ветку в такую же на удалённом сервере.
Simple более интуитивный режим, поэтому он является режимом по умолчанию и используется если push.default не установлен.


text:
Q: C++ std::istream readsome doesn't read anything It's like readsome isn't even reading. Returns 0 and doesn't read any chars. What is wrong here?
#include <fstream>
#include <iostream>

int main ()
{
  std::fstream stream("list.cpp", std::ios::in);

  if (stream.good() || !stream.bad() || stream.is_open()) {

    std::cout << "Well, stream looks good." << std::endl;

    char justOneChar = 'L';
    auto ssize = stream.readsome(&justOneChar, 1);

    std::cout << ssize << " : " << justOneChar << std::endl;
  }

  return -1;
}

Output:
Well, stream looks good.
0 : L

A: auto ssize = stream.readsome(&justOneChar, 1);

1 is the maximum number of characters to read. If the streams internal buffers are empty when you call it, you'll get back zero as a return value.
The following quote (with my bold) shows this aspect:

streamsize readsome (char* s, streamsize n);
Extracts up to n characters from the stream and stores them in the array pointed by s, stopping as soon as the internal buffer kept by the associated stream buffer object (if any) runs out of characters, even if the end-of-file has not yet been reached.
The function is meant to be used to read data from certain types of asynchronous sources that may eventually wait for more characters, since it stops extracting characters as soon as the internal buffer is exhausted, avoiding potential delays.

It's basically a way to get as many characters as are available (subject to your specified limit) without having to wait for the stream to provide more.

A: Consulting a reference,

The behavior of this function is highly implementation-specific. For example, when used with std::ifstream, some library implementations fill the underlying filebuf with data as soon as the file is opened (and readsome() on such implementations reads data, potentially, but not necessarily, the entire file), while other implementations only read from file when an actual input operation is requested (and readsome() issued after file opening never extracts any characters). Likewise, a call to std::cin.readsome() may return all pending unprocessed console input, or may always return zero and extract no characters.

In short, readsome is fairly useless, at least for standard streams. It's a super-nonblocking read: it will only load data that has been buffered in the user-level process, and it will not ever make a kernel call.

A: It doesn't work because there might not be any characters available for reading at that instant. It works as a non-blocking read function as someone mentioned, therefore this means that it doesn't wait for input, which is why it wasn't asking you for input. So for you to use it to successfully read anything, there must be something available in the underlying buffer.
To see the number of characters that can be extracted in the next call to readsome, use the in_avail function.


text:
Q: Does the javascript split function have a special meaning in mirth? I am maintaining a legacy mirth system. We get some incoming HL7 messages with a repeating ZP1.36 segment. As far as I can tell, mirth is dividing these repeating segments into an array of repeating segments via a split function.
var repeat36 = msg['ZP1']['ZP1.36'].toString().split("</ZP1.36>"); //I think returns an array of ZP1.36 segments

But in the raw data, I don't see the string ZP1.36...
I'm used to using split functions in VB/Java/C# that divide strings into tokens around a certain character, like this:
var myTokens = "hello^world".toString().Split("^"); //returns a 2 item array {"hello", "world"}

Mirth's split function doesn't seem to be working this way. It seems to be parsing the messages based on the assumed structure of the HL7 message.
Is this what's going on? Am I missing something? What are the rules for the split function in mirth?
Cross-posted on mirth community http://www.mirthcorp.com/community/forums/showthread.php?p=26203#post26203

A: I know you already found and accepted a sufficient answer to your question (reposted from the Mirth forums), but I thought it might be helpful to give a bit more information in a separate answer.
At its heart, Mirth leverages a couple of pre-existing technologies in order to work with HL7 data.

*

*HAPI (pronounced "Happy"): This is a library of Java code for re-interpretting pipe-delimited V2.x HL7 as XML. The V2.XML format itself is also an official HL7 specification (not to be confused with V3 HL7 which is natively XML). The product name "Mirth" was obviously chosen as a synonym for "happy."

*E4X: This is a JavaScript standard for working with XML. It failed to gain significant traction as a standard web technology, however, it is leveraged by Mirth due to its availability in the Rhino JavaScript  engine.

From the examples that Dans provided you on the Mirth forums:
This snippet is in the standard XML format for HL7 v.2x:
<ZP1.36>
    <ZP1.36.1>Hello</ZP1.36.1>
    <ZP1.36.2>World</ZP1.36.2>
<ZP1.36>

This JavaScript code is utilizing E4X notation to parse and access HL7 data that has been reinterpreted into E4X XML and XMLList data types:
var zp1361 = msg['ZP1']['ZP1.36']['ZP1.36.1'].toString();
var zp1362 = msg['ZP1']['ZP1.36']['ZP1.36.2'].toString();

*

*msg is the E4X XML object holding the HL7 data

*msg['ZP1'] produces an E4X XMLList object that holds a list of ZP1 segments.

A: Dans, a Mirth employee on the Mirth message boards explains that the split function works on the xml translation of the incoming message.
So basically, you are working with xml and the ZP1.36 is already split up:
<ZP1.36>
   <ZP1.36.1>Hello</ZP1.36.1>
   <ZP1.36.2>World</ZP1.36.2>
<ZP1.36>

If you want to get the various sub elements you can do something like this:
var zp1361 = msg['ZP1']['ZP1.36']['ZP1.36.1'].toString();
var zp1362 = msg['ZP1']['ZP1.36']['ZP1.36.2'].toString();


text:
Q: What's the selection criterion for the "best" model in "regsubsets" & how do I access several "best" models? I've been playing around with the regsubsets function a bit, using the "forward" method to select variables for a linear regression model. However, despite also reading the documentation I can't seem to figure out, how the leaps.setup underlying this function determines the "best" model for each separate number of variables in a model.
Say I have a model with potential 10 variables in it (and nvmax = 10), I get exactly one "best" model for a model with 1 var, 2 vars etc. But how is this model selected by the function? I wonder particularly because after having run this function, I'm able to extract the best model of all models with different(!) sizes by determining a specific criterion (e.g., adjr2).
Related to this, I wonder: If I set, for example, nbest = 5 I understand that the function calculates the five best models for each model size (i.e., for a model with ten variables it gives five different variations that perform better than the rest). If I understand that correctly, is there any way to extract these five models for a specific model size? That is, for example, display the coefficients of these five best models?
I hope, I'm being clear about my problems here... Please, let me know, if exemplary data or any further information will help to clarify the issue!

A: The "best" model picked by regsubsets is the one that minimizes the sum of the squares of the residuals.
I'm still working on the second question...

A: Addressing the second question: the next code displays the coefficients of the 5 best models for each quantity of explanatory variables, from 1 to 3 variables. Y is the response variable of the models.
library(leaps)

best_models = regsubsets( Y ~ ., data = data_set, nvmax=3, nbest=5)
coef(best_models, 1:15)


text:
Q: change orientation of diagonal lines in html and css I have diagonal lines as section dividers as explained in this stackoverflow question. However, i didn't find anywhere how to change the orientation, so that instead of descending from right to left they descend from left to right. Can anyone help? I suppose it is easy but I have tried and haven't been successful so far.
Code:

section

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Footer

Thanks!

A: change the angle of rotation and just minor changes in positioning

section

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Footer

A:

     body {

        margin: 0px;
    }
    p {
        color: white;
        margin-top: 5px;
    }
    section {
        position: relative;
        background: blue;
        color: #fff;
        text-align: center;
    }
    .diagonal {
       text-align: center;
        -moz-transform: scale(-1, 1);
    -webkit-transform: scale(-1, 1);
    -o-transform: scale(-1, 1);
    -ms-transform: scale(-1, 1);
    transform: scale(-1, 1);
    }
    .content {
          -moz-transform: scale(-1, 1);
    -webkit-transform: scale(-1, 1);
    -o-transform: scale(-1, 1);
    -ms-transform: scale(-1, 1);
    transform: scale(-1, 1);
    }
    section:before {
        position: absolute;
        content:'';
    }
    section.diagonal {
        background: blue;
    }
    footer {
        position: relative;
        background: black;
        color: #fff;
        text-align: center;
    }
    footer:before {
        position: absolute;
        content:'';
    }
    footer.diagonal {
        background: black;
    }
    .diagonal {
        z-index: 1;
        padding: 3em;
    }
    .diagonal:before {
        -webkit-transform: rotate(-3deg);
        transform: rotate(-3deg);
        -webkit-transform-origin: -3% 0;
        transform-origin: -3% 0;
        top: 0;
        left: -25%;
        z-index: -1;
        width: 150%;
        height: 75%;
        background: inherit;
    }

section

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Footer

This code works finely. Just scale .diagonal to minus value and revert that scale value of .content again.
Try this and let me know the updates. Thanks


text:
Q: How to use jquery within a javascript api? I am looking to develop a javascript web service that a website could include in one  line of code similar to how google analytics is used.  I would like to use jQuery in my javascript code, but I don't want it to conflict with any js libraries that may already be present on the hosting webpage.
Basically, inside the my main javascript file that an end user would include in their webpage, I would want to do something like:
document.write('<script type="text/javascript" ' +
           'src="http://mydomain.com/js/jquery-1.4.2.min.js"></script>');

...to make jquery available within my code library.  I'm wondering if this is the proper way to go about using jquery in a javascript api, or if there are more considerations to be made.  I'd appreciate any examples or articles anyone can suggest.

A: Use jQuery.noConflict()

A: See: How to build a web widget (using jQuery) tutorial by Alex Marandon. It explains many approaches to exactly what you are trying to do.

A: A while back I made a bookmarklet generator shameless plug that's jQuery enabled.
You can check out the code that's being executed, specifically this chunk:
if (!window.zbooks)
  {
    //if zbooks hasn't been set, initialize it

    //s used for the Script element
    var s = document.createElement('script');
    //r used for the Ready state
    var r = false;
    //set the script to the latest version of jQuery
    s.setAttribute('src', 'http://code.jquery.com/jquery-latest.min.js');
    //set the load/readystate events
    s.onload = s.onreadystatechange = function()
    {
/**
 * LOAD/READYSTATE LOGIC
 * execute if the script hasn't been ready yet and:
 * - the ready state isn't set
 * - the ready state is complete
 *   - note: readyState == 'loaded' executes before the script gets called so
 *     we skip this event because it wouldn't have loaded the init event yet.
 */
      if ( !r && (!this.readyState || this.readyState == 'complete' ) )
      {
        //set the ready flag to true to keep the event from initializing again
        r = true;
        //prevent jQuery conflicts by placing jQuery in the zbooks object
        window.zbooks = {'jQuery':jQuery.noConflict()};
        //make a new zbook
        window.zbooks[n] = new zbooks(c);
      }
    };
    //append the jQuery script to the body
    b.appendChild(s);
  }


text:
Q: Linking quotation and order data in way that lets order data to be flexible I have developed a data model as per screenshot. The purpose of this is to have all the relevant quotation data "mapped" out for further analysis.
The data between orders/quotations/invoices etc is linked by generating link tables, which comes out directly from SAP document flow (the document flow table only holds main document number, like quotation number and a line number of the material).
The links serve their purpose and are correct, if the quotations weren't so "flexible".
Orders to invoices are linked on a material level, so there cannot be any difference between them.
But Quotations are not hard linked to orders, I'll explain below.
For example if a quotation is created for 2 lines, which then later is converted in to an order, the user is not forced to keep the order in the same structure as the quotation, he/she can add more items in the order/change quantities etc. so they can really only be linked on the header level, aka Document number to document number.
So this is where I need some help.
I have tried to link the quotations to order in 2 ways, but they both have their issues.

*

*Doc to Doc. - The lines are duplicated when trying to create a report at an item level.

*Doc + line number to Doc + line number - If the order has extra lines added on to compared to quotation, this data is not captured in the flow.

I am hoping someone had a similar task/issue in the past and would be kind enough to share their experience/approach.
Regards


text:
Q: passing serializable object from stackview widget gives null pointer exception AppWidget Provider (BroadcastReciever)
(Trying to send Serializable Object from Stackview Widget)
When i send int as extra though pendingIntent i am able to receive in the activity but when i try to send serializable extra it gives me null pointer exception
Thanks in advance.
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

for (int i = 0; i < appWidgetIds.length; ++i) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_profile_stackview);

// set intent for widget service that will create the views
Intent serviceIntent = new Intent(context,WidgetProfieService.class);
serviceIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);

serviceIntent.setData(Uri.parse(serviceIntent.toUri(Intent.URI_INTENT_SCHEME)));

 remoteViews.setRemoteAdapter( R.id.widget_profilestackimageview, serviceIntent);

            Intent viewIntent = new Intent(context, ProfileActivity.class);
            viewIntent.setAction(Intent.ACTION_VIEW);
            viewIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
            viewIntent.setData(Uri.parse(viewIntent.toUri(Intent.URI_INTENT_SCHEME)));

            PendingIntent viewPendingIntent = PendingIntent.getActivity(context, 0, viewIntent, 0);
            remoteViews.setPendingIntentTemplate(R.id.widget_profilestackimageview, viewPendingIntent);

            // update widget
            appWidgetManager.updateAppWidget(appWidgetIds[i], remoteViews);
        }
        super.onUpdate(context, appWidgetManager, appWidgetIds);
    }
}

RemoteViewService(Sending extra int(image))
public RemoteViews getViewAt(int position) {

   RemoteViews rv = new RemoteViews(mContext.getPackageName(), R.layout.widget_profile);
rv.setImageViewResource(R.id.stack_profile_pic, ((Profile) mWidgetProfiles.get(position)).getImageId());
Log.d("profile",mWidgetProfiles.get(position).getCountry());

Log.d("profile",mWidgetProfiles.get(position).getImageId()+"");

Bundle extras = new Bundle();

//
  extras.putInt("profile",mWidgetProfiles.get(position).getImageId());
  //using int extra works

  extras.putSerializable("profile",(Profile)mWidgetProfiles.get(position));
    Intent fillInIntent = new Intent();
    fillInIntent.putExtras(extras);
    rv.setOnClickFillInIntent(R.id.profile_widgetlayout, fillInIntent);

try {
    System.out.println("Loading view " + position);
    Thread.sleep(1000);
} catch (InterruptedException e) {
    e.printStackTrace();
}
return rv;

}
Recieving Activity
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_profile);

/*
       Using ExtraInt works here
          ImageView img=(ImageView) findViewById(R.id.activity_profilepic);
    if(getIntent().getIntExtra("profile",0)!=0){
        Log.d("widgetpic",getIntent().getIntExtra("profile",0)+"");
        img.setImageResource(getIntent().getIntExtra("profile",0));
    }

*/

ImageView img=(ImageView) findViewById(R.id.activity_profilepic);
        Bundle extras = getIntent().getExtras();

        if(extras !=null)
            if(extras.containsKey("profile"))
            {
            Profile mProfile= (Profile)extras.getSerializable("profile");
            img.setImageResource(mProfile.getImageId());
        }

    }

A:
passing serializable object from stackview widget gives null pointer
  exception

Because sending profile key with bundle but trying to get profile from Intent which is returned by getIntent(). do it as:
Bundle extras = getIntent().getExtras();

    if(extras !=null)
      if(extras.containsKey("profile"))
        {
           Profile mProfile= (Profile)extras.getSerializable("profile");
        }


text:
Q: Placing a single black border around the popup image in Magnific Popup I haven't been able to find any info on the web to help me out here.  Using Magnific Popup I'd like my popup images to display with a single black border.  Ive gone into the Magnific-popup.css file and added the following:
/* Main image in popup */
img.mfp-img {
  width: auto;
  max-width: 100%;
  height: auto;
  display: block;
  line-height: 0;
/*my attempt at adding a border around the image */
  **border: 2px solid red;**
/* end attempt */
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  padding: 40px 0 40px;
  margin: 0 auto; }

What I'm getting is a red border in the display area, adding a black greyish border around the image.
Has anyone done this before?  Thanks in advance.

A: The issue is caused by the padding that has been set to the image, try replacing the padding with margin like this:
img.mfp-img {
    padding: 0;
    margin: 40px auto;
    /*Add your border*/
    border: 2px solid red;
}

Also I must note that modifying core files for any plugin is considered bad practice because it makes upgrading to a newer version more difficult, I suggest you create a separate CSS file to override or add any custom styles.

A: The best way I have found to do this is to remove the padding from the image and apply it to a before and after pseudo class on the figure like so
img.mfp-img {
    padding: 0;
    border: 2px solid red;
  }

  .mfp-figure figure::before {
    padding-top: 40px;
    display: block;
    content: "";
  }

  .mfp-figure figure::after {
    padding-bottom: 40px;
    display: block;
    content: "";
  }


text:
Q: set up loopback on a new server based on json files for models My previous server is lost, I am developing an Android app with backend on a ubuntu server on AWS, what I am trying to do now is I need to recover the backend loopback based on the json files of the models. For example I am having this,
{
"name": "BikeStop",
"plural": "bikeStops",
"base": "PersistedModel",
"idInjection": true,
"options": {
  "validateUpsert": true
},
"properties": {
  "geo": {
    "type": "geopoint",
    "required": true
  },
  "description": {
    "type": "string",
    "required": false
  }
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}

is it possible that I can just import this to a new lb folder, or do i have to call lb model and manually type in and set up? If there is a way to do it, how??

A: Copy your model in a JSON file as
bikestop.json
{
"name": "BikeStop",
"plural": "bikeStops",
"base": "PersistedModel",
"idInjection": true,
"options": {
  "validateUpsert": true
},
"properties": {
  "geo": {
    "type": "geopoint",
    "required": true
  },
  "description": {
    "type": "string",
    "required": false
  }
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}

Now create a javascript file for this model as
bikestop.js
   'use strict';

    module.exports = function(Bikestop) {

    };

PS : Model name should has only the first letter uppercase.
Finally define this model in model-config.json
  "BikeStop": {
    "dataSource": "YourDataSourceName",
    "public": true
  }


text:
Q: How to mitigate the hierarchical error propagation in tree-structured classification Suppose we have a multi-class classification problem, where the number of classes $K \geq 3$
We use a tree structure of multiple SVMs to divide and conquer the problem, with one example in the figure below.

Generally, in this kind of hierarchical classification, if a sample is wrongly classified in an upper layer, it is less likely to be corrected again in lower layers.
My question: Is there any strategy to mitigate such hierarchical error propagation in tree-structured classification?
Much appreciated!


text:
Q: Computer occasionally shuts off mid-boot ; and other weird power issues So I have a desktop computer I assembled myself back in July. It works great and I didn't encounter any hardware issues, except for some weird power ones.
When my computer is on, everything is fine. No problem, no random shut-down, no lack of wattage or anything like this.
The problems are when it's off. Occasionnaly, when trying to switch it on, the computer would shut down mid-boot without any appparent reason. If I try to restart it, same thing. The only way I can get it to work is by entering the BIOS and exiting it, after what everything would work fine.
Note that this doesn't happen everytime I switch my PC on. It just happens randomly.
Now for the other minor problems.
I think my PC is never completely off until I switch the PSU off, this for some reasons :

*

*My motherboard has decorative LEDs that are always on, even when I switch the PC off. However, if I switch the PSU off and on again, these LEDs turn off and don't turn on again - untill I press power button.

*If I put the PC in hibernate mode (which, correct me if I'm wrong, is just switching the PC off but keeping a save of its current state on the hard drive), and I press a key on the keyboard, the keyboard LEDs switch on. Strangely enough, this doesn't happen with my mouse - which has LEDs too.

*Sometimes, but more rarely though, I experience the same keyboard issue when the PC is off.

*If I plug in a xBox 360 controller when the PC is off, its LEDs would light for half a second and then stop. Unplug, replug : same thing.
So as I'm not an hardware expert (I'm more into software actually), I can't seem to find out whether all these strange behaviours are related and, be they or not, where they could come from.
My specs are as follows :

*

*Windows 10 Pro N 64 bits

*LEPA MX F1 650W PSU

*Intel Core i7-4790K @ 4.0 GHz CPU (no overclock)

*8Go HyperX Fury DDR3 RAM

*Asus Z97-E 1150 motherboard

*Sapphire Radeon RX480 GPU

*Kingston 240Go SSD used for C:\

*Seagate Barracuda 1To HDD used for D:\
Thanks in advance for any help.
EDIT :
So thanks to @HighTechGeek's comment I was able to resolve the main issue (shut down mid-boot), that was caused by Fast Boot (the great part is that with my SSD, I didn't notice any change in speed while turning my PC on).
For the motherboard never being off, I found my anwser There.


text:
Q: Is this a geometric distribution Let $X$ be $rv$ with the probability distribution,
$$p(k) = (1 - x)x^k; k = 0, 1, 2,...$$
where $x \in (0, 1)$ is a constant.
Is this computing the number of failures with $Pr[\text{Success}] = 1-x$?

A: Yes, in general, geometric distribution takes the form of $$p(k) = (1-p)^k p, k=0,1,2\ldots, $$
Here $p=1-x$.
Note that failure or success depends on the definition of the user.

A: It depends on your definition of Geometric distribution.
If the geometric distribution is defined as the number of attempts until a success then $0$ does not belong to it's range. Under this intrpretation
$ X = Z -1$ where $Z \sim \mathcal{G} (1-x)$.
Wikipedia


text:
Q: Reshaping a nested Numpy Arrays using reshape I have a numpy array :
ar = [[1,2],[3,4],[5,6]]

I want to convert it to :
ar = [[1,3,5],[2,4,6]]

I have tried numpy reshape function it did not work.
Is there any way to reshape it using numpy reshape method or any other way??
Thank you.

A: Use Transpose (.T)
ar = np.array([[1,2],[3,4],[5,6]])
ar.T


text:
Q: Issue with JAXB generated with xjc I have an issue with JAXB for the following xsd:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">

        <xs:complexType name="data">
            <xs:sequence  maxOccurs="2">
                <xs:element name="indg1" type="xs:string"/>
                <xs:element name="indg2" type="xs:string"/>
                <xs:element name="indg3" type="xs:string"/>
            </xs:sequence>
        </xs:complexType>

    <xs:element name="sample" type="data" />
</xs:schema>

The following class is generated:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "data", propOrder = {
    "indg1AndIndg2AndIndg3"
})
public class Data {

    @XmlElementRefs({
        @XmlElementRef(name = "indg1", type = JAXBElement.class),
        @XmlElementRef(name = "indg2", type = JAXBElement.class),
        @XmlElementRef(name = "indg3", type = JAXBElement.class)
    })
    protected List<JAXBElement<String>> indg1AndIndg2AndIndg3;

    public List<JAXBElement<String>> getIndg1AndIndg2AndIndg3() {
        if (indg1AndIndg2AndIndg3 == null) {
            indg1AndIndg2AndIndg3 = new ArrayList<JAXBElement<String>>();
        }
        return this.indg1AndIndg2AndIndg3;
    }

}

What I was expecting was a class by the name of "Sample" with List<Data>.
Can you tell me how to do it, and why the behavior above is as it is?

A: Look into the generated class ObjectFactory. It contains a method for creating an element sample using an instance of class Data. The top level element of a document doesn't need a class of its own.
You are getting this strange List<JAXBElement<String>> because you have a repetition of a sequence of heterogeneous elements.


text:
Q: Selecting PHP variables from joined tables I am still trying to learn PHP and have some issues with this code. I have a field $youtubeurl in ID_Vehicles and I am trying to output some code if that field has data in it how do I select that field with this join to output the value like the sample below?
   function getDealerSettings($vid)
    {
        include('db.php');
        $query = "SELECT banner, ebay_htmlcss FROM ebay_dealersettings INNER JOIN ID_vehicles ON ebay_dealersettings.did=ID_vehicles.did WHERE vid='".$vid."'";
        $result = @mysql_query($query);
        if ($result)
        {
            $row = mysql_fetch_assoc($result);
            return array("banner" => trim($row['banner']), "css" => str_replace(array("\n", "\t"), " ",$row['ebay_htmlcss']));
        }
        return "";
    }

    function getTemplate($vid)
    {
        $code = "";
        extract($this->getDealerSettings($vid));
        if (!empty($youtubeurl))
            $code .= "$youtubeurl";

A: Seems like you just need to add that field to your select statement:
  $query = "SELECT banner, ebay_htmlcss, youtubeurl FROM ebay_dealersettings INNER JOIN ID_vehicles ON ebay_dealersettings.did=ID_vehicles.did WHERE vid='".$vid."'";

A: You need to add youtubeurl to the SELECT statement as well as ensuring it's in your return array, then it should work.

A: I wasn't returning the value in the array return array("banner" => trim($row['banner']),"youtubeurl" => trim($row['youtubeurl']),

A: Not necessarily an answer, supplements my comment to the question, I couldn't find a $youtubeurl mentioned before the empty check. If the db does not return anything or the query fails, the needed error handling is also not present. I have added simple error handling to the script. the return array contains ($return_array[0]) $errflag, which can be read to see if there was an error, $errmsg is an array containing the error msg, the third element contains your return array.
      function getDealerSettings($vid)
        {
          $errflag=false;
          $errmsg=array();
          $return=array();

            include('db.php');
            $query = "SELECT banner, ebay_htmlcss FROM ebay_dealersettings INNER JOIN ID_vehicles ON ebay_dealersettings.did=ID_vehicles.did WHERE vid='".$vid."'";
            $result = @mysql_query($query);

if (!$result){
   $errflag=true;
    $errmsg[]="Error with db connection". mysql_error();
}else{
     $row = mysql_fetch_assoc($result);
     $return = array("banner" => trim($row['banner']), "css" => str_replace(array("\n", "\t"), " ",$row['ebay_htmlcss']));
            }
$return_array=array($errflag, $errmsg, $return);
return $return_array;
        }


text:
Q: drupal/core-composer-scaffold doesn't put core in web folder I'm trying to bring my drupal 8 composer.json up to date, and move from the old drupal-scaffold to core-composer-scaffold. But composer2 puts the core and related directories directly into the app folder, rather than app/web.
My composer.json contents are:
    "description": "Project template for Drupal 8 projects with composer",
    "type": "project",
    "license": "GPL-2.0-or-later",
    "authors": [
        {
            "name": "",
            "role": ""
        }
    ],
    "repositories": {
        "drupal": {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        },
        "asset-packagist": {
            "type": "composer",
            "url": "https://asset-packagist.org"
        }
    },
    "require": {
        "php": "^7.4",
        "composer/installers": "^1.2",
        "cweagans/composer-patches": "^1.6.5",
        "drupal/clamav": "^1.1.0",
        "drupal/core-composer-scaffold": "^8.8",
        "drupal/core-dev": "^8.1",
        "drupal/core-recommended": "^8.8",
        "drupal/google_analytics": "^2.4.0",
        "drupal/mailsystem": "^4.1.0",
        "drupal/metatag": "^1.9.0",
        "drupal/officialfacebookpixel": "^1.1",
        "drupal/php": "^1.0",
        "drupal/schema_metatag": "^1.4.0",
        "drupal/sendgrid_integration": "^1.3",
        "drupal/simple_facebook_pixel": "1.1",
        "drupal/superfish": "^1.3.0",
        "drupal/token": "^1.5.0",
        "oomphinc/composer-installers-extender": "^2.0"
    },
    "config": {
        "sort-packages": true,
        "discard-changes": true,
        "optimize-autoloader": true
    },
    "conflict": {
        "drupal/drupal": "*"
    },
    "extra": {
        "enable-patching": true,
        "composer-exit-on-patch-failure": true,
        "patchLevel": {
            "drupal/core": "-p2"
        },
        "drupal-scaffold": {
            "locations": {
                "web-root": "web/"
            },
            "patches": [],
            "installer-types": [
                "bower-asset",
                "npm-asset"
            ],
            "installer-paths": {
                "drush/Commands/{$name}": ["type:drupal-drush"],
                "web/core": ["type:drupal-core"],
                "web/modules/contrib/{$name}": ["type:drupal-module"],
                "web/modules/custom/{$name}": ["type:drupal-custom-module"],
                "web/profiles/contrib/{$name}": ["type:drupal-profile"],
                "web/profiles/custom/{$name}": ["type:drupal-custom-profile"],
                "web/themes/contrib/{$name}": ["type:drupal-theme"],
                "web/themes/custom/{$name}": ["type:drupal-custom-theme"],
                "web/libraries/{$name}": [
                    "type:drupal-library",
                    "type:bower-asset",
                    "type:npm-asset"
                ]
            },
            "merge-plugin": {
                "include": [
                    "web/modules/custom/*/composer.json"
                ],
                "replace": false,
                "ignore-duplicates": true
            }
        }
    },
    "scripts": {
        "search-git-submodules": "find . -mindepth 2 -type d -name .git",
        "remove-git-submodules": "find . -mindepth 2 -type d -name .git | xargs rm -rf",
        "post-install-cmd": [
            "@remove-git-submodules"
        ],
        "post-update-cmd": [
            "@remove-git-submodules"
        ]
    },
    "minimum-stability": "dev",
    "prefer-stable": true
}

I can't find anything wrong with that myself, so why is this happening?2

A: According to the doc, web-root should be "./web" instead of "web/"
"locations": {
  "web-root": "./web"
},

A: Okay, I've found the solution to my own problem.
In rare cases it matters what order you use in the required section.
I moved "oomphinc/composer-installers-extender": "^2.0" to the top of the list, and composer now puts everything in the right place.
The problem seems to occur because of specific project dependencies, which keep composer from reordering the installs for itself.

A: Similar answer to @Ken - for me, I was missing the following package which needed to be at the top of the required list:
"require": {
    "composer/installers": "^1.2",

Upon deleting /vendor and re-running composer update, the core folder was properly created.


text:
Q: How to fix/resume a stopped do-release-upgrade I was trying to upgrade from 16.04 to 16.10 using do-release-upgrade, but then had to stop it in the middle. I can't resume it now.
 ~  iitpi sudo do-release-upgrade
Checking for a new Ubuntu release
No new release found
 ✘  ~  iitpi sudo apt upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 python3-aptdaemon.pkcompat : Conflicts: packagekit
                              Conflicts: packagekit:i386
E: Broken packages

A: For me, what it fixed it was a simple
apt update
apt install python3-aptdaemon

Then with apt upgrade all seemed fine.


text:
Q: Excel VBA - Refer to a worksheet as a variable in an IF statement In the following piece of VBA code, how do I replace the reference to the worksheet 'ContolPage' with the variable 'cPage'?
ActiveCell.FormulaR1C1 = "=IF(RC[5]="""","""",ControlPage!R[-13]C[-2])"

Thanks

A: You need to remove any vba variable from the quotes and concatenate with &:
ActiveCell.FormulaR1C1 = "=IF(RC[5]="""","""",'" & cPage & "'!R[-13]C[-2])"