text:
Q: Uncaught Error: Cannot use object of type stdClass while showing the list using WP_List_Table I am working on plugin development and I am getting issues with the table list. I have tried the below code but I am getting an issue called

Fatal error: Uncaught Error: Cannot use object of type stdClass as
array

<?php

if (!class_exists('WP_List_Table')) {
    require_once(ABSPATH . 'wp-admin/includes/class-wp-list-table.php');
}

require_once(ABSPATH . '/wp-load.php'); // static path

class bl_view_list extends WP_List_Table
{

    /** Text displayed when no customer data is available */
    public function no_items()
    {
        _e('No list avaliable.', 'sp');
    }

    public function get_columns()
    {
        $columns = array(
            'id'          => 'ID',
            'bl_name'       => 'Table name',
            'bl_description' => 'Description',
            'bl_create_date'    => 'Create Date',
        );
        return $columns;
    }

    function prepare_items()
    {
        $columns = $this->get_columns();
        $hidden = array();
        $sortable = array();
        $this->_column_headers = array($columns, $hidden, $sortable);
        $this->items = $this->get_table_data();
        // echo "<pre />";
        // print_r($this->items); // here i am getting correct array output
    }

    // Get table data
    private function get_table_data()
    {
        global $wpdb;
        $table = $wpdb->prefix . 'listdata';
        $get_bl_list = $wpdb->get_results("SELECT * from {$table} where bl_is_active=1",);
        return $get_bl_list;
    }

    /**
     * Define what data to show on each column of the table
     *
     * @param  Array $item        Data
     * @param  String $column_name - Current column name
     *
     * @return Mixed
     */
    public function column_default($item, $column_name)
    {
        switch ($column_name) {
            case 'id':
            case 'bl_name':
            case 'bl_description':
            case 'bl_create_date':
                return $item[$column_name];
            default:
                return print_r($item, true);
        }
    }
}

I am getting the below array output in the prepare_items() function
 $this->items = $this->get_table_data();

Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [bl_name] => 404-pages.xlsx
            [bl_description] => 404-pages.xlsx
            [bl_create_date] => 2022-11-28 10:16:57
        )
//and so on
)

but not sure what I am doing wrong.
How can I resolve this issue?

A:     $this->items = $this->get_table_data();

If this line is triggering the error, then the reason is probably that items should be an array of arrays, not an array of stdClass objects. But you don't need to change much, as get_results() does support returning arrays instead of objects (which is the default).
Instead of
$get_bl_list = $wpdb->get_results("SELECT * from {$table} where bl_is_active=1",);

do
$get_bl_list = $wpdb->get_results("SELECT * from {$table} where bl_is_active=1", ARRAY_A);


text:
Q: ScreenToWorldPoint does something strange in Unity I am trying to convert from screen coordinates to world coordinates in Unity, but failing.
I regarded third coordinate as a distance from camera according to documentation and tried
 GetComponent<Camera>().ScreenToWorldPoint(new Vector3(0, 0, 0))
 GetComponent<Camera>().ScreenToWorldPoint(new Vector3(100, 0, 0))
 GetComponent<Camera>().ScreenToWorldPoint(new Vector3(0, 100, 0))
 GetComponent<Camera>().ScreenToWorldPoint(new Vector3(10000000, 0, 0))
 GetComponent<Camera>().ScreenToWorldPoint(new Vector3(0, 10000000, 0))

But result was always
 (0.0, 0.0, 2.0)

where (0.0, 0.0, 2.0) is the coordinates of the camera object.

I found, that if third coordinate is zero, then first two coordinates has no effect. And if third coordinate is 1 then effect exists, but is different, than when third coordinate is 2.
Is this by design?

A: The problem is in defining the variables.
Change this:
float mouseX = -Input.GetAxis("Mouse X");
float mouseY = -Input.GetAxis("Mouse Y");

for this:
float mouseX = Input.mousePosition.x;
float mouseY = Input.mousePosition.y;

You're trying to get the mouse axis, but actually you need to get the mouse positions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Missing package libemu-dev in Ubuntu 20.04 libemu-dev package exists for Ubuntu 18.04 but it seems to be missing for Ubuntu 20.04. Has libemu-dev been discontinued in 20.04  or will it be added in the future? Is there a way I can install libemu-dev in 20.04?
https://www.ubuntuupdates.org/package/core/bionic/universe/base/libemu-dev

A: Open the terminal and type:
sudo apt update
cd ~/Downloads
wget http://archive.ubuntu.com/ubuntu/pool/universe/libe/libemu/libemu2_0.2.0+git20120122-1.2build1_amd64.deb http://archive.ubuntu.com/ubuntu/pool/universe/libe/libemu/libemu-dev_0.2.0+git20120122-1.2build1_amd64.deb
sudo apt install ./libemu2_0.2.0+git20120122-1.2build1_amd64.deb ./libemu-dev_0.2.0+git20120122-1.2build1_amd64.deb


text:
Q: How does Java force classes to extend Object? How does this happen internally? What mechanism is used? JNI, reflection or something different? Does the compiler include the extends clause, perhaps?

A: Not completely correct.
All classes extend Object if they don't already extend another class, with one exception: java.lang.Object itself doesn't extend any class.
The compiler embeds the superclass java.lang.Object in the class file if the code doesn't specify another superclass.
You can even see it yourself if you open the .class file with your favorite editor, you can see the string java/lang/Object embedded in binary data.
(You can compile a very simple source file like public class A { } to observe this best)

A: This is an interesting question about the internals of the java compiler. I found a list of docs providing a high level view of javac [1][2][3][4]. Source code for a specific implementation like OpenJdk can be found online too [source].
Compilation consists of 3 high level steps [5]:

*

*"parse and enter"

*"annotation processing"

*"analyse and generate"

I wrote some code to test these steps out using the Compiler Tree API which provides an interface to javac.
static class TestFileObject extends SimpleJavaFileObject {
    public TestFileObject() {
        super(URI.create("Test.java"), JavaFileObject.Kind.SOURCE);
    }
    public CharSequence getCharContent(boolean ignoreEncodingErrors) {
        return "class Test { private int x; }";
    }
}

public static void main(String[] args) throws IOException {
    JavacTool tool = JavacTool.create();
    JavacTask task = tool.getTask(null, null, null, null, null,
            com.sun.tools.javac.util.List.of(new TestFileObject()));

    // Step 1, Parse
    Iterator<? extends CompilationUnitTree> trees = task.parse().iterator();

    // Step 3, Analyze
    // Iterator<? extends Element> elements = task.analyze().iterator();

    // Step 3, Generate
    // Iterator<? extends JavaFileObject> files = task.generate().iterator();

    while(trees.hasNext()) {
        CompilationUnitTree cu = trees.next();
        System.out.println(cu.getTypeDecls());
    }
}

Running the above code with Step 1 shows the following output:
class Test {
    private int x;
}

So the AST doesn't contain references to java.lang.Object. Next, I uncommented "Step 3, Analyse" and re-ran my code with the resulting output:
class Test {

    Test() {
        super();
    }
    private int x;
}

Notice that the Test() constructor and super() was added in this step,
which also corresponds to the explanation for Step 3 [5] :

While analysing the tree, references may be found to classes which are required for successful compilation, but which were not explicitly specified for compilation.

Finally, I uncommented Step 3, Generate, which creates the Test.class file. Calling javap -c Test.class, the resulting bytecode is blelow :
class Test {
  Test();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return
}

So my conclusion is that the bytecode generation step adds the java.lang.Object related logic.


text:
Q: VIM function to insert timestamp Someone in a previous question suggested the following for adding timestamps to VIM:
nmap <F3> a<C-R>=strftime("%Y-%m-%d %a %I:%M %p")<CR><Esc>
imap <F3> <C-R>=strftime("%Y-%m-%d %a %I:%M %p")<CR>

Instead of using F3, I'd like to insert the timestamp by executing a function instead. For example, typing :Now.
Unfortunately, I don't grok VIM scripting. Can someone help?

A: :Now is not a function, it is a command. You can create command out of first mapping with the following code:
command -nargs=0 -bar Now execute "normal! a\<C-R>=strftime(\"%Y-%m-%d %a %I:%M %p\")\<CR>"

A: " if not has 'Last Change' in first 5 lines
fun! InsertChangeLog()
    let l:flag=0
    for i in range(1,5)
        if getline(i) !~ '.*Last Change.*'
            let l:flag = l:flag + 1
        endif
    endfor
    if l:flag >= 5
        normal(1G)
        call append(0, "File: <+Description+>")
        call append(1, "Created: " . strftime("%a %d/%b/%Y hs %H:%M"))
        call append(2, "Last Change: " . strftime("%a %d/%b/%Y hs %H:%M"))
        call append(3, "author: <+digite seu nome+>")
        call append(4, "site: <+your website+>")
        call append(5, "twitter: <+your twitter here+>")
        normal gg
    endif
endfun
" map F4 to insert change log
map <special> <F4> <esc>:call InsertChangeLog()<cr>

" update changefile log
" http://tech.groups.yahoo.com/group/vim/message/51005
" automaticaly update Last Change whitout change jump list
" see :h keepjumps
fun! LastChange()
    let _s=@/
    let l = line(".")
    let c = col(".")
    if line("$") >= 5
        1,5s/\s*Last Change:\s*\zs.*/\="" . strftime("%Y %b %d %X")/ge
    endif
    let @/=_s
    call cursor(l, c)
endfun
autocmd BufWritePre * keepjumps call LastChange()

" place holders snippets - change map !!!
" File Templates
" --------------
"  <leader>j jumps to the next marker
" iabbr <buffer> for for <+i+> in <+intervalo+>:<cr><tab><+i+>
function! LoadFileTemplate()
    "silent! 0r ~/.vim/templates/%:e.tmpl
    syn match vimTemplateMarker "<+.\++>" containedin=ALL
    hi vimTemplateMarker guifg=#67a42c guibg=#112300 gui=bold
endfunction
function! JumpToNextPlaceholder()
    let old_query = getreg('/')
    echo search("<+.\\++>")
    exec "norm! c/+>/e\<CR>"
    call setreg('/', old_query)
endfunction
autocmd BufNewFile * :call LoadFileTemplate()
nnoremap <leader>j :call JumpToNextPlaceholder()<CR>a
inoremap <leader>j <ESC>:call JumpToNextPlaceholder()<CR>a


