text:
Q: Gmail contacts API.3 in php, how to get name and phone from contact? i need some advise on this one, im having trouble figuring out the array that comes from google contacts, im already extracting the email from an example i found online, but now i need to extract the name of the contact and the phone number, i am seeing this information in the array doing a print_r() but dont know how to get it.
This is are my files:
gmail.php (this one prints all the emails, here i need also name and phone)
include_once 'GmailOath.php';

$oauth =new GmailOath($consumer_key, $consumer_secret, $argarray, $debug, $callback);
$getcontact_access=new GmailGetContacts();

$request_token=$oauth->rfc3986_decode($_GET['oauth_token']);
$request_token_secret=$oauth->rfc3986_decode($_SESSION['oauth_token_secret']);
$oauth_verifier= $oauth->rfc3986_decode($_GET['oauth_verifier']);

$contact_access = $getcontact_access->get_access_token($oauth,$request_token, $request_token_secret,$oauth_verifier, false, true, true);

$access_token=$oauth->rfc3986_decode($contact_access['oauth_token']);
$access_token_secret=$oauth->rfc3986_decode($contact_access['oauth_token_secret']);
$contacts= $getcontact_access->GetContacts($oauth, $access_token, $access_token_secret, false, true,$emails_count);

foreach($contacts as $k => $a)
{
    $final = end($contacts[$k]);
    foreach($final as $email)
    {
            echo 'email: ' . $email["address"] .'
';
    }
}

GmailOath.php
    <?php

    class GmailOath {

        public $oauth_consumer_key;
        public $oauth_consumer_secret;
        public $progname;
        public $debug;
        public $callback;

        function __construct($consumer_key, $consumer_secret, $argarray, $debug, $callback) {
            $this->oauth_consumer_key = $consumer_key;
            $this->oauth_consumer_secret = $consumer_secret;
            $this->progname = $argarray;
            $this->debug = $debug; // Set to 1 for verbose debugging output
            $this->callback = $callback;
        }

        ////////////////// global.php open//////////////
        function logit($msg, $preamble=true) {
            //  date_default_timezone_set('America/Los_Angeles');
            $now = date(DateTime::ISO8601, time());
            error_log(($preamble ? "+++${now}:" : '') . $msg);
        }

        function do_get($url, $port=80, $headers=NULL) {
            $retarr = array();  // Return value
            $curl_opts = array(CURLOPT_URL => $url,
                CURLOPT_PORT => $port,
                CURLOPT_POST => false,
                CURLOPT_SSL_VERIFYHOST => false,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_RETURNTRANSFER => true);

            if ($headers) {
                $curl_opts[CURLOPT_HTTPHEADER] = $headers;
            }

            $response = $this->do_curl($curl_opts);

            if (!empty($response)) {
                $retarr = $response;
            }

            return $retarr;
        }

        function do_post($url, $postbody, $port=80, $headers=NULL) {
            $retarr = array();  // Return value

            $curl_opts = array(CURLOPT_URL => $url,
                CURLOPT_PORT => $port,
                CURLOPT_POST => true,
                CURLOPT_SSL_VERIFYHOST => false,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_POSTFIELDS => $postbody,
                CURLOPT_RETURNTRANSFER => true);

            if ($headers) {
                $curl_opts[CURLOPT_HTTPHEADER] = $headers;
            }

            $response = do_curl($curl_opts);

            if (!empty($response)) {
                $retarr = $response;
            }

            return $retarr;
        }

        function do_curl($curl_opts) {

            $retarr = array();  // Return value

            if (!$curl_opts) {
                if ($this->debug) {
                    $this->logit("do_curl:ERR:curl_opts is empty");
                }
                return $retarr;
            }

            // Open curl session

            $ch = curl_init();

            if (!$ch) {
                if ($this->debug) {
                    $this->logit("do_curl:ERR:curl_init failed");
                }
                return $retarr;
            }

            // Set curl options that were passed in
            curl_setopt_array($ch, $curl_opts);

            // Ensure that we receive full header
            curl_setopt($ch, CURLOPT_HEADER, true);

            if ($this->debug) {
                curl_setopt($ch, CURLINFO_HEADER_OUT, true);
                curl_setopt($ch, CURLOPT_VERBOSE, true);
            }

            // Send the request and get the response
            ob_start();
            $response = curl_exec($ch);
            $curl_spew = ob_get_contents();
            ob_end_clean();
            if ($this->debug && $curl_spew) {
                $this->logit("do_curl:INFO:curl_spew begin");
                $this->logit($curl_spew, false);
                $this->logit("do_curl:INFO:curl_spew end");
            }

            // Check for errors
            if (curl_errno($ch)) {
                $errno = curl_errno($ch);
                $errmsg = curl_error($ch);
                if ($this->debug) {
                    $this->logit("do_curl:ERR:$errno:$errmsg");
                }
                curl_close($ch);
                unset($ch);
                return $retarr;
            }

            if ($this->debug) {
                $this->logit("do_curl:DBG:header sent begin");
                $header_sent = curl_getinfo($ch, CURLINFO_HEADER_OUT);
                $this->logit($header_sent, false);
                $this->logit("do_curl:DBG:header sent end");
            }

            // Get information about the transfer
            $info = curl_getinfo($ch);

            // Parse out header and body
            $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
            $header = substr($response, 0, $header_size);
            $body = substr($response, $header_size);

            // Close curl session
            curl_close($ch);
            unset($ch);

            if ($this->debug) {
                $this->logit("do_curl:DBG:response received begin");
                if (!empty($response)) {
                    $this->logit($response, false);
                }
                $this->logit("do_curl:DBG:response received end");
            }

            // Set return value
            array_push($retarr, $info, $header, $body);

            return $retarr;
        }

        function json_pretty_print($json, $html_output=false) {
            $spacer = '  ';
            $level = 1;
            $indent = 0; // current indentation level
            $pretty_json = '';
            $in_string = false;

            $len = strlen($json);

            for ($c = 0; $c < $len; $c++) {
                $char = $json[$c];
                switch ($char) {
                    case '{':
                    case '[':
                        if (!$in_string) {
                            $indent += $level;
                            $pretty_json .= $char . "\n" . str_repeat($spacer, $indent);
                        } else {
                            $pretty_json .= $char;
                        }
                        break;
                    case '}':
                    case ']':
                        if (!$in_string) {
                            $indent -= $level;
                            $pretty_json .= "\n" . str_repeat($spacer, $indent) . $char;
                        } else {
                            $pretty_json .= $char;
                        }
                        break;
                    case ',':
                        if (!$in_string) {
                            $pretty_json .= ",\n" . str_repeat($spacer, $indent);
                        } else {
                            $pretty_json .= $char;
                        }
                        break;
                    case ':':
                        if (!$in_string) {
                            $pretty_json .= ": ";
                        } else {
                            $pretty_json .= $char;
                        }
                        break;
                    case '"':
                        if ($c > 0 && $json[$c - 1] != '\\') {
                            $in_string = !$in_string;
                        }
                    default:
                        $pretty_json .= $char;
                        break;
                }
            }

            return ($html_output) ?
                    '
' . htmlentities($pretty_json) . '
' :
                    $pretty_json . "\n";
        }

        function oauth_http_build_query($params, $excludeOauthParams=false) {

            $query_string = '';
            if (!empty($params)) {

                // rfc3986 encode both keys and values
                $keys = $this->rfc3986_encode(array_keys($params));
                $values = $this->rfc3986_encode(array_values($params));
                $params = array_combine($keys, $values);

                uksort($params, 'strcmp');

                $kvpairs = array();
                foreach ($params as $k => $v) {
                    if ($excludeOauthParams && substr($k, 0, 5) == 'oauth') {
                        continue;
                    }
                    if (is_array($v)) {
                        // If two or more parameters share the same name,
                        // they are sorted by their value. OAuth Spec: 9.1.1 (1)
                        natsort($v);
                        foreach ($v as $value_for_same_key) {
                            array_push($kvpairs, ($k . '=' . $value_for_same_key));
                        }
                    } else {
                        // For each parameter, the name is separated from the corresponding
                        // value by an '=' character (ASCII code 61). OAuth Spec: 9.1.1 (2)
                        array_push($kvpairs, ($k . '=' . $v));
                    }
                }

                // Each name-value pair is separated by an '&' character, ASCII code 38.
                // OAuth Spec: 9.1.1 (2)
                $query_string = implode('&', $kvpairs);
            }
            return $query_string;
        }

        function oauth_parse_str($query_string) {
            $query_array = array();

            if (isset($query_string)) {

                // Separate single string into an array of "key=value" strings
                $kvpairs = explode('&', $query_string);

                // Separate each "key=value" string into an array[key] = value
                foreach ($kvpairs as $pair) {
                    list($k, $v) = explode('=', $pair, 2);

                    // Handle the case where multiple values map to the same key
                    // by pulling those values into an array themselves
                    if (isset($query_array[$k])) {
                        // If the existing value is a scalar, turn it into an array
                        if (is_scalar($query_array[$k])) {
                            $query_array[$k] = array($query_array[$k]);
                        }
                        array_push($query_array[$k], $v);
                    } else {
                        $query_array[$k] = $v;
                    }
                }
            }

            return $query_array;
        }

        function build_oauth_header($params, $realm='') {
            $header = 'Authorization: OAuth';
            foreach ($params as $k => $v) {
                if (substr($k, 0, 5) == 'oauth') {
                    $header .= ',' . $this->rfc3986_encode($k) . '="' . $this->rfc3986_encode($v) . '"';
                }
            }
            return $header;
        }

        function oauth_compute_plaintext_sig($consumer_secret, $token_secret) {
            return ($consumer_secret . '&' . $token_secret);
        }

        function oauth_compute_hmac_sig($http_method, $url, $params, $consumer_secret, $token_secret) {

            $base_string = $this->signature_base_string($http_method, $url, $params);
            $signature_key = $this->rfc3986_encode($consumer_secret) . '&' . $this->rfc3986_encode($token_secret);
            $sig = base64_encode(hash_hmac('sha1', $base_string, $signature_key, true));
            if ($this->debug) {
                logit("oauth_compute_hmac_sig:DBG:sig:$sig");
            }
            return $sig;
        }

        /**
         * Make the URL conform to the format scheme://host/path
         * @param string $url
         * @return string the url in the form of scheme://host/path
         */
        function normalize_url($url) {
            $parts = parse_url($url);

            $scheme = $parts['scheme'];
            $host = $parts['host'];
            $port = $parts['port'];
            $path = $parts['path'];

            if (!$port) {
                $port = ($scheme == 'https') ? '443' : '80';
            }
            if (($scheme == 'https' && $port != '443')
                    || ($scheme == 'http' && $port != '80')) {
                $host = "$host:$port";
            }

            return "$scheme://$host$path";
        }

        /**
         * Returns the normalized signature base string of this request
         * @param string $http_method
         * @param string $url
         * @param array $params
         * The base string is defined as the method, the url and the
         * parameters (normalized), each urlencoded and the concated with &.
         * @see http://oauth.net/core/1.0/#rfc.section.A.5.1
         */
        function signature_base_string($http_method, $url, $params) {
            // Decompose and pull query params out of the url
            $query_str = parse_url($url, PHP_URL_QUERY);
            if ($query_str) {
                $parsed_query = $this->oauth_parse_str($query_str);
                // merge params from the url with params array from caller
                $params = array_merge($params, $parsed_query);
            }

            // Remove oauth_signature from params array if present
            if (isset($params['oauth_signature'])) {
                unset($params['oauth_signature']);
            }

            // Create the signature base string. Yes, the $params are double encoded.

            $base_string = $this->rfc3986_encode(strtoupper($http_method)) . '&' .
                    $this->rfc3986_encode($this->normalize_url($url)) . '&' .
                    $this->rfc3986_encode($this->oauth_http_build_query($params));

            $this->logit("signature_base_string:INFO:normalized_base_string:$base_string");

            return $base_string;
        }

        /**
         * Encode input per RFC 3986
         * @param string|array $raw_input
         * @return string|array properly rfc3986 encoded raw_input
         * If an array is passed in, rfc3896 encode all elements of the array.
         * @link http://oauth.net/core/1.0/#encoding_parameters
         */
        function rfc3986_encode($raw_input){

            if (is_array($raw_input)) {
                //return array_map($this->rfc3986_encode, $raw_input);
                return array_map(array($this, 'rfc3986_encode'), $raw_input);

                // return $this->rfc3986_encode($raw_input);
            } else if (is_scalar($raw_input)) {
                return str_replace('%7E', '~', rawurlencode($raw_input));
            } else {
                return '';
            }
        }

        function rfc3986_decode($raw_input) {
            return rawurldecode($raw_input);
        }

    }

    class GmailGetContacts {

        function get_request_token($oauth, $usePost=false, $useHmacSha1Sig=true, $passOAuthInHeader=false) {
            $retarr = array();  // return value
            $response = array();

            $url = 'https://www.google.com/accounts/OAuthGetRequestToken';
            $params['oauth_version'] = '1.0';
            $params['oauth_nonce'] = mt_rand();
            $params['oauth_timestamp'] = time();
            $params['oauth_consumer_key'] = $oauth->oauth_consumer_key;
            $params['oauth_callback'] = $oauth->callback;
            $params['scope'] = 'https://www.google.com/m8/feeds';

            // compute signature and add it to the params list
            if ($useHmacSha1Sig) {

                $params['oauth_signature_method'] = 'HMAC-SHA1';
                $params['oauth_signature'] =
                        $oauth->oauth_compute_hmac_sig($usePost ? 'POST' : 'GET', $url, $params,
                                $oauth->oauth_consumer_secret, null);
            } else {
                echo "signature mathod not support";
            }

            // Pass OAuth credentials in a separate header or in the query string
            if ($passOAuthInHeader) {

                $query_parameter_string = $oauth->oauth_http_build_query($params, FALSE);

                $header = $oauth->build_oauth_header($params);

                $headers[] = $header;
            } else {
                $query_parameter_string = $oauth->oauth_http_build_query($params);
            }

            // POST or GET the request
            if ($usePost) {
                $request_url = $url;
                $oauth->logit("getreqtok:INFO:request_url:$request_url");
                $oauth->logit("getreqtok:INFO:post_body:$query_parameter_string");
                $headers[] = 'Content-Type: application/x-www-form-urlencoded';
                $response = do_post($request_url, $query_parameter_string, 443, $headers);
            } else {
                $request_url = $url . ($query_parameter_string ?
                                ('?' . $query_parameter_string) : '' );

                $oauth->logit("getreqtok:INFO:request_url:$request_url");

                $response = $oauth->do_get($request_url, 443, $headers);
            }

            // extract successful response
            if (!empty($response)) {
                list($info, $header, $body) = $response;
                $body_parsed = $oauth->oauth_parse_str($body);
                if (!empty($body_parsed)) {
                    $oauth->logit("getreqtok:INFO:response_body_parsed:");
                   //print_r($body_parsed);
                }
                $retarr = $response;
                $retarr[] = $body_parsed;
            }

            return $body_parsed;
        }

        function get_access_token($oauth, $request_token, $request_token_secret, $oauth_verifier, $usePost=false, $useHmacSha1Sig=true, $passOAuthInHeader=true) {
            $retarr = array();  // return value
            $response = array();

            $url = 'https://www.google.com/accounts/OAuthGetAccessToken';
            $params['oauth_version'] = '1.0';
            $params['oauth_nonce'] = mt_rand();
            $params['oauth_timestamp'] = time();
            $params['oauth_consumer_key'] = $oauth->oauth_consumer_key;
            $params['oauth_token'] = $request_token;
            $params['oauth_verifier'] = $oauth_verifier;

            // compute signature and add it to the params list
            if ($useHmacSha1Sig){
                $params['oauth_signature_method'] = 'HMAC-SHA1';
                $params['oauth_signature'] =
                        $oauth->oauth_compute_hmac_sig($usePost ? 'POST' : 'GET', $url, $params,
                                $oauth->oauth_consumer_secret, $request_token_secret);
            } else {
                echo "signature mathod not support";
            }
    //
            if ($passOAuthInHeader) {
                $query_parameter_string = $oauth->oauth_http_build_query($params, false);
                $header = $oauth->build_oauth_header($params);
                $headers[] = $header;
            } else {
                $query_parameter_string = $oauth->oauth_http_build_query($params);
            }

            if ($usePost){
                $request_url = $url;
                logit("getacctok:INFO:request_url:$request_url");
                logit("getacctok:INFO:post_body:$query_parameter_string");
                $headers[] = 'Content-Type: application/x-www-form-urlencoded';
                $response = $oauth->do_post($request_url, $query_parameter_string, 443, $headers);
            } else {
                $request_url = $url . ($query_parameter_string ?
                                ('?' . $query_parameter_string) : '' );

                $oauth->logit("getacctok:INFO:request_url:$request_url");
                $response = $oauth->do_get($request_url, 443, $headers);
            }

            if (!empty($response)) {
                list($info, $header, $body) = $response;
                $body_parsed = $oauth->oauth_parse_str($body);
                if (!empty($body_parsed)) {
                    $oauth->logit("getacctok:INFO:response_body_parsed:");
                    //print_r($body_parsed);

                }
                $retarr = $response;
                $retarr[] = $body_parsed;
            }
            return $body_parsed;
        }

        function GetContacts($oauth, $access_token, $access_token_secret, $usePost=false, $passOAuthInHeader=true,$emails_count) {
            $retarr = array();  // return value
            $response = array();

            $url = "https://www.google.com/m8/feeds/contacts/default/full";
            $params['alt'] = 'json';
            $params['max-results'] = $emails_count;
            $params['oauth_version'] = '1.0';
            $params['oauth_nonce'] = mt_rand();
            $params['oauth_timestamp'] = time();
            $params['oauth_consumer_key'] = $oauth->oauth_consumer_key;
            $params['oauth_token'] = $access_token;

            // compute hmac-sha1 signature and add it to the params list
            $params['oauth_signature_method'] = 'HMAC-SHA1';
            $params['oauth_signature'] =
                    $oauth->oauth_compute_hmac_sig($usePost ? 'POST' : 'GET', $url, $params,
                            $oauth->oauth_consumer_secret, $access_token_secret);

            // Pass OAuth credentials in a separate header or in the query string
            if ($passOAuthInHeader){
                $query_parameter_string = $oauth->oauth_http_build_query($params, false);

                $header = $oauth->build_oauth_header($params);

                $headers[] = $header;
            } else {
                $query_parameter_string = $oauth->oauth_http_build_query($params);
            }

            // POST or GET the request
            if ($usePost){
                $request_url = $url;
                $oauth->logit("callcontact:INFO:request_url:$request_url");
                $oauth->logit("callcontact:INFO:post_body:$query_parameter_string");
                $headers[] = 'Content-Type: application/x-www-form-urlencoded';
                $response = $oauth->do_post($request_url, $query_parameter_string, 80, $headers);

            } else {
                $request_url = $url . ($query_parameter_string ?
                                ('?' . $query_parameter_string) : '' );
                $oauth->logit("callcontact:INFO:request_url:$request_url");
                $response = $oauth->do_get($request_url, 443, $headers);
            }

            if (!empty($response)) {
                list($info, $header, $body) = $response;
                if ($body) {

                    $oauth->logit("callcontact:INFO:response:");
                    $contact = json_decode($oauth->json_pretty_print($body), true);

                   //echo $contact['feed']['entry'][0]['gd$email'][0]['address'];
                   return $contact['feed']['entry'];

                }
                $retarr = $response;
            }

            return $retarr;
        }

    }

    ?>

