text:
Q: Is there any reason to get NullPointerException when closing a foreground service? Background
On a large app, that is very popular, I've noticed that when we close a foreground service, on a very specific group of devices (OnePlus devices: 6, 6T,A6000 and a few others) and Android versions  (Android 9) , we got NPE:
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'long java.lang.Long.longValue()' on a null object reference
       at android.os.Parcel.createException + 1956(Parcel.java:1956)
       at android.os.Parcel.readException + 1918(Parcel.java:1918)
       at android.os.Parcel.readException + 1868(Parcel.java:1868)
       at android.app.IActivityManager$Stub$Proxy.setServiceForeground + 5111(IActivityManager.java:5111)
       at android.app.Service.stopForeground + 724(Service.java:724)
       at android.app.Service.stopForeground + 710(Service.java:710)
       ...

And the code that calls it is:
    stopForeground(true) //crash here
    stopSelf()

The problem
Since I don't have any of those devices, let alone Android 9 for them, I can't find the reason for this.
Since the app is so popular, and I see this issue exists only on those devices and Android versions, I suspect that indeed something is wrong only for them.
What I've found
Only thing I could do is to search for this issue over the Internet, but I couldn't find it.
The only similar thing is here, but it talks about Android O, and we didn't get even a single crash event there.
I know that sadly various manufacturers have applied a bad behavior that kills apps even if they are in the foreground (written about here), but I didn't think that this could cause a crash...
The questions

*

*Is there anything I can do to prevent it? The other place mentioned to use a wakeLock. Would that help?

*Maybe would using try-catch avoid this crash? But then what could happen? Would stopSelf alone make the service stop as usual? Or maybe I need to use try-catch on it as well?

*What is this exception anyway? I thought it would tell me about some invalid state, but instead I see NPE...


text:
Q: Import database (SQL file) in SQL Server Management Studio I've created the structure of my database first in PhpMyAdmin and exported it to a .sql file.
Now I'm looking everywhere in SQL Server Management Studio where I can import/add the data in a new database.
Does anybody where to look or what to click?
I'm using the 2014 version (CTP2)

A: If you have a .sql file which contains SQL statements, you can just copy and paste the contents (or open the file in a query window) and run it. This assumes it has all of the create table etc. statements to create the schema/structure and not just insert statements for the data.
Check the top of the file to make sure that it is first selecting the correct database, if not add a USE statement to select the correct database.
You didn't say how big the file was, but if it is quite large and has the insert statements (data as well as schema), then you'll probably want to run by CLI using sqlcmd command. Much faster and SSMS won't freak out.
Another alternative option to running the .sql file/code is to set up a data source for mysql and just use odbc to access the database itself.
Bear in mind that there are real and very annoying differences between mysql and t-sql that can make migration a pain. If you're just creating a few tables, it may not be an issue, but if there are a ton of tables with lots of fields of different data types, you may run into issues.

A: If you are looking to import table structure, you can copy-paste the content and run inside SSMS in a query window. Beware of syntax differences with MySQL and SQL Server. You will most likely get errors. You need to convert your SQL script from MySQL dialect to SQL Server dialect (or just add them manually if they are not too many). If you set the databases to a SQL standard-compatibility mode at the very beginning, you will have much less trouble.
If you are ONLY looking just to import the data into existing tables inside the SQL Server only, you can do the same (i.e. copy-paste and run in query window). You will have less trouble with that.

A: Open the server, open "Databases" and right click the database, go to "Tasks" and then Import Data...

A: I have had the most 'trouble free' success importing to SQL via a flat file method (comma delimited .txt file), the only stipulation when creating a flat file (i.e from Access) make sure the text identifier is set to {none} and not "".
To import the file: in the SQL Server Management Studio right click on Databases and create a new database. Then right click on the new database -> Tasks -> Import Data... The import window opens: in the DATA SOURCE option select Flat File Source and select the .txt file...click NEXT. In the DESTINATION field select SQL Server Native Client 11.0 and go through the import process. This worked very well for me.

redpajama_set_name: RedPajamaStackExchange


text: Q: Acoustic signal processing using Python I am new to python & its libraries and need some guide. I have measured time domain signals (volts) and need to upload this data to python and do a a fast fourier transform


text:
Q: UIViewControllers does not detects tap / touch events I am creating UIViewController programmatically. In its viewDidLoad, I am creating instance of custom UIView Component which has bunch of button and text filed. I set this view as viewControllers view.
But when I select any UIButton it does not fire any event  or  tapping inside UITextFiled does not bring  up keyboard either.
- (void)viewDidLoad
{
    [super viewDidLoad];
    SomeView *sv = [[SomeView alloc] initWithFrame:self.view.bounds];
    self.view.userInteractionEnabled = YES;
    self.view = sv;
    //[self.view addSubView:sv];
    self.title = @"Something";
}

Is there anything wrong with this piece of code ? Even adding subivew does not work.
I added tapgesture to sv and It was getting detected but nothing else was getting selected on view.
I tried added buttons/textfiled to the viewcontrollers view directly. Then it works but not through customview component.

A: Try holding a strong reference to the view, It might be getting deallocated.
@interface YOURCLASS ()
@property (nonatomic, strong) SomeView *sv;
@end

And then Go back fro trying to add it as a subview.  See if that works.
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.sv = [[SomeView alloc] initWithFrame:self.view.bounds];
    self.view.userInteractionEnabled = YES;
    [self.view addSubView:self.sv];
    self.title = @"Something";
}


text:
Q: python count size specific type file txt in a directory In my folder, there are two types of files: html and txt.
I want to know the total size of the txt files.
I found this code, but how do I apply it for my needs?
import os
from os.path import join, getsize
size = 0
count = 0
for root, dirs, files in os.walk(path):
    size += sum(getsize(join(root, name)) for name in files)
    count += len(files)
print count, size

A: You can qualify which files by adding an if to the comprehensions like:
for root, dirs, files in os.walk(path):
    size += sum(getsize(join(root, name)) for name in files if name.endswith('.txt'))
    count += sum(1 for name in files if name.endswith('.txt'))
print count, size

