text:
Q: How can I determine if a file is a PDF file? I am using PdfBox in Java to extract text from PDF files. Some of the input files provided are not valid and PDFTextStripper halts on these files. Is there a clean way to check if the provided file is indeed a valid PDF?

A: Here an adapted Java version of NinjaCross's code.
/**
 * Test if the data in the given byte array represents a PDF file.
 */
public static boolean is_pdf(byte[] data) {
    if (data != null && data.length > 4 &&
            data[0] == 0x25 && // %
            data[1] == 0x50 && // P
            data[2] == 0x44 && // D
            data[3] == 0x46 && // F
            data[4] == 0x2D) { // -

        // version 1.3 file terminator
        if (data[5] == 0x31 && data[6] == 0x2E && data[7] == 0x33 &&
                data[data.length - 7] == 0x25 && // %
                data[data.length - 6] == 0x25 && // %
                data[data.length - 5] == 0x45 && // E
                data[data.length - 4] == 0x4F && // O
                data[data.length - 3] == 0x46 && // F
                data[data.length - 2] == 0x20 && // SPACE
                data[data.length - 1] == 0x0A) { // EOL
            return true;
        }

        // version 1.3 file terminator
        if (data[5] == 0x31 && data[6] == 0x2E && data[7] == 0x34 &&
                data[data.length - 6] == 0x25 && // %
                data[data.length - 5] == 0x25 && // %
                data[data.length - 4] == 0x45 && // E
                data[data.length - 3] == 0x4F && // O
                data[data.length - 2] == 0x46 && // F
                data[data.length - 1] == 0x0A) { // EOL
            return true;
        }
    }
    return false;
}

And some simple unit tests:
@Test
public void test_valid_pdf_1_3_data_is_pdf() {
    assertTrue(is_pdf("%PDF-1.3 CONTENT %%EOF \n".getBytes()));
}

@Test
public void test_valid_pdf_1_4_data_is_pdf() {
    assertTrue(is_pdf("%PDF-1.4 CONTENT %%EOF\n".getBytes()));
}

@Test
public void test_invalid_data_is_not_pdf() {
    assertFalse(is_pdf("Hello World".getBytes()));
}

If you come up with any failing unit tests, please let me know.

A: I was using some of the suggestions I found here and on other sites/posts for determining whether a pdf was valid or not.  I purposely corrupted a pdf file, and unfortunately, many of the solutions did not detect that the file was corrupted.
Eventually, after tinkering around with different methods in the API, I tried this:
PDDocument.load(file).getPage(0).getContents().toString();

This did not throw an exception, but it did output this:
 WARN  [COSParser:1154] The end of the stream doesn't point to the correct offset, using workaround to read the stream, stream start position: 171, length: 1145844, expected end position: 1146015

Personally, I wanted an exception to be thrown if the file was corrupted so I could handle it myself, but it appeared that the API I was implementing already handled them in their own way.
To get around this, I decided to try parsing the files using the class that gave the warm statement (COSParser).  I found that there was a subclass, called PDFParser, which inherited a method called "setLenient", which was the key (https://pdfbox.apache.org/docs/2.0.4/javadocs/org/apache/pdfbox/pdfparser/COSParser.html).
I then implemented the following:
        RandomAccessFile accessFile = new RandomAccessFile(file, "r");
        PDFParser parser = new PDFParser(accessFile);
        parser.setLenient(false);
        parser.parse();

This threw an Exception for my corrupted file, as I wanted.  Hope this helps someone out!

A: Pdf files begin "%PDF"  (open one in TextPad or similar and take a look)
Any reason you can't just read the file with a StringReader and check for this?

A: You have to try this....
public boolean isPDF(File file){
    file = new File("Demo.pdf");
    Scanner input = new Scanner(new FileReader(file));
    while (input.hasNextLine()) {
        final String checkline = input.nextLine();
        if(checkline.contains("%PDF-")) {
            // a match!
            return true;
        }
    }
    return false;
}

A: Maybe I am too late to answer. But you should have a look at Tika. It uses PDFBox Parser internally to parse PDF's
You just need to import tika-app-latest*.jar
 public String parseToStringExample() throws IOException, SAXException, TikaException
 {

      Tika tika = new Tika();
      try (InputStream stream = ParsingExample.class.getResourceAsStream("test.pdf")) {
           return tika.parseToString(stream); // This should return you the pdf's text
      }
}

It would be a much cleaner solution . You can refer here for more details of Tika Usage : https://tika.apache.org/1.12/api/

A: Here is what I use into my NUnit tests, that must validate against multiple versions of PDF generated using Crystal Reports:
public static void CheckIsPDF(byte[] data)
    {
        Assert.IsNotNull(data);
        Assert.Greater(data.Length,4);

        // header
        Assert.AreEqual(data[0],0x25); // %
        Assert.AreEqual(data[1],0x50); // P
        Assert.AreEqual(data[2],0x44); // D
        Assert.AreEqual(data[3],0x46); // F
        Assert.AreEqual(data[4],0x2D); // -

        if(data[5]==0x31 && data[6]==0x2E && data[7]==0x33) // version is 1.3 ?
        {
            // file terminator
            Assert.AreEqual(data[data.Length-7],0x25); // %
            Assert.AreEqual(data[data.Length-6],0x25); // %
            Assert.AreEqual(data[data.Length-5],0x45); // E
            Assert.AreEqual(data[data.Length-4],0x4F); // O
            Assert.AreEqual(data[data.Length-3],0x46); // F
            Assert.AreEqual(data[data.Length-2],0x20); // SPACE
            Assert.AreEqual(data[data.Length-1],0x0A); // EOL
            return;
        }

        if(data[5]==0x31 && data[6]==0x2E && data[7]==0x34) // version is 1.4 ?
        {
            // file terminator
            Assert.AreEqual(data[data.Length-6],0x25); // %
            Assert.AreEqual(data[data.Length-5],0x25); // %
            Assert.AreEqual(data[data.Length-4],0x45); // E
            Assert.AreEqual(data[data.Length-3],0x4F); // O
            Assert.AreEqual(data[data.Length-2],0x46); // F
            Assert.AreEqual(data[data.Length-1],0x0A); // EOL
            return;
        }

        Assert.Fail("Unsupported file format");
    }

A: The answer by Roger Keays is wrong! since not all PDF files in version 1.3 and not all terminated by EOL.
The answer below works for all not corrupted pdf files:
public static boolean is_pdf(byte[] data) {
    if (data != null && data.length > 4
            && data[0] == 0x25 && // %
            data[1] == 0x50 && // P
            data[2] == 0x44 && // D
            data[3] == 0x46 && // F
            data[4] == 0x2D) { // -

        // version 1.3 file terminator
        if (//data[5] == 0x31 && data[6] == 0x2E && data[7] == 0x33 &&
                data[data.length - 7] == 0x25 && // %
                data[data.length - 6] == 0x25 && // %
                data[data.length - 5] == 0x45 && // E
                data[data.length - 4] == 0x4F && // O
                data[data.length - 3] == 0x46 && // F
                data[data.length - 2] == 0x20 // SPACE
                //&& data[data.length - 1] == 0x0A// EOL
                ) {
            return true;
        }

        // version 1.3 file terminator
        if (//data[5] == 0x31 && data[6] == 0x2E && data[7] == 0x34 &&
                data[data.length - 6] == 0x25 && // %
                data[data.length - 5] == 0x25 && // %
                data[data.length - 4] == 0x45 && // E
                data[data.length - 3] == 0x4F && // O
                data[data.length - 2] == 0x46 // F
                //&& data[data.length - 1] == 0x0A // EOL
                ) {
            return true;
        }
    }
    return false;
}

A: Relying on magic numbers does not really appeal to me. I ended up using a preflight library from Apache for this:

compile group: 'org.apache.pdfbox', name: 'preflight', version:
  '2.0.19'

private boolean isPdf(InputStream fileInputStream) {
    try {
        PreflightParser preflightParser = new PreflightParser(new ByteArrayDataSource(fileInputStream));
        preflightParser.parse();
        return true;
    } catch (Exception e) {
        return false;
    }
}

PreflightParser has constructors for files and other data sources.

A: Here is a method that checks for the presence of %%EOF with optional checks for white-space characters. You can pass in either a File or a byte[] object. There is less restriction for white-space characters in some PDF versions.
public boolean isPdf(byte[] data) {
    if (data == null || data.length < 5) return false;
    // %PDF-
    if (data[0] == 0x25 && data[1] == 0x50 && data[2] == 0x44 && data[3] == 0x46 && data[4] == 0x2D) {
        int offset = data.length - 8, count = 0; // check last 8 bytes for %%EOF with optional white-space
        boolean hasSpace = false, hasCr = false, hasLf = false;
        while (offset < data.length) {
            if (count == 0 && data[offset] == 0x25) count++; // %
            if (count == 1 && data[offset] == 0x25) count++; // %
            if (count == 2 && data[offset] == 0x45) count++; // E
            if (count == 3 && data[offset] == 0x4F) count++; // O
            if (count == 4 && data[offset] == 0x46) count++; // F
            // Optional flags for meta info
            if (count == 5 && data[offset] == 0x20) hasSpace = true; // SPACE
            if (count == 5 && data[offset] == 0x0D) hasCr    = true; // CR
            if (count == 5 && data[offset] == 0x0A) hasLf    = true; // LF / EOL
            offset++;
        }

        if (count == 5) {
            String version = data.length > 13 ? String.format("%s%s%s", (char) data[5], (char) data[6], (char) data[7]) : "?";
            System.out.printf("Version : %s | Space : %b | CR : %b | LF : %b%n", version, hasSpace, hasCr, hasLf);
            return true;
        }
    }

    return false;
}

public boolean isPdf(File file) throws IOException {
    return isPdf(file, false);
}

// With version: 16 bytes, without version: 13 bytes.
public boolean isPdf(File file, boolean includeVersion) throws IOException {
    if (file == null) return false;
    int offsetStart = includeVersion ? 8 : 5, offsetEnd = 8;
    byte[] bytes = new byte[offsetStart + offsetEnd];
    InputStream is = new FileInputStream(file);
    try {
        is.read(bytes, 0, offsetStart); // %PDF-
        is.skip(file.length() - bytes.length); // Skip bytes
        is.read(bytes, offsetStart, offsetEnd); // %%EOF,SP?,CR?,LF?
    } finally {
        is.close();
    }
    return isPdf(bytes);
}

A: you can find out the mime type of a file (or byte array), so you dont dumbly rely on the extension. I do it with aperture's MimeExtractor (http://aperture.sourceforge.net/) or I saw some days ago a library just for that (http://sourceforge.net/projects/mime-util)
I use aperture to extract text from a variety of files, not only pdf, but have to tweak thinks for pdfs for example (aperture uses pdfbox, but i added another library as fallback when pdfbox fails)

A: Since you use PDFBox you can simply do:
PDDocument.load(file);

It'll fail with an Exception if the PDF is corrupted etc.
If it succeeds you can also check if the PDF is encrypted using .isEncrypted()

A: There is a very convenient and simple library for testing PDF content:
https://github.com/codeborne/pdf-test
API is very simple:
import com.codeborne.pdftest.PDF;
import static com.codeborne.pdftest.PDF.*;
import static org.junit.Assert.assertThat;

public class PDFContainsTextTest {
  @Test
  public void canAssertThatPdfContainsText() {
    PDF pdf = new PDF(new File("src/test/resources/50quickideas.pdf"));
    assertThat(pdf, containsText("50 Quick Ideas to Improve your User Stories"));
  }
}

A: In general, we can like this, any pdf version going to finish with %%EOF so we can check like bellow.
public static boolean is_pdf(byte[] data) {
        String s = new String(data);
        String d = s.substring(data.length - 7, data.length - 1);
        if (data != null && data.length > 4 &&
                data[0] == 0x25 && // %
                data[1] == 0x50 && // P
                data[2] == 0x44 && // D
                data[3] == 0x46 && // F
                data[4] == 0x2D) { // -

              if(d.contains("%%EOF")){
                 return true;
              }
        }
        return false;
    }


text:
Q: How to change the session value of php with different events in jquery $("#family").dblclick(function(){
 <?php $_SESSION["album_name"] = "family"; ?>
 location.href = "<?php echo base_url(); ?>index.php/welcome/home_images/";
});
$("#friends").dblclick(function(){
 <?php $_SESSION["album_name"] = "friends"; ?>
 location.href = "<?php echo base_url(); ?>index.php/welcome/home_images/";
});
$("#work").dblclick(function(){
 <?php $_SESSION["album_name"] = "work"; ?>
 location.href = "<?php echo base_url(); ?>index.php/welcome/home_images/";
});
$("#others").dblclick(function(){
 <?php $_SESSION["album_name"] = "others"; ?>
 location.href = "<?php echo base_url(); ?>index.php/welcome/home_images/";
});

I want to change the session value with various dblclick events in jquery.
But it is storing the last value ie= "others" even if i dblclick on some other id's.

A: You need to use  ajax for implementing the storing session for every events. Reason for stroung others value in session it is last assignment accoring to to that.

A: You can't output PHP code from JavaScript. With that snippet, your browser will see this:
$("#family").dblclick(function(){
 location.href = "<?php echo base_url(); ?>index.php/welcome/home_images/";
});
$("#friends").dblclick(function(){
 location.href = "<?php echo base_url(); ?>index.php/welcome/home_images/";
});
$("#work").dblclick(function(){
 location.href = "<?php echo base_url(); ?>index.php/welcome/home_images/";
});
$("#others").dblclick(function(){
 location.href = "<?php echo base_url(); ?>index.php/welcome/home_images/";
});

While $_SESSION['album_name'] would contain the last value that you assigned, in this case: 'others'.
Why? Because PHP is interpreted in your server, it generates an output (in your case, an HTML document) and sends it in a response.
You could use PHP inside JavaScript, for example, to print values from the server, like this:
// Assuming $foo is 'bar', will output var foo = 'bar';
var foo = '<?php echo $_SESSION['foo']; ?>';

To do what you are trying to do, you need to make AJAX calls to your server:
$("#family").dblclick(function(){
 $.ajax({
   url: 'http://yourdomain.com/album_name.php',
   type: 'post',
   data: {albumName: 'family'},
   success: function(response) {
     // this function will be executed when the server responds successfully to the AJAX call
     // response will have whatever you send from the server.
     // In this example: 'ok'
     alert(response);
   }
 });
});

Then, in your server:
// album_name.php
$whitelist = array('family', 'friends', 'work', 'others');

if (isset($_POST['albumName'] && in_array($_POST['albumName'], $whitelist))
{
  $_SESSION['album_name'] = $_POST['albumName'];
  echo 'ok';
}

A: The only thing that can change a $_SESSION variable is the server. You therefore need to send a request to a PHP script on the server and have that script update the variable. You can't do it on the client side with JavaScript.
You could add the album_name variable to the query string of the URL you are redirecting to and have index.php look for it and update the session value before executing the rest of the script...
...?album_name=family

Then somewhere at the start of index.php ...
if (isset($_GET['album_name'])) {
    $_SESSION['album_name'] = $_GET['album_name'];
}

Make sure this comes after a call to session_start() or the $_SESSION variable won't exist.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change the Y-axis labels and lines dynamically in core plot I want to change the Y-axis dynamically. I have max and min text fields. When I change the max or min fields, the graph will change the Y-axis.
I have tried like following but only two line are coming. Please check the following code.
This is the method for Configure Y-axis.
CPTXYAxis *y = axisSet.yAxis;
y.labelingPolicy              = CPTAxisLabelingPolicyNone;
y.axisLineStyle = axisLineStyle;
y.majorGridLineStyle          = majorGridLineStyle;
y.minorGridLineStyle          = minorGridLineStyle;
y.majorTickLength = 0.0;

NSMutableSet *yLabels = [NSMutableSet setWithCapacity:4];
NSMutableSet *yLocations = [NSMutableSet setWithCapacity:4];

NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];

CGFloat max_value = [[preferences valueForKey:MAX_KEY] integerValue];
CGFloat min_value = [[preferences valueForKey:MIN_KEY] integerValue];

NSLog(@"max_value%f",max_value);

NSInteger range = ((max_value-min_value)*10)/100;

NSLog(@"range%d",range);
newmaxValue = (max_value-min_value) - range;
newMinValue = min_value - range;

yAxisLabels = [NSArray arrayWithObjects:[NSString stringWithFormat:@"%.f",newMinValue], [NSString stringWithFormat:@"%.f",newMinValue+20],[NSString stringWithFormat:@"%.f",newmaxValue-20],[NSString stringWithFormat:@"%.f",newmaxValue], nil];

yAxiscustomTickLocations = [NSArray arrayWithObjects:[NSDecimalNumber numberWithInt:newMinValue], [NSDecimalNumber numberWithInt:newMinValue+20], [NSDecimalNumber numberWithInt:newmaxValue-20], [NSDecimalNumber numberWithInt:newmaxValue],nil];

NSNumberFormatter * nFormatter = [[NSNumberFormatter alloc] init];
[nFormatter setNumberStyle:NSNumberFormatterDecimalStyle];

for ( NSUInteger i = 0; i < [yAxisLabels count]; i++ ) {

    CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:[NSString stringWithFormat:@"%@",[yAxisLabels objectAtIndex:i]]  textStyle:axisTextStyle];
    label.tickLocation = CPTDecimalFromInteger([[yAxiscustomTickLocations objectAtIndex:i] integerValue]);
    //label.offset = y.labelOffset + y.majorTickLength;
    NSLog(@"%d",[[yAxiscustomTickLocations objectAtIndex:i] integerValue]);

    label.offset = y.majorTickLength+2;
    if (label) {
        [yLabels addObject:label];
        [yLocations addObject:[NSString stringWithFormat:@"%d",[[yAxiscustomTickLocations objectAtIndex:i] integerValue]]];
    }
    label = nil;
}