Can you guys help me on this one please. Thanks in advance!

A: Not sure if this can help you as you say you have already used print_r (are you using with braces?), but to display the contents of an array in PHP, I have always used this with success.
It displays the integer ref of the array plus the data in each field.
<?php
  echo "
";                //print array to console
    {print_r($variable_name);}
  echo "
";
?>

Alternately, have you checked the information here: https://developers.google.com/google-apps/contacts/v3/#retrieving_contacts_using_query_parameters
Or try the Context.IO API - there's a call specifically for pulling contacts: http://context.io/docs/2.0/accounts/contacts
Hoping any of these might help you.

A: For your case for first Phone andress and Note Field .
add where you loop the contacts in gmail.php
foreach($contacts as $k => $a)
{
  $phone1 = end($a['gd$phoneNumber'][0]);
  $note = end($a['content']);
  $adress = end($a['gd$postalAddress'][0]);


text:
Q: TextMorph default font size I'm trying to have an empty TextMorph with a default font size of 12 points, where the original default is 9pts. If I bring up the halo and change the font size to 12pts, the empty TextMorph will still default to 9pts when text is entered into it. I can sort of get around this by putting a space in the TextMorph, then changing the font via the halo to be 12pts. However, this seems rather clunky, and as such was wondering if there might be another way to accomplish this?
thanks.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Run Teradata SQL Assistant via a batch script I am trying to Run a teradata SQL script via a batch script and export the details.
I have managed to execute the whole thing in DOS which is great
Im just not sure how to package it up
Below is my very average attempt. COuld anyone point me in the right direction?
The SQL is SELECT DATE
@title Optional Title
@echo off

C:\'Program Files (x86)'\Teradata\Client\15.00\Teradata SQL Assistant\
Sqla -c DB_NAME -f "C:\Temp\test.sql" -e "c:\Temp\test_output.log"

Thanks

A: I found the answer on another different question on Stack Overflow
How do I execute cmd commands through a batch file?
This basically does what i need or at least points me in the correct direction
Thank you for your time


text:
Q: How can I check which model of Neo Geo MVS do I have? I am trying to buy a Neo Geo MVS PCB but the seller doesn't know if his board model is an MV-1, MV-1A, MV-1F and so on. Where should I tell him to look for this information?

A: The information along with pictures of each board are available on the Arcade Otaku wiki on the Beginners Guide to SNK Neo Geo MVS page. The model numbers are built up as follows;
MV - 1  F
     |  `-> Board revision number
      `-> Number of slots on the board

Here are pictures of each of the boards:
MV-1

MV-1A and MV-1AX

You can tell the MV-1A and MV-1AX apart by the fact that the MV-1A has a socketed BIOS chip and the MV-1AX does not (it's soldered to the board).
MV-1B

MV-1C

MV-1F

MV-1FZ

MV-2F

MV-4F

MV-2FS

MV-6F

Additionally, the MV-1A and MV-1FZ have a socketed BIOS, so the BIOS chip can be removed easily from the board. The MV1 and MV1F also have stereo sound by default (although it is possible to mod this onto other boards) so the connectors for sound will cater for this.


text:
Q: java не видит директорию WEB-INF web.xml в директории IDEAProject/demo/src/main/webapp/WEB-INF/
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-config.xml</param-value>
        </init-param>
    </servlet>

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

в этой строке
/WEB-INF/spring-config.xml
пишет что не видит эту директорию (WEB-INF) и предлагает создать. создает по пути
IDEAProject/demo/WEB-INF/
не знаю что делать
после закрытия проекта и заново открытия в web.xml в строке
 <servlet-name>dispatcher</servlet-name>

сервлет должен быть замапен
а в строке
<servlet-mapping>
        <servlet-name>dispatcher</servlet-name>

не могу резолвить сервлет dispatcher

A: В Idea по дефолту (без перенастройки артефактов сборки) WEB-INF ожидается в корне, то есть в вашем случае на одном уровне с src.
Просто перенести в IDEAProject/demo/WEB-INF/ будет лучшим решением. Важно еще отметить что WEB-INF это не пакет, а именно директория.
Вы конечно можете зайти в File -> Project Structure -> Artifacts и пошаманить там, но это уже по ситуации.


text:
Q: Calculating image natural width on initial page load with ember-render-modifiers in Ember Glimmer components Prior to using Ember's new Glimmer components, I used the didInsertElement lifecycle hook to calculate the natural width of an image element. I am passing in a target width so I can resize the image in the browser.
didInsertElement() {
    this._super(...arguments);
    if (this.targetWidth && this.targetWidth < this.element.naturalWidth) {
        this.targetHeight = Math.round(this.targetWidth / this.element.naturalWidth * this.element.naturalHeight);
        set(this, 'width', this.targetWidth);
        set(this, 'height', this.targetHeight);
    }
    else {
        set(this, 'width', this.naturalWidth);
        set(this, 'height', this.naturalHeight);
    }

With Glimmer components, and using @ember/render-modifiers, the src being passed in by the parent:
<img {{did-insert this.calculateDimensions}} src={{@src}} width={{this.width}} height={{this.height}}>

In the component JS file
@action
calculateDimensions(element) {
    if (this.args.targetWidth && this.args.targetWidth < element.naturalWidth) {
        this.height = Math.round(this.args.targetWidth / element.naturalWidth * element.naturalHeight);
        this.width = this.args.targetWidth;
    }
    else {
        this.width = element.naturalWidth;
        this.height = element.naturalHeight;
    }
    element.setAttribute("width", this.width);
    element.setAttribute("height", this.height);
}

This all works fine if you reload the index/home page. However, when you first arrive at the site, the image is not rendered, because the value for element.naturalWidth is zero. The element is present, and if it's logged to the console I can see the values for natural width and height. Is the ember-render-modifier {{did-insert}} not a full replacement for didInsertElement?
Any help much appreciated.

A: I am not sure if this the "Ember" way to solve this but I've used the load event:
<img {{on "load" this.calculateDimensions}} src={{@src}} width={{this.width}} height={{this.height}}>

It solves the problem but I'm still not sure why the ember-modifer {{did-insert}} does not achieve the same thing - I had assumed the element was inserted into the DOM, and therefore you would be able to obtain its naturalWidth and height?


text:
Q: increase the stored procedure perfomance Hi
I have the database with huge data. there are several master-detail relationships within it. so i just wanted to build the Views / stored procedure so that data fetching get much faster. I know I can use Index. but i saw it is a limitation in sql server express version. where as i am using express version. so how to perform this in express version. please guide me .

A: Creating a stored procedure won't speed up query execution.
Making sure that your foreign keys are indexed is the first step.
The definite answer to the question of query performance will give you a look at query execution plan. Make sure you don't have any Table Scans / Table Seeks.


text:
Q: Is it possible to mount an encrypted disk image so that only current user is able to access it? I use VeraCrypt to mount an encrypted volume. When the volume is mounted, other admin users are not able to access it:
admin1 %
admin1 % su - admin2
admin2 % ls /Users/admin1/veracrypt_mounted
admin2 % ls: /Users/admin1/veracrypt_mounted: Permission denied

I'm considering switching to an encrypted disk image (created via Disk Utility and using the sparse bundle format), to avoid the dependency on VeraCrypt and macFUSE. Filesystem portability is not needed.
However, during my tests, when I mount the image its contents are also accessible to other root/admin users.
Is it possible to mount the disk image so that only my user is able to access it, and no other root/admin user?

*

*Why I need this: this is a shared laptop with many admin users.

*System: Monterrey 12.13.1 on M1


text:
Q: Packages and Notebooks as a Databin The new Data Drop product sounds interesting. Can I use Databin to share Packages and Notebooks?
If yes. How? Something like:
bin = CreateDatabin[]
DatabinAdd[bin, <|"myPack" -> "???"|>]

And then, how can I load a package stored in a Databin?
cross related Wolfram Community question

A: An ancient question - I just started digging my nose into Databins.  Here's one way to store a package in databins.  the key is to drop them as inactivated expressions
Remove[Collatz]
Collatz[5]
bin = CreateDatabin[];
DatabinAdd[bin,
 Import["ExampleData/Collatz.m", "InactivatedExpressions"]];
Collatz[5]
(* Collatz should remain unevaluated in both calls above *)

Now, to pull the package from the datadrop:
First@bin["Values"] // Activate
Collatz[5]
(* A string with some package information is generated here *)
(* {5, 16, 4, 2, 1} *)

I played briefly with data semantics since Package is a valid $InterpreterType; however, I did not see any immediate benefit to my dummy code outside of requiring more text to parse the Association.


text:
Q: How can I match this patern over multiple lines Given the below text, I want to return an array of all the the lines of text with the following format 1.SSRDOCSYYHK1/////25AUG52/M//YOUNG/LANDON/KWAN- 1.1 and this should macth a line even if it is actually broken across multiple lines
RegExp:
str.match(/\d{1,2}.SSRDOCSYYHK1\/\/\/\/\/.+?\d\.\d/g)
Full Text:
var str= "A-CA25592185
A-ERNONREF/CHGFEEPLUSFAREDIF/CXL BY FLT TIME NOVALUE
TKG FAX-NOT PRICED  FARE TYPE EX
FOP- 1.CA
G- 1.SSRDOCSWSHK1/////25MAY55/M//YOUNG/LANDON/KWAN -  1.
1
)>MD
    2.SSRPSPTYYHK1///25AUG52/M-  1.1
    3.SSRDOCSWSHK1/////25AUG52/F//YOUNG/LILY/LIMKUO -  2.1
    4.SSRPSPTYYHK1///25AUG52/F-  2.1
    5.SSRDOCSWSHK1/////25AUG52/F//YOUNG/ANDREA/LAUREN -  3.1
    6.SSRPSPTYYHK1///25AUG52/F-  3.1
    7.SSRDOCSWSHK1/////17MAR93/M//YOUNG/ETHAN/WESLEY -  4.1
    8.SSRPSPTYYHK1///25AUG52/M-  4.1
    9.SSRDOCSWSHK1/////23NOV96/M//YOUNG/WINSTON/JEREMY -  5.1
   10.SSRPSPTYYHK1///25AUG52/M-  5.1
   11.SSRDOCSYYHK1/////25MAY55/M//YOUNG/LANDON/KWAN -  1.
1
   12.SSRDOCSYYHK1/////04MAR59/F//YOUNG/LILY/LIMKUO -  2.1
   13.SSRDOCSYYHK1/////25AUG52/F//YOUNG/ANDREA/LAUREN -  3.1
)>MD
    7.SSRDOCSWSHK1/////25AUG52/M//YOUNG/ETHAN/WESLEY -  4.1
    8.SSRPSPTYYHK1///25AUG52/M-  4.1
    9.SSRDOCSWSHK1/////25AUG52/M//YOUNG/WINSTON/JEREMY -  5.1
   10.SSRPSPTYYHK1///25AUG52/M-  5.1
   11.SSRDOCSYYHK1/////25MAY55/M//YOUNG/LANDON/KWAN -  1.
1
   12.SSRDOCSYYHK1/////25AUG52/F//YOUNG/LILY/LIMKUO -  2.1
   13.SSRDOCSYYHK1/////25AUG52/F//YOUNG/ANDREA/LAUREN -  3.1
   14.SSRDOCSYYHK1/////25AUG52/M//YOUNG/ETHAN/WESLEY -  4.1
   15.SSRDOCSYYHK1/////25AUG52/M//YOUNG/WINSTON/JEREMY -  5.1
**** ITEMS SUPPRESSED ****/DR"

I expect an array with all the matches but the two instances of line 11 are not matched due to the line break which  can occur in any of the below way and will not currently be matched:
var str="1.SSRDOCSYYHK1/////25AUG52/M//
YOUNG/LANDON/KWAN- 1.1"

var str="1.SSRDOCSYYHK1/////25AUG52/M//YOUNG/LANDON/KWAN- 1.
1"

var str="1.SSRDOCSYYHK1/////25AUG52/M//YOUNG/LANDON/KWAN- 1
.1"

var str="1.SSRDOCSYYHK1/////25AUG52/M//YOUNG/LANDON/KWAN-
1.1"

var str="1.SSRDOCSYYHK1/////25AUG52/M//YOUNG/LANDON/KWAN
- 1.1"

How change I tell this RegExp to still match in all of the above cases?
I did try str.match(/\d{1,2}.SSRDOCSYYHK1\/\/\/\/\/.+?\d\.\d/m) with no luck
Heres the array that I do get:

anubhava's answer below returns the following array, note that slots 0 and 2 actually hold two lines that were captured as a single instance. This always happens when a line breaks like this and is followed by another matching line if I use his example.

A: If it can be broken anywhere, not only in the DOT matching, the \s trick won't work.
I don't think there's a way to ignore line breaks in javascript regex (or any other engine, actually).
Your best option would be to remove all line breaks before matching, like so:
str = str.replace(/(\r\n|\n|\r)/gm,"");

And then you .match

A: Ok. below regular work for 1.SSRDOCSYYHK1/////25AUG52/M//YOUNG/LANDON/KWAN- 1.1
[0-1]\.[A-Z]+[0-1]\/\/\/\/\/[0-9]+[A-Z]+[0-9]+\/[A-Z]\/\/[A-Z]+\/[A-Z]+\/[A-Z]+\-\s[0-1]\.[0-1]

And it work for :
1.SSRDOCSYYHK1/////25AUG52/M//YOUNG/LANDON/KWAN- 1.
1

[0-1]\.[A-Z]+[0-1]\/\/\/\/\/[0-9]+[A-Z]+[0-9]+\/[A-Z]\/\/[A-Z]+\/[A-Z]+\/[A-Z]+\-\s[0-1]\.\n[0-1]

And it work for :
1.SSRDOCSYYHK1/////25AUG52/M//YOUNG/LANDON/KWAN- 1
.1

[0-1]\.[A-Z]+[0-1]\/\/\/\/\/[0-9]+[A-Z]+[0-9]+\/[A-Z]\/\/[A-Z]+\/[A-Z]+\/[A-Z]+\-\s[0-1]\n\.[0-1]

And it work for :
1.SSRDOCSYYHK1/////25AUG52/M//YOUNG/LANDON/KWAN-
1.1

[0-1]\.[A-Z]+[0-1]\/\/\/\/\/[0-9]+[A-Z]+[0-9]+\/[A-Z]\/\/[A-Z]+\/[A-Z]+\/[A-Z]+\-\n[0-1]\.[0-1]

And it work for :
1.SSRDOCSYYHK1/////25AUG52/M//YOUNG/LANDON/KWAN
- 1.1
[0-1]\.[A-Z]+[0-1]\/\/\/\/\/[0-9]+[A-Z]+[0-9]+\/[A-Z]\/\/[A-Z]+\/[A-Z]+\/[A-Z]+\n\-\s[0-1]\.[0-1]

now you should define nested if and else .....(Conditional statements)
good look.

A: DOT in Javascript doesn't match new lines and unfortunately there is no DOTALL switch in JS regex engine.
However as a workaround you can use [\s\S] for DOT and match regex across new lines as well.
Following regex should work for you:
var arr = str.match(/\d{1,2}\.SSRDOCSYYHK1\/{3,5}[\s\S]+?\d\.\d/g);

Live Demo: http://ideone.com/QIYCMA


text:
Q: Android Google Plus SDK: sign in window not displaying When a user never logged in Google + with my app or did a revoke and want to login again, the following window is displayed once he clicked on the login button:

My problem is the following:

*

*if I copy paste the activity SigninActivity of the Google Sample project in my project, everything works well : the window is displayed when I click on the connect button

*if I copy paste the Google code in my main activity (I think I forgot nothing and did it well) in order to have the connect button and connection process directly in my activity, this window is no more displayed...
To be accurate, as I have 2 Gmail accounts on my phone, what happens is:

*

*execution of the command  mConnectionResult.startResolutionForResult(this,
REQUEST_CODE_SIGN_IN);

*a window asks with which Gmail account I want to connect

*I choose a Gmail account

and...here is the moment when I should see the Google Plus connection window but I don't !
Any idea ?
Thanks !!

A: The way to access that particular screen are:
1) Never logged in (as you mentioned)
2) Revoke and then login (as you mentioned)
and
3) getSettingsIntent()  getSettingsIntent() at Google Developer
The difference between 3) and the other two is that the user is given an overview of current settings which can be changed for your application, and is not show the same exact screen for initial login.  (They are shown "Sign out" and "Sharing settings" options from which they  can change the different visibilities/information access)
public void sendTestIntent() {
        Intent i = mHelper.getGamesClient().getSettingsIntent();
        startActivityForResult(i, RC_SETTINGS);
    }


