text:
Q: Why am I getting negative compressions, for Gzip, Snappy, Smile? I was trying to investigate what compression was suitable for my application for compression JSON string. The aim here is to compression entity JSON before persisting to REDIS.
Here are my results
Gzip Compression Trial
compression percent : -8.7719345 %
to json time : 151 microseconds
pure saveable compression : 3326 microseconds
gzip compression+convert to json time : 3477 microseconds
gzip de-compression to string time : 537 microseconds

Snappy Compression Trial
compression percent : -22.807014 %
to json time : 58 microseconds
pure saveable compression : 259490 microseconds
snappy compression+convert to json time : 259549 microseconds
snappy de-compression to string time : 84 microseconds

Smile (msgpack) Compression Trial
compression percent : -24.561401 %
smile compression time : 3314 microseconds
smile de-compression time : n/a

However what is quite Odd is Snappy is supposed to work much faster (from what i read) only the decompression is fast, but the compression takes longer.
Also strangely smile is producing a longer persistable string
Can anybody point out why or what I am doing wrong here?
Here is my code for this trial
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.smile.SmileFactory;
import com.fasterxml.jackson.dataformat.smile.SmileGenerator;
import com.fasterxml.jackson.dataformat.smile.SmileParser;
import org.xerial.snappy.Snappy;