text:
Q: Can't mount USB drive On Fedora 37 I was working on creating Linux From Scratch and suddenly I can no longer mount my USB drive. When I sudo mount /dev/sdf2 /mnt I get an error kernel: JBD2: Invalid checksum recovering data. Here's full log from journalctl -f
Then the mount command freezes and I have to kill it.
Did I manage to break my partitions? Is there a way to fix it?
Dec 03 12:20:05 fedora sudo[4196]:   jedrek : TTY=pts/1 ; PWD=/home/jedrek ; USER=root ; COMMAND=/usr/bin/journalctl -f
Dec 03 12:20:05 fedora sudo[4196]: pam_unix(sudo:session): session opened for user root(uid=0) by (uid=1000)
Dec 03 12:20:05 fedora audit[4196]: USER_START pid=4196 uid=1000 auid=1000 ses=2 subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 msg='op=PAM:session_open grantors=pam_keyinit,pam_limits,pam_keyinit,pam_limits,pam_systemd,pam_unix acct="root" exe="/usr/bin/sudo" hostname=? addr=? terminal=/dev/pts/1 res=success'
Dec 03 12:20:06 fedora kernel: JBD2: recovery failed
Dec 03 12:20:06 fedora kernel: EXT4-fs (sdf2): error loading journal
Dec 03 12:20:18 fedora audit: BPF prog-id=85 op=LOAD
Dec 03 12:20:18 fedora systemd[1]: Starting fprintd.service - Fingerprint Authentication Daemon...
Dec 03 12:20:18 fedora systemd[1]: Started fprintd.service - Fingerprint Authentication Daemon.
Dec 03 12:20:18 fedora audit[1]: SERVICE_START pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=fprintd comm="systemd" exe="/usr/lib/systemd/systemd" hostname=? addr=? terminal=? res=success'
Dec 03 12:20:22 fedora audit[4201]: USER_AUTH pid=4201 uid=1000 auid=1000 ses=2 subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 msg='op=PAM:authentication grantors=pam_usertype,pam_localuser,pam_unix acct="jedrek" exe="/usr/bin/sudo" hostname=? addr=? terminal=/dev/pts/0 res=success'
Dec 03 12:20:22 fedora audit[4201]: USER_ACCT pid=4201 uid=1000 auid=1000 ses=2 subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 msg='op=PAM:accounting grantors=pam_unix,pam_localuser acct="jedrek" exe="/usr/bin/sudo" hostname=? addr=? terminal=/dev/pts/0 res=success'
Dec 03 12:20:22 fedora audit[4201]: USER_CMD pid=4201 uid=1000 auid=1000 ses=2 subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 msg='cwd="/home/jedrek" cmd=6D6F756E74202F6465762F73646632202F6D6E74 exe="/usr/bin/sudo" terminal=pts/0 res=success'
Dec 03 12:20:22 fedora sudo[4201]:   jedrek : TTY=pts/0 ; PWD=/home/jedrek ; USER=root ; COMMAND=/usr/bin/mount /dev/sdf2 /mnt
Dec 03 12:20:22 fedora audit[4201]: CRED_REFR pid=4201 uid=1000 auid=1000 ses=2 subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 msg='op=PAM:setcred grantors=pam_localuser,pam_unix acct="root" exe="/usr/bin/sudo" hostname=? addr=? terminal=/dev/pts/0 res=success'
Dec 03 12:20:22 fedora sudo[4201]: pam_unix(sudo:session): session opened for user root(uid=0) by (uid=1000)
Dec 03 12:20:22 fedora audit[4201]: USER_START pid=4201 uid=1000 auid=1000 ses=2 subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 msg='op=PAM:session_open grantors=pam_keyinit,pam_limits,pam_keyinit,pam_limits,pam_systemd,pam_unix acct="root" exe="/usr/bin/sudo" hostname=? addr=? terminal=/dev/pts/0 res=success'
Dec 03 12:20:41 fedora systemd[1]: flatpak-system-helper.service: Deactivated successfully.
Dec 03 12:20:41 fedora audit[1]: SERVICE_STOP pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=flatpak-system-helper comm="systemd" exe="/usr/lib/systemd/systemd" hostname=? addr=? terminal=? res=success'
Dec 03 12:20:43 fedora kernel: JBD2: Invalid checksum recovering data block 8479136 in log
Dec 03 12:20:43 fedora kernel: JBD2: Invalid checksum recovering data block 8389614 in log


text:
Q: How to properly store and lookup areacode from a phone number How do I store areacodes (npa-nxx) in a database for fast lookup?
Here's the deal: I have a variable that contains a phone number and I need to look in a database for the city attached to that phone number.
The problem is, different countries have different formats.
Canada/USA: +19055551234 (+1 > Country, 905 > Area Code, 555 > City Code)
France: +33512345678 (+33 > Country, 5 > Areacode, 1 > City, Other numbers > Subscriber number)

and so on (infos based on wikipedia)
I created a table called 'npanxx' that contain the list of area codes, city code and city attached to each one (with the id of the country and the province/state id):
CountryId, RegionId, PrimaryCity, npa, nxx, fnpanxx
1          11        Acton Vale   450  236  +1450236