text:
Q: Linq to SQL Cache Dependency I'd love to hear people's views on the pros and cons of mixing SQL Cache Dependency with Linq to SQL, as described in this article:
http://code.msdn.microsoft.com/linqtosqlcache
This works for me, but I'm interested to know if anyone has any alternatives?
Cheers,
Tim

A: I was just about to ask same question. No comments still added on topic which surprises me, how do people cache with linqtosql anyway?
Also I've tried example in same post http://code.msdn.microsoft.com/linqtosqlcache
but have problem with usign that code on all tables in my database.
Some tables work as expected but others always get cache key removed. What/where should I be looking at for this??

A: According to my experience, Linq to SQL already does some sort of an optimistic cache. We had some problems with refreshes and stale data when using Linq to SQL and had to force flush before proceeding. This article might help: http://weblogs.asp.net/scottgu/archive/2007/08/27/linq-to-sql-part-8-executing-custom-sql-expressions.aspx I also know that it can also use ASP.NET Cache so searching using both these keywords might help.


text:
Q: Non fixed number of substitutions with a single regex? I am trying to create a regular expression to match a c function with any number of parameters and do a substitution for each. Is it possible?
An example:
I would like the  regular expression to match
void functionName(int a);

and convert it to type: int, paranName: a
I would like the regular expression to match also:
void functionName(int a, int b)