import javax.xml.bind.DatatypeConverter;
import java.io.*;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class CompressionTrials {

    public static void main(String[] args) {
        jsonCompressionTrial();
    }

        public static void jsonCompressionTrial(){
            SimpleDto originalDto = new SimpleDto();
            originalDto.setFname("MyFirstName");
            originalDto.setLname("MyLastName");
            originalDto.setDescription("This is a long description. I am trying out compression options for JSON. Hopefully the results will help me decide on one approach");
            originalDto.setCity("MyCity");
            originalDto.setAge(36);
            originalDto.setZip(2424);

            gzipCompressionTrial(originalDto);
            snappyCompressionTrial(originalDto);
            smileCompressionTrial(originalDto);

        }

        public static void gzipCompressionTrial(SimpleDto simpleDto){
            if(simpleDto == null){
                return;
            }

            ObjectMapper mapper = new ObjectMapper();
            String originalJsonString = null;
            long compressionAndConversionMicroSeconds = 0;
            long toJsonMicroSeconds = 0;
            long compressionMicroSeconds = 0;
            long decompressionMicroSeconds = 0;
            SimpleDto restoredDto = null;
            String restoredDtoJson = null;
            try {
                mapper.writeValueAsString(simpleDto);
                long endConversionTime = 0;
                long startTimeCompressionAndConvesion = System.nanoTime();
                originalJsonString = mapper.writeValueAsString(simpleDto);
                endConversionTime = System.nanoTime();
                byte[] compressedBytes = gzipCompress(originalJsonString);
                String compressedStringToSave = bytesToStringBase64(compressedBytes);
                long endTimeCompression = System.nanoTime();
                long startCompressionTime = endConversionTime;
                toJsonMicroSeconds =  TimeUnit.NANOSECONDS.toMicros((endConversionTime-startTimeCompressionAndConvesion));
                compressionMicroSeconds =  TimeUnit.NANOSECONDS.toMicros((endTimeCompression-startCompressionTime));
                compressionAndConversionMicroSeconds =  TimeUnit.NANOSECONDS.toMicros((endTimeCompression-startTimeCompressionAndConvesion));

                long startTimeDecompression = System.nanoTime();
                String unCompressedString = gzipDecompress(compressedBytes);
                long endTimeDecompression = System.nanoTime();
                decompressionMicroSeconds = TimeUnit.NANOSECONDS.toMicros(endTimeDecompression-startTimeDecompression); // TimeUnit.MILLISECONDS.convert((endTimeDecompression - startTimeDecompression), TimeUnit.NANOSECONDS);

                int originalLength = originalJsonString.toString().length();
                int compressedLength = compressedStringToSave.toString().length();
                float compressionPercent = 100 - (( (float)compressedLength / (float)originalLength ) * 100);

                restoredDto = mapper.readValue(originalJsonString, SimpleDto.class);
                restoredDtoJson = mapper.writeValueAsString(restoredDto);

                System.out.println("============================================================================================== ");
                System.out.println("  Gzip Compression Trial");
                System.out.println("----------------------------------------------------------------------------------------------");
    //            System.out.println("origin dto as json : " + originalJsonString );
    //            System.out.println( "original dto-json string length : " + originalLength);
    //            System.out.println( "compressed string length : " + compressedLength );
    //            System.out.println( "uncompressed json string : " + unCompressedString );
    //            System.out.println( " restored dto as json : " + restoredDtoJson );
    //            System.out.println( " is before-compressed = uncompressed : " + unCompressedString.equals(originalJsonString) );
    //            System.out.println( " is restored object json = original object json : " + originalJsonString.equals(restoredDtoJson) );
    //            System.out.println("----------------------------------------------------------------------------------------------");
                System.out.println("compression percent : " + compressionPercent + " %" );
                System.out.println("to json time : " + toJsonMicroSeconds + " microseconds" );
                System.out.println(" pure saveable compression : " + compressionMicroSeconds + " microseconds" );
                System.out.println("gzip compression+convert to json time : " + compressionAndConversionMicroSeconds + " microseconds" );
                System.out.println("gzip de-compression to string time : " + decompressionMicroSeconds + " microseconds" );
                System.out.println("============================================================================================== ");

            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        public static void smileCompressionTrial(SimpleDto simpleDto){
            if(simpleDto == null){
                return;
            }

            ObjectMapper mapper = new ObjectMapper();
            ObjectMapper smileMapper = getSmileObjectMapper();
            String originalJsonString = null;
            try {
                originalJsonString = mapper.writeValueAsString(simpleDto);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                return;
            }
            long compressionMicroSeconds = 0;
            long decompressionMicroSeconds = 0;
            SimpleDto restoredDto = null;
            String restoredDtoJson = null;

            try {
                mapper.writeValueAsString(simpleDto);
                long startTimeCompression = System.nanoTime();
                byte[] compressedBytes = smileMapper.writeValueAsBytes(simpleDto);
                //String compressedStringToSave = new String(compressedBytes, "UTF-8");// bytesToStringBase64(compressedBytes);
                String compressedStringToSave = bytesToStringBase64(compressedBytes);
    //            System.out.println("smile compressed : " + compressedStringToSave);
    //            System.out.println("original length : " + originalJsonString.length() );
    //            System.out.println("length : " + compressedStringToSave.length() );
                long endTimeCompression = System.nanoTime();
                compressionMicroSeconds =  TimeUnit.NANOSECONDS.toMicros((endTimeCompression-startTimeCompression)); //TimeUnit.MILLISECONDS.convert((endTimeCompression - startTimeCompression), TimeUnit.NANOSECONDS);

    //            long startTimeDecompression = System.nanoTime();
    //            String unCompressedString = gzipDecompress(compressedBytes);
    //            long endTimeDecompression = System.nanoTime();
    //            decompressionMicroSeconds = TimeUnit.NANOSECONDS.toMicros(endTimeDecompression-startTimeDecompression); // TimeUnit.MILLISECONDS.convert((endTimeDecompression - startTimeDecompression), TimeUnit.NANOSECONDS);

                int originalLength = originalJsonString.toString().length();
                int compressedLength = compressedStringToSave.toString().length();
                float compressionPercent = 100 - (( (float)compressedLength / (float)originalLength ) * 100);

                restoredDto = smileMapper.readValue( stringToBytesBase64(compressedStringToSave) , SimpleDto.class);
                //restoredDto = smileMapper.readValue( compressedStringToSave.getBytes("UTF-8") , SimpleDto.class);
                restoredDtoJson = mapper.writeValueAsString(restoredDto);

                System.out.println("============================================================================================== ");
                System.out.println("  Smile Compression Trial");
                System.out.println("----------------------------------------------------------------------------------------------");
    //            System.out.println("origin dto as json : " + originalJsonString );
    //            System.out.println( "original dto-json string length : " + originalLength);
    //            System.out.println( "compressed string length : " + compressedLength );
    //            System.out.println( "uncompressed json string : n/a" /*+ unCompressedString*/ );
    //            System.out.println( " restored dto as json : " + restoredDtoJson );
    //            System.out.println( " is before-compressed = uncompressed : n/a " /*+ unCompressedString.equals(originalJsonString)*/ );
    //            System.out.println( " is restored object json = original object json : " + originalJsonString.equals(restoredDtoJson) );
    //            System.out.println("----------------------------------------------------------------------------------------------");
                System.out.println("compression percent : " + compressionPercent + " %" );
                System.out.println("smile compression time : " + compressionMicroSeconds + " microseconds" );
                System.out.println("smile de-compression time : n/a " /*+ decompressionMicroSeconds + " microseconds"*/ );
                System.out.println("============================================================================================== ");

            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        public static void snappyCompressionTrial(SimpleDto simpleDto) {
            if (simpleDto == null) {
                return;
            }

            ObjectMapper mapper = new ObjectMapper();
            String originalJsonString = null;
            long compressionAndConversionMicroSeconds = 0;
            long toJsonMicroSeconds = 0;
            long compressionMicroSeconds = 0;
            long decompressionMicroSeconds = 0;
            SimpleDto restoredDto = null;
            String restoredDtoJson = null;
            try {
                mapper.writeValueAsString(simpleDto);
                long endConversionTime = 0;
                long startTimeCompressionAndConvesion = System.nanoTime();
                originalJsonString = mapper.writeValueAsString(simpleDto);
                endConversionTime = System.nanoTime();
                byte[] compressedBytes = snappyCompress(originalJsonString);
                String compressedStringToSave = bytesToStringBase64(compressedBytes);
                long endTimeCompression = System.nanoTime();
                long startCompressionTime = endConversionTime;
                toJsonMicroSeconds = TimeUnit.NANOSECONDS.toMicros((endConversionTime - startTimeCompressionAndConvesion));
                compressionMicroSeconds = TimeUnit.NANOSECONDS.toMicros((endTimeCompression - startCompressionTime));
                compressionAndConversionMicroSeconds = TimeUnit.NANOSECONDS.toMicros((endTimeCompression - startTimeCompressionAndConvesion));

                long startTimeDecompression = System.nanoTime();
                byte[] unCompressedBytes = snappyUncompress(compressedBytes);
                String unCompressedString = bytesToStringUtf8(unCompressedBytes);
                long endTimeDecompression = System.nanoTime();
                decompressionMicroSeconds = TimeUnit.NANOSECONDS.toMicros(endTimeDecompression - startTimeDecompression);

                int originalLength = originalJsonString.toString().length();
                int compressedLength = compressedStringToSave.toString().length();
                float compressionPercent = 100 - (((float) compressedLength / (float) originalLength) * 100);

                //restoredDto = mapper.readValue(originalJsonString, SimpleDto.class);
                restoredDto = mapper.readValue(unCompressedBytes, SimpleDto.class);
                restoredDtoJson = mapper.writeValueAsString(restoredDto);

                System.out.println("============================================================================================== ");
                System.out.println("  Snappy Compression Trial");
                System.out.println("----------------------------------------------------------------------------------------------");
                //            System.out.println("origin dto as json : " + originalJsonString );
                //            System.out.println( "original dto-json string length : " + originalLength);
                //            System.out.println( "compressed string length : " + compressedLength );
                //            System.out.println( "uncompressed json string : " + unCompressedString );
                //            System.out.println( " restored dto as json : " + restoredDtoJson );
                //            System.out.println( " is before-compressed = uncompressed : " + unCompressedString.equals(originalJsonString) );
                //            System.out.println( " is restored object json = original object json : " + originalJsonString.equals(restoredDtoJson) );
                //            System.out.println("----------------------------------------------------------------------------------------------");
                System.out.println("compression percent : " + compressionPercent + " %");
                System.out.println("to json time : " + toJsonMicroSeconds + " microseconds");
                System.out.println(" pure saveable compression : " + compressionMicroSeconds + " microseconds");
                System.out.println("gzip compression+convert to json time : " + compressionAndConversionMicroSeconds + " microseconds");
                System.out.println("gzip de-compression to string time : " + decompressionMicroSeconds + " microseconds");
                System.out.println("============================================================================================== ");

            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        private static ObjectMapper getSmileObjectMapper() {
            SmileFactory smileFactory = new SmileFactory();
            smileFactory.configure(SmileGenerator.Feature.CHECK_SHARED_NAMES,true);
            smileFactory.configure(SmileGenerator.Feature.CHECK_SHARED_STRING_VALUES,true);
            smileFactory.configure(SmileGenerator.Feature.ENCODE_BINARY_AS_7BIT,true);
            smileFactory.configure(SmileGenerator.Feature.WRITE_HEADER,true);
            smileFactory.configure(SmileGenerator.Feature.WRITE_END_MARKER,false);
            smileFactory.configure(SmileParser.Feature.REQUIRE_HEADER,false);
            return new ObjectMapper(smileFactory);
        }

        public static byte[] gzipCompress(String str) throws IOException {
            if (str == null || str.length() == 0) {
                return null;
            }
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            GZIPOutputStream gzip = new GZIPOutputStream(out);
            gzip.write(str.getBytes());
            gzip.close();
            return out.toByteArray();
    //        String outStr = out.toString("UTF-8");
    //        return outStr;
        }

        public static String gzipDecompress(byte[] bytes) throws Exception {
            if (bytes == null || bytes.length == 0) {
                return null;
            }
            GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes));
            BufferedReader bf = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
            String outStr = "";
            String line;
            while ((line=bf.readLine())!=null) {
                outStr += line;
            }
            return outStr;
        }

        public static byte[] snappyCompress(String stringData) throws IOException {
            return Snappy.compress(stringData);
        }

        public static byte[] snappyUncompress(byte[] bytes) throws IOException {
            return Snappy.uncompress(bytes);
        }

        private static String bytesToStringBase64(byte[] bytes){
            return DatatypeConverter.printBase64Binary(bytes);
        }

        private static byte[] stringToBytesBase64(String dataString){
            return DatatypeConverter.parseBase64Binary(dataString);
        }

        private static String bytesToStringUtf8(byte[] bytes) throws UnsupportedEncodingException {
            return new String(bytes, "UTF-8");
        }

        private static byte[] stringToBytesUtf8(String dataString) throws UnsupportedEncodingException {
            return dataString.getBytes("UTF-8");
        }

}

Environment details : windows 7, i7 2.4 Gz processor, 16 GB RAM, Java 8
Versions of libraries used:
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-smile</artifactId>
    <version>2.6.4</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.6.4</version>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <scope>provided</scope>
    <version>1.16.6</version>
</dependency>

<dependency>
    <groupId>org.xerial.snappy</groupId>
    <artifactId>snappy-java</artifactId>
    <version>1.1.2</version>
</dependency>

*** This is not a benchmark, but just a personal trial to decide compression strategy for my use-case.
Please let me know if anybody sees any mistake in my trial
Update:
Below is a simpler code to try
    public static void stringCompressionTrial(){
        String string = "I am what I am hhhhhhhhhhhhhhhhhhhhhhhhhhhhh"
                + "bjggujhhhhhhhhh"
                + "rggggggggggggggggggggggggg"
                + "esfffffffffffffffffffffffffffffff"
                + "esffffffffffffffffffffffffffffffff"
                + "esfekfgy enter code here`etd`enter code here wdd"
                + "heljwidgutwdbwdq8d"
                + "skdfgysrdsdnjsvfyekbdsgcu"
                +"jbujsbjvugsduddbdj";

        // uncomment below to use the json
//        SimpleDto originalDto = new SimpleDto();
//        originalDto.setFname("MyFirstName");
//        originalDto.setLname("MySecondName");
//        originalDto.setDescription("This is a long description. I am trying out compression options for JSON. Hopefully the results will help me decide on one approach");
//        originalDto.setCity("MyCity");
//        originalDto.setAge(36);
//        originalDto.setZip(1111);
//        ObjectMapper mapper = new ObjectMapper();
//        try {
//            string = mapper.writeValueAsString(originalDto);
//        } catch (JsonProcessingException e) {
//            e.printStackTrace();
//        }

        byte[] compressedBytes = null;
        String compressedString = null;
        try {
            compressedBytes = gzipCompress(string);
            compressedString = bytesToStringBase64(compressedBytes);
            System.out.println("after gzipDecompress:" + compressedString);
            //String decomp = gzipDecompress(compressedBytes);
            String decompressedString = gzipDecompress( stringToBytesBase64(compressedString) );
            System.out.println("decompressed string  : " + decompressedString);
            System.out.println( " original string length : " + string.length());
            System.out.println( " compressedString length : " + compressedString.length() );

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

A: Because you are trying to compress short strings. Compression needs more data to find redundancy and to take advantage of skewed symbol frequencies.


text:
Q: Query to get the result in between epoch_timestamp I have a table where I have company_id and epoch_timestamp when they accessed. When I am running a query to get the result in between two timestamps I am not getting the result. Its showing 0 result but the result lies in between in Postressql db
My query is:
select company_id, count(company_id) AS count from tblhistorymaster
WHERE user_last_request_time BETWEEN 1586197800000 AND 1614277799999
group by company_id

select company_id, count(company_id) AS count from tblhistorymaster
WHERE user_last_request_time >= 1586197800000    AND user_last_request_time < 1614277799999
group by company_id

Any suggestion will be of great help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: XMLHttpRequest returning response in inspector but null when accessing it I have the following function:
var submit = (event) => {
    event.preventDefault();
    var xhr = new XMLHttpRequest();
    var url = '*removed*';
    xhr.open('POST', url, true);
    xhr.responseType = "json";
    xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    xhr.send(JSON.stringify({ email: this.state.email, password: this.state.password }));
    console.log(xhr);
}

Everything works just fine, I get the response I expected. This is the response (short):
readyState: 4

response: {token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkI…DQxfQ.s4Py_lmVK1-Ji9F573ZFddtpdnb2qa1ETHHluG11l44"}

responseType: "json"

status: 200

statusText: "OK"

I need to grab the token contained in the "response" field for future requests. The problem is that, if I call xhr.response it says "null". No matter how I call any single element of the object returned, I can't access them.

A: The last time I used XMLHttpRequest, I remember it having an onreadystatechange event that is triggered once the asynchronous call is complete, that you have to write a handler for, in order to access the response from the http call.
Further reading from the mozilla docs

submit = (event) => {
  event.preventDefault();
  var xhr = new XMLHttpRequest();
  var url = '*removed*';
  xhr.open('POST', url, true);
  xhr.responseType = "json";
  xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  xhr.onreadystatechange = function(){
    if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
          console.log(xhr.responseText);
      }
  }
  xhr.send(JSON.stringify({ email: this.state.email, password: this.state.password }));
}


text:
Q: Solve $(x-2)^6+(x-4)^6=64$ using a substitution. Solve $(x-2)^6+(x-4)^6=64$ using a substitution.
I tired using $t=x-2$.
But again I have to know the expansion of the power $6$.
Can it be transformed to a quadratic equation ?
I know that it can be somehow solved by expanding the powers. But I'm trying to get a good transformation by a sub.

A: Put $y=x-4$
$$(y+2)^6+y^6=2^6$$
It should be clear that $0$ and $-2$ are solutions.
The function $f(y)=(y+2)^6+y^6-2^6$ is decreasing for $y \in (-\infty,-1)$. And increasing for $(-1,\infty)$, so it at most has two roots.

A: If you put $t = x-3$, you have
$$
(t-1)^6 + (t+1)^6 = 64
$$
the odd terms cancel out when you expand the LHS, so you get
$$
u^3 + 15u^2 + 15u + 1 = 32
$$
where $u = (x-3)^2$. From looking at either the initial equation or this one, it's clear that $u = 1$ (corresponding to $t=\pm1$ and $x = 4,2$) is a solution, so can factor to
$$
(u^2 + 16u + 31)(u-1) = 0
$$

A: Let $x-2=a$ and $4-x=b$.
Hence, $a+b=2$ and $a^6+b^6=64$ or
$$(a^2+b^2)(a^4+b^4-a^2b^2)=64$$ or
$$(2-ab)(a^2b^2-16ab+16)=32$$ or
$$ab(a^2b^2-18ab+48)=0.$$
$ab=0$ gives $x=2$ or $x=4$.
$ab=9-\sqrt{33}$ does not give a real roots and $ab=9+\sqrt{33}$ does not give a real roots.
Id est, the answer is $\{2,4\}$.


text:
Q: Deducing if the series converges. $$\displaystyle \sum\limits_{}^{} \dfrac{1}{k(ln(k)^2)}$$
Integral test
$$\int_{} \frac {1}{u^2} du = \int  u^{-2} du = \frac {-1}{u} = \frac{-1}{\ln k} +c$$

A: One way is to use the Cauchy Condensation Test
See that the terms of the sequence are non negative and decreasing, so $\displaystyle \sum\limits_{k=2}^{\infty} \dfrac{1}{k(\ln^2 k)}$ converges if and only if $\displaystyle \sum\limits_{k=2}^{\infty} \dfrac{2^k}{2^k(\ln^2 2^k)} = \dfrac{1}{\ln^2 2}\sum\limits_{k=2}^{\infty} \dfrac{1}{k^2}$ converges (which is true).
Since, $\displaystyle \sum\limits_{k=2}^{\infty} \frac{1}{k^2} \le \displaystyle \sum\limits_{k=2}^{\infty} \frac{1}{k(k-1)} = \displaystyle \sum\limits_{k=2}^{\infty} \left(\frac{1}{k-1} - \frac{1}{k}\right) = 1$ (telescopes).

A: Using the integral test as you suggested
$$\sum_{k=2}^{\infty} \frac{1}{k \ln^2k} < \int_{2}^{\infty} \frac{1}{x\ln^2x} dx = \frac{1}{\ln (2)}$$
where $\int \frac{1}{x \ln^2x} dx = - \frac{1}{\ln x}  + C$


text:
Q: MongoDB - 2 Unique keys in Single Schema not allowed? Trying to do this in mongoose:
const blogPost = new Schema({
  title: { type: String, unique: true },
  slug: { type: String, unique: true },
  //...
});

However, I get an error:

MongoError: E11000 duplicate key error collection: blog.articles
  index: slug_1 dup key: { : null }

Is this not allowed? I just want to make sure nobody creates a slug twice, and neither uses the same title twice.

A: Actually you are creating slug with null value and getting error with having multiple documents with the null in the slug field.
Use sparse index to eliminate the null values.
const blogPost = new Schema({
  title: { type: String, unique: true, sparse: true },
  slug: { type: String, unique: true, sparse: true },
  //...
});


text:
Q: Split overlapping intervals into non-overlapping intervals, within values of an identifier I would like to take a set of intervals, possibly overlapping, within categories of an identifier and create new intervals that are either exactly overlapping (ie same start/end values) or completely non-overlapping. These new intervals should collectively span the range of the original intervals and not include any ranges not in the original intervals.
This needs to be a relatively fast operation because I'm working with lots of data.
Here is some example data:
library(data.table)
set.seed(1113)
start1 <- c(1,7,9, 17, 18,1,3,20)
end1 <- c(10,12,15, 20, 23,3,5,25)
id1 <- c(1,1,1,1,1,2,2,2)
obs <- rnorm(length(id1))
x <- data.table(start1,end1,id1,obs)

    > x
   start1 end1 id1         obs
1:      1   10   1 -0.79701638
2:      7   12   1 -0.09251333
3:      9   15   1 -0.08118742
4:     17   20   1 -2.33312797
5:     18   23   1  0.26581138
6:      1    3   2 -0.34314127
7:      3    5   2 -0.17196880
8:     20   25   2  0.11614842

The output should be something like this:
    id1 start1 end1 i.start1 i.end1         obs
 1:   1      1    6        1     10 -0.79701638
 2:   1      7    8        1     10 -0.79701638
 3:   1      7    8        7     12 -0.09251333
 4:   1      9   10        1     10 -0.79701638
 5:   1      9   10        7     12 -0.09251333
 6:   1      9   10        9     15 -0.08118742
 7:   1     11   12        7     12 -0.09251333
 8:   1     11   12        9     15 -0.08118742
 9:   1     13   15        9     15 -0.08118742
10:   1     17   17       17     20 -2.33312797
11:   1     18   20       17     20 -2.33312797
12:   1     18   20       18     23  0.26581138
13:   1     21   23       18     23  0.26581138
14:   2      1    2        1      3 -0.34314127
15:   2      3    3        1      3 -0.34314127
16:   2      3    3        3      5 -0.17196880
17:   2      4    5        3      5 -0.17196880
18:   2     20   25       20     25  0.11614842

I found this algorithm that corresponds to what I want:
https://softwareengineering.stackexchange.com/questions/363091/split-overlapping-ranges-into-all-unique-ranges?newreg=93383e379afe4dd3a595480528ee1541
I tried programming it directly but it was quite slow.

A: Here is another option.
#borrowing idea from https://stackoverflow.com/a/28938694/1989480
#group overlapping intervals together
x[, g := c(0L, cumsum(shift(start, -1L) > cummax(end))[-.N]), by=.(id)]

#cut those intervals into non-overlapping ones
itvl <- x[, {
    s <- sort(c(start - 1L, start, end, end + 1L))
    as.data.table(matrix(s[s %between% c(min(start), max(end))], ncol=2L, byrow=TRUE))
    }, by=.(id, g)]

#get OP's desired output using non-equi join
x[itvl, on=.(id, start<=V1, end>=V1),
    .(id1=id, start1=V1, end1=V2, i.start1=x.start, i.end1=x.end, obs),
    allow.cartesian=TRUE]

output:
    id1 start1 end1 i.start1 i.end1         obs
 1:   1      1    6        1     10 -0.79701638
 2:   1      7    8        1     10 -0.79701638
 3:   1      7    8        7     12 -0.09251333
 4:   1      9   10        1     10 -0.79701638
 5:   1      9   10        7     12 -0.09251333
 6:   1      9   10        9     15 -0.08118742
 7:   1     11   12        7     12 -0.09251333
 8:   1     11   12        9     15 -0.08118742
 9:   1     13   15        9     15 -0.08118742
10:   1     17   17       17     20 -2.33312797
11:   1     18   20       17     20 -2.33312797
12:   1     18   20       18     23  0.26581138
13:   1     21   23       18     23  0.26581138
14:   2      1    2        1      3 -0.34314127
15:   2      3    3        1      3 -0.34314127
16:   2      3    3        3      5 -0.17196880
17:   2      4    5        3      5 -0.17196880
18:   2     20   25       20     25  0.11614842

data:
library(data.table)
set.seed(1113)
id <- c(1,1,1,1,1,2,2,2)
x <- data.table(start=c(1,7,9, 17, 18,1,3,20),
    end=c(10,12,15, 20, 23,3,5,25),
    id=id,
    obs=rnorm(length(id)))

addressing comment:
library(data.table)
set.seed(1113)
x2 <- data.table(start=c(1,5,5),end=c(5,5,10),id=c(1,1,1),obs=rnorm(3))
x2[, g := c(0L, cumsum(shift(start, -1L) > cummax(end))[-.N]), by=.(id)]
itvl <- x2[, {
    s <- sort(c(start - 1L, start, end, end + 1L))
    as.data.table(matrix(s[s %between% c(min(start), max(end))], ncol=2L, byrow=TRUE))
    }, by=.(id, g)]
ans <- x2[itvl, on=.(id, start<=V1, end>=V1),
    .(id1=id, start1=V1, end1=V2, i.start1=x.start, i.end1=x.end, obs),
    allow.cartesian=TRUE]
ans[start1 >= i.start1 & end1 <= i.end1]

output:
   id1 start1 end1 i.start1 i.end1         obs
1:   1      1    4        1      5 -0.79701638
2:   1      4    5        1      5 -0.79701638
3:   1      5    5        1      5 -0.79701638
4:   1      5    5        5      5 -0.09251333
5:   1      5    5        5     10 -0.08118742
6:   1      5    6        5     10 -0.08118742
7:   1      6   10        5     10 -0.08118742

A: Here's my solution.
It's based on the algorithm here (https://softwareengineering.stackexchange.com/questions/363091/split-overlapping-ranges-into-all-unique-ranges?newreg=93383e379afe4dd3a595480528ee1541), but uses data.table, shift, and vectorized ifelse statements for efficiency. It also differs from the alrgorithm in that my code allows this operation to be performed separately for multiple datasets identified by an id_column. My approach also ignores keeping track of rows (ie "attribute") since it's not necessary to define this when the intervals can be easily merged back to the original data using foverlaps anyway. foverlaps also serves the purpose of excluding gaps
Please tell me whether you see any inefficiencies
remove_overlaps <- function(x, start_column, end_column, id_column=NULL){

  xd <- melt(x[,c(start_column,end_column,id_column),with=FALSE],id=id_column)

  xd[variable==start_column,end:=FALSE]
  xd[variable==end_column,end:=TRUE]
  setorderv(xd,c(id_column, "value","end"))

  xd[,end_next:=shift(end,type="lead"),by=id_column]
  xd[,value_next:=shift(value,type="lead"),by=id_column]

  #excluding end_next when missing should cause this to ignore the last row in each group
  #because this element will be NA as defined by shift
  temp <- xd[,.SD[!is.na(end_next),list(
    start=ifelse(!end,value,value+1),
    end=ifelse(!end_next,value_next-1,value_next)
  )],by=id_column]

  temp <- temp[end>=start]

  setnames(temp , c("start","end"),c(start_column,end_column))

  setkeyv(temp,c(id_column,start_column,end_column))

  out <- foverlaps(x,temp)
  setorderv(out, c(id_column,start_column,
                   paste0("i.",start_column),
                   paste0("i.",end_column)
  ))

  out
}
remove_overlaps(x, start_column="start1",end_column="end1",id_column="id1")

Also, for what it's worth I don't think the suggestion linked on that page is correct on how to exclude gaps.

This answer doesn't take account of gaps (gaps should not appear in
  output), so I refined it: * If e=false, add a to S. If e=true, take
  away a from S. * Define n'=n if e=false or n'=n+1 if e=true * Define
  m'=m-1 if f=false or m'=m if f=true * If n' <= m' and (e and not f) =
  false, output (n',m',S), otherwise output nothing. – silentman.it Aug
  23 '18 at 12:19

Here is a second version of this code algorithm implemented in R: remove_overlaps doesn't explicitly use silentman.it's suggestion to exclude gaps, whereas remove_overlaps1 uses that suggestion. Note that both functions do exclude gaps via the subsequent call to foverlaps, which only returns intervals if they partially match to those in x (the original data).
library(data.table)

remove_overlaps1 <- function(x, start_column, end_column, id_column=NULL){

  xd <- melt(x[,c(start_column,end_column,id_column),with=FALSE],id=id_column)

  xd[variable==start_column,end:=FALSE]
  xd[variable==end_column,end:=TRUE]
  setorderv(xd,c(id_column, "value","end"))

  xd[,end_next:=shift(end,type="lead"),by=id_column]
  xd[,value_next:=shift(value,type="lead"),by=id_column]

###subset to rows where (e & !f) = FALSE, as per comment suggestion on linked answer
  temp <- xd[,.SD[!is.na(end_next)&!(end & !end_next),list(
    start=ifelse(!end,value,value+1),
    end=ifelse(!end_next,value_next-1,value_next)
  )],by=id_column]

  temp <- temp[end>=start]

  setnames(temp , c("start","end"),c(start_column,end_column))

  setkeyv(temp,c(id_column,start_column,end_column))

  out <- foverlaps(x,temp) #this should exclude gaps since foverlaps by default subsets to
  setorderv(out, c(id_column,start_column,
                   paste0("i.",start_column),
                   paste0("i.",end_column)
  ))

  out
}

Example data:
library(data.table)
x <-
  structure(
    list(
      native_id = c(
        "1",
        "1",
        "1",
        "1",
        "1"
      ),
      n_start_date = c(14761, 14775,
                       14789, 14803, 14817),
      n_end_date = c(14776, 14790, 14804, 14818,
                     14832),
      obs = c(
        31.668140525481,
        34.8623263656539,
        35.0841466093899,
        37.2281249364127,
        36.3726151694052
      )
    ),
    row.names = c(NA,-5L),
    class = "data.frame",
    .Names = c("native_id",
               "n_start_date", "n_end_date", "obs")
  )

setDT(x)

> x
   native_id n_start_date n_end_date      obs
1:         1        14761      14776 31.66814
2:         1        14775      14790 34.86233
3:         1        14789      14804 35.08415
4:         1        14803      14818 37.22812
5:         1        14817      14832 36.37262

Results:
> remove_overlaps(x, start_column="n_start_date",end_column="n_end_date",id_column="native_id")
    native_id n_start_date n_end_date i.n_start_date i.n_end_date      obs
 1:         1        14761      14774          14761        14776 31.66814
 2:         1        14775      14776          14761        14776 31.66814
 3:         1        14775      14776          14775        14790 34.86233
 4:         1        14777      14788          14775        14790 34.86233
 5:         1        14789      14790          14775        14790 34.86233
 6:         1        14789      14790          14789        14804 35.08415
 7:         1        14791      14802          14789        14804 35.08415
 8:         1        14803      14804          14789        14804 35.08415
 9:         1        14803      14804          14803        14818 37.22812
10:         1        14805      14816          14803        14818 37.22812
11:         1        14817      14818          14803        14818 37.22812
12:         1        14817      14818          14817        14832 36.37262
13:         1        14819      14832          14817        14832 36.37262

Seemingly incorrect, excludes too many intervals:
>  remove_overlaps1(x, start_column="n_start_date",end_column="n_end_date",id_column="native_id")
    native_id n_start_date n_end_date i.n_start_date i.n_end_date      obs
 1:         1        14761      14774          14761        14776 31.66814
 2:         1        14775      14776          14761        14776 31.66814
 3:         1        14775      14776          14775        14790 34.86233
 4:         1        14789      14790          14775        14790 34.86233
 5:         1        14789      14790          14789        14804 35.08415
 6:         1        14803      14804          14789        14804 35.08415
 7:         1        14803      14804          14803        14818 37.22812
 8:         1        14817      14818          14803        14818 37.22812
 9:         1        14817      14818          14817        14832 36.37262
10:         1        14819      14832          14817        14832 36.37262

A: I wrote a package, intervalaverage, for this and some related functions:
library(data.table)
set.seed(1113)
start1 <- c(1,7,9, 17, 18,1,3,20)
end1 <- c(10,12,15, 20, 23,3,5,25)
id1 <- c(1,1,1,1,1,2,2,2)
obs <- rnorm(length(id1))
x <- data.table(start1,end1,id1,obs)

library(intervalaverage)

x[, start1:=as.integer(start1)]
x[, end1:=as.integer(end1)]
isolateoverlaps(x,interval_vars = c("start1","end1"),group_vars = "id1")

    id1 start end start1 end1         obs
 1:   1     1   6      1   10 -0.79701638
 2:   1     7   8      1   10 -0.79701638
 3:   1     9  10      1   10 -0.79701638
 4:   1     7   8      7   12 -0.09251333
 5:   1     9  10      7   12 -0.09251333
 6:   1    11  12      7   12 -0.09251333
 7:   1     9  10      9   15 -0.08118742
 8:   1    11  12      9   15 -0.08118742
 9:   1    13  15      9   15 -0.08118742
10:   1    17  17     17   20 -2.33312797
11:   1    18  20     17   20 -2.33312797
12:   1    18  20     18   23  0.26581138
13:   1    21  23     18   23  0.26581138
14:   2     1   2      1    3 -0.34314127
15:   2     3   3      1    3 -0.34314127
16:   2     3   3      3    5 -0.17196880
17:   2     4   5      3    5 -0.17196880
18:   2    20  25     20   25  0.11614842

y <- data.table(start1=c(1L,5L,5L),end1=c(5L,5L,10L),id=c(1L,1L,1L))
isolateoverlaps(y,interval_vars = c("start1","end1"),group_vars = "id")

   id start end start1 end1
1:  1     1   4      1    5
2:  1     5   5      1    5
3:  1     5   5      5    5
4:  1     5   5      5   10
5:  1     6  10      5   10


text:
Q: Ignoring zeros in columns I want to ignore zeros in a specific column using Percentile function. I was seeking out for the Aggregate function , but it does not work. I have also used the following formula, but it did not work:
 =PERCENTILE(IF(D1:D8,0.3),0.3"<>0")

Here are data : I do not want to use it as an array
30
24
23
12
0
17
15
14

A: The correct Aggregate Function:
=AGGREGATE(16,6,$A$1:$A$8/($A$1:$A$8<>0),0.3)

A: If you don't want to use an array formula then you can use a helper column.  In E1 enter:
=IF(D1=0,"",D1)

and copy down.  Then in another cell enter:
=PERCENTILE(E1:E8,0.3)


text:
Q: How to find the start date of week from a given date? I have a concern is that I want from a given date to retrieve the start date of the week for example: 15/04/2015 So the beginning of the week will: 13/04/2015 (for me the beginning of the week is Monday).
thanks

A: Try this :-)
Dim FirstDayInWeek, LastDayInWeek  As Variant
Dim dtmDate As Date
dtmDate = "15/04/2015"

The begin date of week:
FirstDayInWeek = dtmDate - Weekday(dtmDate, vbUseSystem) + 1
MsgBox FirstDayInWeek

The end date of Week
LastDayInWeek = dtmDate - Weekday(dtmDate, vbUseSystem) + 7
MsgBox LastDayInWeek

A: Try this Formula:-
=A1-WEEKDAY(A1,2)+1

Where A1 contains your Input Date.


text:
Q: Symfony - parametrized ips in security.yml In my app I have api and admin access, I am trying to move allowed ips to parameters.yml
Composer stores array as:
api_allowed_ips:
    - 127.0.0.1
    - 192.168.0.1

Then in security.yml I do:
- { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY, ips: %api_allowed_ips% }

But it does not work, all IPs are let through. Am I doing something wrong or is this not possible at all?

A: You should put %api_allowed_ips% inside quotes


text:
Q: Why sw instruction in mips using byte as offset unit? I have a question about the offset units used in MIPS32 instructions. I just noticed that memory access instructions like lw $t0, offset($s1) has offset of unit byte, while branching instructions like beq $r1, $r2, L1 and jump j SOMEWHERE both have unit word.
IIRC, MIPS requires that every data/instructions should be stored aligned in memory at address of multiple of 4, i.e. 0x0, 0x4, 0x8, ... etc. If this is true, then why not let offset in lw/sw of unit word, so the range is larger? Is this because of lb/sb which uses a byte unit? So Special cases aren't special enough to break the rules ["] Good design demands good compromises.[."] applies here?
I also wonder what will happen if I use lw to load data that is at address that is not a multiple of 4?


text:
Q: Is a signal summable when given a z-transform? The output of a system is given as z-transform:
$$
Y(z)=\frac{1+z^{-2}}{(1+\frac{1}{4}z^{-1})(1-\frac{1}{2}z^{-1})}
$$
I want to know if the signal in the time domain is summable, meaning that the following is true:
$$
\sum_{n=-\infty}^{\infty}|y[n]|<B<\infty
$$
Is it enough to say: Well, there is already a $Y(z)$ given, so the infinite sum for calculating a z-transform obviously converges, which means $y[n]$ is summable? I am not sure about this, because when calculationg a z-transform the z also plays a major role if the sum converges or not:
$$
Y(z)=\sum_{n=-\infty}^{\infty}y[n]z^{-n}
$$
How do I do this correctly?


text:
Q: SetTimeout issue in Node.js I've the following code which runs fine under Chrome (V8) but fails inside node:
var id;
id = setTimeout("TimeoutHandler()", 10);
console.log ('SET');

function TimeoutHandler()
{
  clearTimeout(id);
  console.log ('CLEAR');
}

Chrome output:
SET
CLEAR

Nodejs output:
SET
timers.js:110
    first._onTimeout();
          ^
TypeError: Property '_onTimeout' of object [object Object] is not a function
    at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)

Any ideas why?
Thanks

A: Unlike in most browsers, setTimeout in node.js does not accept a string parameter.  You must pass it a function.  For example:
function TimeoutHandler()
{
  clearTimeout(id);
  console.log ('CLEAR');
}

var id;
id = setTimeout(TimeoutHandler, 10);
console.log ('SET');


text:
Q: Duplicity incremental backup taking too long I have duplicity running an incremental daily backup to S3. About 37 GiB.
On the first month or so, it went ok. It used to finish in about 1 hour. Then it started taking too long to complete the task. Right now, as I type, it is still running the daily backup that started 7 hours ago.
I'm running two commands, first to backup and then cleanup:
duplicity --full-if-older-than 1M LOCAL.SOURCE S3.DEST --volsize 666 --verbosity 8
duplicity remove-older-than 2M S3.DEST

The logs
Temp has 54774476800 available, backup will use approx 907857100.

So the temp has enough space, good. Then it starts with this...
Copying duplicity-full-signatures.20161107T090303Z.sigtar.gpg to local cache.
Deleting /tmp/duplicity-ipmrKr-tempdir/mktemp-13tylb-2
Deleting /tmp/duplicity-ipmrKr-tempdir/mktemp-NanCxQ-3
[...]
Copying duplicity-inc.20161110T095624Z.to.20161111T103456Z.manifest.gpg to local cache.
Deleting /tmp/duplicity-ipmrKr-tempdir/mktemp-VQU2zx-30
Deleting /tmp/duplicity-ipmrKr-tempdir/mktemp-4Idklo-31
[...]

This continues for each day till today, taking long minutes for each file. And continues with this...
Ignoring incremental Backupset (start_time: Thu Nov 10 09:56:24 2016; needed: Mon Nov  7 09:03:03 2016)
Ignoring incremental Backupset (start_time: Thu Nov 10 09:56:24 2016; needed: Wed Nov  9 18:09:07 2016)
Added incremental Backupset (start_time: Thu Nov 10 09:56:24 2016 / end_time: Fri Nov 11 10:34:56 2016)

After a long time...
Warning, found incomplete backup sets, probably left from aborted session
Last full backup date: Sun Mar 12 09:54:00 2017
Collection Status
-----------------
Connecting with backend: BackendWrapper
Archive dir: /home/user/.cache/duplicity/700b5f90ee4a620e649334f96747bd08

Found 6 secondary backup chains.
Secondary chain 1 of 6:
-------------------------
Chain start time: Mon Nov  7 09:03:03 2016
Chain end time: Mon Nov  7 09:03:03 2016
Number of contained backup sets: 1
Total number of contained volumes: 2
Type of backup set:                            Time:      Num volumes:
               Full         Mon Nov  7 09:03:03 2016                 2
-------------------------
Secondary chain 2 of 6:
-------------------------
Chain start time: Wed Nov  9 18:09:07 2016
Chain end time: Wed Nov  9 18:09:07 2016
Number of contained backup sets: 1
Total number of contained volumes: 11
Type of backup set:                            Time:      Num volumes:
               Full         Wed Nov  9 18:09:07 2016                11
-------------------------

Secondary chain 3 of 6:
-------------------------
Chain start time: Thu Nov 10 09:56:24 2016
Chain end time: Sat Dec 10 09:44:31 2016
Number of contained backup sets: 31
Total number of contained volumes: 41
Type of backup set:                            Time:      Num volumes:
               Full         Thu Nov 10 09:56:24 2016                11
        Incremental         Fri Nov 11 10:34:56 2016                 1
        Incremental         Sat Nov 12 09:59:47 2016                 1
        Incremental         Sun Nov 13 09:57:15 2016                 1
        Incremental         Mon Nov 14 09:48:31 2016                 1
        [...]

After listing all chains:
Also found 0 backup sets not part of any chain, and 1 incomplete backup set.
These may be deleted by running duplicity with the "cleanup" command.

This was only the backup part. It takes hours doing this and only 10 minutes to upload 37 GiB to S3.
ElapsedTime 639.59 (10 minutes 39.59 seconds)
SourceFiles 288
SourceFileSize 40370795351 (37.6 GB)

Then comes the cleanup, that gives me this:
Cleaning up
Local and Remote metadata are synchronized, no sync needed.
Warning, found incomplete backup sets, probably left from aborted session
Last full backup date: Sun Mar 12 09:54:00 2017
There are backup set(s) at time(s):
Tue Jan 10 09:58:05 2017
Wed Jan 11 09:54:03 2017
Thu Jan 12 09:56:42 2017
Fri Jan 13 10:05:05 2017
Sat Jan 14 10:24:54 2017
Sun Jan 15 09:49:31 2017
Mon Jan 16 09:39:41 2017
Tue Jan 17 09:59:05 2017
Wed Jan 18 09:59:56 2017
Thu Jan 19 10:01:51 2017
Fri Jan 20 09:35:30 2017
Sat Jan 21 09:53:26 2017
Sun Jan 22 09:48:57 2017
Mon Jan 23 09:38:45 2017
Tue Jan 24 09:54:29 2017
Which can't be deleted because newer sets depend on them.
Found old backup chains at the following times:
Mon Nov  7 09:03:03 2016
Wed Nov  9 18:09:07 2016
Sat Dec 10 09:44:31 2016
Mon Jan  9 10:04:51 2017
Rerun command with --force option to actually delete.

A: I found the problem. Because of an issue, I followed this answer, and added this code to my script:
rm -rf ~/.cache/deja-dup/*
rm -rf ~/.cache/duplicity/*

This is supposed to be a one time thing because of random bug duplicity had. But the answer didn't mention this. So every day the script was removing the cache just after syncing the cache, and then, on the next day it had to download the whole thing again.


text:
Q: Angular 1 removes slash from ng-style I need to display a ellipse cut in half and am using the elliptical corners of CSS3, i.e.:
return {
    'border-radius': '50% / 100%';
    'border-bottom-left-radius': 0;
    'border-bottom-right-radius': 0;
};

I serve the computed CSS via ng-style to the element but Angular seems to remove the slash from the css resulting in faulty css. I serve other shapes as well, so i need to calculate the CSS
I tried both '50% \/ 100%' and '50% / 100%', with or without spaces, none worked. All produced the same result.
Here is what I get in the style explorer in Chrome:

Is Angular removing the slash? How can I bypass that behaviour?
This is the console log right before it returns it to ng-style:


text:
Q: finished with non-zero exit value 1 in new project I just setup all my android setup on 64 bit system in which installed API level 21 and 19 also after setup every thing every time when I tried to create a fresh project whether its  for API 21 or for 19 all failed with non zero exit value
Error:Gradle: Execution failed for task ':app:processDebugResources'.

com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files (x86)\Android\android-sdk\build-tools\23.0.0\aapt.exe'' finished with non-zero exit value 1

C:\Users\rahul\IdeaProjects\MyApplication\app\build\intermediates\exploded-aar\com.android.support\appcompat-v7\23.0.0\res\values-v21\values-v21.xml
Error:(1, -1) Gradle: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material'.
Error:(1, -1) Gradle: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Body1'.
Error:(1, -1) Gradle: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Body2'.
Error:(1, -1) Gradle: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Button'.
Error:(1, -1) Gradle: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Caption'.
Error:(1, -1) Gradle: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Display1'.
Error:(1, -1) Gradle: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Display2'.
Error:(1, -1) Gradle: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Display3'.
Error:(1, -1) Gradle: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Display4'.
Error:(1, -1) Gradle: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Headline'.
Error:(1, -1) Gradle: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Inverse'.
Error:(1, -1) Gradle: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Large'.

A: You are using the appcompat v21.
You have to compile your project with api21.
In your build.gradle change:
android {
    compileSdkVersion 21
    //...
}

If you are switching to appcompat 23, you have to use API23.
android {
    compileSdkVersion 23
    //...
}

A: I am phased these kind of error...
MUST REMEMBER
Your compileSdkVersion must match the support library's major version.

Since you are using version 23 of the support library, you need to compile against version 23 of the Android SDK.

OR

Alternatively you can continue compiling against version 22 of the Android SDK by switching to the latest support library v22.

if, you need to set compileSdkVersion to 23.
Since API 23 Android removed the deprecated Apache Http packages, so if you use them for server requests, you'll need to add useLibrary 'org.apache.http.legacy' to build.gradle as stated in Apache HTTP Client Removal:
    android {
        compileSdkVersion 23
        buildToolsVersion "23.0.0"
        ...

        //only if you use Apache packages
        useLibrary 'org.apache.http.legacy'
    }
    dependencies {
         //only if you use Appcompat dependencies
        compile 'com.android.support:appcompat-v7:23.1.1'
     }


text:
Q: Can you say "feel to" do something? Is it correct to say, "I don't feel to trust him," particularly in British English?
I'm actually a native speaker, but I live in Italy with my Italian wife, and so I've got so used to her (English language) mistakes, that sometimes I don't even know if they're mistakes or not.
In any case, this is something my wife says, but it doesn't sound quite natural to me, but I'm just not sure any more.
Is there a more natural way of saying it (in British English, or other dialects)?

A: I have come across this usage of the catenation feel + to-infinitive at Church ('I felt to ask him...'; 'I felt to go to ...') but consider it to be non-standard. I can't find dictionary or Google Ngram support for the catenative usage. Perhaps it is a downtoning of 'I felt led to ask him...' here.
The feel + that-clause

I don't feel [that] I can trust him.
I felt [ ] I ought to ask him.

(whether the 'that' is included or not) is quite acceptable, of course.

A: I'd say, "I don't feel like trusting him."

A: I think I would say 'I do not feel inclined to trust him'. I can understand why the Italian might be different. Most would agree that the Italians are more 'touchy-feely' than the English. What a fabulous place it is. Lucky you!


text:
Q: Angular : sanitizing HTML stripped some content on css style
I am using a wysiwyg editor in my Angular component, when i try to preview the content of the editor, (after i apply center to the text),
i get this warning:

WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss).
platform-browser.es5.js:1015

when i inspect the html:

Text Here...

but when i try to use console.log() to preview the content of the editor i get:

Text Here...

A: This is by design in Angular 2+ for security reasons. You can workaround it by using the DomSanitizer class.
For example you can make a pipe that prevents sanitization of the value:
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Pipe({ name: 'noSanitize' })
export class NoSanitizePipe implements PipeTransform {
   constructor(private domSanitizer: DomSanitizer) {

   }
   transform(html: string): SafeHtml {
      return this.domSanitizer.bypassSecurityTrustHtml(html);
   }
}

Then you can use it in binding for example like this:


text:
Q: Drawing a rectangle above an inline tikz picture TikZ noob here: The following is a simplified and equivalentdescription of my problem.
The following TikZ code
\begin{tikzpicture}
       \node[inner sep=0pt] (stony1) at (0,0){\includegraphics[width=.04\textwidth]{example-image-a}};
\end{tikzpicture}

produces the following a picture inline with my latex text as expected . However, I would like to add some tikz code that produces a blue rectangle above that same included image of the same (horizontal) width.  I should be able to customize the height of that rectangle.
What code should I add for this?
In a nutshell, I want to go from the following picture to

the following picture

A: You can draw a rectangle on top of the node containing the image.
The yshift=1ex adjusts the height of the blue box.
\documentclass{article}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
    \node[inner sep=0pt,outer sep=0pt] (stony1) at (0,0) {\includegraphics[width=.04\textwidth]{example-image-a}};
    \fill[blue] (stony1.north west) rectangle ([yshift=1ex]stony1.north east);
\end{tikzpicture}
\end{document}


text:
Q: Router Guards canActivate not working with API in angular This  Auth guard not working with API  response.  When I run the code it always returns true. but I want to run guard base on api response. is their way to achieving that?

import {Injectable} from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router, Route} from '@angular/router';
import {
    HttpClient,
    HttpHeaders
} from '@angular/common/http';
import {Observable} from 'rxjs';

@Injectable()
export class AuthGuard implements CanActivate {

    constructor(private router: Router, private http: HttpClient) {
    }

    canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

        const sendData = {};
        sendData['id'] = sessionStorage.getItem('id');
        console.log(JSON.stringify(sendData));
        const headers = new HttpHeaders()
            .set('Content-Type', 'application/json')
            .set('token', sessionStorage.getItem('auth') ? sessionStorage.getItem('auth') : 'test');
        this.http.post('http://127.0.0.1:5000/auth',
            JSON.stringify(sendData), {
                headers
            })
            .subscribe(
                (val: any) => {
                },
                response => {

                    this.router.navigate(['/login']);
                },
                () => {
                    console.log('The POST observable is now completed.');
                });

        return true;

    }

}

A:
Check this. You have returned true at the end of the canActivate authguard. This way it will always return true. Instead you should have it in the subscribe method of the http post request based on your condition. Something like this..
this.http.post('http://127.0.0.1:5000/auth',
JSON.stringify(sendData), {
    headers
}).pipe(map(response => {
    //suppose we get isAuthenticated bit in response. Your response obj may vary but logic shall be same
    if (response.isAuthenticated) {
        return true;
    }
    else {
        return false;
    }
}));

Thanks.


text:
Q: Specifying parameters in multiple QQ-plots using ggplot2 I have melted a data set "mtotal", and want to make a QQ-plot against a normal distribution such that each variable in "mtotal" has its own specified parameters (mean() and sd()).
So far my code looks like this:
qplot(sample = value, data = mtotal, dist = qnorm) +
            facet_wrap(~variable, scales = "free")

It makes a QQ-plot for each variable against a standard normal distribution.
mtotal looks like this:
"Variable"   "Value"
 V1            10
 V1            11
 V1            8
 V1            12
 V2            100
 V2            102
  .            .
  .            .
  .            .


text:
Q: C++ Pointers in 64bit instructions I'm writing a jit compiler (64bit only, windows). I need to access variables of the c++ program, by reference (pointer).
Example: Adding a 32bit integer from memory to a 32bit register, using this instruction:
opcode "03 /r" : ADD r32, m32. (valid in 64bit mode)

unfortunately this is asking for a 32bit displacement, but I (only?) have a 64bit pointer to the c++ variable.
My question: is there some way to get a 32bit displacement from a 64bit c++ pointer?
Or if not, more generally, how would I adress c++ variables?
I also tried to mov the pointer value to rax and use indirect adressing [rax]. Which doesn't seem to work either.
I've looked at some dis-assembly (clang), and it seems to use RIP (relative instruction pointer), such as
mov dword ptr [rip + test], 2358

Which seems odd, as rip changes on every instruction (as far as I know).
Any pointers in the right direction would be greatly appreciated.
Edit: Indirect adressing through, [rax], is working now! I had a bug in the c++. Still no luck with 32bit displacement adressing.

A: Just found the answer in the Intel Developer Manual vol 1 page 70:
"Generally, displacements and immediates in 64-bit mode are not extended to 64 bits. They are still limited to 32 bits and sign-extended during effective-address calculations. In 64-bit mode, however, support is provided for 64-bit displacement and immediate forms of the MOV instruction."
And in the Intel Instruction Set Reference Manual page 42:
"In 64-bit mode, the ModR/M Disp32 (32-bit displacement) encoding is re-defined to be RIP+Disp32 rather than displacement-only. See Table 2-7."
So disp32 can be used in 64bit mode only for relativ to instruction pointer adressing.


text:
Q: Letting users generate XML product feed through my website My problem is that i need to let users create an XML feed with all my sites products (including photos and prices) so that they can then upload it to their sites. How can i achieve that?

A: You can use wordpress feeds
Refer the following plugin for products
WooCommerce Product Feed Manager – WordPress plugin ...
https://wordpress.org/plugins/best-woocommerce-feed/


text:
Q: Pass argument to void function How to pass argument line to void? it keep show error the data type should be

line [100][260]

I try other ways like

wchar_t * line[][]

still can't
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <windows.h>

using namespace std;

  void test(DWORD a, wchar_t * line[])
    {

        unsigned int i;

        for (i = 0; i < a; i++)
        {
            wcout << line[i];
        }

    }

    int main()
    {
        FILE *pFile;
        wchar_t *file = L"d:\\a.txt";
        wchar_t line[100][MAX_PATH];
        unsigned int a = 0;
        if (_wfopen_s(&pFile, file, L"r, ccs = UNICODE") == 0)
        {
            while (fgetws(line[a], 100, pFile))
            {
                a++;
            }
        }

        test(a, line);

        return 0;
    }

Thank you

A: Your function wants a 1-dimensional array of pointers to null-terminated strings. But you are trying to pass it a 2-dimensional array of chars instead.  They are NOT the same thing!
At the very least, you can create a second array that contains pointers to the elements of the first array, eg:
#include "stdafx.h"

#include <iostream>
#include <fstream>

#include <windows.h>

void test(DWORD a, wchar_t * lines[])
{
    for (unsigned int i = 0; i < a; ++i) {
        std::wcout << lines[i] << std::endl;
    }
}

int main()
{
    FILE *pFile;
    wchar_t *file = L"d:\\a.txt";
    wchar_t lineData[100][MAX_PATH];
    wchar_t* lines[100];
    wchar_t *line;

    unsigned int a = 0;
    if (_wfopen_s(&pFile, file, L"r, ccs = UNICODE") == 0)
    {
        do
        {
            line = lineData[a];

            if (!fgetws(line, MAX_PATH, pFile))
                break;

            size_t len = wcslen(line);
            if ((len > 0) && (line[len-1] == L'\n'))
                line[--len] = 0;

            lines[a] = line;
        }
        while (++a < 100);

        fclose(pFile);
    }

    test(a, lines);

    return 0;
}

That being said, since you are using C++ anyway, you should be using C++ functionality instead of C functionality to read the file, eg:
#include "stdafx.h"
#include <windows.h>

#include <iostream>
#include <fstream>
#include <vector>
#include <string>

void test(const std::vector<std::wstring> &lines)
{
    for (std::wstring &line : lines) {
        std::wcout << line << std::endl;
    }

    /* or: prior to C++11:

    for (std::size_t i = 0; i < lines.size(); ++i) {
        std::wcout << lines[i] << std::endl;
    }

    or:

    for (std::vector<std::wstring>::iterator iter = lines.begin(); iter != lines.end(); ++iter) {
        std::wcout << *iter << std::endl;
    }
    */
}

int main()
{
    std::vector<std::wstring> lines;
    std::wstring line;

    std::wifstream file(L"d:\\a.txt");
    if (file.is_open())
    {
        while (std::getline(file, line)) {
            lines.push_back(line);
        }
        file.close();
    }

    test(lines);

    return 0;
}


text:
Q: UIAlertController not working in iOS 9 I have added the UIAlertController code showing login and password textfields, it works for iOS 8 but in iOS 9 not works. The textfields shrinks as shown in figure below
The code I am trying is as follows :
 - (void)toggleLoginLdap:(UIViewController *)currentVC
 {

 if ([UIAlertController class])
        {

            self.alertController= [UIAlertController
                                       alertControllerWithTitle:@"Title of Msg"
                                       message:@"Hello"
                                       preferredStyle:UIAlertControllerStyleAlert];

            UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                       handler:^(UIAlertAction * action){
                                                           NSString *userName = self.alertController.textFields[0].text;
                                                           NSString *password = self.alertController.textFields[1].text;

                                                       }];
            UIAlertAction* cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel
                                                           handler:^(UIAlertAction * action) {

                                                               [self.alertController dismissViewControllerAnimated:YES completion:nil];

                                                           }];

            [self.alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
                 textField.placeholder = @"Username/Email";
                 //textField.preservesSuperviewLayoutMargins = YES;
                textField.autoresizesSubviews = YES;
            }];
            [self.alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
                textField.placeholder = @"Password";
                textField.secureTextEntry = YES;
            }];
            //alertController.view.autoresizesSubviews = YES;
            [self.alertController addAction:ok];
            [self.alertController addAction:cancel];
            [currentVC presentViewController:self.alertController animated:YES completion:nil];
 }