I am thinking about the following procedure:
Get all country codes from sql to php array
Go through each entry and check if there's a match from the beginning of the phone number
When (If there's) a match is found
  Remove the beginning of the phone number
  Get all npa-nxx that belong to that contry and put them in a php array
  Go through each value of the array to find a matching beginning
  When (If there's) a match is found
    Remove the beginning of the phone number
    Store data in different variables like: $country = 'Canada'; $city = 'Acton Vale'...
    etc, etc.

First mistake (I think): To much database requests (the npanxx table contain 3000 records for only one province in Canada)
Second mistake: I'm pretty sure there's no need to go through each and every npa-nxx code
another problem: It's not sure that if the phone number is a France one that this procedure will work.
And... If there's an entry for, let's say 336 and another for 3364, it might give the wrong result.
Do you have any idea how I can solve this problem ? (I don't ask for any code, I don't want to to do the work for me, I would like some clues though)
This is for a personnel project to make donation for Multiple Sclerosis Society of Canada and would really like to finish that project :)

A: I would think maybe some kind of set of reg-exes or other pattern matches to whiddle down your options in terms of search. Just some basic way or "guessing" at the possibilities instead of searching all of them.

A: Here's a small script I wrote in PHP to return the NPA/NXX as a JSON object in real time from area-codes.com.
It returns some very useful data.  It's only for the NANP, so it doesn't do so well trying to discern international calls.  For that, I would suggest making a table of all international country codes and the appropriate methods to dial them, internationally.
Additionally, network exchange operators demand an international dial code (like 011 for the USA, or + for cell phones, in general) to figure out if the number is international, and then take the steps, above, to figure out where you're trying to go.  You could add this constraint into the input field and be done with it.
If you're trying to just get NPA/NXX information in the North American Numbering Plan, though, this script should be very helpful.
Just an aside, the area-codes.com counts online lookups among their free services, and I have found nothing on the site to suggest that this code violates that policy. But this code can be retooled to gather data from other providers, none-the-less.
 <?php

    // Small script to return and format all data from the NPA/NXX info site www.area-codes.com
    // Returns a JSON object.

    error_reporting(E_NONE);

    $npa = $_GET['npa'];
    $nxx = $_GET['nxx'];

    function parseInput($input) {

        $v = new DOMDocument();

        $v->formatOutput = true;
        $v->preserveWhiteSpace = false;

        $v->loadHTML($input);

        $list = $v->getElementsByTagName("td");

        $e = false;
        $dataOut = array();
        $p = "";

        foreach($list as $objNode) {
            if (!$e) {
                $p = $objNode->nodeValue;

                $p = strtolower($p);
                $p = preg_replace("%[+ .:()\/_-]%", "", $p);
                $p = str_replace("\xc2\xa0", "", $p);
                $p = trim($p);
            }
            else {
                if ($p != "") {
                    $d = trim($objNode->nodeValue);
                    if ($d != "") $dataOut[$p] = $d;
                }
                $p = "";
            }

            $e = !$e;
        }

        return $dataOut;

    }

    function getNPANXX($npa, $nxx) {

        $url = "www.area-codes.com/exchange/exchange.asp?npa=$npa&nxx=$nxx";
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_VERBOSE, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
        curl_setopt($ch, CURLOPT_URL, $url);

        $response = curl_exec($ch);
        curl_close($ch);

        $i = strpos($response, "
AreaCode/Prefix $npa-$nxx Details
");
        $i = strpos($response, "
", $i);
        $e = strpos($response, "
", $i);

        $scan = substr($response, $i, ($e-$i) + 8);
        return parseInput($scan);

    }

    $result = getNPANXX($npa, $nxx);

    if (!isset($result['npaareacode'])) {
        $result = array("error" => "invalid");
    }

    echo json_encode($result);
    die;

?>

For the query npanxx.php?npa=202&nxx=520 the JSON outputs as follows:
{
"npaareacode":"202",
"nxxusetype":"WIRELESS",
"nxxprefix":"520",
"nxxintroversion":"11\/16\/2007",
"city":"WASHINGTON",
"state":"DC",
"latitude":"38.901",
"county":"DISTRICT OF COLUMBIA",
"longitude":"-77.0315",
"countypopulation":"0",
"lata":"236",
"zipcode":"20005",
"zipcodecount":"0",
"ratecenter":"WSHNGTNZN1",
"zipcodefreq":"0",
"fips":"11001",
"ocn":"6664",
"observesdst":"Unknown",
"cbsacode":"47900",
"timezone":"Eastern (GMT -05:00)",
"cbsaname":"Washington-Arlington-Alexandria, DC-VA-MD-WV",
"carriercompany":"SPRINT SPECTRUM L.P."
}

For your example npanxx.php?npa=450&nxx=236 the data returned is a little bit limited  because it's Canada and Canada doesn't provide all the FIPS and carrier data like the United States does, but the returned data still quite useful:
{
"npaareacode":"450",
"nxxusetype":"WIRELESS",
"nxxprefix":"236",
"nxxintroversion":"2002-08-04",
"city":"ACTON VALE",
"state":"QC",
"latitude":"45.6523",
"longitude":"-72.5671",
"countypopulation":"51400",
"lata":"850",
"zipcodecount":"0",
"zipcodefreq":"-1",
"observesdst":"Unknown",
"timezone":"Eastern (GMT -05:00)"
}


text:
Q: CSS rule cleanup tool We have several massive CSS files that just kept growing over the years whenever new elements were added to our system as well as JSP pages (which further include other JSP pages and so on) that reference these files.
We know that we have many rules that are no longer used and many that are redundant.
New tools just keep coming out. Is there a tool that (besides obvious ones such as Aptana and W3C's CSS validator) that can analyze a directory and aid in cleaning up and optimizing CSS rules?

A: There's Dust-Me-Selectors plugin for Firefox, although it looks through a page rendered in the browser, of course, not through a directory.

A: It is a tricky task... especially if your HTML DOM content is generated on the fly in any way.
The Dust-Me-Selectors plugin is helpful, but on a page-by-page basis, lots of selectors will be unused... but not necs be invalid.
There's a few tricks I've used to help clean up.
One by one, insert some HORRID styling that you'll be able to spot immediately to determine if a selector is being used. e.g.
border:6px dashed #ffaacc;
padding:12px;

Anything that renders with a huge dashed hot pink border now... is an "active" selector. If you can surf most of your site/app without seeing it, then it is likely "dead".
(if your CSS code is "generated" you can optimize this to test with various colors at once, AND use generated content to prepend the "id" of the selector)
Another option if you use a generated CSS system... is to add a final property to your selector that sets say... a background image with a generated URL. e.g.
#selector_a > .foo{
  ...
  background-image:url('selectortest/id_123.png');
}
#selector_b .bar{
  ...
  background-image:url('selectortest/id_124.png');
}

Then you simply surf your site/app for a while then check your web log for HTTP image requests... for any generated image URL that wasn't requested in the log... you've likely found a "dead" selector.

A: Selenium allows you to automate page testing and select elements via css selectors. If you accumulate the matches across the site you would be able to identify unmatched items.


text:
Q: Remove SVN checkout I accidentally put a checkout in the root of my drive, not in a sub directory.
Normally to remove an SVN checkout I just delete the directory in which I created the checkout.
Since this is now my complete drive, I cannot do this.
Is there another way to remove a checkout?
In windows explorer, I now see that my drive is versioned, which is not what I want.

A: In the directory you accidentally checked out to there will be a hidden .svn directory that you can delete.  This will return it to a normal directory which you can clean up.
You will need to show hidden files in order to see the .svn directory.


text:
Q: Add child node to a specific index in an object with php I have an object, and I have a new value which I need to add to this object, but not just to the end of it, that would be no problem accomplishing. What I need to do is add this value to a new node on a specific index.
Ok so here's the object.
[object]=>{
  ["a"]=> "value"
  ["b"]=> "value"
  ["c"]=> "value"
  ["d"]=> "value"
}

Then I have this fifth value that I now need to add to index 1, or as it's named in this example "b". Like this.
[object]=>{
  ["a"]=> "value"
  ["e"]=> "fifth value"
  ["b"]=> "value"
  ["c"]=> "value"
  ["d"]=> "value"
}

So the question remains, is there a smart way to do this or do I have to split them up and make them into arrays and merge them as arrays then assign them to a new object explicitly telling it to be an object?
Like this.
$object = (object)array_merge((array)$first, (array)$second);

I feel that there must be a better way to handle this, with only objects.
Thank you for your time.

A: What are you doing that needs this:
[object]=>{
  ["a"]=> "value"
  ["e"]=> "fifth value"
  ["b"]=> "value"
  ["c"]=> "value"
  ["d"]=> "value"
}

to be different from this:
[object]=>{
  ["a"]=> "value"
  ["b"]=> "value"
  ["c"]=> "value"
  ["d"]=> "value"
  ["e"]=> "fifth value"
}

?
If you NEED them to be different, you are using OOP wrong.
EDIT: What's stopping you from using arrays?

A: Objects simply don't have indexes, they have properties, and $obj->property is always $obj->property - no ordering, no indexes nothing like that.
What you need here is (generally) a numerically indexed array, not an object, and not an associative array - if you insist you need an alpha sorted associative array (alpha keys rather than numerical keys) then you can use ksort to handle this particular problem.
$array = array(
  "a" => "value",
  "e" => "fifth value",
  "b" => "value",
  "c" => "value",
  "d" => "value",
);
ksort($array);
print_r($array);

note you can always turn it in to an object if for some reason you need this by doing $obj = (object)$array; after the sort


text:
Q: Why three.js uses IIFE pattern on some simple member functions? Take Object3D base class as an example:
rotateOnAxis: function () {

    // rotate object on axis in object space
    // axis is assumed to be normalized

    var q1 = new Quaternion();

    return function rotateOnAxis( axis, angle ) {

        q1.setFromAxisAngle( axis, angle );

        this.quaternion.multiply( q1 );

        return this;

    };

}(),

...
and this pattern is commonly seen in other classes, why not just write a normal function like:
function rotateOnAxis(axis, angle) {...}?

A: A closure is used in this case to avoid instantiating a temporary quaternion every call.
This coding pattern is used frequently in three.js -- especially in methods that may be called in tight loops, such as an animation loop.
three.js r.89

A: By referring to How do JavaScript closures work? and printing some variables on chrome console, I think "a closure is a stack frame which is allocated when a function starts its execution, and not freed after the function returns (as if a 'stack frame' were allocated on the heap rather than the stack!)" can perfectly explain this.
when I eval 'app._scene.scene.children[0].rotateOnAxis' on the console, it prints:

ƒ rotateOnAxis( axis, angle ) {
      q1.setFromAxisAngle( axis, angle ); <-- q1 is referenced but no declaration

      this.quaternion.multiply( q1 );

      return this;

  }

and eval 'app._scene.scene.children[0].rotateOnAxis.q1' prints:

undefined.

and eval 'app._scene.scene.children[0].rotateOnAxis.prototype' prints:
{constructor: ƒ}
 + constructor:ƒ rotateOnAxis( axis, angle )
 | ... (ignored here)
 | [[Scopes]]:Scopes[3]
 ---+ 0:Closure {type: "closure", name: "", object: {…}}
    |--+ q1:Quaternion {_x: 0, _y: 0, _z: 0, _w: 1} <-- scope search here
    | 1:Closure {type: "closure", name: "", object: {…}}
    | 2:Global {type: "global", name: "", object: Window}

Seen above there's clearly a 3-layers stacking closure frame attached to this rotateOnAxis function's prototype.constructor property. And another important thing is the var(q1) saved in the closure will change whenever the outer function is invoked, so the content of var(q1) must be reset in its setFromAxisAngle interface.


text:
Q: Bold text in Google play App Description? Maybe it's long time but I just noticed that there is no bold text in description any more, right?
Before I used to put some text in  tags and it was bold. Did Google change formatting or just removed it at all. Is there any chance to have bold text in Google play App description?

A: Yes, Google Play has removed it completely, there is no other way to do this.
But you still can use emojis in the description.

A: Yes, Google Play has removed the formatting option. And I personally don't know any other option for doing this.


text:
Q: Understanding this highly templated C++ function binder template<typename Container, typename Ret, typename ...Args>
    struct BindImpl {
        template<Ret (Container::*MemberFunc)(Args...)>
        class Callable {
        public:
            inline constexpr Callable (Container *container) :
                m_container(container)
            {}

            inline Ret operator() (Args ...args) const
            {
                return (m_container->*MemberFunc)(std::forward<Args>(args)...);
            }

            inline Function<Ret(Args...)> toFunction() const
            {
                return Function<Ret(Args...)>(*this);
            }

        private:
            Container *m_container;
        };
    };
    template<typename Container, typename Ret, typename ...Args>
    BindImpl<Container, Ret, Args...> DeduceImpl (Ret (Container::*)(Args...));

This code is called like this:
(typename decltype(::AIpStack::BindPrivate::DeduceImpl(&EthIpIface::driverSendIp4Packet)) ::template Callable<&EthIpIface::driverSendIp4Packet>((this)).toFunction())

I'm trying to understand what this code does. It apprently is a way to bind function pointers (like &EthIpIface::driverSendIp4Packet) to something.
The line above is from this macro, which fills this struct member, if anyone is intersted. You may wanna have a loot at Function.
The first part that I don't understand is
template<Ret (Container::*MemberFunc)(Args...)>

For me a template must be followed by typename. Also, what follows typename, is the thing to be substituted for. I don't see how this template makes Callable templated. I don't know where something goes to in  Callable<something>.
Also, what is DeduceImpl? Looks like a function declaration but without a definition.
Also, what Container::*MemberFunc means?

A: Firstly, templates can also take in non-type parameters as well as with typename and class. In this case:
template<Ret (Container::*MemberFunc)(Args...)>

This is a template taking a function pointer as a parameter, where Ret is the return type, Container::*MemberFunc is the pointer to a specific member function in Container with Args... referencing variadic arguments. This gives the pointer the identifier MemberFunc. I have a feeling the asterisk following the scope resolution operator confused you, as usually you would receive a compiler error if you used these two together in any other situation but in this specific case these two are considered one token ::* representing this kind of template parameter instead of the two :: and *.

For this line:
BindImpl<Container, Ret, Args...> DeduceImpl (Ret (Container::*)(Args...));

It is a function declaration. This is a function named DeduceImpl that will return a BindImpl struct that takes a function pointer as an argument. I'm inferring that this function is the interface by which you bind the function pointer, hence the (probably) shortened names "Deduce Implementation" and "Bind Implementation" From what I've read, this function is only used for decltype, so there's no actual definition for this function.

For how this template is actually being utilized in this line (reformatted for easier reading):
typename decltype(::AIpStack::BindPrivate::DeduceImpl(&EthIpIface::driverSendIp4Packet))
::
template Callable<&EthIpIface::driverSendIp4Packet>(this).toFunction()

This is a template disambiguator created just so the compiler knows that the actual template is being utilized instead of a less-than comparison operator.
You wouldn't write all of this just to use the template. This line was probably written because it's one of the few ways the template is instantiated in the project.

In summary:

*

*template<Ret (Container::*MemberFunc)(Args...)> is a template that takes a function pointer referred to as MemberFunc as a parameter.

*DeduceImpl returns a BindImpl struct by taking in the function pointer you want to bind.


text:
Q: cx_Freeze: Python error in main script(_tkinter.TclError) I am using python 3.4
Trying to build an exe for win_xp using cx_freeze.
Developed the script and build on win 7. Tested there, working fine.
But when I try to run the exe in win xp, it throws following during execution.
Tried Googling but cound not find any solution. How to find a solution for it.
Any specific reason why is it not running on xp. Please help.

A: If you want to make your program compatible with Win XP, you need to build your program in that system. According to the documentations of any program frozen utilities, the program will only compatible with the system with which the program was frozen. Generally, if you want to backward compatibility, you should just build your program in the lowest version of system that you want it to run on.


text:
Q: How to automatically deploy node repo on github in linux server? I have a linux server as my a production environment, and my node repo is on github .
When I push my code, if I want to deploy it , I need to .
>local
git push
ssh user@host

>remote
cd repo
git pull

I am using node forever to auto update my code , but it is still a very troublesome .
Is there any solution , like travis-ci or heroku , can Automatically deploy my code on github ?

A: Travis-ci is for continuous integration (as its name)
While Heroku is just a cloud platform.
They are not for deployment.
My solution is to set up a git hook on your server, push to it to trigger the hook, and do whatever you want in that script.
for example, you can:

*

*cd ~/repo && mkdir myproj && cd myproj

*git init --bare

*edit ~/repo/myproj/hooks/post-update
#!/bin/sh
unset GIT_DIR;
cd <your project-root>
export NODE_ENV="product"
git pull
npm install
pm2 restart <your app name>

*chmod +x ~/repo/myproj/hooks/post-update
now you can add your repo on server as one of your remotes
There's some services available to monitor your deployment, such as http://dploy.io/ and https://www.codeship.io/
Feel free to use them when your business grows up.


text:
Q: Detect (non-blocking) key press while accepting client connections I am fairly new at programming in python. I am trying to code some form of simulation using sockets. I am able connect multiple clients to the server successfully. However I would like the server to accept client connections while waiting for some input (say enter key or a string input from the console/terminal). If the user presses the enter key or enters that string, then the server should stop accepting client connections and send the list of connected clients to all clients. I know how to code the rest of the part but I dont know where to detect this key press while accepting connections. This is what I have so far. I have tried looking for similar approaches taken, but I have not found something that fits my needs.
Server File:
import socket, sys, traceback, json, pygame, curses, time
from threading import Thread
clientList = {}

def initialize():
    serverConnect()

def serverConnect():
    local_hostname = socket.gethostname()
    host = socket.gethostbyname(local_hostname)
    port = 6666
    sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sockfd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    try:
        sockfd.bind((host, port))
    except:
        print("Bind failed. Error : " + str(sys.exc_info()))
        sys.exit()
    sockfd.listen(3)
    cid = 0
    # infinite loop - do not reset for every requests
    while True:
        print("Awaiting client connection...")
        clientSocket, address = sockfd.accept()
        cid += 1
        add_client_to_list(cid, address)
        ip = str(address[0])
        port = str(address[1])
        print("Connected with " + ip + ":" + port)
        try:
            Thread(target=client_thread, args=(clientSocket, ip, port, cid, address)).start()
        except:
            print("Thread did not start.")
            traceback.print_exc()
    sockfd.close()

def client_thread(clientSocket, ip, port, cid, address, BUFSIZE = 5120):
    clientAddress = address
    clientID = cid
    print("Sending client ID " + str(clientID) + " to " + ip + ":" + port)
    clientSocket.sendall(str(clientID).encode("utf-8"))
    threadActive = True
    while threadActive:
        recdData = receive_input(clientSocket, BUFSIZE)
        if "--QUIT--" in recdData:
            print("Client is requesting to quit")
            clientSocket.close()
            print("Connection " + ip + ":" + port + " closed")
            threadActive = False
        else:
            print("\nReceived: {}".format(recdData) + " from %d" %clientID)
            clientSocket.sendall("-".encode("utf8"))

def receive_input(clientSocket, BUFSIZE):
    recdData = clientSocket.recv(BUFSIZE)
    recdDataSize = sys.getsizeof(recdData)
    if recdDataSize > BUFSIZE:
        print("The input size is greater than expected {}".format(recdDataSize))
    decodedData = recdData.decode("utf8").rstrip()  # decode and strip end of line
    result = process_input(decodedData)
    return result

def process_input(input_str):
    return str(input_str).upper()

def add_client_to_list(client_ID, client_address):
    clientList[client_ID] = client_address
    print(clientList)

def send_client_list(clientSocket, clientList):
    jsonList = json.dumps(clientList)
    clientSocket.sendall(str(jsonList).encode("utf-8"))

def keyPress(stdscr):
    """checking for keypress"""
    stdscr.nodelay(True)  # do not wait for input when calling getch
    return stdscr.getch()

if __name__ == "__main__":
    initialize()

Client File:
import socket
import sys
import json

def initialize():
    sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = socket.gethostname()
    port = 6666
    try:
        sockfd.connect((host, port))
    except:
        print("Connection error")
        sys.exit()

    # Receiving server assigned client ID
    try:
        myID = sockfd.recv(1024).decode("utf-8")
        print("Received ID: " + myID + " from server.")
    except:
        print("Could not receive my ID from server")
        sys.exit()

    print("Enter 'quit' to exit and 'list' to receive client List")
    message = input(" -> ")
    while True:
        if message == "list":
            print("Receiving clientList from server...")
            try:
                jsonList = sockfd.recv(8192).decode("utf-8")
                clientList = json.loads(jsonList)
                print("Received list: %s" % clientList)
            except:
                print("Could not receive list from server")
                sys.exit()
        elif message != 'quit':
            sockfd.sendall(message.encode("utf8"))
            if sockfd.recv(5120).decode("utf8") == "-":
                pass

            message = input(" -> ")
        else:
            sockfd.send(b'--quit--')
            break;

if __name__ == "__main__":
    initialize()

This is what I have found. It is a small script which detects if the user inputs {a} on the console. And if he does, then a message is printed. Else it keeps listening for key presses.
import curses, time
def keyPress(stdscr):
    # checking for keypress
    stdscr.nodelay(True)  # do not wait for input when calling getch
    return stdscr.getch()
while True:
    if curses.wrapper(keyPress) == 97:
        print("You pressed 'a'")
    else:
        pass
    time.sleep(0.1)

It would be great if you could guide me how I can use this concept to detect key press on the server side and stop accepting client connections and call the function to send client list to all clients. Or if you have any other approaches or suggestions.


text:
Q: Weird capacitor looking things shows up in altium when I zoom into the pcb layout I am using altium for first time for my little circuit project. My layout start showing these weird capacitor looking things in PCB layout. What exactly are they and what are they used for and how do I disable them to show up on layout?

A: That comes from running a design rule check with no traces routed. It is showing you the rubber band connections that are not complete.
Go to Tools->Reset Error Markers to get rid of them. The rubber band lines will stay but the 'capacitor' error markers will go away.

A: That's a broken net. They will disappear as you route traces and run a DRC.


text:
Q: Assign DatePicker Selection Value To String Array On Change SWIFTUI I have a date picker, when the fromDate and toDate sections changes, I would like to assign it to the myArray["fromDate"] = $fromDate, how do I do that, thank you for your time.
I tried with onTapGesture, but it crash the app when I'm selecting the dates.
var myArray["fromDate"] : [String: Any]

 struct myDatePicker: View {
        @State public var toDate = Date()

        @State public var fromDate: Date = Calendar.current.date(byAdding: DateComponents(year: -1), to: Date()) ?? Date()

        var body: some View {
            HStack(spacing:10) {
                VStack(alignment:.leading, spacing:10) {
                    Text("Service Date Range")
                        .font(.system(size: 16))
                        .bold()
                        .foregroundColor(.black)
                    HStack {
                        DatePicker(selection: $fromDate.onchange({ myArray["fromDate"] = $fromDate}), displayedComponents: .date) {
                            Text("From")
                                .font(.body)
                                .fixedSize()
                        }
                        DatePicker(selection: $toDate, in: ...Date(), displayedComponents: .date) {
                            Text("To")
                                .font(.body)
                                .fixedSize()
                        }
                    }
                }
            }.padding(10)
        }
    }

A: you could try something like this:
DatePicker("From", selection: $fromDate)
   .onChange(of: fromDate) { myArray["fromDate"] = $0 }

or
DatePicker(selection: $fromDate, displayedComponents: .date) {
     Text("From").font(.body).fixedSize()
 }.onChange(of: fromDate) { myArray["fromDate"] = $0 }

A: The following will work in iOS 13 where you don't have access to onChange:
class ViewModel : ObservableObject {
    @Published public var toDate = Date()
    @Published var fromDate = Calendar.current.date(byAdding: DateComponents(year: -1), to: Date()) ?? Date() {
        didSet {
            //perform whatever side-effect you need here
            print("Set from date: \(fromDate)")
        }
    }
}

struct myDatePicker: View {
    @ObservedObject var viewModel = ViewModel()

    var body: some View {
        HStack(spacing:10) {
            VStack(alignment:.leading, spacing:10) {
                Text("Service Date Range")
                    .font(.system(size: 16))
                    .bold()
                    .foregroundColor(.black)
                HStack {
                    DatePicker(selection: $viewModel.fromDate, displayedComponents: .date) {
                        Text("From")
                            .font(.body)
                            .fixedSize()
                    }
                    DatePicker(selection: $viewModel.toDate, in: ...Date(), displayedComponents: .date) {
                        Text("To")
                            .font(.body)
                            .fixedSize()
                    }
                }
            }
        }.padding(10)
    }
}

I'm still not clear on where myArray is defined -- if it's just a global variable as you imply in the comments, you can set it inside the didSet that I show above.


text:
Q: data model for notification in social network? I build a social network with Neo4j, it includes:
Node labels: User, Post, Comment, Page, Group
Relationships: LIKE, WRITE, HAS, JOIN, FOLLOW,...
It is like Facebook.
example: A user follow B user: when B have a action such as like post, comment, follow another user, follow page, join group, etc. so that action will be sent to A. Similar, C, D, E users that follow B will receive the same notification.
I don't know how to design the data model for this problem and I have some solutions:

*

*create Notification nodes for every user. If a action is executed, create n notification for n follower. Benefit: we can check that this user have seen notification, right? But, number of nodes quickly increase, power of n.

*create a query for every call API notification (for client application), this query only get a action list of users are followed in special time (24 hours or a 2, 3 days). But Followers don't check this notification seen or yet, and this query may make server slowly.

*create node with limited quantity such as 20, 30 nodes per user.

*Create unlimited nodes (include time of action) on 24 hours and those nodes has time of action property > 24 hours will be deleted (expire time maybe is 2, 3 days).
Who can help me solve this problem? I should chose which solution or a new way?

A: I believe that the best approach is the option 1. As you said, you will be able to know if the follower has read or not the notification. About the number of notification nodes by follower: this problem is called "supernodes" or "dense nodes" - nodes that have too many connections.
The book Learning Neo4j (by Rik Van Bruggen, available for download in the Neo4j's web site) talk about "Dense node" or "Supernode" and says:

"[supernodes] becomes a real problem for graph traversals because the graph
  database management system will have to evaluate all of the connected
  relationships to that node in order to determine what the next step
  will be in the graph traversal."

The book proposes a solution that consists in add meta nodes between the follower and the notification (in your case). This meta node should got at most a hundred of connections. If the current meta node reaches 100 connections a new meta node must be created and added to the hierarchy, according to the example of figure, showing a example with popular artists and your fans:

I think you do not worry about it right now. If in the future your followers node becomes a problem then you will be able to refactor your database schema. But at now keep things simple!
In the series of posts called "Building a Twitter clone with Neo4j" Max de Marzi describes the process of building the model. Maybe it can help you to make best decisions about your model!


text:
Q: powerquery : combining two tables for each data i have two tables
one includes dates (table1)
Date
11/10/2019
11/17/2019

the other one has names (table2)
Name Surname
xxxxxx
yyyyyy

i want to combine the second table for each data in the table1
result should be
Name Surname      Date
xxxxxx           11/10/2019
yyyyyy           11/10/2019
xxxxxx           11/17/2019
yyyyyy           11/17/2019

i am sure it is very for you guys,
thanks for the help,

A: It's quite easy:
= Table.Join(table2,{},table1,{})


text:
Q: Remove some word/string from a regular expression pattern I have a vector with the following values:
list <- c("test_data", "train_data", "random_forest_output", "xgboost_output", "light_gbm_output", "all_output", "all_output_final")

I need to select all variables that contain "output" word, but in the case of values "all_output" and "all_output_final" I need to choose only the "all_output_final".
That is, I need to get a list like this:
new_list <- c("random_forest_output", "xgboost_output", "light_gbm_output", "all_output_final")

Is it possible to implement using a regular expression?

A: First off, it's misleading to other users to call a data object list For one thing list is an important R function and for another your object "list" is not an R list. That said it's pretty easy to do this with logical values returned from the regex function grepl by using &! to eliminate the unwanted pattern which is denoted regex-ly by including the end of string "$"
list[ grepl("output", list)&!grepl("^all_output$",list)]
[1] "random_forest_output" "xgboost_output"       "light_gbm_output"     "all_output_final"

You could read that &! (and NOT) expression as "... all of the preceding stuff  but nonone of the following matches"


text:
Q: href doesn't work, using react router I'm trying to get a separate url to a pop up module, I'm using a button to redirect :
trigger={ <Link href="/exercisesadd">
          <Button style={style} waves='light' > Add new</Button></Link>
        }>

but I receive 404 error, even though, i have this route in react router :
    export default () => {
    return <Route path="/"component={Container} auth={auth}>
        <IndexRoute component={Home}/>
        <Route path="/portfolio"  onEnter={requireAuth} component={Portfolio} />
        <Route path="/Login" component={Home} />
        <Route path="/home" component={Home}  />
        <Route path="/edit" component={Edits}/>
        <Route path="/exercises" component={Exercises}/>
        <Route path="/exercisesadd" component={Exercises}/>
    </Route>
};

A: The Link component takes a 'to' prop rather than href. So you would want
<Link to="/exerciseadd">


text:
Q: How to configure Gcloud Python Pyca library I am having trouble importing the key to the Google Cloud KMS. How to get the key imported to gcloud KMS?
Even if latest version of pyca library is installed then still no attribute 'aes_key_wrap_with_padding' is found. When removing pyca from pip and from ubuntu 20.04 then still the gcloud cli is able to find invalid version somewhere.
gcloud kms keys versions import   --import-job importing-soft-key-2   --location europe-north1   --keyring eID-Easy-ring-1   --key Soft   --algorithm rsa-sign-pkcs1-2048-sha256 --target-key-file mykey.key
ERROR: gcloud crashed (AttributeError): module 'cryptography.hazmat.primitives.keywrap' has no attribute 'aes_key_wrap_with_padding'

A: I think you have to install Pyca cryptography library. In Google Documentation in Importing key section there is article about it:

update the gcloud command-line tool to enable support for automatically wrapping keys for secure import into Cloud Key Management Service, by installing the Pyca cryptography library. Version 2.2.0 or higher adds support for the required aes_key_wrap_with_padding wrapping mechanism.

I think the documentation explains how to do it well enough for many OS.


text:
Q: creating environment variable with user-defined name - indirect variable expansion I am trying to create an environment variable in bash script, user will input the name of environment variable to be created and will input its value as well.
this is a hard coded way just to elaborate my question :
#!/bin/bash
echo Hello
export varName="nameX" #
echo $varName
export "$varName"="val" #here I am trying to create an environment
#variable  whose name is nameX and assigning it value val
echo $nameX

it works fine
it's output is :
Hello
nameX
val

But, I want a generic code. So I am trying to take input from user the name of variable and its value but I am having trouble in it. I don't know how to echo variable whose name is user-defined
echo "enter the environment variable name"
read varName
echo "enter the value to be assigned to env variable"
read value
export "$varName"=$value

Now, I don't know how to echo environment variable
if I do like this :
echo "$varName"

it outputs the name that user has given to environment variable not the value that is assigned to it. how to echo value in it?
Thanks

A: To get closure: the OP's question boils down to this:
How can I get the value of a variable whose name is stored in another variable in bash?
var='value'    # the target variable
varName='var'  # the variable storing $var's *name*

gniourf_gniourf provided the solution in a comment:
Use bash's indirection expansion feature:
echo "${!varName}"  # -> 'value'

The ! preceding varName tells bash not to return the value of $varName, but the value of the variable whose name is the value of $varName.
The enclosing curly braces ({ and }) are required, unlike with direct variable references (typically).
See https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html
The page above also describes the forms ${!prefix@} and ${!prefix*}, which return a list of variable names that start with prefix.

bash 4.3+ supports a more flexible mechanism: namerefs, via declare -n or, inside functions, local -n:
Note: For the specific use case at hand, indirect expansion is the simpler solution.
var='value'

declare -n varAlias='var'  # $varAlias is now another name for $var

echo "$varAlias" # -> 'value' - same as $var

The advantage of this approach is that the nameref is effectively just an another name for the original variable (storage location), so you can also assign to the nameref to update the original variable:
varAlias='new value'  # assign a new value to the nameref

echo "$var" # -> 'new value' - the original variable has been updated

See https://www.gnu.org/software/bash/manual/html_node/Shell-Parameters.html

Compatibility note:

*

*Indirect expansion and namerefs are NOT POSIX-compliant; a strictly POSIX-compliant shell will have neither feature.

*ksh and zsh have comparable features, but with different syntax.


text:
Q: Including a file with the Site Directory - Making Navigation always include connect.php no matter what sub-directory I've been working on a small site, to work on my PHP Skills. I've got the navigation inside of a sub-folder called Templates. Now basically, the navigation is going to be included on every page, and along with it connect.php. Now the problem is, if it goes into another sub-folder then it isn't going to be able to find the connect.php file. I've got the APP Directory setup, and that is working on the Stylesheet and all.
However I'm not sure how I would do the include, I got the idea/code for the link href from StackOverflow on another question and on that it said that include (APP_DIR .'connect.php') however that doesn't seem to work for me, it brings up an error "Warning: include(APP_ROOT/connect.php): failed to open stream: No such file or directory in C:\xampp\htdocs\ytsite\templates\navigation.php on line 2
"
Any help on how to correctly include a file so no matter where it is, it includes the connect would be much appreciated.
Thanks,
Ben

A: Your constant should be a directory path, not a url. Try this with your constant definition..
define('APP_ROOT', $_SERVER['DOCUMENT_ROOT'] . '/ytsite' );

echo APP_ROOT; //to test

Not tested. Beware you don't get double slashes and make sure the path goes to the correct directory.
Also make sure you add a slash when you include 'connect.php'. Include it in the constant definition, or add it to your include line.
include (APP_ROOT .'/connect.php');

edit
So include your connect file like this:
Make a master file to include into your pages and add these lines.
<?php
    define('APP_ROOT', $_SERVER['DOCUMENT_ROOT'] . '/ytsite' );
    include (APP_ROOT .'/connect.php');
?>

Every time you launch a new page, the constant needs to be recreated.


text:
Q: C# string and sql injection I want to protect the DB from SQL Injection attacks, and I have noticed that post http://www.dascode.net/post/2009/11/01/An-example-of-how-to-check-for-SQL-Injections.aspx which can be useful.
Here's scenario (I'm using Entity Framework)
1) user want to add e.g. a comment like "I want to select a book, then open it and get a char".
code snippet (an example):
string commVal = "lorem";

using(DB ctx = new DB())
{
   Comment c = new Comment { Value = commVal };
   ctx.Comment.Add(c);
   ctx.SaveChanges();
}

As you can see it's not a SQL Injection but that string contains unwanted words - select, open, char. So, the only way for prevention from the SQL Injection is to add a quotation marks around that unwanted words ?

A: No, and the original article doesn't work at all. The easiest and cheapest way to avoid SQL injection attacks is to used parameterized queries, and EF (and almost all ORMs) does just that.
A parameterized query is a query where all external values are replaced by (strongly-typed) parameters. The parameter values are passed out-of-band so there is no way that SQL Injection can occur.
There are multiple added benefits when using parameterized queries:

*

*You avoid internationalization errors with ASCII, decimal separators, date formats, because the values are passed as their original types.

*Network traffic is reduced because the native representations are invariably smaller than their text equivalents.

*The resulting queries result in much faster system performance, because SQL Server only has to parse a parameterized query the first time it is sent. Subsequent executions use the original execution plan.

So, the original article is wide open to injection attacks while EF is safe.


text:
Q: Why is my ng-style not working? I am trying to set a style with ng-style.  I have an array:
scope.order = [0, 1, 2, 3, 4, 5]

And I am trying to use it to set the order on a div:

 ...

And the order is not being set.
I have tried ng-style="{order: order.indexOf(3)}"
  And that doesn't work either.  I am using Angular 1.5.8.  How does this work?

A: your code looks fine, you only need to make the array visible on your template, instead of using a block scope declaration.
try to define your array attached to the $scope.
$scope.order = [0, 1, 2, 3, 4, 5];

or if you using controller as syntax
this.order = [0, 1, 2, 3, 4, 5]

A: Try to assign the order to $scope.

let order = [0, 1, 2, 3, 4, 5]
  angular.module('myApp', [])
      .controller("example", ["$scope", function (s) {
          s.order = order;
      }])

 Order:  {{order.indexOf(3)}}


text:
Q: Bug using Python 3.7 (from QGIS) and trying to install package with pip I use QGIS 3.6 and Python 3.7 and I try to install a package with pip in command line tool under Windows 7 but I have the following message :
Fatal Python error: initfsencoding: unable to load the file system codec
ModuleNotFoundError: No module named 'encodings'

Current thread 0x0000188c (most recent call first):

My path and PYTHONPATH are well configured with link to QGIS' Python folders. The problem appeared recently with use of Python 3.7.

A: At least for Mac recent QGIS versions seem to support only Python 3.6, not 3.7, see https://qgis.org/en/site/forusers/download.html


text:
Q: Android BackGround Service With HTTPS and Location Request Does 436 HTTPS request and 36 location request per day on background of an android app drain battery high?

A: In my opinion 436 HTTPS requests would not cause severe battery drain but location might do but
Thats depends on how you are requesting location from location manager.
Are you requesting location updates after regular interval?
e.g. locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, locationListener);
If yes then that requires location services always ON and that may cause battery drain.

A: HTTPS requests doesn't have any effect on the battery but location listening might cause a battery drain if you used it wrong.
For example requesting a location update and never removing it will cause the location listener to always search for location in background and it depends on which provider you use either GPS or NETWORK, so my advice to u is to set and scheduled requests and every time you request an location update once you get the location remove the location update request so it do not keep getting the location


text:
Q: Mongoid saving only ids and leaving out other fields I am using Nokogiri and mongoid in a test project.
Here's my code:
urls = Array[
  'http://www.example.com/cairo',
  'http://www.example.com/alexandria',
]

urls.each do |url|
  doc = Nokogiri::HTML(open(url))
  #Theater and location details here

  #movies scrapper starts here
  movies = doc.css('.itemContainer')

  movies.each do |movie|

  #movie title
  title = movie.css("h3.catItemTitle a").text

  #More code here

  #movie synopsis
  synopsis = movie.css(".catItemIntroText p").text

  Movie.create! {
    {title: title}
    {synopsis: synopsis }
    #{movielength: movielength }
    #embedded theater collection
      {theaters: {theater: theater,
             address: address
            }
        }
  }
 end
end

My mongoid models look like this:
require 'mongoid'

class Movie
  include Mongoid::Document

  field :title, :type => String
  field :synopsis, :type => String

  attr_accessible :title, :synopsis

  embeds_many :theaters
end

When I run the Nokogiri script only the mongodb objectid gets saved and the field details are not created or saved.
Here's a sample of my database:
] }
{ "_id" : ObjectId("52be9b3c4cfad19f0c000011") }
{ "_id" : ObjectId("52be9b3c4cfad19f0c000012") }
{ "_id" : ObjectId("52be9b3c4cfad19f0c000013") }
has more