and convert it to type: int, paramName: a,  type: int, paramName: b
I know how to do substitutions, etc... but don't know it it is possible to do them in a non fixed way.

A: Using the case-insensitive and . does not match newlines:
Find: (?:[a-z]+(?: [a-z]+)+\()?([a-z]+) ([a-z]+)(?:\);?)?
Replace: Type: \1, paramName: \2
I used Notepad++, but I think it would work in C# too.


text:
Q: EF Core 3.1 with composite primary key navigation property My Tables
CREATE SEQUENCE SeqA START WITH 1 INCREMENT BY 1;
CREATE TABLE TblA (
    CompanyID BIGINT NOT NULL,
    ID BIGINT DEFAULT (NEXT VALUE FOR SeqA),
    ..
    PRIMARY KEY (CompanyID, ID));

And
CREATE TABLE TblB (
    MyID BIGINT PRIMARY KEY IDENTITY(1, 1),
    ..
    CompanyID BIGINT NOT NULL, -- These are foreign key references to TblA
    ID BIGINT NOT NULL
);

Question 1: How can I setup foreign key to reference TblA from TblB?
Question 2: When using EF Core 3.1, how can I setup navigation property for CompanyID and ID in TblB to references TblA?


text:
Q: Magento 2 ACL is not working on custom controller I have tried to use ACL on custom admin controller but it is not working.
My etc/acl.xml file is this:
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">
    <acl>
        <resources>
            <resource id="Magento_Backend::admin">
                <resource id="Vendor_Module::index_index" sortOrder="10" title="Tool Title"/>
            </resource>
        </resources>
    </acl>
</config>

Controller location:

Vendor/Module/Controller/Adminhtml/Index/Index.php

I have also added this function in my controller
protected function _isAllowed()
{
    return $this->_authorization->isAllowed('Vendor_Module::index_index');
}

After this, option appearing in admin role, but after assigning to role, tool is not appearing on that specific role user.
Any help would be highly appreciated.

A: You may be missing an entry in the authorization_rule table. Find your group role ID in the authorization_role table and check to see if it has a paired entry with your resource ID (in your case, Venodr_Module::index_index) in the authorization_rule table. If not, try saving the group role again or manually add entry into the table.


text:
Q: jQuery this selector not available to animate() method properies Can someone explain to me why the "this" selector is not available to the animate() methods properties.
See the 1st example at http://jsfiddle.net/qZVv4/, there are no errors produced it just ignores it.
 $('#test1 .bar[data-percentage]').animate({
     width: $(this).attr('data-percentage'),
     easing: 'easeOutBounce'
 }, 1000, function () {
     $(this).text($(this).attr('data-percentage'));
 });

A: Because this isn't referring to your element. You're still in the same scope, so this doesn't change. You'd have to do something like this instead:
// You need the easing plugin
// https://github.com/danro/jquery-easing

$('#test1 .bar[data-percentage]').each(function() {
    var $this = $(this);

    $this.animate({
        width: $this.data('percentage')
    }, {
        duration: 1000,
        //easing: 'easeOutBounce',
        step: function(value) {
            $(this).text(value + '%');
        }
    });
});

Demo: http://jsfiddle.net/qZVv4/4/

A: Javascript only has function scope, the this in your example is not in the callback function, it is just referring to the window object.


text:
Q: postgresql select row with minimum value This is my query in PostgreSQL:
SELECT
    "axapta_calls".id,
    "axapta_calls".call_time,
    calls.calltime,
    "calls"."id" as "call_id",
    abs(extract(epoch from (axapta_calls.call_time::timestamp - calls.calltime::timestamp))) as ab
FROM
    "axapta_calls"
inner join
    "calls" (ON
        axapta_calls.converted_outer_phone=calls.caller_phone
        and abs(extract(epoch from (axapta_calls.call_time::timestamp - calls.calltime::timestamp)))<= 600 )
WHERE  ("axapta_calls"."id" > 0)
GROUP BY "axapta_calls"."id", "calls"."id"

And result is:

How to get only one row with minimum "ab" value?
I change this query to:
SELECT
    distinct on (axapta_calls.id)
    "axapta_calls".id,
    "axapta_calls".call_time,
    calls.calltime,
    "calls"."id" as "call_id",
    abs(extract(epoch from (axapta_calls.call_time::timestamp - calls.calltime::timestamp))) as ab
FROM
    "axapta_calls"
inner join
    "calls" ON
        axapta_calls.converted_outer_phone=calls.caller_phone
        and abs(extract(epoch from (axapta_calls.call_time::timestamp - calls.calltime::timestamp)))<= 600
WHERE  ("axapta_calls"."id" > 0)
GROUP BY "axapta_calls"."id", "calls"."id"

But get second row with ab = 347.783. What I am doing wrong?

A: You are missing an ORDER BY clause.  You should be ordering first by the id, then by the ab column.  Then, Postgres will return a single record for each id corresponding to the lowest ab value.
SELECT
    distinct on (axapta_calls.id),
    "axapta_calls".id,
    "axapta_calls".call_time,
    calls.calltime,
    "calls"."id" as "call_id",
    abs(extract(epoch from (axapta_calls.call_time::timestamp - calls.calltime::timestamp))) as ab
