text:
Q: Converting a comma separated string to array I have been trying to convert a string in array of integers, floats and characters. While I could get it work for integers and floats, there is some problem for characters.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char *s1;
    int k, no=5;
    char* variable = "R1,R2,R3,R4,R5";
    void* value;

    s1 = calloc(no,sizeof(char)*81);
    for (k=0; k<no; k++) s1[k] = strdup(mchar);
    ListChar(variable, s1, no, ",");
    memcpy(value, s1, no*sizeof(char)*81);
    free(s1);

    int i;
    for (i = 0; i < no; i++)
        printf("%s", value[i]);
    printf("\n");
    return 0;
}

In the header file I have
#define mchar "A...(81times)"

Implementation:
int ListChar(char *buf, char *list, int maxloop, char* delim)
{
    int n = 0;
    char *s,*t;
    s= strdup(buf);
    t= strtok(s,delim);
    while ( t && (n<maxloop))
    {
        if (list!=NULL) list[n] =strdup(t);
        n++;
        t=strtok(NULL,delim);
    }
    free(s);
    return(n);
}

During the calloc memory assignment when I watch s1 its 0xsomeadress ""
After the for loop s1 becomes 0xsomeadress "Garbage value 81 times"
When s1 is assigned to list its still reads the same garbage value.
And when list [n] = strdup(t) list[0] reads the first block of garbage value like -21 '\221 ṗ'.
t is getting delimited correctly. I even tried initializing char *s1[81] = {"something"} and looping it on j but it wont work, same problem, and I need to free s1 at the end because this function runs for number of times. I did it for integers and floats by list[n]=atoi(t) it works fine. Can anyone suggest me something?

A: There seems to be a fundamental misunderstanding about how strings work.  Your  s1 clearly needs to be a char ** and the usage of strdup is incorrect.  If s1 is of type char *, then s1[k] is of type char.  But strdup returns a char *, so s1[k] = strdup ... is clearly an error which your compiler ought to warn you about.  Perhaps you want something like:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void * xmalloc(size_t s);

void
ListChar(const char *buf, char **list, int maxloop, int delim)
{
    char set[] = {delim, 0};
    for( int n = 0; n < maxloop; n += 1 ){
        size_t len = strcspn(buf, set);
        list[n] = xmalloc(len + 1);
        memcpy(list[n], buf, len);
        buf += len + 1;
    }
}

int
main(int argc, char **argv)
{
    int delim = ',';
    (void)argc; /* Suppress compiler warning */
    while( *++argv ){
        char **s1;
        int k, num = 1;
        char *input = *argv;
        for( const char *p = input; *p; p += 1 ){
            if( *p == delim ){
                num += 1;
            }
        }
        s1 = xmalloc(num * sizeof *s1);
        ListChar(input, s1, num, delim);
        for( int i = 0; i < num; i += 1 ){
            printf("%s\n", s1[i]);
        }
        free(s1);
    }
    return 0;
}

void *
xmalloc(size_t s)
{
    void *rv = malloc(s);
    if( rv == NULL ){
        perror("malloc");
        exit(EXIT_FAILURE);
    }
    return rv;
}