Everything works well using Ruby puts to output but saving in mongodb is a hassle. What am I doing wrong? I am using Mongoid (3.1.6) with Ruby 1.9.3p448 on Mac OS Mavericks.

A: You're nesting the hashes. Do this instead for a starter:
Movie.create!(title: title, synopsis: synopsis, theaters: [theater])


text:
Q: Calculating preferred height based on actual Codenameone's component width I'm creating a custom Codenameone component that has variable size. The component displays a fixed amount of text, spanning multiple lines. Thus the width and height are related. If the width is small less text fits on a line and more lines are needed. I've managed to set preferred width and preferred height. The trouble is that when the actual painting occurs the width is apparently given by the graphics object graphics.getClipWidth() and doesn't match my preferred width. Thus my preferred height (which appears equal to graphics.getClipHeight() when painting) is incorrect as the clip width is unequal to my preferred width, which was used to calculate the preferred height. How can I get graphics.getClipHeight() to have the correct height? In other words, is it possible to specify the height of the component using the width the component will actually have when rendering?
Best wishes
Marc K

A: That's the exact problem we have with the TextArea and I'm afraid there are no easy answers. E.g. if the component provides a preferred size of X the layout manager might decide to allocate size differently thus requiring a different layout.
This was a conscious design choice we made when building Codename One, in order to accomplish this you will need to "reflow" effectively recursing thru the hierarchy recalculating sizes/dimensions until you get the best fit. These algorithms are by definition slow and harder to benchmark (since its hard to predict how reflow will behave on the device with varying fonts, paddings etc.).
In the TextArea we have a "poor mans reflow" that triggers revalidation if the width doesn't seem right. This has been a source of many problems in TextArea.
You can see this in the TextArea source, search for the setShouldCalcPreferredSize calls.