Also tried to show on rootviewcontroller but no luck , same code works on ios 8. Project is old and having support from iOS 5. Any help will be appreciated. Thanks.

A: add [self.alertController.view layoutIfNeeded] after presenting alertController
I had the same problem and it worked

A: I know this question is old but I've been researching this for more than a day.
I stumbled upon a thread in the Pixate freestyle github.
My problem was that we were using Pixate Freestyle pod
If you take your code and put it in a clean Xcode project, it will look fine. There was a workaround mentioned there; but it's in swift. I'll try to find it and post a link when I do.
EDIT: https://github.com/Pixate/pixate-freestyle-ios/issues/178


text:
Q: Magnific popup verticalFit doesn't work I got some trouble with my Magnific lightbox. In my gallery I would like to show vertical pictures in full screen. I found the verticalFit option which seems to be therefore.
$('li.lightbox').magnificPopup({
       type: 'image',
       delegate: 'a',

       image:{
          verticalFit: true, // Fits image in area vertically
          tError: 'The image could not be loaded.'
       },

       gallery: { enabled: true },
       callbacks: {
               buildControls: function () {
               this.contentContainer.append(this.arrowLeft.add(this.arrowRight));
          }
       }
});

Unfortunately the vertical images are not fitting. Does anyone of you has experiences with this plugin, had the same issue or an idea how to fix this?
Here my website where the problem occurs.
I appreciate your help! =)
Cheers
Eric