Note that the above code scans each string twice, which is not ideal. Rather than scanning the string to find the number of delimiters and then parsing the string, it would be better to do both in one pass.  But for the purposes of demonstrating how to break up the string, that seems like unnecessary complexity.  (Though it's actually simpler, IMO)


text:
Q: SQL - Calculate number of days I am trying to calculate the number of days customers pay invoices either early or late.
select
    a.Invoice,
    datediff(day,InvoiceDate,JournalDate) as Days,
    c.DueDays,
    c.Description as Terms

from
    ArInvoice a
    Inner Join ArInvoicePay b on a.Invoice = b.Invoice
    Inner Join TblArTerms c on a.TermsCode = c.TermsCode

This is great for customers with a Date of Invoice term. The problem is for customers with for instance 60 days end of month. I am struggling to come up with a way using the InvoiceDate and using two other fields InvDayOfMonth = '31' and InvMonths = '2' to calculate the number of days.
In laymans terms I need to calculate the number of days from the InvoiceDate until 31 days, add this to the then multiplied InvMonth by 31.
Any pointers would be greatly appreciated.

A: SQL would look like this
SELECT
dateadd(day,-1,
dateadd(month, 2, --Your variable here
--replace getdate with Invoice date, and figure out the 0+month part
convert(DATE, cast(Year(getdate()) as NVARCHAR) + '0'+cast(Month(getdate()) as NVARCHAR) + '01')))

Due to Your Comment the answer is simple then
SELECT
dateadd(day,60,InvoiceDate)
--replace 60 with the number You've already calculated

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pandas read_sql duplicating columns when using both index_col and columns parameters I've got a SQLite database with the table test_data whose columns are:

date
id
kpi
value
run_datetime

I'm using the read_sql function to read in this table, keep only the first 4 columns, and set the first 3 as an index. To do this, I've called the read_sql function in the following way:
conn = sqlalchemy.create_engine('sqlite:///test.db')
data = pd.read_sql(
    sql='test_data',
    con=conn,
    columns=['date', 'id', 'kpi', 'value'],
    index_col=['date', 'id', 'kpi']
)

However, this returns the following:

date__1
id__1
kpi__1
value

date
id
kpi

2021-05-01
0001
kpi_1
2021-05-01
0001
kpi_1
100

kpi_2
2021-05-01
0001
kpi_2
200

kpi_3
2021-05-01
0001
kpi_3
300

This keeps the columns that I want, but it duplicates the 3 I want in the index rather than converting them into the index like I'd expect. I get the same output if I explicitly use the read_sql_table function instead.
So, my questions are...

*

*Is this behaviour expected, or do I have a malformed query?

*If this is a malformed query, how can I fix it?
I can work around this by only using one of the arguments and applying the logic for the other on the DataFrame itself (e.g. only keeping the columns and then calling the set_index method) or by writing the SELECT query explicitly, so I'm not asking for an alternative solution.

MWE
import pandas as pd
import sqlalchemy

def make_data(connection):
    pd.DataFrame(
        data=[
            ['2021-05-01', '0001', 'kpi_1', 100,  '2021-05-01 09:00'],
            ['2021-05-01', '0001', 'kpi_2', 200,  '2021-05-01 09:00'],
            ['2021-05-01', '0001', 'kpi_3', 300,  '2021-05-01 09:00']
        ],
        columns=['date', 'id', 'kpi', 'value', 'run_datetime']
    ).to_sql(
        name='test_data',
        con=connection,
        if_exists='replace',
        index=False
    )

def main():
    conn = sqlalchemy.create_engine('sqlite:///test.db')
    make_data(conn)

    data = pd.read_sql(
        sql='test_data',
        con=conn,
        columns=['date', 'id', 'kpi', 'value'],
        index_col=['date', 'id', 'kpi']
    )
    print(data)

if __name__ == '__main__':
    main()

A: As per van's comment, this was a malformed query -- the columns for the index (index_col) should be distinct to the columns for the DataFrame (columns), so the working query is
conn = sqlalchemy.create_engine('sqlite:///test.db')
data = pd.read_sql(
    sql='test_data',
    con=conn,
    columns=['value'],
    index_col=['date', 'id', 'kpi']
)


text:
Q: How to set up an exposed docker frontend and a non-exposed backend? I have a simple docker network set up with two containers. The frontend has its port mapped 80:80 so that I can access it via localhost in my browser. My backend does not have its port (3000) mapped. I want my frontend to be accessible on my network but do not want my backend to be.
The problem I have run into is that I cannot make requests from my frontend to my backend from the browser. Both containers are on the proper network and can communicate internally.
ex: using curl inside the frontend container provides the expected output from the backend:
curl 10.5.0.4:3000/test
But calling
axios.get(10.5.0.4:3000/test) from the webpage will result in a 404 error.
Is the problem that the axios request is coming from the browser and therefore cannot connect to the docker network? If so is there a solution that does not involve making the backend to be accessible outside the docker network?
Here is my docker-compose file for clarity
services:
  backend:
    build: ./testbe
    image: testbe:dev
    networks:
      test_net:
        ipv4_address: 10.5.0.4

  frontend:
    build: ./testfe
    image: testfe:dev
    networks:
      test_net:
        ipv4_address: 10.5.0.5
    ports:
      - "80:80"

networks:
  test_net:
    driver: bridge
    driver_opts:
      com.docker.network.endable_ipv6: "false"
    ipam:
      driver: default
      config:
        - subnet: 10.5.0.0/5
          gateway: 10.5.0.1

A: You shouldn't use the private IP of the container to call it, but call the name it has on the network.


text:
Q: Plug-in org.eclipse.jdt.ui was unable to load class org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart. Kotlin Plugin not working in Eclipse I'm using eclipse and trying to add a kotlin plugin after installing them in the marketplace. But it seems it's not working even I followed a simple tutorial that it should work (https://www.kotlintutorialblog.com/run-kotlin-program-eclipse-ide/). I'm stuck in step 4 and 5. I need to know why this has happened. My eclipse is portable. I put it in my external driver instead of in the Program Files.
https://i.imgur.com/IdRZ9Sa.png
My Eclipse version: 2021-03 (4.19.0)
Kotlin Plugin: 0.8.21
I want the kotlin plugin to work in eclipse that's all I wanted, thank you.


text:
Q: Syncing query params and state variables in react-redux I am fairly new to the react-redux environment.
Using react-boilerplate for my application.
I am trying to find the right way to sync some redux state variables with query params so that link can be shared with other people.
went through redux-query-sync but it is no longer being maintained.
What I want to sync with the URL query params are the search query string and filters.
Please suggest a good way to implement this in the boilerplate that I am using.
-Thanks

A: Since there is no library to do this I kind of figured my own way hope this helps someone. This is not the most efficient way so feel free to suggest me a better one.
Step 1: Catch the state change:

For this all of your related components should be in a singular container and catch the state change using:
componentDidUpdate(prevProps, prevState, snapshot) {
    if (JSON.stringify(prevProps.search.queryString) !== JSON.stringify(this.props.search.queryString)){
       // make sure to use escape to build the queryParams variable
       this.props.history.push(queryParams, null);
    }
}

Step 2: Get the state when the page is refreshed in reducer.js (if you have one)

use a good parser like query-string
import queryString from 'query-string';
const params = queryString.parse(history.location.search);

Step 3: Load required state variables on componentDidMount

Some state variables are needed to be loaded into the state when that component is mounted you can use componentDidMount in that case (if you are getting into one)


text:
Q: Online parameter estimation for inverse reinforcement learning We have developed a novel interpretable RL paradigm for continuous actions where agents are compositions of trained prototypical agents with affinities for certain strategies; this aids strategy interpretation.
We use hierarchical RL to learn agent strategy composition - as function superpositions -, i.e. we learn the coefficients of a linear combination of the prototypical agents which maximizes the reward function. This linear combination is the interpretation of the combined agent.
In general, inverse RL which tries to recover the reward function is an ill-posed problem. We would like to investigate whether our paradigm may offer an alternative method for directly estimating the weights from online observation of an unknown agent.
For now, we assume the agent is trained using known prototypical agents.
My questions:

*

*What is the goto method for online linear coefficient estimation?

*Under what conditions are these parameters identifiable?
Any pointers to fruitful literature or any other insights are appreciated.
Thank you.


text:
Q: money_format() function showing � instead of local currency symbol (pound) Does anyone have any idea why money_format() is showing � instead of pound sign (£).
The function performs fine on my local server, but when I upload it to my remote server if renders incorrectly.
Does anyone know a solution?

A: You need to use £, not £
A full list of characters affected in this way can be found at http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references

A: Related: php remove/identify this symbol �
Quoted from Gumbo
The character � is the REPLACEMENT CHARACTER (U+FFFD). It is used when there was an error within an UTF code:
FFFD � REPLACEMENT CHARACTER
used to replace an incoming character whose value is unknown or unrepresentable in Unicode


text:
Q: Find occurrences where a comma is separated by numbers using regex I need to find occurrences where a comma is separated by a number on either side.
For example:
SampleString ='A,B,C, 1, 2, 3, 4, G'

I need to replace the commas with all space before and after comma with just a comma(no space). I need to do this only if the comma is separating numbers.
CleanString =re.sub(r([0-9]+)\s?,\s?([0-9]+)' ,r"\g<1>,\g<2>",SampleString)

This output gives me A,B,C, 1,2, 3,4, G.
The output I need is A,B,C, 1,2,3,4, G

A: You can use the following regex:
import re

SampleString = 'A, B,B, M1, 3, 44, 45, 46, 47, G, 1, 33'

CleanString = re.sub(r'(\b\d+)(\s*,\s*)(?=\d+\b)', r'\1,', SampleString)

print(CleanString)

Output:
A, B,B, M1, 3,44,45,46,47, G, 1,33

A: CleanString = re.sub(r"(?<=\d)\s*,\s*(?=\d)", ",", SampleString)

(?<=\d) is a lookbehind that requires one digit (\d) to precede the current position
(?=\d) is a lookahead that requires one digit to follow the current position
You don't need to capture anything, i.e., you don't any extra parentheses. Anyway it may be good to know that lookaheads and lookbehinds are non-capturing (unless they contain parentheses inside).

A: This regex uses lookahead:
((\d+)\s*,\s*)(?=\d)
This matches digits optionally followed by spaces followed by a comma optionally followed by spaces only if that sequence is followed by a digit. So, in the string 1, 2 , 3, the first match is 1,.
import re
SampleString ='A,B,C, 1, 2 , 3 , 4, G'
CleanString = re.sub(r'((\d+)\s*,\s*)(?=\d)', r"\g<2>,", SampleString)
print(CleanString)

Prints:
A,B,C, 1,2,3,4, G


text:
Q: custom payment gateway response leads to white page i'm creating my own payment method and gateway but the payment controller doesn't seem to handle the response of the gateway properly.
the gateway sends one POST-var as response with a html form submitted by javascript to /magento/mygateway/payment/response but then it doesn't lead back to the shop. instead it shows just a white page.
i also tried responding to /magento/index.php/mygateway/payment/response but that just leads to the homepage of the store. both methods place the order successfully but when i view the orders in admin panel it says that they were not paid.
here's the code of the responseAction() function that should be triggered by the response:
public function responseAction() {
    if($this->getRequest()->isPost()) {

        $data = $this->getRequest()->getPost();

        if ($data['valid'] == $order->getId()) $validated = true;

        $orderId = '123'; // Generally sent by gateway

        if($validated) {
            // Payment was successful, so update the order's state, send order email and move to the success page
            $order = Mage::getModel('sales/order');
            $order->loadByIncrementId($orderId);
            $order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true, 'Gateway has authorized the payment.');

            $order->sendNewOrderEmail();
            $order->setEmailSent(true);

            $order->save();

            Mage::getSingleton('checkout/session')->unsQuoteId();

            Mage_Core_Controller_Varien_Action::_redirect('checkout/onepage/success', array('_secure'=>true));
        }
        else {
            // There is a problem in the response we got
            $this->cancelAction();
            Mage_Core_Controller_Varien_Action::_redirect('checkout/onepage/failure', array('_secure'=>true));
        }
    }
    else
        Mage_Core_Controller_Varien_Action::_redirect('');
}

and here's the code of the gateway (it doesn't make any sense, it's only for testing):
<?php
$orderid = $_POST['orderid'];
?>
<form name="mygatewayform" method="post" action="http://kgwshop.intothis.org/magento/mygateway/payment/response">
    <input type="hidden" name="valid" value="<?=$orderid?>">
</form>
<script type="text/javascript">
    document.mygatewayform.submit();
</script>

config.xml:
<?xml version="1.0"?>
<config>
  <modules>
    <Myname_Mygateway>
      <version>0.1.0</version>
    </Myname_Mygateway>
  </modules>
  <global>
    <models>
      <mygateway>
        <class>Myname_Mygateway_Model</class>
      </mygateway>
    </models>
    <helpers>
      <mygateway>
        <class>Myname_Mygateway_Helper</class>
      </mygateway>
    </helpers>
    <blocks>
      <mygateway>
        <class>Myname_Mygateway_Block</class>
      </mygateway>
    </blocks>
  </global>
  <default>
    <payment>
      <mygateway>
        <model>mygateway/standard</model>
        <active>1</active>
        <order_status>pending</order_status>
        <title>My Gateway</title>
        <payment_action>sale</payment_action>
        <allowspecific>0</allowspecific>
        <sort_order>1</sort_order>
      </mygateway>
    </payment>
  </default>
  <frontend>
    <routers>
      <mygateway>
        <use>standard</use>
        <args>
          <module>Myname_Mygateway</module>
          <frontName>mygateway</frontName>
        </args>
      </mygateway>
    </routers>
  </frontend>
</config>

whole PaymentController.php:
<?php

class Myname_Mygateway_PaymentController extends Mage_Core_Controller_Front_Action {
    // The redirect action is triggered when someone places an order
    public function redirectAction() {
        $this->loadLayout();
        $block = $this->getLayout()->createBlock('Mage_Core_Block_Template','mygateway',array('template' => 'mygateway/redirect.phtml'));
        $this->getLayout()->getBlock('content')->append($block);
        $this->renderLayout();
    }

    // The response action is triggered when your gateway sends back a response after processing the customer's payment
    public function responseAction() {
        if($this->getRequest()->isPost()) {

            $data = $this->getRequest()->getPost();

            if ($data['valid'] == $order->getId()) $validated = true;

            $orderId = '123'; // Generally sent by gateway

            if($validated) {
                // Payment was successful, so update the order's state, send order email and move to the success page
                $order = Mage::getModel('sales/order');
                $order->loadByIncrementId($orderId);
                $order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true, 'Gateway has authorized the payment.');

                $order->sendNewOrderEmail();
                $order->setEmailSent(true);

                $order->save();

                Mage::getSingleton('checkout/session')->unsQuoteId();

                Mage_Core_Controller_Varien_Action::_redirect('checkout/onepage/success', array('_secure'=>true));
            }
            else {
                // There is a problem in the response we got
                $this->cancelAction();
                Mage_Core_Controller_Varien_Action::_redirect('checkout/onepage/failure', array('_secure'=>true));
            }
        }
        else
            Mage_Core_Controller_Varien_Action::_redirect('');
    }

    // The cancel action is triggered when an order is to be cancelled
    public function cancelAction() {
        if (Mage::getSingleton('checkout/session')->getLastRealOrderId()) {
            $order = Mage::getModel('sales/order')->loadByIncrementId(Mage::getSingleton('checkout/session')->getLastRealOrderId());
            if($order->getId()) {
                // Flag the order as 'cancelled' and save it
                $order->cancel()->setState(Mage_Sales_Model_Order::STATE_CANCELED, true, 'Gateway has declined the payment.')->save();
            }
        }
    }
}

.htaccess in the same folder as PaymentController.php:
############################################
## uncomment these lines for CGI mode
## make sure to specify the correct cgi php binary file name
## it might be /cgi-bin/php-cgi

#    Action php5-cgi /cgi-bin/php5-cgi
#    AddHandler php5-cgi .php

############################################
## GoDaddy specific options

#   Options -MultiViews

## you might also need to add this line to php.ini
##     cgi.fix_pathinfo = 1
## if it still doesn't work, rename php.ini to php5.ini

############################################
## this line is specific for 1and1 hosting

    #AddType x-mapp-php5 .php
    #AddHandler x-mapp-php5 .php

############################################
## default index file

    DirectoryIndex index.php

<IfModule mod_php5.c>

############################################
## adjust memory limit

#    php_value memory_limit 64M
    php_value memory_limit 256M
    php_value max_execution_time 18000

############################################
## disable magic quotes for php request vars

    php_flag magic_quotes_gpc off

############################################
## disable automatic session start
## before autoload was initialized

    php_flag session.auto_start off

############################################
## enable resulting html compression

    #php_flag zlib.output_compression on

###########################################
# disable user agent verification to not break multiple image upload

    php_flag suhosin.session.cryptua off

###########################################
# turn off compatibility with PHP4 when dealing with objects

    php_flag zend.ze1_compatibility_mode Off

</IfModule>

<IfModule mod_security.c>
###########################################
# disable POST processing to not break multiple image upload

    SecFilterEngine Off
    SecFilterScanPOST Off
</IfModule>

<IfModule mod_deflate.c>

############################################
## enable apache served files compression
## http://developer.yahoo.com/performance/rules.html#gzip

    # Insert filter on all content
    ###SetOutputFilter DEFLATE
    # Insert filter on selected content types only
    #AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript

    # Netscape 4.x has some problems...
    #BrowserMatch ^Mozilla/4 gzip-only-text/html

    # Netscape 4.06-4.08 have some more problems
    #BrowserMatch ^Mozilla/4\.0[678] no-gzip

    # MSIE masquerades as Netscape, but it is fine
    #BrowserMatch \bMSIE !no-gzip !gzip-only-text/html

    # Don't compress images
    #SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary

    # Make sure proxies don't deliver the wrong content
    #Header append Vary User-Agent env=!dont-vary

</IfModule>

<IfModule mod_ssl.c>

############################################
## make HTTPS env vars available for CGI mode

    SSLOptions StdEnvVars

</IfModule>

<IfModule mod_rewrite.c>

############################################
## enable rewrites

    Options +FollowSymLinks
    RewriteEngine on

############################################
## you can put here your magento root folder
## path relative to web root

    #RewriteBase /magento/

############################################
## uncomment next line to enable light API calls processing

#    RewriteRule ^api/([a-z][0-9a-z_]+)/?$ api.php?type=$1 [QSA,L]

############################################
## rewrite API2 calls to api.php (by now it is REST only)

    RewriteRule ^api/rest api.php?type=rest [QSA,L]

############################################
## workaround for HTTP authorization
## in CGI environment

    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

############################################
## TRACE and TRACK HTTP methods disabled to prevent XSS attacks

    RewriteCond %{REQUEST_METHOD} ^TRAC[EK]
    RewriteRule .* - [L,R=405]

############################################
## redirect for mobile user agents

    #RewriteCond %{REQUEST_URI} !^/mobiledirectoryhere/.*$
    #RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC]
    #RewriteRule ^(.*)$ /mobiledirectoryhere/ [L,R=302]

############################################
## always send 404 on missing files in these folders

    RewriteCond %{REQUEST_URI} !^/(media|skin|js)/

############################################
## never rewrite for existing files, directories and links

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l

############################################
## rewrite everything else to index.php

    RewriteRule .* index.php [L]

</IfModule>

############################################
## Prevent character encoding issues from server overrides
## If you still have problems, use the second line instead

    AddDefaultCharset Off
    #AddDefaultCharset UTF-8

<IfModule mod_expires.c>

############################################
## Add default Expires header
## http://developer.yahoo.com/performance/rules.html#expires

    ExpiresDefault "access plus 1 year"

</IfModule>

############################################
## By default allow all access

    Order allow,deny
    Allow from all

###########################################
## Deny access to release notes to prevent disclosure of the installed Magento version

    <Files RELEASE_NOTES.txt>
        order allow,deny
        deny from all
    </Files>

############################################
## If running in cluster environment, uncomment this
## http://developer.yahoo.com/performance/rules.html#etags

    #FileETag none


text:
Q: java reading contents from a text file import java.io.File;
import java.util.Scanner;
import java.lang.*;

public class ReadFile {
public static void main(String[] args) {
int i=0;
String[] myStringArray = new String[]{ };
    try {
         Scanner input = new Scanner(System.in);
         File file = new File("123.txt");

     input = new Scanner(file);
     while (input.hasNextLine()) {
         String line = input.nextLine();
         if(line.contains("int ")){
             System.out.println("found int "+(++i));
             System.out.println(line);
             myStringArray=line.split("[\\s,;]+");
             }
        }
System.out.println(myStringArray.length());
input.close();
} catch (Exception ex) {
      ex.printStackTrace();
      }
    }
}

Why is it showing me error on myStringArray.length()
I wanted to read a text file which had contains as follows:
#include<stdio.h>
#include<conio.h>

void main()
{

int i=5;
int j=9;
int s,t;

s=i+3;
t=j+7;
q=j+4;

cout<<s<<t<<q;
}

I wanted to store all the variables value such as I wanted to store i = 5, j = 9 and then my task was to print the expressions s = i + 3 with the values of i and j.

A: It should be myStringArray.length and not myStringArray.length().

A: Try to use:
  myStringArray.length;

Instead of:
  myStringArray.length()


text:
Q: A problem with conditional statement shorthand I have this Conditional Statement that I am trying to use shorthand.
As you can see when I get on the else I don't know how to make the passwordMatchError.setAttribute("id", "error") to show together with the passwordMatchError.textContent = ("Password does not match. Please retype.");
I tried using the signs +, || and && but didnt work.
Can you guys help me out?
Many thanks.

const checkThePassword = (registration) => {
    let getTheOriginalPassword = registration.password.value; //assign passwords by value, avoid const here in case of unprotected memory
    let getTheRetypedPassword = registration.retypedpassword.value;
    // Simple equality check for retyped password
    getTheOriginalPassword === getTheRetypedPassword ? passwordMatchError.setAttribute("id", "error") :  passwordMatchError.textContent = ("Password does not match. Please retype.");
    // false return is done together with error handling

}

Here is the original code

const checkThePassword = (registration) => {
 let getTheOriginalPassword = registration.password.value; //assign passwords by value, avoid const here in case of unprotected memory
 let getTheRetypedPassword = registration.retypedpassword.value;
 // Simple equality check for retyped password
 if (getTheOriginalPassword === getTheRetypedPassword) {
  return true;
 } else {
  passwordMatchError.setAttribute("id", "error");
  passwordMatchError.textContent = ("Password does not match. Please retype.");
  return false; // false return is done together with error handling
 }
}

A: You could wrap the return parts in parentheses and return finally a boole value.
Please use the explicit programming with an if statement!
const checkThePassword = (registration) => {
    let getTheOriginalPassword = registration.password.value; //assign passwords by value, avoid const here in case of unprotected memory
    let getTheRetypedPassword = registration.retypedpassword.value;
    // Simple equality check for retyped password
    return getTheOriginalPassword === getTheRetypedPassword
        ? (passwordMatchError.setAttribute("id", "error"), true)
        : (passwordMatchError.textContent = ("Password does not match. Please retype."), false);
}

A: If you want to squash it all into one line with the conditional operator, it's possible, because assignments evaluate to expressions (unfortunately), but it's pretty unreadable, I'd highly recommend against it:
getTheOriginalPassword === getTheRetypedPassword
  ? '' // do nothing... unused expression
  : ( // squash two "statements" which can be evaluated as expressions into a single expression:
    passwordMatchError.setAttribute("id", "error"), // use the comma operator
    passwordMatchError.textContent = ("Password does not match. Please retype.")
  )

It's syntactically valid and will do what you're looking for, but it's horrible code. Consider using your original code instead. Best to only use the conditional operator when you want to construct an expression conditionally - if you want to run statements conditionally, use if/else.


text:
Q: sending websocket message greater than 64kB causes Ratchet websocket server to throw 'Underflow exception' i have a websocket server written in php using ratchet websocket, and the clients are written in javascript creating websocket connection to connect to the php websocket server.
Client and server are communicating via json string, i found that when the json message size is greater than 64kB, the ratchet server would throw an 'underflow exception'
'UnderflowException' with message 'Frame must be coalesced before applying mask'
php server code
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Socket;

$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new Socket()
        )
    ),
    8080
);