A: better use glob (https://docs.python.org/3/library/glob.html) instead of os to find your files. that makes it imho more readable.
import glob
import os

path = '/tmp'
files = glob.glob(path + "/**/*.txt")
total_size = 0
for file in files:
    total_size += os.path.getsize(os.path.join(path, file))
print len(files), total_size


text:
Q: SPARQL nested tuples in rdf file How to write SPARQL for a rdf file that contains these kind of tuples
<rdf:Description rdf:about="http://example.com/BEROVO">
            <j.0:destDetails rdf:resource="http://example.com/0c64a8f2-fd39-4e9d-a03b-527359af8661"/>
            <j.0:destDetails rdf:resource="http://example.com/31dd238d-0356-4d78-b6fb-26647902ecd3"/>
            <j.0:destDetails rdf:resource="http://example.com/76248058-5dd1-42a5-b988-affcf732ac6a"/>
            <j.0:destDetails rdf:resource="http://example.com/f8541d66-4107-464a-bc31-60df76a4f7a4"/>
            <j.0:destDetails rdf:resource="http://example.com/1298d38c-e69f-42ca-a329-f0cd8091a524"/>
            <j.0:destDetails rdf:resource="http://example.com/5122c7a1-ca0d-4302-84ad-fea4909e8551"/>
            <j.0:destDetails rdf:resource="http://example.com/cb25a063-0787-4079-8e4a-21e3440df8c3"/>
            <j.0:destDetails rdf:resource="http://example.com/f72eeb27-4852-4737-b248-338bc05206b4"/>
            <j.0:destDetails rdf:resource="http://example.com/0fc999e9-0a5a-4555-a7bf-6a4a41508ae8"/>
            <j.0:destDetails rdf:resource="http://example.com/3303225e-f2dd-4712-9cb3-d10a69bd4357"/>
            <j.0:destDetails rdf:resource="http://example.com/31d37728-a72d-445e-b554-d5cdc91830e5"/>
</rdf:Description>
<rdf:Description rdf:about="http://example.com/0c64a8f2-fd39-4e9d-a03b-527359af8661">
            <j.0:distrName>BEROVOTRANS-BEROVO</j.0:distrName>
            <j.0:moneyTwoDir>520 den.</j.0:moneyTwoDir>
            <j.0:moneyOneDir>420 den.</j.0:moneyOneDir>
            <j.0:hasTimeStop>17:15</j.0:hasTimeStop>
            <j.0:hasTimeStart>13:20</j.0:hasTimeStart>
</rdf:Description>

For every item from the list with tuples I like to get information for the properties:

*

*j.0:distrName,

*j.0:moneyTwoDir,

*j.0:moneyOneDir,

*j.0:hasTimeStop, and

*j.0:hasTimeStart.

A: While the syntaxes for Turtle and SPARQL aren't exactly the same, many Turtle expressions are suitable as SPARQL patterns.  If we take a slight modification of your data (to make it a complete RDF document), we get:
<rdf:RDF xmlns:j.0="http://example.com/"
         xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
  <rdf:Description rdf:about="http://example.com/BEROVO">
    <j.0:destDetails rdf:resource="http://example.com/0c64a8f2-fd39-4e9d-a03b-527359af8661"/>
    <j.0:destDetails rdf:resource="http://example.com/31dd238d-0356-4d78-b6fb-26647902ecd3"/>
    <j.0:destDetails rdf:resource="http://example.com/76248058-5dd1-42a5-b988-affcf732ac6a"/>
    <j.0:destDetails rdf:resource="http://example.com/f8541d66-4107-464a-bc31-60df76a4f7a4"/>
    <j.0:destDetails rdf:resource="http://example.com/1298d38c-e69f-42ca-a329-f0cd8091a524"/>
    <j.0:destDetails rdf:resource="http://example.com/5122c7a1-ca0d-4302-84ad-fea4909e8551"/>
    <j.0:destDetails rdf:resource="http://example.com/cb25a063-0787-4079-8e4a-21e3440df8c3"/>
    <j.0:destDetails rdf:resource="http://example.com/f72eeb27-4852-4737-b248-338bc05206b4"/>
    <j.0:destDetails rdf:resource="http://example.com/0fc999e9-0a5a-4555-a7bf-6a4a41508ae8"/>
    <j.0:destDetails rdf:resource="http://example.com/3303225e-f2dd-4712-9cb3-d10a69bd4357"/>
    <j.0:destDetails rdf:resource="http://example.com/31d37728-a72d-445e-b554-d5cdc91830e5"/>
  </rdf:Description>
  <rdf:Description rdf:about="http://example.com/0c64a8f2-fd39-4e9d-a03b-527359af8661">
    <j.0:distrName>BEROVOTRANS-BEROVO</j.0:distrName>
    <j.0:moneyTwoDir>520 den.</j.0:moneyTwoDir>
    <j.0:moneyOneDir>420 den.</j.0:moneyOneDir>
    <j.0:hasTimeStop>17:15</j.0:hasTimeStop>
    <j.0:hasTimeStart>13:20</j.0:hasTimeStart>
  </rdf:Description>
</rdf:RDF>

Using Jena's rdfcat tool, we can get this in Turtle:
$ rdfcat -out Turtle data.rdf
@prefix rdf:     <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .

<http://example.com/BEROVO>
      <http://example.com/destDetails>
              <http://example.com/31dd238d-0356-4d78-b6fb-26647902ecd3> , <http://example.com/5122c7a1-ca0d-4302-84ad-fea4909e8551> , <http://example.com/cb25a063-0787-4079-8e4a-21e3440df8c3> , <http://example.com/3303225e-f2dd-4712-9cb3-d10a69bd4357> , <http://example.com/0c64a8f2-fd39-4e9d-a03b-527359af8661> , <http://example.com/1298d38c-e69f-42ca-a329-f0cd8091a524> , <http://example.com/31d37728-a72d-445e-b554-d5cdc91830e5> , <http://example.com/0fc999e9-0a5a-4555-a7bf-6a4a41508ae8> , <http://example.com/76248058-5dd1-42a5-b988-affcf732ac6a> , <http://example.com/f72eeb27-4852-4737-b248-338bc05206b4> , <http://example.com/f8541d66-4107-464a-bc31-60df76a4f7a4> .

<http://example.com/0c64a8f2-fd39-4e9d-a03b-527359af8661>
      <http://example.com/distrName>
              "BEROVOTRANS-BEROVO" ;
      <http://example.com/hasTimeStart>
              "13:20" ;
      <http://example.com/hasTimeStop>
              "17:15" ;
      <http://example.com/moneyOneDir>
              "420 den." ;
      <http://example.com/moneyTwoDir>
              "520 den." .

Sure enough, that's pretty much what the corresponding SPARQL query would look like:
prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>

select ?details ?name ?moneyTwoDir ?moneyOneDir ?timeStop ?timeStart where {

  <http://example.com/BEROVO>
    <http://example.com/destDetails>
      ?details .

  ?details
    <http://example.com/distrName>
      ?name ;
    <http://example.com/hasTimeStart>
      ?timeStart ;
    <http://example.com/hasTimeStop>
      ?timeStop ;
    <http://example.com/moneyOneDir>
      ?moneyOneDir ;
    <http://example.com/moneyTwoDir>
      ?moneyTwoDir .
}

You can make the query a bit cleaner if you want:
prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
prefix ex: <http://example.com/>

select ?details ?name ?moneyTwoDir ?moneyOneDir ?timeStop ?timeStart where {

  ex:BEROVO ex:destDetails ?details .

  ?details ex:distrName ?name ;
           ex:hasTimeStart ?timeStart ;
           ex:hasTimeStop ?timeStop ;
           ex:moneyOneDir ?moneyOneDir ;
           ex:moneyTwoDir ?moneyTwoDir .
}

The results are as you'd expect:
$ arq --data data.rdf --query query.sparql
---------------------------------------------------------------------------------------------------------------------
| details                                 | name                 | moneyTwoDir | moneyOneDir | timeStop | timeStart |
=====================================================================================================================
| ex:0c64a8f2-fd39-4e9d-a03b-527359af8661 | "BEROVOTRANS-BEROVO" | "520 den."  | "420 den."  | "17:15"  | "13:20"   |
---------------------------------------------------------------------------------------------------------------------


text:
Q: Spring JavaMailSenderImpl logs into SMTP server every time for sending emails, causing latency in web application I am using Google's SMTP server to send transactional emails from my web application, using Spring's JavaMailSenderImpl class.
The problem is: the send Email function send(SimpleMailMessage simpleMessage), is authenticating on the SMTP for every email. This is slowing down the web server, as I am sending the emails synchronously (which is of course a bad idea, I should rather be sending the emails asynchronously using a queue.)Nevertheless my question is:
Is there a way to save the SMTP auhenitcation during the first email and use it for all the subsequent emails.

A: Use the method send(SimpleMailMessage[] messages) of JavaMailSenderImpl. It will reuse the same transport for each message.


text:
Q: JavaScript create new Array from existing by filtering object value I am trying to create new array from existing array by filtering  array object only if
value.added === true AND value.SP.type === 2
witch JavaScript function useful for fast create new array from existing array with cat_id and rm_id ? i have large number object in array trying to fast possible witch function i use ?
This is existing array
[
  {
    "cat_id": 38,
    "rm_id": 1,
    "items": {
      "Box": [
        [
          {
            "parent_name": "Box",
            "child_name": "Small",
            "category_name": "Box",
            "SP": {
              "id": 203,
              "type": 2,
              "price": 15
            },
            "added": true
          },
          {
            "parent_name": "Box",
            "child_name": "Big",
            "category_name": "Box",
            "SP": {
              "id": 203,
              "type": 2,
              "price": 15
            },
            "added": true
          },
          {
            "parent_name": "Box",
            "child_name": "Very Big",
            "category_name": "Box",
            "SP": {
              "id": 203,
              "type": 1,
              "price": 15
            },
            "added": true
          }
        ]
      ]
    }
  },
  {
    "cat_id": 37,
    "rm_id": 1,
    "items": {
      "Box": [
        [
          {
            "parent_name": "Box",
            "child_name": "Small",
            "category_name": "Box",
            "SP": {
              "id": 203,
              "type": 1,
              "price": 15
            },
            "added": true
          },
          {
            "parent_name": "Box",
            "child_name": "Big",
            "category_name": "Box",
            "SP": {
              "id": 203,
              "type": 2,
              "price": 15
            },
            "added": true
          },
          {
            "parent_name": "Box",
            "child_name": "Very Big",
            "category_name": "Box",
            "SP": {
              "id": 203,
              "type": 1,
              "price": 15
            },
            "added": true
          }
        ]
      ],
      "Sets": [
        [
          [
            {
              "parent_name": "Drawers",
              "child_name": "Full",
              "SP": {
                "id": 172,
                "type": 1,
                "price": 20
              }
            },
            {
              "parent_name": "Drawers",
              "child_name": "Queen",
              "SP": {
                "id": 174,
                "type": 2,
                "price": 20
              },
              "added": true
            }
          ],
          [
            {
              "parent_name": "Drawers",
              "child_name": "Full",
              "SP": {
                "id": 172,
                "type": 1,
                "price": 20
              }
            },
            {
              "parent_name": "Drawers",
              "child_name": "Queen",
              "SP": {
                "id": 174,
                "type": 2,
                "price": 20
              },
              "added": true
            }
          ]
        ]
      ]
    }
  }
]

I am trying to create new array from existing array like this output
[
  {
    "cat_id": 38,
    "rm_id": 1,
    "parent_name": "Box",
    "child_name": "Big",
    "category_name": "Box",
    "SP": {
      "id": 203,
      "type": 2,
      "price": 15
    },
    "added": true
  },
  {
    "cat_id": 37,
    "rm_id": 1,
    "parent_name": "Box",
    "child_name": "Big",
    "category_name": "Box",
    "SP": {
      "id": 203,
      "type": 2,
      "price": 15
    },
    "added": true
  },
  {
    "cat_id": 37,
    "rm_id": 1,
    "parent_name": "Box",
    "child_name": "Big",
    "category_name": "Box",
    "SP": {
      "id": 203,
      "type": 2,
      "price": 15
    },
    "added": true
  },
  {
    "cat_id": 37,
    "rm_id": 1,
    "parent_name": "Drawers",
    "child_name": "Queen",
    "SP": {
      "id": 174,
      "type": 2,
      "price": 20
    },
    "added": true
  }
]

A:

        const data = [
          {
            "cat_id": 38,
            "rm_id": 1,
            "items": {
              "Box": [
                [
                  {
                    "parent_name": "Box",
                    "child_name": "Small",
                    "category_name": "Box",
                    "SP": {
                      "id": 203,
                      "type": 2,
                      "price": 15
                    },
                    "added": true
                  },
                  {
                    "parent_name": "Box",
                    "child_name": "Big",
                    "category_name": "Box",
                    "SP": {
                      "id": 203,
                      "type": 2,
                      "price": 15
                    },
                    "added": true
                  },
                  {
                    "parent_name": "Box",
                    "child_name": "Very Big",
                    "category_name": "Box",
                    "SP": {
                      "id": 203,
                      "type": 1,
                      "price": 15
                    },
                    "added": true
                  }
                ]
              ]
            }
          },
          {
            "cat_id": 37,
            "rm_id": 1,
            "items": {
              "Box": [
                [
                  {
                    "parent_name": "Box",
                    "child_name": "Small",
                    "category_name": "Box",
                    "SP": {
                      "id": 203,
                      "type": 1,
                      "price": 15
                    },
                    "added": true
                  },
                  {
                    "parent_name": "Box",
                    "child_name": "Big",
                    "category_name": "Box",
                    "SP": {
                      "id": 203,
                      "type": 2,
                      "price": 15
                    },
                    "added": true
                  },
                  {
                    "parent_name": "Box",
                    "child_name": "Very Big",
                    "category_name": "Box",
                    "SP": {
                      "id": 203,
                      "type": 1,
                      "price": 15
                    },
                    "added": true
                  }
                ]
              ],
              "Sets": [
                [
                  [
                    {
                      "parent_name": "Drawers",
                      "child_name": "Full",
                      "SP": {
                        "id": 172,
                        "type": 1,
                        "price": 20
                      }
                    },
                    {
                      "parent_name": "Drawers",
                      "child_name": "Queen",
                      "SP": {
                        "id": 174,
                        "type": 2,
                        "price": 20
                      },
                      "added": true
                    }
                  ],
                  [
                    {
                      "parent_name": "Drawers",
                      "child_name": "Full",
                      "SP": {
                        "id": 172,
                        "type": 1,
                        "price": 20
                      }
                    },
                    {
                      "parent_name": "Drawers",
                      "child_name": "Queen",
                      "SP": {
                        "id": 174,
                        "type": 2,
                        "price": 20
                      },
                      "added": true
                    }
                  ]
                ]
              ]
            }
          }
        ];
        const arry = [];
        const nested = data.reduce((obj,value) => {
            Object.values(value.items).forEach((inner,k) => {
                if(Array.isArray(inner)){
                  inner.forEach((inner,key) => {
                    if(Array.isArray(inner)){
                      inner.forEach((inner,key) => {
                        if(Array.isArray(inner)){
                          inner.forEach(inner => {
                            if(inner.added && inner.SP.type === 2){
                              arry.push({"cat_id":value.cat_id,"room_id":value.rm_id,...inner})
                            };
                          })
                        }
                        if(inner.added && inner.SP.type === 2){
                          arry.push({"cat_id":value.cat_id,"room_id":value.rm_id,...inner})
                        };
                      })
                    }
                  })
                }
            });
            return arry;
        },[]);

    console.log(nested);

A: Here's a partially complete answer if anyone wants to finish it. It doesn't concat the outer properties and there's some nested circular objects
Input

    let arr = [
      {
        "cat_id": 38,
        "rm_id": 1,
        "items": {
          "Box": [
            [
              {
                "parent_name": "Box",
                "child_name": "Small",
                "category_name": "Box",
                "SP": {
                  "id": 203,
                  "type": 2,
                  "price": 15
                },
                "added": true
              },
              {
                "parent_name": "Box",
                "child_name": "Big",
                "category_name": "Box",
                "SP": {
                  "id": 203,
                  "type": 2,
                  "price": 15
                },
                "added": true
              },
              {
                "parent_name": "Box",
                "child_name": "Very Big",
                "category_name": "Box",
                "SP": {
                  "id": 203,
                  "type": 1,
                  "price": 15
                },
                "added": true
              }
            ]
          ]
        }
      },
      {
        "cat_id": 37,
        "rm_id": 1,
        "items": {
          "Box": [
            [
              {
                "parent_name": "Box",
                "child_name": "Small",
                "category_name": "Box",
                "SP": {
                  "id": 203,
                  "type": 1,
                  "price": 15
                },
                "added": true
              },
              {
                "parent_name": "Box",
                "child_name": "Big",
                "category_name": "Box",
                "SP": {
                  "id": 203,
                  "type": 2,
                  "price": 15
                },
                "added": true
              },
              {
                "parent_name": "Box",
                "child_name": "Very Big",
                "category_name": "Box",
                "SP": {
                  "id": 203,
                  "type": 1,
                  "price": 15
                },
                "added": true
              }
            ]
          ],
          "Sets": [
            [
              [
                {
                  "parent_name": "Drawers",
                  "child_name": "Full",
                  "SP": {
                    "id": 172,
                    "type": 1,
                    "price": 20
                  }
                },
                {
                  "parent_name": "Drawers",
                  "child_name": "Queen",
                  "SP": {
                    "id": 174,
                    "type": 2,
                    "price": 20
                  },
                  "added": true
                }
              ],
              [
                {
                  "parent_name": "Drawers",
                  "child_name": "Full",
                  "SP": {
                    "id": 172,
                    "type": 1,
                    "price": 20
                  }
                },
                {
                  "parent_name": "Drawers",
                  "child_name": "Queen",
                  "SP": {
                    "id": 174,
                    "type": 2,
                    "price": 20
                  },
                  "added": true
                }
              ]
            ]
          ]
        }
      }
    ]

const isObject = function(obj){
  return obj === Object(obj);
}

const myFunc = function(result, value){

  if (Array.isArray(value)){
      value.reduce(myFunc, result)
    // value.filter(function(child) {
    //  return ! Array.isArray(child)
    // })
  }
  if (isObject(value)) {
        Object.values(value).reduce(myFunc, result)
        Object.keys(value).forEach(child => {
        if (child != "SP" && isObject(value[child])){
            delete value[child]
      }
    })
  }
  //for(let i = 0; i<result.length; i++){
  //  result[i] = {...result[i], ...value}
  //}
  if (value.SP && value.added === true && value.SP.type === 2){
    result.push(value)
  }
  return result
}

newArr = arr.reduce(myFunc, [])

Output

[{
  added: true,
  category_name: "Box",
  child_name: "Small",
  parent_name: "Box",
  SP: {
    id: 203,
    price: 15,
    type: 2
  }
}, {
  added: true,
  category_name: "Box",
  child_name: "Big",
  parent_name: "Box",
  SP: {
    id: 203,
    price: 15,
    type: 2
  }
}, [circular object Object], [circular object Object], {
  added: true,
  category_name: "Box",
  child_name: "Big",
  parent_name: "Box",
  SP: {
    id: 203,
    price: 15,
    type: 2
  }
}, [circular object Object], {
  added: true,
  child_name: "Queen",
  parent_name: "Drawers",
  SP: {
    id: 174,
    price: 20,
    type: 2
  }
}, [circular object Object], {
  added: true,
  child_name: "Queen",
  parent_name: "Drawers",
  SP: {
    id: 174,
    price: 20,
    type: 2
  }
}, [circular object Object]]


text:
Q: Problems with datetime plot in matplotlib I am trying to plot some datetime data but I have two problems I can't solve. My code is the following:
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime as DT
import numpy as np

%matplotlib inline

dt = np.dtype([('date', 'datetime64[D]'), ('count', np.uint32)])
data = np.array([(np.datetime64('2014-12-' + str(i)), i) for i in range(11,20)], dtype=dt)

fig, ax = plt.subplots(figsize=(18,8), dpi=300)
ax.plot_date(data['date'], data['count'])
#ax.set_xlim( [mdates.date2num( (data['date'][0] - np.timedelta64(1, 'D')).astype(DT) ),
               mdates.date2num( (data['date'][-1] + np.timedelta64(1, 'D')).astype(DT) )]);

