text:
Q: How to DUMP API request information to a TXT file in PHP? I am working on API for DHRU CMS.
Unfortunately there are NO API setting to modify API CALLs, I can only provide domain: www.mydomain.com and Press SYNC. Then it will make a call to www.mydomain.com/api/index.php
Content of /api/index.php below:
   <?php
    if(!extension_loaded('ionCube Loader')){$__oc=strtolower(substr(php_uname(),0,3));
    $__ln='ioncube_loader_'.$__oc.'_'.substr(phpversion(),0,3).(($__oc=='win')?'.dll':'.so');
    if(function_exists('dl')){@dl($__ln);}if(function_exists('_il_exec')){return _il_exec();
    }
    $__ln='/ioncube/'.$__ln;
    $__oid=$__id=realpath(ini_get('extension_dir'));
    $__here=dirname(__FILE__);if(strlen($__id)>1&&$__id[1]==':'){$__id=str_replace('\\','/',substr($__id,2));
    $__here=str_replace('\\','/',substr($__here,2));
    }$__rd=str_repeat('/..',substr_count($__id,'/')).$__here.'/';
    $__i=strlen($__rd);
    while($__i--){if($__rd[$__i]=='/'){$__lp=substr($__rd,0,$__i).$__ln;if(file_exists($__oid.$__lp)){$__ln=$__lp;
    break;
    }}}if(function_exists('dl')){@dl($__ln);
    }}else{die('The file '.__FILE__." is corrupted.\n");
    }if(function_exists('_il_exec')){return _il_exec();
    }echo('Site error: the file '.__FILE__.' requires the ionCube PHP Loader '.basename($__ln).' to be installed by the website operator. If you are the website operator please use the ionCube Loader Wizard to assist with installation.');
    exit(199);
    ?>
    HR+cP/ElGN2OERf73MJKKmN0O3NzOb4pGJD4uAtGY1PaUwYj7l+JHDMBep4pqmahy4Kl4sfAGrTZ
    aL2G93Ks855rHFW7zCB0T54xRH9H3qrSrF0bW8cu82ephdXnKG7gU+xqeIGYrhCDtjkrnbjxfTW6
    SPgO1ywEMkU6IXNYZ/qD4SE3xzccXKU68rw9qYO6SWnfNL48ek9+x1+AhB1etCJY5QRNVub/Y7XI
    n42bVdO8Xx4gEGoUd5OI3lCEqfl2ojsJVJ5rHz8glJ798zsRYapbyXrQw6JU2u7f7mh1CjbJ5RBa
    jWL/SqHd/M7MYfblBiTdEi45H444RK66kWf3/ubHaIum4m5VMsXpG5CRiVSOWfDL2POK0S9gsFyk
    aUQBqJIkBirzm+/jdQaVFun5FJMf5lSB8Lb0KX0KmfLBiwYy9kLsGSNB7XCLOyJdFKNE7GjpPR3f
    DIXXUSCiq4NjJ1DBc58FhrMIcRadT6muczYvxmenoA8AtIY/zF5YBsjzzFCivOlpWzHwfGheRTOv
    PFTGwDQJCq5BsULjUKRmd0BN0hgY8/wGurwtYDtIS1gM5lfiZYeWl8gdDE7UWvZywSIpEilnFfiW
    f13lcxq4pHC0l8ff7b9duqETtzfRjqDiHAXJi+liNKVJjXVLo5EybeYEJHh3N+ivjP3zWtWMX3NI
    Cm8Xx5N6qak4jFNtzo2BmH1yyDU3LAjrI2uDmckCtE6ZYwxsZlOXAlrwtiwEyPOZOZQ4c8mOhQv4
    WiZCjkNfholywBh3DehwJLc5vM7hAEwVPAJuyduj+cOR059eQyfxuk9DtHyFsMTu4diXYuhZa2cm
    nleD/HBoImYkEy+W3h8Y9SUXUDV3w/1ZPSX29ZPpYClis4Sc+V0t2b/kS/+GeVf4tvyZ6LzKn1Ej
    +61dQ4NMAbGu0rYNJs0t3xruPNOdJ9IJHshPAOpJi2cQPbII8KAqbR1+B0cDWkUSmfYsXAqMJqc7
    NioSFduxtUkDXL1Lhl4VFIb1JHC7/uMD5aOhKYIq53if8zPvI7SX7bU9RglGA0M64vondAbXwh1A
    2xdT+vtQFYa10kA3FaqPtByxmUho0chuA2utqnXCU6qtqZa1Wvdl3mx6kSXEe+I3ENYevLucve+m
    GXLQ6l2uDVdnjqiLtPjRK5Ss/zktgTU2vHSFCSAzl7oW5tCDjazNr45ebpqXMWIZ/N6iyDytG8lN
    CbG60jkeTRb5mVdg/r7jqPVYUpeGvnsfcIK4vfo1rAjQzE16vf1f5FkRe/FJ7aLbCrf2HfE3PVrE
    dexHXHVpec1GtBkAcZPEpPrPGldbz84oEpAeLkXBpXCpnB9vPZZR3fXJKwSO4PpqD8FxO2cm8gkL
    gmGK83ii++SqADkcNv667gOk0cB/+7uv5IVKVYrMcLqOQKxybTDaHYNR1TYnua3mJESMFwvy+yRO
    DK2PaBNLGI3S+1u5R0Vvyyvfm/HJZw1w71O7v37N0ubVaJrbTv5QyJ5KFGxSDG/EYIaI/NbdjP9f
    XKszlcHjU8NcVpvrGzUQAfmkzLW21/04+mZpfuolV/CsA2rP0KKFuE+IqxAPTan/6H9PfVnY9OZ/
    kHi47EptJlJQr2ZLeqDOY5HJFPN6ynuPksgQnn9Pzo/7HUGkqJHISRTa4HUEWBSB3UKI+6SC0w6q
    DfTvPpj8Zfh/DuX+J7k9WWTh88U91MXQv4PO3iuhYymKjjAfAEdsJHKCsp81CNsSHV/VSXJB00Yw
    0059QtJNTFT5X3OTztfgSgMhDn0vEBmB0pKBOWLJKaqsOVYzyOu6TZh80WZ09K8/I2PA0+tLFMyu
    FUTXsVSEEEeFFViDC79O6ATJ2CqIUdZzgi/dfPYS3z+Epau6/Fou5gDDFGpY/c6MvOp+gwzlSAmS
    rPumQb44TmnuZAWSwmh6qYIK7v4e1Se1b9c2THmXNCF7KRqOFIVvrPyw48ZdadoVM2PG1d4DuEGM
    5EeUs5AxLX5sPM+99M90K5ACrBp8lN5aHmI/pmWvqKOXG2ebJIj/Q5W8OjzP5SFaahiGQrd1/OyG
    81gEXbC2Skf+wRdhgpInsEmDZ8Wb7+Yzyv5f4e+eG/BZ+s+eOJqtIGrpBNbtqL/2CXeBu1+5Lbe5
    5deIDBQQb7N1BhGa1DosrANj3iwlqsQ9IpEn4ntxkPjlVAyXV5wCkGTFQMgrHwCRh6KTnLhKToHs
    GSYgjkxJjSyTeJ60B3a7E/KfXPsJpw40qOkCOh3vXLrRO0dci+V0ifVAA4eA4tPJ3ylxqMHEpJID
    NG1vLkP8TVfyDvnNQZYL2t99qehZK+1RyYZ/AmkV6MBvgNJaLHFBapcEkOGgUfmO4hqFQ+uYpK/5
    2aIa2yHS2tjeQr/8qBtdd+2yekYDqG/qCU+4WeIoWfMJCHTfpVCs+m+bYku+RHeeHSsRn/A7JL0M
    G63/pTwB69kCq5N/br8Iygg2mh/uFydT/ua05lNtCxFrVVg/Hs5yBYORS1Zz7FBo7GQZI3afP6Iv
    Ul9oOTeX5rdJaYj+yp5VMKgRy2V8aISMtiEx4ne4izUyYnrNUpt5pMqXW4Dn+ZFeW4dJwK5jxpXE
    rkU1aULKBJh9KNGULnzDXQCvdu0jkKUhxvpXGkwpP1VDfdCFJUQ8jnpaWitSwrPTKqspU05+3Sp2
    Cpkem6lDm3cHmbbAru/sUo6l626fiv4qaBklZc/voZVo5X+RAVbOtFSwegeKlufkH8UsGRjRDrWI
    8WC8fh4XTuMY/3rAJ2h3tCus/9LnQE61exJUO/PkLFyhCRedRZ1DfJNS8CMJrGtFSzJVXqj3d0M/
    V9XF2nVA5onD+5HtHfjBqxJrbVqP5nu8YtKlTBZdEfau+wuvBSV0qmNV+19RGucVwAoA2cpl67/j
    3pDNnY4hmtNH/eo8Kcd7DXa8p/wWWVlF97V4niqQGCD2qe34SxH6fv0kex2X24FwlCVvnfkXkcn5
    1pyHRWX57kLudQZUXYdqxognkPhf7j7APGaPv+nupVezNI2qXyuZGLKkL449yjQnrBYKP7MlrE1s
    gS6vn5MLp0sMfpjlYterc0oF/qza1QDhPfnrQH6PgUWbA5dHOq7KUjn4q9W+H2ghedknFeEDp5Lw
    W8eLCHw4OOe5rC8JL7VT603UQdHBLxUDvFWoWfclBCBSazLCeuFy/p08gO/V7bUvrrPqI3ALYXLc
    PCZD7KQUI4qo29oJ+yrneu2hzGBFzBMWBasH9BcIK7BpZ+vWcdZ50Ev2OzwgtRC9OzxQCI30+p1j
    ldE0nq8+FKvVWqkt+dDoQNEfvQJ2bsqopkiMoeqispfuUsqYI5C7/cQbvxNlbPqDPZfikSSATzru
    Kl0jT8HmNKxuASj+yDldUhhAhLSKTucpfNbLUAGpsk277dOdT2k8ZK5UXs4cnZMTTBph5iTtdg+y
    eKukLtvt6xH2ymHsQdpaERn1ZQehrhjlnl0YGuVHJqq840A+bKqUVcbyJ3PdT8QuhWpYS5H1oBT8
    UcB3I15HN3KcKAATZJX6u9nV4iAlxKN3iZxqMfCAVpv9gAi99fXIEcvhkeoEi4ux4nYCDKVvJXnV
    8tznbh8FbfIGw7WVAcT49uzkgurX/UVACSYSMdn6wpTRTE==

I cant figure out what this contents means, but but the contents above is answer to API call. Now I am trying to figure out what it is asking for and how to reply.
Here I have made a simple script to read values and dump them to TXT file.
But file is empty.. No result so far with this code:
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$text = var_dump($__oc);
fwrite($myfile, $text);
$text = var_dump($__ln);
fwrite($myfile, $text);
$text = var_dump($__oid);
fwrite($myfile, $text);
$text = var_dump($__id);
fwrite($myfile, $text);
$text = var_dump($__here);
fwrite($myfile, $text);
$text = var_dump($__id);
fwrite($myfile, $text);
$text = var_dump($__rd);
fwrite($myfile, $text);
$text = var_dump($__i);
fwrite($myfile, $text);
$text = var_dump($__lp);
fwrite($myfile, $text);
fclose($myfile);
?>

I have also tried $_POST, $_GET and $_REQUEST but no result.
Is there any other way I can dump result from a API call?
Thanks for helping me out.

A: Example of fetching both $_GET and $_POST and write it to some logfile:
<?php
$rawpost = print_r($_POST, true);
$rawget = print_r($_GET, true);

$logfile = "/full/path/to/log/file/logfilename.log";
$fh = fopen($logfile,'a') or die("can't open the file");
fwrite($fh, "DATE: ".date('l jS \of F Y h:i:s A')."\r\n");
fwrite($fh, "\r\nRAW POST: =\t ".$rawpost."\r\n");
fwrite($fh, "\r\nRAW GET: =\t ".$rawget."\r\n");
fwrite($fh, "-------------------------------------------------------\r\n");
fclose($fh);
?>

With the above if someone posts data with the GET and POST method it will write it to the logfile. Your log file will need the proper write permissions if you are on a Linux system.
btw: The content of that index.php file is encoded with ionCube.