text:
Q: Gnuplot histogram with errorbars (High and Low) I am trying to create a histogram (barchart) with High and Low errors, using gnuplot. I have found this thread Gnuplot barchart histogram with errorbars Unfortunately it consists only from X value and X-error (2 vaues). Whats I would like to achieve is X value (average) and error bar consisting of High and Low values (total 3: avg, High and Low). How I can do this using gnuplot?
My script is identical to the one mentioned in the Thread, I only changed some labels etc (simple cosmetic changes). My example dataset structure is as follows:
WikiVote 10 12 7

A: If you have a very simple datafile:
#y ymin ymax
4   3    8

You can plot this datafile using:
set yrange [0:]
set style histogram errorbars gap 2 lw 1
plot 'datafile' u 1:2:3 w hist

A: I have modified the code provided by mgilson, to achieve multiple histograms for a single X value. If anybody needs it here is the code.
plot 'stack_2.dat' u 2:3:4:xtic(1) w hist ti "Hadoop" linecolor rgb "#FF0000", '' u 5:6:7:xtic(1) w hist ti "Giraph" lt 1 lc rgb "#00FF00"

Here is the pattern
    #y_0 #min #max #y_1 #min #max
Dataset 4   3    8    6    5    9


text:
Q: How can I write a "Hello World" app in assembly language?
Possible Duplicate:
how to write hello world in assembler under windows?