*

*With the last line commented out I get a plot but with the x labels shifted to the right of 1 day.

*When I try to set the x limits to the day before the first day of the data and to the day after the last day of the data the limits are correctly setted but I lose the data points

A: I replicated the behaviour that you see and it appears that matplotlib does not recognise the numpy datetime64 type.
This works - converting the np.datetime64 to a standard python datetime object:
import datetime
ax.plot_date([d.astype(datetime.datetime) for d in data['date']], data['count'])


text:
Q: if statement unusual behavior Heyho,
I have a little website and want to create a pdf out of it. For this I use dompdf and some basic php:
/**
* @Route ("/generatePDF/{php}", name="generatePDF")
*/
public function generatePDFAction($php)
{
   $isPHP = $php;

   if($isPHP == true)
   {
      $lang = "php";
   }else
   {
      $lang = "js";
   }

   //open a link with $lang and get it's html (=> $html)

   //Just for testing, normally it's a working websites html-code
   $html = $isPHP;

   $dompdf = new Dompdf();
   $dompdf->loadHtml($html);
   $dompdf->setPaper('a4', 'landscape');
   $dompdf->render();
   $pdf = $dompdf->output();

   //$isPHP = false;

   if($isPHP == true)
   {
      file_put_contents("downloads/rulesphp.pdf", $pdf);
      unset($dompdf);
      return new Response($this -> redirect('/downloads/rulesphp.pdf'));
   }else
   {
      file_put_contents("downloads/rulesjs.pdf", $pdf);
      unset($dompdf);
      return new Response($this -> redirect('/downloads/rulesjs.pdf'));
   }
}

then call it:
PDF aktualisieren

or
PDF aktualisieren

whether I want the php or the js rules.
$isPHP is a boolean I handover to the function. The first if-statement works like charm, it only breaks at the end...
$html is normally the websites html, I just set it to $isPHP for testing purpose (to see if $isPHP is true/false). Now the problem:
Whenever I run my code it creates and redirects me to a rulesphp.pdf, whether or not $isPHP is set to "true" or "false".
Sidenote: When I uncomment the "//$isPHP = false" - line it creates a "rulesjs.pdf", as expected, but if I comment it in again or delete it, it won't go back to it's old behavior (as if $isPHP is always true -> creating rulesphp.pdf, regardless of what $isPHP is set), it just keeps the "creating rulesjs.pdf / $isPHP is always false"-behavior.
Sidenote2: $isPHP is set correctly, so if it's true, then the pdfs content is true (because of $html = $isPHP), if it's false the pdfs content is false, too.

A: @Route ("/generatePDF/{php}", name="generatePDF")
Your routing pass you string parameters. So, if you call it by /generatePDF/true, /generatePDF/false urls - you receive strings.
Use:
$isPHP === 'true'

or $isPHP = $php === 'true'


text:
Q: Spacebars - insert params in pure javascript without handlebars style braces I have a spacebars template for creating a button that invokes a modal:
{{#bootstrapModal
    triggerLabel="Delete"
    triggerIcon="fa-trash-o"
    triggerClass="btn-danger"
    id="deleteModal"
    title="Delete Item"
    closeLabel="No"
    primaryLabel="Delete it!"
    infoId="item123"
    infoName="Document 123"
}}
Are you sure you want to delete?
{{/bootstrapModal}}