text:
Q: Express performance requiring modules Having a question regarding the performance of a NodeJS application.
When I have the following express app in NodeJS:
const app = require('express')();
const about = require('./about');

app.use('/about', about);

app.listen(3000, () => console.log('Example app listening on port 3000!'));

My current understanding is that only when the server is started up it does need to require() these files using commonJS modules.
Question:
Does the express  application has to execute the require() statements with every request to the server or is this only necessary when starting the server?
Any extra information about how express works under the hood would be nice.

A: No, those require are only run once when you start the app. It would be different if you include those in the router functions.
app.use('/about', (req, res) => {
  const some = require('some');
});

Still in this scenario, modules require are cached so it's not such a big deal.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to Concatenate Multiple Message as one at the delivery by NodeJs SMPP Hello im using Nodejs with farhadi node-smpp library to send Message through smpp v3.4 protocals and gsm library to split the message, In my case i have a long Message(More than 255 characters), when i split the message i want it to be delivered as single long message, but unfortunately it is delivered in parts. Here are my sample codes for sending the message
var info = gsm(text);
var concat_ref = Math.floor(Math.random() * 255);
var part_id = 0;
info.parts.forEach(function(part){

  part_id++;
  var udh = new Buffer.allocUnsafe(6);
  udh.write(String.fromCharCode(0x5), 0); //Length of UDF
  udh.write(String.fromCharCode(0x0), 1); //Indicator for concatenated message
  udh.write(String.fromCharCode(0x3), 2); //  Subheader Length ( 3 bytes)
  udh.write(String.fromCharCode(concat_ref), 3); //Same reference for all concatenated messages
  udh.write(String.fromCharCode(info.sms_count), 4); //Number of total messages in the concatenation
  udh.write(String.fromCharCode(part_id), 5); //Sequence number ( used by the mobile to concatenate the split messages)

  session.submit_sm({
    source_addr:      from,
    destination_addr: to,
    message_payload: { udh: part.udh, message: part }
}, function(pdu) {
  console.log('sms pdu status', lookupPDUStatusKey(pdu.command_status));
    if (pdu.command_status == 0) {
        // Message successfully sent
        console.log(pdu.message_id);
    }
});

})

A: You can use the message_payload parameter (field name) as stated in the official SMPP's specification to send messages longer than 254 octets.
message_payload definition:

Contains the extended short message user data. Up to 64K octets can be
transmitted.

The official document says:

Applications which need to send messages longer than 254 octets should
use the message_payload parameter. In this case the sm_length field
should be set to zero.
The short message data should be inserted in either the short_message
or message_payload fields. Both fields must not be used
simultaneously.

I made a test with node-smpp, and it works. No need to concatenate.

A: It's not very clear what you mean by "i want it to be delivered as single long message".
But SMPP wise, what you are doing seems correct. Long messages are delivered in parts and they are concatenated by the terminal(phone) based on the three parameters : part_ref, part_number and total_parts. However, from my experience, the concatenation is not really standard across all devices. For instance, some devices don't wait long enough for all the parts to arrive and show incomplete messages or nothing at all.
You have 2 choices when sending concatenated sms via SMPP : One is what you used (UDH), but there are also TLV parameters dedicated for the 3 parameters. You could ask your SMPP provider about extra details on how they support the sending of concatenated messages.


text:
Q: If $a$ and $b$ are the zeroes of $x^2 + ax + b = 0$, then how many pairs of $(a,b)$ exist?
If $a$ and $b$ are the zeroes of $x^2 + ax + b = 0$, then how many pairs of $(a,b)$ exist?

*

*One

*Two

*Three

*Infinitely many

Also, what are these pairs?

A: Since $a, b$ are zeros, they each satisfy the equation:
$$x=a: \quad a^2 + a\cdot a + b = 0\iff 2a^2 + b = 0 \iff b = -2a^2$$
$$x = b:\quad b^2 + ab + b = 0$$
Substituting $b = -2a^2$ into the second equation: $$(-2a^2)^2 + a(-2a^2) + -2a^2 = 0 \iff 4a^4 -2a^3 - 2a^2 = 2a^2(2a^2 -a - 1) = 0$$
The right-hand factor itself factors nicely, giving you 3 solutions to $a$, and then you can find the corresponding value for $b$ by using $b = -2a^2$.

A: Sum of the roots is $a+b = -a \implies 2a+b = 0$.
Product of the roots is $ab = b \implies b = 0 \text{ or } a = 1$.
If $b=0$, then $2a+ 0 = 0 \implies a = 0$.
If $a=1$, then $2+b = 0 \implies b = -2$.

A: Hint: if $a$ and $b$ are the zeroes then $x^{2}+ax+b=\left(x-a\right)\left(x-b\right)$.


text:
Q: Using quote() and substitute() for conditions within a shiny app I'm trying to use quote/substitute as a method to apply a condition in shiny. I'm not very familiar with either quote/substitute or shiny - so it is definitely possible that I'm not going about this problem in the right way.
I've created a simple example below that I illustrates the problem I get.
#Create test dataframe
test<-data.frame(x=c(0:10), y=c(rep(1,5),rep(2,6)), z=c("A","A","A","B","B","B","C","C","C","C","C"))

#example of what I would like to do outside shiny app
test[test$x > 5,]

#or using quote and eval
test[eval(quote(test$x > 5)),]

All of the above code works. But now lets say I want to apply it within a shiny app (and allow the user to choose the condition):
#create simple shiny app
require(shiny)

# Server
server <- function(input, output) {

  # subset of nodes
    df <- reactive({

        #eliminate certain observations
        x <- test[eval(input$condition),]

    })

    output$table <- renderTable({
        df <- df()

    })

}

# UI
ui <- fluidPage(

radioButtons("conditon", "Condition", choices = c("cond_1" = substitute(test$x > 5), "cond_2" = substitute(test$x<5))),

tableOutput("table")

)

# Create app
shinyApp(ui = ui, server = server)