$server->run();

javascript client
var socket  = new WebSocket('ws://123.123.123.123:8080');

let reader = new FileReader();
reader.onload = function()
{
    sendPackageImageFile(reader.result);
};

reader.onerror = function()
{
    console.log('reader.error');
};

reader.readAsDataURL('some-file');

function sendPackageImageFile(imageFileData)
{
    var message = {};
    message.sender = 'someUser';
    message.action = 'send-package-image';
    message.packer = 'packer';
    message.data = 'some data';
    message.file = imageFileData;
    const js = JSON.stringify(message);
    socket.send(js);
}


text:
Q: LibSVM training error I'm using java version of libsvm (regression) for prediction purposes.
After training my data set, the generated model shows the Support Vectors, but no indication on the training error rate.
I would like to know if it's possible to find the training error of my training set? Is there any function I can call, or a class attribute I can use to find it?
Thank you,

A: You will have to create a svm_problem from your training-set and call svm_predict(..) on that - then compute the MSE (mean squared error) - but note that LibSVM performs quite poor on regression datasets compared to neural networks.


text:
Q: Linear regression with sine/cosine elements How can you derive formula and regression coefficients for a regression model of a form $y(x)= A + B\, x + C\, \cos (2 \pi x) + D\,  \sin (2 \pi x)$? I know that there are automatic tools who can do that if I provide the data but I need a formula and a procedure. Thank you in advance.

A: You simply compute $x_c=\cos(2\pi x)$ and $x_s=\sin(2\pi x)$ and perform a plain multiple linear regression of $y$ on $x, x_c,$ and $x_s$.
That is you supply the original $x$ and the two calculated predictors as if you had three independent variables for your regression, so your now-linear model is:
$$Y = \alpha + \beta x +\gamma x_c + \delta x_s+\varepsilon$$
This same idea applies to any transformation of the predictors. You can fit a regression of the form $y = \beta_0  + \beta_1 s_1(x_1) + \beta_2 s_2(x_2) +...+ \beta_k s_k(x_k)+\varepsilon$ for transformations $s_1$, ... $s_k$ by supplying $s_0(x_1),  s_2(x_2), ..., s_k(x_k)$ as predictors.
So for example, $y = \beta_0  + \beta_1 \log(x_1) + \beta_2 \exp(x_1) + \beta_3 (x_2\log x_2) + \beta_4 \sqrt{x_3x_4} +\varepsilon$ would be fitted by supplying
$\log(x_1),$ $\exp(x_1),$ $(x_2\log x_2),$ and $\sqrt{x_3x_4}$ as predictors (IVs) to linear regression software.
The regression is just fitted as normal to the new set of predictors and the coefficients are those for the original equation.
See, for example the answer here: regression that creates $x\log(x)$ functions, which details a different specific example.

A: You can find list of methods used for solving of linear regression problems in this article from Do Q Lee:
Numerically efficient methods for solving Least-Squares problems
Most commonly used methods for these kind of problems are:

*

*Normal equations method using Cholesky factorization. It is the fastest method but numerically unstable. Normal equations is basically system of linear equations. You get this system by computing partial derivations using every predictor and setting this partial derivation to zero. This corresponds to finding global minimum of error term.

*QR factorization. More accurate and broadly applicable, but may fail when matrix of linear system of equations is nearly rank-deficient.

*Singular value decomposition. It is expensive to compute, but is numerically stable and can handle rank deficiency. You can use tool like Matlab to compute SVD of choosen matrix. If you are deploying customized solution you can use software package like LAPACK or its Intel clone which is heavily optimised using x86 assembler and from september 2015 completely free for everyone.
In all three cases you need to find a solution to system of linear equations. There are not analytical formulas for regression coefficient except for very simple cases like for example line fitting.


text:
Q: jQuery Bootgrid rendering issues I'm trying to use Bootgrid in a project of mine, and I want it to appear exactly as the example in http://www.jquery-bootgrid.com/Examples#data-api :

However, when I wrote my own implementation, it rendered differently, as shown below:

Please notice the misaligned search icon, and the absence of borders in every button (search, refresh, items per page, column selector and pages).
This is the source HTML:
<!DOCTYPE html>

    <title>Test</title>

    <meta http-equiv="content-type"
          content="text/html;charset=UTF-8" />

    <meta http-equiv="X-UA-Compatible"
          content="ie=edge">

    <meta name="viewport"
          content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet"
          href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"
          integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS"
          crossorigin="anonymous">

    <link rel="stylesheet"
          href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"
          integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN"
          crossorigin="anonymous">

    <link rel="stylesheet"
          href="https://cdnjs.cloudflare.com/ajax/libs/jquery-bootgrid/1.3.1/jquery.bootgrid.min.css"
          integrity="sha256-i397iDijTcJqMf2j733J1b+WKakC2U8Y3k2eMScEugA="
          crossorigin="anonymous" />

                    ID
                    Sender
                    Received

Both were rendered in the same browser (Firefox 64.0.2 64-bit, Windows 10).
I would like to know what I'm doing wrong here... Are my JS and CSS references correct? Is there something missing?

A: it's not your fault!
It's a little too late but maybe the answer can be useful for other people: I have fixed the issue. I have download the last bootgrid version (v1.3.1) and I have changed the following code in jquery.bootgrid.js
search: "

<input type=\"text\" class=\"{{css.searchField}}\" placeholder=\"{{lbl.search}}\" />

",

and I have add in jquery.bootgrid.css this code
ul.pagination li a {
    position: relative;
    display: block;
    padding: .5rem .75rem;
    margin-left: -1px;
    line-height: 1.25;
    color: #007bff;
    background-color: #fff;
    border: 1px solid #dee2e6;
}
ul.pagination li.active a {
    z-index: 1;
    color: #fff;
    background-color: #2196f3;
    border-color: #2196f3;
}
.btn-default {
    background-color: #f4f4f4;
    color: #444;
    border-color: #ddd;
}

in my case now the library work very well with bootstrap 4!
Best regard, m.


text:
Q: É possível desenvolver multiplataforma mobile usando Java? Estou migrando o desenvolvimento dos meus aplicativos para Java para construir aplicativos nativos para Android. Gostaria de expandir meus aplicativos para outras plataformas, como iOS e Windows Phone. É possível fazer isto com Java?

A: Procure aqui: http://mobile-frameworks-comparison-chart.com/
No momento que procurei, encontrei três frameworks:

*

*eMobc

*Kendo UI

*Mono for Android

Porém isso não é garantia que a linguagem nativa seja mantida no Android (será nativo, mas você não codificará diretamente com a API do Android e sim com classes fornecidas pelo framework, que poderão inclusive ser convertidas para um formato intermediário).
Procurando por coisas como "cross platform java" encontrei também essas opções:
https://www.codenameone.com/
http://www.oracle.com/technetwork/developer-tools/maf/overview/index.html
https://robovm.com/
http://juniversal.org/

A: Tem o [Tabris]
http://www.infoq.com/br/news/2013/09/tabris-mobile-multiplataforma
Porém o Tabris é voltado para empresa e tem a licença paga: "O Tabris não é um framework de código aberto, mas as licenças corporativas dão acesso aos fontes."
Link: http://developer.eclipsesource.com/tabris/

A: Honestamente, não acredito que você consiga aproveitar o código nativo Java para, digamos compilar direto para iOS ou Windows Phone. De alguma forma você vai sempre ter que adaptar seu código para atender alguma funcionalidade específica do sistema.
O que você consegue é usar frameworks, que geralmente vão ser plataformas híbridas que usam html e js, como o pessoal já mencionou. Essa é a forma mais rápida, e basicamente o aplicativo roda como se fosse uma pagina web na plataforma (na maioria deles), só que o usuário abre o app no lugar de acessar um endereço.
Outra solução seria usar uma linguagem que consiga 'buildar' para outras plataformas mobile. como GO, mas como mencionado no artigo pode não valer a pena, por que sempre vai ter um impacto de alguma forma (e não é java), interface não nativa, ou código não nativo do android, por exemplo. Acho que C# vai pelo mesmo caminho.