The bootstrapModal template:
<template name="bootstrapModal">
<button class="btn {{triggerClass}}" data-toggle="modal" data-target="#{{id}}">
    {{#if triggerIcon}}
         {{triggerLabel}}
    {{/if}}

</button>

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

{{title}} {{infoName}}

                {{> UI.contentBlock}}
                {{infoName}}

                {{#if closeLabel}}
                <button type="button" class="btn btn-default" data-dismiss="modal">{{closeLabel}}</button>
                {{/if}}
                <button type="button" class="btn btn-primary">{{primaryLabel}}</button>

Which creates a button, assigns a modal to it and then I use a helper to assign functionality to the modal.
I am using the excellent reactive tables package and the fn capability https://github.com/ecohealthalliance/reactive-table#virtual-columns. I would like to use an object as params to insert into a table cell as from what I gather you can't use  handlebars / spacebars {{ }} syntax within the function. Can anyone point me in the right direction? I have some code below...
{ key: 'hello', label: "Tools", fn: function(value, object) {
                var context = {
                    triggerLabel: "Delete",
                    triggerIcon: "fa-trash-o",
                    triggerClass: "btn-danger",
                    id: "deleteModal",
                    title: "Delete Item",
                    closeLabel: "No",
                    primaryLabel: "Delete it!",
                    infoId: object._id,
                    infoName: object.name
                }

                // how to insert the context object into the bootstrapModal spacebars template in raw JS?

}
Am relatively new with Meteor, any clues?

A: You can use the #with helper to change the current context in Handlebars:
{{#with context}}
  {{#bootstrapModal}}
    ...
  {{/bootstrapModal}}
{{/with}}


text:
Q: Complex ordering in SQL Query: possibly using CASE WHEN I have a complex prioritisation algorithm that I want to write in SQL to when return prioritised pages of data.
Some of these are prioritised according to fixed values, other are ordered by variable values. i.e.
// Initial sort on ATTR1 (value1/value2 is higher than value3)
if ATTR1 = value1 or value2
  then orderBy creationDate, then modifiedDate, then author
else if ATTR1 = value3
  then
    // if ATTR1 = value3, do secondary sort on ATTR2 (value4 is higher than value5)
    if ATTR2 = value4
       then orderBy oldPriority, then modifiedDate, then creationDate, then author
    if ATTR2 = value5
       then orderBy creationDate, then modifiedDate

I have had a look at SQL CASE WHEN, but not sure how to make that work with the second level of attribute comparison.
Is CASE WHEN a suitable tool for achieving this?  Does anyone have any tips on dealing with the additional levels of complexity?
Thank you in advance!

A: Something like this should do it:
ORDER BY attr1,
CASE WHEN ATTR1 IN (value1, value2)
       THEN TO_CHAR(creationDate,'YYYYMMDDHH24MISS')
            || to_char(modifiedDate,'YYYYMMDDHH24MISS') || author
     WHEN ATTR1 = value3
       THEN attr2 || CASE WHEN ATTR2 = value4
                            THEN to_char(oldPriority,'99999')
                                 || to_char(modifiedDate,'YYYYMMDDHH24MISS')
                                 || to_char(creationDate,'YYYYMMDDHH24MISS')
                                 || author
                          WHEN ATTR2 = value5
                            THEN to_char(creationDate,'YYYYMMDDHH24MISS')
                                 || to_char(modifiedDate,'YYYYMMDDHH24MISS')
                          END
     END

I assumed that oldPriority was a NUMBER column, which may not be the case.  The point is to convert everything to strings that order correctly, using appropriate format masks.

A: Making a couple small assumptions, it seems this should work:
order by
   case ATTR1
      when value1 then
         1
      when value2 then
         2
      when value3 then
         3
   end,
      when ATTR1 in (value1,value2)
           or (ATTR1 = value3 and ATTR2 = value5) then
         creationDate
      else
         null
      end,
   case
      when ATTR1 = value3 and ATTR2 = value4 then
         oldPriority
      else
         null
      end,
   modifiedDate,
   case
      when not (ATTR1 = value3 and ATTR2 = value5) then
          author
      else null
      end


text:
Q: Time-efficiently load data from pymongo to pandas dataframe I am currently working with a MongoDB database into which I loaded ~30 Mio entries.
I need to retrieve the data from the database, filtered during the query, then transform it into a pandas DataFrame. The data is then used in a flask web application for plotting.
I tried several queries:
df = pd.DataFrame(list(db["demographics.sex"].find({"value": "male"})))

This returns 1.25 mio values and takes about 11 seconds.
I tried
data_list = list(db["demographics.sex"].find({"value": "male"}))

This takes about 8 seconds, so this step is already pretty time consuming.
Using only the query:
cursor = db["demographics.sex"].find({"value": "male"})

Takes 0-1 seconds.
So the most time consuming part seems is not the execution of the query and filter, but the transformation to a DataFrame.
Is there any method that does mongodb-->pandasdf more time-efficiently?
I would also be interested if the transformation to pandas is particularly inefficient? Is there a much better way to transport the data to a flask  powered web app?


text:
Q: anyone doing php-fpm and APC? cache files missing in /tmp I have been using xcache for a long time. Recently I put together php-fpm and nginx. I see apc is installed and enabled in the configuration. I was assuming that apc will automatically opcode the files and store it somewhere. According to config it should be in /tmp/apx.xxxx but there is no such thing there.
What am i missing? any clues to investigate would be of much help.
Please note I am using php 5.3 fpm.
thanks mates.
UPDATE: i looked at apc.php it says things are fine. will just have to take its word for it.

A: the cache files did show up eventually. Cant remember the exact location. The APC admin page shows that caching is working as you can see from the graphs.
In the combination of nginx and php-fpm I have noticed that for changes to take effect (like installing a new module) you need to retstart both nginx and php-fpm. This could be something only with my versions of the install.
hope it helps.

A: I've found the exact same behaviour, and I'm still wondering where the files are.
Did you use chroot with php-fpm? If so, if you set into the pool's config file /tmp, where did the file go? Into the chrooted /tmp directory, or outside the chroot?


text:
Q: how to drag and resize DIV element I want to resize and drag DIV element in a HTML page. The code I used is as follows.
Javascript:

CSS

HTML

The issue is that I can't drag it any where I can resize but can't reduce the DIV element size from the original size, I don't know why..?.

A: I see you are using the code from TwinHelix http://www.twinhelix.com/javascript/dragresize/
1) Please give credit to the author by always stating, clearly, where you got the code you are using. You should have told us that you are using the package available from TwinHelix. Don't, deliberately or by omission, let people think that code you show is your own. If you got it somewhere, tell us.
2) I've used that code to explore some possibilities and I had no problem with it. I could resize divs to any size, including to smaller than the original size.
I recommend you go to the TwinHelix site and get the current code and then start over and make sure you are using it correctly.
You can set limits on how large or small a div can be made, limits on how much it can be moved up and down, etc.
Make sure you understand at least the basics of what it is doing and how to code the divs to do what you want done.
Take TwinHelix's demo page, copy it to your system, with all the Javascript, etc. and get it to work on your system. Then make that page work the way you want - divisions sizes, content, etc. - and once you have divisions working the way you want, integrate the code into your own pages. Never take code from somewhere and jump right in and put it in your pages. Isolate things, make a separate test page with only the new thing, drag and resize in this example, and then integrate it into your pages.
Trying to change it to work the way you want at the same time you are integrating it into your pages will cause you more problems than you can handle.
When doing any programming, break it down into easily handled chunks, get them working the way you want, and then put them together to make the whole (I've been at "this" for 39+ years and have just a bit of experience).
Read the comments in the sample code and the other code and understand at least who to define the divisions.
Unless you are sure of what you are doing, don't modify any of the code or CSS or you may introduce problems with no idea of where they came from.
3) Except for a couple of issues, the TwinHelix code works well. My problem was in trying to stretch the capabilities and adding new ones. I got things working the way I want but there are a few quirks I simply don't like. So, I'm looking at some other methods of doing it. I don't know when I'll have it done, but when I do I'll post a page on my web site at http://www.bobnovell.com --- be aware that there is not much there right now (as of December 28, 2012) but I have a lot to add when I have time.
4) For a reasonably good drag function, take a look at http://tool-man.org/ToolManDHTML/ - the "Basic Dragable Layers" It does not have resizing but it works well. The only problem has to do with setting the zIndex. I've added code to handle mouseDowns to bring divisions
5) I would not expect anyone to look at all of the code - JavaScript, CSS, HTML - that you provided in this question and give you advice -- it is simply too large.
Also, go to the authors if you have questions.


text:
Q: Can't access filename.php without .php in extension The code inside my .htaccess file is:
# Do not remove this line or mod_rewrite rules and search engine friendly URLs will stop working
RewriteBase /

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

Is this code all right?
I was told that this would ensure that I can access my files without typing .php in the browser. However, this is not the case. I'm using WampServer Version 2.5. I've already ensured that rewrite_module is turned on in the apache modules, and ensured it's on in httpd.conf. My port 80 is used by apache itself.
So why can't I access the page without typing the extension? I get a 404 Error when I try to do so.
EDIT : I tried the solution provided Here, with the new code being:
# Do not remove this line or mod_rewrite rules and search engine friendly URLs will stop working
RewriteBase /

RewriteEngine On
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule !.*\.html$ %{REQUEST_FILENAME}.html [L]

But it still returns a 404 Error. Why is this happening?
NOT FOUND. The requested URL /SomuFinanceAJAX/bill/billMaker/index was not found on this server.

A: As per the comments, the issue appears to be related to the RewriteBase. Remove the RewriteBase / altogether.


text:
Q: How can I make leading or trailing spaces visible in a Rails HTML view? I am displaying data that is being pulled one-way from another system and I would like to highlight (not trim) trailing and leading spaces so people can see the unwanted spaces and update the data in the source system.
I'm using Rails so the obvious solution is to use the ActionView::Helpers::TextHelper.highlight method but I had some trouble getting it to behave the way I want/expect:
<%= highlight(' Adam John  ', /^\s*|\s*$/) %>

 Adam John

This generates the HTML I wanted but it turns out neither Blink nor WebKit mark leading or trailing spaces...

The same thing happens when I try to use  instead of ... The output is correct but browsers don't display it.
<%= highlight(" Adam John  ", /^\s*|\s*$/, highlighter: '\1') %>

 </span
Adam John

Is there a better way to achieve this than using highlight? My end goal is to make it clear there's extra characters there... either highlight them yellow or have something a bit like text editors and word processors do when "Invisibles" are turned on... but only the leading and trailing invisibles:

A: While researching this question I came up with a solution (and a variation) that I am sharing here. If anyone has a better answer I will happily accept that instead.
Instead of trying to fight rendering engines, replace the unwanted space(s) with some other character. A subtle dot similar to what word processors and text editors often use can be achieved like this (utility classes from Tailwind CSS):
<%= highlight(" Adam John  ", /^\s*|\s*$/, highlighter: '·') %>

...or highlight the unwanted spaces bright yellow by replacing them with non-breaking spaces (or adding an HTML entity to force it to display):
<%= highlight(" Adam John  ", /^\s*|\s*$/, highlighter: ' ') %>

Side notes
I spent some time figuring out how  works with different spaces. I experimented with invisible characters like  and  as well as space and

How <mark> handles spaces

<mark> can highlight spaces between words...

  ...but regular leading and trailing spaces are ignored

 Non-breaking leading and trailing spaces can be highlighted as part of longer string...

 ...or even on their own

 A zero width joiner outside a space means the space gets highlighted...

 ...even on their own:

 A short hyphen is shy but outside a space means the space gets highlighted...

 ...even on their own:


text:
Q: Wordpress - single-.php showing multiple results I've created a custom post type using register_post_type( 'gallery' , $args );, setting the capability_type to 'post'.
I've then created single-gallery.php to display this data.
Within single-gallery.php I have put the following code:
<?php get_header(); ?>
  <div id="galleryShow">
    <?php if ( have_posts() ) while ( have_posts() ) : the_post();
      echo(get_the_ID());
      echo($post->post_title);
      the_content();
    endwhile; ?>
  </div>
<?php get_footer(); ?>

As I understand it this should show the details of the currently selected 'gallery' page?  However it's showing the ID, title and content for EVERY gallery page.
Should I create single-gallery.php and have everything 'out' of the loop rather than 'in the loop' as I have done?  If so how would I get only the selected pages ID outside the loop?

A: I just updated my site to Wordpress 3.1 and it seems to have resolved this issue.


text:
Q: How do I avoid feature creep on a solo project? So I have a program I'm worked on back in 2011 and all through 2012, but the last release was in December of 2011. I've been actively working on it, but feature creep lured its ugly head and now it is filled with tons on unfinished features.
The bad part is that as I implement a feature, a new one creeps in. What can I do to avoid feature creep in the future so I can actually get a release out in over a year?
The project is based around iOS and used to have releases around each iOS version update, but the last one was back with 5.1 (2011). I would like to be able to get that steady release cycle back, but it has proven too difficult.

A: The answer is trite and frequently impossible: refuse to add additional features.
In more depth, the answer really comes down to what makes a new feature fall into the feature creep bin? If we assume that features that creep are those that are added to a project despite the fact that their functionality is only tangential to the intended use of the project and that the creeping features are useful, not superfluous, the answer is to move them to separate, but related tools. Use the Unix philosophy of building orthogonal tools and gluing them together.
From a project management standpoint, the answer is comparable. Decide how much time you are willing to devote to the next release and set a deadline. Estimate the features and cut enough to make the deadline. If there are stakeholders involved other than yourself, make them choose what matters most to them.
A good overview on Scheduling can be found on Joel on Software:
http://www.joelonsoftware.com/articles/fog0000000245.html

A: In my experience, it's easiest if you can have a development and release cadence that doesn't get in the way of what you want to get done. Here's how I've done it:

*

*Write the features down, and give them a rating that reflects how much you want to work on it and how much you think it will benefit the user (it may be possible to engage actual users for this). Then write them in that order.

*Before you check in/push a feature, make sure you have a stable, deployable build (strongly consider a CI system to facilitate that).

This way, you can just push a release after each feature if you want... or wait for a rollup that offers the value that you want a release to have.
Note:

*

*A feature can never be given a higher priority than the one you're working on (or it can, but it can't interrupt the one you're working on). It can come next but never now. That means that when you go from now to next, you'll have the opportunity to cut a release build if you want.

A: One of the most important lessons in development is knowing when its time to stop.
What typically happens is a developer adds a features.  That in turn inspires more ideas.  So more features get added.  That is, as you said, one of the ways a project becomes vaporware.  The developer never sees the project as 'finished', so it never gets released.
The habit you want to get into is to stop thinking in terms of a release/version as a 'finished' project.  Rather, look at development as a long-term process.  Think of releases as milestones along the path to what you one day hope the program will be.  Thus, a release/version is just a snapshot of where you are in the longer term process... a snapshot thats been well rounded out and tested.
What you can do, on the practical side, is sit down and spec out your next release.  It doesn't have to be terribly thorough.  Write down the 3-5 new major pieces of functionality you believe are essential for the next release. (actual number of features may vary depending on the type of app, not counting bug fixes or minor gui changes)  Work on those.  If you come up with other ideas, thats fine... just make notes and implement them in the following release.  When you get those 3-5 items done, your release is ready for beta.
When I start a new application, I typically think about the final 'vision' for the app.  That, to me, is what I want in version 3 of the app.  With that benchmark, I have an idea of what will make solid version 1 - just the basics.
Summary:
Each release does not have to be the finished 'vision' of the project.  Just a milestone towards that vision.

A: Use a version control system in which it is cheap to create a branch for some idea, and keep it out of your release path. For instance in git, you can "creep up" some idea, and then git stash it away. Later you can review these stashes and cherry pick them in whatever order seems interesting.
For larger features, make a real branch (so you can do multiple commits). Case in point: when I wanted to add generational support to the garbage collector, I made a branch. Stashes capture the distracting little stuff very well. Big features can start as stashes, then turn into branches, and then finally merge when they are ready.
With stashes and branches, you can take stock of your ideas, prioritize them and establish a scope for the releases of your solo project, just like a managed team project.
Look, when you get an idea, it has to go somewhere, and the best somewhere is code: the repo. Creeping features is better than forgetting good ideas. But of course, if you creep all your features into the same mainline, it will keep delaying release, unless you cut untidy releases full of half-done stuff that users have to be warned not to use.


text:
Q: Microsoft Graph - Delegated access in background process Does the O365 / graph api allow a background process to be manually configured to query with graph api the mailbox of a specific user ? The idea is to have this process condigured with the identity of a specific user to not be able to access other users data.
If yes, would provide a documentation link or some more info ?


text:
Q: Using NINI with IsolatedStorage I'm trying to save some configuration info and I wish to use NINI library and files within IsolatedStorage. I don't know why but when I try to save the configuration I got the following  exception on Nini Save method: Source cannot be saved in this state
Here's the code:
        isf = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly | IsolatedStorageScope.Domain, null, null);
        var isfs = new IsolatedStorageFileStream("file.ini", FileMode.Create, isf);
        //Stream s = new StreamWriter(isfs);

        IConfigSource mainSource = new IniConfigSource(isfs);

        var config1 = mainSource.Configs["General"];

        if (config1 == null)
        {
            mainSource.AddConfig("General");
            config1 = mainSource.Configs["General"];
        }
        config1.Set("CW", CommentWidth);
        mainSource.Save();

        isfs.Close();

The exception happens in mainSource.Save(); . Any ideas?

A: From the constructor documentation for IniConfigSource(Stream):

This is a non-savable source unless you call one of the overloaded Save methods.

So, you probably want Save(Stream). You might want to Seek the stream back to the origin before passing it to Save.

Contrary to your comments, I tried this out, and discovered that the isfs stream had been closed (presumably by the constructor method - it's not documented what it will do to the stream) - so I got a different error message. This led me to re-initializing isfs and, as I had said, passing it to the Save method:
isfs = new IsolatedStorageFileStream("file.ini", FileMode.Create, isf);
((IniConfigSource)mainSource).Save(isfs);

and it works fine.


text:
Q: How do I call an oracle stored procedure using jstl in my web project? All the inserts, updates and deletes need to be implemented in my database i need to know a form of calling them from my web application using jstl.
 I'll appreciate your help

A: It is possible
See http://dev-answers.blogspot.com/2008/04/call-stored-procedure-from-jsp-with.html
but change exec with call

A: You must not do that. Come up with a DAO layer which does the database stuff and use your DAO in your controller / servlet. Never ever should you invoke database code directly from JSP!


text:
Q: Words with friends receiving extra points not earned My friend's tiles do not add up to their value when she enters a word. She receives more points than the tiles' value. For example, she got 40pt for Zap, with 'Z' on a TL tile only.
It keeps happening. Is this possible?

A: Was ZAP the first word played in the game? If not it had to connect to another word, and you get points for that connecting word.
ZAP should be worth 14 points.  10 for Z, 1 for A, 3 for P.  With Z on a triple letter tile, you are looking at 34 points.
The other 6 points almost certainly come from the words ZAP connected to.  For instance, if OUR was on the board (3 points) and ZAP was played such that the Z was on a triple letter, and the P landed in front of OUR, you would get 34 points for ZAP, and 6 points for POUR, for a total of 40 points.
Like So:
Z
A
P O U R
The full rules for scoring in Words with friends can be found here but basically, you get points for any words you create, but special tiles only get used the first time they are covered up.  If your friend puts PED after ZAP, she gets 20 points, not 40.


text:
Q: POST to Python Flask server from Node / Express: OSError: Invalid chunk header I am trying to post some json to a python flask server and am getting the following error:
OSError: Invalid chunk header

header params
let apiParams = {
    host: "0.0.0.0",
    port: "5000",
    path: "/",
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    }
};

the post request:
generatePostRequest(apiParams) {
        let req = http.request(apiParams, function (res) {
            console.log('Status: ' + res.statusCode);
            console.log('Headers: ' + JSON.stringify(res.headers));
            res.setEncoding('utf8');
            res.on('data', function (body) {
                console.log('Body: ' + body);
            });
            req.on('error', function(e) {
                console.log('problem with request: ' + e.message);
            });
        });
        return req;
}
 let req = this.generatePostRequest(apiParams);
 req.write(JSON.stringify({text:"this is only a test"}));

console.log output
Headers: {"content-type":"application/json","content-length":"37","server":"Werkzeug/0.14.1 Python/3.7.0","date":"Fri, 12 Oct 2018 17:46:23 GMT"}
Body: {"message": "Internal Server Error"}

simple get request works
getRequest() {
        let res = fetch('http://0.0.0.0:5000')
        .then((response) => {
             return response.json();
        })
        .then(function(data){
            console.log(data);
            return data;
        })
        .catch(function(e) {
            console.log(e);
        });
        return res;
    }

A: When you're using req.write(), Node.js will default to using "chunked transfer encoding", which means that each call to req.write() will send a chunk of data to the HTTP server, preceded by a bytecount.
My guess is that Werkzeug is timing out, because you're not ending the request (so Werkzeug is expecting a new chunk, or an end-of-request, but isn't getting it and at some point it throws an error).
To end the request, you need to explicitly call req.end() when you're done:
let req = this.generatePostRequest(apiParams);
req.write(JSON.stringify({text:"this is only a test"}));
req.end();

Or, if you have a fixed amount of data to send, you can combined req.write and req.end:
let req = this.generatePostRequest(apiParams);
req.end(JSON.stringify({text:"this is only a test"}));


text:
Q: From cell coordinates to Canvas pixel position on OnSelectCell event in tStringGrid in Delphi The OnDrawCell event gives me a "Rect" record so that I know where the real pixel coordinates are:
OnDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);

On the other hand, the OnSelectCell only gives me the row/col coordinates.
OnSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);

How do I translate the row/col to pixel coordinates?
I need those because I need to create a ComboBox at runtime to cover the whole selected cell, but only when the cell is selected. I know how to do everything, but I do not know how to get the coordinates (right now, I am just creating the combo at 0,0 of the parent tStringGrid).
I am using Delphi7, but I think it is a general question and not related to the Delphi version.
PS: I am aware that there are plenty of commercial and freeware components that implement a combobox inside a cell, but I cannot and/or do not want to use them.
Thank you

A: You can determine cell screen coordinates using CellRect method
P.S. Have you ever tried to integrate controls into StringGrid?
When you meet problems with controls (having grid as Parent) behavior, look at this topic


text:
Q: Dominating function Let $$f_n: X \rightarrow \mathbb{R}$$ be a sequence of integrable functions converging uniformally towards $f$. Prove that for a finite measure, $\mu$
$$\lim_{n\rightarrow \infty}\int f_n d\mu = \int f d\mu $$
My teacher put online a proof of this implication using the dominated convergence theorem with the function
$g(x) = |f_1|+|f_2|+...+|f_n|+2$ where $\forall m \geq n$ we have $|f_m-f|\leq 1$. I understand why such a $g$ exists and why it's integrable, but I have trouble seeing why it would be greater than any $f_m$. (Obviously if $m\leq n$ it's trivial.)