FROM
    "axapta_calls"
inner join "calls"
    ON axapta_calls.converted_outer_phone=calls.caller_phone and
       abs(extract(epoch from (axapta_calls.call_time::timestamp - calls.calltime::timestamp)))<= 600 )
WHERE  ("axapta_calls"."id" > 0)
ORDER BY
    axapta_calls.id, 5;

A: You can use analytics function as well:
select *
from
(SELECT
    "axapta_calls".id,
    "axapta_calls".call_time,
    calls.calltime,
    "calls"."id" as "call_id",
    abs(extract(epoch from (axapta_calls.call_time::timestamp - calls.calltime::timestamp))) as ab,
    rank() OVER (ORDER BY ab )rnk
FROM
    "axapta_calls"
inner join
    "calls" (ON
        axapta_calls.converted_outer_phone=calls.caller_phone
        and abs(extract(epoch from (axapta_calls.call_time::timestamp - calls.calltime::timestamp)))<= 600 )
WHERE  ("axapta_calls"."id" > 0) )
where rnk=1


text:
Q: How do I delete a DeadLetter message on an Azure Service Bus Topic I'm writing a piece of code which will allow us to:

*

*View a list of all dead letter messages that exist within an Azure Service Bus Topic (Peek)

*Fix and send them back to the Topic

*Delete them from the dead letter queue upon resending.

I have no issues with the first 2 points; using the Peek receive mode I can show a list of messages and we can edit and resend with no issues.
The problem comes when I want to actually delete the message from the dead letter queue.
How do we do this on a message by message level?  We may only want to delete 2 of the messages residing in the dead letter queue and keep the others for reviewing at a later stage.  Does calling .Complete() on a message in the dead letter queue remove it like it does in the main subscription?
For reference; here is our code for getting the SubscriptionClient for the dead letter queue:
private SubscriptionClient GetOrCreateSubscriptionClient(string connectionString)
{
    if (!NamespaceManager.TopicExists(_topicName))
    {
        NamespaceManager.CreateTopic(new TopicDescription(_topicName)
        {
            MaxSizeInMegabytes = 5120,
            DefaultMessageTimeToLive = TimeSpan.FromSeconds(DEFAULT_LOCK_DURATION_IN_SECONDS)
        });
    }

    if (!NamespaceManager.SubscriptionExists(_topicName, _subscriptionName))
    {
        NamespaceManager.CreateSubscription(_topicName, _subscriptionName);
    }

    var deadLetterPath = SubscriptionClient.FormatDeadLetterPath(_topicName, _subscriptionName);

    var client = SubscriptionClient.CreateFromConnectionString(
        connectionString, deadLetterPath, _subscriptionName, ReceiveMode.PeekLock);

    return client;

}

A: Here is how you can get a list of all messages in the dead letter queue:
public async Task<IEnumerable<BrokeredMessage>> GetDeadLetterMessagesAsync(string connectionString,
    string queueName)
{
    var queue = QueueClient.CreateFromConnectionString(connectionString, QueueClient.FormatDeadLetterPath(queueName));
    var messageList = new List<BrokeredMessage>();
    BrokeredMessage message;
    do
    {
        message = await queue.PeekAsync();
        if (message != null)
        {
            messageList.Add(message);
        }
    } while (message != null);
    return messageList;
}

Using the SequenceNumber you can then delete a specific message:
public async Task DeleteDeadLetterMessageAsync(string connectionString, string queueName, long sequenceNumber)
{
    var deadLetterQueue = QueueClient.CreateFromConnectionString(connectionString, QueueClient.FormatDeadLetterPath(queueName));
    var msg = await deadLetterQueue.PeekAsync(sequenceNumber);
    if (msg.SequenceNumber == sequenceNumber)
    {
        msg = await deadLetterQueue.ReceiveAsync();
        await msg.CompleteAsync();
    }
}

Please note that Peek may return another message if there isn't any message with the specified SequenceNumber. Therefore you'll need to check the SequenceNumber, so that you don't delete the wrong message.

A: Yes, calling complete on the reference to the brokered message you receive from the dead letter queue will remove it from the dead letter queue.

A: Updated code to delete a message from the dead letter queue using the new ServiceBusClient from azure.messaging.servicebus:
public async Task DeleteDeadLetterMessageAsync(string connectionString, string queueName, long sequenceNumber)
{
    var serviceBusClient = new ServiceBusClient(connectionString);
    var receiverOptions = new ServiceBusReceiverOptions { SubQueue = SubQueue.DeadLetter };
    var receiver = serviceBusClient.CreateReceiver(queueName, receiverOptions);
    var msg = await receiver.PeekMessageAsync(sequenceNumber);
    if (msg.SequenceNumber == sequenceNumber)
    {
        msg = await receiver.ReceiveMessageAsync();
        await receiver.CompleteMessageAsync(msg);
    }
}


text:
Q: A multi-threaded writer: concurrency issues using cpp I am trying to build a library that would write to a single file, and would be able to work in a multi-threaded environment. The requirements are:

*

*No concurrency problems will occur while writing to the file.

*The order in which threads are handled is not important.

*The library should be non blocking, i.e. the write and flush functions will return before the given buffer had been written.

Here's what I have so far:
int write2device(char *buffer, int length) {
    Task * task = new Task(id++,buffer,length);
    pthread_t * thread = new pthread_t;
    Argument * arg = new Argument; //A sturct with pthread_t and task fields
    arg->task = task;
    arg->thread = thread;
    pthread_create(thread,NULL,deamonWrite,arg);
    return 0;
}

void wait(Argument * arg) {
    //manager is a singleton class that handles the threads database and related
    //issues
    manager->pushDeamon(arg->thread);
    manager->lock(arg->task->getId()); //mutex - only one thread can write
}

void * deamonWrite(void * arg) {
    Argument * temp = (Argument *) arg;
    wait(temp);
    //critical section
    //will add signal() later
    return NULL;
}