But this gives the error "All sub-lists in "choices" must be names"). I'm not sure how to interpret this, and so am stuck. I looked at the answers in Shiny - All sub-lists in "choices" must be named? but did not find them helpful.
Would appreciate a way to solve this, or suggestions of a better approach (though note that I can't create the subsets ahead of time, as for my more complex actual example this creates issues).

A: A quick fix could be to wrap with deparse and then use eval(parse.  It is not entirely clear why the input needs to be expressions.  If this is just for subsetting, there are easier ways to accomplish the same
library(shiny)

-ui
ui <- fluidPage(
  radioButtons("conditon", "Condition",
                  choices = list(cond_1 = deparse(substitute(test$x > 5)),
                                 cond_2 = deparse(substitute(test$x<5))),
            selected = deparse(substitute(test$x > 5)) ),

   tableOutput("table")

  )

-server
server <- function(input, output) {

  # subset of nodes
  df <- reactive({

    #eliminate certain observations
     test[eval(parse(text=input$conditon)),, drop = FALSE]

  })

  output$table <- renderTable({
     df()

  })

}

-Create app
shinyApp(ui = ui, server = server)

-output


text:
Q: (click) and [ngClass] not changing table cell color Im trying to change the color of a cell within a table once clicked using the following:

                {{ column | uppercase }}

When each cell is created during the loop, It also has a click event added to it corresponding to the css styling. However, once a cell is clicked I get no change in color at all.
For reference the css is:
toChange {
     background-color: blue;
}

Anyone care to explain to me why my code doesn't work? Many thanks!

A: You do have two [ngClass] directives. Put them into a single one and separate them with commas like this:
[ngClass]="{'selected': column == val, 'toChange': clicked}"

A: Try this:
[class.toChange]="column == val"

A: one issue might be two [ngClass] do like this , you should not have more then on [ngClass] on element

                {{ column | uppercase }}

or you can do like this to make it more readable code

Below will work as you need as per you comment, only want to color clicked cell
Dunno if I'm pushing
  my luck here man but do you know any amendments I could do to colour
  the specifically clicked cell rather than the whole table?

                    {{ column | uppercase }}

 clickedIndex: number;

   setClickedIndex(i){
      this.clickedIndex = i;
   }

    getCssClasses(column,index) {
    let cssClass = column;
    if(column == val)
      cssClass = ' selected';
    if(index===this.clickedIndex)
       cssClass = ' toChange';
    return cssClass;
    }


text:
Q: Pearson Correlation from multiple rows I want to calculate the Pearson Correlation between two arrays.
The function CORR only accepts 2 values which has to be in a table. In my procedure I select multiple rows of numbers from two different sets and I want to calculate the correlation from them.
EDIT:
The corr function is an oracle function which calculates the pearson correlation between two values. Here is the problem. I want to calculate the correlation between two arrays which says to me array1 is similar to array2 of for example 50%.

A: You can simply calculate average of pairwise correlations
select
  (abs(corr1) + abs(corr2) + abs(corr3))/3 as Avg_Corr
from (
  SELECT
    CORR(a.col1, b.col1) as corr1,
    CORR(a.col2, b.col2) as corr2,
    CORR(a.col3, b.col3) as corr3
  FROM table1 a, table2 b
  WHERE a.id = b.id
)

or use more complex but more adequate generalization of Pearson correlation (there are no internal function in Oracle for this)


text:
Q: Why do some figures sparkle? I've noticed that some Pokemon have sparkles when viewed in the library or on the board - e.g.

Why? And does this make any difference to a non-sparkled version?

A: It seems that that's just the way the figures look for some Pokémon.
Based on threads like this one that mention the lack of shiny Pokémon in Pokémon Duel, it looks like this is just the standard figure for Jolteon.

I'm surprised there's no "foils" in this game. Shiny color palettes and some sparklies would be a good way to bling out a deck.

I noticed there are a few others that also have sparkles on the Serebii page with all of the figures listed.
From that list, Jolteon and Vaporeon both appear to have sparkles on their figures.
As mentioned by @Gremlin, these appear to be all of the figures with rarity "Rare". After looking back at the list, I can confirm this.
The following 49 Pokémon have sparkling figures:

*

*Armaldo

*Murkrow

*Steelix

*Luxray

*Heracross

*Meowth

*Skarmory

*Machamp

*Wobbuffet

*Dratini

*Eevee

*Pinsir

*Absol

*Salamence

*Gabite

*Drapion

*Goodra

*Lapras

*Pikachu

*Sneasel

*Electabuzz

*Tyranitar

*Tentacruel

*Banette

*Slaking

*Jigglypuff

*Onix

*Gastly

*Gyarados

*Flygon

*Sylveon

*Leafeon

*Vaporeon

*Jolteon

*Wigglytuff

*Shiftry

*Kirlia

*Ralts

*Glaceon

*Weavile

*Flareon

*Magmar

*Umbreon

*Hydreigon

*Dragonair

*Whimsicott

*Gothitelle

*Reuniclus

*Druddigon

A: Following this link to a list of figures given by Vemonus, it seems that all Rare (R) figures have sparkles.


text:
Q: Why would layer be nil, after wantsLayer=true? I made a new OS X project in Xcode 8, added a single (image) view.  I dragged it to the default ViewController source, to add an @IBOutlet (named "image").  Then in viewDidLoad(), I added:
image.wantsLayer = true
image.layer!.cornerRadius = 10

About half the time, it works fine, and about half the time, it dies with:
fatal error: unexpectedly found nil while unwrapping an Optional value

while pointing at the second line, and in the debugger:
(lldb) po image.wantsLayer
true

(lldb) po image.layer
nil

Is setting wantsLayer supposed to create a layer immediately?  The documentation seems to suggest this, but I can't find a statement that makes this explicit.
I've seen a lot of code, like this, which makes an NSView do:
self.wantsLayer = true
self.layer!.backgroundColor = ...

so it seems like it ought to.  Why would layer be nil, after setting wantsLayer?  Am I supposed to set layer myself, even if I ask for wantsLayer?

A: For layer backed views on OS X it is not recommended to interact with the layer object directly. The layer is owned by AppKit. That is described in a few more words here as well: https://www.objc.io/issues/14-mac/appkit-for-uikit-developers/
Now, if you subclass your view and return YES/true on wantsUpdateLayer property of your NSView, you can update the layer in updateLayer. Note this will lead to AppKit not calling drawRect anymore.

A: For future searchers here's the Swift 3 code to safely set the corner radius for an image (or NSView), no subclassing needed. It's dangerous to access the layer directly because NSViews are not always backed by Core Animation layers. Instead you can create a layer-hosting view and write to that.
So, in viewDidLoad():
let layer = CALayer()
image.layer = layer
image.wantsLayer = true
image.masksToBounds = true
image.cornerRadius = 19


text:
Q: What is blocking in async or sync? I'm thinking about async / sync / blocking / non-blocking while learning OS. I read many articles but, these just focused on non-blocking or how async does work with a simple picture. But I want to know what blocking really is in the more big picture including CPU, Memory, OS, I/O Device etc.
So, this picture is my guess.

I think the blocking means that My App's code is not processed by CPU from 1 until 5. Am I right?
And my understanding of blocking is right?

A: The answer is not simple, You may have to look at the javascript event loop. Because you are using async, await it does not mean your application is blocked, they are used to avoid writing complex callback hell or promise chains. When your are using async and await the javascript will add those executions as required to the event loop to  avoid executions that may need one execution completed before the next one.
But in the meantime it will execute other executions, which is not related to each other and wait one for finish (maybe rendering the webpage while HTTP response comes in).
So in big picture your app will only use one CPU thread. All other non blocking magic happens due to the the implementation of event loop, which makes your application non blocking, but not asynchronous (No matter what a javascript process is always a synchronous process).
If you need real asynchronous executions on your nodejs or javascript. Child Processes and web workers may help you to achieve that.

A: The best way to learn this is to look at an operating system that has synchronous and asnchronous I/O system services. Windoze under the covers and (best example) VMS are such operating systems.
In the VMS operating system, the SYS$QIO and SYS$QIOW perform I/O operations.The two system services have identical parameters. One of those parameters (optional) is the address of a routine to be called when the I/O operation completes (known as an AST) and another (option) is a parameter to pass to that routine.
If your application calls SYS$QIO, that function returns immediately after the I/O operations is queued and the application can continue to do other processing. The application has to rely on the callback routine to know when the I/O is done.
If your application calls SYS$QIOW, that function waits (suspends the process) until the I/O operation is complete.
When such non-blocking I/O is available as under SYS$QIO, your application can set up loops of asynchronous operations. Let's say your application wants to handle an arbitrary number of network connections where data can come in at any time. For each connection, you call SYS$QIO to read from the connection. Your process does not wait so it can do that for any number of connections. When data comes in, the AST function gets called and you so another call to SYS$QIO (giving the same function as the AST) to do the next read.
Using this method a single program can handle hundreds (as any as the system parameters will allow) of network connections.

A: Your app will stop at a synchronous request (whatever it is doing) and wait until the request finished.
PRO: on the next line in your app you can rely that this sync request has done whatever it was doing
CONTRA: your app just sits and waits. It is blocked.
Your app will not stop at an asynchronous request (whatever it is doing).
PRO: App will continue working. It is not blocked
CONTRA: if you need to know when the request is finished and what it's result is, you need take special care to get the result (using callbacks or events or promises or whatever technology is used in your technological framework)


text:
Q: How to synchronize DataTables with database I'm creating a small wpf project which involves users registration. In this project I'm using dataAdapter to load data from database to datatables.
con = new SqlConnection(connectionString);

string query = "select * from Users;";
cmd = new SqlCommand(query, con);
da = new SqlDataAdapter();

da.SelectCommand = cmd;

users = new DataTable();
con.Open();
da.Fill(users);

Database have 6 columns Id which is auto increment, username, password, name and two int type columns with default value to Zero. Here is database schema.
CREATE TABLE [dbo].[Users] (
    [Id]        INT           IDENTITY (1, 1) NOT NULL,
    [username]   NVARCHAR (20) NOT NULL,
    [password]  NVARCHAR (20) NOT NULL,
    [name]      NVARCHAR (50) NULL,
    [attempted] INT           DEFAULT ((0)) NULL,
    [correct]   INT           DEFAULT ((0)) NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC),
    UNIQUE NONCLUSTERED ([username] ASC)
);

Whenever I insert new user into datatable I only provide username, password and name remaining field should be filled automatically but datatable only save provided fields and remaining are left blank and when I call
da.update(users);

it update data in database and remaining fields are filled automatically butt datatable still contain those fields as empty columns.

But I need user Id to update or delete user. Problem is how can I sync datatable with database for updated fields so I could use them for further operations. Thanks in Advance for your assistance.
Update:
Insert query and parameters are given below
query = "insert into Users (username, password, name)values(@u, @p, @n)";
SqlCommand insertcmd = new SqlCommand(query, con);
insertcmd.Parameters.Add(new SqlParameter("u", SqlDbType.NVarChar, 20, "username"));
insertcmd.Parameters.Add(new SqlParameter("p", SqlDbType.NVarChar, 20, "Password"));
insertcmd.Parameters.Add(new SqlParameter("n", SqlDbType.NVarChar, 50, "name"));

da.InsertCommand = insertcmd;

A: After the insert command do thes to get the ID:
select SCOPE_IDENTITY()
int newId = Convert.ToInt32( cmd.ExecuteScalar());

Then add the newId to the right place
This is an example:
 SqlCommand cmd = new SqlCommand("Insert into Products (ProductName, UnitPrice) VALUES (@ProductName, @Price); select SCOPE_IDENTITY()", conn);
int newId = Convert.ToInt32( cmd.ExecuteScalar());

A: If you are using a stored procedure, make sure to declare the id parameter as an output parameter.
create procedure dbo.SaveUser
(
    @id int = null out,
   ...
)
as
begin

     --insert goes here

     set @id = scope_identity()
end

A: I used following parameterized insert query to update Id field in dataTable on the basis of Id generated by database.
query = "insert into Users (username, password, name)values(@u, @p, @n); set @Id = SCOPE_IDENTITY()";
insertcmd = new SqlCommand(query, con);
insertcmd.Parameters.Add(new SqlParameter("u", SqlDbType.NVarChar, 20, "username"));
insertcmd.Parameters.Add(new SqlParameter("p", SqlDbType.NVarChar, 20, "Password"));
insertcmd.Parameters.Add(new SqlParameter("n", SqlDbType.NVarChar, 50, "name"));

SqlParameter Id = new SqlParameter("Id", SqlDbType.Int, 0, "Id");
Id.Direction = ParameterDirection.Output;

insertcmd.Parameters.Add(Id);

da.InsertCommand = insertcmd;

Complete explanation given here with stored procedure.


text:
Q: A question about the number of chords in a cycle Prove that there exists a positive constant $d$, such that for every graph $G$ with minimal degree at least $d$, $G$ contains a cycle $C$ with at least $l$ chords, where $l$ is the length of $C$, and a chord in $C$ is an edge in $G[C]$ but not on $C$.
The proof may need to consider a longest path in $G$ and use Posas's Rotation Lemma.
Thanks in advance


text:
Q: How can i copy the visual content of a window and put it on a new window in win32 c++? I've read something about GetDIBits or BitBlt but i do not understand them.
That could be because i don't understand how Windows actually handles graphics on windows. It would be perfect if someone could refer me to a page where i could learn about these things! :)

A: I solved the problem using this code in the windows WM_PAINT. It now shows the exact same content as the target window.
PAINTSTRUCT ps;
HDC hdc = BeginPaint(MainWindow, &ps);

HDC TargetDC = GetDC(TargetWindow);

RECT rect;
GetWindowRect(TargetWindow, &rect);

BitBlt(hdc,0,0,rect.right-rect.left,rect.bottom-rect.top,TargetDC,0,0,SRCCOPY);

EndPaint(MainWindow, &ps);

A: You might have some luck with sending the window a WM_PRINTCLIENT message.  This may not work well for windows that use DirectX or OpenGL.
You may have some issues using WM_PRINTCLIENT on systems that have Aero enabled (i.e. when the DWM is active).  If the system DOES have DWM active then it may offer ways of getting at the window backing store but I have not looked into doing that in any great depth before.

A: What you want is to:

*

*Get a HWND to the window of which you want the pixels.

*Create a memory DC of the correct size (check this out).

*Send a WM_PRINTCLIENT or WM_PAINT to the window whilst supplying your memory DC (not all controls/windows implement this though)

*Copy the contents of your memory DC to screen

Alternatively for step 3 you can use the DWM or get hacky using the clipboard:
void CopyWndToClipboard(CWnd *pWnd)
{
    CBitmap     bitmap;
    CClientDC   dc(pWnd);
    CDC         memDC;
    CRect       rect;

    memDC.CreateCompatibleDC(&dc);

    pWnd->GetWindowRect(rect);

    bitmap.CreateCompatibleBitmap(&dc, rect.Width(),rect.Height());

    CBitmap* pOldBitmap = memDC.SelectObject(&bitmap);
    memDC.BitBlt(0, 0, rect.Width(),rect.Height(), &dc, 0, 0, SRCCOPY);

    pWnd->OpenClipboard() ;
    EmptyClipboard() ;
    SetClipboardData(CF_BITMAP, bitmap.GetSafeHandle()) ;
    CloseClipboard() ;

    memDC.SelectObject(pOldBitmap);
    bitmap.Detach();
}


text:
Q: Is there a way to use whitespace in BNFC? How do you use whitespace in a BNFC definition?
For example, suppose I want to produce a parser for the lambda calculus where I allow a list of variables to be abstracted:
\x y z.x z (y z)

The "obvious" thing to do is use a labeled rule like:
ListAbs . Exp ::= "\\" [Ident] "." Exp ;
separator Ident " "

However, BNFC defaults to stripping whitespace, so that does not work.  What does work is using a comma separator.  A bit uglier, but I could live with it... Still it would be nice to be able to separate by space.
Is there a whitespace character class in BNFC?

A: You can declare the empty string as separator:
separator Ident ""

In practice this lets you use white-spaces (or any space character) as separator:
$ cat test.cf
A . A ::= [Ident] ;
separator Ident ""
$ bnfc -haskell -m test.cf
$ make
$ echo 'x y z' | ./Testtest

Parse Successful!

[Abstract Syntax]

A [Ident "x",Ident "y",Ident "z"]

[Linearized tree]

x y z


text:
Q: Value retrieval from the Multiple selection dropdown in excel I am trying to make calculation from my dropdown menu.
This is how my dropdown looks.
Category

*

*AAA

*BBB

*CCC

*DDD

These are the values associated with my dropdown.
Category Category value

*

*AAA 1

*BBB   2

*CCC 3

*DDD 4

I added VBA code for multiple selection and also added simple Vlookup formula to retrieve the value of category.
=VLOOKUP(E2;Sheet2!I2:J5;2;)

With the VBA code, i am able to select all three category and also remove the selected category later. But I am failing to retrieve the sum of selected category. For e.g. I want if customer chooses category AAA & CCC, he/she should be able to see sum as 4. Also if customer first chooses all three category and then removes one of the category then also the sum should get updated. I am not getting how do i update my Vlookup formula to get the sum.
Here is my VBA code for multiple selection.
Private Sub Worksheet_Change(ByVal Target As Range)
    'Updated: 2016/4/12
    Dim xRng As Range
    Dim xValue1 As String
    Dim xValue2 As String
    If Target.Count > 1 Then Exit Sub
    On Error Resume Next
    Set xRng = Cells.SpecialCells(xlCellTypeAllValidation)
    If xRng Is Nothing Then Exit Sub
    Application.EnableEvents = False
    If Not Application.Intersect(Target, xRng) Is Nothing Then
        xValue2 = Target.Value
        Application.Undo
        xValue1 = Target.Value
        Target.Value = xValue2
        If xValue1 <> "" Then
            If xValue2 <> "" Then
                '                If xValue1 = xValue2 Or _
                '                   InStr(1, xValue1, ", " & xValue2) Or _
                InStr(1, xValue1, xValue2 & ",") Then
                If InStr(1, xValue1, xValue2 & ",") > 0 Then
                    xValue1 = Replace(xValue1, xValue2 & ", ", "") ' If it's in the middle with comma
                    Target.Value = xValue1
                    GoTo jumpOut
                End If
                If InStr(1, xValue1, ", " & xValue2) > 0 Then
                    xValue1 = Replace(xValue1, ", " & xValue2, "") ' If it's at the end with a comma in front of it
                    Target.Value = xValue1
                    GoTo jumpOut
                End If
                If xValue1 = xValue2 Then        ' If it is the only item in string
                    xValue1 = ""
                    Target.Value = xValue1
                    GoTo jumpOut
                End If
                Target.Value = xValue1 & ", " & xValue2
            End If
            jumpOut:
        End If
    End If
    Application.EnableEvents = True
End Sub

A: I would do something like so for the summation part.  I have my reference table A1:B4.  I called using Get_Sum("A,C,D")
Function Get_Sum(strInput As String) As Double

Dim a() As String
Dim v As Variant
Dim r As Excel.Range
Dim l As Long

a = Split(strInput, ",")
Set r = Range("a1:b4")

Get_Sum = 0

For Each v In a
    l = Application.WorksheetFunction.Match(v, r.Columns(1), 0)
    Get_Sum = Get_Sum + r.Cells(l, 2)
Next v

Set r = Nothing
Erase a

End Function

Calling like so
Private Sub Worksheet_Change(ByVal Target As Range)

    '   Where A5 is the validated cell and B5 is the sum result

    If Target = Range("a5") Then
        Range("b5").value = Get_Sum (Target.Value)
    End If

    End Sub

A: Instead of coding in VBA, you can simply use this function and it will work.
=SUMPRODUCT(ISNUMBER(SEARCH(Sheet2!A1:I4;Sheet1!A2))*Sheet2!B1:B4)


text:
Q: Will my pdf look same in other computers Say I use a font "foo" in my TeX document.

\setmainfont{foo}

This font is not free or not widely available on other systems.
Will my PDF document will look same in other computers where this font is not available / installed?
And if not what can I do about it to make sure that it looks same in other computers?

A: Fonts are embedded by default when you compile TeX to PDF. To be sure, you may wish to upload your PDF to a cloud, say, GoogleDrive (free) and see, how it looks there in another previewer.

A: I'm not an expert on PDF, but the whole idea of PDF in opposite to Word is that the viewer displays the same picture and the printer prints the same glyphs on the paper.
Well, more or less. It obviously does not depend on the installation of fonts on the computer you use to display the PDF, but there are differences even between different viewers on the same computer. Compare the display of a PDF by Adobe's Reader and DocView (Emacs!). For an example see here: Why do fonts look thinner in adobe and different and richer in sumatra pdf
And think of the properties of the printer. Or: A printout from a dot matrix printer will look completely different from a ink printer. Even laser printer produce very different output.
tl;dr: Your PDF will look quite similar, independently from installed fonts.

Edit:
There seems to be a misunderstanding about the license of commercial fonts. Of course you can use a fonts you bought to produce a PDF. The company which sold the fonts to you has no whatever rights on your PDF! Selling fonts includes the fair use of making a PDF. And making a PDF means that all the needed glyphs become part of the PDF. (I am a lawyer! OK, only in Germany.)
It is something different, if you embedd by using attachfile, embeddfile or whatever the *.ttf or *.otf file itself -- this might not be legal!

Edit 2:
There are companies which try to limit the use of sold fonts to a PDF with a circulation of one hundred copies, e.g. the Font Bureau in Florida (thank you, Thérèse). I read the license agreement of some of the fonts I bought and there is no limitation for a PDF, but the lincense of Linotype says:

»Embedding of the Font Software into electronic documents
  or Internet pages is only permitted under the absolute assur-
  ance that the recipient cannot use the Font Software to edit or
  create a new document (read-only). It must be ensured that the
  Font Software cannot be fully or partially extracted from said
  documents.«


text:
Q: How to find a 2x2 matrix with integer entries for eigenvalues and eigenvectors using python? For example, if I had eigenvalues 7 and 20 with eigenvectors (2,3) and (1,3), how would I go about calculating the 2x2 matrix? Can I use python to calculate an array with these integer entries?

A: This is more of a math than programming question. To get a matrix with eigenvalues 7 and 20 and eigenvectors [2, 3] and [1, 3] you need to create a matrix P which has the eigenvectors as columns and a diagonal matrix D with eigenvalues on the main diagonal. Using numpy this would be:
import numpy as np

P = np.array([[2, 3], [1, 3]]).T
D = np.diag([7, 20])

(this assumes that 7 is the eigenvalue corresponding  [2, 3] and 20 is corresponding to [1, 3]). The matrix you are looking for is obtained by multiplying PDP^(-1). With numpy:
A = P@D@np.linalg.inv(P)

Since numpy is using floating numbers, there is some loss of precision involved in computing the inverse matrix of P. If you want to avoid it and get entries of A expressed as fractions you can use sympy instead:
from sympy import Matrix, diag

P = Matrix([[2, 3], [1, 3]]).T
D = diag(7, 20)
A = P*D*P**(-1)


text:
Q: Fetch assoc error Hello
i'm trying to make a table with this query but i cant get it to work. the thing is that it cant select 2 query's at a time but i dont know another way for it..
$active_ids = '1, 3, 4';
$query = "SELECT * FROM users WHERE id IN ({$active_ids})";
$result = $mysqli->query($query);

$query = "SELECT dj, count(*) AS n FROM timetable WHERE dj IN ({$active_ids}) GROUP BY dj";
$result = $mysqli->query($query);

while($row = $result->fetch_assoc()){
    echo $row['username'], "
";
    echo $row['n'], "
";
}

A: Try this:
$active_ids = '1, 3, 4';
$result = $mysqli->query("
    (SELECT * FROM users WHERE id IN ({$active_ids}))
    UNION
    (SELECT dj, count(*) AS n FROM timetable WHERE dj IN ({$active_ids}) GROUP BY dj)
") ;

if (!$rec = mysqli_fetch_array($result)) {
    echo ("Sorry, no records found");
}
else {
    do {
        echo ($rec["username"]);
        echo "
";
        echo ($rec["n"]);
        echo "
";
    }
    while ($rec = mysqli_fetch_array($result));
}

A:      $active_ids = '1, 3, 4';

    $query = "SELECT users.* from users
              LEFT JOIN timetable ON users.id=timetable.dj
                  WHERE users.id IN ({$active_ids})
              UNION
              SELECT timetable.dj,timetable.count(*) as n from timetable
              RIGHT JOIN users ON timetable.dj=users.id
                  WHERE timetable.dj IN ({$active_ids}) GROUP BY timetable.dj
    ";
    $result = $mysqli->query($query);

    while($row = $result->fetch_assoc()){
        echo $row['username'], "
";
        echo $row['n'], "
";
    }

I don't know it is certainly true but can you try this code ?


text:
Q: приватный метод область видимости namespace user\login\SystemCommand;

class Command extends SystemCommand
{
    ...
    private function transaction (){
        ...
        $date = new DateTime();
        $date->add(DateInterval::createFromDateString('yesterday'));
        $time =  $date->format(\DateTime::RFC3339);
        ...
    }
    ...

    echo $this->yad_transaction();
}

Почему возникает ошибка
PHP Fatal error:  Class 'user\login\SystemCommand\DateTime' not found in ...


text:
Q: which barcode sdk for iOS and Android I should use to scan IMEI number on mobile wrapper I want to scan the barcode of IMEI of mobile device using mobile application. Current barcode type of IMEI is of 15 numeric digit, as shown in following image :

*

*Please let me know the barcode codec type it is using?

*SDK to scan this barcode for iOS application

*SDK to scan this barcode for Android application

A: There are a lot of Barcode SDKs out there that can read the IMEI barcodes which is a Code128 type Barcode.
The company I work for has a Barcode SDK that supports reading over 100 1D and 2D barcode types including Code128 on many different platforms including iOS and Android.
Here is all the code you would need in order to read these types of barcodes on your devices:
Android
BarcodeData data = null;
data = mBarcodeEngine.getReader().readBarcode(<image to be processed>, <screen coordinates to search in>, <barcode symbologies to search for>); return data;

iOS Obj-c
data = [_barcodeEngine.reader readBarcodes:rasterImage
searchBounds:LeadRectZero symbologies:enabledSymbologies options:_barcodeReadOptions error:&error];

iOS Swift
data = try? self.barcodeEngine.reader.readBarcode(rasterImage, searchBounds:
LeadRectZero, symbologies: enabledSymbologies, options: self.barcodeReadOptions)


text:
Q: How do I detect that a tilt sensor has been tilted "shorted" when polling only every minute? I thought about modifying this circuit (Momentary switch power: press to turn on, microcontroller can turn itself off), but I wonder if something simpler might work (or if someone had a better idea)?
I'm using the Atmel SAM R21 Xplained to prototype a device.  I want to detect if a tilt sensor has been activated, but I don't want to continuously poll its stated so I can save power.  I'd like to poll, let's say once a minute, send it's state over 802.15.4 to the cloud.
Here is the idea I've come up with:
By using a digital output to charge a capacitor and the analog input to detected it's voltage, track the capacitor's voltage to see if it got shorted out within the 1 minute interval.  The circuit would look something like this:

simulate this circuit – Schematic created using CircuitLab
The algorithm would be:

*

*Initially charge the capacitor.

*Loop forever -
Detect, if the voltage dropped significantly, send a message.
Charge the capacitor.

Thanks,
Greg

A: The usual approach to this sort of problem would be not to poll, but to use an interrupt.
If you mask the interrupt but poll the interrupt request flag you will have essentially the same result as what you have suggested, with no hardware (consider filtering to establish a minimum pulse length in order to reject noise).

A: Maybe just use an interrupt? That way the sensor High will wake up the mcu rather than having to poll.
A quick check of Amel seems to indicate they are supported. Ie
The Atmel SAM R21 devices provide the following features: In-system programmable Flash, 12-channel direct memory access (DMA) controller, 12-channel Event System, programmable interrupt controller, up to 28 programmable I/O pins, ultra-low power 2.4GHz ISM band transceiver with a data rate of 250kb/s, 32-bit real-time clock and calendar, three 16-bit Timer/Counters (TC) and three 16-bit Timer/Counters for Control (TCC), where each TC can be configured to perform frequency and waveform generation, accurate program execution timing or input capture with time and frequency measurement of digital signals.


text:
Q: GCP's Vertex AI - Restarting notebook :  does not have enough resources available to fulfill the request I'm having issues starting / creating new user-managed notebooks in Vertex AI > Workbench, where I'll end up with this error and can't even open JupyterLabs:

[Vertex AI] - Restarting notebook NAME: ZONE does not have enough
resources available to fulfill the request. Retry later or try another zone in your configurations.

I didn't have this problem last month when I was still under the free trial. I also noticed this error only come up when I try to install the GPU in the notebook.
So far, I've done the following:

*

*Change payment method (got an email that asked me to update payment settings at the end of the trial last month)

*Create new notebook in different zones and cluster over the past week, all give the same error when I attach a GPU.

*In Quotas, changed 'GPU (all regions)' from 1 to 0, and then back to 1.

*In Quotas, changed 'VM instances (default)' from 24 to 48, and then back to 24.

*Created several new projects, didn't work either.

I also created a snapshot of both the data and boot of the notebook, but don't know how to use it to recreate it in Vertex AI again.
Have you faced a similar issue before, how did you fix it? Thanks


text:
Q: Failed to resolve: com.github.worker8:tourguide:1.0.17-SNAPSHOT Whenever I'm trying to include worker8/TourGuide library in my gradle file it is throwing me this error:

"Failed to resolve: com.github.worker8:tourguide:1.0.17-SNAPSHOT"

I tried to clean the project and tried to rebuild as well but nothing worked for me. Please provide your help. Thanks in advance.
app gradle file
android {
                compileSdkVersion 26
                defaultConfig {
                    applicationId "com.example.abdulrehman.myapplication"
                    minSdkVersion 15
                    targetSdkVersion 26
                    versionCode 1
                    versionName "1.0"
                    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
                }
                buildTypes {
                    release {
                        minifyEnabled false
                        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
                    }
                }
            }

            dependencies {
                implementation fileTree(include: ['*.jar'], dir: 'libs')
                implementation 'com.android.support:appcompat-v7:26.1.0'
                implementation 'com.android.support.constraint:constraint-layout:1.0.2'
            //    compile ('com.github.worker8:tourguide:1.0.13-SNAPSHOT@aar'){
            //        transitive=true
            //    }
                compile 'com.github.amlcurran.showcaseview:library:5.4.3'
                testImplementation 'junit:junit:4.12'
                androidTestImplementation 'com.android.support.test:runner:1.0.1'
                androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
            }

Project gradle file
buildscript {

                repositories {
                    jcenter()
                    google()
                    mavenCentral()
                    maven(){
                        url "https://oss.sonatype.org/content/repositories/snapshots"
                    }
                }
                dependencies {
                    classpath 'com.android.tools.build:gradle:3.0.0'
                    classpath 'com.google.gms:google-services:3.0.0'
                }
            }

            allprojects {
                repositories {
                    jcenter()
                    google()
                }
            }
            task clean(type: Delete) {
                delete rootProject.buildDir
            }

A: dont place third party url in buildscript. place in allprojects.
   buildscript {
                repositories {
                    jcenter()
                }
                dependencies {
                    classpath 'com.android.tools.build:gradle:3.0.0'
                    classpath 'com.google.gms:google-services:3.0.0'
                }
            }

            allprojects {
                repositories {
                    jcenter()
                    google()
                    mavenCentral()
                    maven(){
                            url "https://oss.sonatype.org/content/repositories/snapshots"
                        }
                }
            }
            task clean(type: Delete) {
                delete rootProject.buildDir
            }


text:
Q: Abstractions provided by the operating system In the book "Computer System: A Programmer's Perspective", it says that "files are abstractions for I/O devices, virtual memory is an abstraction for both the main memory and disk I/O devices, and processes are abstractions for the processor, main memory, and I/O devices.". I don't really understand that. Can anyone please give me some easy-to-understand explanation ?

A: The whole point about abstractions is that they don't exist physically, they are just conceptual. So a storage device is just a bunch of storage blocks, but we impose the abstract concept of directories and files as a way of organising all these blocks of storage into something useful. Each block on the storage device has no way of "knowing" that it belongs to a particular file.
Similarly for the other examples, e.g. processes don't physically exist - the CPU is just executing code, but we organise the code and the way it is executed conceptually into processes and threads, etc - the CPU has no "knowledge" of processes, it's just a code executing machine.


text:
Q: System.DllNotFoundException: Unable to load DLL 'AD101Device.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E) this question is already here But there's no suitable solution I found.
*I cannot Comment so than I had to ask in a new question.
There's a CallerID device attached with my pc. My application is needed to be hit if any caller calls. I've implemented the procedure. but got stuck with this .dll file.
*I am using Visual Studio Installer Project to create installer file. When I install and run my application I got, System.DllNotFoundException: Unable to load DLL 'AD101Device.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E) this error.
**Yes I've placed the .dll file on the bin folder.
please enlighten me, how can I overcome this situation with the .dll file working.
*I'm using Visual Studio 2015. .net framework version 4.5.1


text:
Q: 4 variable boolean algebra: Converting sum of maxterms to product of minterms I am struggling to convert the sum of maxterms:
((¬b ∧ ¬d) ∨ ((b ∧ (¬c ∧ d)) ∨ (¬a ∧ (b ∧ d))))
into a product of minterms.
I use Morgan and get this:
((¬b ∨ ¬d) ∧ ((b ∨ (¬c ∨ d)) ∧ (¬a ∨ (b ∨ d))))
which doesn't have an equivalent truth table.
(btw, this is a very handy site that is helping me
 http://web.stanford.edu/class/cs103/tools/truth-table-tool/ )
I know drawing Karnaugh's make it easier to visualize, but I wanted to learn how to do the conversion algebrically, just using Morgan and distribution laws. Any good soul to enlight me on this puzzle?
thank you really much and sorry for the dumb question!
Martin

A: Start as follows:
$$\begin{align*}
\overline{b}\:\overline{d} + b\: d\: \overline{c}  + b\: d\: \overline{a}\tag{1}\\\\
\overline{\overline{\overline{b}\:\overline{d} + b\: d\: \overline{c}  + b\: d\: \overline{a}}}\tag{2}\\\\
\overline{\overline{\overline{b}\:\overline{d}} \cdot \overline{b\: d\: \overline{c}} \cdot \overline{b\: d\: \overline{a}}}\tag{3}\\\\
\overline{(b+d) \cdot (\overline{b}+ \overline{d}+ c) \cdot (\overline{b}+ \overline{d}+ a)}\tag{4}\\\\
\overline{(b\:\overline{b}+ b\:\overline{d}+ b\:c+d\:\overline{b}+ d\:\overline{d}+ d\:c) \cdot (\overline{b}+ \overline{d}+ a)}\tag{5}\\\\
\overline{(b\:\overline{d}+ b\:c+d\:\overline{b}+ d\:c) \cdot (\overline{b}+ \overline{d}+ a)}\tag{6}\\\\
\overline{\overline{b}\:d+ \overline{b}\:d\:c+b\:\overline{d}+ \overline{d}\:b\:c+ a\:b\:\overline{d}+ a\:b\:c+a\:d\:\overline{b}+ a\:d\:c}\tag{7}\\\\
\overline{\overline{b}\:d+b\:\overline{d}+ c(\overline{b}\:d+ \overline{d}\:b)+ a(b\:\overline{d}+d\:\overline{b}+ b\:c+ d\:c)}\tag{8}\\\\
\overline{\overline{b}\:d+b\:\overline{d}+ a\:c(b+ d)}\tag{9}
\end{align*}$$

NOTE
The last, going from (8) to (9) above, can be handled several ways. Rather than belabor things with algebra, I'll just explain in words.
It's pretty easy to see that if \$\overline{b}\:d+b\:\overline{d}\$ is true or false, then \$c(\overline{b}\:d+ \overline{d}\:b)\$ is irrelevant. If \$c\$ is false, then the earlier term \$\overline{b}\:d+b\:\overline{d}\$ still over-rides. And if \$c\$ is true, all it does is permit the additional factor \$\overline{b}\:d+b\:\overline{d}\$ to express itself. But it already has done so. So \$c(\overline{b}\:d+ \overline{d}\:b)\$ is entirely redundant. It can be removed. I could write this algebraically, adding opposite conditions and then simplifying, but I think these words are sufficent to get the point across.
A similar argument also says that the same terms, \$\overline{b}\:d+b\:\overline{d}\$, that are inside of \$ a(b\:\overline{d}+d\:\overline{b}+ b\:c+ d\:c) \$ are equally pointless and can be removed, reducing it down nicely.

At this point, there are two completely equivalent statements in (9) above. You can choose either one of them:
$$\begin{align*}
\overline{\overline{b}\:d+b\:\overline{d}+ a\:b\:c}&=\overline{\overline{b}\:d+b\:\overline{d}+ a\:c\: d}\tag{10}
\end{align*}$$
The reason should be obvious. Examine \$\overline{b}\:d+b\:\overline{d}+ a\:c(b+ d)\$. If \$b\$ is false and \$d\$ is true, then the first term picks that up. If \$b\$ is true and \$d\$ is false, then the second term picks that up. So the only way that matters for the third term is when either \$b\$ or \$d\$ is true. But none of this matters unless both of the first two terms are false. And the only remaining possibility is that if one of \$b\$ or \$d\$ is true, then the other must also be true. So you can neglect either one of them; your choice. Hence, (10) must be a true statement.
So I'll pick the left side now:
$$\begin{align*}
\overline{\overline{b}\:d+b\:\overline{d}+ a\:b\:c}\tag{11}\\\\
(b+\overline{d})\cdot (\overline{b}+d)\cdot (\overline{a}+\overline{b}+\overline{c})\tag{12}
\end{align*}$$
But you could just as well have  picked the right side.
Algebra works.
Ask questions if you have any about the above process. I did a few things that you may consider "subtle" but are easily explained.


text:
Q: gstreamer: create rtp-stream out of mp4-file without transcoding I wanted to create a RTP-stream of a mp4-file with gstreamer.
I am using gstreamer 1.18.4 on debian bullseye.
To create a mp4-file I recorded an RTSP-stream from my webcam using the following command:
gst-launch-1.0 -e rtspsrc location="rtsp://192.168.111.146/axis-media/media.amp" port-range=28000-38000 buffer-mode=0 latency=80 ! rtph264depay ! h264parse ! mp4mux ! filesink location=filename.mp4

After recording the file filename.mp4 I tried to stream it using RTP:
gst-launch-1.0 filesrc location=filename.mp4 ! qtdemux ! h264parse ! avdec_h264 ! x264enc ! h264parse ! rtph264pay ! udpsink port=50000 host=127.0.0.1

And the playback of the stream could be started using the following command on the same machine:
gst-launch-1.0 udpsrc address=127.0.0.1 port=50000 auto-multicast=true ! application/x-rtp,encoding-name=H264,payload=96 ! rtph264depay ! avdec_h264 ! autovideosink

Everything works as expected!
But since I don't want to transcode the file, I just wanted to skip the decoding and encoding part. Therefore, I created the following pipelines:
gst-launch-1.0 filesrc location=filename.mp4 ! qtdemux ! h264parse ! rtph264pay ! udpsink port=50000 host=127.0.0.1

and
gst-launch-1.0 filesrc location=filename.mp4 ! qtdemux ! rtph264pay ! udpsink port=50000 host=127.0.0.1

However, if I retry the playback pipeline (the pipeline with udpsrc) on both pipelines the stream is not displayed.
Interestingly, nload shows network traffic on lo.
What is wrong with the streaming pipelines?
Did I miss some magic-plugin in between?

A: Meanwhile I found an answer to my question.
Changing the stream-server-pipeline from
gst-launch-1.0 filesrc location=filename.mp4 ! qtdemux ! h264parse ! rtph264pay ! udpsink port=50000 host=127.0.0.1

to
gst-launch-1.0 filesrc location=filename.mp4 ! qtdemux ! h264parse config-interval=-1 ! rtph264pay ! udpsink port=50000 host=127.0.0.1

solves the issue.
Thus, the difference is setting the parameter config-interval=-1 for h264parse.


text:
Q: NSMutableArray sort with object
Possible Duplicate:
How to sort an NSMutableArray with custom objects in it?

i have a object with Type of NSObject contains "posts" object type of NSMutableArray. that post object has ID property.
MyObject.posts.post.ID = NSInteger;
I want to sort "posts" NSMutableArray by ID. i have tried couple ways but couldn't be success.
any help/sample would be great.
thank you.

A: You can implement a compare method, or use NSSortDescriptor.
This question and the answer may helps you.
How to sort an NSMutableArray with custom objects in it?

A: You can sort an array with a block using NSComparator (NSComparator)
Definition of -sortedArrayUsingComparator: found here
MyObject.posts = [MyObject.posts sortedArrayUsingComparator:^(id obj1, id obj2) {
  if (obj1.post.ID > obj2.post.ID)
    return (NSComparisonResult)NSOrderedDescending;
  if (obj1.post.ID < obj2.post.ID)
    return (NSComparisonResult)NSOrderedAscending;
  return (NSComparisonResult)NSOrderedSame;
}];


text:
Q: What does the trace of a loxodromic Mobius transformation tell us about how it rotates? A matrix $X=\begin{pmatrix}a&b\\c&d\end{pmatrix}\in\mathrm{PSL}_2(\mathbb{C})$
acts isometrically on the upper half-space model $\mathbb{H}^3$
via isometric extension of the Mobius transformation on $\widehat{\mathbb{C}}=\partial\mathbb{H}^3$,
which is defined by $X(z)=\dfrac{az+b}{cz+d}$.
$X$ is called loxodromic if $tr(X)=a+d\in\mathbb{C}\smallsetminus[-1,1]$.
The action of such an isometry is by translation along and rotation about a unique invariant axis in $\mathbb{H}^3$.
This action can be described completely by a specification of

*

*a pair of fixed points on $\widehat{\mathbb{C}}$ (the axis being the
geodesic between these),

*the translation length, and

*the angle of rotation.

For 1: The fixed points can be directly solved for in terms of the entries, and in fact this is related to the classification of the type of isometry by trace, using the characteristic polynomial. As far as I know the expression in $a,b,c,d$ however is not linked to a convenient matrix property. Is it?
For 2: The translation length can be computed from the trace. In fact it's $2\mathrm{cosh}^{-1}(\frac{tr(X)}{2})$ where if necessary we use the complex logarithm.
For 3: What about the rotation amount? If we only know the trace, can we determine this? If not, is there some other nice minimal matrix property that gives this information? My feeling is that if $tr(X)=x+iy$ where $x,y\in\mathbb{R}$ then we should have something like a translation length determined by $x$ and a rotation angle determined by $y$.
If this is well-known, forgive me, I am not finding it in my references. If this is the case please feel free to migrate to stackexchange.

A: Complex translation length $\lambda$  is given by $tr X = 2\cosh \lambda,$ where $\Re \lambda > 0,$ and is the translation length, whilst the imaginary part is the rotation angle.


text:
Q: How can I make link go to a page and toggle popup in it? I need to have a link open certain page and toggle a hidden popup in it right after. The popup normally shows by click on a specified button on that page. Is this even possible? I need this for a html email template, so not sure if javascript will work

A: I would append a URL parameter to the link in the email... Something like
?popup=true
Then, on the page that you've linked to in JavaScript you can check for that URL parameter then display the popup.
var urlParams = new URLSearchParams(window.location.search);
if (urlParams.get('popup') === 'true') {
    // show popup code here... $('.popup').show() if using jQuery...
}

URLSearchParams doesn't working in IE though https://caniuse.com/#feat=urlsearchparams
So if you need to support IE you can use this function instead
function getUrlParameter(name) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var results = regex.exec(location.search);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};


text:
Q: UIPath Tibco EMS Integration We are trying to send a message to the Tibco EMS queue from the UiPath Tool.
Is it possible to this via the paelltes/activities or we need to write some custom Code.
Please let me know if anyone is aware.

A: If UIPath support JMS connectivity you should be able to get this to work by copying TIBCO EMS client Jar files to the UIpath environment (note that you should have an EMS client licence to do that).


text:
Q: I am getting following error when running ng serve I'm new and I have a problem with VSCode. I am getting the following error when running ng serve:

PS C:\Windows\System32\x-app> ng serve --configuration=it
An unhandled exception occurred: Workspace config file cannot le loaded: C:\Windows\System32\x-app\angular.json
Invalid JSON character: "\"" at 73:7.
See "C:\Users\C-PROJ~1\AppData\Local\Temp\ng-LpcKJr\angular-errors.log" for further details

[error] Error: Workspace config file cannot le loaded: C:\Windows\System32\x-app\angular.json
Invalid JSON character: "\"" at 73:7.
    at Object.getWorkspace (C:\Windows\System32\x-app\node_modules\@angular\cli\utilities\config.js:59:15)
    at ServeCommand.validateScope (C:\Windows\System32\x-app\node_modules\@angular\cli\models\command.js:97:60)
    at ServeCommand.validateAndRun (C:\Windows\System32\x-app\node_modules\@angular\cli\models\command.js:122:24)
    at Object.runCommand (C:\Windows\System32\x-app\node_modules\@angular\cli\models\command-runner.js:185:38)
    at process._tickCallback (internal/process/next_tick.js:68:7)
    at Function.Module.runMain (internal/modules/cjs/loader.js:834:11)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

I use prettier, in fa,ct I noticed that there was an oversight about internalization. I fixed the json file, and returned the command ng serve --configuration=it, but the result is another error.

PS C:\Windows\System32\x-app> ng serve --configuration=it
An unhandled exception occurred: Project does not exist.
See "C:\Users\C-PROJ~1\AppData\Local\Temp\ng-IomfPN\angular-errors.log" for further details.

[error] Error: Project does not exist.
    at WorkspaceNodeModulesArchitectHost.findProjectTarget (C:\Windows\System32\x-app\node_modules\@angular-devkit\architect\node\node-modules-architect-host.js:94:23)
    at WorkspaceNodeModulesArchitectHost.getOptionsForTarget (C:\Windows\System32\x-app\node_modules\@angular-devkit\architect\node\node-modules-architect-host.js:66:33)
    at core_1.experimental.jobs.createJobHandler.target (C:\Windows\System32\x-app\node_modules\@angular-devkit\architect\src\architect.js:171:21)
    at Observable.rxjs_1.Observable.subject [as _subscribe] (C:\Windows\System32\x-app\node_modules\@angular-devkit\core\src\experimental\jobs\create-job-handler.js:91:26)
    at Observable._trySubscribe (C:\Windows\System32\x-app\node_modules\rxjs\internal\Observable.js:44:25)
    at Observable.subscribe (C:\Windows\System32\x-app\node_modules\rxjs\internal\Observable.js:30:22)
    at C:\Windows\System32\x-app\node_modules\rxjs\internal\util\subscribeTo.js:22:31
    at Object.subscribeToResult (C:\Windows\System32\x-app\node_modules\rxjs\internal\util\subscribeToResult.js:10:45)
    at SwitchMapSubscriber._innerSub (C:\Windows\System32\x-app\node_modules\rxjs\internal\operators\switchMap.js:65:54)
    at SwitchMapSubscriber._next (C:\Windows\System32\x-app\node_modules\rxjs\internal\operators\switchMap.js:55:14)
    at SwitchMapSubscriber.Subscriber.next (C:\Windows\System32\x-app\node_modules\rxjs\internal\Subscriber.js:66:18)
    at SwitchMapSubscriber.notifyNext (C:\Windows\System32\x-app\node_modules\rxjs\internal\operators\switchMap.js:86:26)
    at InnerSubscriber._next (C:\Windows\System32\x-app\node_modules\rxjs\internal\InnerSubscriber.js:28:21)
    at InnerSubscriber.Subscriber.next (C:\Windows\System32\x-app\node_modules\rxjs\internal\Subscriber.js:66:18)
    at MapSubscriber._next (C:\Windows\System32\x-app\node_modules\rxjs\internal\operators\map.js:55:26)
    at MapSubscriber.Subscriber.next (C:\Windows\System32\x-app\node_modules\rxjs\internal\Subscriber.js:66:18)

A: your angular.json is probably malformed. please check if the file complies to the json standard. you may use tools like prettier to format the json.


text:
Q: Should I use multiple Lucene directories/indexes to search different types of data? I have many MySQL tables to store different types of data like goods, catagories, brands, suppliers, etc. Each of them needs to implement full-text search via Lucene.
So I plan to build one Lucene Directory (and one IndexWriter + one IndexReader corresponding to this Directory) for each table, e.g.
HashMap<String, Directory> = ...;
put("goods", FSDirectory.open(luceneDirRoot + "/goods"));
put("catagories", FSDirectory.open(luceneDirRoot + "/catagories"));
...

Is this a good practice to use Lucene?
Furthur more, how can I know how many directories I made by Lucene, like MySQL command "SHOW TABLES"? new File(luceneDirRoot).listFiles() can be a choice but I am not sure whether there are other non-Lucene folders.

A: I would implement one Lucene index pro MySQL table provided you do not need to perform search over several tables. Alternative would be to write everything into one index and add table name into each lucene document, that way you could limit the search to particular table.
AFAIK Lucene does not support SHOW TABLES equivalent the way you desire it, but you might easily do that by yourself, e.g. by using naming convention for the directories.
I would recommend to look at Hibernate Search, this is a good match for your needs, it builds one index directory pro table and allows you to perform full text search while handling the low-level lucene issues for you. You just configure the index by annotating the JPA entities corresponding to your tables and have to implement the full text queries. This is much easier then doing naked Lucene with data from MySQL on your own, Hibernate Search builds the index for you and integrates well with data from relational DB such as MySQL.


text:
Q: How to access the items array in a JSON file I want to access the JSON data for my YouTube channel and here is what I got
    {
  "version": "https://jsonfeed.org/version/1",
  "title": "Tooabstractive",
  "home_page_url": "https://www.youtube.com/channel/UCm814Any5c0GvOrRCUE3z8g",
  "author": {
    "name": "Tooabstractive"
  },
  "items": [{
      "guid": "yt:video:im1kHs3dBlQ",
      "url": "https://www.youtube.com/watch?v=im1kHs3dBlQ",
      "title": "TCP/IP Explained The Easy Way | Tooabstractive",
      "date_published": "2022-02-28T22:19:59.000Z",
      "author": {
        "name": "Tooabstractive"
      }
    },
    {
      "guid": "yt:video:q2U7Rg9KNG8",
      "url": "https://www.youtube.com/watch?v=q2U7Rg9KNG8",
      "title": "How Do You Know If A MAC Address is Unicast, Multicast or Broadcast | Tooabstractive",
      "date_published": "2022-02-28T05:37:30.000Z",
      "author": {
        "name": "Tooabstractive"
      }
    }
  ]
}

But the problem is that I am unable to because the data I want to loop is inside the items:[....].
One way i know to do this is to remove it from the file but i want to access it remotely using Hugo, so it is difficult for me to access it.


text:
Q: iOS Map Kit Locations read from database I have been tasked with creating an iPhone application for a client.
I have some coding experience but only in C# so it doesn't really help here but other than that I am a complete novice on iPhone coding.
What I am trying to accomplish is to get some form of store locator on a map.
I have successfully added the map, get the user location with it zooming into the user. I have added 2 annotations (Which I believe the the best way to go about showing locations on the map).
I have 2 queries that I need help with, What is the best way to go about listing the stores in some form of database. XML, PList, .sql etc... (this would also need to be read from the web as it would need to be easily edited as new stores would be added a lot). Is it possible to loop through the database and dynamically add the stores onto the map within a location of the user?
I am not asking anyone to write any code for me, I am just asking for some help as I have googled the hell out of this and cant seem to find anything that helps.
Any help would be much appreciated,
Thanks

A: In terms of your potential formats for saving these locations, you options include:

*

*XML/JSON are good formats for exchanging data with a remote server, but less ideal for a local database (though they theoretically could be used for that purpose). JSON is marginally easier to deal with (using NSJSONSerialization), but XML can be relatively easily parsed, too (using, for example, NSXMLParser). If you're doing network operations, I also heartily recommend looking at AFNetworking, which offers some nice advantages over the standard NSURLConnection. This, of course, presumes that you have written a web service on your server to deliver the necessary JSON or XML feed.

*Plist is a fine, simple format if you want to save a short, local list of locations on iOS devices. Saving data to a plist is as simple as calling writeToFile method for your NSDictionary or NSArray and reading data is done via [NSDictionary dictionaryWithContentsOfFile:filename] or [NSArray arrayWithContentsOfFile:filename].

*Core Data is a good, iOS-specific format for larger databases. It's probably the preferred iOS mechanism for dealing with persistent objects, but is an order of magnitude more complicated than plists.

*SQLite is also a good database format if you're thinking about a structure that lends itself towards larger database, but also which lends itself towards eventual rollout to multiple platforms (e.g. both Android and iOS). If you decide to go SQLite route, consider an Objective-C wrapper (such as FMDB), which will simplify your life greatly.
Implicit in all of the above discussion is that, yes, you certainly can write code that iterates through your database and/or model data structures, extracting the necessary location information, and dynamically add annotations to your map. The Location Awareness Programming Guide should help introduce you to some of the MapKit related features.

A: "Is it possible to loop through the database and dynamically add the stores onto the map within a location of the user?"
Yes. Just as you have created those first two annotations, you now need to create more annotations in a loop. The only additional info you might need is that once you have added an annotation to the map it will stay there until you remove it. So you don't need to maintain your own list of annotations unless you want to do something else with it. Just fire and forget. So now your question comes down to how to loop through data from your chosen data source in Objective-C and not MapKit specific.

A: I know this is old but if anyone else comes across this like I did, you can use tmysqlkit by tanmay bakshi to read and write directly to a mysql database on a server.
Best,
Sam


text:
Q: Why are the values stored in memory locations changing? I am trying to implement segment tree. In the following way:
#include<bits/stdc++.h>
using namespace std;
int size;
int construct(int *arr,int *s,int curr,int end,int ad)
{
    if(arr[curr]==arr[end])
    {
        s[ad]=arr[curr];
        return s[ad];
    }
    int mid=(curr+end)/2;
    s[ad]=construct(arr,s,curr,mid,ad*2+1)+construct(arr,s,mid+1,end,ad*2+2);
    return s[ad];
}
int* cons(int *arr,int n)
{
    int height=ceil(log2(n));
    size=(int)(2*pow(2,height)-1);
    int s[(int)(2*pow(2,height)-1)]={0};
    construct(arr,s,0,n-1,0);
    //printf("\n In cons function \n\n");
    for (int i = 0; i <size; ++i)
    {
        printf("%d  %p\n",s[i], &s[i] );
    }
    int *po=s;
    printf("\n%p  %d\n",po,size );
    return po;
}
int main()
{
    int arr[6]={1,3,5,7,9,11};
    int *b=cons(arr,6);
    printf("%p  %d\n\n",b,size );
    //printf("\n\n In main function \n\n");
    for (int i = 0; i <size; ++i)
    {
        printf("%d  %p\n",b[i],&b[i]);
    }
return 0;
}

When I am printing array values in function cons, it displays expected values. Then I return the address of the starting of the array which I store in the main function. Now when I print the same values in main function, some of the values are different, even though the address where the value is stored remain same.
Here's a sample output:
36  0x7ffce0eb6130
9  0x7ffce0eb6134
27  0x7ffce0eb6138
4  0x7ffce0eb613c
5  0x7ffce0eb6140
16  0x7ffce0eb6144
11  0x7ffce0eb6148
1  0x7ffce0eb614c
3  0x7ffce0eb6150
0  0x7ffce0eb6154
0  0x7ffce0eb6158
7  0x7ffce0eb615c
9  0x7ffce0eb6160
0  0x7ffce0eb6164
0  0x7ffce0eb6168

0x7ffce0eb6130  15
0x7ffce0eb6130  15

36  0x7ffce0eb6130
9  0x7ffce0eb6134
9  0x7ffce0eb6138
0  0x7ffce0eb613c
-521445060  0x7ffce0eb6140
32764  0x7ffce0eb6144
20  0x7ffce0eb6148
0  0x7ffce0eb614c
0  0x7ffce0eb6150
0  0x7ffce0eb6154
18  0x7ffce0eb6158
0  0x7ffce0eb615c
9  0x7ffce0eb6160
0  0x7ffce0eb6164
0  0x7ffce0eb6168

A: Look at your code:
int* cons(int *arr,int n)
{
    ....
    int s[(int)(2*pow(2,height)-1)]={0};
    ...
    int *po=s;
    printf("\n%p  %d\n",po,size );
    return po;
}

Which is called by
int *b=cons(arr,6);

Here, po is a pointer to the first element of s. This po, which points to a local variable, is then returned to the caller of cons. Eventually b points to released stack space.
Later you have
printf("%d %p\n",b[i],&b[i]);

which refers to released stack. This is undefined behavior. In practice, the implementation of printf reuses the released stack, overwriting parts of b (maybe all of it). That's why reading a released stack is undefined behavior.
There are several possible solutions. Use and return std::vector, instead of a pointer. Usually, this is the preferred solution.
In C you may pass a pointer to the output array to cons. Also, in C, you might use malloc() inside cons, and use it instead of the s array in cons. You would return that pointer, and the caller would be responsible to call free(). But all this only if you want to stick to C idioms, instead of C++.


text:
Q: Expanding tensors This is a follow-up on / clarification of this thread.
I have the following in a notebook:

$Assumptions = A ∈ Matrices[{3,3},Reals] && B ∈ Matrices[{3,3},Reals]
TensorExpand[(A+B).(A+B)]

(* MatrixPower[A + B, 2] *)

Apparently, TensorExpand does not expand the dot product if the two arguments of the dot product are equal. Is there any way I can expand these kinds of dot products of tensors in Mathematica, i.e. to get A.A + A.B + B.A + B.B in the above example?

A: For this specific case, Distribute will work.
Distribute[(A + B).(A + B)]
(* A.A + A.B + B.A + B.B *)

TensorExpand[%]
(* A.B + B.A + MatrixPower[A, 2] + MatrixPower[B, 2] *)

Keep in mind that Distribute is a purely structural operation without any mathematical smarts.


text:
Q: EF Many-to-Many When Class Already Referenced as FK Not Working I am trying to create an Entity Framework many-to-many relationship between People and Penguins in the form of the usual PenguinPeople table holding Person_Id and Penguin_Id. When I generate a migration with the code below, the many-to-many is not created. However, if I comment out the 3 "OwnerId" lines in the Penguin class, the many-to-many works. What gives? They should be independent.
public class Penguin
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }

    public long OwnerId{ get; set; } //works if I comment this out
    [ForeignKey("OwnerId")] //works if I comment this out
    public Person Person{ get; set; } //works if I comment this out

    public virtual ICollection<Person> PenguinTrainers{ get; set; }
}