A: After many hours of searching, the problem was super simple.
<!DOCTYPE html>

Somehow the 'l' of html disappeared and this caused many weird behavior of my code but no error message regarding this!!!
I am so glad that I saw it and totally ashamed to the same time.
Thanks anyway for everybody who put thoughts into this.
Eric


text:
Q: Assembly - MIPS - Unknown size of adjacency table, how to traverse So I am working on doing a depth-first search on a graph of an unknown length. The graph itself will be coded as a "2D" array adjacency table.
Ex:
 Graph: .word 0, 1, 1, 1, 0
        .word 1, 0, 1, 1, 1
        .word 1, 1, 0, 1, 1
        .word 1, 1, 1, 0, 1
        .word 1, 1, 0, 0, 0

But, this graph can be any size, when it gets graded the TAs can put a graph of any size in my code to test. So I do not know the size of the graph.
This becomes a problem when I want to check the adjacency table. How do I know when I have reached the end of a row? How do I advance to a particular row? I know how to advance by word, but I do not know how I could advance to the next row without knowing how many elements (and therefore bytes) I need to advance through.

A: If you want to compute the row size without user intervention, you need a marker after the graph definition (in my example, I used EndGraph label as a marker).
Knowing the address of the first element of the matrix and where the matrix ends allows you to compute the row size, you just have to compute the squared root of the total number of elements of the matrix:
.data
 Graph: .word 0, 1, 1, 1, 0
        .word 1, 0, 1, 1, 1
        .word 1, 1, 0, 1, 1
        .word 1, 1, 1, 0, 1
        .word 1, 1, 0, 0, 0