The idea is that for every thread calling write2device I open a thread that runs deamonWrite(). This function has the structure of wait() -> critical section -> signal().
In wait, if someone else is writing I will (haven't done yet) suspend the thread so that the user won't wait till it's done writing.
I have two questions:

*

*How do I implement the mutex (lock function)? I understand that This must be an atomic function, sense several threads trying to acquire a lock might result in chaos.

*Is my general structure in the right way?

I am new to concurrency and would appreciate any thoughts on this matter - thanks!

A: Push the Task structures to a queue/vector and process them sequentially from a single thread instead of multiple threads for each task individually. The only place where you'll need a mutex is when pushing to and pulling from the queue. As Ben correctly noted in the comments, you should leave the implementation of thread synchronization primitives (mutex, critical section) to the OS and/or whatever system API you're allowed to use.


text:
Q: Cannot locate namei.c or super.c, etc in linux Studying linux filesystem, trying to copy over an existing fs and modify it and mount it back to linux, And eventually to create a simple one.
The problem here is that I cannot find all the source files for filesystem.
As google says, they should be at /linux/fs/ext2/, but the only file I am seeing there is a Makefile. I have searched the whole Filesystem disk, nothing comes up.
The systems I have tried are 3 Ubuntu, 1 redhat, all of which have kernel 2.6
Thanks!

A: download source code of kernel from "kernel.org" , then extract it wit "tar xfz"
then you can find requested "c" program under "fs"

A: Unless performance is at an absolute premium, it would be better to write a user mode filesystem module, check out fuse.
Filesystem development is hard. For some look at what goes on there, perhaps look at the articles by Valerie Aurora on LWN: UnionFS part I, part II. She has written a few others there, all worth a read. Perhaps also check up on BTRFS, starting here. Note that BTRFS has been in intensive development for more than 5 years, and is still far from being considered stable enough for more than personal experimental use...


text:
Q: How to export inline quotations from emacs org mode to latex csquotes syntax? I would like to export inline quotations in an org-document to \enquote{} commands. The csquotes package then ensures French quotation marks « » are used in the resulting pdf document.
I am well aware this question has been asked before here - and that solutions have been suggested by @Jonathan Leech-Pepin and @Christophe Poile. I tried all solutions suggested, without success. I would like to avoid (1) hardcoding the correct quotation marks or (2) using the latex command in my org document. OSX 10.15.5, emacs 26.2, org 9.2.5.
Org document header:
#+Title: GS
#+AUTHOR: HDV
#+SEQ_TODO:
#+TAGS:
#+STARTUP: indent
#+LANGUAGE: fr
#+LaTeX_CLASS: article
#+LATEX_CLASS_OPTIONS: [a4paper,11pt,twoside]
#+LATEX_HEADER: \usepackage[utf8]{inputenc}
#+LATEX_HEADER: \usepackage{ae,lmodern}
#+LATEX_HEADER: \usepackage[french]{babel}
#+LATEX_HEADER: \usepackage[T1]{fontenc}
#+LATEX_HEADER: \usepackage{graphicx}
#+LATEX_HEADER: \usepackage[babel=true]{csquotes}

Exported latex preamble:
    % Created 2020-07-07 Tue 20:45
% Intended LaTeX compiler: pdflatex
\documentclass[a4paper,11pt,twoside]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{graphicx}
\usepackage{grffile}
\usepackage{longtable}
\usepackage{wrapfig}
\usepackage{rotating}
\usepackage[normalem]{ulem}
\usepackage{amsmath}
\usepackage{textcomp}
\usepackage{amssymb}
\usepackage{capt-of}
\usepackage{hyperref}
\usepackage[utf8]{inputenc}
\usepackage{ae,lmodern}
\usepackage[french]{babel}
\usepackage[T1]{fontenc}
\usepackage{graphicx}
\usepackage[babel=true]{csquotes}
\author{}
\date{\today}
\title{}
\hypersetup{
 pdfauthor={},
 pdftitle={},
 pdfkeywords={},
 pdfsubject={},
 pdfcreator={Emacs 26.2 (Org mode 9.2.5)},
 pdflang={French}}
\begin{document}

A: I used to use the following code to convert @xxx@ to \hl{xxx} (using the soul LaTeX package). You might be able to adapt this to convert "xxx" to \enquote{xxx}?
** convert @highlighted@ text on export to ~\hl{highlighted}~
#+begin_src emacs-lisp
  (defun esf/latex-filter-highlight (text backend info)
    "Convert @...@ to \hl{...} in LaTeX export."
    (when (org-export-derived-backend-p backend 'latex)
      (replace-regexp-in-string "@\\([^@]+\\)@" "\\\\hl{\\1}" text)))

  (add-to-list 'org-export-filter-plain-text-functions
               'esf/latex-filter-highlight)
#+end_src

A: You do not need csquotes or \enquote{} to get guillemets; there is smart quote support out of the box in Org mode. The following suffices:
#+OPTIONS: ':t
#+LANGUAGE: fr
#+LATEX_HEADER: \usepackage[french]{babel}

* foo

As somebody once said:

"You cannot explain anything to a stone."

You turn on smart quotes, set the  #+LANGUAGE to fr to select the french style of smart quotes and then let babel figure it out. The TeX file produced looks like this (only the significant parts are shown):
...
\usepackage[french]{babel}
...
\begin{document}

...

\section{foo}
\label{sec:orgd0ec1fc}

As somebody once said:

\og You cannot explain anything to a stone.\fg{}
\end{document}

If you really want \enquote, you can modify the value of org-export-smart-quotes-alist. I think the best way is to duplcate the current section for fr, modify it for your purposes and add it to the beginning of the alist where it is going to shadow the existing entry:
  (setq fr-quotes '("fr"
            (primary-opening :utf-8 "« " :html "« " :latex "\\enquote{" :texinfo "@guillemetleft{}@tie{}")
            (primary-closing :utf-8 " »" :html " »" :latex "}" :texinfo "@tie{}@guillemetright{}")
            (secondary-opening :utf-8 "« " :html "« " :latex "\\\enquote{" :texinfo "@guillemetleft{}@tie{}")
            (secondary-closing :utf-8 " »" :html " »" :latex "\\}" :texinfo "@tie{}@guillemetright{}")
            (apostrophe :utf-8 "'" :html "'"))

  (add-to-list 'org-export-smart-quotes-alist fr-quotes)

As you can see I changed the opening and closing quotes for LaTeX to use \enquote{ to open and } to close. Adding it to the front of the list allows you to get rid of it quickly if you want to go back to the default:
(setq org-export-smart-quotes-alist (cdr org-export-smart-quotes-alist))

gets rid of the first entry (the added "fr" entry) allowing the default "fr" entry to be seen. You should probably do C-h v org-export-smart-quotes-alist and look at its value carefully.
Then the Org mode file becomes:
#+OPTIONS: ':t
#+LANGUAGE: fr
#+LATEX_HEADER: \usepackage[french]{babel}
#+LATEX_HEADER: \usepackage[babel=true]{csquotes}

* foo

As somebody once said:

"You cannot explain anything to a stone."

and the resulting tex file looks like this (again, only the significant parts are shown):
...
\usepackage[french]{babel}
\usepackage[babel=true]{csquotes}
...
\begin{document}
...
\section{foo}
\label{sec:orgb8fcb36}

As somebody once said:

\enquote{You cannot explain anything to a stone.}
\end{document}


text:
Q: Sampling random points over each class of a Classification in GEE I performed an Unsupervised Classification in GEE and I have 3 classes. I need to create random points in each class in order to draw a histogram of spectral signature later.
In line 150 of the script I tried to use stratifiedSample to create 100 points per class, but it takes a very long time and does not finish and gives the error:

Layer 2: Layer error: The service is currently unavailable.

I do not think mapping 300 points is so difficult for GEE. How can I add these random points to my classification classes?


text:
Q: sustitución de registros específicos en un dataframe estoy realizando una limpieza en una base de datos,y para ello quiero cambiar diversos registros de una columna según unas condiciones.
Adjunto parte del código donde intento realizar el cambio:
for i in range(len(alquiler)):
    if alquiler.iloc[i]['price']<=2000 and alquiler.iloc[i]['floor_area']=="":
        alquiler.iloc[i]['floor_area']=media1
    elif alquiler.iloc[i]['price']>2000 and alquiler.iloc[i]['price']<=4000 and alquiler.iloc[i]['floor_area']=="":
        alquiler.iloc[i]['floor_area']=media2
    elif alquiler.iloc[i]['price']>4000 and alquiler.iloc[i]['price']<=6000 and alquiler.iloc[i]['floor_area']=="":
        alquiler.iloc[i]['floor_area']=media3
    elif alquiler.iloc[i]['price']>6000 and alquiler.iloc[i]['price']<=10000 and alquiler.iloc[i]['floor_area']=="":
        alquiler.iloc[i]['floor_area']=media4
    elif alquiler.iloc[i]['price']>10000 and alquiler.iloc[i]['floor_area']=="":
        alquiler.iloc[i]['floor_area']=media5

Donde para poneros en contexto, he definido varias condiciones y diferentes medias que es una variable con un simple valor numérico. Mi idea es que si se cumple la condición, ese registro cambie a algunas de esas medias, pero no me realiza el cambio.

A: Lo primero, no te recomiendo usar for i in range(len(alquiler)):, cuando tienes un método de pandas para iterar sobre filas: for i, fila in alquiler.iterrows():.
Segundo, creo que tu aproximación es más complicada de lo necesario. Me explico: estas iterando fila a fila en un dataframe, y en función a un conjunto de reglas decides qué valor sustituir (media1, media2...). ¿No sería más sencillo seleccionar de una tacada todas las filas de tu dataframe que cumplen la condición X y a todas ellas aplicarles el valor que quieres? Te adjunto un ejemplo de juguete para ilustrar:
condiciones_y_valor = tuple(
    [
        ("price <= 2000 and floor_area == ''", media1),
        ("price > 2000 and price <= 4000 and floor_area == ''", media2),
    ]
)

for condicion, media in condiciones:
    df_cumple_condicion = alquiler.query(condicion) # equivalente a tu if ... elif pero devuelve todas las filas del DF que cumplan 'condicion'
    alquiler.loc[df_cumple_condicion.index, 'floor_area'] = media
    # Si algún registro cumple la condición, cogemos su índice y sustituimos el valor de esa fila en el df alquiler


text:
Q: Will and future fact There is something I don't understand with the future simple.
My book says we can use it in this sentence:

"In June we will bring out two new models"

Instead I  would say:

"In June we are bringing out two new models"

(present continuous) because this is planned!
According to the book we should use the future simple because this is a future fact! Is it true? If yes can you give me (better) examples of future facts.

A: For your example both work because you included the prepositional phrase "In June".  Without that phrase, the second sentence gives you no information about the timing of the event, while the first still tells you with certainty that it will happen at some point in the future:
"We will bring out two new models"
vs.
"We are bringing out two new models"
In general future fact sounds very certain, and implies something about the timing without any prepositions.  Consider the differences between:
"I will survive" versus "I am surviving". The first sounds reassured, while the second sounds like you're barely surviving.
"I will go on vacation" versus "I am going on vacation".  The first is clear that this is something that will happen in the future.  The second is unclear, it could mean you are leaving right now.


text:
Q: Remove submodule repository from Xcode source control I had 2 submodules which I deleted recently. Removed them from .gitmodules, removed them from project directory, removed them from .git/modules. But Xcode still thinks that they're existing in Source Control. So I noticed an xccheckout file that contains the remotes. I googled about half of hour how to actually remove them, and found a single f...g instruction to remove them manually from xccheckout, others are about how to remove Git support from project (which isn't actually what I f...g need) or questions about should I put xccheckout into .gitignore or not.
Am I doing something wrong? Isn't there any way to remove the submodule link from Xcode project with actually the program created it? Am I the only who needs this?


text:
Q: How to find source of inherited permission on Exchange online mailbox? Example:
Get-MailboxPermissions -Identity "<user>"

Shows permissions with IsInherited=True
Where would this permission be inherited from in Exchange online?
In on premise exchange I would use Get-MailboxDatabase and/or Get-ADPermission but these are unavailable in Exchange online.
There is a permission we want to remove, but can't because it's inherited:
WARNING: An inherited access control entry has been specified: [Rights: ReadControl, ControlType: Allow]  and was ignored on object "CN=<user>,OU=<organization>,OU=Microsoft Exchange Hosted Organizations,DC=<server>,DC=PROD,DC=OUTLOOK,DC=COM".

A: When you run the Get-MailboxPermission in Exchange Online, it can list all users who have mailbox level permission to the specific mailbox. For example:

For the IsInherited=True results, we can check the User column. Some permissions are interited from some role groups in AD and Exchange organization such as Administrator, Domain Admins, Organization Management, Enterprise Admins and so on.
These permissions are generally configured be default. In Exchange Admin Center, you can click Permissions > Admin Roles to view the role group.


text:
Q: c# Methods error CS0236 Guys i need some help here,
i have error in
Line 50: CS0236  C# A field initializer cannot reference the non-static field, method, or property
Line 51: CS0236  C# A field initializer cannot reference the non-static field, method, or property
namespace ConsoleApplication5
{
    public delegate string Metodo(string t1, string t2);

    class Program
    {
        static void Main(string[] args)
        {

        }
    }

    public class ExemploDel
    {
        public static string NomeMetodo(string t1, string t2)
        {
            return t1 + t2;
        }

        Metodo meuMetodo = NomeMetodo;
    }

    public class Metodos
    {

        public string Method1(string tx1, string tx2)
        {
            return tx1 + tx2;
        }
        public string Method2(string tx1, string tx2)
        {
            return tx2 + tx1;
        }
    }

    public class DelegatesEx
    {
        public static string NomeMetodo(string t1, string t2)
        {
            return t1 + t2;
        }

        Metodos obj = new Metodos();
        Metodo m1 = obj.Method1;
        Metodo m2 = obj.Method2;
        Metodo m3 = NomeMetodo;

    }
}

A: First of all, you have placed the calling code at wrong place, the following 4 lines should go in the Main method of your program:
Solution1:
class Program
{
    static void Main(string[] args)
    {
       Metodos obj = new Metodos();
       Metodo m1 = obj.Method1;
       Metodo m2 = obj.Method2;
       Metodo m3 = NomeMetodo;
    }
}

Secondly, you have marked your delegate as static while you are trying to assign it instance method, so either make the delegate non-static in declaration and make the methods static.
public delegate string Metodo(string t1, string t2);

Solution2:
if you want to keep the Metodo delegate static, then your methods should also be satic like:
public class Metodos
{

        public static string Method1(string tx1, string tx2)
        {
            return tx1 + tx2;
        }
        public static string Method2(string tx1, string tx2)
        {
            return tx2 + tx1;
        }
}

and now your main method code will also be changed, as static methods are access using the class not instance of it:
class Program
{
    static void Main(string[] args)
    {
       Metodo m1 = Metodos .Method1;
       Metodo m2 = Metodos .Method2;
       Metodo m3 = NomeMetodo;
    }
}


text:
Q: NoClassDefFoundError: kotlin/jvm/JvmInline I'm new to Kotlin. I appreciate her help.
I am building a rest to get a list of people:
@RestController
@RequestMapping(Constants.URL_BASE_PERSONS)
class PersonRestController {
  @Autowired
  val personBussiness: PersonBussiness? = null

  @GetMapping(Properties.EMPTY)
  fun findAll(): ResponseEntity<List<Person>> {
    return try {
      ResponseEntity(personBussiness!!.findAll(), HttpStatus.OK)
    } catch (e: Exception) {
      ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR)
    }
  }
...

When I invoke it from postman I get this error. I can't identify the problem :

ERROR 15479 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: kotlin/jvm/JvmInline] with root cause

java.lang.ClassNotFoundException: kotlin.jvm.JvmInline
at java.net.URLClassLoader.findClass(URLClassLoader.java:382) ~[na:1.8.0_292]
at java.lang.ClassLoader.loadClass(ClassLoader.java:418) ~[na:1.8.0_292]
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352) ~[na:1.8.0_292]
at java.lang.ClassLoader.loadClass(ClassLoader.java:351) ~[na:1.8.0_292]
at > com.fasterxml.jackson.module.kotlin.ExtensionsKt.isUnboxableValueClass(Extensions.kt:122) ~[jackson-module-kotlin-2.13.0.jar:2.13.0]
at com.fasterxml.jackson.module.kotlin.KotlinSerializers.findSerializer(KotlinSerializers.kt:69) ~[jackson-module-kotlin-2.13.0.jar:2.13.0]
at com.fasterxml.jackson.databind.ser.BeanSerializerFactory._createSerializer2(BeanSerializerFactory.java:215) ~[jackson-databind-2.13.0.jar:2.13.0]
at com.fasterxml.jackson.databind.ser.BeanSerializerFactory.createSerializer(BeanSerializerFactory.java:173) ~[jackson-databind-2.13.0.jar:2.13.0]
at com.fasterxml.jackson.databind.SerializerProvider._createUntypedSerializer(SerializerProvider.java:1495) ~[jackson-databind-2.13.0.jar:2.13.0]
at com.fasterxml.jackson.databind.SerializerProvider._createAndCacheUntypedSerializer(SerializerProvider.java:1443) ~[jackson-databind-2.13.0.jar:2.13.0]
at com.fasterxml.jackson.databind.SerializerProvider._findExplicitUntypedSerializer(SerializerProvider.java:1412) ~[jackson-databind-2.13.0.jar:2.13.0]
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.hasSerializerFor(DefaultSerializerProvider.java:260) ~[jackson-databind-2.13.0.jar:2.13.0]
at com.fasterxml.jackson.databind.ObjectMapper.canSerialize(ObjectMapper.java:3432) ~[jackson-databind-2.13.0.jar:2.13.0]
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.canWrite(AbstractJackson2HttpMessageConverter.java:274) ~[spring-web-5.3.13.jar:5.3.13]
at org.springframework.http.converter.AbstractGenericHttpMessageConverter.canWrite(AbstractGenericHttpMessageConverter.java:76) ~[spring-web-5.3.13.jar:5.3.13]
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.getProducibleMediaTypes(AbstractMessageConverterMethodProcessor.java:380) ~[spring-webmvc-5.3.13.jar:5.3.13]
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:230) ~[spring-webmvc-5.3.13.jar:5.3.13]
at org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:219) ~[spring-webmvc-5.3.13.jar:5.3.13]
at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:78) ~[spring-web-5.3.13.jar:5.3.13]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:135) ~[spring-webmvc-5.3.13.jar:5.3.13]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) ~[spring-webmvc-5.3.13.jar:5.3.13]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) ~[spring-webmvc-5.3.13.jar:5.3.13]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.13.jar:5.3.13]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067) ~[spring-webmvc-5.3.13.jar:5.3.13]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) ~[spring-webmvc-5.3.13.jar:5.3.13]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.13.jar:5.3.13]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.3.13.jar:5.3.13]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:655) ~[tomcat-embed-core-9.0.55.jar:4.0.FR]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.13.jar:5.3.13]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) ~[tomcat-embed-core-9.0.55.jar:4.0.FR]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) ~[tomcat-embed-core-9.0.55.jar:9.0.55]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.55.jar:9.0.55]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.55.jar:9.0.55]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.55.jar:9.0.55]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.55.jar:9.0.55]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.13.jar:5.3.13]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.13.jar:5.3.13]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.55.jar:9.0.55]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.55.jar:9.0.55]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.13.jar:5.3.13]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.13.jar:5.3.13]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.55.jar:9.0.55]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.55.jar:9.0.55]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.13.jar:5.3.13]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.13.jar:5.3.13]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.55.jar:9.0.55]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.55.jar:9.0.55]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197) ~[tomcat-embed-core-9.0.55.jar:9.0.55]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) [tomcat-embed-core-9.0.55.jar:9.0.55]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540) [tomcat-embed-core-9.0.55.jar:9.0.55]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135) [tomcat-embed-core-9.0.55.jar:9.0.55]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.55.jar:9.0.55]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) [tomcat-embed-core-9.0.55.jar:9.0.55]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) [tomcat-embed-core-9.0.55.jar:9.0.55]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382) [tomcat-embed-core-9.0.55.jar:9.0.55]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.55.jar:9.0.55]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895) [tomcat-embed-core-9.0.55.jar:9.0.55]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1722) [tomcat-embed-core-9.0.55.jar:9.0.55]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.55.jar:9.0.55]
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) [tomcat-embed-core-9.0.55.jar:9.0.55]
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) [tomcat-embed-core-9.0.55.jar:9.0.55]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.55.jar:9.0.55]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_292]