public class Person
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }

    public virtual ICollection<Person> People{ get; set; }
}

A: If you have an
ICollection<Penguin> AssignedPenguins { get; set; }

on your Person class and just the Id properties on both classes then it should create the associative table.

A: I don't know if there is an easier way to do this, but I was forced to use FluentAPI as outlined in the EF docs. Example is just from docs, since obviously my penguin/person models were just made-up replacements for the ones actually causing the problem:
modelBuilder.Entity<Post>()
                .HasMany(p => p.Tags)
                .WithMany(t => t.Posts)
                .Map(mc =>
                   {
                       mc.ToTable("PostTags");
                       mc.MapLeftKey("Post_Id");
                       mc.MapRightKey("Tag_Id");
                   });


text:
Q: Using tape with create react app without ejecting Is it possible to use tape to test redux-saga within create-react-app without ejecting?
It seems like it might be possible but I can't quite get things to work. My tape test is reported as:
 RUNS  src/tests/sagas/parserSaga.test.js
TAP version 13
 FAIL  src\tests\sagas\parserSaga.test.js
  ● Test suite failed to run

    Your test suite must contain at least one test.

      at node_modules/jest-cli/build/test_scheduler.js:95:22
          at Generator.next (<anonymous>)
          at new Promise (<anonymous>)
          at <anonymous>