A: Since you said that you are all right with the case $m\leq n$, I will just focus on the case $m>n$.
Let us set $g'(x):=|f_n(x)|+2$ with the hypothesis that $\forall m\geq n(|f-f_m|<1$ (so $g'<g$). Let $m>n$ be fixed. Let us evaluate $A:=g'(x)-f_m(x)=g'(x)-f(x)+f(x)-f_m(x).$
By hypothesis $f(x)-f_m(x)\geq-1$. Similarly, $f(x)_n-f(x)\geq-1$, which implies $g'(x)-f(x)\geq -1+2=1$. Hence, $A\geq 0$, which means that $g$ dominates $f_m$.


text:
Q: java.lang.NullPointerException: uriString when receiving image sd card path what is the reason of this error  :
 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example/com.example.sqlfirst.AddImage}: java.lang.NullPointerException: uriString

the error is pointing at this line where I am receiving the intent
img.setImageURI(Uri.parse(imagePath ));

I am trying to send a sd card path through an intent to another acitivity and convert it into an image
this is the code:
Here sending the path of the image in sd card
public   void openGallery() {

        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);

        // startActivityForResult(
          // Intent.createChooser(intent, "Complete action using"),2);
       }

   protected void onActivityResult(int requestCode, int resultCode, Intent data) {

           super.onActivityResult(requestCode, resultCode, data);

            if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {

   Bundle extras2 = data.getExtras();

                filePath = data.getData();
  Intent i = new Intent(this,
                        AddImage.class);
  i.putExtra("imagepath", filePath);
 startActivity(i);

here I suppose to recieve the path of the image and decrease the size of the image.
    String imagePath = getIntent().getStringExtra("imagePath");
    ImageView img=(ImageView) findViewById(R.id.imageView);
    img.setImageURI(Uri.parse(imagePath ));

    Bitmap bitmap = ((BitmapDrawable)img.getDrawable()).getBitmap();
    Bitmap out = Bitmap.createScaledBitmap(bitmap, 500, 500, false);
    // bitmap is the image
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
   out.compress(Bitmap.CompressFormat.JPEG, 60, stream);
   bitmap.recycle();

A: To use the path correctly you should first create it to have somewhere to store it, you can use that and later on delete it or use the data from the result you got.
Here is the code to create a Uri, pass it to your Intent. Once you get the result you can pass the Uri to another class by using getPath from the Uri package.
/**
         * Creating file uri to store image/video
         */
        public static Uri getOutputMediaFileUri() {
            return Uri.fromFile(getOutputMediaFile());
        }

    /**
     * returning image / video
     */
    private static File getOutputMediaFile() {

        // External sdcard location
        File mediaStorageDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                "YOUR DIRECTORY NAME");

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d("image upload", "Oops! Failed create "
                        + "YOUR DIRECTORY NAME" + " directory");
                return null;
            }
        }

        //TODO change naming
        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.getDefault()).format(new Date());
        File mediaFile;
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");
        return mediaFile;
    }