NSLog(@"newmaxValue%f",newmaxValue);
NSLog(@"newMinValue%f",newMinValue);

y.axisLabels = yLabels;
y.majorTickLocations = [NSSet setWithArray:yAxiscustomTickLocations];
y.visibleRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat((NSInteger)newMinValue) length:CPTDecimalFromFloat((NSInteger)newmaxValue)];
y.labelFormatter = nFormatter;

And also I am setting the range like this
[self getCoreplotSpace].xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromUnsignedInteger(0.0f) length:CPTDecimalFromUnsignedInteger(1800.0f)];

[self getCoreplotSpace].yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInteger((NSInteger)newMinValue) length:CPTDecimalFromInteger((NSInteger)newmaxValue)];

EDIT::
Log OUTPUT
  newmaxValue225.000000
  newMinValue-75.000000
  yAxisLabels(
    "-75",
    "-55",
    205,
    225
  )
   yAxiscustomTickLocations(
    "-75",
    "-55",
    205,
    225
)

Could you please help me guys...
Thanks

A: Your problem is at the end where you specify the y axis visible range:
y.visibleRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat((NSInteger)newMinValue) length:CPTDecimalFromFloat((NSInteger)newmaxValue)];

The length should be the range, not the newmaxValue:
y.visibleRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat((NSInteger)newMinValue) length:CPTDecimalFromFloat((NSInteger)(newmaxValue-newminValue))];


text:
Q: The proper way to prepare a dynamic Statement in Java I am preparing a SQL statement from values passed through a query string. ( I am using the Play! framework. Basically what I'm running into (not really an issue just something I don't like very much) is that when I want to use ? in the SQL string and set them later with dynamic values.
This is what I have:
String sql = "SELECT * FROM foobar_table WHERE";

if ( foo != 0 )
    sql += " AND foo=?";
if ( !bar )
    sql += " AND bar=?";

try{
    PreparedStatement getStmt = con.prepareStatement(sql);
    if ( foo != 0 )
        getStmt.setInt(1,foo);
    if ( foo != 0 && !bar )
        getStmt.setBoolean(2, bar);
    else
        getStmt.setBoolean(1, bar);
} catch (SQLException e ){
    e.printStackTrace();
}
This does work but as you can see not very intuitive. It's OK when there are 2 dynamic values but when you get up to 5 or 6 this would just get ridiculous.
Is there an easier way of doing this to make it more flexible so that I would know how to fill in all the ? in a better fashion?

A: An example (was too long for comment):
String sql = "SELECT * FROM foobar_table WHERE 1 = 1 ";
ArrayList paramList = new ArrayList();

if ( foo != 0 ) {
    sql += " AND foo=?";
    paramList.add(foo);
}

if ( !bar ) {
    sql += " AND bar=?";
    paramList.add(bar);
}

try{

    PreparedStatement getStmt = con.prepareStatement(sql);

    int index = 1;

    for (Object param : paramList) {
        getStmt.setObject(index, param);
        index++;
    }

    // execute

} catch (SQLException e ){
    e.printStackTrace();
}