The bit that makes me hopeful is that jest-cli seemed to pickup TAP version 13 so I presume it knows what tape tests are?


text:
Q: Laravel 5.8 - Error en configuración inicial Estoy desarrolando un sistema en laravel desde cero y he realizado la instalación en base a los manuales y este momento mediante artisan he realizado:
php artisan make:aut
se ha creado todo, pero al dar click ya se en la opción de Login o Register se muestra lo siguiente:


text:
Q: Removing selection image on user location annotation I have the following code:
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)annotation{
    annotation.image = [UIImage imageNamed:@"pinIconOn.png"];
}

- (void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)annotation{
    annotation.image = [UIImage imageNamed:@"pinIconOff.png"];
}

However, when I select the user location, the pin icon appears. How can I set the select annotation as void for the user location, but enabled for all the other annotations?

A: In the delegate methods, you can check if the selected annotation is of type MKUserLocation and, if it is, do not change the image.
MKUserLocation is the documented class of the user location annotation.
In these delegate methods, the second parameter is the MKAnnotationView.
That class has the property annotation which points to the underlying annotation model object that the view is for.  Check the type of the annotation property.
For example:
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)annotation{

    if ([annotation.annotation isKindOfClass:[MKUserLocation class]])
    {
        //it's the user location, do nothing
        return;
    }

    annotation.image = [UIImage imageNamed:@"pinIconOn.png"];
}