EndGraph:
.text
  la $t1, Graph
  la $t2, EndGraph
  sub $t2, $t2, $t1  # Get size of matrix
  srl $t2, $t2, 2    # Get the total number of items of the matrix
  move $t3, $zero
computeRowSize:
  mult $t3, $t3
  mflo $t4
  beq $t2, $t4, done
  addiu $t3, $t3, 1
  j computeRowSize
done:
  sll $t3, $t3, 2    # compute the size of each row (number of row elements * size(element)
  # Here you have the RowSize in $t3


text:
Q: inserting different data with different id on single save button I do have three fields which are text input which is of type number.these three data are being saved with different ids but on the same save button.i.e i am inserting data into all the field and then clicking on the save button but the my first data is being saved by different id and the same for the rest of two data.for example if i put 1 in first input,2 in second and 3 in the next since these are number type.but 1 is being saved by say by id:11,2 is being saved by say by id:12,3 is being saved by say by id:13.
my view is like below:
<form class="form">

            High Priority

            <input type="number"name="sval"id="sval"/>Days

            Low Priority

            <input type="number"name="sval" id="sval"/>Days

            Normal

            <input type="number" name="sval" id="sval"/>Days

        <button id="btn" class="btn btn-primary insert">Save</button>
</form>

and the queries are:
var sqld:String;
 sqld = "Delete from app_settings where kunnr = '"+kunnr+"' and ( skey = 'hp_days' or skey = 'np_days' or skey = 'lp_days' )";
 wcisql.query(sqld,'clearRDays');
}
public function saveRDays():void{
 var sqlu:String;
 sqlu = "Insert into app_settings(kunnr,skey,sval) Values ('"+kunnr+"','hp_days','"+hp_days.value+"')";
 wcisql.query(sqlu,'saveRDays');
 sqlu = "Insert into app_settings(kunnr,skey,sval) Values ('"+kunnr+"','np_days','"+np_days.value+"')";
 wcisql.query(sqlu,'saveRDays');
 sqlu = "Insert into app_settings(kunnr,skey,sval) Values ('"+kunnr+"','lp_days','"+lp_days.value+"')";
 wcisql.query(sqlu,'saveRDays');
 $sql = "Select * from app_settings where kunnr = '$kunnr'";
   }