A: Something like this maybe (just rough code but you get the idea):
    class Param{
        final int type;
        final Object value;
        Param(int type, Object value){
            this.type = type;
            this.value = value;
        }
    }

    final List<Param> params = new ArrayList<>();

    final StringBuilder sql = new StringBuilder("SELECT * FROM bcu_venue_events WHERE 1=1");
    int foo = 0;
    boolean bar = true;
    if (foo != 0){
        sql.append(" AND foo=?");
        params.add(new Param(Types.INTEGER, foo));
    }
    if (!bar){
        sql.append(" AND bar=?");
        params.add(new Param(Types.BOOLEAN, bar));
    }
    try(Connection conn = null; PreparedStatement getStmt = conn.prepareStatement(sql.toString())) {
        for(int i = 0; i < params.size(); i++){
            Param p = params.get(i);
            getStmt.setObject(i + 1, p.value, p.type);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }

A: How about this:
String sql = "SELECT * FROM foobar_table WHERE 1=1";

if ( foo != 0 )
    sql += " AND foo=" + foo;
if ( !bar )
    sql += " AND bar=" + bar;

try{
    PreparedStatement getStmt = con.prepareStatement(sql);
} catch (SQLException e ){
    e.printStackTrace();
}


text:
Q: Memtest 86 for my laptop errors 'memtest86 unexpected interrupt halting cpu0' Any ideas what could be wrong in this instance. My laptop has refused to take new Win 7 Operating system, I get blue screen errors. The previous Os on the laptop was Vista Home Edition, which became unstable and crashed (blue screen of death) regulary.
I tried to run memtest86, I get the error message above.

A: It pretty much means that the ram is likely to be faulty. Both windows versions BSODing might be due to this too.
Breaking it down a little more 'cpu0' is your 'first' processor. Your memory is acting in an unexpected way, and apparently memtest itself is crashing due to this, or simply failing the memory - the more typical output looks like

Unexpected Interrupt - Halting CPU0 (Test #2 failed at 16% with four errors)

So there should also be an indication of failed test from memtest in addition to that error i believe.
Any errors at all from memtest is a bad thing (tm)


text:
Q: is it possible to have a conditional field in an anonymous type i have some code that looks like this and creates a list from an existing collection
 var items = items.ConvertAll(r => new
            {
                description = FormatDescription(r),
                start = r.Milestone.HasValue ? r.Milestone.Value.ToString("yyyy-MM-ddTHH:mm:ssZ") : DateTime.Today.ToString("yyyy-MM-ddTHH:mm:ssZ"),
                classname = "significance" + r.SignificanceLevel,

As you can see, right now if i dont have a start date (r.Milestone) then i put in today's date.  What i really want to do if say:

*

*if i have a r.Milestone.Hasvalue show that date, if i dont have a value DONT HAVE THE START DATE field in the anonymous type at all.

Is it possible to have this conditional logic where you can remove the field all together inside this type of code?

A: No, you can't, mostly since it would make the anonymous class different in different executions and the class couldn't be type checked.
I'd recommend setting your Start date to null instead of a default, and checking for that later in your code.


text:
Q: hashing json in java I'm trying to connect to Grooveshark api. This is Grooveshark guideline for signing the request:
http://developers.grooveshark.com/tuts/public_api
This is how I sign my data. But I get the error :"signature not valid". Should I form JsonObject or data can be String?
String data = "{\"method\":\"getArtistSearchResults\",\"parameters\":{\"query\":\"adele\"},\"header\":{\"wsKey\":\"concertboom\"}}";

String key = "XXXXX";

SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1");
Mac mac = Mac.getInstance("HmacMD5");
mac.init(keySpec);
byte[] result = mac.doFinal(data.getBytes());

BASE64Encoder encoder = new BASE64Encoder();

signature = encoder.encode(result);

A: If we are to look at http://developers.grooveshark.com/docs/public_api/v3/, the following code should work:
    private static final String EXPECTED_SIGNATURE = "cd3ccc949251e0ece014d620bbf306e7";

    @Test
    public void testEnc() throws NoSuchAlgorithmException, InvalidKeyException {
        String key = "key";
        String secret = "secret";
        String payload = "{'method': 'addUserFavoriteSong', 'parameters': {'songID': 0}, 'header': {'wsKey': 'key', 'sessionID': 'sessionID'}}";

        String signature = getHmacMD5(payload, secret);
        assertEquals(EXPECTED_SIGNATURE, signature);

    }

    public static String getHmacMD5(String payload, String secret) {
        String sEncodedString = null;
        try {
            SecretKeySpec key = new SecretKeySpec((secret).getBytes("UTF-8"), "HmacMD5");
            Mac mac = Mac.getInstance("HmacMD5");
            mac.init(key);

            byte[] bytes = mac.doFinal(payload.getBytes("UTF-8"));

            StringBuffer hash = new StringBuffer();

            for (int i=0; i<bytes.length; i++) {
                String hex = Integer.toHexString(0xFF &  bytes[i]);
                if (hex.length() == 1) {
                    hash.append('0');
                }
                hash.append(hex);
            }
            sEncodedString = hash.toString();
        }
        catch (UnsupportedEncodingException e) {}
        catch(InvalidKeyException e){}
        catch (NoSuchAlgorithmException e) {}
        return sEncodedString ;
    }


text:
Q: How to import and use bpmn file in vue component with aid of raw-loader I'm new to bpmn-js and try to import and use a .bpmn file in a vue.js component (BPMNViewer.vue). My research only brought up to use the raw-loader. So I'm kind of at a loss here.
<script>
import demo from './examples/demo.bpmn'
...

export default {
  data() {
    return {
      xmlData: demo,
    };
  }
}

This results in the following Error:
error in ./src/views/BPMNViewer.vue?vue&type=script&lang=js&

Module not found: Error: Can't resolve './examples/demo.bpmn' in '/bpmn-test/src/views'

ERROR in ./src/views/BPMNViewer.vue?vue&type=script&lang=js& (./node_modules/@vue/vue-loader-v15/lib/index.js??vue-loader-options!./src/views/BPMNViewer.vue?vue&type=script&lang=js&) 12:0-39

Module not found: Error: Can't resolve './examples/demo.bpmn' in '/bpmn-test/src/views'
 @ ./src/views/BPMNViewer.vue?vue&type=script&lang=js& 1:0-134 1:150-153 1:155-286 1:155-286
 @ ./src/views/BPMNViewer.vue 2:0-62 3:0-57 3:0-57 10:2-8
 @ ./src/router/index.js 3:0-48 12:15-25
 @ ./src/main.js 3:0-29 9:2-8
webpack compiled with 1 error

I try to integrate the raw-loader in my vue.config.js:
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
    transpileDependencies: true,

    chainWebpack: config => {
        config.module
            .rule("bpmn")
            .test(/\.bpmn$/)
            .use("raw-loader")
            .loader("raw-loader")
            .end();
    }
})

My package.json:
{
  "name": "bpmn-test",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "test:unit": "vue-cli-service test:unit",
    "test:e2e": "vue-cli-service test:e2e",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "bpmn-js": "^7.3.1",
    "bpmn-js-cli": "^2.0.0",
    "bpmn-js-properties-panel": "^0.37.2",
    "camunda-bpmn-moddle": "^4.4.0",
    "diagram-js-minimap": "^2.0.3",
    "inherits": "^2.0.4",
    "core-js": "^3.8.3",
    "vue": "^2.6.14",
    "vue-router": "^3.5.1",
    "vuex": "^3.6.2"
  },
  "devDependencies": {
    "@babel/core": "^7.12.16",
    "@babel/eslint-parser": "^7.12.16",
    "@vue/cli-plugin-babel": "~5.0.0",
    "@vue/cli-plugin-e2e-cypress": "~5.0.0",
    "@vue/cli-plugin-eslint": "~5.0.0",
    "@vue/cli-plugin-router": "~5.0.0",
    "@vue/cli-plugin-unit-jest": "~5.0.0",
    "@vue/cli-plugin-vuex": "~5.0.0",
    "@vue/cli-service": "~5.0.0",
    "@vue/test-utils": "^1.1.3",
    "@vue/vue2-jest": "^27.0.0-alpha.2",
    "babel-jest": "^27.0.6",
    "cypress": "^8.3.0",
    "eslint": "^7.32.0",
    "eslint-plugin-vue": "^8.0.3",
    "jest": "^27.0.5",
    "less": "^3.0.4",
    "less-loader": "^5.0.0",
    "raw-loader": "^3.1.0",
    "vue-template-compiler": "^2.6.14"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/essential",
      "eslint:recommended"
    ],
    "parserOptions": {
      "parser": "@babel/eslint-parser"
    },
    "rules": {},
    "overrides": [
      {
        "files": [
          "**/__tests__/*.{j,t}s?(x)",
          "**/tests/unit/**/*.spec.{j,t}s?(x)"
        ],
        "env": {
          "jest": true
        }
      }
    ]
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not dead"
  ],
  "jest": {
    "preset": "@vue/cli-plugin-unit-jest"
  }
}

Seems like I miss something here. Please let me know if I need to provide more information.

A: This looks like nothing Bpmn-js specific. Can you first ensure that the raw XML is indeed available in your xmlData object?
Your webpack may not be configured to use the raw-loader or not to use it for for the .bpmn extension. An inline solution would be
ìmport demo from 'raw-loader!./examples/demo.bpmn'

(if you don't have the raw-loader yet:
npm install raw-loader --save-dev)


text:
Q: Identifying new entry between two tables I would like to identify recent (since 60 days) entries in a table T1 that are not in another table T2.
Since 'FULL OUTER JOIN' is not supported by MySQL, I have tried the code below.
I expect to find as a result a record from T1 that I have erased from T2. The current code does not yield the expected result.
What's going wrong?
SELECT * FROM (

  SELECT store, name, date
  FROM `T1` A
  LEFT JOIN `T2` V
    ON A.name=V.namebis AND A.store=V.storebis

  UNION ALL

  SELECT store, name, date
  FROM `T1` A
  RIGHT JOIN `T2` V
    ON A.name=V.namebis AND A.store=V.storebis
  WHERE A.name is null

) C
WHERE store IN (NYC, CHICAGO)
  AND (date BETWEEN CURRENT_DATE AND subdate(CURRENT_DATE, 60))
GROUP BY store, name

A: If you only want to check which entries in T1 are no longer in T2, you don't need a FULL JOIN, you can simply use a LEFT JOIN and check if the row no longer exists in T2 by checking whether the fields in T2 are NULL. Note that the order of values in your BETWEEN clause is wrong, the lowest value must be first. I have fixed that below too.
SELECT store, name, date
FROM T1
LEFT JOIN T2 ON T1.name = T2.namebis AND T1.store = T2.storebis
WHERE store IN (NYC, CHICAGO)
  AND (date BETWEEN subdate(CURRENT_DATE, 60) AND CURRENT_DATE)
  AND T2.namebis IS NULL

A: Try this:
SELECT store, name, date
FROM T1
LEFT JOIN T2
ON (T1.name = T2.namebis AND T1.store = T2.storebis)
WHERE store IN (NYC, CHICAGO)
  AND TIMESTAMPDIFF(DAY, DATE(T1.`date`),CURDATE()) =60
  AND T2.namebis IS NULL


text:
Q: Cannot locate xindy module for language german in codepage latin Newly I received the above message as I compiled one of my old documents (last year it compiled without errors). I use TeXnicCenter x64 with following arguments

I also found the same messages for british, dutch and persian, but I'd never used the commandline commands, because TeXnicCenter does it alone.
If I compile this MWE:
\documentclass[ngerman]{scrreprt}
\usepackage{babel,makeidx}
\makeindex