Thanks


text:
Q: SQL: How to enforce functional dependency using constraints? Assume we have a table:
CREATE TABLE Jobs
    (
      JobID INT PRIMARY KEY ,
      AssignedUser VARCHAR(10) ,
      Zone VARCHAR(10)
    )

The constraint we need to enforce is this: make sure that no user is assigned jobs in more than one zone, that is, there is a functional dependency AssignedUser => Zone.
How to enforce this in SQL? Unfortunately, this is a legacy table and we cannot change its structure, but we are allowed to create constraints to enforce integrity.

A: Something like the following should work. You may want to add a where clause excluding Zone IS NULL depending on the desired semantics for that.
CREATE VIEW V
WITH SCHEMABINDING
AS
  SELECT AssignedUser,
         Zone,
         COUNT_BIG(*) AS C
  FROM   dbo.Jobs
  GROUP  BY AssignedUser,
            Zone

GO

CREATE UNIQUE CLUSTERED INDEX IX
  ON V(AssignedUser)


text:
Q: Can't fade in my navbar when fixing it to the top with jquery I use jQuery to fix my navbar at the top on scrolldown, the sticky class takes care of that. However, I want the browser to do it smoothly, like a quick fade In. Can I use fadeIn before adding the class? So far, it hasn't worked.
var num = 1; //number of pixels before modifying styles
$(window).bind('scroll', function() {
    if ($(window).scrollTop() > num) {
        $('.navbar') fadeIn(500).addClass('sticky');
    } else {
        $('.navbar').removeClass('sticky');
    }
});

A: You forgot to put . in this statement
 $('.navbar')fadeIn(500).addClass('sticky');

It should be
 $('.navbar').fadeIn(500).addClass('sticky');

A: Add a transition to your .navbar CSS:
.navbar {
    ...
    transition: all 0.5s;
}

Note: The property to animate, must always be set - even before the scrolling...
Here a working demo: http://jsfiddle.net/ky3916tn/1/


text:
Q: Analysis Services Attribute Hierarchy and Attribute Relationships Is it possible to have a attribute hierarchy where the parent doesn't always have children? If so, how is this achieved in SQL server Analysis Services?

A: Never mind - found the solution: http://iman77.blogspot.com/2009/09/handling-raggedunbalanced-hierarchies.html


text:
Q: Calling methods conditionally from two different classes I have two classes ExceptionLog and DebugLog.
public class ExceptionLog {
    public static String StackTrace {get; set;}
    public static String ClassName {get; set;}
    public static String MethodName {get; set;}
    public static String LogType {get;set;}
    public static Exception ex {get;set;}

    public Static void Debug(Exception ex)
    {
        logType = 'EXCEPTION';
        ex = ex;
        log();
    }

    public Static void log()
    {
        try
        {
            extractException();
            writeToObject();

        }
        catch(Exception e)
        {
            //new ExceptionLog().Module('LogException').log(e);
        }
    }

    public static void extractException()
    {
        // Logic here
    }

    public static void writeToObject()
    {
        // data save to object logic here
    }
}

and
public class DebugLog {
    public static String LogType {get;set;}
    public static String DebugMessage {get;set;}

    public Static void Debug(String message)
    {
        Debug(null, message);
    }

    public Static void Debug(LoggingLevel level, String message)
    {
        if(level != null )
        {
            LogType = String.valueOf(level);
        }

        DebugMessage = message;

        log();
    }

    public Static void log()
    {
        // Log logic here
    }

}

What I want to achieve is, write a controller class that will decide which debug method needs to be called
public class Log {
    public void Debug(String message)
    {
        DebugLog.Debug(message);
    }
    public void Debug(loggingLevel loggingLevel, String message)
    {
        DebugLog.Debug(loggingLevel, message);
    }
    public void Debug(Exception ex)
    {
        ExceptionLog.Debug(ex);
    }
}

That is, if I pass Exception in the debug method, it will call the ExceptionLog.Debug(ex) else it will call the debug method from DebugLog class.
How can I design the classes more elegantly or any design pattern fit here?

A: You can send in an un-typed argument and find the type in the Log class as seen below:
public class Log {
    public void debug(Object genericLog){
        if(genericLog instanceof String){
            DebugLog.Debug(String.valueOf(message));
        }
        else if(genericLog instanceof Exception){
            ExceptionLog.Debug((Exception)genericLog);
        }
        else if(genericLog instanceof DebugWrapper){
            DebugWrapper wrapper = (DebugWrapper)genericLog;
            DebugLog.Debug(wrapper.loggingLevel, wrapper.message);
        }
        else{
            //do whatever
        }
    }

    public void debug(String message, LoggingLevel loggingLevel){
        debug(wrapLog(message, loggingLevel));
    }

    public class DebugWrapper{
        public String message;
        public LoggingLevel loggingLevel;

        public DebugWrapper(String message, LoggingLevel loggingLevel){
            this.message = message;
            this.loggingLevel = loggingLevel;
        }
    }

    public DebugWrapper wrapLog(String message, LoggingLevel loggingLevel){
        return new DebugWrapper(message, loggingLevel);
    }
}

Alternatively, you can implement the Apex Callable interface which is designed to handle a map of generic arguments. Your class would have a call(String action, Map<String, Object> args) method defined. Passing the action through a switch case will determine which method is called.