i am adding image as well so that u can get better idea:

how to do this please suggest..
and for my view:

A: use Multiple Insert statement
ckeck out this referenced link:
Multiple INSERT statements vs. single INSERT with multiple VALUES
&
http://www.techonthenet.com/sql/insert.php

A: The problem is you can only use one ID for each HTML element.
So there are two ways to achieve this, one is dynamic the second is static.
Static Solutions:

        High Priority

        <input type="number"name="sval1"id="sval1"/>Days

        Low Priority

        <input type="number"name="sval2" id="sval2"/>Days

        Normal

        <input type="number" name="sval3" id="sval3"/>Days

    <button id="btn" class="btn btn-primary insert">Save</button>

Dynamic Solution

        High Priority

        <input type="number" name="sval[]"/>Days

        Low Priority

        <input type="number" name="sval[]"/>Days

        Normal

        <input type="number" name="sval[]"/>Days

    <button id="btn" class="btn btn-primary insert">Save</button>

Now when you post the form the items will come in array so you have an array
$_GET['sval'] or $_POST['sval'] contains array(1,2,3)


text:
Q: Cannot delete mail from storage in Usage section of IPhone In the usage section of IPhone 5 it says I have 349MB inn Mail.  However, I have deleted ALL inbox, sent, trash etc...there is nothing in the mail.  How do I get the Storage in the Usage section to empty this mail?  Thanks