\begin{document}

  Test\index{Test}.
  \printindex

\end{document}

I receive the above message. What do I wrong?
Thank you for your help and effort in advance!


text:
Q: jquery sortable accordion should stay closed on drop I have a sortable accordion. When I drop the accordion it opens the dropped section by default. I do not want to open the dropped section rather it should stay closed when I drop any section. Here is my code
$( "#accordion" ).accordion({
    header: "> div > h3",
    heightStyle: "content",
    collapsible: true,
    active: false,
    activate: function( event, ui){
        //this fixes any problems with sorting if panel was open (remove to see what I am talking about)
        if(sorting)
            $(this).sortable("refresh");
    }
})
.sortable({
    handle: "h3",
    value: "ui-state-highlight",
    start: function( event, ui ){
        //change bool to true
        sorting=true;

        //find what tab is open, false if none
        active = $(this).accordion( "option", "active" );

        //possibly change animation here
        $(this).accordion( "option", "animate", { easing: 'swing', duration: 0 } );

        //close tab
        $(this).accordion({ active:false });

        unloadEditors();
    },
    stop: function( event, ui ) {
$(this).accordion( active, false);
         loadEditors();
        sorting=false;

    },
     update: function(event, ui) {
        var params = $(this).sortable('toArray');
        //alert(params);
        var pageUrl = $("#orderUrl").val();
        dataString = 'ordering='+params;
        $.ajax({
            type: "POST",
            url: pageUrl,
            data: dataString,
            success: function(data) {
            //data = jQuery.trim(data);
        }
        });
    }
});

Thanks in advance,
Aisha

A: I have fixed this issue by triggering the click event in stop handler. Here is my code
$( "#accordion" ).accordion({
    header: "> div > h3",
    heightStyle: "content",
    collapsible: true,
    active: false,
    activate: function( event, ui){
        //this fixes any problems with sorting if panel was open (remove to see what I am talking about)
        if(sorting)
            $(this).sortable("refresh");
    }
})
.sortable({
    handle: "h3",
    value: "ui-state-highlight",
    start: function( event, ui ){
        //change bool to true
        sorting=true;

        //find what tab is open, false if none
        active = $(this).accordion( "option", "active" );

        //possibly change animation here
        $(this).accordion( "option", "animate", { easing: 'swing', duration: 0 } );

        //close tab
        $(this).accordion({ active:false });

        unloadEditors();
    },
    stop: function( event, ui ) {
ui.item.children( "h3" ).triggerHandler( "click" );
        sorting=false;

    },
     update: function(event, ui) {
        var params = $(this).sortable('toArray');
        //alert(params);
        loadEditors();
        var pageUrl = $("#orderUrl").val();
        dataString = 'ordering='+params;
        $.ajax({
            type: "POST",
            url: pageUrl,
            data: dataString,
            success: function(data) {
            //data = jQuery.trim(data);
        }
        });
    }
});


text:
Q: Windows Phone Emulator: Error Missing or Invalid ROM Image. I installed Windows Phone SDK7.1 in my WIN7 machine. When I try to open the Windows Phone emulator from the Windows Phone SDK7.1, the emulator is opened as shown but I got the following Error that "Error: Invalid or Missing ROM Image.
Please help me in solving the issue to make my win Phone emulator. My actual requirement here is to test the Web page in Windows Phone. Thanks in Advance For any help.

A: Now Emulator is Working in my system. Thanks a lot For the Help i found in Eric's Question  see the link .
What id did is very simple .I closed all the applications but browser(to see the instruction) and opened the Emulator as "Run As Administrator" then it works for me.


text:
Q: XSLT Identity Transform doesn't copy all attributes I have following code for XSL transform:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="@*|node()">
    <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

That's the standard sample of identity transformation. For most cases it works just right. But I was able to find a case when it doesn't copy properly. For following XML code:
<c xmlns:x="x">

</c>

the transformed xml code looks following:
<c xmlns:x="x"></c>

If you remove namespaces xmlns from XML code, then it starts working properly. Also, if you change name of the second argument (leaving xmlns namespace), you have proper identity transformation. I'm stuck, because I can't explain WHY using same argument with this exact same namespace makes such troubles.
BTW, you can reproduce those errors on https://www.freeformatter.com/xsl-transformer.html webpage.

A: Essentially, an element's declared namespace prefix, xmlns:x="x", matching the same namespace prefix and URI as its parent is redundant. And the XSLT processing removes this redundancy. Both are essentially the same XML content.
According to the W3C rules on Namespaces in XML (emphasis added):

If the attribute name matches PrefixedAttName, then the NCName gives
  the namespace prefix, used to associate element and attribute names
  with the namespace name in the attribute value in the scope of the
  element to which the declaration is attached.
  ...
  An example namespace declaration, which associates the namespace
  prefix edi with the namespace name http://ecommerce.org/schema:
<x xmlns:edi='http://ecommerce.org/schema'>

</x>

Specifically with your use case, the x namespace prefix is already defined in the scope of <c> so  (being the child element) can use the x namespace prefix anywhere in its contents without another declaration. So your original content:
<c xmlns:x="x">

</c>

Is identical to XSLT output:
<c xmlns:x="x"></c>

Or with line breaks and indents as mentioned in comments by @michael.hor257k.
<c xmlns:x="x">

</c>


text:
Q: Powershell Variable in Double Double Quotes I have a PS Script that should generate a html file with add-content $datei
works fine but here is the Problem,
I have something like that:
"some html...
<textarea id="Text$counter" style="width: 100%; height: 100%;"></textarea>
some html...
$NameEdit
some html...
document.getElementById('Text$counter').select();
some html...
" | add-content $datei

so i have multible double and single qoutes and multible variables in the html part but i cant find out how to escape all that stuff right that the script runs as expected AND fill in the variables in the html code
im using PS 7.0