text:
Q: "Missing argument in parameter list" in Azure Devops Pipeline with AzurePowerShell@5 In an Azure devops pipeline, I am trying to execute a powershell script from a file.
- task: AzurePowerShell@5
  displayName: 'AzurePowershell script'
    inputs:
      azureSubscription: 'MyServiceConnection'
      ScriptType: FilePath
      ScriptPath: '$(System.DefaultWorkingDirectory)/path-to-script.ps1'
      ScriptArguments:  -firstParam "test"
      azurePowerShellVersion: LatestVersion

The issue is that I keep getting the following error:
Missing argument in parameter list.
At D:\a\_temp\a05fb35e-757c-4a3a-8729-*******.ps1:48 char:60
+ . 'D:\a\1\s\path-to-script.ps1' -firstParam "test"
+                                                            ~
The string is missing the terminator: ".
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : MissingArgument

I simplified my script to the point of having only a Write-Host inside to be sure it did not come from it, but at the end the goal is to use the pre-deployment script provided by microsoft for Azure data factories here.
param
(
   [parameter(Mandatory = $false)] [String] $firstParam
)

Write-Host $firstParam

I also tried using a PowerShell@2 and AzurePowerShell@4 tasks instead of the AzurePowerShell@5 and there it worked. So the problem seems to be only when using AzurePowerShell@5.
Do you have an idea of what I am doing wrong ?


text:
Q: Can declare your JSON Schema by a reference to type? I am trying to validate a small bit of JSON like:
{
    "success": true,
    "message": "all's good!"
}

which works with the schema:
{
    "type": "object",
    "properties": {
        "success": { "type": "boolean" },
        "message": { "type": "string"  }
    }
}

however it fails with the schema
{
    "definitions": {
        "response": {
            "type": "object",
            "properties": {
                "success": { "type": "boolean" },
                "message": { "type": "string"  }
            }
        }
    },

    "type": { "$ref": "#/definitions/response" }
}

with the error

java.lang.AssertionError: schema resource:/json-schema/sample.schema.json was > invalid: fatal: invalid JSON Schema, cannot continue
  Syntax errors:

[ {
    "level" : "error",
    "message" : "value has incorrect type (found object, expected one of [array, string])",
    "domain" : "syntax",
    "schema" : {
        "loadingURI" : "resource:/json-schema/sample.schema.json#",
        "pointer" : ""
    },
    "keyword" : "type",
    "found" : "object",
    "expected" : [ "array", "string" ]
} ]

level: "fatal"

are you not allowed to use a reference for a type outside the definitions section? My motivation is that this is a response to a singular case, but there are cases where this structure is nested in others as well.
If it matters I'm using json-schema-validator version 2.2.6.

PS - this is a simplified example, the actual schema is more complicated as to justify why reuse and not copying and pasting is desirable.

A: You can use "id" and "$ref".
id for identifying, e.g.:
{
    "type": "object",
      "id": "#response",
      "properties": {
        "success": { "type": "boolean" },
        "message": { "type": "string"  }
       }
  }
}

And then you use $ref, e.g.:
"some": { "$ref": "#response" }

or external ref:
"ext": { "$ref": "http://url.com#response" }

See
http://json-schema.org/latest/json-schema-core.html#anchor27

A: The value of the type keyword must be a string of the name of one of the JSON primitave types (e.g. "string", "array", etc.), or an array of these strings.  That is what the error message is saying.  Keyword type must be a string or an array.  The closest thing to what I think you are trying to do is this ...
{
    "definitions": {
        "response": {
            "type": "object",
            "properties": {
                "success": { "type": "boolean" },
                "message": { "type": "string"  }
            }
        }
    },
    "allOf": [{ "$ref": "#/definitions/response" }]
}

A: You should declare your definition in it's own file, and they have your types refer to that file reference. See How to manage multiple JSON schema files? for details.


text:
Q: How to overwrite function using prototype in javascript? In the following example I expect that createProduct function will be overwritten. But the result is the error.
var AbstractFactory = function(){
  this.createProduct = function(){
    throw new Error("The createProduct() method has not been implemented.");
  }
}

AbstractFactory.prototype.createProduct = function(){
  console.log('The method has been overwriten successfully');
};

var factory = new AbstractFactory();
factory.createProduct();

A: The search for properties starts with the object itself, and only when no property is found is the prototype checked. Thus, the first "createProduct" function found on your "factory" object is the error function. If you initialize the object and the prototype in the other order, then you'll get the results you expect.
Note that the properties on the prototype object do not cause properties to come into existence on instance objects created with the constructor.

A: The problem is that there is no such thing as Abstraction in JavaScript. One way you can implement what you want is to use a more modular approach. When you create the factory object, you can pass a function into the AbstractFactory function that will override the createProduct function.
var AbstractFactory = function(func){
  this.createProduct = func || function(){
    throw new Error("The createProduct() method has not been implemented.");
  }
}

var factory = new AbstractFactory(function() {
  console.log('The method has been overwriten successfully');
});
factory.createProduct();  // The method has been overwriten successfully

You also might want to check first that func is a function before assigning it to createProduct.

A: Another example to help a little:
Override using a config to implement the object.
var AbstractFactory = function(config){
  this.init(config)
}

AbstractFactory.prototype ={
createProduct : function(){
    console.log('The method has been overwriten successfully');
},
init : function(config){
    console.log("Start my object")
    if(typeof config.createProduct === "function"){
        this.createProduct = config.createProduct;
    }
}
}
var myConfig = {
createProduct : function(){
    throw new Error("The createProduct() method has not been implemented.");
}
}
var factory = new AbstractFactory(myConfig);
factory.createProduct()


text:
Q: Help on LateX Diagram using TikZ package I'm new to Latex and I would like to know if you could help me with this diagram. Thank you in advance!