I've often heard of applications written using the language of the gods, assembly language. I've never tried though, and I don't even have a clue how to do it.
If I wanted to dabble, how would I go about doing it? I know absolutely nothing about what is required, although presumably some kind of compiler and Notepad.
Just purely out of curiousity, what would I need to write a "Hello World!" application?
Edit to add, I am running Windows 7 64bit
Edit to add, I wonder if there is an assembly language plugin for Visual Studio?

A: For this, you gain nothing by writing 64-bit code -- you might as well stick to 32-bit code.
If you want output to a MessageBox, it could look like this:
.386
.MODEL flat, stdcall

MessageBoxA PROTO near32 stdcall, window:dword, text:near32,
        windowtitle:near32, style:dword

.stack 8192

.data
message db "Hello World!", 0
windowtitle   db "Win32 Hello World.", 0

.code
main proc
        invoke MessageBoxA, 0, near32 ptr message, near32 ptr windowtitle, 0
        ret
main endp
        end main

If you want output to the console, it's (strangely enough) a bit more complex:
.386
.MODEL flat, stdcall

getstdout = -11

WriteFile PROTO NEAR32 stdcall,     \
        handle:dword,                   \
    buffer:ptr byte,        \
        bytes:dword,                    \
        written: ptr dword,             \
        overlapped: ptr byte

GetStdHandle PROTO NEAR32, device:dword

ExitProcess PROTO NEAR32, exitcode:dword

.stack 8192

.data
message db "Hello World!"
msg_size equ $ - offset message

.data?
written  dd ?

.code
main proc
    invoke GetStdHandle, getstdout
    invoke WriteFile,                   \
           eax,                         \
           offset message,              \
           msg_size,                    \
           offset written,              \
           0

    invoke ExitProcess, 0
main endp
        end main

In theory, moving to 64 bit code doesn't make a lot of difference -- for example, you can use the same functions in both. In reality, it's a bit painful, because the calling convention for 64-bit code is somewhat complex, and you can't use MASM's invoke for 64-bit code. Working code wouldn't be a whole lot more complex, but getting the code working probably would be a bit more work. The general idea is that for 64-bit code, you allocate space on the stack for all your parameters, but the first N parameters that are small enough to fit, go in registers.

A: Have a look at WinAsm.

A: I advise you find a tool supporting Intel style ASM, rather than AT&T's horrible syntax.

A: In fasm:
include 'win32axp.inc'

.code
  start:
        invoke  AllocConsole
        invoke  WriteConsole,<invoke GetStdHandle,STD_OUTPUT_HANDLE>,tex,tex.size,dummy,0
        invoke  Sleep,-1
.end start

.data
tex     TCHAR   'Hello World!'
 .size  =       ($-tex)
dummy   rd      1


text:
Q: How to implement ImageSVG() using FPDI and TCPDF to render PDF? I'm using FPDI to render a PDF that has a PDF set as a background, but want to include an SVG file on it, which for some reason gives me the error while using the TCPDF library along with it. Are there any workarounds, or my code incorrect.
(before I put in the "ImageSVG" and "require('tcpdf.php')" lines, it was working perfectly)
Here's my PHP code:
ob_clean();
ini_set("session.auto_start", 0);
define('FPDF_FONTPATH','font/');
define('FPDI_FONTPATH','font/');
require('fpdf.php');
require('fpdi.php');
require('tcpdf.php');

$pdf = new FPDI();

// let's get an id for the background template
$pdf->setSourceFile('/home/user/public_html'.$pdfName);
$backId = $pdf->importPage(1);

// iterate over all pages of HTML_Generated_pdf.pdf and import them
$pageCount = $pdf->setSourceFile('/home/user/public_html/wp-content/themes/myTheme/'.$filename.'.pdf');
for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
    // add a page
    $pdf->AddPage($specs['h'] > $specs['w'] ? 'P' : 'L', 'Letter');
    // add the background
    $pdf->useTemplate($backId);
    // import the content page
    $pageId = $pdf->importPage($pageNo);
    // add it
    $pdf->useTemplate($pageId);

    $pdf->ImageSVG($file='images/EN-Logo.svg', $x=30, $y=100, $w='', $h=100, $link='', $align='', $palign='', $border=0, $fitonpage=false);
}

$pdf->Output($filename.'2.pdf', 'F');

The error I'm getting: ImageSVG not a method of FPDI library.
I know that this method is part of the TCPDF library, which I have already included (7th line of text). Anyone care to help?

A: Remove the require statement for FPDF require('fpdf.php');. That way FPDI will extend TCPDF instead of FPDF.
You also can remove the constants. If you use TCPDF you don't need a constant of FPDF. Additionally FPDI_FONTPATH it's never used nor documentated at all and uselsee in any case.


text:
Q: Issue to access KSQL CLI on Docker I'm trying access the KSQL CLI for first time on Windows terminal but I got the error: Unable to find image 'cp-ksql-cli:5.3.1' locally
To do it I get docker images
$ docker images
REPOSITORY                                  TAG                 IMAGE ID            CREATED             SIZE
cnfldemos/kafka-connect-datagen             0.1.3-5.3.1         f88aea51c605        2 weeks ago         1.03GB
confluentinc/ksql-examples                  5.3.1               b9fb66d15198        4 weeks ago         499MB
confluentinc/cp-ksql-server                 5.3.1               7c40b5e474a2        4 weeks ago         522MB
confluentinc/cp-ksql-cli                    5.3.1               a488fb1cc028        4 weeks ago         510MB
confluentinc/cp-enterprise-kafka            5.3.1               2b5ee743a097        4 weeks ago         646MB
confluentinc/cp-enterprise-control-center   5.3.1               c29150c8588e        4 weeks ago         771MB
confluentinc/cp-schema-registry             5.3.1               b7abcb36a4d9        4 weeks ago         986MB
confluentinc/cp-kafka-rest                  5.3.1               27066ec8dcc2        4 weeks ago         984MB
confluentinc/cp-zookeeper                   5.3.1               711eb38827f6        4 weeks ago         590MB

So:
$ docker run cp-ksql-cli:5.3.1 http://ksql-server:8088

also it:
$ docker run confluentinc/cp-ksql-cli:5.3.1 http://ksql-server:8088

and got the error:
Unable to find image 'cp-ksql-cli:5.3.1' locally

I'am a new on KSQL and I don't know if this is the correct way to access the CLI. On the google I found this tutorial but I can't understanted how enter on the KSQL CLI terminal. Besides that I don't know how it connect with my Kafka broker, zookeper and others..
SOLVED
Accessed using: $ docker-compose exec ksql-cli ksql http://ksql-server:8088

A:
I don't know how it connect with my Kafka broker, zookeper and others..

KSQL CLI doesn't. Kafka is connected to Zookeeper, and KSQL server is connected to Kafka.
KSQL CLI only connects to KSQL Server.
Therefore, you need a total of at least 4 containers to be running at once, which is why Docker Compose is recommended, as the tutorial you linked to shows.

the correct way to access the CLI

It should be like this, where some_network is a Docker network that already hosts a ksql-server container
docker run --rm -ti --network=some_network confluentinc/cp-ksql-cli:5.3.1 http://ksql-server:8088

(or longer version shown in the tutorial is docker run --network some_network --rm --interactive --tty ...)

A: I think it's because you didn't open the 8088 port.
Checkout below docker commands.
1) KSQL server docker start
$ docker run \
    -p 127.0.0.1:8088:8088 \
    -e KSQL_BOOTSTRAP_SERVERS=localhost:9092 \
    -e KSQL_LISTENERS=http://0.0.0.0:8088/ \
    -e KSQL_KSQL_SERVICE_ID=ksql_standalone_1_ \
    confluentinc/cp-ksql-server:5.3.1

2) KSQL-cli docker start
$ docker run --net=host --interactive --tty \
    confluentinc/cp-ksql-cli:5.3.1 \
    http://localhost:8088

If you do this, it will work out.
Good luck.


text:
Q: Why is my Python turtle screen asymmetrical? I created a pong game where I noticed the paddles are not placed equally at the screen edges.
I created an 800 pixel wide screen, and placed paddles at xcor = 380 and xcor = -380 but on the screen left paddle shows some gap but right paddle doesn't. Is my screen unsymmetrical? How do I fix it?
screen.setup(width=800, height=600)
screen.bgcolor("black")
screen.title("PONG")
screen.tracer(0)

l_paddle = Paddle()
l_paddle.create_paddle((-380, 0))
r_paddle = Paddle()
r_paddle.create_paddle((380, 0))

screenshot of screen

A: When we specify a window size to setup(), we're talking about total pixels used on the screen.  Since there is chrome around the window (edges, title bar, etc.) the actual area we have to work with is slightly smaller.  Trying to place two turtles at exactly the left and right edge, ignoring chrome:
from turtle import Screen, Turtle

CURSOR_SIZE = 20

WIDTH, HEIGHT = 600, 400

screen = Screen()
screen.setup(WIDTH, HEIGHT)

l_paddle = Turtle('square')
l_paddle.fillcolor('white')
l_paddle.setx(CURSOR_SIZE/2 - WIDTH/2)

r_paddle = Turtle('square')
r_paddle.fillcolor('white')
r_paddle.setx(WIDTH/2 - CURSOR_SIZE/2)

screen.exitonclick()

We get a result similar to yours:

If we compensate for the internal and external chrome elements:
from turtle import Screen, Turtle

CURSOR_SIZE = 20
BORDER_SIZE = 2  # inside the window
CHROME_SIZE = 9  # around the window

WIDTH, HEIGHT = 600, 400

screen = Screen()
screen.setup(WIDTH, HEIGHT)

l_paddle = Turtle('square')
l_paddle.fillcolor('white')
l_paddle.setx(CURSOR_SIZE/2 - WIDTH/2 + BORDER_SIZE)

r_paddle = Turtle('square')
r_paddle.fillcolor('white')
r_paddle.setx(WIDTH/2 - CURSOR_SIZE/2 - BORDER_SIZE - CHROME_SIZE)

screen.exitonclick()

We can get a more precise result:

The problem here is that the amount of chrome is system dependent but turtle doesn't tell us how much to compensate.  You might be able to find out from the underlying tkinter code.
My recommendation is you estimate the best you can, assume it's not accurate on all systems, and stay away from the edges so it's less of an issue.  The error can be greater in the Y dimension when the title bar is part of the chrome.


text:
Q: Morris Line Chart not working I'm trying to figure out what's wrong with my code. I've read the documentation a lot of times but I don't know why this is simply not working. In this code I show the stats of the last 7 days. Even the label just shows 'V' instead of 'Value'. What's going on?!

var ledata = {
 "element":"bar-example",
 "data":[
  {"day":"31","count":0},
  {"day":"01","count":0},
  {"day":"02","count":0},
  {"day":"03","count":0},
  {"day":"04","count":0},
  {"day":"05","count":0}
 ],
 "xkey":"day",
 "ykeys":["count"],
 "labels":"Value"
};
new Morris.Line( ledata );
<!DOCTYPE html>

<meta charset=utf-8 />
<title>Morris.js Bar Chart Example</title>

A: Labels should be a list. You could have more than one series, so you could have more than one label. You need to define it as an array.
As for the days, this value needs to be a date, now you're just setting the day. Easiest way would be to use the Date object. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date. Morris.js can work with the milliseconds format returned by Date object.
Once the date is properly set, you can always modify the way it's displayed on the chart using xLabelFormat or the intervals using xLabels.