A: The solution you probably want is a Here String
But you could also use the escape char `
@"
some html...
<textarea id="Text$counter" style="width: 100%; height: 100%;"></textarea>
some html...
$NameEdit
some html...
document.getElementById('Text$counter').select();
some html...
"@ | add-content $datei

To use a Here string you need to have the @" or @' then a new line where you will put your string. Then to close a Here string you will need to have a new line and "@ or '@. The "@ or '@ must be at the very first start of the new line.
Here are some examples that would fail
#This will NOT work
@"
Hey There "Buddy"
  "@

#This will NOT work
@"Hey There "Buddy""@

#This will NOT work
@"
Hey There "Buddy""@

Here are couple Working correctly examples
#This WILL work
@"
Hey There "Buddy"
"@

#This WILL work
  @"
Hey There "Buddy"
"@

#This WILL work
$Test = @"
Hey There "Buddy"
"@

It does make beautifying code harder
Example
Function Test(){
    $Text1 = "Hello There"
    $Text2 = @"
"Buddy"
"@
    return "$Text1 $Text2"
}

Now lets go over the escape char `
Its called a Backtick.
"Hey There `"Buddy`""

Is equal to Hey There "Buddy"


text:
Q: Entity Framework Core Linq query doesn't translate to correct SQL statements So I am debugging our application which uses Entity Framework Core 2.1.14. I created my entities from database first by scaffolding. Database is MySQL 5.7.29, the SQL data provider for EF Core is Oracle's MySql.Data.EntityFrameworkCore 8.0.19.
Example: a simple Linq query should create a proper SQL statement in the backend. However it does not. "Inactive" is a Byte?.
Dim associates = (From a In DatabaseContext.Associate
                  Where a.Inactive = 0
                  Select a.AssociateId).ToList()

This simple Linq query returns: SELECT `a`.`Inactive`, `a`.`AssociateID` FROM `associate` AS `a`. So basically it downloads all associates and does the "where" in memory and returns the values. I know according to the documentation some queries can be complicated and can't be translated, but this is a simplest of the simple queries. Is it because the Inactive column is nullable? Something is terrible not right.
FYI: EF Core is in a class library that is C#. The VB code is in another project that is VB that references the class library.

A: Hmm, seems the answer is to make the query more specific in VB. I guess the query conversion between C# class library and VB project seems to be the issue.
Dim associates = (From a In DatabaseContext.Associate
                  Where a.Inactive.Value = Convert.ToByte(0)
                  Select a.AssociateId).ToList()

This provides the correct query:
SELECT `a`.`AssociateID`
FROM `associate` AS `a`
WHERE `a`.`Inactive` = 0

Very weird that in C# you don't have to check against the .Value and convert the 0 to a byte but in VB I had to do it, there was no other way to get it work. Thanks for everyone trying to help with this.


text:
Q: Waiting to run, over default 60 seconds. Seleinium C# Faced a problem, wrote a program that uses selenium (chromedriver) and everything is ok. The program is written in C #. It works fine on my computer, but the program was intended for an older computer.
The old computer is rather weak and starts Seleniuim for a long time. Sometimes the startup time exceeds 60 seconds and I get an exception.
Is it possible to somehow increase the allowable waiting time before the launch of selenium?
Timeouts for loading the page, as I understand it, will not help in this case.

A: You could try something like this
this.driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
this.driver.manage().timeouts().setScriptTimeout(60, TimeUnit.SECONDS);


text:
Q: java.lang.RuntimeException at android.app.ActivityThread.performLaunchActivity From Google Play Console,
java.lang.RuntimeException occurs without "Caused by:"
The below log is copied from Google Play Console Crash log.
This is for: Android 8.0, Android 8.1, Android 7.0, Android 7.1
java.lang.RuntimeException:
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2955)
  at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:3030)
  at android.app.ActivityThread.-wrap11 (Unknown Source)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1696)
  at android.os.Handler.dispatchMessage (Handler.java:105)
  at android.os.Looper.loop (Looper.java:164)
  at android.app.ActivityThread.main (ActivityThread.java:6938)
  at java.lang.reflect.Method.invoke (Method.java)
  at com.android.internal.os.Zygote$MethodAndArgsCaller.run (Zygote.java:327)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1374)

Please help me regarding this!

A: ActivityThread.java says it's updatePendingConfiguration() or registerOnActivityPausedListener(), so it either fails with .onPause() or it fails to call the super() method with the correct arguments - or something is wrong with the Configuration being applied.
I'd glady explain how to solve the issue, but the question lacks the code which throws the exception. The best way to tackle this might be to employ something alike Firebase Crashlytics, so that one can see where exactly this is coming from and which devices are affected (in case this should be specific). I'd almost suspect that it might be caused by starting an Activity with the application's Context, while not setting flag Intent.FLAG_ACTIVITY_NEW_TASK (see: this answer).

A: From analyzing the log following assumption can be made,

The exception is thrown in any of the external libraries
  used in the project

Explanation: Basically, the exception is thrown by ActivityThread.java, more specifically, the performLaunchActivity() method at line 2955 threw the exception. As the stack trace didn't include any of your application's internal class, we can assume that the exception is thrown in an external class that is shipped with a library you are using in your project.
If that is the case, following workarounds can be performed to sort this out -

*

*Look into all the library dependencies and markdown suspected ones

*If you are using a custom view (such as AdView) from an external library, that library is most likely to cause this crash

*Upgrade all the 3rd party libraries to latest version since the crash is causing in the latest OSs

*Look into the official documentation to correctly implement those libraries. Like, troubleshoot page of the SDK's website may have the solution to this exact issue. Like, Dynamsoft Camera SDK already addressed this issue here

*Look into the issue tracker of the libraries for this issue. For example, Android-Permission library has a closed issue having exactly the same log.

*If your project is react native, there is a long discussion about it here
Suggestion: I want to add few more lines with @Martin Zeitler's suggestion of using Crashlytics.

I recommend you to Customize your Firebase Crashlytics crash
  reports. Because, sometimes only stack trace is not enough to reproduce the
  crash.

By using the customization feature you will be able to get,

*

*User's identity

*State of the app

*The Events that were performed before the crash
Which will surely help you regenerate the crash and fix it.

A: I was getting the same error. I solved it, maybe it helps some people:
The problem was in my land/tooldbar.xml. I have migrated to Androidx library. I solved my problem changing problematic xml files.
Do not use:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
....
....
</android.support.v4.widget.DrawerLayout>
Instead use:
<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
....
....
</androidx.drawerlayout.widget.DrawerLayout>

A: Intro
For the people saying:
did you resolve this issue? It's a rising crash in my app as well – Bao Le Feb 6 at 8:36
did anybody resolve this issue? – AwaisMajeed Feb 9 at 13:15
Also happening to me. =( – masterlopau Feb 26 at 1:51
do this solved? – Vengat Jul 19 at 5:55

Do YOU have the extra cause log ? It would help enormously.
This is your Crash log:
java.lang.RuntimeException:
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2955)
  at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:3030)
  at android.app.ActivityThread.-wrap11 (Unknown Source)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1696)
  at android.os.Handler.dispatchMessage (Handler.java:105)
  at android.os.Looper.loop (Looper.java:164)
  at android.app.ActivityThread.main (ActivityThread.java:6938)
  at java.lang.reflect.Method.invoke (Method.java)
  at com.android.internal.os.Zygote$MethodAndArgsCaller.run (Zygote.java:327)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1374)

Compare with this Crash log (identical line numbers and code flow):
java.lang.RuntimeException:
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2955)
  at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:3030)
  at android.app.ActivityThread.-wrap11 (Unknown Source)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1696)
  at android.os.Handler.dispatchMessage (Handler.java:105)
  at android.os.Looper.loop (Looper.java:164)
  at android.app.ActivityThread.main (ActivityThread.java:6938)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.Zygote$MethodAndArgsCaller.run (Zygote.java:327)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1374)

This line differs:
  at java.lang.reflect.Method.invoke (Method.java)

and:
  at java.lang.reflect.Constructor.newInstance0 (Native Method)

with the extra cause log:
Caused by: android.support.v4.app.i$b:
  at android.support.v4.app.i.instantiate (Fragment.java:386)
  at android.support.v4.app.k.a (FragmentContainer.java:33)
  at android.support.v4.app.s.a (FragmentState.java:79)
  at android.support.v4.app.o.a (FragmentManager.java:3080)
  at android.support.v4.app.l.a (FragmentController.java:152)
  at android.support.v4.app.j.onCreate (FragmentActivity.java:330)
  at host.exp.exponent.experience.f.onCreate (ReactNativeActivity.java:140)
  at host.exp.exponent.experience.a.onCreate (BaseExperienceActivity.java:79)
  at host.exp.exponent.experience.ExperienceActivity.onCreate (ExperienceActivity.java:160)
  at host.exp.exponent.experience.ShellAppActivity.onCreate (ShellAppActivity.java:22)
  at android.app.Activity.performCreate (Activity.java:7174)
  at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1220)
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2908)
Caused by: java.lang.reflect.InvocationTargetException:
  at java.lang.reflect.Constructor.newInstance0 (Native Method)
  at java.lang.reflect.Constructor.newInstance (Constructor.java:334)
  at android.support.v4.app.i.instantiate (Fragment.java:364)
Caused by: java.lang.IllegalStateException:
  at abi30_0_0.host.exp.exponent.modules.api.screens.Screen$ScreenFragment.<init> (Screen.java:19)

NOTE the at android.support.v4.app lines.
See Android standalone app randomly crashes on app open
Fixes
android.support class packages, or have a *Compat suffix
(1) AndroidX
(i) This problem has a miriad of causes from my internet search. A common cause seems to be the use of android.support class packages, or having a *Compat suffix. Review you build.gradle files for android.support.v4 etc...
(ii) Because sometimes it does not occur in testing, only deployment I guess the android.support.v4 etc... use's a problematic device library on some devices or API's.

*

*Note: With the release of Android 9.0 (API level 28) there is a new
  version of the support library called AndroidX which is part of
  Jetpack. The AndroidX library contains the existing support library
  and also includes the latest Jetpack components.

*You can continue to use the support library. Historical artifacts
  (those versioned 27 and earlier, and packaged as android.support.*)
  will remain available on Google Maven. However, all new library
  development will occur in the AndroidX library.

*We recommend using the AndroidX libraries in all new projects. You
  should also consider migrating existing projects to AndroidX as well.
  Support Library Setup

*The support libraries are now available through Google's Maven
  repository. We no longer support downloading the libraries through the
  SDK Manager, and that functionality will be removed soon..

*Note: After including the Support Library in your application project,
  we strongly recommend that you shrink, obfuscate, and optimize your
  app for release. In addition to protecting your source code with
  obfuscation, shrinking removes unused classes from any libraries you
  include in your application, which keeps the download size of your
  application as small as possible.

*Note: If you are including several support libraries, the minimum SDK
  version must be the highest version required by any of the specified
  libraries. For example, if your app includes both the v14 Preference
  Support library and the v17 Leanback library, your minimum SDK version
  must be 17 or higher.

See also:
Support Library Packages
features
(2) react-native-screens

It is related to react-native-screens and they have workaround for
  this issue, please have a look at:

Android crashes nondeterministically when restoring from background - veedeo.

A: This crash could happen from literally anything. I had the same issue and the root cause was an IllegalArgumentException thrown by an incorrectly implemented Comparator within an overridden Fragment#onViewCreated. The fragment itself was added during AppCompatActivity#onCreate via FragmentManager.
2020-01-03 15:38:33.001 7860-7860/com.example.app E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.app, PID: 7860
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.app/MyActivity}: android.view.InflateException: Binary XML file line #9 in com.example.app:layout/my_activity: Binary XML file line #9 in com.example.app:layout/my_activity: Error inflating class fragment
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
     Caused by: android.view.InflateException: Binary XML file line #9 in com.example.app:layout/my_activity: Binary XML file line #9 in com.example.app:layout/my_activity: Error inflating class fragment
     Caused by: android.view.InflateException: Binary XML file line #9 in com.example.app:layout/my_activity: Error inflating class fragment
     Caused by: java.lang.IllegalArgumentException: Comparison method violates its general contract!
        at java.util.TimSort.mergeLo(TimSort.java:777)
        at java.util.TimSort.mergeAt(TimSort.java:514)
        at java.util.TimSort.mergeCollapse(TimSort.java:441)
        at java.util.TimSort.sort(TimSort.java:245)
        at java.util.Arrays.sort(Arrays.java:1492)
        at java.util.ArrayList.sort(ArrayList.java:1470)
        at java.util.Collections.sort(Collections.java:206)
        at com.example.app.MyFragment.onViewCreated(MyFragment.java:188)
        at androidx.fragment.app.FragmentManagerImpl.ensureInflatedFragmentView(FragmentManagerImpl.java:1144)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:851)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1133)
        at androidx.fragment.app.FragmentManagerImpl.addFragment(FragmentManagerImpl.java:1393)
        at androidx.fragment.app.FragmentManagerImpl.onCreateView(FragmentManagerImpl.java:3205)
        at androidx.fragment.app.FragmentController.onCreateView(FragmentController.java:134)
        at androidx.fragment.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:357)
        at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:336)
        at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1069)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:997)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:961)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:1123)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:656)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:534)
2020-01-03 15:38:33.003 7860-7860/com.example.app E/AndroidRuntime:     at android.view.LayoutInflater.inflate(LayoutInflater.java:481)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:555)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:161)

Of course, it's almost impossible to find the root cause if you just have the crash report from Google Play Console. I had the luck to have a customer incident, giving me insights on where to look and how to reproduce the crash. You might also switch to a custom crash reporting tool like HockeyApp or Firebase to see the whole stacktrace.

A: Upload the deobfuscation(mapping.txt) file to Google playstore.
Read the following document on how to generate and upload.
https://support.google.com/googleplay/android-developer/answer/9848633?hl=en


text:
Q: How to use multiple upper bounds in generics I have a Interface Foo which has a generic type -
 public interface Foo<T> {
     boolean apply(T t);
 }

Having another class Bar which implements this interface but what I want is the generic Type of Bar should be a Collection of type Interface A and B, With the below definition its giving compiler error -
public class Bar implements Foo<Collection<? extends A & B>>{
  @Override
  public boolean apply(Collection<? extends A & B> collect){
   ...
  }
}

Can you suggest the correct way to achieve this?
I can use multiple bounds at method level only?

A: Wouldn't this work?
public class Bar<T extends A & B> implements Foo<Collection<T>>{
  @Override
  public boolean apply(Collection<T> collect){
   ...
  }
}


text:
Q: Version of Löwenheim-Skolem theorem and the axiom of choice I was looking through Set Theory and the Continuum Problem by Smullyan and Fitting and came across this note in Exercise 1.2 in Chapter 11 (pg 147 of Dover version).

(We remark that the Skolem-Löwenheim theorem can be proved without the axiom of choice.)

However, it appears to be the case that the theorem is equivalent to the axiom of dependent choice. See, for instance, this answer. The statement in the book would be true in the sense that the full-strength axiom of choice is not required, but since this is an axiomatic set theory book, a statement like this seems like it would imply it's provable under ZF.
I'm wondering if this is just an oversight, or is it that they are using a weak version of the theorem that doesn't require any choice axiom? Their version of the theorem is given toward the end of section $0$ in the same chapter (p. 144):

Given any denumerable set $S$ of pure formulas (i.e. w/o constants), if there is a relational system in which all the formulas of $S$ are satisfiable, then there is a denumerable such relational system.

A: This version indeed does not require the axiom of choice.  The more usual formulation that is equivalent to DC requires that the countable model you obtain be an elementary submodel of your original model.  The version you quoted can be proved without choice as follows.  First, if $S$ has a model, then it is consistent.  Henkin's proof of the completeness theorem (which does not require choice if your language is countable) then produces a countable model of $S$.


text:
Q: AngularJS: Is this the right way to write a directive handling updates in the model/content? I have to create a html page with svg elements that will be loaded from a json file. The json file is loaded using $http and returns a promise.
In the html file I have the following markup:
<ext-svg content="svg"></ext-svg>

svg will first contain undefined and when the json is loaded a valid svg content.
My directive is defined as:
 angular.module('myApp.directives')
      .directive('extSvg', function () {
        "use strict";

        return {
          restrict: 'E',
          scope: {
            content: '='
          },
          link: function (scope, element) {
            scope.$watch('content', function (value) {
              if  (value) {
                element.replaceWith('<svg>' + scope.content + '</svg>');
              }
            });
          }
        };
      });

The page rendered contains e.g.:
<svg><circle cx="10" cy="10" r="10" fill="yellow" stroke="black" stroke-width="1"></circle></svg>

It worked, but is it the correct way to implement this?

A: Perhaps a diferent aproach using the ngSanitize module and directly bind the values from your controller, that way you dont actualy need a directive just to use the ng-bind-html anywhere you need to insert the SVG and no need for replace elements Look at this fiddle
so in your HTML

and in your controller
$scope.svg = $sce.trustAsHtml('<svg><circle r="50"/></svg>'); //$sce needs to be injected in your controller


text:
Q: connect my galaxy s duos phone as mass storage or drivers i want the drivers of my phone to be installed in Ubuntu 12.04 Lts  please help me on this

A: You need not to install any extra driver for your Smartphone to use it as a mass storage device. I am also having Samsung galaxy duos and there is no problem like this. What you have to do is, simply connect your phone with laptop/desktop using data cable. It will automatically detect your phone. Ubuntu12.04LTS is preloaded with the necessary drivers.


text:
Q: Appcelerator: Label layout composite in View layout vertical I need put a Label above an image. This image is in a view with layout "vertical", and i need that this LABEL put it in the right top of the image, in absolute. How can I do this?
My code:
index.html
`<Alloy>
        <View class="col col-2">
                            <ImageView id="images" class="img-thumbnail"  />

        </View>