EDIT 1:
To convert a file to a bitmap you can use this code, provided by @Nikhilreddy Gujjula in this question
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
selected_photo.setImageBitmap(bitmap);

A: You are setting imagepath as an extra and trying to retrieve imagePath.
Also note that setImageURI() is not a good choice, as it will load and decode the image on the main application thread. Use an image-loading library, like Picasso or Universal Image Loader.


text:
Q: Amazon Aurora Snapshot backups are full or incremental? RDS Snapshot backup is full backup in the first time, and the second snapshot is incremental backup. I can find out about this in the following documents.
https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithAutomatedBackups.html

The first snapshot of a DB instance contains the data for the full DB instance. Subsequent snapshots of the same DB instance are incremental, which means that only the data that has changed after your most recent snapshot is saved.

I'd like to know Aurora's snapshot taking is a full backup or a differential.
Does anyone have any information on this?
I've checked the following in the manual, but I can't confirm that Aurora's snapshot works with this text.
https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.Managing.Backups.html

Aurora backs up your cluster volume automatically and retains restore data for the length of the backup retention period. Aurora backups are continuous and incremental so you can quickly restore to any point within the backup retention period.

And, I've checked the AWS re:Invent 2019 materials below. I thought take a full image snapshot of in each segment(per 10GB protection groups), does this right?
https://youtu.be/Ul-j5fKfv2k?t=1095

AWS re:Invent 2019: [REPEAT 1] Deep dive on Amazon Aurora with PostgreSQL compatibility (DAT328-R1)

A: AWS works always on incremental snapshots.. Even if you take EBS volume snapshot.. it will be incremental.
Here is the link to aws document. Please search for word incremental on this page
https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.Managing.Backups.html

A: Deepak is correct, look what AWS says in the documentation
Backups

Aurora backs up your cluster volume automatically and retains restore
  data for the length of the backup retention period. Aurora backups
  are continuous and incremental so you can quickly restore to any
  point within the backup retention period. No performance impact or
  interruption of database service occurs as backup data is being
  written. You can specify a backup retention period, from 1 to 35 days,
  when you create or modify a DB cluster.
If you want to retain a backup beyond the backup retention period, you
  can also take a snapshot of the data in your cluster volume. Because
  Aurora retains incremental restore data for the entire backup
  retention period, you only need to create a snapshot for data that you
  want to retain beyond the backup retention period. You can create a
  new DB cluster from the snapshot.
Note For Amazon Aurora DB clusters, the default backup retention
  period is one day regardless of how the DB cluster is created.
You cannot disable automated backups on Aurora. The backup retention
  period for Aurora is managed by the DB cluster.
Your costs for backup storage depend upon the amount of Aurora backup
  and snapshot data you keep and how long you keep it. For information
  about the storage associated with Aurora backups and snapshots, see
  Understanding Aurora Backup Storage Usage. For pricing information
  about Aurora backup storage, see Amazon RDS for Aurora Pricing. After
  the Aurora cluster associated with a snapshot is deleted, storing that
  snapshot incurs the standard backup storage charges for Aurora.

A: Aurora manual snapshots are technically incremental (only technically). That is why they can be generated so quickly. BUT, they are billed as "full backups".
So if you snapshot your database everyday for 30 days, and the database is on average 10GB large, you will be billed for 30x10GB = 300GB of storage, even if the difference between each snapshots is tiny.
So even if AWS was using about 12GB to store those backups, they will bill you for 300GB.


text:
Q: Generating characters randomly with proper frequencies I'm making a game where characters randomly appear on the screen, and the user needs to make words using those characters.
Currently, I have a string array with A,E,I,O,U each being there 3 times; and all the remaining letters in the alphabet once each.
I randomly pick a position and print that character from the string array.
Sometimes the letters picked are good, and good words can be made, but sometI me they aren't.
What's the best way about going upon this?
I'm developing it using Java for Android.

A: The only possibility to be sure that you get "good letters" every time is if you use a word list, read a random word and shuffle the letters.


text: Q: Is there a way to enable/disable Haptic Feedback based on User approval? My idea is to implement haptic feedback on navigationitems but then I've realised that I have haptics set to off on most of my apps(battery saving reasons) So I was wondering if there is a way to prompt/override system settings rules in android with the flutter framework. E.g. with a toggle like you have for Light/Dark mode


text:
Q: ECharts - set axisPointer positioning to vertical (time type) I am using ECharts to plot a simple line graph that displays data about CPU usage over a period of time. I want the xAxis to only have 6 intervals, which are hourly; between each interval there are values for every half hour. I also want the axisPointer to be vertical, not horizontal.
The problem is, that to do this I need to set the xAxis type to time and by doing this is makes the axisPointer change to horizontal, instead of vertical. In the image below you can see how the axisPointer looks in vertical orientation with the category type.

(source: zips.me)
Here you can see what my chart looks like and what I am trying to explain,

Finally, this is the code used to make my graph.

var myChart = echarts.init(document.getElementById('myChart'));
var option = {
 grid: {
        x: 40,
        x2: 40,
        y: 35,
        y2: 25
    },
    // Add tooltip
    tooltip: {
        trigger: 'axis',
    },

    color: ['#EF5350', '#66BB6A'],

    calculable: false,

    // Horizontal axis
    xAxis: [{
        type: 'time',
    }],

    // Vertical axis
    yAxis: [{
        type: 'value',
        axisLabel: {
            formatter: '{value}%'
        }
    }],

    series: [
        {
            name: 'CPU',
            type: 'line',
            showAllSymbol: true,
   tooltip: {
   trigger: 'axis',
    padding: 15,
    formatter: function(params, ticket, callback){
     var res = 'Today, ' + params[1].getHours() + ':' + params[1].getMinutes() + '

CPU: ' + params[2][1] + '%';
     return res;
    }
   },
            data: (function(){
                var d = [];
                var tme = 10;
                var now = new Date();
                var value;
                while(tme++ < 16){
                    d.push([
                        new Date(2017, 3, 15, tme, 0), Math.floor(Math.random() * 85) + 25
                    ]);
     if(tme !==16){
      for(i = 5; i < 60; i+=5){
       d.push([
        new Date(2017, 3, 15, tme, i), Math.floor(Math.random() * 70) + 30
       ]);
      }
     }
                }
                return d;
            })()
        }
    ]
};

myChart.setOption(option);
#myChart {
  height: 400px;
  width: 100%;
}


text:
Q: Visualforce StandardController Event based on PageLayouts There is a way to create a dynamic visualforce page and render the fields depends of the page layout?. Now I have 2 page layouts with different fields and I won't to create two visualforces. I'm creating this page because visualforce is not visible in the standard edit mode page of my recodrs.
Greats

A: Not sure whether you can get the current layout directly but since the page layout is determined by record type and current user's profile and you can definitely adjust your VF page based on those two values. This is not the perfect solution since once you changed your page layout assignment you will have to change your code but will solve your issue. And the maintenance shouldn't be too bad though.


text:
Q: How do I write a lattice graph (say a square lattice) in boost C++ library? Most examples in the boost-library shows me how to create a graph in boost by adding vertices and edges one by one.
If I have to create a boost graph representing a general lattice (or say a square lattice with periodic boundary conditions), how do I go about doing that ?
How do I make an edge between vertices in a for loop ?


text:
Q: Object of ArrayLists, how to add/remove them from the object? public class MapData {

    ArrayList<String> Redsp = new ArrayList<String>();
    ArrayList<String> Bluesp = new ArrayList<String>();
    ArrayList<String> Playersp = new ArrayList<String>();

    public MapData(ArrayList<String> redsp, ArrayList<String> bluesp, ArrayList<String> playersp) {
        Redsp = redsp;
        Bluesp = bluesp;
        Playersp = playersp;
    }
}

How do I make a object of MapData, and add/remove items to/from the object?
I would like to add like 6 items to bluesp and redsp, and 20 to playersp.
MapData TEST = new MapData(null,null,null);
TEST.??

A: I would create some more methods to MapData
For example to add to Bluesp
public void addToBlueSp(String string) {
    Bluesp.add(string);
}

Also I would use camelCase as this is the standard thing to do in Java.
I would probably recommend creating the ArrayLists inside the ctor too as there is little point passing them into an object and then using that object to add/remove items from them. If you have the ArrayList you could add them outside of this object. But that is a design thing...

A: Use add() and remove() methods
- You can opt for creating the adding and removing methods Or make all the ArrayList as static
Eg:
public void addToRedSp(String string) {

    Redsp.add(string);

}

public void remToRedSp(String string) {

    Redsp.remove(string);

}

MapData TEST = new MapData(null,null,null);

    // To add

    test.addToRedSp("Vivek");

    // To remove

    test.remToRedSp(0);   // or  MapData.Redsp.remove("Vivek");

- ArrayList as static
public static ArrayList<String> Redsp = new ArrayList<String>();
public static ArrayList<String> Bluesp = new ArrayList<String>();
public static ArrayList<String> Playersp = new ArrayList<String>();