var date = new Date();

var ledata = {
  "element": "bar-example",
  "data": [{
    "day": date.valueOf(),
    "count": 0
  }, {
    "day": date.setDate(date.getDate() - 1),
    "count": 0
  }, {
    "day": date.setDate(date.getDate() - 1),
    "count": 0
  }, {
    "day": date.setDate(date.getDate() - 1),
    "count": 0
  }, {
    "day": date.setDate(date.getDate() - 1),
    "count": 0
  }, ],
  "xkey": "day",
  "xLabelFormat": function(x) {
    return x.toLocaleDateString();
  },
  "ykeys": ["count"],
  "labels": ["Value"],
  "xLabels": "days"
};
new Morris.Line(ledata);
<!DOCTYPE html>

  <meta charset=utf-8 />
  <title>Morris.js Bar Chart Example</title>


text:
Q: Trying to locate a leak! What does anon mean for pmap? I'm trying to locate where my memory has gone for a java process running in linux. Someone suggested I use pmap -x to see exactly what the memory is doing.
The output is really long but basically a good portion of it is a repeat of this:
00007fbf75f6a000    1016       -       -       - rwx--    [ anon ]
00007fbf76068000      12       -       -       - -----    [ anon ]

What exactly does this mean? Why do I have so many entries of this (4000+)?

A: Anon blocks are "large" blocks allocated via malloc or mmap -- see the manpages. As such, they have nothing to do with the Java heap (other than the fact that the entire heap should be stored in just such a block).
In my experience, thread stacks also use anon blocks. If you see a lot of anon blocks that all have the same size, and that size is 512k to 4Mb (the example below is repeated over a dozen times for a Tomcat process that I have running), that's the likely cause. Depending on the program, you may have up to a few dozen of these; if you're seeing thousands, it means you have a problem with threading.
b089f000    504K rwx--    [ anon ]
b091d000     12K -----    [ anon ]
b0920000    504K rwx--    [ anon ]
b099e000     12K -----    [ anon ]
b09a1000    504K rwx--    [ anon ]
b0a1f000     12K -----    [ anon ]

But that leaves a question: why are you using pmap to diagnose a Java memory issue?

A: See this part this part of System Performance Tuning for anonymous memory.

A: I've seen that pattern before in a thread leak.  If you have code that is trying to pool threads, but somehow messes up and leaks a thread, you get a pattern like that in pmap.
I think each bit of memory is the minimum stack size for the thread, certainly it had nothing to do with heap in our case.
We still got OutOfMemoryErrors when we hit OS limits, even tho when we analise the heap it is not overallocated.
When we had a problem like this pmap [pid] | grep -c 12K turned out to be the number of threads in use.

A: Use Eclipse MAT (when you get OutOfMemoryExceptions in the Java Heap not the native heap).


text:
Q: DRF PWT Postman detail": "Authentication credentials were not provided Отправляю запрос в Postman по адресу http://127.0.0.1:8000/api/v1/users/, перед этим генерируя токен с использованием username и password по адресу http://127.0.0.1:8000/api/v1/token/obtain/, но Postman выдаёт "detail": "Authentication credentials were not provided."
settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
      ...
    'rest_framework',
    'rest_framework_simplejwt',
]

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
    'PAGE_SIZE': 15,

    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renders.JSONRenderer',
        'rest_framework.renders.BrowsableAPIRenderer',
    ],

    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    )
}

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=20),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
    'ROTATE_REFRESH_TOKENS': False,
    'BLACKLIST_AFTER_ROTATION': False,
    'UPDATE_LAST_LOGIN': False,

    'ALGORITHM': 'HS256',
    'SIGNING_KEY': SECRET_KEY,
    'VERIFYING_KEY': None,
    'AUDIENCE': None,
    'ISSUER': None,
    'JWK_URL': None,
    'LEEWAY': 0,

    'AUTH_HEADER_TYPES': ('Token',),
    'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
    'USER_ID_FIELD': 'id',
    'USER_ID_CLAIM': 'user_id',
    'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule',

    'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
    'TOKEN_TYPE_CLAIM': 'token_type',
    'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser',

    'JTI_CLAIM': 'jti',

    'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
    'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
    'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}

views.py
from rest_framework import viewsets
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticatedOrReadOnly, IsAdminUser, IsAuthenticated
from api.permissions import IsAdminOrReadOnly, IsOwnerOrReadOnly

from author.models import Author
from book.models import Book
from order.models import Order
from django.contrib.auth.models import User

from api.serializers import *

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = (IsAuthenticated,)

urls.py
urlpatterns = [
    path('', include(router.urls)),
    path('drf-auth/', include('rest_framework.urls')),
    path('token/obtain/', TokenObtainPairView.as_view(), name='obtain_token'),
    path('token/refresh/', TokenRefreshView.as_view(), name='refresh_token'),
    path('token/verify/', TokenVerifyView.as_view(), name='verify_token'),
]

A: Нашел ошибку:
Так как я импортировал renderers из rest_frameword в settings.py, то drf не загружал настройки из словаря settings.REST_FRAMEWORK.


text:
Q: Drawing a 3-Point Arc VB.NET I'm trying to create a simple interface (like paint) to draw a few basic shapes such as lines, circles, and arcs. I've already got lines and circles figured out, but I'm having difficulties getting the desired effect of drawing arcs. I'm using the graphics.Draw... methods in .NET right now, but might be willing to try a different native approach.
I'm looking to create the functionality that a user picks a start point, end point and "radius". However, I want the "semi-circle" to be touching all three points.  Following the picture (taken from the application), Pt5 is calculated from the user's three clicks and sets the "radius" of the arc. The image depicts that the center of the circle is on Pt4, but ideally the center would be calculated with Pt1 and Pt2 at the edge.
Once the center is calculated, I'd like to use it to create the Arc's bounds (DrawArc(Pens.Black, CInt(Center.X - Radius), CInt(Center.Y - Radius), CInt(Radius * 2), CInt(Radius * 2), ?, ?)) and "cut" the circle by the projection of points Pt1 and Pt2 along the Pt1-Pt2 line.
Here's my calculation for the lines/circle above (sorry for the lengthy question...):
    '' Pt1 and Pt2 are taken earlier
    Dim pt3 As Point = e.Location
    Dim pt4, pt5, pt10, pt11, Cntr As New Point
    Dim m1, m2, m3, m4 As Double
    Dim b1, b2, b3, b4, b5 As Double
    Dim r As Double
    '' Get center (midpoint)
    pt4.X = ((pt1.X - pt2.X) / 2) + pt2.X
    pt4.Y = ((pt1.Y - pt2.Y) / 2) + pt2.Y
    '' Get picked-point slope
    m1 = (pt2.Y - pt1.Y) / (pt2.X - pt1.X)
    '' Inverse slope
    m2 = -(1 / m1)
    '' Get picked-intercept
    b1 = pt1.Y - (m1 * pt1.X)

    '' Get perpendicular intercept
    b2 = pt4.Y - (m2 * pt4.X)
    '' Get parallel intercept
    b3 = pt3.Y - (m1 * pt3.X)

    ''ln1: y = m1X + b1 ; (pt1, pt2)
    ''ln2: y = m2X + b2 ; (pt4, pt5)
    ''ln3: y = m1X + b3 ; (pt3, pt5)
    '' pt5.X = (yInt1 - yInt2)/(slope1-slope2)
    '' pt5.Y = (slope2 * pt5.X) + yInt2
    pt5.X = ((b2 - b3) / (m1 - m2))
    pt5.Y = (m2 * pt5.X) + b2

    '' Get perpendicular slope between Pt1 and Pt5
    m3 = -(1 / (pt5.Y - pt1.Y) / (pt5.X - pt1.X))
    '' Get perpendicular slope between Pt2 and Pt5
    m4 = -(1 / ((pt5.Y - pt2.Y) / (pt5.X - pt2.X)))
    '' Get perpendicular intercept between Pt1 and Pt5
    b4 = pt1.Y - (m3 * pt1.X)
    '' Get perpendicular intercept between Pt2 and Pt5
    b5 = pt2.Y - (m4 * pt2.X)
    Cntr.X = (b5 - b4) / (m3 - m4) '((m3 * m4 * ((pt1.Y - pt2.Y))) + (m4 * (pt1.X + pt5.X)) - (m3 * (pt5.X + pt2.X))) / (2 * (m4 - m3))

    Cntr.Y = (m2 * Cntr.X) + b2
    '' Calculate radius
    r = Math.Sqrt(((pt5.Y - Cntr.Y) ^ 2) + ((pt5.X - Cntr.X) ^ 2))

A: So we're all on the same page, the DrawArc method has several overloads, but I'll be using this one
Public Sub DrawArc(pen As System.Drawing.Pen,
                   x As Single,
                   y As Single,
                   width As Single,
                   height As Single,
                   startAngle As Single,
                   sweepAngle As Single)

In order to use it we need to calculate the bounding rectangle that contains the arc, if it were drawn as a complete ellipse, the angle to start sweeping from, and the central angle of the arc.
For the following the user is defining the three arc points in a more common way: Center, Start, Angle. That is, the first click defines the center, the second click determines the start point, and the third click determines the angle that the arc spans. It's easy enough to adapt this to other methods, but the one I'm using has the simplest math to explain.
On the first click, we record the mouse position into the variable center.  This is now the center of our arc.
On the second click, we record the mouse position into the variable start.  This point gives us two key pieces of information, the radius, and angle to the start point.  We calculate the radius using the Pythagorean theorem (aka the distance formula) as follows:
r = Math.Sqrt(Math.Pow(start.X - center.X, 2) + Math.Pow(start.Y - center.Y))

To calculate the angle we can use the arc-tangent of Δy/Δx
theta = Math.Atan((start.Y - center.Y) / (start.X - center.X))

(I'll leave it as an exercise for you to check for (start.X - center.X) = 0 and figure out whether it's +/- π/2.)
We now also have enough information to calculate the bounding rectangle for the arc.  Since the arc is circular, our box is just
x = center.X - r
y = center.Y - r
width = 2 * r
height = 2 * r

When the user clicks for the third time (or indeed whenever the mouse is moved) we store the value into the angle variable. Now, all we need to do is calculate the angle for that point, since we're drawing a circular arc segment. The second angle is calculated the same way as the previous:
alpha = Math.Atan((angle.Y - center.Y) / (angle.X - center.X))

(Remember, as before, to check for (angle.X - center.X) = 0)
We can now calculate the sweep angle by subtracting
sweep = theta - alpha

We now have enough information to call the DrawArc method using our calculated parameters:
g.DrawArc(Pen.Black, x, y, width, height, theta, sweep)

A few final thoughts:

*

*This method will always draw the arc counter-clockwise from the starting
angle.

*The center, start and end variables are all PointF, you will need to convert as necessary.  I removed the conversions and capture logic to make the code above easier to follow.

*All other variables are Single. You'll need to convert the results of the Atan function to Single.

*If Δx is 0 when calculating the arc-tangent, you can tell whether the angle is positive or negative by comparing the y values. If (center.Y < start.Y) then you know it's +π/2.
-You should also probably check for a 0 radius.

A: I may have misunderstood exactly what you are trying to do, but assuming that your calculation for pt5 is what you want and you want pt1 and pt2 to be on the circumference, then something like this might do it.
I think you want pt5 to be the centre.
r = Math.Sqrt((pt5.Y - pt1.Y) ^ 2 + (pt5.X - pt1.X) ^ 2)