</Alloy>
`

    app.tss

    ".col-2":{
        layout: 'vertical',
        width: '49.25%',
        height: Ti.UI.SIZE,
    }
   ".badge":{
    top:0,
    right:0,
    backgroundColor:'green',
    color:'white',
    layout:'composite'
}

Alloy.
TITANIUM SDKA: 7.0.0.GA

A: If you want to show a label at top-right corner above image & along with other views in that vertical layout, then you can wrap your vertical layout in a different view & show image at top-right like this:
<Alloy>
    <View width="49.25%" height="Ti.UI.SIZE">

        <View class="col col-2" width="Ti.UI.FILL">
            <ImageView id="images" class="img-thumbnail"  />

        </View>

    </View>
</Alloy>


text:
Q: Path syntax rules I'm writing a library for manipulation Unix path strings. That being the case, I need to understand a few obscure corners of the syntax that most people wouldn't worry about.
For example, as best as I can tell, it seems that foo/bar and foo//bar both point to the same place.
Also, ~ usually stands for the user's home directory, but what if it appears in the middle of a path? What happens then?
These and several dozen other obscure questions need answering if I'm going to write code which handles every possible case correctly. Does anybody know of a definitive reference which explains the exact syntax rules for this stuff?
(Unfortunately, searching for terms like "Unix path syntax" just turns up a million pages discussing the $PATH variable... Heck, I'm even struggling to find suitable tags for this question!)

A:
For example, as best as I can tell, it seems that foo/bar and foo//bar both point to the same place.

Yes.  This is common because software sometimes concatenates a path assuming the first part was not terminated with a forward slash, so one is thrown in to make sure (meaning there may end up being two or more). foo///bar and foo/////bar also point to the same place as foo/bar.  A nice function for a path manipulation library would be one which reduces any number of sequential slashes to one (except at the beginning of a path, where it may be used in an URL-ish way, or, as Stephane points out, for any unspecified special purpose).

Also, ~ usually stands for the user's home directory

That transformation is done via the shell and tilde exapansion, which only works if it is the first character in the path.  Whether or not you need to deal with this depends on context.  If the library is to be used with normal programs which receive, e.g., command line arguments containing a path, tilde expansion is already done when they see the path.  The only situation I can see it being a concern is if you are processing paths directly from a text file.
Beyond that, ~ is a legal character in a *nix path and should not be changed to anything else.  As per this, the only characters which aren't legal in a unix filename are / (because it is the path separator) and "null" (aka. a zero byte) because they are illegal in text generally.

A: There are three types of paths:

*

*relative paths like foo, foo/bar, ../a, .. They don't start with / and are relative to the current directory of the process making a system call with that path.

*absolute paths like /, /foo/bar or ///x. They start with 1, or 3 or more /, they are not relative, are looked up starting from the / root directory.

*POSIX allows //foo to be treated specially, but doesn't specify how. Some systems use that for special cases like network files. It has to be exactly 2 slashes.

Other than at the start, sequences of slashes act like one.
~ is only special to the shell, it's expanded by the shell, it's not special to the system at all. How it's expanded is shell dependent. Shells do other forms of expansions like globbing (*.txt) or variable expansion /$foo/$bar or others. As far as the system is concerned ~foo is just a relative path like _foo or foo.
Things to bear in mind:

*

*foo/ is not the same as foo. It's closer to foo/. than foo (especially if foo is a symlink) for most system calls on most systems (foo// is the same as foo/ though).

*a/b/../c is not necessarily the same as a/c (for instance if a/b is a symlink). Best is not to treat .. specially.

*it's generally safe to consider a/././././b the same as a/b though.


text:
Q: Multipage Application Form with Sessions or Database? I want to build a 5-page application form with php, where a user has to enter about 50 data entries (name, age, other details ...) which should be saved in the main database if the form is completed.
I wonder, which of the following approaches performs better:
A) After completing a page, save all entries in a big $_SESSION array. At the end save all entries from the $_SESSION array in the main database
or
B)  After completing a page, save all entries in a small database. Save in the $_SESSION array only the id of the small database and the page where the user currently is on the form. At the end save all entries from the $_small database to the main database.
I am not sure if it leads to problems when storing about 50 entries in the $_SESSION array, especially if many users use the form. Therefore I was thinking that B might be better. But if not, I would not want to make the extra effort of maintaining an extra local database if there is no difference in the performance of the website. Are there maybe other downsides one should be aware of when using A) or B) ?

A: First of all there are no big and small databases, there are only big and small database tables. There is no need to have separate schemas for each page so in the second approach you should have multiple tables and not multiple databases.
Regardless, the first approach is actually better because if the user cancels or never follows along on all the five pages you will be left with useless information in your tables. Storing the entries in $_SESSION is also faster since you don't have to query the database after every form submit, just the final one. The only downside of the second approach is that if a user leaves your page and then later returns they will need to input everything from scratch whereas in the first approach they can continue from where they left off (that's provided you have a way to tell the users apart with something like a unique id or email). Still first approach is the best.


text:
Q: English translation of german bureaucratic term: "Weglegesache" The German bureaucratic term Weglegesache is used in German public administration to refer to documents that they are forced to keep for a certain amount of time, but which are very unlikely ever to get retrieved/used.
I am searching for a translation that keeps the bureaucratic context and communicates that it refers to a bureaucratic action. The term Weglegesache is intended to be used as a title for a piece of art, so I can't just describe it in the translation.

A: The bureaucratic term "file/d under pending" can mean neutrally "file/d until it comes up for a scheduled action or until some event makes it current again".
But it can also have the connotation "file/d in the hope or expectation that no further action will ever be taken on it".
For example,

"Everything can be filed under pending."

From a humorous collection of "incredibly useful terms for the workplace".
And the following extracts from three Google books which show up on the first page of a search on "filed under pending" also appear to have the same connotation of "filed and (intentionally) forgotten":

Source: Legal and other Issues in Repatriating Nigeria's Looted Artefacts

Source: Making an Exhibition of Myself: the autobiography of Peter Hall

Source: Why we die
In my opinion Filed under pending would be a good, ambiguous title for a work of art.

A: I won't say it's in common usage (I came across it in a book by Leslie Thomas) but Moribund Documents would be a good phrase here.


text:
Q: invalid operation - mismatched types string and nil I'm trying to create a Go RESTful API that connects to Google Cloud API's.
An issue is happening, described as:
invalid operation: req.ParentId != nil (mismatched types string and nil)
Before creating the local API, I managed to write a Go module that could connect, authenticate, and pull data from Google Cloud. I'm now migrating that module to become a Restful API with paths.
The point of the module was to get a list of all current running Virtual Machines.
Here is the module before changing it to a restful API (which worked):
package main

import (
    "fmt"

    "example.com/compute"

    "bytes"
)

func main() {
    buf := new(bytes.Buffer)

    // Get a message and print it.
    r.HandleFunc("/virtualmachines", ListAllInstances)
    err := compute.ListAllInstances(buf, "unique-string-id")
    if err != nil {
        panic(err)
    }
    fmt.Println(buf.String()) // <======= Print buf contents!
}

// new file:

package compute

// [START compute_instances_list_all]
import (
    "context"
    "fmt"
    "io"

    compute "cloud.google.com/go/compute/apiv1"
    "google.golang.org/api/iterator"
    computepb "google.golang.org/genproto/googleapis/cloud/compute/v1"
    "google.golang.org/protobuf/proto"
)

// listAllInstances prints all instances present in a project, grouped by their zone.
func ListAllInstances(w io.Writer, projectID string) error {
    // projectID := "your_project_id"
    ctx := context.Background()
    instancesClient, err := compute.NewInstancesRESTClient(ctx)

    if err != nil {
        return fmt.Errorf("NewInstancesRESTClient: %v", err)
    }
    defer instancesClient.Close()

    // Use the `MaxResults` parameter to limit the number of results that the API returns per response page.
    req := &computepb.AggregatedListInstancesRequest{
        Project:    projectID,
        MaxResults: proto.Uint32(6),
    }

    it := instancesClient.AggregatedList(ctx, req)
    fmt.Fprintf(w, "Instances found:\n")
    // Despite using the `MaxResults` parameter, you don't need to handle the pagination
    // yourself. The returned iterator object handles pagination
    // automatically, returning separated pages as you iterate over the results.

    for {
        pair, err := it.Next()
        if err == iterator.Done {
            break
        }
        if err != nil {
            return err
        }
        instances := pair.Value.Instances
        if len(instances) > 0 {
            fmt.Fprintf(w, "%s\n", pair.Key)
            for _, instance := range instances {
                fmt.Fprintf(w, "- %s %s\n", instance.GetName(), instance.GetMachineType())
            }
        }
    }

    return nil
}

The above worked well, even though it might not like pretty.
Below is my effort to move/transition the module to a Restful API:
package handlers

import (
    "context"
    "fmt"
    "net/http"

    compute "cloud.google.com/go/compute/apiv1"
    "google.golang.org/api/iterator"
    computepb "google.golang.org/genproto/googleapis/cloud/compute/v1"
    "google.golang.org/protobuf/proto"
)

// use Google Cloud compute API to get the list of instance virtual machine instances
func (s *Server) getListAllInstances(w http.ResponseWriter, r *http.Request) error {

    ctx := context.Background()
    instancesClient, err := compute.NewInstancesRESTClient(ctx)

    if err != nil {
        return fmt.Errorf("NewInstancesRESTClient: %v", err)
    }
    defer instancesClient.Close()

    // Use the `MaxResults` parameter to limit the number of results that the API returns per response page.
    req := &computepb.AggregatedListInstancesRequest{
        Project:    "unqie-string-id",
        MaxResults: proto.Uint32(16),
    }

    it := instancesClient.AggregatedList(ctx, req)
    fmt.Fprintf(w, "Instances found:\n")
    // Despite using the `MaxResults` parameter, you don't need to handle the pagination
    // yourself. The returned iterator object handles pagination
    // automatically, returning separated pages as you iterate over the results.

    for {
        pair, err := it.Next()
        if err == iterator.Done {
            break
        }
        if err != nil {
            return err
        }
        instances := pair.Value.Instances
        if len(instances) > 0 {
            w.WriteHeader(http.StatusOK)
            fmt.Fprintf(w, "%s\n", pair.Key)
            for _, instance := range instances {
                fmt.Fprintf(w, "- %s %s\n", instance.GetName(), instance.GetMachineType())
            }
        }
    }

    return nil

}

ParentId is the culprit (scroll below for the full error). The string I inserted does not seem to work in the code above. Google Cloud API is trying to figure out what parent ID is for the project.
How can I fix the code above?
Il leave this code below just for reference

Here is the path that my api uses to pull the list of active virtual machines
package handlers

import "skeleton/api/middlewares"

func (s *Server) InitializeRoutes() {

    s.Router.HandleFunc("/compute", middlewares.MiddlewaresJSON(s.getListAllInstances)).Methods("GET")

}

here is my MiddlewaresJSON:
package middlewares

import (
    "log"
    "net/http"
)

// intercept the incoming request, and set one of the headers to Content-Type: application/json
func MiddlewaresJSON(next http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        // log the route and method
        log.Println("== route: " + r.URL.Path)
        log.Println("== method: " + r.Method)

        // modify the header
        w.Header().Set("Content-Type", "application/json")
        next(w, r)
    }
}

Here is the full error:
cloud.google.com/go/compute/apiv1
..\go\pkg\mod\cloud.google.com\go@v0.97.0\compute\apiv1\firewall_policies_client.go:684:32: invalid operation: req.ParentId != nil (mismatched typen: req.ParentId != nil (mismatched types string and nil)

Here is the code in the library that error is referring too:
    if req != nil && req.ParentId != nil {
        params.Add("parentId", fmt.Sprintf("%v", req.GetParentId()))
    }

A: I had the same issue, solved by downgrading of 1 commit :
 go get google.golang.org/genproto@81c1377

https://github.com/googleapis/go-genproto/commits/main

A: Is it error in your code or just in publication?
in publication I see
req := &computepb.AggregatedListInstancesRequest{
        Project:    "unqie-string-id,
        MaxResults: proto.Uint32(16),
    }

but should be
req := &computepb.AggregatedListInstancesRequest{
        Project:    "unqie-string-id",
        MaxResults: proto.Uint32(16),
    }


text:
Q: Communication between Windows Host and Linux Docker Container I have the following problem. I have a piece of software on a windows host system, which emulates the com-interface at this computer. Now i would like to provide a API / Socket / Pipe in this software, which accepts a string which is transfered over LAN.
The submit software should be a .net core webapplication, which is hosted in kubernetes as a docker container (Linux).
Which kind of technology could i use to speak between a Linux Container and a Windows Host.

*

*Named Pipes -> I think they are not available under Linux?

*Sockets?

*Try to open a webserver on the windows host to get access via http ?

Whats your ideas and why do you prefer a solution?

A: Linux do have named pipes, though the exact semantic of different operations vary, but the problem you'll have is that named pipe cannot be used to communicate between different systems. Named pipe is an inter-process communication for process running on the same machine. Note that Windows Host and Linux Guest are considered two separate systems here even when they live in the same physical machines.
TCP is the most general purpose form of sockets and is the standard way to connect between two OSes. If you don't know why you want to use the other protocols, TCP is usually a good bet that it'll be able to connect almost everything.
Now the only problem is what application level protocol you want to use, and whether you want to add any security layer (i.e. TLS) to encrypt and authenticate the connection between the machines. If you have a simple service that only needs to transmit simple strings, then you probably can just use TCP/TLS socket directly, but if you want to benefit from standardized phraseology, techniques, and libraries and frameworks for various things like communicating request and responses statuses, authentication, optimistic locking, caching, proxying, session management, arbitrary length stream encoding, etc, then building your communication on top of HTTP/HTTPS is a sensible thing to do. You'll find that a lot of services nowadays are built as a web service as it makes things a lot simpler when you need to scale and make use of those features.


text:
Q: How to determine if true/false and then return a function I have truth tables for different logical operators;
truthtable a1
 | a1 == "mynot"   = [(p,q,r,s) | p <- [0,1], q <- [0,1], let r = mynot p, s <- ["mynot"]]
 | a1 == "myand"   = [(p,q,r,s) | p <- [0,1], q <- [0,1], let r = myand p q, s <- ["myand"]]
 | a1 == "myor"    = [(p,q,r,s) | p <- [0,1], q <- [0,1], let r = myor p q, s <- ["myor"]]
 | a1 == "myimply" = [(p,q,r,s) | p <- [0,1], q <- [0,1], let r = myimply p q, s <- ["myimply"]]

Now I have to make a function (equiv) that determines if two operators act the same and give a counter example if not. So for equiv "myimply" "myimply" it should determine that it is equivalent, but for equiv "myimply" "myor" it should call the function counterEx which gives a counterexample (that the operators are not the same).
Now I had this:
equiv a1 a2
 | truthtable a1 == truthtable a2 = True
 | otherwise = counterEx a1 a2

counterEx a1 a2 = truthtable a1 ++ truthtable a2

But of course, equiv has different outcomes and thus is not possible. However I don't really know how I can give a better counter example (than just give all possibilities and you would just look what is not the same). As well I don't really know how I can call the function counterEx if the truth tables are not equivalent but only determine that they are the same if the truth tables really are the same.

A: The most idiomatic solution here is to use a custom return data type
type TTable = [(Int,Int,Int,Int)]

data EquivResult
  = Equivalent
  | NotEquivalent TTable

equiv :: TTable -> TTable -> EquivResult
equiv a1 a2
 | truthtable a1 == truthtable a2 = Equivalent
 | otherwise                      = NotEquivalent (counterEx a1 a2)

One can also use Maybe TTable instead of defining a custom EquivResult, but it is less obvious that Nothing would mean "equivalent", and Just _ would mean "_ is a counterexample".
equiv :: TTable -> TTable -> Maybe TTable
equiv a1 a2
 | truthtable a1 == truthtable a2 = Nothing
 | otherwise                      = Just (counterEx a1 a2)

By the way, why do you use the integers 0 and 1 for booleans? Why not False and True of type Bool. Using Int for booleans feels weird, and allows invalid values like 2.
(As a general recommendation, I would suggest to start writing each function by declaring its type. Type signatures are very important to detect potential errors soon, and to help the compiler to produce better error messages.)


text:
Q: Unexpected token u in JSON at position 0 not working for async I am fairly new to js and node.js but I have managed to get the calls going to the API and getting the necessary information.  However when I was attempting to continue to raise the batter id to get the next information available.  I have successfully gotten the undefined error check to work as well.  But I was unable to loop through because I was trying to perform something immediately on an async function.  I am now trying to make the entire function async with a 2 second delay after each run, but it is returning the following error (i'm assuming because something is undefined)
**Note:  When I just get the value for i=4 and p=1 the value does exist in the API data.  However it gives this error when I attempt to start with those values using this code.
error:
Unexpected token u in JSON at position 0

this is my code:
   request('API Info redacted',
       setTimeout (function (err, response, body) {

        //do stuff below
        //to get the first play of the game, set i=1 and p=0
         var i = 4;
         var p = 1;
         // ************
         var boolIn = 1;

         // parse the body as JSON
         var parsedBody = JSON.parse(body);
         var apiResults = parsedBody.apiResults;

         if( typeof(apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p]) == 'undefined') {
            //sets the variables to the first batter of the next inning
            p=0;
            i = i+1;
         }

         //below pulls the apiResults from the body of the API request
         var sportId = apiResults.sportId;
         var hitName = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].name;
         var fname = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].batter.firstName;
         var lname = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].batter.lastName;
         var outsB = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].outs.before;
         var outsA = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].outs.after;
         var rbis = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].runsBattedIn;
         var outDifference = (outsA - outsB);
         var hitB = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].baseSituation.beforeId;
         var hitA = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].baseSituation.afterId;
         var baseDifference = (hitA - hitB);

         //prints the details pulled above
         res.json("First Name: " + fname + ", Last Name: " + lname + ", Hit name: " + hitName + ", Outs on the play: " + outDifference + ", Rbi's: " + rbis +
         ", Base Sit: " + baseDifference);

         //increases the batter call
         p = p+1;

        //below ends the setTimeout
        }, 2000));

        //ended request
    });

A: setTimeout will not pass arguments to the function it calls, so body is undefined. When you pass that to JSON.parse, it will be converted to the string "undefined", which isn't a valid JSON text.
Nowhere is your code do you show any JSON coming into your program (or embedded into it). You need to have some JSON to parse before you try to parse it.


text:
Q: Как менять цвет шапки при прокручивании страницы? На сайте есть несколько разделов. Первый с картинкой, на нем шапка должна быть прозрачной. Следующие блоки цветные и на них шапка должна принимать цвет блока. Как мне этого добиться? Я написал код, чтобы шапка менялась с прозрачной на цвет второго блока, но вот мне кажется есть решение получше, чем писать так для каждого блока, однако я не могу его найти... Код:

$(function() {
    let header = $('.header'),
        intro = $('.intro');

    $(window).scroll(function() {
      if($(this).scrollTop() > intro.outerHeight()) {
       header.addClass('header_filled');
      } else {
       header.removeClass('header_filled');
      }
    });
});
*,
*::before,
*::after {
    box-sizing: border-box;
}

h1, h2, h3, h4, h5, h6 {
    margin: 0;
}

a {
    text-decoration: none;
}

body {
    margin: 0;
    font-family: 'Montserrat', sans-serif;

    font-size: 15px;
    line-height: 1.6;
    color: #fff;
}

/* Animations */

/* Container */
.container {
    width: 100%;
    max-width: 1200px;
    margin: 0 auto;
}

/* Header */
.header {
    width: 100%;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;
}

.header__logo {
    font-size: 30px;
    font-weight: 700;
    color: #fff;
}

.header__inner {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header_filled {
    background-color: #3ebb46;
    border-radius: 0 0 20px 20px;
    transition: .2s ease-in;
}

/* Intro */
.intro {
    display: flex;
    flex-direction: column;
    justify-content: center;

    width: 100%;
    height: 100vh;

    background: url("../img/intro.jpg") center no-repeat;
    background-size: cover;
    font-size: 20px;
}

.intro__inner {
    margin: 0 auto;
    backdrop-filter: blur(2px);
    -webkit-backdrop-filter: blur(2px);
    border: 1px solid #fff;
    border-radius: 30px;
}

.intro__title {
    font-size: 72px;
    text-align: center;
}

.intro__subtitle {
    font-family: 'Jost', sans-serif;
    text-transform: uppercase;
    font-size: 36px;
    text-align: center;
}

/* Navigation */
.nav {
    display: flex;
    font-size: 15px;
    font-weight: 500;
    text-transform: uppercase;

}

.nav__link {
    color: #fff;
    padding: 0 10px;
}

.nav__link:hover {
    color: #ffffff;
    background-color: #0d7711;
    border-radius: 10px;
}

/* About */
.about {
    background-color: #3ebb46;
    width: 100%;
    height: 100vh;
    padding: 60px 0;

    color: #fff;
    font-size: 20px;
}

.about__title {
    background-color: #61c467;
    text-align: center;
    border-radius: 10px;

}

.about__text {
    text-align: justify;
}

.about__link {
    font-size: 21px;
    font-weight: 700;
    color: #6868d8;
    text-decoration: wavy;
    padding:0 2px 0 2px;

}

.about__link:hover {
    text-decoration: none;
    color: #3ebb46;
    background-color: #fff;
    border-radius: 5px;
    transition: .1s ease-in;
}

/* Servives */
.services {
    background-color: #48daae;
    width: 100%;
    height: 100vh;
    padding: 60px 0;

    color: #fff;
    font-size: 20px;
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="css/normalize.css">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;700&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Jost&display=swap" rel="stylesheet">

    <title>Document</title>

CottageKarelia

                    Главная
                    О компании
                    Услуги
                    Отдых в Карелии
                    Владельцам
                    Оплата
                    Контакты

Гостевые дома и коттеджи Карелии

Простой выбор для Вашего отдыха!

О деятельности компании

                    Наш сайт является крупнейшим каталогом гостевых домов и коттеджей в Карелии,
                    на котором собрано более 1000 позиций. Здесь Вы сможете найти любой дом,
                    соответствующий всем Вашим потребностям. Благодаря удобной форме поиска,
                    Вы наиболее полно сможете охарактеризовать, что именно Вам необходимо, после чего,
                    Вам будут представлены наиболее подходящие дома. Когда Вы определитесь с выбором дома,
                    Вам будет предложено забронировать его, после чего и начнется Ваш отдых! Кроме того,
                    мы с радостью предлагаем гостям Карелии различные туры, созданные для абсолютно любой
                    категории людей.

                    Наши менеджеры свяжутся с Вами и узнают все Ваши пожелания, после чего они сформируют Вам тур:
                    определят наиболее предпочтительные и удобные варианты проезда, сообщат о дополнительных возможностях
                    на территории выбранного места или тура, посоветуют достопримечательности Карелии, которые можно будет
                    посетить неподалеку от выбранного дома, предложат Вам трансфер с вокзала к гостевому дому или коттеджу
                    и обратно. Иными словами, за Вас сделают все и обеспечат Вам лучший отдых на земле в райском уголке,
                    по имени Карелия!

Дополнительные услуги

A: <!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Test</title>

CottageKarelia

                Главная
                О компании
                Услуги
                Отдых в Карелии
                Владельцам
                Оплата
                Контакты

Гостевые дома и коттеджи Карелии

Простой выбор для Вашего отдыха!

О деятельности компании

                Наш сайт является крупнейшим каталогом гостевых домов и коттеджей в Карелии,
                на котором собрано более 1000 позиций. Здесь Вы сможете найти любой дом,
                соответствующий всем Вашим потребностям. Благодаря удобной форме поиска,
                Вы наиболее полно сможете охарактеризовать, что именно Вам необходимо, после чего,
                Вам будут представлены наиболее подходящие дома. Когда Вы определитесь с выбором дома,
                Вам будет предложено забронировать его, после чего и начнется Ваш отдых! Кроме того,
                мы с радостью предлагаем гостям Карелии различные туры, созданные для абсолютно любой
                категории людей.

                Наши менеджеры свяжутся с Вами и узнают все Ваши пожелания, после чего они сформируют Вам тур:
                определят наиболее предпочтительные и удобные варианты проезда, сообщат о дополнительных возможностях
                на территории выбранного места или тура, посоветуют достопримечательности Карелии, которые можно будет
                посетить неподалеку от выбранного дома, предложат Вам трансфер с вокзала к гостевому дому или коттеджу
                и обратно. Иными словами, за Вас сделают все и обеспечат Вам лучший отдых на земле в райском уголке,
                по имени Карелия!

Дополнительные услуги

                Наш сайт является крупнейшим каталогом гостевых домов и коттеджей в Карелии,
                на котором собрано более 1000 позиций. Здесь Вы сможете найти любой дом,
                соответствующий всем Вашим потребностям. Благодаря удобной форме поиска,
                Вы наиболее полно сможете охарактеризовать, что именно Вам необходимо, после чего,
                Вам будут представлены наиболее подходящие дома. Когда Вы определитесь с выбором дома,
                Вам будет предложено забронировать его, после чего и начнется Ваш отдых! Кроме того,
                мы с радостью предлагаем гостям Карелии различные туры, созданные для абсолютно любой
                категории людей.

                Наши менеджеры свяжутся с Вами и узнают все Ваши пожелания, после чего они сформируют Вам тур:
                определят наиболее предпочтительные и удобные варианты проезда, сообщат о дополнительных возможностях
                на территории выбранного места или тура, посоветуют достопримечательности Карелии, которые можно будет
                посетить неподалеку от выбранного дома, предложат Вам трансфер с вокзала к гостевому дому или коттеджу
                и обратно. Иными словами, за Вас сделают все и обеспечат Вам лучший отдых на земле в райском уголке,
                по имени Карелия!

 *,
        *::before,
        *::after {
            box-sizing: border-box;
        }

        h1, h2, h3, h4, h5, h6 {
            margin: 0;
        }

        a {
            text-decoration: none;
        }

        body {
            margin: 0;
            font-family: 'Montserrat', sans-serif;

            font-size: 15px;
            line-height: 1.6;
            color: #fff;
        }

        /* Animations */

        /* Container */
        .container {
            width: 100%;
            max-width: 1200px;
            margin: 0 auto;
        }

        /* Header */
        .header {
            width: 100%;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 100;
            transition: 0.2s;
        }

        .header__logo {
            font-size: 30px;
            font-weight: 700;
            color: #333;
        }

        .header__inner {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        /* Intro */
        .intro {
            display: flex;
            flex-direction: column;
            justify-content: center;
            width: 100%;
            background-size: cover;
            font-size: 20px;
            padding-top: 60px;
            background-color: #fff;
        }

        .intro__inner {
            margin: 0 auto;
            backdrop-filter: blur(2px);
            -webkit-backdrop-filter: blur(2px);
            border: 1px solid #fff;
            border-radius: 30px;
        }

        .intro__title {
            font-size: 72px;
            text-align: center;
            color: #555;
        }

        .intro__subtitle {
            font-family: 'Jost', sans-serif;
            text-transform: uppercase;
            font-size: 36px;
            text-align: center;
        }

        /* Navigation */
        .nav {
            display: flex;
            font-size: 12px;
            font-weight: 500;
            text-transform: uppercase;
        }

        .nav__link {
            color: #666;
            padding: 0 10px;
        }

        .nav__link:hover {
            color: #ffffff;
            background-color: #0d7711;
            border-radius: 10px;
        }

        /* About */
        .about {
            background-color: #3ebb46;
            width: 100%;
            padding: 60px 0;
            color: #fff;
            font-size: 20px;
        }

        .about__title {
            background-color: #61c467;
            text-align: center;
            border-radius: 10px;
        }

        .about__text {
            text-align: justify;
        }

        .about__link {
            font-size: 21px;
            font-weight: 700;
            color: #6868d8;
            text-decoration: wavy;
            padding:0 2px 0 2px;
        }

        .about__link:hover {
            text-decoration: none;
            color: #3ebb46;
            background-color: #fff;
            border-radius: 5px;
            transition: .1s ease-in;
        }

        /* Servives */
        .services {
            background-color: #48daae;
            width: 100%;
            padding: 60px 0;
            color: #fff;
            font-size: 20px;
        }

let sections = {};
    let currentBlock;
    let header = $('.header');

    $(function () {

        $('body > section').each(function () {
            let blockTop = Math.round($(this).offset().top) - $('.header').outerHeight();

            if(blockTop < 0) {
                blockTop = 0;
            }

            sections[blockTop] = $(this).attr('id');
        });

        defineBlock(sections);

        header.css('background-color', $(`#${sections[currentBlock]}`).css('background-color'));

        $(window).scroll(function () {
            defineBlock(sections);

            let currentBlockColor = $(`#${sections[currentBlock]}`).css('background-color');

            if (header.css('background-color') !== currentBlockColor) {
                header.css('background-color', currentBlockColor);
            }
        });
    });

    function defineBlock(sections) {
        $(Object.keys(sections)).each(function (index, item) {
            if ($(window).scrollTop() >= +item) {
                currentBlock = +item;
            }
        });
    }

Можно попробовать без классов https://jsfiddle.net/qxwhc86n/


text:
Q: Why does the getter function gives error when used in place of "?" I tried to give the values of column in SQL query using the get() function but it gives an SQLSyntaxErrorException.
try {
    Class.forName("com.mysql.cj.jdbc.Driver");

    Connection connect = DriverManager.getConnection("DB URL");

    String sl = "INSERT INTO users(username,password)" + "VALUES(" + beans.getUsername() + "," + beans.getPassword() + ")";

    PreparedStatement pts = connect.prepareStatement(sl);

    pts.executeUpdate();

}

A: Assuming1 that those two columns are VARCHAR (or similar), the values need to be supplied as string literals in the SQL.  But your code for building the SQL is not putting the quotes around the strings.  Therefore, the SQL is not valid.
Another problem with creating SQL statements like that is that it potentially makes your application vulnerable to SQL Injection.
PreparedStatement and ? solve both of those problems.  The JDBC driver handles any quoting, escaping and other transformations needed to insert the values into the SQL safely.

1 - This assumption is based on the column names: username and password.