MapData TEST = new MapData(null,null,null);

// To add

MapData.Redsp.add("Vivek");

// To remove

MapData.Redsp.remove(0);   // or  MapData.Redsp.remove("Vivek");

A: The easiest way is to provide getters for the three collections and then manipulate them the ordinary way. Such manipulations will take effect on the member fields:
public class MapData {

    ArrayList<String> Redsp = new ArrayList<String>();
    ArrayList<String> Bluesp = new ArrayList<String>();
    ArrayList<String> Playersp = new ArrayList<String>();

    public MapData(ArrayList<String> redsp, ArrayList<String> bluesp, ArrayList<String> playersp) {
        Redsp = redsp;
        Bluesp = bluesp;
        Playersp = playersp;
    }

    public ArrayList<String> getRedsp();
}

And then you do:
MapData TEST = new MapData(null,null,null);
TEST.getRedsp().add("Text1");
TEST.getRedsp().add("Text2");

and so on.
However, take care: you construct not with empty lists, but with null and my code will trigger NPE. Consider setting the default values to empty lists.

A: You can either add getter and setter methods for the Lists to MapData and add new elements like this:
TEST.getRedsp().add("hello");

with
public ArrayList<String> getRedsp()
{
    if(Redsp == null)
        Redsp = new ArrayList<String>();

    return Redsp;
}

or you can introduce an add method for each list to MapData:
TEST.addToRedsp("hello");

with
public boolean addToRedsp(String value)
{
    if(Redsp == null)
        Redsp = new ArrayList<String>();

    return Redsp.add(value)
}

Proceed similarly for the delete case.
By the way: Have a look at variable naming conventions.


text:
Q: SOAP message is empty when catching MessageLoggingTraceRecords with CustomTraceListener I want to write CustomTraceListener which writes all data to SQL Server DB.
Here's the stub for it:
public class SqlTraceListener : TraceListener
{
    public SqlTraceListener()
        : base()
    { }

    public SqlTraceListener(String name)
        : base(name)
    { }

    protected override string[] GetSupportedAttributes()
    {
        List<string> attributes = new List<string>();
        attributes.Add("connectionString");
        attributes.Add("actionFilter");
        attributes.Add("hostFilter");
        return base.GetSupportedAttributes();
    }

    public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data)
    {  }//Other empty methods...

}

In overridden method TraceData I want to catch SOAP messages sent to my WCF service. But when I check what is in "data" parameter I get this: (sorry for posting xml as pictures - it seems SO editor doesn't allow some xml keywords in posts):

But according to standard XmlWriterTraceListener I should get this:

How to configure TraceListener not to eliminate SOAP messages?
My config is here:
  <system.diagnostics>
<sources>
  <source name="System.ServiceModel.MessageLogging">
    <listeners>
      <add name="xml"/>
      <add name="sql"/>
    </listeners>
  </source>
</sources>
<sharedListeners>
  <add initializeData="C:\logs\StockPriceService.svclog" type="System.Diagnostics.XmlWriterTraceListener" name="xml"/>
  <add type="SqlTraceListener.SqlTraceListener, SqlTraceListener" name="sql"/>
</sharedListeners>
<trace autoflush="true"/>

A: Is there any reason you're not using the out of the box database trace listener? See: Enterprise Library Database Trace Listener?.


text:
Q: How to refactor huge if-statement chain with multiple math expression I have a snippet of perfectly running code but it's ugly and clunky, I'm looking for a more efficiently compressed if-statement for it
//my code

function func_tion() {
  let someval_1 = this.x;
  let someval_2 = this.y;

  let val_A=//dynamic integer
  let val_B=//dynamic integer

  let loc_x =//dynamic integer
  let loc_y =//dynamic integer

  if (val_A - loc_x <= 5 && val_A - loc_x >= -5 || loc_x - val_A <= 5 && loc_x - val_A >= -5) {

    if (val_B - loc_y <= 5 && val_B - loc_y >= -5 || loc_y - val_B <= 5 && loc_y - val_B >= -5) {

      if (val_A > loc_x && val_A - loc_x <= 5) { this.x = this.x - 1 };
      if (loc_x > val_A && loc_x - val_A <= 5) { this.x = this.x + 1 };
      if (loc_y > val_B && loc_y - val_B <= 5) { this.y = this.y + 1 };
      if (val_B > loc_y && val_B - loc_y <= 5) { this.y = this.y - 1 };

      if (val_A === loc_x && val_B === loc_y) { console.log("match") };

    } else { this.y = this.y + 1; this.x = this.x + 1; };
  } else { this.x = this.x + 1; this.y = this.y + 1 };
};


text:
Q: JavaFx Binding spinner to the product of fixedValue time theValue of another spinner Binding spinner to the product of fixedValue * theValue of another spinner
I have a Label witch calculate the total from a tableView let's call it
Label totalHt witch it bounded to the sum of table's observable list items total;
another is tvaSpinner witch is editable by user to enter a TVA (10%) Value.
and the last one is
Label totalWithTVA witch needs to be bounded to the product of:
 totalHt * (tvaSpinner.valueProperty()/100) .

Here is an example of what i want to do:
public class BindingSpinnerExample {
@FXML
Label totalHt;
@FXML
Spinner<Double> taxSpinner;
@FXML
Label totalWithTVA;

taxSpinner.setEditable(true);

i want to bound totalWithTVA to:
totalWithTVA = totalHt * (taxSpinner.valueProperty() / 100)

but i don't know how to do this biding
    }

A: This gets a bit ugly. Your Spinner is (presumably) a Spinner<Double>, so it has a ReadOnlyObjectProperty<Double> valueProperty(). The arithmetic computation methods multiply(), divide(), etc are defined for ReadOnlyDoubleProperty, not for ReadOnlyObjectProperty<Double>, so you need to convert the properties into ReadOnlyDoubleProperty. There is a static ReadOnlyDoubleProperty.readOnlyDoubleProperty(ReadOnlyObjectProperty<Double>) method that can do this conversion for you.
So you need to do something like
DoubleBinding total = totalHtProperty.multiply(ReadOnlyDoubleProperty
    .readOnlyDoubleProperty(taxSpinner.valueProperty()).divide(100));

and then of course
totalWithTVA.textProperty().bind(total.asString());

where totalHtProperty is some kind of DoubleExpression with the value displayed in the totalHt label (I assume you are calculating this somewhere).
Here's a SSCCE:
import javafx.application.Application;
import javafx.beans.binding.DoubleBinding;
import javafx.beans.property.ReadOnlyDoubleProperty;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.Spinner;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class BoundSpinners extends Application {

    @Override
    public void start(Stage primaryStage) {
        Spinner<Double> taxSpinner = new Spinner<>(0.0, 100.0, 6.0, 0.5);
        Spinner<Double> priceSpinner = new Spinner<>(0, Double.MAX_VALUE, 0, 10);

        DoubleBinding taxAmount =
                ReadOnlyDoubleProperty.readOnlyDoubleProperty(priceSpinner.valueProperty())
                    .multiply(ReadOnlyDoubleProperty.readOnlyDoubleProperty(taxSpinner.valueProperty()).divide(100));

        Label taxLabel = new Label();
        taxLabel.textProperty().bind(taxAmount.asString("$%.2f"));

        GridPane root = new GridPane();
        root.addRow(0, new Label("Price:"), priceSpinner);
        root.addRow(1, new Label("Tax rate:"), taxSpinner);
        root.addRow(2, new Label("Tax due:"), taxLabel);

        root.setAlignment(Pos.CENTER);

        Scene scene = new Scene(root, 400, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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


text:
Q: Clickhouse Dictionaries: why CREATE DICTIONARY needs a database? The new CREATE DICTIONARY idiom in ClickHouse will create the dictionary inside a database:
CREATE DICTIONARY [IF NOT EXISTS] [db.]dictionary_name [ON CLUSTER cluster]

Dictionaries created by XML file are created as empty-string database:
<dictionaries>
  <dictionary>
  <name>rates</name>
  <source>
  ...
</dictionaries>

and they generate an entry on system.dictionaries like this:
:) select * from system.dictionaries \G
...
Row 4:
──────
database:
name:                        rates

which is empty-string database, that is understood as a global dictionary that can be referred to without a database prefix.
However, with the CREATE DICTIONARY SQL idiom, if db is not specified, the DICTIONARY is created in the default database, no as a global dictionary:
:) CREATE DICTIONARY IF NOT EXISTS rates (...)

:) select * from system.dictionaries \G

Row 2:
──────
database:                    default
name:                        rates

Question: Is there a way to create a global dictionary via SQL idiom?

A: DDL dictionary cannot reside in the global scope because it does not exist in terms of DDL.
As I understood, your problem is a backward incompatibility xml-based dictionary and DDL one, so the once way to fix it is to add the database-prefix (for example, if it defines in table schema need to apply ALTER TABLE MODIFY COLUMN-statement).
To make migration painlessly from xml- to DDL-based dictionary need to temporarily host both types of dictionaries (xml and DDL) and switched all consumers one by one to DDL dictionaries.

DDL dictionaries are much more maintainable and flexible than xml-based ones, because:

*

*easy to manage them (add, remove, etc) without touching xml-files

*ON CLUSTER-clause allows doing some actions on all the servers of a specified cluster

*manage access privileges

*starting from v20.4.2.9, 2020-05-12 dictionary can be efficiently used in JOIN-clause instead of dictGet (see Altinity: Clickhouse Dictionaries Reloaded)

*work with it as ordinal tables


text:
Q: Shopify: redirect sharing links i use S Loyalty. I followed all the instructions for setting up but faced the problem of redirecting
link will be  http://"YOUR STORE DOMAIN"/#!sharing/
but when I try to link - i have http://"YOUR STORE DOMAIN"/#/!sharing/
(added '/')
and nothing happens
Maybe someone encountered this problem?

A: i use angular.js -> need to add
$locationProvider.hashPrefix('!sharing');


text:
Q: CSS Styles in ASCX are not being Rendered I have a Visual WebPart being used on a self-hosted SharePoint 2013 stack.
Problem is that in the WebPart design file, I have a Style tag
<asp:Panel ID="pnlError" Visible="false" runat="server">
</asp:Panel>
<asp:Panel ID="pnlView" Visible="true" runat="server">
    <asp:Panel ID="pnlViewResults" runat="server">

Test Text

    </asp:Panel>
</asp:Panel>

WebPart.ascx.cs:
protected void GetResults()
{
    AddTrace("Creating Connection");
    using (var conn = new SqlConnection(DatabaseConnection))
    {
        try
        {
            AddTrace("Opening Connection");
            conn.Open();

            AddTrace("Creating SQL Command Object");
            var cmd = new SqlCommand()
            {
                Connection = conn,
                CommandType = CommandType.StoredProcedure,
                CommandText = "Poll.p_Get_Results"  // Produces multiple Record-Sets
            };
            AddTrace("Executing SQL Command as Reader");
            var rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                //Question Result Set
                ResultQuestionText.InnerHtml = rdr["question"].ToString();
            }
            AddTrace("Getting Next Result Set");
            rdr.NextResult();

            HtmlGenericControl dt; HtmlGenericControl dd; HtmlGenericControl bar; HtmlGenericControl txt;
            ResultAnswerList.Controls.Clear();
            AddTrace("Populating List and associated Percentages");
            while (rdr.Read())
            {
                //Answer Result Set
                dt = new HtmlGenericControl("dt");
                dt.InnerText = rdr["answer"].ToString();
                ResultAnswerList.Controls.Add(dt);

                dd = new HtmlGenericControl("dd");
                dd.Style.Add("width", "100%");

                if (Convert.ToDecimal(rdr["perc"]) > 0)
                {
                    bar = new HtmlGenericControl("div");
                    bar.Attributes["class"] = "pollpart-bar";
                    bar.Style.Add("width", string.Format("{0:F1}%", rdr["perc"]));
                    if (Convert.ToDecimal(rdr["perc"]) >= 10)
                    {
                        bar.InnerText = string.Format("{0:F1}%", rdr["perc"]);
                    }
                    dd.Controls.Add(bar);
                }

                if (Convert.ToDecimal(rdr["perc"]) < 10)
                {
                    txt = new HtmlGenericControl("span");
                    txt.InnerText = string.Format("{0:F1}%", rdr["perc"]);
                    dd.Controls.Add(txt);
                }

                ResultAnswerList.Controls.Add(dd);
            }

            pnlViewPoll.Visible = false;
            pnlViewResults.Visible = true;
        }
        catch (Exception ex)
        {
            ShowTrace(ex);
        }
    }
}