Assuming you already have access to an appropriate graphics object, g
g.DrawEllipse(Pens.Blue, New Rectangle(pt5.X - r, pt5.Y - r, 2 * r, 2 * r))

A: I used a number of resources to accomplish my objective. In the end, I ended up dropping the use of DrawArc for ExcludeClip thanks to this question. Basically, once I created the right ellipse, I needed to clip the area of the ellipse between points 1 and 2. Below, you'll see my solution. The first image shows the "helper" lines I used to verify my math was correct, followed by the end result.
Legend:
*Yellow Line1: Perpendicular to Pt1-Pt2 line at midpoint (Pt4-Pt5)
*Yellow Line2: Perpendicular line to first yellow (parallel to Pt1-Pt2 line) (Pt3-Pt5)
*Pt5: Intersection point between yellow lines
*Red Line: Pt1-Pt5
*Blue Line:Pt2-Pt5
*Pink lines: Perpendicular lines to Red/Blue at midpoints (Pt10,Pt11)
*Center: Intersection point between pink lines (Cntr)
*Beige Lines: Extensions of Red/Blue lines, used in ExcludeClip {(Pt20-Pt1-Pt5) and (Pt21-Pt2-Pt5)}

Here's my code:
Dim pt3 As Point = e.Location
Dim pt4, pt5, pt10, pt11, pt20, pt21, Cntr As New Point
Dim m1, m2, mr, mt As Double
Dim b1, b2, b3, b4, b5 As Double
Dim r As Double

'' Get center (midpoint)
pt4.X = ((pt1.X - pt2.X) / 2) + pt2.X
pt4.Y = ((pt1.Y - pt2.Y) / 2) + pt2.Y
'' Get picked-point slope
m1 = (pt2.Y - pt1.Y) / (pt2.X - pt1.X)
'' Inverse slope
m2 = -(1 / m1)
'' Get picked-intercept
b1 = pt1.Y - (m1 * pt1.X)
'' Get perpendicular intercept
b2 = pt4.Y - (m2 * pt4.X)
'' Get parallel intercept
b3 = pt3.Y - (m1 * pt3.X)

''ln1: y = m1X + b1 ; (pt1, pt2)
''ln2: y = m2X + b2 ; (pt4, pt5)
''ln3: y = m1X + b3 ; (pt3, pt5)
'' pt5.X = (yInt1 - yInt2)/(slope1-slope2)
'' pt5.Y = (slope2 * pt5.X) + yInt2
pt5.X = ((b2 - b3) / (m1 - m2))
pt5.Y = (m2 * pt5.X) + b2

'' Setup Pt1-Pt5 perpendicular line (Pt10-Cntr)
pt10.X = ((pt5.X - pt1.X) / 2) + pt1.X
pt10.Y = ((pt5.Y - pt1.Y) / 2) + pt1.Y

'' Setup Pt2-Pt5 perpendicular line (Pt11-Cntr)
pt11.X = ((pt5.X - pt2.X) / 2) + pt2.X
pt11.Y = ((pt5.Y - pt2.Y) / 2) + pt2.Y

'' Get perpendicular slope between Pt1 and Pt5
mr = (pt5.Y - pt1.Y) / (pt5.X - pt1.X)
'' Get perpendicular slope between Pt2 and Pt5
mt = (pt2.Y - pt5.Y) / (pt2.X - pt5.X)
'' Get perpendicular intercept between Pt1 and Pt5
b4 = pt1.Y - (mr * pt1.X)
'' Get perpendicular intercept between Pt2 and Pt5
b5 = pt2.Y - (mt * pt2.X)

If Not mr > 10000 And Not mt > 10000 And Not mr < -10000 And Not mt < -10000 And Not mr = 0 And Not mt = 0 And Not mr = mt Then
    Cntr.X = (((mr * mt) * ((pt2.Y - pt1.Y))) + (mr * (pt5.X + pt2.X)) - (mt * (pt1.X + pt5.X))) / (2 * (mr - mt))

    Cntr.Y = -(1 / mr) * (Cntr.X - ((pt1.X + pt5.X) / 2)) + ((pt1.Y + pt5.Y) / 2)
    '' Calculate radius
    r = Math.Sqrt(((pt5.Y - Cntr.Y) ^ 2) + ((pt5.X - Cntr.X) ^ 2))

    '' Determine which side to extend Chords
    If pt1.X > pt5.X Then
        pt20.X = pt1.X + (r * 2)
    Else
        pt20.X = pt1.X - (r * 2)
    End If
    pt20.Y = (mr * (pt20.X)) + b4

    If pt2.X > pt5.X Then
        pt21.X = pt2.X + (r * 2)
    Else
        pt21.X = pt2.X - (r * 2)
    End If
    pt21.Y = (mt * (pt21.X)) + b5

    'g.DrawLine(Pens.Black, pt1, pt2)
    'g.DrawLine(Pens.Orange, pt4, pt5)
    'g.DrawLine(Pens.Orange, pt3, pt5)
    'g.DrawLine(Pens.Pink, pt10, Cntr)
    'g.DrawLine(Pens.Pink, pt11, Cntr)
    'g.DrawLine(Pens.Red, pt1, pt5)
    'g.DrawLine(Pens.Blue, pt2, pt5)
    'g.DrawLine(Pens.Beige, pt1, pt20)
    'g.DrawLine(Pens.Beige, pt2, pt21)
    Dim path As New Drawing2D.GraphicsPath()
    path.AddPolygon({pt20, pt1, Cntr, pt2, pt21})
    g.ExcludeClip(New Region(path))

    g.DrawEllipse(Pens.Black, CInt(Cntr.X - r), CInt(Cntr.Y - r), CInt(r * 2), CInt(r * 2))
Else
    Debug.WriteLine("mr: " & mr.ToString & vbTab & "mt: " & mt.ToString)
End If

This helped me find the center of the circle based on 3 points on the circumference


text:
Q: Save powerpoint selected slides to desktop or desired location I have below code that save powerpoint to documents folder by default i woul like to save it in desktop or give an option to select folder to save it.
    private void SaveSelectedSlide_Click(object sender, RibbonControlEventArgs e)
    {
      try
        {
            PowerPoint.Application ppApp = Globals.ThisAddIn.Application;
            PowerPoint.SlideRange ppslr = ppApp.ActiveWindow.Selection.SlideRange;
            string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            var temporaryPresentation = Globals.ThisAddIn.Application.Presentations.Add(Microsoft.Office.Core.MsoTriState.msoTrue);
            Microsoft.Office.Interop.PowerPoint.CustomLayout customLayout = ppApp.ActivePresentation.SlideMaster.CustomLayouts[Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutText];

            for (int i = 1; i <= ppslr.Count; i++)
            {
                var sourceSlide = ppslr[i];
                sourceSlide.Copy();

                var design = sourceSlide.Design;
                temporaryPresentation.Slides.Paste();

            }
            temporaryPresentation.SaveAs("Temporary", Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPresentation, Microsoft.Office.Core.MsoTriState.msoTrue);

            temporaryPresentation.Close();

        }
        catch (COMException Ex)
        {
            Debug.WriteLine("Some problem" + Ex.Message + Ex.StackTrace);
            MessageBox.Show("PLease enter text ");
        }

    }

A: The SaveAs method doesn't display the SaveAs dialog. You need to use the FileDialog property of the Application class which returns a FileDialog object that represents a single instance of a file dialog box. For example:
Sub ShowSaveAsDialog()
    Dim dlgSaveAs As FileDialog
    Set dlgSaveAs = Application.FileDialog( _
        Type:=msoFileDialogSaveAs)
    dlgSaveAs.Show
End Sub

You may use any .Net components and class for implementing the required task in PowerPoint. For example, you can use the SaveAs dialog from BCLs. See Powerpoint 2007 Save As Dialog for more information.


text:
Q: ServiceLayer Exception not been catched on controller Testing my application I decided to shutdown the database.
public Object getEntityById(Class<?> clazz, Object _id) throws PersistenceServiceException {
    Object o = null;
    try {
        o = entityManager.find(clazz, _id);
    } catch (Exception e) {
        throw new PersistenceServiceException(e);
    }
    return o;
}

so, any database exception should be passed to the caller.
and in the controller I have
    try {
        template = (Template)persistenceService.getEntityById(Template.class, id);
    } catch (PersistenceServiceException e) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setStatusMessage("INTERNAL SERVER ERROR");
        response.setData(e);
        return  response;
    }

when debugging, I can see the DatabaseException been throw.
but in servlet-context, once I have this...
<beans:bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <beans:property name="defaultErrorView" value="core/error.uncatched" />
</beans:bean>

it keeps treating the above error as unhandled.
How can I catch it on the controller? Why is it happening?
The Exception
ERROR: org.springframework.transaction.interceptor.TransactionInterceptor - **Application exception overridden by commit exception**
com.company.exceptions.PersistenceServiceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.0.v20130619-7d05127): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

A: You should use PersistenceException to catch exception .Because you are using JPA.

A: The true is that the Transactional context is throwing a TransactionSystemException (a RunTimeException), so the wrapped excetion I did is been wrapper again by the TransactionSystemException. This last one need to be added to the catch clause in the controller.
Anyway I not mark it as correct right now. If somebody wants to add something, is welcome.

A: The stacktrace shows these two exceptions:

Internal Exception: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

It means that the database is not reachable. Which is because you have shutdown the database. Here is a discussion about this exception.

ERROR: org.springframework.transaction.interceptor.TransactionInterceptor - Application exception overridden by commit exception

The default configuration of Spring framework's transaction infrastructure marks a transaction for rollback only when the thrown Exception is an unchecked exception. If you have defined the PersistenceServiceException as a checked exception, it will not cause rollback in Spring transaction. You are catching an unchecked exception (in your getEntityById method), converting it to a checked exception and then you are throwing this checked exception.
To solve this you can configure the transaction infrastructure to rollback the transaction for PersistenceServiceException by

Changing the PersistenceServiceException into a runtime exception (PersistenceServiceException extends RuntimeException)

or by annotating your service with

@Transactional(rollbackFor = PersistenceServiceException.class)


text:
Q: How to remove a field and set default value for a ModelForm in Django? I have a ModelForm in my forms.py as follows:
class ChoiceForm(forms.ModelForm):
class Meta:
    model = Choice
    fields = ['choice_text', 'is_choice_correct']
    labels = {
        'choice_text': "",
        'is_choice_correct': ""
    }
    widgets = {
        "choice_text": forms.Textarea(),
        "is_choice_correct": "",
    }

Based on some conditions, I would like the is_correct_field, a boolean field to not display in the form and set default value for the field (because it is required) so that when I write form.save() in my views, there occurs no error.
However, I don't want to hide the form field. To make it more clear, here's what I want to say. I submit the form with only choice_text in my form. The form does not contain the field is_choice_correct, either hidden or displayed. When I save the form with form.save(), I want the is_choice_correct to be True.

A: Why not declare the default value for is_choice_correcton the model itself?
class Choice(models.Model):
    is_choice_correct = models.BooleanField(default=True)

Then exclude the field from the form as Exprator shows.
If you want to include the field on the form only under some conditions, you can edit the form's .fields during __init__.
class ChoiceForm(forms.ModelForm):

    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs) # important, call super() first or the form has no .fields attribute
        if my_condition:
            self.fields['is_choice_correct'] = Choice._meta.get_field('is_choice_correct').formfield()


text:
Q: Prefill form through url I would like to fill the form on the following site thanks to parameters defined in the url, especially the referral ID.
I try http://tumblr.followd.co.nz/signup.php?referral_id=1234 but it is not working for some reason.
It works on the login page of the site, not the signup one. Can anyone help?
Thanks in advance.