A: Try rebooting the phone. Press and hold Home+Sleep until the Apple logo appears.
If that doesn't work, and the email account you are using with Mail is not connected using POP3, then try removing the email account and re-adding it. Go to Settings app > Mail, Contacts, Calendars > tap on the specific account > Delete Account. Confirm that you want to delete it, and reboot the phone - press and hold Home + Sleep until the Apple logo appears. Re-add the account by going to Settings app > Mail, Contacts, Calendars > Add Account.

A: Tubedogg is correct, but I would like to add that his method for rebooting the phone actually forces the phone to reboot. This is good for when the phone is non-responsive or you are doing other troubleshooting steps. But it should not be necessary for most applications, including this one. Simply holding down the Sleep button (at the top of the phone, or side if it is a 6/6+) until you get a control that tells you to slide to power off. That is a graceful shutdown.
Removing the account may work and is worth a try. failing that you may want to backup the phone then wipe it: Settings -> General -> Reset -> Erase all content and settings. Once it is wiped, just restore from the backup you just made.
Doing that cleared up a lot of free space on my phone (a 5 with 8.1).


text:
Q: Getting error 500 when adding RewriteCond with .to domain I am trying to redirect traffic coming from a specific domain inside my .htaccess file. It works fine unless I do this for a domain with a .to extension. Any idea what is going on here?
Produces error 500:
RewriteCond %{HTTP_HOST}            ^(www\.)?domain\.to [NC]
RewriteRule ^.*$                    /foo/bar [L]

Works fine:
RewriteCond %{HTTP_HOST}            ^(www\.)?domain\.com [NC]
RewriteRule ^.*$                    /foo/bar [L]

A: Since I do not know for sure which rule does produce rewrite loop, I can only suggest this approach at this moment:
RewriteCond %{HTTP_HOST} ^(www\.)?domain\.to [NC]
RewriteCond %{REQUEST_URI} !^/foo/bar
RewriteRule ^.*$ /foo/bar [L]

Your attempt is not technically correct for 2 reasons:

*

*in .htaccess URL will be without leading slash (I'm referring to $1);

*you are using $1 .. but you have no matching group setup (in other words $1 will always be empty).

If still nothing -- please provide real htaccess ... or try enabling rewrite debugging (RewriteLogLevel 9) -- but for this you have to have full control over Apache server, as this directive cannot be placed in .htaccess (only server config / virtual host context) + you will need to restart Apache to re-read configuration file.

Try adding this rule somewhere on the top -- where it will be appropriate:
# do not do anything for already existing files
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule .+ - [L]


text:
Q: cannot get getCurrentUser() after ajaxSuccess after i done with this post, and i already add my code into application.groovy like this
grails.plugin.springsecurity.controllerAnnotations.staticRules = [
[pattern: '/',               access: ['permitAll']],
[pattern: '/error',          access: ['permitAll']],
[pattern: '/index',          access: ['permitAll']],
[pattern: '/shutdown',       access: ['permitAll']],
[pattern: '/assets/**',      access: ['permitAll']],
[pattern: '/**/js/**',       access: ['permitAll']],
[pattern: '/**/css/**',      access: ['permitAll']],
[pattern: '/**/images/**',   access: ['permitAll']],
[pattern: '/**/favicon.ico', access: ['permitAll']],
[pattern: '/login/ajaxSuccess',       access: ['permitAll']],
[pattern: '/login/ajaxSuccess/**',       access: ['permitAll']],
[pattern: '/**/ajaxSuccess/**',       access: ['permitAll']]

]
my error log become like this..
this is corporateUserService.groovy file
def getCurrentCifUser() { //line 949
def cifUser = CifUser.find("from com.vastpalaso.app.cif.CifUser cu where cu.userDetails.user.id=?", [
                    springSecurityService.principal.id //line 950
            ])

            return cifUser
        }

and this is in logincotroller..
def cifUser = corporateUserService.getCurrentCifUser() //line 168

A: Try changing like 950 segment to :
def getCurrentCifUser() {
                def cifUser = CifUser.find("from com.vastpalaso.app.cif.CifUser cu where cu.userDetails.user=?", [
                                springSecurityService.currentUser
                ])

                return cifUser
        }

Now going back to your original question
How about you change your HTTPURLConnection to be more like this on the android app:
public class BasicAuthenticationExample {

    public static final String URL_SECURE = "[secure url]";
    public static final String URL_LOGOUT = "[logout url]";

    private HttpClient client = null;

    /**
     * Constructor for BasicAuthenticatonExample.
     */
    public BasicAuthenticationExample(String host, int port) {
        client = new HttpClient();

        List<String> authPrefs = new ArrayList<String>(2);
        authPrefs.add(AuthPolicy.DIGEST);
        authPrefs.add(AuthPolicy.BASIC);
        client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM),
                new UsernamePasswordCredentials(ConnectionConstants.USERNAME, ConnectionConstants.PASSWORD));
    }

    public static void main(String[] args) {

        BasicAuthenticationExample example = new BasicAuthenticationExample("localhost", 8080);

        // create a GET method that reads a file over HTTPS, we're assuming
        // that this file requires basic authentication using the realm above.
        GetMethod get = new GetMethod(URL_SECURE);

        // Tell the GET method to automatically handle authentication. The
        // method will use any appropriate credentials to handle basic
        // authentication requests. Setting this value to false will cause
        // any request for authentication to return with a status of 401.
        // It will then be up to the client to handle the authentication.
        get.setDoAuthentication(true);

        try {
            // execute the GET
            int status = example.client.executeMethod(get);

            // print the status and response
            System.out.println(status + example.client.getState().toString() + "\n" + get.getStatusLine()
                    + get.getResponseBodyAsString());

            example.logout();
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // release any connection resources used by the method
            get.releaseConnection();
        }
    }

    private void logout() throws HttpException, IOException {
        // create a GET method that reads a file over HTTPS, we're assuming
        // that this file requires basic authentication using the realm above.
        System.out.println("Logging out...");
        System.out.println("--------------");
        GetMethod get = new GetMethod(URL_LOGOUT);
        try {
            // execute the GET
            int status = client.executeMethod(get);

            // print the status and response
            System.out.println(status + client.getState().toString() + "\n" + get.getStatusLine()
                    + get.getResponseBodyAsString());

        } finally {
            // release any connection resources used by the method
            get.releaseConnection();
        }
    }

}

Also a point of reference here


text:
Q: Printing HTML tables with repeated header rows and non-breaking body rows I've been Googling back and forth for a few hours now, out of sheer frustration that the seemingly simple, basic task of printing a table so that page breaks fall in a sane manner appears to be completely impossible to achieve.

Background: the HTML/CSS file
The basis for all this is a dynamic HTML/CSS page that represents an invoice. It consists of a header area, a table listing invoice items and a footer area. The header and footer areas are fairly fixed in size (each about 5 cm in height); the table naturally varies greatly depending on how many items the invoice has.
When the invoice is fairly short, printing (or printing to PDF) works fine in most browsers – the entire invoice is on one page, and things look dandy. With longer invoices, though, things completely fall apart and the table gets mangled in various different ways (see "The problem" below).
The body element on the page is a grid container controlling the layout, with the table inside a full-width section. The fiddle at the end of the question shows the structure and the broken layout when printing.

The problem: sanely break multi-page tables
What I would like to happen when printing multi-page invoices is, I think, quite reasonable and expected behaviour:

*

*The table starts right after the header area as usual

*If page breaks are necessary, they are added between table rows

*Table column headers are repeated at the top of each page

But this seems to be impossible in any browser currently available to me for testing.
Firefox, for some reason, refuses to break the table at all and just leaves the entire page empty after the 5-cm header area and puts the table on the following page; if the table itself is too tall for one page, it will add page breaks later on, but ignoring the break-inside setting and chopping letters in half across the page boundary. (It doesn't seem to want to repeat table headers either, even though most of what I find on Google indicates that this should work in Firefox.)
Chromium browsers like Chrome, Opera and Brave do support both Paged Media and repeated header rows – but they too ignore break-inside for table rows/cells (bug claims to be fixed, but it's clearly not) and also prints repeated header rows on top of body rows, making the output completely illegible.
Safari seems to be the only browser to actually respect the break-inside setting for table content and only add page break between rows – but it doesn't support CSS Paged Media at all (for reasons only known to Apple developers), so you can't control page size, margins, etc., and there doesn't seem to be a way to get header rows to repeat either.
So, am I missing something essential here, or is it really the case that in 2021, no major browser is seemingly capable of printing tables the way you'd assume they ought to print by default?
Is there a way to print multi-page tables in a way that page breaks are only added between rows, not inside them, while still making sure that header rows are repeated on each page and not printed overlaid on top of body rows?

Working snippet

@charset "UTF-8";

@page {
  size: A4 portrait;
  margin: 15mm
}

body {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  row-gap: 5mm;
  align-content: start;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 10pt;
  margin: 0;
  padding: 0
}

p {
  font-size: inherit
}

section {
  grid-column: 1/span all;
  height: -webkit-max-content;
  height: max-content;
  font-size: inherit
}

table {
  width: 100%;
  border-collapse: collapse;
  break-inside: auto
}

table td,
table th {
  padding: 1.5mm;
  border-bottom: 1px solid #ccc;
  border-top: 1px solid #ccc;
  vertical-align: top;
  font-size: inherit
}

table thead {
  background: #faf9fc;
  font-weight: 700;
  display: table-header-group
}

table th {
  text-align: left;
  vertical-align: bottom
}

table td,
table th,
table tr {
  break-inside: avoid;
  break-after: auto
}

.address {
  grid-column: span 1;
  display: flex;
  flex-direction: column
}

.address p {
  margin: .5em 0
}

.address p.addressheader {
  margin-bottom: 0;
  font-style: italic
}

.address span {
  margin-right: 1rem
}

.amt {
  text-align: right
}

.date {
  align-self: start;
  grid-column: 2/span 1
}

.invoice-number {
  grid-column: span 1
}

.items {
  margin: 1cm 0
}

.metadata,
.subtotals {
  grid-column: span 2;
  padding: 1.5mm;
  display: grid;
  grid-template-columns: 1fr 2fr
}

.signature {
  display: -webkit-box;
  display: flex;
  justify-content: center;
  align-items: center
}

.signature div {
  width: 60%;
  border-bottom: 1px solid #000;
  display: -webkit-box;
  display: flex;
  align-items: flex-end
}

.signature div p {
  min-width: 30%;
  margin-bottom: 0;
}

.subtotals {
  grid-template-columns: 1fr 1fr;
  text-align: right
}

.subtotals > b {
  text-align: left
}

.title {
  font-size: 24pt;
  font-weight: 700;
  text-transform: uppercase;
  text-align: center;
  align-self: center
}
<!DOCTYPE html>

        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Sample Invoice</title>

Sample invoice

Ship to:

                Recipient Name

                123 Street

                12345 City

                United States

Contact Person Name

                +1 (555) 123-4567

                mail@example.com

Bill to:

                Customer Name

                123 Street

                12345 City

                United States

Contact Person Name

                +1 (555) 123-4567

                mail@example.com

From:

                Company Name

                123 Street

                12345 City

                United States

Contact Person Name

                +1 (555) 123-4567

                mail@example.com

            Invoice Date

            5 January 2022

            Invoice Number

            999

                        HS Code
                        EAN
                        Commodity
                        Origin
                        Qty
                        Rate
                        Total

                        12345678
                        1234567890123
                        A very useful item
                        US
                        1
                        5.00
                        5.00

                        12345678
                        1234567890123
                        A very useful item
                        US
                        1
                        5.00
                        5.00

                        12345678
                        1234567890123
                        A very useful item
                        US
                        1
                        5.00
                        5.00

                        12345678
                        1234567890123
                        A very useful item
                        US
                        1
                        5.00
                        5.00

                        12345678
                        1234567890123
                        A very useful item
                        US
                        1
                        5.00
                        5.00

                        12345678
                        1234567890123
                        A very useful item
                        US
                        1
                        5.00
                        5.00

                        12345678
                        1234567890123
                        A very useful item
                        US
                        1
                        5.00
                        5.00

                        12345678
                        1234567890123
                        A very useful item
                        US
                        1
                        5.00
                        5.00

                        12345678
                        1234567890123
                        A very useful item
                        US
                        1
                        5.00
                        5.00

                        12345678
                        1234567890123
                        A very useful item
                        US
                        1
                        5.00
                        5.00

                        12345678
                        1234567890123
                        A very useful item
                        US
                        1
                        5.00
                        5.00

                        12345678
                        1234567890123
                        A very useful item
                        US
                        1
                        5.00
                        5.00

                        12345678
                        1234567890123
                        A very useful item
                        US
                        1
                        5.00
                        5.00

                        12345678
                        1234567890123
                        A very useful item
                        US
                        1
                        5.00
                        5.00

                        12345678
                        1234567890123
                        A very useful item
                        US
                        1
                        5.00
                        5.00

                        12345678
                        1234567890123
                        A very useful item
                        US
                        1
                        5.00
                        5.00

                        12345678
                        1234567890123
                        A very useful item
                        US
                        1
                        5.00
                        5.00

                        12345678
                        1234567890123
                        A very useful item
                        US
                        1
                        5.00
                        5.00

                        12345678
                        1234567890123
                        A very useful item
                        US
                        1
                        5.00
                        5.00

                        12345678
                        1234567890123
                        A very useful item
                        US
                        1
                        5.00
                        5.00

                        12345678
                        1234567890123
                        A very useful item
                        US
                        1
                        5.00
                        5.00

                        12345678
                        1234567890123
                        A very useful item
                        US
                        1
                        5.00
                        5.00

                        12345678
                        1234567890123
                        A very useful item
                        US
                        1
                        5.00
                        5.00

                        12345678
                        1234567890123
                        A very useful item
                        US
                        1
                        5.00
                        5.00

                        12345678
                        1234567890123
                        A very useful item
                        US
                        1
                        5.00
                        5.00

                        12345678
                        1234567890123
                        A very useful item
                        US
                        1
                        5.00
                        5.00

                        12345678
                        1234567890123
                        A very useful item
                        US
                        1
                        5.00
                        5.00

                        12345678
                        1234567890123
                        A very useful item
                        US
                        1
                        5.00
                        5.00

                        12345678
                        1234567890123
                        A very useful item
                        US
                        1
                        5.00
                        5.00

                        12345678
                        1234567890123
                        A very useful item
                        US
                        1
                        5.00
                        5.00

                        12345678
                        1234567890123
                        A very useful item
                        US
                        1
                        5.00
                        5.00

                        12345678
                        1234567890123
                        A very useful item
                        US
                        1
                        5.00
                        5.00

            Tracking number1234567890
            Transport typeDHL Standard
            Reference999
            Shipment weight (kg)100
            CurrencyUSD
            Inco termsDDP
            Export reasonPermanent
            Number of colli3

            Subtotal125.00
            Freight costs20.00
            Insurance5.00
            Other0.00
            VAT10.00
            Total160.00

5 Jan 2022

                [signature]


text:
Q: Server Error in '/' Application. Incorrect Syntax near ')' Im creating and INSERT form and i got this error, this is my code in codebehind:
protected void btnSave_Click(object sender, EventArgs e)
{
    string Selected = category_ddl.SelectedValue;
    lb_date.Text = System.DateTime.Now.ToLongDateString();
    process();
}

private void process()
{
    string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename= |DataDirectory|\ASPNETDB.MDF;Integrated Security=True;User Instance=True";
    string sql = "INSERT INTO News (date_time,title,author,source,category,description,) VALUES (@date, @title, @author,@source,@Selected,@description)";
    SqlConnection conn = new SqlConnection(connectionString);
    conn.Open();
    SqlCommand cmd = new SqlCommand(sql, conn);
    cmd.Parameters.AddWithValue("@date", lb_date.Text.ToString());
    cmd.Parameters.AddWithValue("@title", title_tb.Text.ToString());
    cmd.Parameters.AddWithValue("@author", author_tb.Text.ToString());
    cmd.Parameters.AddWithValue("@source", source_tb.Text.ToString());
    cmd.Parameters.AddWithValue("@Selected", category_ddl.Text.ToString());
    cmd.Parameters.AddWithValue("@description", desc_tb.Text.ToString());
    cmd.ExecuteNonQuery();
    conn.Close();
}

and this is my error:
Server Error in '/' Application.

Incorrect syntax near ')'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near ')'.

Source Error:

Line 37:             cmd.Parameters.AddWithValue("@Selected", category_ddl.Text.ToString());
Line 38:             cmd.Parameters.AddWithValue("@description", desc_tb.Text.ToString());
Line 39:             cmd.ExecuteNonQuery();
Line 40:             conn.Close();
Line 41:         }

the Line 39:             cmd.ExecuteNonQuery(); is highlighted in color red. what did I do something wrong?,i have this using:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

A: You have an extra comma after description:

string sql = "INSERT INTO News (date_time,title,author,source,category,description,)


text:
Q: No SMB access when using two routers I have the following network topology:

The desktop PC is connected via WiFi to the D-Link - Router. The problem is to access SMB-Shares on the Synology NAS.
I can ping the NAS and also access the webinterface (via hostname or IP) on different ports. But I cannot access any SMB-Share.
When I, however, connect the Desktop PC to the Fritzbox instead (retrieving an address from the 192.168.178.xxx subnet) I can access the SMB-shares on the NAS.
There are no firewall rules on the D-Link or on the FritzBox that explicitly block any port. On the Synology there are no log entries about the attempt.
Any clue how to even find out which device is causing the trouble there?
This all had worked before, so either I screwed up a configuration part anywhere or an update caused that issue.

A: Solved it. It might be quite an usual solution:
Looks like the D-Link-Router blocked SMB3 - Traffic. (And SMB2, too) Switching to SMB1 on my NAS solved the problem.