text:
Q: How can I prevent Symfony trying to load a service while using Swift Mailer Attachment? I try to attach a file via Swiftmail to my Email in Symfony:
$message = (new \Swift_Message($message))
      ->setFrom([$smtpMail => $smtpName])
      ->setTo($smtpMail)
      ->setBody($html, 'text/html');
      ->attach(Swift_Attachment::fromPath('sample.pdf'));

The problem is now, that because of the :: Symfony thinks that I am trying to load a service.
The error message is:

Attempted to load class "Swift_Attachment" from namespace
"App\Service". Did you forget a "use" statement for another namespace?

How can I prevent this?

A: Nothing to do with symfony and services. do \Swift_Attachment (backslash at the begining) like you do new \Swift_Message because the class is in global scope.
Right now php tries to find the class in current namespace which happens to be App\Service (check top of the file this code is from to verify).
Symfony never loads services via static methods (no magic there, you have to access them from DIC or inject them to your service as dependency).


text:
Q: how to understand bindkey Comming from this page with information on how to customize zsh I encounter this
# oh wow!  This is killer...  try it!
bindkey -M vicmd "q" push-line

I'm not able to find a man page for bindkey, nor understanding what is the key being binded, what does -M means and what is vicmd.
So I've no idea how to know whats the beautifier killer feature :)

A: % type bindkey
bindkey is a shell builtin

So its documentation is in the zsh manual, not in a man page of its own. Although there's a man zshbuiltins, the bindkey builtin is not documented there because it's part of a semi-autonomous piece of zsh, the line editor zle, and so it's documented in man zshzle.
You can find the documentation by running run-help bindkey in zsh, or pressing M-h while the cursor is on a bindkey command. This requires run-help to be properly set up, which for some reason is not the case by default: it's an alias to man. To get a useful run-help, put these lines in your .zshrc:
unalias run-help
autoload -U run-help

Alternatively, use man zshall. Or if you're browsing a hypertext version of the manual, use the functions index, which also lists builtins.

vicmd is the keymap used in vi command mode. push-line is an editor widget, which have their own index. So this command makes q "pause" the current line in vi command mode (for some reason this feature, which is indeed useful, is only bound to a key by default in emacs mode).


text:
Q: Xpages how to obtain/create this calculations module We have to achieve some task consisting in some calculations ( recursive calculations ) based on some fields values inside the doc. Let say, for example, creating some invoices.
IN some old classic lotus notes applications, we just created a table with 24 rows and 4 columns, in every cell being an editable / computed field. You can imagine what kind of formulas we entered in each field, considering the fact that the current fields row were based on the value of the previous fields row and so on.
In xpages, my scenario was to create a button which shows a dialog where the invoice structure is. Completing all the fields and then save/hide the dialog, the doc. < invoice > will be listed on an (embedded) view inside the main document. the current opened dialog / invoice will take consideration on the previous invoice values. Obviously, there would be some disadvantages, the first I noticed was: let say my view lists 5 invoices. If I open for editing the 2nd one, I modify some field => from the 3rd to the last one, will be all be changing on this last edit?
Is there any sample snippet from I could get inspired or a simple module of this type ofcalculations?
I would like some advices and some helpful tips/suggestions. Also, I will appreciate any important considerations that I should be beware of.

A: This is a prime example of where XPages and a repeat control is of benefit.
On the old Notes form, you'd have added 24 rows of 4 columns. Think of the overhead involved if someone then needs to create 25 invoices, or the calculation/hide-when is wrong for one column, or another column is required.
Repeat controls allow you to build one instance of the layout and iterate over 2, 20, 200 rows dynamically. You can use a dialog, or make a row editable/non-editable by having a button that adds the relevant key (a UNID for a document, a key if you're building a Map of Java objects) to a scoped variable; then the fields are editable if the viewScope variable is the key for the current row, otherwise not.
Adding additional rows is simple - change the rows value or add a page. Adding an additional column is easy - do it once and it's done for all. There are no hide-when formulas for each row, so no chance of mistakes there. Calculations point to the data for that row, not a field with "_1", "_2", "_3" etc. If a calculation needs changing, do it once and it's done for all rows.

A: The code you need is in Exercise 23 of the intro to XPages workshop. You might want to review it here:
http://www-10.lotus.com/ldd/ddwiki.nsf/m_Home.xsp?documentId=C8E56F876AF2315A852575F60076592B#mobileViewer
I wrote it

A: In our own instance of this, we have requisitions, purchase orders and payment requests. Each of those is a document and each line item on each of those documents is ALSO a document. Then, the repeat on the main document (invoice in your case) references the view, using a filter so that it only gets the line items for that invoice. Thus, you can edit the line items on the invoice (include edit, save and cancel buttons on each entry in the repeat control) and save them.
Here's the skeleton of a viewEntryCollection used to make line items available in a panel inside a repeat.
<xp:repeat id="repeat1" rows="1000" var="lineItem" indexVar="itemIndex">
    <xp:this.value><![CDATA[#{javascript:var ludb:NotesDatabase = getDb("tamisDb");
var luview:NotesView = ludb.getView("LULineItemsByParentDocID");
var parentDocID = compositeData.parentDocID;
if (parentDocID == null) { parentDocID = "0" };
var vec:NotesViewEntryCollection = luview.getAllEntriesByKey(parentDocID, true);
if (vec.getCount() == 0){
    viewScope.totalProcValue = 0;
}
return vec;}]]></xp:this.value>
    <xp:panel id="lineItemDataPanel">
        <xp:this.data>
            <xp:dominoDocument var="itemDoc" formName="LineItem"
                action="openDocument" documentId="#{javascript:lineItem.getUniversalID()}"
                ignoreRequestParams="true">
                <xp:this.databaseName><![CDATA[#{javascript:getDb("tamisDb")}]]></xp:this.databaseName>
            </xp:dominoDocument>
        </xp:this.data>

To bind a control to the line item document, use the var in the source document.
<xp:inputText value="#{itemDoc.Description}" id="lineItemEditDescription" style="width:200.0px">
</xp:inputText>

So, 'lineitem' from the var value of the repeat is a NotesViewEntry object (lineitem) used by that dominoDocument definition to create a NotesDocument data source, which we refer to by the var on it's definition (itemdoc). Does that make sense? I might not have needed the second layer of abstraction, but that's how the code was passed to me.


text:
Q: Ajax query string parameters null There is a delete button on UI and on click of that I have to call some service method which would call get some value from DB and I have to display that on popup.
I have to call a particular method of an Action class. So I am adding the task id and command name(method name) to the query string. But when in action class I do
request.getParameter("command")--> this results in null
Please found the javascript method.
function ajaxGetDependentTask(id)
{
    try
    {
        xmlHttp = new ActiveXObject("Msxml2.XMLHTTP")  // For Old Microsoft Browsers
    }
    catch (e)
    {
        try
        {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")  // For Microsoft IE 6.0+
        }
        catch (e2)
        {
            xmlHttp = false   // No Browser accepts the XMLHTTP Object then false
        }
    }
    if (!xmlHttp && typeof XMLHttpRequest != 'undefined')
    {
        xmlHttp = new XMLHttpRequest();        //For Mozilla, Opera Browsers
    }
    var url = "/admin/TaskEdit.do?id=" + id + "&command=findDependenciesFor";
    xmlHttp.open("GET", url, true);
    xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlHttp.onreadystatechange = handleServletResponse;
    xmlHttp.send();
}

Here I found that the form is getting submitted and the query string is coming as null.

A: If the for is actually submitted, then the request parameters you see on your server are the inputs inside the form, and not what wrote here...
You should use jQuery, and in the form.submit(), you should construct your own ajax call (example below), and don't forget to return false; to prevent the form from submitting.
You should use jQuery ajax for the ajax call, for the ease of use, and cross browsers compatibility:
function ajaxGetDependentTask(id){
  $.ajax({
    url: '/admin/TaskEdit.do',
    type: 'GET',
    data: {
      id: id,
      command: 'findDependenciesFor'
    },
    success: handleServletResponse,
    error: function(){console.log('something bad just happened');}
  });
}
$('#yourButtonId').on('click', function(){
  var id = $(this).val(); // assuming that's how you get the 'id' for your example code above...
  ajaxGetDependentTask(id);
});
$('#yourFormId').submit(function(){return false;});


text:
Q: Batch-file string builder I want to create a string builder to combine the line contents of a .txt-file by using a batch file so I can import it later on(CSV).
The source file contains lines of information that repeat themselves after for example 3 times. Like this:
Info1 a
Info2 b
Info3 c
Info1 aa
Info2 DD
Info3 ff

The new target file should look like this:
Info1 a; Info2 b; Info3 c
Info1 aa; Info2 dd; Info3 ff

This is my start code:
set OutFile=D:\outfile.txt
if exist %OutFile% del /q %OutFile%
set counter=0;
for /F "tokens=*" %%y in (D:\list.txt) do (
if %counter% == 0 do (
set string=%%y
)
if %counter% == 2 do (
 echo %string%>>%OutFile%
)

if %counter% != 0  && %counter% != 2 do (
set string=%string% and ";" and %%y
)
)

Thanks for your help!

A: I modified a little bit your sourcefile:

*

*Instead of removing the output file if it exists, always create an empty one (the copy command)

*_RepeatCount holds the number of lines when the pattern repeats (change it if the input file format changes)

*I am using delayed expansion

*The algorithm is simple: I iterate to each line of the input file, and add it to a variable that holds the already read lines; every time I read _RepeatCount lines, I dump the variable into the output file and reset it. the last if clause if is for handling cases where the input files doesn't have a number of lines that is multiple of _RepeatCount, they will be dumped in the output file as well.

Here's the code:
@echo off
setlocal enableextensions, enabledelayedexpansion

set OutFile=D:\outfile.txt
copy NUL %OutFile%

set InFile=D:\list.txt

set _RepeatCount=3
set _Index=0

for /F "tokens=*" %%y in (%InFile%) do (
    set /A _Index=_Index + 1
    if !_Index! equ %_RepeatCount% (
        set _Lines=!_Lines!%%y
        set _Index=0
        echo !_Lines! >> %OutFile%
        set _Lines=
    ) else (
        set _Lines=!_Lines!%%y;
    )
)
if "%_Lines%" neq "" (
    echo %_Lines% >> %OutFile%
)


text:
Q: Can't get yuidoc running on Mac OS X Mountain Lion On installing yuidoc I'm getting the following warning.
npm WARN package.json connect@1.9.2 No README.md file found!

When trying to start yuidoc --server later it shows me:
info: (yuidoc): Scanning for yuidoc.json file.
error: (yuidoc): Scanned 5001 directories looking for a yuidoc.json file, something is probably wrong here..

Thanks for help!

A: The warning is nothing to worry about.
The error is that you haven't provided a yuidoc.json file:
http://yui.github.com/yuidoc/args/index.html#json