The problem is that the


text:
Q: How to change the default border color of fbox? I have a lot of figures inside an fbox. Unfortunately the default black is too strong for my advisor and I need to change the default border color to something more soft.
I've done my research and so far all other answers suggest do solve the problem by not using fbox and switching to other packages. That's something I'd like to avoid, unless absolutely necessary.
Surely there is an option for something so basic in the fbox package itself?

A: Without setting the background color, one can save the current text color and apply it when the text of the \fbox is typeset, changing color for typesetting the rules.
\documentclass{article}
\usepackage{xcolor}
\usepackage{etoolbox}

\makeatletter
\let\cfbox\fbox
\let\c@frameb@x\@frameb@x
\pretocmd{\cfbox}
  {\leavevmode\begingroup\colorlet{currentcolor}{.}\color{red}}
  {}{}
\patchcmd\cfbox{\@frameb@x}{\c@frameb@x}{}{}
\patchcmd{\c@frameb@x}
  {\box\@tempboxa}
  {\color{currentcolor}\box\@tempboxa}
  {}{}
\apptocmd{\c@frameb@x}{\endgroup}{}{}
\makeatother

\begin{document}

text \cfbox{text} text

\fcolorbox{green}{blue}{text \cfbox{text} text}

\end{document}

I'd prefer a different command to redefining \fbox. If you instead want to use \fbox, just remove the \let\cfbox\fbox line and change \cfbox into \fbox in the remaining places.

A: You can try this. It will also set the background to white, normally this should be not a problem.
\documentclass{article}

\usepackage{xcolor}

\renewcommand\fbox{\fcolorbox{red}{white}}
\begin{document}

\fbox{text}

\end{document}


text:
Q: Node.js + request json format I'm working with the spotify web api to build a Node.js app. One of the functions provided by the api allows you to play a specific track/album/playlist through the spotify player, here's the Start/Resume a User's Playback documentation.
However, when I send the put request, the song I chose doesn't start, it only continues playing the current song. I was hoping that it was my bad formatting of the json string to send, and not spotify's api not working?
Here's my code:
request({
    method: 'PUT',
    uri: 'https://api.spotify.com/v1/me/player/play',
    headers:{
        Authorization: 'Bearer ' + access_token
    },
    data:{
        "context_uri": "spotify:user:spotify:playlist:37i9dQZF1DX0s5kDXi1oC5",
        "offset": {
            "position": 0
        }
    },
    json: true
}, function (error, response, body) {
    err = error;
});

I don't get any errors, as the api is doing it's job, I guess it just doesn't get the "context_uri" that I'm trying to give to it. I've also tried multiple different links for the context_uri that are valid.
So if you've looked at the documentation, I guess my question is should the context_uri be inside the "data" array, is that why it's not being seen?
Really appreciate the help, been trying to figure this out for days.

A: To confirm:
'context_uri': 'spotify:user:spotify:playlist:37i9dQZF1DX0s5kDXi1oC5',
'offset': {
    'position': 0
}

works as expected for me. It begins playing Justin Timberlake - My Love.
So the problem is elsewhere. Things to consider:

*

*The 'active' device hasn't recently been active / playing?

*You're not catching an exception somewhere else?


text:
Q: Why is my active passband filter (LP and HP Butterworth filters in series) not working?
I did each filter alone and they work fine, but when they are made together to form a bandpass filter with the same components I used they don't work.
The output on the oscilloscope is a very weak signal that is similar to the output signal when the circuit is not fed with electricity (I guess it's negligible environment noise) while the input is a sine function from the function generator. Am I missing a middle stage or something? I tried all frequencies from 1Hz to 3MHz and nothing changes, even changing the amplitude of the input has no effects.

A: It seems you've switched the corners you intended to implement.
What you're looking to build is a bandpass filter between 49 - 497 Hz. In order to accomplish this, first you need a high pass filter at 49 Hz, which will eliminate all low frequencies. Then the output of that stage needs to be filtered with a low pass filter with a 497 Hz corner.
So, fix the corner frequencies and you should be in good shape.

A: Supplemental info.
As you now know, the sequence of breakpoints makes a difference in attenuation , but not the sequence of cascading the same stages.  These are different filters.
See the difference is 40 dB in this case and a slight shift in the 0 deg phase.


text:
Q: AWS amplify Angular custom authenticator component I am following the guide on this page: https://aws-amplify.github.io/docs/js/angular to build a sign-in page for my website.
After several hours of setting up, I got a result like this:

Now I need to remove the Create account button, how can I do that?
I've tried to search a lot on the internet but all of the tutorials are for React not Angular.

A: For Angular 8 and lower, hide it with css:
.amplify-form-signup {
  display: none;
}

For Angular 9 and up, add hide-sign-up to your sign-in slot:
<amplify-authenticator>
  <amplify-sign-in slot="sign-in" hide-sign-up></amplify-sign-in>
  <app-myapp></app-myapp>
</amplify-authenticator>

A: just in case you haven't figured it out yet:
you can override the angular component. So in your case you'd probably want to create your own
  component
and create one that does not have a Create Account link
I think this is the most detailed part I could find on the amplify page:
Check here


text:
Q: Netbeans is not recognizing a JAR library I have a weird problem: Netbeans is not recognizing a JAR file added as a library.
I used to have classes in the default package and I was able to access Thing.jar by calling new Thing(); in the Main class. After I created some packages and reorganized my classes, Netbeans started complaining over that line of code: "cannot find symbol: Class Thing". I tried removing/adding the jar library. It doesn't complain anything and I can see the jar file under projects/libraries. Google also didn't turn up any magic tricks regarding how to add JAR files. I don't understand why this worked inside the default package, but doesn't work in another package.

A: Have you imported the classes at the beginning of your file.
If a class is not in the same package java requires an import, even when the jar file is placed in the Libraries.

A: You shouldn't use the default package if you want the class to be available outside the current jar. It is not possible to import from the default package.
See How to import a class from default package


text:
Q: $|e^{inr}-1| \geq C>0$, $\forall n \in \mathbb{Z}$ I'm looking for an optimal assumption on $r$ such that $|e^{2inr}-1| \geq C>0$, for any $n$.
It is clear that $$|e^{2inr}-1|^2=2(1-\cos(2nr)).$$
If $r$ is irrational, $1-\cos(2nr)>0$ but it is not clear whether it is uniformly bounded from below.
Any help?.
Thank you in advance.


text:
Q: A tool to uncompress Windows LZNT1 format I have some binary data that is compressed with Microsoft's LZNT1 compression.
Apparently it can be decompressed by calling RtlDecompressBuffer ntdll API.
But is there an easier way to decompress it, without having to write an app?

A: Couldn't find anything so ended up writing one myself (link).


text:
Q: Good Anomaly Detection Model for a Complicated Data I am working on data and want to produce an Anomaly Detection model for this data. The data contains only three features: Latitude, Longitude and Speed. I normalized it and then applied t-SNE then normalized again. There is no labeled or target data. So, it should be an unsupervised anomaly detection.
I cannot share the data since it is private. But, it seems like this:

There are some abnormal values in the data such as abnormal values:

Here's the final shape of the data:

As you can see, the data is a bit complicated. When I searched for abnormal instances manually (by looking at feature values), I observed that the instances inside the red circle (in the below image) should be detected as anomalies.
The instances inside the red region should be abnormal:

I used OneClassSVM to detect anomalies. Here are the parameters;
nu = 0.02
kernel = "rbf"
gamma = 0.1
degree = 3
verbose = False
random_state = rng

And the model;
# fit the model
clf = svm.OneClassSVM(nu=nu, kernel=kernel, gamma=gamma, verbose=verbose, random_state=random_state)
clf.fit(data_scaled)
y_pred_train = clf.predict(data_scaled)
n_error_train = y_pred_train[y_pred_train == -1].size

Here is what I obtained at the end:

Here is the detected anomalies of OneClassSVM and red instances were detected as anomalies:

So, as you can see, the model predicted many instances as anomalies, but in reality, most of these instances should be normal.
I tried different parameter values for nu, gamma and degree. However, I could not find a suitable decision line to detect only real anomalies.

*

*What is wrong with my model? Should I try a different anomaly detection algorithm?

*Is not my data appropriate for anomaly detection?

A: It appears some of the anomalies reported by One-class SVM are global but not local anomalies.  You might want to try Local Outlier Factor.
It will consider the local structure of your data.  So the original outliers on the left side which are part of small clusters should not be as anomalous.
http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.LocalOutlierFactor.html
# fit the model
clf = LocalOutlierFactor()
y_pred_train = clf.fit_predict(data_scaled)
n_error_train = y_pred_train[y_pred_train == -1].size

I would also try Isolation Forest and try tweaking the contamination ratio.  You don't have to scale your data for IF and I suspect you might not want to here.
http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.IsolationForest.html#sklearn.ensemble.IsolationForest.predict
# fit the model
clf = IsolationForest(contamination=0.01)
clf.fit(data)
y_pred_train = clf.predict(data)
n_error_train = y_pred_train[y_pred_train == -1].size