- (void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)annotation{

    if ([annotation.annotation isKindOfClass:[MKUserLocation class]])
    {
        //it's the user location, do nothing
        return;
    }

    annotation.image = [UIImage imageNamed:@"pinIconOff.png"];
}

Two additional suggestions:

*

*Don't name the parameter annotation in these delegate methods.  Use the same name as suggested in the documentation which is view because that is what the parameter really is.  It is the view object for the annotation -- not the annotation model object itself.  This will make the code in the delegate method less confusing.
So change (MKAnnotationView *)annotation to (MKAnnotationView *)view and the check becomes if ([view.annotation isKindOfClass:[MKUserLocation class]]).

*Ideally, you should be storing the "selected" state in the annotation model object when these delegate methods are called as well as changing the image on the view.  Then, in viewForAnnotation, the code should check the annotation's state and set the image there using the same logic as the delegate methods (different image based on whether it's "selected" or not)  Otherwise, what may happen is that after selecting an annotation, if the user zooms/pans the map, the image may revert back to the value specified in viewForAnnotation.

A: If I understand correctly your question, you need to use an annotationArray of type (NSMutableArray) that will hold all your pins every time you drop a pin. Ex:
something like this :
MKPointAnnotation *annotationPoint = [[MKPointAnnotation alloc]init];
annotationPoint.coordinate = annotationCoord;
annotationPoint.title = yourPinName;//add more things...