A: A quick proposal with some comments. Now, it's time to read this question.
\documentclass[tikz]{standalone}
\usetikzlibrary{shapes,positioning}
\begin{document}
\begin{tikzpicture}[>=stealth]
\sffamily
% The main nodes
\node[minimum height=1.5cm,minimum width=2cm,text centered,draw] (a) {Traning};
\node[minimum height=1.5cm,minimum width=2cm,text centered,draw,right=2cm of a] (b) {Prediction};
% The arrow in the middle
\draw[->] (a)--(b) node[midway,above,align=center,font=\footnotesize] (mid) {Model\\Parameter};
% The ellipse node at the bottom needs `shapes' library
\node[below=1.5cm of mid,ellipse,draw] (mod) {Model};
\draw[->] (mod) -| (a); % Read https://tex.stackexchange.com/q/481195/156344
\draw[->] (mod) -| (b); %
% The outside arrows: take care of the direction of the arrow
% Read more in https://tex.stackexchange.com/q/66094/156344
\draw[<-] (a.west) -- ++ (-1,0) node[left,align=center,font=\footnotesize] {Ground\\Truth};
\draw[->] (b.east) -- ++ (1,0) node[right,font=\footnotesize] {Prediction};
\draw[<-] (a.north) -- ++ (0,1) node[above] {Observation};
\draw[<-] (b.north) -- ++ (0,1) node[above] {Observation};
\end{tikzpicture}
\end{document}


text:
Q: how to invoke a method from an Entry Widget in Ruby Tk I'm looking for an option or a way to bind an event, which invokes a method from an Entry-Widget.
Like the command option for button-widgets: command { method } or
like binding an event for combobox-widgets:
$combobox.bind("<ComboboxSelected>") { method }
Now I'm looking for something similar for Entry-Widgets. I want to invoke a method every time an entry (value) has been edited. That's my initial situation:
$foo = TkVariable.new
$entry = Tk::Tile::Entry.new(parent) {
  validate 'key'; validatecommand method; textvariable $foo
  }

validatecommand works only at the first time.

A: If you change the content of the widget during the validation callback and still want to have a validation callback applied in the future, you must re-apply the validation callback. This is documented (for the core Tk version of this, see the end of the validation section of the entry docs) but pretty obscure, to be fair.
Use Tk::after.idle to schedule some code to reapply the validation callback inside the validation callback.


text:
Q: How do I install MATLAB R2012b via the ISO file? I want a quick and simple tutorial on "install MATLAB R2012b via the ISO file on my ubuntu 12.10". As you know i have the iso file. Consider that i'm new to linux and ubuntu.
Help me please!

A: Best solution is to try an alternative. QtOctave. It works almost fine for me. But if you want to definitely use Matlab, the long but perfectly working solution is to install XP through VirtualBox and get Matlab running in seamless mode.


text:
Q: Regex to catch comma-separated decimal numbers not inside latex command I am trying to create a regex to catch comma-separated decimal numbers not inside LaTeX command \num{}.
Here are examples of what I want to catch:
2,47
12,67
\mathbf{12,76}

Here are examples that I don't want to catch:
\num{2,76}
\num{12,76}

I tried this regex but it doesn't work.
(?<!num\{)(\d*\,\d*)

Thanks!

A: You could prepend the pattern with a word boundary and if you want to exclude multiple patterns, you could add another lookbehind.
Note that you don't have to escapte the { and the , and using \d* matches 0 or more digits.
\b(?<!num{)(?<!SI{)\d+,\d+

See a regex demo


text:
Q: Recovering source code of uncommited new file after running unit test in Xcode In Xcode, I added a new file with unit tests. I somehow did not commit the file and now the file is empty. I did run the unit tests a few times and was wondering if could recover the Swift source file from Xcode (e.g. temp files?)

A: Since Git is not involved (the file was not added to the index or committed), check if Time Machine has a backup of your file.
IF Time Machine was enabled, you might recover your file that way.


text:
Q: Watson Assistant Api calls count We have developed a watson assistant chatbot and integrated with client application. Now we want know how many times each user calling watson service from client application and its billing details per person.
We tried using watson settings(passing user id and customer id as parameter ) but we are not getting the per user details , we only got total user count details.
Please let me know how we can achieve this from application side or any other alternative approaches.
Code:
version_date: '2018-02-16',
version: 'v1',
context : {
    metadata : {
       "user_id": "{1234}"
       }
     },
 headers: {'X-Watson-Metadata':'customer_id=user777;customer_id=xyz'}
 });

A: You need to send the user_id and other information with each call to the message API. See the V2 API and its message method for the structure of the context object.
The message method is supported by the various SDKs (Node.js, Python, ...). Before making the call, you would need to make sure that the user_id information is added to the context object. The code that you shared seems to indicate that you only passed the information on the initialization.
Once the user_id is sent, the graphs described in this overview are generated. For other analytics you would need to use the log files. Obtain the logs (download them) and run your custom-analytics on them. AFAIK the Watson Assistant analytics only have averages across users.


text:
Q: Why does the Mac OS X Finder append " copy" to a filename when duplicating it but adds a number to it (2, 3, etc…) if it's copied via drag and drop? The title says it all. Not much of an issue as much as I am curious about some Mac OS X Finder behavior I just noticed today and if there is any documentation on this behavior.
In this first screenshot below, I simply duplicated the folder "Pics" via Command ⌘+D—or via "Duplicate" by right clicking on the folder—the folder is copied with " copy" appended to the name to make it "Pics copy":

But if I selected that same "Pics" folder and the dragged and dropped it on the desktop, the new copy would be named "Pics 2"; and if I further copied "Pics 2" it would be incremented to "Pics 3" and so on:

But then… If I copied that "Pics copy" folder again Command ⌘+D—or via "Duplicate" by right clicking on the folder—instead of getting "Pics copy copy" it is now incrementing so I now get "Pics copy 2":

So, what is up with this?

*

*The first copy of a folder without the word " copy" appended to it gets the word " copy" appended to it.

*Copies made by drag and drop just get a number incremented next to the folder name.

*But any copies of the folder with  word " copy" appended to it then get the number incremented.

Shouldn't it just all be a number incrimination at this point? Or am I noticing an odd evolution in user experience on Mac OS X where someone at sometime just wanted " copy" appended but then the incrementation issue was mixed in since how many " copy copy copy" things can one filename endure?
Would like to know if there is any official Apple Finder documentation on this. Or perhaps someone whose history with Mac OS X goes back to the good old days could possibly explain this with some clear references.

A: When the Finder appends "copy" to the name of a newly created duplicate of an object, the user can infer that the actual contents of the original and the duplicate are the same, at least initially.  When the Finder instead adds a number to the object name, it is intended only to disambiguate two otherwise identical names within the same container, and the user should not infer that the actual contents of the two objects are same (although they might be)...
BTW, this behavior goes back to at least System 7.5, as described on pg. 169 in "Macworld System 7.5 Bible, 3rd Edition" 1994, by Lon Poole, ISBN 1-56884-098-5.  I don't think finding an exact published reference from Apple is going to be easy. I looked thru my copies of Apple's "Inside Macintosh, Vols. 1-6", 1985, and "Macintosh Human Interface Guidelines", 1992, developer docs, but no luck.


text:
Q: Using RSAPI to save JSON into Core Data I'm trying to parse JSON from a web service to Core Data. I've looked at the RSAPI library but I can't really understand how to use it in my case. What I used until now to get my JSON data was: json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; NSData *data = [NSData dataWithContentsOfURL:url]; and then display it as an array in my tableview. Any suggestions on how to save the JSON data into Core Data for my custom entity?

A: The Easy/Dangerous Way
Cocoa provides a method that makes this much, much simpler. Thanks to key-value coding there's a method in NSObject that reduces the above to a single line:
[myObj setValuesForKeysWithDictionary:jsonDict];

This will run through key/value pairs in jsonDict and set the same key/value pairs on myObj. The only caveat is that the key names must match, but that shouldn't be a problem assuming you've named them the same in your data model.
Actually there's one more caveat, and it's a biggie. In this method, the keys contained in the dictionary determine what keys are used on the managed object. But what if the dictionary contains a key that's not part of the entity description? Then your app crashes with an error about how the object is not key-value coding compliant for the key. Using this method here puts your app's stability at the mercy of the web service you're using. If you don't have absolute control over the web service, you're running serious risks using this method here. We can do better.
Inspecting Managed Objects
Since we're using Core Data, we can use NSEntityDescription to inspect a managed object's attributes and turn the logic above around. Instead of using the incoming dictionary to determine what key/value pairs to use, we can use the managed object.
You can look up the entity description for a managed object by asking for its entity. That gives you an NSEntityDescription which you can then ask for all kinds of useful information, like what attributes exist. That leads to a safer approach when converting from JSON:
NSDictionary *attributes = [[myObj entity] attributesByName];
for (NSString *attribute in attributes) {
id value = [jsonDict objectForKey:attribute];
if (value == nil) {
    continue;
}
[myObj setValue:value forKey:attribute];
}

This code iterates over the entity's attributes, looks up a key in the dictionary for each of them, and applies that key/value pair to the managed object. That's still nice and generic, and has the advantage that changes to incoming data won't crash the app any more. It looks up values in the dictionary only for attributes that actually exist in the entity description. Extra dictionary keys are simply ignored.
The check for nil is there because the code does hit all of the entity's attributes. If the entity has any attributes that aren't present in the incoming data (a "favorites" flag, for example) the code would end up setting a nil value for the attribute. That could lead to accidentally wiping out data that you really want to keep.
Handling Broken and Inconsistent JSON
The JSON standard is quite clear about how to distinguish strings from numbers– basically, strings are surrounded by quotes and numbers are not. JSON web services however, are not always good about following this requirement. And even when they are, they are not always consistent from one record to another.
An example, similar to one I encountered recently: Size information for clothing. Sizes are provided by the web service and are typically something like "30-32″, "34-36″, etc. These are correctly quoted as strings in the JSON, and the app saves them as string attributes and displays them to the user as is.
But sometimes the size just has one number, e.g. "8″, "10″, etc. In this case the server drops the quotes, making them numbers. My JSON parser correctly produces an NSNumber. Only I want to save this in my entity's string attribute! I can use Objective-C introspection to see if I received an NSString or an NSNumber from my JSON parser, but I also need to know what type the managed object expects for the property. I briefly considered breaking my JSON parser so that it would always return NSString, so at least I would know what to expect from it. Fortunately NSEntityDescription came to the rescue again.
Besides asking the entity description what its attribute names are, you can also inquire about the attribute types configured in the Core Data model. This is returned as an NSAttributeType. Using this, we can expand the code above to handle mismatched data types. It's probably a good idea to abstract the code for easy reuse, too, so I'll put it in a category on NSManagedObject:
@implementation NSManagedObject (safeSetValuesKeysWithDictionary)

- (void)safeSetValuesForKeysWithDictionary:(NSDictionary *)keyedValues

{
    NSDictionary *attributes = [[self entity] attributesByName];
    for (NSString *attribute in attributes) {
        id value = [keyedValues objectForKey:attribute];
        if (value == nil) {
            // Don't attempt to set nil, or you'll overwite values in self that aren't present in keyedValues
            continue;
        }
        NSAttributeType attributeType = [[attributes objectForKey:attribute] attributeType];
        if ((attributeType == NSStringAttributeType) && ([value isKindOfClass:[NSNumber class]])) {
            value = [value stringValue];
        } else if (((attributeType == NSInteger16AttributeType) || (attributeType == NSInteger32AttributeType) || (attributeType == NSInteger64AttributeType) || (attributeType == NSBooleanAttributeType)) && ([value isKindOfClass:[NSString class]])) {
            value = [NSNumber numberWithInteger:[value  integerValue]];
        } else if ((attributeType == NSFloatAttributeType) && ([value isKindOfClass:[NSString class]])) {
            value = [NSNumber numberWithDouble:[value doubleValue]];
        }
        [self setValue:value forKey:attribute];
    }
}
@end

This code inspects the types of both the value found in the dictionary we created from the incoming JSON and the attribute on the managed object, and if there's a string/number mismatch it modifies the value to make sure it matches what's expected.
This is getting pretty useful. Not only is it a generic JSON-to-NSManagedObject conversion, it also handles mismatches between numeric and string types without needing any entity-specific information. It could be even better, though.
Handling Dates
JSON does not have a date type, but dates are nevertheless common in JSON. They're just represented as strings using one date format or another. Only you probably want an NSDate, not a string. NSDateFormatter is really useful here, but wouldn't it be nice to make the date conversion generic as well, so you don't need to special-case your date attribute? Can you see where I'm going with this?
Having written the category method above, it's not much more work to add an optional NSDateFormatter argument, and then to use it whenever an entity's attribute expects a date. This modified version adds that argument, and an extra case to the "else … if" chain:
@implementation NSManagedObject (safeSetValuesKeysWithDictionary)

- (void)safeSetValuesForKeysWithDictionary:(NSDictionary *)keyedValues dateFormatter:(NSDateFormatter *)dateFormatter
{
    NSDictionary *attributes = [[self entity] attributesByName];
    for (NSString *attribute in attributes) {
        id value = [keyedValues objectForKey:attribute];
        if (value == nil) {
            continue;
        }
        NSAttributeType attributeType = [[attributes objectForKey:attribute] attributeType];
        if ((attributeType == NSStringAttributeType) && ([value isKindOfClass:[NSNumber class]])) {
            value = [value stringValue];
        } else if (((attributeType == NSInteger16AttributeType) || (attributeType == NSInteger32AttributeType) || (attributeType == NSInteger64AttributeType) || (attributeType == NSBooleanAttributeType)) && ([value isKindOfClass:[NSString class]])) {
            value = [NSNumber numberWithInteger:[value integerValue]];
        } else if ((attributeType == NSFloatAttributeType) &&  ([value isKindOfClass:[NSString class]])) {
            value = [NSNumber numberWithDouble:[value doubleValue]];
        } else if ((attributeType == NSDateAttributeType) && ([value isKindOfClass:[NSString class]]) && (dateFormatter != nil)) {
            value = [dateFormatter dateFromString:value];
        }
        [self setValue:value forKey:attribute];
    }
}
@end


text:
Q: Android keystore Short read of DER length I'm  trying to use gitlab ci/cd for my android project. I created the pipeline but i'm facing this error that says "Short read of DER length" for my keystore (jks) file. I don't know what I'm doing wrong. All the examples showing the exact pipeline.
this the pipeline:
image: openjdk:11-jdk

variables:

  # ANDROID_COMPILE_SDK is the version of Android you're compiling with.
  # It should match compileSdkVersion.
  ANDROID_COMPILE_SDK: "32"

  # ANDROID_BUILD_TOOLS is the version of the Android build tools you are using.
  # It should match buildToolsVersion.
  ANDROID_BUILD_TOOLS: "33.0.0"

  # It's what version of the command line tools we're going to download from the official site.
  # Official Site-> https://developer.android.com/studio/index.html
  # There, look down below at the cli tools only, sdk tools package is of format:
  #        commandlinetools-os_type-ANDROID_SDK_TOOLS_latest.zip
  # when the script was last modified for latest compileSdkVersion, it was which is written down below
  ANDROID_SDK_TOOLS: "8512546"

# Packages installation before running script
before_script:
  - apt-get --quiet update --yes
  - apt-get --quiet install --yes wget tar unzip lib32stdc++6 lib32z1

  # Setup path as ANDROID_HOME for moving/exporting the downloaded sdk into it
  - export ANDROID_HOME="${PWD}/android-home"
  # Create a new directory at specified location
  - install -d $ANDROID_HOME
  # Here we are installing androidSDK tools from official source,
  # (the key thing here is the url from where you are downloading these sdk tool for command line, so please do note this url pattern there and here as well)
  # after that unzipping those tools and
  # then running a series of SDK manager commands to install necessary android SDK packages that'll allow the app to build
  - wget --output-document=$ANDROID_HOME/cmdline-tools.zip https://dl.google.com/android/repository/commandlinetools-linux-${ANDROID_SDK_TOOLS}_latest.zip
  # move to the archive at ANDROID_HOME
  - pushd $ANDROID_HOME
  - unzip -d cmdline-tools cmdline-tools.zip
  - pushd cmdline-tools
  # since commandline tools version 7583922 the root folder is named "cmdline-tools" so we rename it if necessary
  - mv cmdline-tools tools || true
  - popd
  - popd
  - export PATH=$PATH:${ANDROID_HOME}/cmdline-tools/tools/bin/

  # Nothing fancy here, just checking sdkManager version
  - sdkmanager --version

  # use yes to accept all licenses
  - yes | sdkmanager --licenses || true
  - sdkmanager "platforms;android-${ANDROID_COMPILE_SDK}"
  - sdkmanager "platform-tools"
  - sdkmanager "build-tools;${ANDROID_BUILD_TOOLS}"

  # Not necessary, but just for surity
  - chmod +x ./gradlew

stages:
  - build
  - test

# lintDebug:
#   stage: build
#   script:
#     - ./gradlew clean
#     - ./gradlew -Pci --stacktrace --warning-mode=all --console=plain :app:lintDebug -PbuildDir=lint

assembleRelease:
  stage: build
  script:
    - echo -n ${KEY_STORE_FILE} | base64 -d > straiberry.keystore
    - echo "storeFile=../straiberry.keystore" >> keystore.properties
    - echo "storePassword=${STORE_PASSWORD}" >> keystore.properties
    - echo "keyAlias=${KEY_ALIAS}" >> keystore.properties
    - echo "keyPassword=${KEY_PASSWORD}" >> keystore.properties
    - ./gradlew clean --stacktrace --warning-mode=all
    - ./gradlew assembleRelease --stacktrace --warning-mode=all
  artifacts:
    paths:
    - straiberry.keystore
    - keystore.properties
    - app/release

# debugTests:
#   stage: test
#   script:
#     - ./gradlew -Pci --console=plain :app:testDebug

I encrypted my keystore to base64 and save it in gitlab variables with type of file.

But i'm facing this error:
Caused by: com.android.ide.common.signing.KeytoolException: Failed to read key  from store "/builds/straiberry/client-apps/android-app/straiberry.keystore": Short read of DER length

A: The problem was the variables in gitlab ci/cd was protected. When variables are protected only the protected branch can read them. My branch wasn't protected so variables was empty when calling them.


text:
Q: python app engine Model query for models in the same group I have transactional Groups of entities of type db.Model that have a parent defined. I want to query the datastore to only return models that are in the same group. Currently I'm querying all objects of a 'Kind' then removing those that don't have the same root entity.
Is there a cleaner way to do this - I can't see one in the sdk.
for example:
from google.appengine.ext import db

class ParentObject(db.Model):
  ....

class ChildObject(db.Model):
  ....

parent1 = ParentObject()
parent2 = ParentObject()
child1 = ChildObject(parent=parent1)
child2 = ChildObject(parent=parent2)
child3 = ChildObject(parent=parent1)

I want to run a query that returns child1 and child3 because they have the same parent.

A: I think this is what you are looking for.
get_chlids=ChildObject.all().ancestor(parent1)

To know more about modeling in appengine. You can have a look here

A: class TestFamilyTree(unittest.TestCase):

def test_family_tree(self):
  parent1 = ParentObject()
  parent1.put()
  parent2 = ParentObject()
  parent2.put()
  child1 = ChildObject(parent=parent1)
  child1.put()
  child2 = ChildObject(parent=parent2)
  child2.put()
  child3 = ChildObject(parent=parent1)
  child3.put()
  query = ChildObject.all()
  query.ancestor(child1.parent())
  siblings = query.fetch(100)
  self.assertEqual(len(siblings),2)


text:
Q: How can I get AWS cloudwatch logs into GCP stack driver logs viewer? I have set up the "connector account" thing in Stackdriver, and I'm able to see metrics in GCP, which is super cool! I would now like to also get all cloudwatch logs into google's logging tool. Can this be done with the connector account as well? Or will I have to write a lambda to ship those off?

A: You can integrate AWS CloudWatch to send metrics to the Google StackDriver. For more information please read these documentation [1][2].
Regarding your Lamba question I found this stackoverflow link that might be helpful. I would also recommend reviewing the following best practice when using a Stackdriver account to monitor any number of GCP projects and AWS accounts.


text:
Q: Constructing function tangent to $h(x)$ How do you construct a function $T(x;a)$ for the tangent line to the curve $(sin(4x)+2)^{cos(e^x)} - 1.25$ at the point $x=a=2.2$.
Also shown steps would be much appreciated as I don't want just the answer but rather learn it. Thanks.

A: Hint:
The 1st order Taylor series of $h(x)$ about $x = a$,
$$T(x;a) = h(a) + h'(a) (x-a),$$
happens to meet the tangent line to $h(x)$ in $x=a$. Note that this is the point-slope formula for a line given $a$ and $h'(a)$ (slope at $x = a$).
Here is a plot of what I am talking about:
http://www4b.wolframalpha.com/Calculate/MSP/MSP16911bg8ff09gib89a36000049399ii8bef97ahf?MSPStoreType=image/gif&s=32&w=470.&h=179.&cdf=RangeControl
SPOILER: $T(x) = 0.41694 - 0.9088 (x-2.2)$ is your solution $T(x;2.2)$.

A: Hint : The derivate at x = 2.2 is equal to the slope of the tangent at the
       point ( 2.2 / f(2.2) )


text:
Q: Two ways of using offsets in memory addressing For accessing arrays, I have the seen the following two notations used quite often:
# Addressing in the general form of:
#  address_or_offset(%base_or_offset, %index, scale)

# (1) using a label, which resolves to an address
movzwq myarray(, %rdi, 2), %rbx           # 0x400078

# (2) using an offset based on a register, usually %rbp
movzwq -8(%rbp, %rdi, 2), %rcx

In the first form it uses the notation of address(offset, index, scale) and in the second it uses the notation of offset(base, index, scale). My question is whether it is every practical to use the first notation with including an index register, something like:
movzwq myarray(%r11, %rdi, 2), %rbx

Of is that never used, and it's just always left blank (like in the first example) when using that address(, index, scale) notation?
Finally, is offset/base and address/offset just two ways of doing the same thing, that is, it allows arriving at start memory location by doing an offset from a register in the first case and from an address/label in the second case?


text:
Q: Gantt chart on Excel - Conditional Formatting based on the number of days for a task which are in a given month I'm trying to build a Gantt Chart in Excel where I could conditionally fortmat cells to reflect the number of days a task has on a given month.
For example, today is 24-oct-19. A task starting on 11-oct-19 and ending on 08-nov-19 has 20 days on October and 8 days in November. I need to conditionally format a cell on the task row, October column, to be painted in a proportion given by 20/31. I should format similarly the same row, November column.
None of the many Gantt charts I found online could make it. Could you please give advice on how could I do this?
I'm also attaching a sketch.
Thank you!
Gantt chart with next 12 months

A: Just a proof of concept (not very aesthetically pleasing because of padding round cells, but this can be fixed).
I just wanted to see if you could get a reasonable chart using basic string functions to get a bar in the right position in each cell:
=IFERROR(LEFT($A$5,ROUND((MAX(D$1,$B6)-D$1)/DAY(EOMONTH(D$1,0))*10,0))&LEFT($A$3,ROUND((MIN($C6,EOMONTH(D$1,0))-MAX(D$1,$B6)+1)/DAY(EOMONTH(D$1,0))*10,0)),"")

Slightly more pleasing appearance - the trick is to centre the text in the cell, but then you need to include spaces to the right where necessary (e.g. in cell E6) to make it work:
=IFERROR(LEFT($A$5,ROUND((MAX(D$1,$B6)-D$1)/DAY(EOMONTH(D$1,0))*10,0))
&LEFT($A$3,ROUND((MIN($C6,EOMONTH(D$1,0))-MAX(D$1,$B6)+1)/DAY(EOMONTH(D$1,0))*10,0))
&LEFT($A$5,ROUND((EOMONTH(D$1,0)-MIN(EOMONTH(D$1,0),$C6))/DAY(EOMONTH(D$1,0))*10,0)),"")

To get fixed character size, I have set the area where the bars are to use Courier font, and chosen a suitable column width.


text:
Q: Ubuntu 16.04 second monitor is black I use ubuntu 16.04 and I connected my second monitor, it is detected but it is black.
Output of xrandr -q :
DP-1 connected 1280x1024+1920+0 (normal left inverted right x axis y axis) 338mm x 270mm 1280x1024 60.02*+ 75.02
1152x864 75.00
1024x768 75.03 60.00
832x624 74.55
800x600 75.00 60.32
640x480 75.00 59.94
720x400 70.08

It is connected with VGA. What can I do to turn on second monitor?

A: Sometimes the problem is with refresh rate.
You can change it in Display Settings (maybe 60 would be alright)
Or you can use this command  xrandr to see what's your second screen name and what resolutions/refresh rates does it support. For example XX.
Then you can set it by:
xrandr --output DP-1 --rate XX


text:
Q: Selenium can't find ninth element - python I have a problem with Selenium webdriver.
I want to log in a website and collect some articles from there. I could log in the website with my code, but couldn't find all elements.
This code can find all elements except ninth element of 'major' and 'notice'. (I don't know why but it could find ninth element of 'upload')
from selenium import webdriver
import MyCode

Data = []

....

driver = webdriver.Chrome()
driver.get(MyCode.url[0])
driver.implicitly_wait(10)

major = driver.find_elements_by_class_name('board-lecture-title')
notice = driver.find_elements_by_xpath('//*[@class=\'post-title\']/*')
upload = driver.find_elements_by_class_name('post-date')

....

driver.close()

This is a part of HTML code of the website

            [Course]Title

    2020년 7월 30일, 목요일, 오전 10:58

        0

        View

            [Course]Title

    2020년 7월 15일, 수요일, 오후 12:20

        0

        View

            [Course]Title

    2020년 6월 29일, 월요일, 오전 11:18

        47

        View

....

I'm sorry for my poor english give you confusion.


text:
Q: from a xlsx file that contains links / references to xls raw data file I want to save my xlsx file that contains links to other worksheets, to a xls format that contains raw output without formulas..

A: Would
Select all, Copy, Paste Values

Do it?

A: Agree with Jaydee if the worksheets are in the same workbook - but remember to save as XLS first or you might accidentally lose the formula if you were intending to keep them in XLSX.
For multiple worksheets too. Simply click on the tab of the first worksheet, then the final worksheet while holding down the shift key. You can then select all on the first worksheet and it will automatically do the same for every other worksheet.
If you have links to worksheets in other workbooks (Excel files) use save as XLS then Edit Links & Break Links (data tab) will do the trick.


text:
Q: push_notebook does not work in Google Collab Jupyter Notebook I am using bokeh on Google collab. I wonder if anybody has used push_notebook in Google Collab Jupyter  notebook. I am trying to run following code in Jupiter Notebook on Google Collab , but it get stuck on push_notebook() command
from ipywidgets import interact
import numpy as np
from bokeh.io import push_notebook,show,output_notebook
from bokeh.plotting import figure
output_notebook()

x=np.linspace(0,2*np.pi,2000)
y=np.sin(x)
p=figure(title="ff",plot_height=300,plot_width=600,y_range=(-5,5))
r=p.line(x,y,color="red",line_width=2)
def update(f,w=1,A=1,phi=0):
   print("fff")
   if f== "sin":func=np.sin
   if f== "sin":func=np.sin
   elif f=="cos":func =np.cos
   elif f== "tan":func=np.tan
   r.data_source.data['y']=A*func(w*x+phi)
   push_notebook()
show(p,notebook_handle=True)
interact(update,f=["sin","cos","tan"],w=(0,100),A=(1,5),phi=(0,20,0.1))

Can anybody suggest whats wrong in the code and how can it be run Google Collab.

A: push_notebook does not and cannot work on Google Collab due to the fact that Google's notebook implementation will not allow the necessary websocket connections to be opened. There is nothing that can be done about this until/unless Google makes changes on their end.
ref: https://github.com/bokeh/bokeh/issues/9302


text:
Q: Innerclass sharing attribute information I have a class called ContentStream... the problem is that the inner class AddRectancle suppose to get the info of the getter of the class GraphicBeginn...I thought the class ContentStream can reach the getter at least as the getter is public ... plse tell me how to
public class ContentStreamExt extends ContentStreamProcessor

{

private Matrix  graphicalMatrix;

public ContentStreamProcessorExt(ExtListener extListener)
{
    super(extListener);
}

private void enhanceAdditional()
{
    GraphicBeginn beginnGraphic = new GraphicBeginn();

    super.register("a", beginnGraphic);
    super.register("b", new AddRectangle(beginnGraphic));
}

private static class AddRectangle(GrapicBeginn beginn)
{
    // should get the info of uUx and uUy
}

private static class GraphicBeginn implements ContentOperator
{
    private float   uUx;
    private float   uUy;

    public float getuUx()
    {
        return this.uUx;
    }

    public float getuUy()
    {
        return this.uUy;
    }
..... // the input for uUx and uuy will be created in a method
}

A: If i understand your question correctly, The add rectangle class should be passed an instance of graphic begin on which it can invoke the public getters. This wiring can be done by the content stream class.
By the way the following is syntactically invalid
private static class AddRectangle(GrapicBeginn beginn)

A: The code you gave has a number of problems, it doesn't compile correctly as another poster has noted. It also appears you are providing a method signature while also declaring a class called "AddRectange". Is this a class or a method? You need to decide which, it can't be both. Here is an example that I think illustrates what you're trying to do in a general sense:
public class SampleClass {

public SampleClass() {
}

private void sampleClassMethod() {
    A a = new A();
    a.acceptB(new B());
}

private class A {
    public void acceptB(B bObject) {
        System.out.println(bObject.memberVar1);
    }

}

private class B {
    private int memberVar1 = 5;
}

}


text:
Q: Update SonarQube 5.2 UTF-8 issue I updated my Sonar 3.4.2 working with MySQL database to SonarQube 5.2 (following the upgrade procedures). But now my Jenkins Jobs failed all the time.
My shorted stacktrace:
2015.11.26 09:40:16 ERROR web[o.s.s.w.WebServiceEngine] Fail to process request http://se02/sonarqube/batch/project.protobuf?key=de.adnova%3Amodule.benutzerunterstuetzung
java.lang.NullPointerException: null
         at com.google.protobuf.Utf8.encodedLength(Utf8.java:378) ~[protobuf-java-3.0.0-beta-1.jar:na]
         at com.google.protobuf.CodedOutputStream.computeStringSizeNoTag(CodedOutputStream.java:911) ~[protobuf-java-3.0.0-beta-1.jar:na]
         at com.google.protobuf.FieldSet.computeElementSizeNoTag(FieldSet.java:834) ~[protobuf-java-3.0.0-beta-1.jar:na]
         at com.google.protobuf.MapEntryLite.getFieldSize(MapEntryLite.java:143) ~[protobuf-java-3.0.0-beta-1.jar:na]
         at com.google.protobuf.MapEntryLite.getSerializedSize(MapEntryLite.java:135) ~[protobuf-java-3.0.0-beta-1.jar:na]
         at com.google.protobuf.MapEntry.getSerializedSize(MapEntry.java:120) ~[protobuf-java-3.0.0-beta-1.jar:na]
         at com.google.protobuf.CodedOutputStream.computeMessageSizeNoTag(CodedOutputStream.java:947) ~[protobuf-java-3.0.0-beta-1.jar:na]
         at com.google.protobuf.CodedOutputStream.computeMessageSize(CodedOutputStream.java:707) ~[protobuf-java-3.0.0-beta-1.jar:na]
         at org.sonarqube.ws.WsBatch$WsProjectResponse$FileDataByPath.getSerializedSize(WsBatch.java:783) ~[sonar-ws-5.2.jar:na]
         at com.google.protobuf.CodedOutputStream.computeMessageSizeNoTag(CodedOutputStream.java:947) ~[protobuf-java-3.0.0-beta-1.jar:na]
         at com.google.protobuf.FieldSet.computeElementSizeNoTag(FieldSet.java:846) ~[protobuf-java-3.0.0-beta-1.jar:na]
         at com.google.protobuf.MapEntryLite.getFieldSize(MapEntryLite.java:143) ~[protobuf-java-3.0.0-beta-1.jar:na]
         at com.google.protobuf.MapEntryLite.getSerializedSize(MapEntryLite.java:136) ~[protobuf-java-3.0.0-beta-1.jar:na]
         at com.google.protobuf.MapEntry.getSerializedSize(MapEntry.java:120) ~[protobuf-java-3.0.0-beta-1.jar:na]
         at com.google.protobuf.CodedOutputStream.computeMessageSizeNoTag(CodedOutputStream.java:947) ~[protobuf-java-3.0.0-beta-1.jar:na]
         at com.google.protobuf.CodedOutputStream.computeMessageSize(CodedOutputStream.java:707) ~[protobuf-java-3.0.0-beta-1.jar:na]
         at org.sonarqube.ws.WsBatch$WsProjectResponse.getSerializedSize(WsBatch.java:1856) ~[sonar-ws-5.2.jar:na]
         at com.google.protobuf.AbstractMessageLite.writeTo(AbstractMessageLite.java:77) ~[protobuf-java-3.0.0-beta-1.jar:na]
         at org.sonar.server.ws.WsUtils.writeProtobuf(WsUtils.java:48) ~[sonar-server-5.2.jar:na]
         at org.sonar.server.batch.ProjectAction.handle(ProjectAction.java:83) ~[sonar-server-5.2.jar:na]
         at org.sonar.server.ws.WebServiceEngine.execute(WebServiceEngine.java:85) ~[sonar-server-5.2.jar:na]
         at sun.reflect.GeneratedMethodAccessor166.invoke(Unknown Source) ~[na:na]
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_66]
         at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_66]
         at org.jruby.javasupport.JavaMethod.invokeDirectWithExceptionHandling(JavaMethod.java:425) [jruby-complete-1.7.9.jar:na]
         at org.jruby.javasupport.JavaMethod.invokeDirect(JavaMethod.java:292) [jruby-complete-1.7.9.jar:na]
         at org.jruby.java.invokers.InstanceMethodInvoker.call(InstanceMethodInvoker.java:44) [jruby-complete-1.7.9.jar:na]
         at org.jruby.runtime.callsite.CachingCallSite.call(CachingCallSite.java:70) [jruby-complete-1.7.9.jar:na]
         at rubyjit.Api::JavaWsController$$index_F0093F46F7B98A69318D6BFF77A0745BB14C850A115612850.__file__(D:/SEU/Sonarqube/web/WEB-INF/app/controllers/api/java_ws_controller.rb:34) [jruby-complete-1.7.9.jar:na]
         at rubyjit.Api::JavaWsController$$index_F0093F46F7B98A69318D6BFF77A0745BB14C850A115612850.__file__(D:/SEU/Sonarqube/web/WEB-INF/app/controllers/api/java_ws_controller.rb) [jruby-complete-1.7.9.jar:na]
         at org.jruby.internal.runtime.methods.JittedMethod.call(JittedMethod.java:161) [jruby-complete-1.7.9.jar:na]
         at org.jruby.RubyClass.finvoke(RubyClass.java:527) [jruby-complete-1.7.9.jar:na]
         at org.jruby.RubyBasicObject.send(RubyBasicObject.java:2590) [jruby-complete-1.7.9.jar:na]
         at org.jruby.RubyKernel.send(RubyKernel.java:2223) [jruby-complete-1.7.9.jar:na]
         at org.jruby.RubyKernel$INVOKER$s$send.call(RubyKernel$INVOKER$s$send.gen) [jruby-complete-1.7.9.jar:na]
         at org.jruby.internal.runtime.methods.JavaMethod$JavaMethodOneOrNBlock.call(JavaMethod.java:350) [jruby-complete-1.7.9.jar:na]
         at org.jruby.runtime.callsite.CachingCallSite.cacheAndCall(CachingCallSite.java:326) [jruby-complete-1.7.9.jar:na]
         at org.jruby.runtime.callsite.CachingCallSite.call(CachingCallSite.java:170) [jruby-complete-1.7.9.jar:na]
         at rubyjit.ActionController::Base$$perform_action_DA0FC0A901DD1257EC969DB0C482DD8514B8F04B115612850.__file__(D:/SEU/Sonarqube/web/WEB-INF/gems/gems/actionpack-2.3.15/lib/action_controller/base.rb:1333) [jruby-complete-1.7.9.jar:na]
         at rubyjit.ActionController::Base$$perform_action_DA0FC0A901DD1257EC969DB0C482DD8514B8F04B115612850.__file__(D:/SEU/Sonarqube/web/WEB-INF/gems/gems/actionpack-2.3.15/lib/action_controller/base.rb) [jruby-complete-1.7.9.jar:na]
         at org.jruby.internal.runtime.methods.JittedMethod.call(JittedMethod.java:141) [jruby-complete-1.7.9.jar:na]
         at org.jruby.internal.runtime.methods.DefaultMethod.call(DefaultMethod.java:185) [jruby-complete-1.7.9.jar:na]
         at org.jruby.internal.runtime.methods.AliasMethod.call(AliasMethod.java:56) [jruby-complete-1.7.9.jar:na]
         at org.jruby.runtime.callsite.CachingCallSite.cacheAndCall(CachingCallSite.java:306) [jruby-complete-1.7.9.jar:na]
         at org.jruby.runtime.callsite.CachingCallSite.call(CachingCallSite.java:136) [jruby-complete-1.7.9.jar:na]
         at rubyjit.ActionController::Filters::InstanceMethods$$call_filters_A7E1D3FFBF56E3CB7C0EBA850688505249A05AE9115612850.__file__(D:/SEU/Sonarqube/web/WEB-INF/gems/gems/actionpack-2.3.15/lib/action_controller/filters.rb:617) [jruby-complete-1.7.9.jar:na]
         at rubyjit.ActionController::Filters::InstanceMethods$$call_filters_A7E1D3FFBF56E3CB7C0EBA850688505249A05AE9115612850.__file__(D:/SEU/Sonarqube/web/WEB-INF/gems/gems/actionpack-2.3.15/lib/action_controller/filters.rb) [jruby-complete-1.7.9.jar:na]
         at org.jruby.internal.runtime.methods.JittedMethod.call(JittedMethod.java:261) [jruby-complete-1.7.9.jar:na]
         at org.jruby.runtime.callsite.CachingCallSite.call(CachingCallSite.java:236) [jruby-complete-1.7.9.jar:na]
         at rubyjit.ActionController::Filters::InstanceMethods$$perform_action_with_filters_4C7C67B4A5564FF5DC76344AF2372660F608839C115612850.__file__(D:/SEU/Sonarqube/web/WEB-INF/gems/gems/actionpack-2.3.15/lib/action_controller/filters.rb:610) [jruby-complete-1.7.9.jar:na]
         at rubyjit.ActionController::Filters::InstanceMethods$$perform_action_with_filters_4C7C67B4A5564FF5DC76344AF2372660F608839C115612850.__file__(D:/SEU/Sonarqube/web/WEB-INF/gems/gems/actionpack-2.3.15/lib/action_controller/filters.rb) [jruby-complete-1.7.9.jar:na]
         at org.jruby.internal.runtime.methods.JittedMethod.call(JittedMethod.java:141) [jruby-complete-1.7.9.jar:na]
         at org.jruby.internal.runtime.methods.DefaultMethod.call(DefaultMethod.java:185) [jruby-complete-1.7.9.jar:na]
         at org.jruby.internal.runtime.methods.AliasMethod.call(AliasMethod.java:56) [jruby-complete-1.7.9.jar:na]
         at org.jruby.internal.runtime.methods.AliasMethod.call(AliasMethod.java:56) [jruby-complete-1.7.9.jar:na]
         at org.jruby.runtime.callsite.CachingCallSite.call(CachingCallSite.java:134) [jruby-complete-1.7.9.jar:na]
         at rubyjit.ActionController::Benchmarking$$perform_action_with_benchmark_303676EADF39D1B66CBA6FF2131B0D6C74E04345115612850.block_0$RUBY$__file__(D:/SEU/Sonarqube/web/WEB-INF/gems/gems/actionpack-2.3.15/lib/action_controller/benchmarking.rb:68) [jruby-complete-1.7.9.jar:na]
         at rubyjit$ActionController::Benchmarking$$perform_action_with_benchmark_303676EADF39D1B66CBA6FF2131B0D6C74E04345115612850$block_0$RUBY$__file__.call(rubyjit$ActionController::Benchmarking$$perform_action_with_benchmark_303676EADF39D1B66CBA6FF2131B0D6C74E04345115612850$block_0$RUBY$__file__) [jruby-complete-1.7.9.jar:na]
         at org.jruby.runtime.CompiledBlock.yield(CompiledBlock.java:112) [jruby-complete-1.7.9.jar:na]
         at org.jruby.runtime.CompiledBlock.yield(CompiledBlock.java:95) [jruby-complete-1.7.9.jar:na]
         at org.jruby.runtime.CompiledBlock.yieldSpecific(CompiledBlock.java:75) [jruby-complete-1.7.9.jar:na]
         at org.jruby.runtime.Block.yieldSpecific(Block.java:111) [jruby-complete-1.7.9.jar:na]
         at rubyjit.Module$$ms_A9C6E2920290A1221EDA9CE357DE380BBA9B1BD9115612850.block_0$RUBY$__file__(D:/SEU/Sonarqube/web/WEB-INF/gems/gems/activesupport-2.3.15/lib/active_support/core_ext/benchmark.rb:17) [jruby-complete-1.7.9.jar:na]
         at rubyjit$Module$$ms_A9C6E2920290A1221EDA9CE357DE380BBA9B1BD9115612850$block_0$RUBY$__file__.call(rubyjit$Module$$ms_A9C6E2920290A1221EDA9CE357DE380BBA9B1BD9115612850$block_0$RUBY$__file__) [jruby-complete-1.7.9.jar:na]
         at org.jruby.runtime.CompiledBlock.yield(CompiledBlock.java:112) [jruby-complete-1.7.9.jar:na]
         at org.jruby.runtime.CompiledBlock.yield(CompiledBlock.java:95) [jruby-complete-1.7.9.jar:na]
         at org.jruby.runtime.CompiledBlock.yieldSpecific(CompiledBlock.java:75) [jruby-complete-1.7.9.jar:na]
         at org.jruby.runtime.Block.yieldSpecific(Block.java:111) [jruby-complete-1.7.9.jar:na]
         at rubyjit.Benchmark$$realtime_D80759D5ED3DED92A37F972B3598DFDF9CC64E2A115612850.__file__(jar:file:/D:/SEU/Sonarqube/lib/server/jruby-complete-1.7.9.jar!/META-INF/jruby.home/lib/ruby/1.8/benchmark.rb:308) [jruby-complete-1.7.9.jar:na]
         at rubyjit.Benchmark$$realtime_D80759D5ED3DED92A37F972B3598DFDF9CC64E2A115612850.__file__(jar:file:/D:/SEU/Sonarqube/lib/server/jruby-complete-1.7.9.jar!/META-INF/jruby.home/lib/ruby/1.8/benchmark.rb) [jruby-complete-1.7.9.jar:na]
         at org.jruby.internal.runtime.methods.JittedMethod.call(JittedMethod.java:161) [jruby-complete-1.7.9.jar:na]
         at org.jruby.internal.runtime.methods.DefaultMethod.call(DefaultMethod.java:193) [jruby-complete-1.7.9.jar:na]
         at org.jruby.internal.runtime.methods.WrapperMethod.call(WrapperMethod.java:74) [jruby-complete-1.7.9.jar:na]
         at org.jruby.runtime.callsite.CachingCallSite.callBlock(CachingCallSite.java:143) [jruby-complete-1.7.9.jar:na]
         at org.jruby.runtime.callsite.CachingCallSite.callIter(CachingCallSite.java:154) [jruby-complete-1.7.9.jar:na]
         at rubyjit.Module$$ms_A9C6E2920290A1221EDA9CE357DE380BBA9B1BD9115612850.__file__(D:/SEU/Sonarqube/web/WEB-INF/gems/gems/activesupport-2.3.15/lib/active_support/core_ext/benchmark.rb:17) [jruby-complete-1.7.9.jar:na]
         at rubyjit.Module$$ms_A9C6E2920290A1221EDA9CE357DE380BBA9B1BD9115612850.__file__(D:/SEU/Sonarqube/web/WEB-INF/gems/gems/activesupport-2.3.15/lib/active_support/core_ext/benchmark.rb) [jruby-complete-1.7.9.jar:na]
         at org.jruby.internal.runtime.methods.JittedMethod.call(JittedMethod.java:161) [jruby-complete-1.7.9.jar:na]
         at org.jruby.runtime.callsite.CachingCallSite.callBlock(CachingCallSite.java:143) [jruby-complete-1.7.9.jar:na]
         at org.jruby.runtime.callsite.CachingCallSite.callIter(CachingCallSite.java:154) [jruby-complete-1.7.9.jar:na]
         at rubyjit.ActionController::Benchmarking$$perform_action_with_benchmark_303676EADF39D1B66CBA6FF2131B0D6C74E04345115612850.__file__(D:/SEU/Sonarqube/web/WEB-INF/gems/gems/actionpack-2.3.15/lib/action_controller/benchmarking.rb:68) [jruby-complete-1.7.9.jar:na]
         at rubyjit.ActionController::Benchmarking$$perform_action_with_benchmark_303676EADF39D1B66CBA6FF2131B0D6C74E04345115612850.__file__(D:/SEU/Sonarqube/web/WEB-INF/gems/gems/actionpack-2.3.15/lib/action_controller/benchmarking.rb) [jruby-complete-1.7.9.jar:na]
         at org.jruby.internal.runtime.methods.JittedMethod.call(JittedMethod.java:141) [jruby-complete-1.7.9.jar:na]
         at org.jruby.internal.runtime.methods.DefaultMethod.call(DefaultMethod.java:185) [jruby-complete-1.7.9.jar:na]
         at org.jruby.internal.runtime.methods.AliasMethod.call(AliasMethod.java:56) [jruby-complete-1.7.9.jar:na]
         at org.jruby.internal.runtime.methods.AliasMethod.call(AliasMethod.java:56) [jruby-complete-1.7.9.jar:na]
         at org.jruby.runtime.callsite.CachingCallSite.call(CachingCallSite.java:134) [jruby-complete-1.7.9.jar:na]
         at rubyjit.ActionController::Rescue$$perform_action_with_rescue_C881D7FD614DB6154FDE67AADAA1B18CFBA9E44D115612850.chained_0_rescue_1$RUBY$SYNTHETIC__file__(D:/SEU/Sonarqube/web/WEB-INF/gems/gems/actionpack-2.3.15/lib/action_controller/rescue.rb:160) [jruby-complete-1.7.9.jar:na]
         at rubyjit.ActionController::Rescue$$perform_action_with_rescue_C881D7FD614DB6154FDE67AADAA1B18CFBA9E44D115612850.__file__(D:/SEU/Sonarqube/web/WEB-INF/gems/gems/actionpack-2.3.15/lib/action_controller/rescue.rb) [jruby-complete-1.7.9.jar:na]
         at rubyjit.ActionController::Rescue$$perform_action_with_rescue_C881D7FD614DB6154FDE67AADAA1B18CFBA9E44D115612850.__file__(D:/SEU/Sonarqube/web/WEB-INF/gems/gems/actionpack-2.3.15/lib/action_controller/rescue.rb) [jruby-complete-1.7.9.jar:na]
         at org.jruby.internal.runtime.methods.JittedMethod.call(JittedMethod.java:141) [jruby-complete-1.7.9.jar:na]
         at org.jruby.internal.runtime.methods.DefaultMethod.call(DefaultMethod.java:185) [jruby-complete-1.7.9.jar:na]
         at org.jruby.internal.runtime.methods.AliasMethod.call(AliasMethod.java:56) [jruby-complete-1.7.9.jar:na]
         at org.jruby.internal.runtime.methods.AliasMethod.call(AliasMethod.java:56) [jruby-complete-1.7.9.jar:na]
         at org.jruby.runtime.callsite.CachingCallSite.call(CachingCallSite.java:134) [jruby-complete-1.7.9.jar:na]
         at rubyjit.ActionController::Flash::InstanceMethods$$perform_action_with_flash_00190F39E4A509D41D1870DF577ADEFF4F2D86E0115612850.__file__(D:/SEU/Sonarqube/web/WEB-INF/gems/gems/actionpack-2.3.15/lib/action_controller/flash.rb:151) [jruby-complete-1.7.9.jar:na]
         at rubyjit.ActionController::Flash::InstanceMethods$$perform_action_with_flash_00190F39E4A509D41D1870DF577ADEFF4F2D86E0115612850.__file__(D:/SEU/Sonarqube/web/WEB-INF/gems/gems/actionpack-2.3.15/lib/action_controller/flash.rb) [jruby-complete-1.7.9.jar:na]
         at org.jruby.internal.runtime.methods.JittedMethod.call(JittedMethod.java:161) [jruby-complete-1.7.9.jar:na]
         at org.jruby.internal.runtime.methods.DefaultMethod.call(DefaultMethod.java:193) [jruby-complete-1.7.9.jar:na]
         at org.jruby.internal.runtime.methods.AliasMethod.call(AliasMethod.java:81) [jruby-complete-1.7.9.jar:na]
         at org.jruby.RubyClass.finvoke(RubyClass.java:527) [jruby-complete-1.7.9.jar:na]
         at org.jruby.RubyBasicObject.send(RubyBasicObject.java:2590) [jruby-complete-1.7.9.jar:na]
         at org.jruby.RubyKernel.send(RubyKernel.java:2223) [jruby-complete-1.7.9.jar:na]
         at org.jruby.RubyKernel$INVOKER$s$send.call(RubyKernel$INVOKER$s$send.gen) [jruby-complete-1.7.9.jar:na]
         at org.jruby.internal.runtime.methods.JavaMethod$JavaMethodOneOrNBlock.call(JavaMethod.java:350) [jruby-complete-1.7.9.jar:na]
         at org.jruby.runtime.callsite.CachingCallSite.call(CachingCallSite.java:168) [jruby-complete-1.7.9.jar:na]
         at org.jruby.runtime.callsite.CachingCallSite.callVarargs(CachingCallSite.java:103) [jruby-complete-1.7.9.jar:na]
         at rubyjit.ActionController::Base$$process_0CD993B4C06E435A5AD30338E2A0816E50206655115612850.chained_0_ensure_1$RUBY$__ensure__(D:/SEU/Sonarqube/web/WEB-INF/gems/gems/actionpack-2.3.15/lib/action_controller/base.rb:532) [jruby-complete-1.7.9.jar:na]
         at rubyjit.ActionController::Base$$process_0CD993B4C06E435A5AD30338E2A0816E50206655115612850.__file__(D:/SEU/Sonarqube/web/WEB-INF/gems/gems/actionpack-2.3.15/lib/action_controller/base.rb) [jruby-complete-1.7.9.jar:na]
         at rubyjit.ActionController::Base$$process_0CD993B4C06E435A5AD30338E2A0816E50206655115612850.__file__(D:/SEU/Sonarqube/web/WEB-INF/gems/gems/actionpack-2.3.15/lib/action_controller/base.rb) [jruby-complete-1.7.9.jar:na]
         at org.jruby.ast.executable.AbstractScript.__file__(AbstractScript.java:50) [jruby-complete-1.7.9.jar:na]
         at org.jruby.internal.runtime.methods.JittedMethod.call(JittedMethod.java:261) [jruby-complete-1.7.9.jar:na]
         at org.jruby.internal.runtime.methods.DefaultMethod.call(DefaultMethod.java:233) [jruby-complete-1.7.9.jar:na]
         at org.jruby.internal.runtime.methods.AliasMethod.call(AliasMethod.java:71) [jruby-complete-1.7.9.jar:na]
         at org.jruby.runtime.callsite.CachingCallSite.call(CachingCallSite.java:236) [jruby-complete-1.7.9.jar:na]
         at org.jruby.runtime.callsite.CachingCallSite.callVarargs(CachingCallSite.java:105) [jruby-complete-1.7.9.jar:na]
         at rubyjit.ActionController::Filters::InstanceMethods$$process_with_filters_77F73D0F3CFC9652FC1D8F99FD6ECB9ACFAEB2BE115612850.__file__(D:/SEU/Sonarqube/web/WEB-INF/gems/gems/actionpack-2.3.15/lib/action_controller/filters.rb:606) [jruby-complete-1.7.9.jar:na]
         at rubyjit.ActionController::Filters::InstanceMethods$$process_with_filters_77F73D0F3CFC9652FC1D8F99FD6ECB9ACFAEB2BE115612850.__file__(D:/SEU/Sonarqube/web/WEB-INF/gems/gems/actionpack-2.3.15/lib/action_controller/filters.rb) [jruby-complete-1.7.9.jar:na]
         at org.jruby.ast.executable.AbstractScript.__file__(AbstractScript.java:46) [jruby-complete-1.7.9.jar:na]
         at org.jruby.internal.runtime.methods.JittedMethod.call(JittedMethod.java:221) at org.jruby.runtime.callsite.CachingCallSite.call(CachingCallSite.java:168) [jruby-complete-1.7.9.jar:na]
         at rubyjit.ActionController::StringCoercion$$call_D51288B7BF2BE6EC36483A8B41C5A7EAEorg.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.0.18.jar:8.0.18]
         at java.lang.Thread.run(Unknown Source) [na:1.8.0_66]

It seems to be a problem with the text format. Has anyone an idea to fix this?
I found this : SONAR-7008 , but I can not wait for the 5.3 release.