[annotationArray addObject:annotationPoint];
[self addAnnotation:annotationPoint];//self is your mapView

is this helping at all?


text:
Q: MSWord does not open embedded in OLE SWT frame after upgrading to Office 365 I am trying to open MSWord in my swt.eclipse.ole application in embedded view of SWT frame. After upgrading to Office 365 version Microsoft® Word for Microsoft 365 MSO (Version 2208 Build 16.0.15601.20446) 64-bit the Word file opens outside the OLE application and not in the embedded view. I am using org.eclipse.swt.win32.win32.x86_64_3.109.0.v20181204-1801.jar in this application. Other swt jar version that I have tried is org.eclipse.swt_3.122.0.v20221123-2302.jar but MSWord does not open in embedded view.
Below image shows embedded MSWord view after Open file... operation.

Below is the code:
/*******************************************************************************
 * Copyright (c) 2007, 2018 IBM Corporation and others.
 *
 * This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License 2.0
 * which accompanies this distribution, and is available at
 * https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.swt.examples.ole.win32;

import java.io.*;

import org.eclipse.swt.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.ole.win32.*;
import org.eclipse.swt.widgets.*;

/**
 * OLEExample is an example that uses org.eclipse.swt
 * libraries to implement a simple SWT window that can host different Active X
 * controls.
 *
 * @since 3.3
 */
public class OLEExample1 {

    OleClientSite clientSite;
    OleFrame oleFrame;
    Button closeButton;
    boolean createClientSite = false; // to create OleClientSite, set to true.
    private Button clientControlSiteToggle;

    public static void main(String[] args) {
        Display display = new Display();
        OLEExample example = new OLEExample();
        example.open(display);
        display.dispose();
    }

    /**
     * Create a file Exit menu item
     */
    void addFileMenu(OleFrame frame) {
        final Shell shell = frame.getShell();
        Menu menuBar = shell.getMenuBar();
        if (menuBar == null) {
            menuBar = new Menu(shell, SWT.BAR);
            shell.setMenuBar(menuBar);
        }
        MenuItem fileMenu = new MenuItem(menuBar, SWT.CASCADE);
        fileMenu.setText("&File");
        Menu menuFile = new Menu(fileMenu);
        fileMenu.setMenu(menuFile);
        frame.setFileMenus(new MenuItem[] { fileMenu });

        MenuItem menuFileExit = new MenuItem(menuFile, SWT.CASCADE);
        menuFileExit.setText("Exit");
        menuFileExit.addSelectionListener(SelectionListener.widgetSelectedAdapter(e -> shell.dispose()));
    }

    OleClientSite createSite(OleFrame frame, String progID) {

        if (createClientSite) {
            return new OleClientSite(frame, SWT.NONE, progID);
        } else {
            return new OleControlSite(frame, SWT.NONE, progID);
        }
    }

    OleClientSite createSite(OleFrame frame, String progID, File file) {

        if (createClientSite) {
            return new OleClientSite(frame, SWT.NONE, progID, file);
        } else {
            return new OleControlSite(frame, SWT.NONE, progID, file);
        }
    }

    void disposeClient() {
        if (clientSite != null)
            clientSite.dispose();
        clientSite = null;
    }

    /**
     * Prompt the user for a file and try to open it with some known ActiveX controls.
     */
    void fileOpen() {

        Shell shell = oleFrame.getShell();
        FileDialog dialog = new FileDialog(shell, SWT.OPEN);
        String fileName = dialog.open();
        if (fileName == null) return;

        oleFrame.setCursor(shell.getDisplay().getSystemCursor(SWT.CURSOR_WAIT));
        shell.getDisplay().readAndDispatch();

        disposeClient();

        // try opening a .doc file using Word
        if (clientSite == null) {
            int index = fileName.lastIndexOf('.');
            if (index != -1) {
                String fileExtension = fileName.substring(index + 1);
                if (fileExtension.toLowerCase().startsWith("doc") ||
                        fileExtension.equalsIgnoreCase("rtf") ||
                        fileExtension.equalsIgnoreCase("txt")) {
                    try {
                        clientSite = createSite(oleFrame, "Word.Document", new File(fileName));
                    } catch (SWTException error2) {
                        disposeClient();
                    }
                }
            }
        }

        if (clientSite != null){
            clientSite.doVerb(OLE.OLEIVERB_INPLACEACTIVATE);
        }

        oleFrame.setCursor(null);
    }

    void newClientSite(String progID) {
        disposeClient();
        try {
            clientSite = createSite(oleFrame, progID);
        } catch (SWTException error) {

        }
        if (clientSite != null)
            clientSite.doVerb(OLE.OLEIVERB_INPLACEACTIVATE);
    }

    public void open(Display display) {
        Shell shell = new Shell(display);
        shell.setText("OLE Example");
        shell.setLayout(new FillLayout());

        Composite parent = new Composite(shell, SWT.NONE);
        parent.setLayout(new GridLayout(4, true));

        Composite buttons = new Composite(parent, SWT.NONE);
        buttons.setLayout(new GridLayout());
        GridData gridData = new GridData(SWT.BEGINNING, SWT.FILL, false, false);
        buttons.setLayoutData(gridData);

        Composite displayArea = new Composite(parent, SWT.BORDER);
        displayArea.setLayout(new FillLayout());
        displayArea.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1));

        new Label(buttons, SWT.NONE);
        Button openButton = new Button(buttons, SWT.RADIO);
        openButton.setText("Open file...");
        openButton.addSelectionListener(SelectionListener.widgetSelectedAdapter(e -> {
            if (((Button) e.widget).getSelection())
                fileOpen();
        }));
        new Label(buttons, SWT.NONE);
        closeButton = new Button(buttons, SWT.RADIO);
        closeButton.setText("Close file");
        closeButton.addSelectionListener(SelectionListener.widgetSelectedAdapter(e ->{
                if (((Button) e.widget).getSelection())
                    disposeClient();
            }
        ));
        closeButton.setSelection(true);

        new Label(buttons, SWT.NONE);
        clientControlSiteToggle = new Button(buttons, SWT.CHECK);
        clientControlSiteToggle.setText("Create Control Site");
        clientControlSiteToggle.addSelectionListener(SelectionListener.widgetSelectedAdapter(e ->{
                createClientSite = !((Button) e.widget).getSelection();
            }
        ));

        closeButton.setSelection(!createClientSite);

        oleFrame = new OleFrame(displayArea, SWT.NONE);
        addFileMenu(oleFrame);

        shell.setSize(800, 600);
        shell.open();

        while (!shell.isDisposed()) {
            if (!display.readAndDispatch())
                display.sleep();
        }
    }
}


text:
Q: Cannot connect to MS Access DB with PHP : SQLSTATE[IM002] I am trying to get data from a MS Access DB (.mdb) but I'm getting:

échec de connexion: SQLSTATE[IM002] SQLDriverConnect: 0
  [Microsoft][Gestionnaire de pilotes ODBC] Source de données
  introuvable et nom de pilote non spécifié.

English:

connection failure: SQLSTATE [IM002] SQLDriverConnect: 0 [Microsoft]
  [ODBC driver manager] data source not found and driver name
  unspecified.

I have : Office 365 Business 32-bit
 installed. Already installed the latest Access Database Engine 32-bit. Uncommented " extension=pdo_odbc " in php.ini.
 Added the "Microsoft Access Driver" to the list of drivers.
$dbName = 'C:\wamp64\www\Test\Workgroup.mdb';
if (!file_exists($dbName))
{
    die("Could not find database file.");
}
else
{
    try{
        //$dbName = 'Workgroup.mdb';
        $cnx = new PDO("odbc:DRIVER={Microsoft Access Driver (*.mdb)}; Dbq=$dbName; Uid=; Pwd=;");
        echo "connected successfully";
        return $cnx;
    }
    catch(Exception $e){
        die ("failed to connect: " . $e->getMessage());
    }
}


text:
Q: Addresses coming up in wrong spot The map in which i am building will be used by an Emergency backup 911 system. I am plotting addresses from a csv file and geocoding with google. To do a test I did 100 addresses in a town I am very familiar with (I grew up there). The addresses in which i plotted are way off from where they should be. For instance an address in the 600 block in this town is plotting on the map in the 1000 block. Again I am geocoding it from Google. Information I have looks like this of course with actual real addresses names ect.
Address      City        Zip          Name
600 Main       Anywhere    99999        Jane Doe
These addresses need to be almost spot on.

A: There are different geocoders which use different methods and input data.
One approach relies on centroids of either parcel or building data.  If the address is 123 Main St, the geocoder identifies the parcel or building with that address and assigns the point location based on the centroid of the polygon   This will be inaccurate, for example, when you have a large tract and the building is not located near the center.  This is the method that Google uses.  In addition, any inaccuracies in the original assessors will show up in the results.
The other method uses street data with block number and related attributes.  So, for 123 Main St, it first identifies the 100-block of main street, then determines if odd is on the left or ride side of the street, and then assigns the point location 23% up that block (assuming address on the block range from 100-199).  This is the method that ESRI geocoder uses.
I believe that the QGIS plugin can work through either method, though I have only used it with the Google geocoder.
Neither method is perfect and any errors in the input data will show up in the results.  For this context, I would suggest that you visually adjust and verify each location using georeferenced imagery.


text:
Q: cake php link to the current page with different prefix In my default layout I would like to show link which points to the current page but with different prefix. I am using prefix 'language' to use address like www.site.com/eng/controller/action/param.
I tried $this->Html->link('eng', array('language' => 'eng') );
But this creates link with url eng/controller/action without passed arguments, without named arguments and without url params.
How I can do this? I would prefer elegant solution like 1 line of code - I know it can be done but can't find it :(.

A: Try this:
// helper method, possibly AppHelper, or in AppController and set a view var
function getCurrentParams() {
    $route = Router::currentRoute();
    $params = $this->request->params;
    $pass = $params['pass'];
    $named = $params['named'];
    unset($params['pass'], $params['named']);
    if (!empty($route->options['pass'])) {
        $pass = array();
    }
    return array_merge($params, $named, $pass);
}

$params = $this->SomeHelper->getCurrentParams();
$params['language'] = 'eng';
// use $params for your link now

A: in my case this easy solution worked too!
<?php
App::uses('HtmlHelper', 'View/Helper');
class MyHtmlHelper extends HtmlHelper {
    public function url($url = null, $full = false) {
        if(!isset($url['language']) && isset($this->params['language']) && is_array($url)) {
          $url['language']= $this->params['language'];
        }
        if(count($url) == 1 && isset($url['language'])){
            $params = $this->params;
            $url = array_merge($params['pass'],$url);
        }
        return parent::url($url, $full);
   }
}

and in AppController
public $helpers = array(
    ...
    'Html' => array('className' => 'MyHtml')
    ...
);

A: $this->Html->link('eng', array('language' => 'eng', 'pass') );

A: Something like this should work:
$url = Router::parse($this->here);
$url['language'='end';
$this->Html->link('eng', $url);

It's not one line, but you could compress it into one line but it would be pretty unreadable.
You could wrap it in a helper / function which would be a one line call though ;-)


text:
Q: Limiting results in a SQL query based on distinctness in an arbitrary column I need to write a SQL query that pulls from a table that stores records for each time one of our salespeople speaks to a client. The relevant columns are: (1) the salesperson's employee ID, (2) the client's account number, and (2) the date of the conversation.
It's often the case that salespeople have spoken to clients multiple times within the report period (a calendar month) so there will be several entries that are nearly identical except for the date.
Where I'm getting tripped up is that, for the purpose of this query, I need to return only one record per salesperson/client combination, but I can't use DISTINCT because I need to include the date of the most recent conversation within the reporting period.
So, if salesperson John has spoken to client ABC on 10/10, 10/18, and 10/25 I need to pull the 10/25 record but not the others.
It's a Sybase database.
I have the feeling that I may be missing something simple here but I've tried searching and remain stumped. Any help is greatly appreciated.
Thanks for your time,
John

A: Guessing at the column names...
  SELECT employee_id, client_acct_no,
         MAX(conversation_date) AS MOST_RECENT_CONV_DATE
    FROM mytable
   WHERE conversation_date BETWEEN DATE '2010-10-01' AND DATE '2010-10-31'
GROUP BY employee_id, client_acct_no

Documentation for GROUP BY clause.


text:
Q: how to include column data that you do not want used in distinct group by set calculation I've been unable to find search hit explaining how to include column data that i do not want used as part of sql distinct group by set calculation
I have a select statement returning just the records I want, i.e. the latest support request by a specific company we collaborate with . . .
SELECT company, max(created_date) FROM support_request WHERE critical_vendor = 1 and status <> 'Cancelled' GROUP BY company ;
. . . and now i just want to include the contact data associated with that distinct group by set calculation without it affecting that set selection but adding it is, as i would intuitively expect to be able to do so, it appears is going to end up affecting the distinct group by set calculation as i get noted syntax error which is asking me to include it in the group by clause
SELECT company, max(created_date), contact_name FROM support_request WHERE critical_vendor = 1 and status <> 'Cancelled' GROUP BY company ;
Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'isrm_request.qc_contact' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

A: You use the partition over clause
SELECT  company,
 max(created_date) OVER (partition by company)  as max_created_date, contact_name
     FROM support_request
    WHERE critical_vendor = 1 and status <> 'Cancelled'
     GROUP BY company


text:
Q: Django choices vs store in data base What is better to do in case you want to set fixed choices in a model, but they are too numerous?
I will put an example with countries, is not exactly my case, but is with geographic locations:
This:
COUNTRY_CHOICES = (
    ('A', 'ARGENTINA'),
    # 200 more countries
)
# model field
my_field = models.CharField(
    choices = COUNTRY_CHOICES
)

Vs store every value in database.
Thanks.

A: For DB storage-wise, I would suggest that you have separate class for the countries and have a FK in your actual model.


text:
Q: Brightness doesn't change on Dell XPS15 7590 with Ubuntu 19.10 If I try to change the brightness of my Dell XPs15 7590 with Fn+F11 or Fn+F12 nothing happens. The bar which is indicating the brightness changes up and down, but the screen stays on a constant brightness. I have tried the following:

*

*changing the grub settings as mentioned here: Unable to change the brightness on my Dell XPS 15 (L502X)

*adding an additional X config file like mentioned in Brightness doesn't change on Dell XPS15 9550 with 16.04.

The output of acpi_listen was:
someone@dell-XPS15:~$ acpi_listen
 9DBB5994-A997- 000000d0 00000000
video/brightnessup BRTUP 00000086 00000000 K
 9DBB5994-A997- 000000d0 00000000
video/brightnessup BRTUP 00000086 00000000 K
 9DBB5994-A997- 000000d0 00000000
video/brightnessup BRTUP 00000086 00000000 K
 9DBB5994-A997- 000000d0 00000000
video/brightnessdown BRTDN 00000087 00000000 K
 9DBB5994-A997- 000000d0 00000000
video/brightnessdown BRTDN 00000087 00000000 K
 9DBB5994-A997- 000000d0 00000000
video/brightnessdown BRTDN 00000087 00000000 K

The output of lspci was:
00:00.0 Host bridge: Intel Corporation Device 3e20 (rev 0d)
00:01.0 PCI bridge: Intel Corporation Xeon E3-1200 v5/E3-1500 v5/6th Gen Core Processor PCIe Controller (x16) (rev 0d)
00:02.0 VGA compatible controller: Intel Corporation UHD Graphics 630 (Mobile) (rev 02)
00:04.0 Signal processing controller: Intel Corporation Xeon E3-1200 v5/E3-1500 v5/6th Gen Core Processor Thermal Subsystem (rev 0d)

And through this I created the following X config file:
someone@dell-XPS15:~$ cat /usr/share/X11/xorg.conf.d/20-intel.conf
Section "Device"
        Identifier  "card0"
        Driver      "intel"
        Option      "Backlight"  "intel_backlight"
        BusID       "PCI:0:2:0"
EndSection

And after a reboot nothing changed.

A:
OK, should also work, but the preferred location is under /etc/.
  /usr/share/X11 is reserved for the distribution, and files there may
  eventually be overwritten by system updates.

After putting the file there, I was able to configure the brightness of the screen.