text:
Q: Create multiple chart.js charts from jsonfile data I have created a json file using python which is a list of lists.  Each sublist has data for a chart.js chart i.e.chartObject[0] has chartObject[0][0] and chartObject[0][1] for x and y axis.
This is the json containing the list and sublist.
The code below creates one chart but I would like to loop though all entries and create charts for each sublist (multiple instances of the chart).
How do I loop through the json file listed in the code below and create multiple chart.js charts? i.e. a chart for chartObject[0], chartObject[1] etc.
<script>

    const requestURL =
  "http://secstat.info.s3.eu-west-2.amazonaws.com/testthechartdata001.json";
const request = new XMLHttpRequest();
request.open("GET", requestURL);
request.send();

request.onreadystatechange = function() {
  if (request.readyState === 4) {
    doWithResponse(request.response);
  }
};

function doWithResponse(chart) {
  var chartObject = JSON.parse(chart)
  var ctx = document.getElementById("myChart");
  var myChart = new Chart(ctx, {
    type: "horizontalBar",
    data: {
      labels: [...chartObject[0]],
      datasets: [
        {
          label: "Frequency",
          data: [...chartObject[1]],
          backgroundColor: [
            "rgba(255, 99, 132, 0.2)",
            "rgba(54, 162, 235, 0.2)",
            "rgba(255, 99, 132, 0.2)",
            "rgba(54, 162, 235, 0.2)",
            "rgba(255, 99, 132, 0.2)",
            "rgba(54, 162, 235, 0.2)",
            "rgba(255, 99, 132, 0.2)",
            "rgba(54, 162, 235, 0.2)",
            "rgba(255, 99, 132, 0.2)",
            "rgba(54, 162, 235, 0.2)"
          ],
          borderColor: [
            "rgba(255, 99, 132, 1)",
            "rgba(54, 162, 235, 1)",
            "rgba(255, 99, 132, 1)",
            "rgba(54, 162, 235, 1)",
            "rgba(255, 99, 132, 1)",
            "rgba(54, 162, 235, 1)",
            "rgba(255, 99, 132, 1)",
            "rgba(54, 162, 235, 1)",
            "rgba(255, 99, 132, 1)",
            "rgba(54, 162, 235, 1)"
          ],
          borderWidth: 2
        }
      ]
    },
    options: {
        title: {
                display: true,
                text: 'Threat Count'},
    legend: {
                    display: false
                }     ,
      scales: {
        yAxes: [
          {
            ticks: {
              beginAtZero: true
            }
          }
        ]
    }
    }
  });
}
    </script>

A: You can do it this way :
 <script>
   const requestURL =
   "http://secstat.info.s3.eu-west-2.amazonaws.com/testthechartdata001.json";
 const request = new XMLHttpRequest();
 request.open("GET", requestURL);
 request.send();

 request.onreadystatechange = function() {
   if (request.readyState === 4) {
     doWithResponse(request.response);

   }
 };

 function doWithResponse(chart) {
   const chartObject = JSON.parse(chart)
   var canvasArray = [];
   for (let i = 0; i < chartObject.length / 2; i++) {
     document.getElementById('myChart').innerHTML += "<canvas id=c" + i + "></canvas>";
     var ctxPrep = "c" + i;
     canvasArray.push(ctxPrep)
   }
   var el = 0;
   for (let i = 1; i <= chartObject.length - 1; i = i + 2) {
     var ctx = document.getElementById(`${canvasArray[el]}`).getContext("2d");
     el++
     var myNewChart = new Chart(ctx, {
       type: "horizontalBar",
       data: {
         labels: chartObject[i - 1].map((x, index) => chartObject[i - 1][index]),
         datasets: [{
           label: "Frequency",
           data: chartObject[i].map((x, index) => chartObject[i][index]),
           backgroundColor: [
             "rgba(255, 99, 132, 0.2)",
             "rgba(54, 162, 235, 0.2)",
             "rgba(255, 99, 132, 0.2)",
             "rgba(54, 162, 235, 0.2)",
             "rgba(255, 99, 132, 0.2)",
             "rgba(54, 162, 235, 0.2)",
             "rgba(255, 99, 132, 0.2)",
             "rgba(54, 162, 235, 0.2)",
             "rgba(255, 99, 132, 0.2)",
             "rgba(54, 162, 235, 0.2)"
           ],
           borderColor: [
             "rgba(255, 99, 132, 1)",
             "rgba(54, 162, 235, 1)",
             "rgba(255, 99, 132, 1)",
             "rgba(54, 162, 235, 1)",
             "rgba(255, 99, 132, 1)",
             "rgba(54, 162, 235, 1)",
             "rgba(255, 99, 132, 1)",
             "rgba(54, 162, 235, 1)",
             "rgba(255, 99, 132, 1)",
             "rgba(54, 162, 235, 1)"
           ],
           borderWidth: 2
         }]
       },
       options: {
         title: {
           display: true,
           text: 'Threat Count'
         },
         legend: {
           display: false
         },
         scales: {
           yAxes: [{
             ticks: {
               beginAtZero: true
             }
           }]
         }
       }
     });
   }
   }
 </script>


text:
Q: Is there a way to persist HSQLDB data? We have all of our unit tests written so that they create and populate tables in HSQL. I want the developers who use this to be able to write queries against this HSQL DB ( 1) by writing queries they can better understand the data model and the ones not as familiar with SQL can play with the data before writing the runtime statements and 2) since they don't have access to the test DB/security reasons). Is there a way to persist the results of the test data so that it may be examine and analyzed with a an sql client?
Right now I am jury rigging it by switching the data source to a different DB (like DB2/mysql, then connecting to that DB on my machine so I can play with persistant data), however it would be easier for me if HSQL supports persisting this than to explain how to do this to every new developer.
Just to be clear, I need an SQL client to interact with persistent data, so debugging and checking memory won't be clean. This has more to do with initial development and not debugging/maintenance/testing.

A: If you use an HSQLDB Server instance for your tests, the data will survive the test run.
If the server uses a jdbc:hsqldb:mem:aname (all-in-memory) url for its database, then the data will be available while the server is running. Alternatively the server can use a jdbc:hsqldb:file:filepath url and the data is persisted to files.
The latest HSQLDB docs explain the different options. Most of the observations also apply to older (1.8.x) versions. However, the latest version 2.0.1 supports starting a server and creating databases dynamically upon the first connection, which can simplify testing a lot.
http://hsqldb.org/doc/2.0/guide/deployment-chapt.html#N13C3D

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pyspark DataFrame Returns Inconsistent Result I am running some codes on Databricks platform and encountered a super werid problem that the results returned by the same dataframe were inconsistent. Here comes my code:
Firstly, I want to show the records satisfying a specefic criteria:

As highlighted in the above figure, the record with "unique_key" 26486 matches my criteria. And now I want to query this record inversely by its "unique_key":

The super werid thing happens, what was returned by the same dataframe "sdf" was inconsistent with the previous result: the highlighted contents were different except for the "unique_key".
I have been struggling in this problem for a while and don't know if it is a bug of pyspark. Anyone has ideas on that? THX.


text:
Q: How to pass JobParameters to myBatisPagingItemReader without using @StepScope I am using spring batch restart functionality so that it reads from the last failed point forward. My restart works fine as long as I don't use @StepScope annotation to my myBatisPagingItemReader bean method.
I have to use @StepScope so that i can do late binding to get the jobParameters using the input parameter to my myBatisPagingItemReader bean method
    @Value("#{JobParameters['run-date']}"))
If I use @StepScope the restart does not work.
I tried adding listener new JobParameterExecutionContextCopyListener() to copy JobParameters to ExecutionContext.
But how will i get access to ExecutionContext inside myBatisPagingItemReader as I don't have ItemReader's open methods?
Not sure how i can get access to jobParameters when running myBatisPagingItemReader without using @StepScope? Please any inputs.
Also not sure if my understanding on spring-batch restart is correct on how it works when new instance (stateful) is used when using @StepScope.
@Configuration
@EnableBatchProcessing
public class BatchConfig {
    @Bean
    public Step step1(StepBuilderFactory stepBuilderFactory,
        ItemReader<Model> myBatisPagingItemReader,
        ItemProcessor<Model, Model> itemProcessor,
        ItemWriter<Model> itemWriter) {

        return stepBuilderFactory.get("data-load")
            .<Model, Model>chunk(10)
            .reader(myBatisPagingItemReader)
            .processor(itemProcessor)
            .writer(itemWriter)
            .listener(itemReadListener())
             .listener(new JobParameterExecutionContextCopyListener())
            .build();
   }

   @Bean
    public Job job(JobBuilderFactory jobBuilderFactory, @Qualifier("step1")
               Step step1) {
           return jobBuilderFactory.get("load-job")
            .incrementer(new RunIdIncrementer())
            .start(step1)
            .listener(jobExecutionListener())
            .build();
      }
}

@Component
public class BatchInputReader {

    @Bean
    //@StepScope
    public ItemReader<Model> myBatisPagingItemReader(
             SqlSessionFactory sqlSessionFactory) {
         MyBatisPagingItemReader<Model> reader = new
         MyBatisPagingItemReader<>();
         Map<String, Object> parameterValues = new HashMap<>();
     // populate parameterValues  from jobParameters ??
         reader.setSqlSessionFactory(sqlSessionFactory);
         reader.setParameterValues(parameterValues);
         reader.setQueryId("query");
         return reader;
    }
 }

A: You are declaring a Spring Bean (myBatisPagingItemReader) in a Class annotated with @Component (BatchInputReader). This is not correct.
What you need to do is to declare the mybatis reader as a bean in your configuration class BatchConfig. Once this is done and the bean is annotated with @StepScope, you can pass pass job parameters as follows:
@Configuration
@EnableBatchProcessing
public class BatchConfig {

    @Bean
    @StepScope
    public ItemReader<Model> myBatisPagingItemReader(
            SqlSessionFactory sqlSessionFactory,
            @Value("#{jobParameters['param1']}") String param1,
            @Value("#{jobParameters['param2']}") String param2) {
        MyBatisPagingItemReader<Model> reader = new
                MyBatisPagingItemReader<>();
        Map<String, Object> parameterValues = new HashMap<>();
        // populate parameterValues  from jobParameters ?? => Those can be now accessed from method parameters
        reader.setSqlSessionFactory(sqlSessionFactory);
        reader.setParameterValues(parameterValues);
        reader.setQueryId("query");
        return reader;
    }

    @Bean
    public Step step1(StepBuilderFactory stepBuilderFactory,
                      ItemReader<Model> myBatisPagingItemReader,
                      ItemProcessor<Model, Model> itemProcessor,
                      ItemWriter<Model> itemWriter) {

        return stepBuilderFactory.get("data-load")
                .<Model, Model>chunk(10)
                .reader(myBatisPagingItemReader)
                .processor(itemProcessor)
                .writer(itemWriter)
                .listener(itemReadListener())
                .listener(new JobParameterExecutionContextCopyListener())
                .build();
    }

    @Bean
    public Job job(JobBuilderFactory jobBuilderFactory, @Qualifier("step1")
            Step step1) {
        return jobBuilderFactory.get("load-job")
                .incrementer(new RunIdIncrementer())
                .start(step1)
                .listener(jobExecutionListener())
                .build();
    }
}

More details about this in the Late Binding of Job and Step Attributes section. BatchInputReader will be left empty and is not needed anymore. Less is more! :-)
Hope this helps.

A: Adding to my question. I have added myBatisPagingItemReader() as suggested to my configuration annoated class.
Restart example when I use @Stepscope annotaton to myBatisPagingItemReader(), the reader is fetching 5 records and I have chunk size(commit-interval) set to 3.
Job Instance - 01 - Job Parameter - 01/02/2019.
chunk-1:
- process record-1
- process record-2
- process record-3
writer - writes all 3 records
chunk-1 commit successful
chunk-2:
    process record-4
    process record-5 - Throws and exception
Job completes and set to 'FAILED' status
Now the Job is Restarted again using same Job Parameter.
Job Instance - 01 - Job Parameter - 01/02/2019.
chunk-1:
    process record-1
    process record-2
    process record-3
writer - writes all 3 records
chunk-1 commit successful
chunk-2:
    process record-4
    process record-5 - Throws and exception
Job completes and set to 'FAILED' status
Please note: Here as I am using @Stepscope annotation on myBatisPagingItemReader() bean method, the job creates a new instance , see below log message.
Creating object in scope=step, name=scopedTarget.myBatisPagingItemReader
    Registered destruction callback in scope=step, name=scopedTarget.myBatisPagingItemReader
As it is new instance it start the process from start, instead of starting from chunk-2.
If i don't use Stepscope, it restarts from chunk-2 as the restarted job step sets - MyBatisPagingItemReader.read.count=3.
I would like to use Stepscope to use the late bindings, if i use stepscope, is it possible for my myBatisPagingItemReader to set the read.count from the last failure to get restart working?
Or
If I don't use @Stepscope, is there a way to get job parameters inside myBatisPagingItemReader?


text:
Q: Multiple conclusions(formulas) in one cell Let's say I have a table with the values:

*

*0

*100

*200

*300

In the next coloumn I have data entry cell of 250.
Underneath the 250 I would like a formula that says:

*

*If 250 is less than 100 but more than 0, "A"

*If 250 is less than 200 but more than 100, "B"

*If 250 is less than 300 but more than 200, "C"

Based on that formula, the cell below would automatically be "C"
How do I create that formula?

A: LOOKUP can be used here, i.e.
=LOOKUP(C1,A1:A4,{"A","B","C","Error"})
That returns Error if C1 >= 300, you didn't say what you want in that case......

A: It sounds to me like you are looking for the IF and AND functions. I don't have Excel handy, but try this:
=IF(AND(A1>0;A1<100);"A";IF(AND(A1>100;A1<200);"B";IF(AND(A1>200;A1<300);"C";"")))

The format is =IF(condition;true-value;false-value). In this case, the condition is a call to AND(), and false-value is another (similar) IF statement. I hope I got the number of paranthesises right. Paste the above into a cell other than A1, then adjust the value in A1 and see if it does what you want. If not, adjust the conditions accordingly. Once you get it working the way you want it for one cell, just range-fill the entire range.
Using IF gets unwieldy very quickly if you have long lists of conditions, though. If you find yourself with more than 2-3 levels of IFs, it's probably better to consider the possibility of using VBA instead, which is much easier to structure in a readable fashion.
For some more examples, you may want to consider How to use nested IF statements in Excel with AND, OR, NOT on the Experiments in Finance blog.
I also took a guess that your first bullet point was supposed to be the range 0 to 100, since no number will simultaneously be less than 0 and more than 100.

A: You can use MATCH and CHOOSE pretty efficiently here. Where A1:A4 are the values to compare against and C1 is the data entry cell:
=CHOOSE(MATCH(C1,$A$1:$A$4,1),"A","B","C")


text:
Q: Sharing/Security File/Folder Permissions I'm trying to run an executable (.exe) from LAN without allowing users access to the contents of the LAN folder itself. e.g.
1) User clicks on a link in their email to an executable at a folder path e.g. I:\Folder A\setup.exe
2) On clicking the link, the installer runs
3) If user tries to access the folder i.e. I:\Folder A\, they are disallowed from seeing the contents of the folder by either a prompt or by not showing anything there.
Does anyone know how this could be done. Essentially, I just want to make sure users have execute only permissions for setup.exe. This is for NTFS permissions.

A: If you really want to do this, do the following (assuming that "Authenticated Users" should have rights to execute the SETUP.EXE):

*

*Verify that the folder doesn't name "Authenticated Users" as having any permissions. If it does, remove them (either by removing permission directly set at that folder, or by breaking the inheritance hierarchy and then removing the permissions assigned).

*On the SETUP.EXE file itself, set "Authenticated Users - Read and Execute" permission.
Users will able to execute the file if they know the path of the file, but they will not be able to access the folder.
I predict that your SETUP program will need access to other files in that folder, though, and won't work because the user executing SETUP won't have access to the other files. (Any why are users allowed to install software on their computers, anyway? Are they using their computers day-to-day with 'Administrator' accounts... shame...)

A: I do not think it is possible. If you have to go in folder then execute permission is enough. But to read files read permission is required. In order to run setup.exe, the person must be able to read setup.exe (executable code) which requires read permission on folder.

A: You need to go into the Advanced permissions on setup.exe. Remove all rights for the users/groups (removing inherited perms if necessary), then go into the advanced permissions and add the users/groups with just the permission "Travers folder / execute file".
This allows the users to execute setup.exe, but they could not open it in a e.g. a hex editor and view it's contents.
JR
I had another look at this following Evan's commnents. It turns out that I'm correct (of course :-) but that Evan is also correct; sort of.
Here are the details. I created a folder C:\test and left the ACLs at the defaults. The ACL on the folder doesn't seem to matter. Into this folder I copied a few Windows applets like Paint and Notepad. I also copied a ultrasimple Windows app that I wrote myself. The source for the ultrasimple app is:
#include <windows.h>

int PASCAL WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
  MessageBox(NULL, "Hello world\n", "Hello world\n", 0);

  return 0;
}

which I'm sure you'll agree is pretty simple. Now I edited the permissions on all the files. I disabled inheritance, removed all the permissions and set the ACLs to contain just the one entry granting Everyone the permission "Traverse folder / Execute file".
Now if I drag any of the files into Notepad I immediately get an access denied error. If I try to copy any of the files into another folder I get an access denied error. This shows that read access to the files has been denied.
Now I double click my simple app, and it launches. Just for completeness I copied in another rather bigger app I'm working on, and after setting the permissions this too worked. This is the point I got to when I first posted, and it's why I was confident my answer was correct.
But, when I try to run mspaint.exe or notepad.exe they do not run. Instead I get an access denied error. This is the point where I'm grudgingly inclined to admit Evan may have a point :-)
My interpretation of this is that both Notepad and MSPaint have resources that Windows tries to load when they are started. This requires read access to the file, in order to read the resource, and because read access has been denied the attempt to launch the file fails. Because my app has no resources Windows manages to launch it quite happily. I imagine this would apply to any but the most simple of Windows apps, so although my original posting was technically correct, in practice just setting execute permission will not allow you to run anything useful. You will need read access as well.

A: Another possibility would be to serve it from a hidden share, such as an administrative share.  These are denoted by the $ sign after the share name, and don't appear on the LAN by default.  In other words, you have to know it's there to use it.  Kinda security by obscurity, but it might serve your purpose.

A: Maybe I'm crazy, but couldn't you just remove the "List Folder Contents" right for that folder from their accounts?


text:
Q: OAuth 2.0: Benefits and use cases — why? Could anyone explain what's good about OAuth2 and why we should implement it? I ask because I'm a bit confused about it — here's my current thoughts:
OAuth1 (more precisely HMAC) requests seem logical, easy to understand, easy to develop and really, really secure.
OAuth2, instead, brings authorization requests, access tokens and refresh tokens, and you have to make 3 requests at the very start of a session to get the data you're after. And even then, one of your requests will eventually end up failing when the token expires.
And to get another access token, you use a refresh token that was passed at the same time as the access token. Does that make the access token futile from a security point of view?
Plus, as /r/netsec have showed recently, SSL isn't all entirely secure, so the push to get everything onto TLS/SSL instead of a secure HMAC confuses me.
OAuth are arguing that it's not about 100% safety, but getting it published and finished. That doesn't exactly sound promising from a provider's point of view. I can see what the draft is trying to achieve when it mentions the 6 different flows, but it's just not fitting together in my head.
I think it might be more my struggling to understand it's benefits and reasoning than actually disliking it, so this may be a bit of an unwarranted attack, and sorry if this could seem like a rant.

A: First, as clearly indicated in OAuth authentication
OAuth 2.0 is not an authentication protocol.
Authentication in the context of a user accessing an application tells an application who the current user is and whether or not they're present. A full authentication protocol will probably also tell you a number of attributes about this user, such as a unique identifier, an email address, and what to call them when the application says "Good Morning".
However, OAuth tells the application none of that.
OAuth says absolutely nothing about the user, nor does it say how the user proved their presence or even if they're still there.
As far as an OAuth client is concerned, it asked for a token, got a token, and eventually used that token to access some API. It doesn't know anything about who authorized the application or if there was even a user there at all.
There is a standard for user authentication using OAuth: OpenID Connect, compatible with OAuth2.
The OpenID Connect ID Token is a signed JSON Web Token (JWT) that is given to the client application along side the regular OAuth access token.
The ID Token contains a set of claims about the authentication session, including an identifier for the user (sub), the identifier for the identity provider who issued the token (iss), and the identifier of the client for which this token was created (aud).
In Go, you can look at coreos/dex, an OpenID Connect Identity (OIDC) and OAuth 2.0 Provider with Pluggable Connector.
Answer from this post vonc

A: I would answer this question slightly differently, and I will be very precise and brief, mainly because @Peter T answered it all.
The main gain that I see from this standard is to respect two principles:

*

*Separation of concerns.

*Decoupling authentication from the web application, which usually serves business.

By doing so,

*

*You can implement an alternative to Single SignOn: If you have multiple applications that trust one STS. What I mean, one username for all applications.

*You can enable your web application (The client) to access resources that belong to the user and do not belong to the web application (The client).

*You can mandate the authentication process to a third party that you trust , and never worry about user authenticity validation.

A: Background: I've written client and server stacks for OAuth 1.0a and 2.0.
Both OAuth 1.0a & 2.0 support two-legged authentication, where a server is assured of a user's identity, and three-legged authentication, where a server is assured by a content provider of the user's identity. Three-legged authentication is where authorization requests and access tokens come into play, and it's important to note that OAuth 1 has those, too.
The complex one: three-legged authentication
A main point of the OAuth specs is for a content provider (e.g. Facebook, Twitter, etc.) to assure a server (e.g. a Web app that wishes to talk to the content provider on behalf of the client) that the client has some identity. What three-legged authentication offers is the ability to do that without the client or server ever needing to know the details of that identity (e.g. username and password).
Without (?) getting too deep into the details of OAuth:

*

*The client submits an authorization request to the server, which validates that the client is a legitimate client of its service.

*The server redirects the client to the content provider to request access to its resources.

*The content provider validates the user's identity, and often requests their permission to access the resources.

*The content provider redirects the client back to the server, notifying it of success or failure. This request includes an authorization code on success.

*The server makes an out-of-band request to the content provider and exchanges the authorization code for an access token.

The server can now make requests to the content provider on behalf of the user by passing the access token.
Each exchange (client->server, server->content provider) includes validation of a shared secret, but since OAuth 1 can run over an unencrypted connection, each validation cannot pass the secret over the wire.
That's done, as you've noted, with HMAC. The client uses the secret it shares with the server to sign the arguments for its authorization request. The server takes the arguments, signs them itself with the client's key, and is able to see whether it's a legitimate client (in step 1 above).
This signature requires both the client and the server to agree on the order of the arguments (so they're signing exactly the same string), and one of the main complaints about OAuth 1 is that it requires both the server and clients to sort and sign identically. This is fiddly code and either it's right or you get 401 Unauthorized with little help. This increases the barrier to writing a client.
By requiring the authorization request to run over SSL, OAuth 2.0 removes the need for argument sorting and signing altogether. The client passes its secret to the server, which validates it directly.
The same requirements are present in the server->content provider connection, and since that's SSL that removes one barrier to writing a server that accesses OAuth services.
That makes things a lot easier in steps 1, 2, and 5 above.
So at this point our server has a permanent access token which is a username/password equivalent for the user. It can make requests to the content provider on behalf of the user by passing that access token as part of the request (as a query argument, HTTP header, or POST form data).
If the content service is accessed only over SSL, we're done. If it's available via plain HTTP, we'd like to protect that permanent access token in some way. Anyone sniffing the connection would be able to get access to the user's content forever.
The way that's solved in OAuth 2 is with a refresh token. The refresh token becomes the permanent password equivalent, and it's only ever transmitted over SSL. When the server needs access to the content service, it exchanges the refresh token for a short-lived access token. That way all sniffable HTTP accesses are made with a token that will expire. Google is using a 5 minute expiration on their OAuth 2 APIs.
So aside from the refresh tokens, OAuth 2 simplifies all the communications between the client, server, and content provider. And the refresh tokens only exist to provide security when content is being accessed unencrypted.
Two-legged authentication
Sometimes, though, a server just needs to control access to its own content. Two-legged authentication allows the client to authenticate the user directly with the server.
OAuth 2 standardizes some extensions to OAuth 1 that were in wide use. The one I know best was introduced by Twitter as xAuth. You can see it in OAuth 2 as Resource Owner Password Credentials.
Essentially, if you can trust the client with the user's credentials (username and password), they can exchange those directly with the content provider for an access token. This makes OAuth much more useful on mobile apps--with three-legged authentication, you have to embed an HTTP view in order to handle the authorization process with the content server.
With OAuth 1, this was not part of the official standard, and required the same signing procedure as all the other requests.
I just implemented the server side of OAuth 2 with Resource Owner Password Credentials, and from a client's perspective, getting the access token has become simple: request an access token from the server, passing the client id/secret as an HTTP Authorization header and the user's login/password as form data.
Advantage: Simplicity
So from an implementor's perspective, the main advantages I see in OAuth 2 are in reduced complexity. It doesn't require the request signing procedure, which is not exactly difficult but is certainly fiddly. It greatly reduces the work required to act as a client of a service, which is where (in the modern, mobile world) you most want to minimize pain. The reduced complexity on the server->content provider end makes it more scalable in the datacenter.
And it codifies into the standard some extensions to OAuth 1.0a (like xAuth) that are now in wide use.


text: Q: Some useful tips for/of learning English and any other languages? Should I use "for" or "of" for the sentence in the title? It feels right in both cases. I did some research on the internet but still I am having trouble deciding which one is correct. I would really appreciate some one to help clear things up for me.


text:
Q: Best way to present a pushgateway metric in Grafana I am new to Prometheus.
I wrote a bash script that retuns either "1" or "0", and using pushgateway created a metric in prometheus for it.
In pushgatway metrics UI I can see the meteic's value as expected (or so I think):
# TYPE pg_bck untyped
pg_bck{instance="11.98.8.14",job="pg_bck"} 0

In Grafana however, if I pick "stats" or "gauge" visualization the graph, or gauge, shows a number with a decimal point (e.g: 0.245)
What is the correct way to show the value as either 1 or 0 in Grafana ?
Thanks

A: If the value is supposed to increase/decrease, I think it is better to expose it as a "gauge".
https://prometheus.io/docs/concepts/metric_types/#gauge
Furthermore, you probably want to check the "Instant" setting in the grafana query to get the last value.
Best,

A: Thank you for the answer.
Haven't checked your suggestion as seems like choosing for the pannel calulation "last" (as appraenlty the default alucaltion is the avarage) solved the problem.


text:
Q: How do i check someones balance? So like im trying to get my bot to have a command that checks someone elses balance in a economy thing. This is my code. I dont know what ive done wrong...
async def check(ctx,member:discord.Member):
    await open_account(ctx.author)
    user = discord.Member

    users = await get_bank_data()

    wallet_amt = users[str(discord.Member)]["wallet"]
    bank_amt = users[str(discord.Member)]["bank"]

    embed = discord.Embed(
        title = f"{discord.Member}'s balance",
        Colour = discord.Colour.red()
    )
    embed.set_author(name='Author Name', inline=False)
    embed.add_field(name='Wallet', value= wallet_amt, inline=False)
    embed.add_field(name='Bank', value= bank_amt, inline=False)
    await ctx.send(embed = embed)

A: Well assuming you used @client.command() above your function, there are still a couple of things that need some tinkering. First, your check function's member argument is never actually called and you're opening the account for the specific user that sent the command here await open_account(ctx.author) which should instead be await open_account(member)
Now if you want to have to specify which user account you want to open every time you call the function you can try this:
    @client.command()
    async def check(ctx,member:discord.Member):
        await open_account(member)
        users = await get_bank_data()

        wallet_amt = users[str(member.id)]["wallet"]
        bank_amt = users[str(member.id)]["bank"]

        embed = discord.Embed(
            title = f"{member}'s balance",
            Colour = discord.Colour.red()
        )
        embed.set_author(name=member)
        embed.add_field(name='Wallet', value= wallet_amt, inline=False)
        embed.add_field(name='Bank', value= bank_amt, inline=False)
        await ctx.channel.send(embed=embed)

or if you still want to have the option to show your own account as well as the member's account, you can try this.
    @client.command()
    async def check(ctx, member:discord.Member= None):
        if member != None:
            await open_account(member)
            users = await get_bank_data()

            wallet_amt = users[str(member.id)]["wallet"]
            bank_amt = users[str(member.id)]["bank"]

            embed = discord.Embed(
                title = f"{member}'s balance",
                Colour = discord.Colour.red()
            )
            embed.set_author(name=member)
            embed.add_field(name='Wallet', value= wallet_amt, inline=False)
            embed.add_field(name='Bank', value= bank_amt, inline=False)
            await ctx.channel.send(embed=embed)
        else:
            user = ctx.author
            await open_account(user)
            users = await get_bank_data()

            wallet_amt = users[str(user.id)]["wallet"]
            bank_amt = users[str(user.id)]["bank"]

            embed = discord.Embed(
                title = f"{user}'s balance",
                Colour = discord.Colour.red()
            )
            embed.set_author(name=user)
            embed.add_field(name='Wallet', value= wallet_amt, inline=False)
            embed.add_field(name='Bank', value= bank_amt, inline=False)
            await ctx.channel.send(embed=embed)


text:
Q: Is it possible to develop DirectX 9 apps using the latest DirectX SDK? I know that most people have DirectX9-capable cards but is it really necessary to install the DirectX9 SDK in order to develop DX9 apps or is it possible to do it using the latest DX SDK?

A: The latest DirectX SDK (March 2009) supports DirectX 9, DirectX10, and includes the preview of DX11.
You can use it to develop against any of these DX versions.
You do need the DX SDK installed to develop for DirectX, unless you're doing it indirectly through a library.  The header files, libraries, etc, are included with the SDK.  That being said, even if you're using a library, you'll want to install the latest SDK - it's very, very difficult to debug DX applications without the SDK, since the SDK is what allows you to run using the Debug version of DirectX.


text:
Q: How to write integration and system tests in Asp.net MVC My application
I have an application design that looks like this:

*

*web application layer - asp.net MVC app with controllers and views that use POCOs and call services

*service layer - business processes that use POCOs and call repositories

*data layer - repositories that use POCOs and communicate with the model in the form of EF model which is part of this same layer

*POCO layer - defines all classes that are used for inter communication between these layers

So my data layer is completely transparent to data model implementation because upper layer don't use data entities at all.
Testing
As much as I understand unit, integration and system testing (with relation to Asp.net MVC) is this:

*

*unit testing - this one's easy. Mock decoupled objects and inject them in your unit test so tested unit will use them

*integration testing - should make a group of production functionality units and mock the rest: so writing integration tests that would test controller, service and repository integration without actually using production database

*system testing - run tests on all layers without any mocking, meaning I have to use production (test) database as well

Problem
I can easily see how to write unit tests as well as system tests, but I don't know how to write integration tests? Maybe my view of these is completely distorted and I don't understand them at all.
How should one write integration and system tests for an Asp.net MVC application?
Or any .net application for that matter?
Some code that helps explain the problem
Suppose I have classes like:

*

*TaskController calls into TaskService

*TaskService calls into TaskRepository

*TaskRepository manipulate EF data internally

So here are my (abbreviated) classes:
public class TaskController
{
    private ITaskService service;

    // injection constructor
    public TaskController(ITaskService service)
    {
        this.service = service;
    }

    // default constructor
    public TaskController() : this(new TaskService()) {}

    public ActionResult GetTasks()
    {
        return View(this.service.GetTasks());
    }
    ...
}

public class TaskService : ITaskService
{
    private ITaskRepository repository;

    // injection constructor
    public TaskService(ITaskRepository repository)
    {
        this.repository = repository;
    }

    // default constructor
    public TaskService() : this(new TaskRepository()) {}

    public IList<Task> GetTasks()
    {
        return this.repository.GetTasks();
    }
    ...
}

public class TaskRepository : ITaskRepository
{
    public IList<Task> GetTasks()
    {
        // code that gets tasks from EF and converts to Task POCOs
    }
    ...
}

Unit test is simple and would look like this:
public void UnitTest()
{
    var mock = new Mock<ITaskService>();
    // other code that mocks the service

    TaskController controller = new TaskController(mock.Object);

    // do the test
}

But when it comes to an integration test, how do I mock only certain parts of the integration.
public void IntegrationTest()
{
    // no mocking at all
    TaskController = new TaskController();
    // do some testing
}

First of all I can't just mock database here? I could mock repository and have real service and controller though...

A: Integration tests should test the integration between components.  While unit tests test individual pieces of a single component, integration tests the interactions between components, and are meant to work live.  So an integration test would utilize a database and any other external dependencies, where its best to mock these services in unit testing.
System test to me would be functional testing (another level of testing using something like fit), or ui testing through a tool like testcomplete or telerik's QA tool.
HTH.

A: Integration tests that don't involve the UI can still be written in NUnit, xUnit, etc.
For ASP.NET MVC in particular (or any web application), you can use WatiN or Selenium to write system/integration tests using the UI.
You might also want to look at T.S.T. for T-SQL unit testing, and SpecFlow if you are curious about BDD in .NET.
Note:  I wrote this before the question was updated with code and a description of the specific situation.  It doesn't really address the question anymore, but hopefully will still be interesting/useful to someone.

A: I just replied to a related question: Integration tests implementation. I think it addressed the issue here, by presenting a clear approach to take.
Part of the issue is that higher level integration tests get too complex v. quickly. Its the nature of the problem, so I prefer to make sure all the separate pieces work as intended, through unit tests and focused integration tests depending on the class involved.
With the above in place, you only need to make sure the separate pieces are hooked correctly, so I use the full system tests for that. This has the best of its effect if the code follows SOLID and DRY.


text:
Q: I pass all test spf,dmarc,dkim but still email going into spam I am using amazon ec2 ubuntu 14.04 instance and  i did configure postfix,dkim and spf but still email are coming into inbox.Below you can see the orignal msg.

Delivered-To: malikkamranabid@gmail.com
Received: by 10.46.36.3 with SMTP id k3csp2397059ljk;
        Sun, 25 Feb 2018 02:44:16 -0800 (PST)
X-Google-Smtp-Source: AG47ELso8sEH+HXagEwS+Cp3omW50lz8Zg7pnhNvaYcsvQjzjA3ezzCRkOZII/vpg/Dws4WboCl+
X-Received: by 10.55.168.4 with SMTP id r4mr11222502qke.311.1519555456508;
        Sun, 25 Feb 2018 02:44:16 -0800 (PST)
ARC-Seal: i=1; a=rsa-sha256; t=1519555456; cv=none;
        d=google.com; s=arc-20160816;
        b=bs3mUdAYvaINS8ojtjqe6SkOBmcUEIiWFDx2pxqxVqVoQjv48OJbFqfcOo9xsjuBNV
         7GOEf+9Y33e+sxQEgUdnKnhsR7BDf1zCRb56mdDZLUrUUrMbJmkcADAGkzbAshdAnNH2
         PHmrozAYOGzHUxhGqx8GxdGFp4dfvcFyQ4vv7XUo42jTcvEE72d6IU62s883sFMMhEei
         KecC7gpsSESHi+GR/SO2J5cwgw8/7bVstZB4EMbUc4FRkCDAoW14WUdjpYifVIDGJ6eo
         F+Yy/YOnkdSHqArkh1ECbAdVxducy5Ech7n293IgwWkVbAVPB7gs0rdpbWh9R6mYAAQH
         nuYA== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816;
        h=date:message-id:cc:reply-to:from:mime-version:subject:to
         :dkim-signature:arc-authentication-results;
        bh=z6TUz85EdYrACGMHYgZhJGvVy5oQI0dooVMKa2ZT7c4=;
        b=SiayPbnRmwqPYvN/3fDjKeb9AlUFUybSFOjuk6wbwNKOkm67rTByIHSCqyDsyNpALJ
         aNsFUe6TJY+4ADJwfTfekBTAbs6DJthyLR47ELn6G2R7FTDebmg6eu6sZsCrX9mrrGGT
         rCKIvfnPq+56TvU7UYzZvicnw/nnUaA1GmJKQAAn0/94ZlPgf4Q/Qf4QKGUpag/65DTI
         UTzttdeioLEAwaRcbSzOEd77I2e5sv+1VIsn8dPM+zYwbaK5Lic/Zz4y/o3Z2cm6IwcF
         UZmUAB+0Nm01O2U1qXUyVnN4wTrjAp5ruYVNwwCTp7la3RolM9r4gtTaj2T+JYaJKDx+
         Viug== ARC-Authentication-Results: i=1; mx.google.com;
       dkim=pass header.i=@lnl.com.hk header.s=dkim header.b=oyNNr3rQ;
       spf=pass (google.com: domain of noreply@lnl.com.hk designates 54.210.33.152 as permitted sender) smtp.mailfrom=noreply@lnl.com.hk;
       dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=lnl.com.hk Return-Path: <noreply@lnl.com.hk>
Received: from mail.lnl.com.hk (ec2-54-210-33-152.compute-1.amazonaws.com. [54.210.33.152])
        by mx.google.com with ESMTP id m5si5766866qkd.12.2018.02.25.02.44.16
        for <malikkamranabid@gmail.com>;
        Sun, 25 Feb 2018 02:44:16 -0800 (PST)
Received-SPF: pass (google.com: domain of noreply@lnl.com.hk designates 54.210.33.152 as permitted sender) client-ip=54.210.33.152;
Authentication-Results: mx.google.com;
       dkim=pass header.i=@lnl.com.hk header.s=dkim header.b=oyNNr3rQ;
       spf=pass (google.com: domain of noreply@lnl.com.hk designates 54.210.33.152 as permitted sender) smtp.mailfrom=noreply@lnl.com.hk;
       dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=lnl.com.hk
Received: by mail.lnl.com.hk (Postfix, from userid 33) id 34432426FE; Sun, 25 Feb 2018 10:44:17 +0000 (UTC)
DKIM-Signature: v=1; a=rsa-sha256; c=simple/simple; d=lnl.com.hk; s=dkim; t=1519555457; bh=z6TUz85EdYrACGMHYgZhJGvVy5oQI0dooVMKa2ZT7c4=; h=To:Subject:From:Reply-To:CC:Date:From; b=oyNNr3rQhOdPqaNvZfQv2Fx6C/Ypx6T4SLKyhihBIP3I5A/8Q3NeY/VbFOEdshIvL    pKl1cRm+RzbdNKJULdUCklWJBIoi1EIiAlvUh0cWYTR1YQZo1/b+c2FKoNfK6N5E01      cFp+U1mmuuTXx19T8uQQBRlvZBLUTMuNIq0OvFA8=
To: malikkamranabid@gmail.com
Subject: My subject
X-PHP-Originating-Script: 1000:emailphp.php
MIME-Version: 1.0
Content-type: text/html; charset=iso-8859-1
From: noreply@lnl.com.hk
Reply-To: malikkamranabid@gmail.com
CC: malikkamranabid94@yahoo.com X-Mailer: PHP/5.5.9-1ubuntu4.22
Message-Id: <20180225104417.34432426FE@mail.lnl.com.hk> Date: Sun, 25 Feb 2018 10:44:17 +0000 (UTC)

Hello world!

A: If you are not using an elastic IP address for your mail server, you need to do that.
If you are...
Received: from mail.lnl.com.hk (ec2-54-210-33-152.compute-1.amazonaws.com. [54.210.33.152])

...then you haven't asked AWS Support to configure reverse DNS on your EIP, which you will definitely want to do.
https://aws.amazon.com/blogs/aws/reverse-dns-for-ec2s-elastic-ip-addresses/
There is nothing obvious contributing to this message going into spam, but it would not be surprising if gmail gives some weight to the default *.compute-1.amazonaws.com reverse DNS record, which clearly identifes the source as a dynamic or pool address, which is a potential red flag indicating a transient sender (spammer).
Afterthought: The From address as interpreted by gmail is distinctly wrong.  Verify that your messages aren't actually malformed.  You need this to look correct.  The CC line looks invalid in the message body, as well.

A: It's probably a reverse DNS lookup issue. Without a valid reverse DNS record, many ISPs will block your email or mark it as spam.
See this line?
'Received: from mail.lnl.com.hk (ec2-54-210-33-152.compute-1.amazonaws.com. [54.210.33.152]'
The IP address 54.210.33.152 reverse lookup PTR record returns ec2-54-210-33-152.compute-1.amazonaws.com, not mail.lnl.com.hk. This is a big red flag in most spam scoring systems. It's probably affecting you here.
For more info on reverse DNS, see https://www.rackaid.com/blog/email-dns-records/


text:
Q: Unable to switch to TabBarController after dismissing Modal View Controller iOS I want to implement login(modal) and tab Bar items(VCs) but getting stuck. I am unable to switch to tabs or the TabBarController after dismissing the modalVC.
The Whole implementation is programmatically done. Just a blank Login VC is my root VC in main.StoryBoard.
What I want -> Dismiss LoginModal on success and switch to Tab1 of TabBarController.
What's happening? -> LoginModal being dismissed but not switching to any tab or the TabViewController or I don't know what's happening. I am attaching the Screenshots of what's happening, below. {The View after dismissing the modalVC}
So,
I have a LoginViewController with a 'login' function ->
//LoginController.swift
func login() {
   let rootViewController = UIApplication.shared.keyWindow?.rootViewController
    guard let mainNavigationController = rootViewController as? MainNavigationController else { return }
    mainNavigationController.tabBarController?.selectedIndex = 1

    UserDefaults.standard.setIsLoggedIn(value: true)
    dismiss(animated: true, completion: nil)
}

I have created TabBarController class as follows->
//TabBarController.swift
class TabBarController: UITabBarController {

override func viewDidLoad() {
    super.viewDidLoad()

    let firstViewController = HomeController()
    firstViewController.tabBarItem = UITabBarItem(tabBarSystemItem: .favorites, tag: 0)

    let secondViewController = EventsViewController()
    secondViewController.tabBarItem = UITabBarItem(tabBarSystemItem: .contacts, tag: 1)

let tabBarList = [firstViewController, secondViewController, thirdViewController, fourthViewController]
    viewControllers = tabBarList
}

And Finally the MainNavigationController as follows->
//MainNavigationController.swift
class MainNavigationController: UINavigationController {
override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .white
if isLoggedIn() {
        //assume user is logged in
        let rootViewController = UIApplication.shared.keyWindow?.rootViewController
        guard let mainNavigationController = rootViewController as? TabBarController else { return }
        mainNavigationController.tabBarController?.selectedIndex = 1

    } else {
        //present LoginVC modally
        perform(#selector(showLoginController), with: nil, afterDelay: 0.01)
    }

A: I think you're dismissing your LoginVC when there's nothing behind that controller to display.
Change your root view controller from the loginVC to your tabBarVC.  In the tabBarVC's viewWillAppear method, do the logic to check if the user it logged in or not.  If not logged in, segue (or present) the user with the LoginVC and dismiss when they log in.  If they are already logged in, skip the LoginVC segue and display your TabBarVC.


text:
Q: Get contiguous date ranges grouped into a single line I have a table which holds a lot of rows (Currently, 500K, expected to rise to 15 Million in the next 3 years). The table holds payments made for a certain event for a specific day. And event can have 1 or many payments for the same day, but the payments on the same day must have different PaymentTypes.
Below is a table variable creation that creates the basic data (Input), and then a hardcoded select which is the expected output. I need to group continuous date ranges for a payment type, for a placement, in one row, with a From and To date, and then when there's a break - no rows, and then for the next date range.
For example:
Placement 1 got payments from the 1st to the 2nd (2 days) for Payment type 5, and then from the 4th until the 6th for the same type. Therefore, two rows. Payment type 1 also got a payment for the 1st to the 3rd for payment type 10. So, that is another row.
DECLARE @Temp TABLE
(
    Id INT NOT NULL IDENTITY(1,1),
    PlacementId INT NOT NULL,
    PaymentTypeId INT NOT NULL,
    DateValue DATETIME NOT NULL,
    Amount DECIMAL(16,2) NOT NULL
)

INSERT INTO @Temp (PlacementId, PaymentTypeId, DateValue, Amount)
SELECT 1, 5, '01-JAN-2015', 100 UNION
SELECT 1, 5, '02-JAN-2015', 150 UNION
SELECT 1, 5, '04-JAN-2015', 78 UNION
SELECT 1, 5, '05-JAN-2015', 89 UNION
SELECT 1, 5, '06-JAN-2015', 22 UNION
SELECT 1, 10, '01-JAN-2015', 10 UNION
SELECT 1, 10, '02-JAN-2015', 10 UNION
SELECT 1, 10, '03-JAN-2015', 15 UNION
SELECT 2, 5, '01-JAN-2015', 200 UNION
SELECT 2, 5, '02-JAN-2015', 5 UNION
SELECT 2, 5, '03-JAN-2015', 50 UNION
SELECT 3, 5, '01-JAN-2015', 80 UNION
SELECT 4, 5, '07-JAN-2015', 100 UNION
SELECT 4, 5, '08-JAN-2015', 12 UNION
SELECT 4, 5, '12-JAN-2015', 66 UNION
SELECT 4, 5, '14-JAN-2015', 4 UNION
SELECT 5, 10, '08-JAN-2015', 10

SELECT * FROM @Temp

SELECT 1 AS PlacementId, 5 AS PaymentTypeId, '2015-01-01' AS FromDate, '2015-01-02' AS ToDate, 250 AS Amount UNION
SELECT 1, 10, '2015-01-01', '2015-01-03', 35 UNION
SELECT 1, 5, '2015-01-04', '2015-01-06', 189 UNION
SELECT 2, 5, '2015-01-01', '2015-01-03', 255 UNION
SELECT 3, 5, '2015-01-01', '2015-01-01', 80 UNION
SELECT 4, 5, '2015-01-07', '2015-01-08', 112 UNION
SELECT 4, 5, '2015-01-12', '2015-01-12', 66 UNION
SELECT 4, 5, '2015-01-14', '2015-01-14', 4 UNION
SELECT 5, 10, '2015-01-08', '2015-01-08', 10

Note, there is a NCI on PlacementID and PaymentTypeID.
We're doing it at the moment with a crazy load of cursors, and are having extreme speed issues. (The 500K lines takes 4 minutes to process).
Is there an efficient method to achieve the desired output?

A: This is a problem called Grouping Islands of Contiguous Dates. Read this article be Jeff Moden for more info.
SQL Fiddle
;WITH Cte AS(
    SELECT *,
        RN = DATEADD(DAY, - ROW_NUMBER() OVER(PARTITION BY PlacementId, PaymentTypeId ORDER BY DateValue), DateValue)
    FROM @Temp
)
SELECT
    PlacementId,
    PaymentTypeId,
    FromDate = MIN(DateValue),
    ToDate = MAX(DateValue),
    Amount = SUM(Amount)
FROM Cte
GROUP BY PlacementId, PaymentTypeId, RN
ORDER BY PlacementId, PaymentTypeId, FromDate


text:
Q: Required tooltip displayed when close modal in FireFox Got a strange issue, I am developing an angularJS app that is to use Firefox only but I have an issue with the tooltip on a modal if the user clicks the Close button.
When the modal opens there is a dropdown list which is blank by default and is also required. The modal also has a Submit button and Close button.  The Submit button is disabled until all mandatory fields are completed and the Close button is always enabled.
If you click the Close button without selecting an option (which is a valid action) the modal closes as expected but the required tooltip is displayed.
Does anyone know of a fix for this issue?

A: Since the sample code is not exist, based on your question I tried a solution with the "Submit" and "Close" buttons.
Whatever the button you clicks, it fires the submit's function. So you need to block the execution by using $event.preventDefault();
Sample HTML
<form name="form" novalidate ng-submit="saveModal()">

        <button class="btn btn-success" type="submit">
            Submit
        </button>
        <button class="btn btn-default" ng-click="closeModal($event)">
            Close
        </button>

</form>

Sample Controller
$scope.closeModal= function ($event) {
    $event.preventDefault();
    // Close modal related codes here
};

$scope.saveModal = function() {
    // I assume that the required tooltip related codes are available
    // inside the submit's function
};


text:
Q: Making paragraph look better when using bootstrap grid Hello I am using bootstrap grid and trying to make this:

(source: gyazo.com)
That's what I am using to try to get something like this:
The code is inside bootstrap container by the way,

    Experienced

Brought to you by a well-knowledged developer and designer, that are ready to serve. We deliver one Hell of a product so strap yourself down to your chair and get ready.

    Web Development

    UI/UX Design

That's the result:

(source: gyazo.com)
as you see the paragraph looks way different than in the first paragraph, that's because the bootstrap grid span class number is too short, but if I will use span 4, the icon will just mess up to the bottom.
How can I make the paragraphs look a bit of what it looks in the first image?
What is the issue here? Thanks.

A: Your text looks a larger than the orig, but that's too simple. Try making a new class, .span3wide and in your stylesheet increase the size, reduce the padding/margin. Also, add margin:0 auto; to #icon-1 to centre.


text:
Q: Installing hadoop is trouble
Have some  problem when I start hadoop. Namenode and Datanode can't operate.
Help me...

A: Looks like the namenode address definition has a white space before it. Make sure there are no spaces or tabs or new lines before it in your hdfs-site.xml. You probably have something like this:
<configuration>
  <property>
    <name>fs.default.name</name>
    <value>
      hdfs://localhost:9000</value>
  </property>
...

But it should look like this:
<configuration>
  <property>
    <name>fs.default.name</name>
    <value>hdfs://localhost:9000</value>
  </property>
...


text:
Q: HttpClient Response returns scrambled data I'm trying to get a proper JSON response from this URL using HttpClient. When I view the URL in Chrome the data is properly formatted JSON. When I use the HttpClient, I get a bunch of junk data that looks like bytes or something like that. I can't figure out how to decode it into a string. Please advise.
string url = "https://api.nasdaq.com/api/calendar/earnings?date=2010-07-30";

string calendar = await DownloadFile(new string[] { url });

private static readonly HttpClient httpClient = new HttpClient();

        public static async Task<string> DownloadFile(string[] args)
        {
            string url = args[0];

            httpClient.DefaultRequestHeaders.AcceptEncoding.ParseAdd("gzip, deflate, br");
            httpClient.DefaultRequestHeaders.Connection.ParseAdd("keep-alive");

            string text = await httpClient.GetStringAsync(url);

            return text;

        }

A: The data is coming back compressed with gzip. You can have your HttpClient automatically decompress this data by enabling this property when instantiating your HttpClient:
    private static readonly HttpClient httpClient = new HttpClient(new HttpClientHandler
    {
        AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
    });

A: I think you have to remove Brotli compression from your request header. Brotli (br) is not decoded out of the box by .Net.
That is, change:
httpClient.DefaultRequestHeaders.AcceptEncoding.ParseAdd("gzip, deflate, br");

to
httpClient.DefaultRequestHeaders.AcceptEncoding.ParseAdd("gzip, deflate");


text:
Q: Maven 3.5.2 cannot deploy artifact to Artifactory with error 417 I'm creating the simple pom project as the following:-
<project xmlns="http://maven.apache.org/POM/4.0.0"
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                        http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.test</groupId>
    <artifactId>test-maven</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>pom</packaging>
    <name>test-maven</name>
    <distributionManagement>
        <repository>
            <id>central</id>
            <name>myartifactory</name>
            <url>
               https://myhost/artifactory/libs-release-local
            </url>
        </repository>
        <snapshotRepository>
            <id>snapshots</id>
            <name>myartifactory</name>
            <url>
               https://myhost/artifactory/libs-snapshot-local
            </url>
        </snapshotRepository>
    </distributionManagement>
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

The settings.xml is
<servers>
    <server>
        <id>central</id>
        <username>my-user-id</username>
        <password>some-encrypyted-password</password>
    </server>
    <server>
        <id>snapshots</id>
        <username>my-user-id</username>
        <password>some-encrypyted-password</password>
    </server>
</servers>

This project is able to be deployed to Artifactory 5.8.3 by using Maven 3.3.9: mvn clean deploy.
Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-10T23:41:47+07:00)
Maven home: C:\Java.Application\Apache\apache-maven-3.3.9\bin\..
Java version: 1.8.0_121, vendor: Oracle Corporation
Java home: C:\Java.Application\Sun\Java\jdk1.8.0_121\jre
Default locale: en_US, platform encoding: UTF-8
OS name: "windows 10", version: "10.0", arch: "amd64", family: "dos"

But when I change to Maven 3.5.2
Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T14:58:13+07:00)
Maven home: C:\Java.Application\Apache\apache-maven-3.5.2\bin\..
Java version: 1.8.0_121, vendor: Oracle Corporation
Java home: C:\Java.Application\Sun\Java\jdk1.8.0_121\jre
Default locale: en_US, platform encoding: UTF-8
OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"

During the executing the mvn clean deploy there is an error as
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-deploy-plugin:2.8.2:deploy
(default-deploy) on project test-maven: Failed to deploy artifacts:
Could not transfer artifact com.test:test-maven:pom:0.0.1-20180213.064245-2 from/to
snapshots (https://myhost/artifactory/libs-snapshot-local): Failed to transfer file:
https://myhost/artifactory/libs-snapshot-local/com/test/test-maven/
0.0.1-SNAPSHOT/test-maven-0.0.1-20180213.064245-2.pom.
Return code is: 417, ReasonPhrase: Expectation Failed. -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException:
    Failed to execute goal org.apache.maven.plugins:maven-deploy-plugin:2.8.2:deploy
    (default-deploy) on project test-maven:
    Failed to deploy artifacts: Could not transfer artifact...
    .../0.0.1-SNAPSHOT/test-maven-0.0.1-20180213.064245-2.pom.
    Return code is: 417, ReasonPhrase: Expectation Failed.
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:213)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:154)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:146)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:51)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)

Am I doing something wrong? Could you please help to advise?
EDIT 1

*

*There is no any log printing at artifactory.log at that time.

*The request.log
20180213162947|1|REQUEST|some-ip|non_authenticated_user|GET|/libs-snapshot-local/com/test/test-maven/0.0.1-SNAPSHOT/maven-metadata.xml|HTTP/1.0|401|0
20180213162947|193|REQUEST|some-ip|my-user|GET|/libs-snapshot-local/com/test/test-maven/0.0.1-SNAPSHOT/maven-metadata.xml|HTTP/1.0|200|605
20180213162947|3|REQUEST|some-ip|my-user|GET|/libs-snapshot-local/com/test/test-maven/0.0.1-SNAPSHOT/maven-metadata.xml.sha1|HTTP/1.0|200|40

*The access.log
2018-02-13 16:29:47,347 [ACCEPTED DOWNLOAD] libs-snapshot-local:com/test/test-maven/0.0.1-SNAPSHOT/maven-metadata.xml for my-user/some-ip.
2018-02-13 16:29:47,437 [ACCEPTED DOWNLOAD] libs-snapshot-local:com/test/test-maven/0.0.1-SNAPSHOT/maven-metadata.xml.sha1 for my-user/some-ip.

EDIT 2
The mvn clean deploy -e -X log
[INFO]
[INFO] --- maven-deploy-plugin:2.8.2:deploy (default-deploy) @ test-maven ---
[DEBUG] Dependency collection stats: {ConflictMarker.analyzeTime=129185, ConflictMarker.markTime=69136, ConflictMarker.nodeCount=36, ConflictIdSorter.graphTime=58074, ConflictIdSorter.topsortTime=20149, ConflictIdSorter.conflictIdCount=16, ConflictIdSorter.conflictIdCycleCount=0, ConflictResolver.totalTime=960001, ConflictResolver.conflictItemCount=36, DefaultDependencyCollector.collectTime=76597424, DefaultDependencyCollector.transformTime=1258668}
[DEBUG] org.apache.maven.plugins:maven-deploy-plugin:jar:2.8.2:
[DEBUG]    org.apache.maven:maven-plugin-api:jar:2.2.1:compile
[DEBUG]    org.apache.maven:maven-project:jar:2.2.1:compile
[DEBUG]       org.apache.maven:maven-settings:jar:2.2.1:compile
[DEBUG]       org.apache.maven:maven-profile:jar:2.2.1:compile
[DEBUG]       org.apache.maven:maven-artifact-manager:jar:2.2.1:compile
[DEBUG]          org.apache.maven:maven-repository-metadata:jar:2.2.1:compile
[DEBUG]          backport-util-concurrent:backport-util-concurrent:jar:3.1:compile
[DEBUG]       org.apache.maven:maven-plugin-registry:jar:2.2.1:compile
[DEBUG]       org.codehaus.plexus:plexus-interpolation:jar:1.11:compile
[DEBUG]       org.codehaus.plexus:plexus-container-default:jar:1.0-alpha-9-stable-1:compile
[DEBUG]          junit:junit:jar:3.8.1:compile
[DEBUG]          classworlds:classworlds:jar:1.1-alpha-2:compile
[DEBUG]    org.apache.maven:maven-model:jar:2.2.1:compile
[DEBUG]    org.apache.maven:maven-artifact:jar:2.2.1:compile
[DEBUG]    org.codehaus.plexus:plexus-utils:jar:3.0.15:compile
[DEBUG] Created new class realm plugin>org.apache.maven.plugins:maven-deploy-plugin:2.8.2
[DEBUG] Importing foreign packages into class realm plugin>org.apache.maven.plugins:maven-deploy-plugin:2.8.2
[DEBUG]   Imported:  < maven.api
[DEBUG] Populating class realm plugin>org.apache.maven.plugins:maven-deploy-plugin:2.8.2
[DEBUG]   Included: org.apache.maven.plugins:maven-deploy-plugin:jar:2.8.2
[DEBUG]   Included: backport-util-concurrent:backport-util-concurrent:jar:3.1
[DEBUG]   Included: org.codehaus.plexus:plexus-interpolation:jar:1.11
[DEBUG]   Included: junit:junit:jar:3.8.1
[DEBUG]   Included: org.codehaus.plexus:plexus-utils:jar:3.0.15
[DEBUG] Configuring mojo org.apache.maven.plugins:maven-deploy-plugin:2.8.2:deploy from plugin realm ClassRealm[plugin>org.apache.maven.plugins:maven-deploy-plugin:2.8.2, parent: sun.misc.Launcher$AppClassLoader@55f96302]
[DEBUG] Configuring mojo 'org.apache.maven.plugins:maven-deploy-plugin:2.8.2:deploy' with basic configurator -->
[DEBUG]   (f) artifact = com.test:test-maven:pom:0.0.1-SNAPSHOT
[DEBUG]   (f) attachedArtifacts = []
[DEBUG]   (f) deployAtEnd = false
[DEBUG]   (s) localRepository =       id: local
      url: file:///D:/M2/Repository/
   layout: default
snapshots: [enabled => true, update => always]
 releases: [enabled => true, update => always]

[DEBUG]   (f) offline = false
[DEBUG]   (f) packaging = pom
[DEBUG]   (f) pomFile = D:\JavaPrj\sample\test-maven\pom.xml
[DEBUG]   (f) project = MavenProject: com.test:test-maven:0.0.1-SNAPSHOT @ D:\JavaPrj\sample\test-maven\pom.xml
[DEBUG]   (f) reactorProjects = [MavenProject: com.test:test-maven:0.0.1-SNAPSHOT @ D:\JavaPrj\sample\test-maven\pom.xml]
[DEBUG]   (f) retryFailedDeploymentCount = 1
[DEBUG]   (f) skip = false
[DEBUG]   (f) updateReleaseInfo = false
[DEBUG] -- end configuration --
[DEBUG] Using transporter WagonTransporter with priority -1.0 for https://myhost/artifactory/libs-snapshot-local
[DEBUG] Using connector BasicRepositoryConnector with priority 0.0 for https://myhost/artifactory/libs-snapshot-local with username=my-user, password=***
Downloading from snapshots: https://myhost/artifactory/libs-snapshot-local/com/test/test-maven/0.0.1-SNAPSHOT/maven-metadata.xml
Progress (1): maven-metadata.xml (605 B)

Downloaded from snapshots: https://myhost/artifactory/libs-snapshot-local/com/test/test-maven/0.0.1-SNAPSHOT/maven-metadata.xml (605 B at 961 B/s)
[DEBUG] Writing tracking file D:\M2\Repository\com\test\test-maven\0.0.1-SNAPSHOT\resolver-status.properties
Uploading to snapshots: https://myhost/artifactory/libs-snapshot-local/com/test/test-maven/0.0.1-SNAPSHOT/test-maven-0.0.1-20180213.092946-2.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.018 s
[INFO] Finished at: 2018-02-13T16:29:46+07:00
[INFO] Final Memory: 11M/162M
[INFO] ------------------------------------------------------------------------

EDIT 3
Add the Apache httpd access_log.
my-ip - - [13/Feb/2018:17:40:48 +0700] "GET /artifactory/libs-snapshot-local/com/test/test-maven/0.0.1-SNAPSHOT/maven-metadata.xml HTTP/1.1" 401 91
my-ip - - [13/Feb/2018:17:40:48 +0700] "GET /artifactory/libs-snapshot-local/com/test/test-maven/0.0.1-SNAPSHOT/maven-metadata.xml HTTP/1.1" 200 605
my-ip - - [13/Feb/2018:17:40:48 +0700] "GET /artifactory/libs-snapshot-local/com/test/test-maven/0.0.1-SNAPSHOT/maven-metadata.xml.sha1 HTTP/1.1" 200 40
my-ip - - [13/Feb/2018:17:40:48 +0700] "PUT /artifactory/libs-snapshot-local/com/test/test-maven/0.0.1-SNAPSHOT/test-maven-0.0.1-20180213.104048-2.pom HTTP/1.1" 417 364

EDIT 4
Regarding to the Configuring a Reverse Proxy, this generating is not available for the Artifactory OSS version.

*

*Here is my Apache httpd setting.

<Location /artifactory/>

  ProxyPass https://myhost:62443/artifactory/
  ProxyPassReverse https://myhost/artifactory/
  SetEnv force-proxy-request-1.0 1
  SetEnv proxy-nokeepalive 1
</Location>

*The artifactory/tomcat/conf/server.xml
<Server port="8015" shutdown="SHUTDOWN">

    <Service name="Catalina">

        <Connector
           protocol="org.apache.coyote.http11.Http11NioProtocol"
           port="62443" maxThreads="200" URIEncoding="UTF-8"
           scheme="https" secure="true" SSLEnabled="true"
           keystoreFile="/path/to/jks" keystorePass="some-password"
           clientAuth="false" sslProtocol="TLS"/>

        <Connector port="8040" sendReasonPhrase="true" maxThreads="50"/>

        <Connector port="8019" protocol="AJP/1.3" sendReasonPhrase="true"/>

        <Engine name="Catalina" defaultHost="localhost">
            <Host name="localhost" appBase="webapps" startStopThreads="2"/>
        </Engine>
    </Service>

</Server>

EDIT 5
I would like to highlight some significant as the following: -

*

*By using the Maven 3.3.9 to deploy this project against the existing Artifactory with Apache httpd is worked properly. Please correct me if I'm wrong. I understand that there is no any issue about the configuration.

*The only changing is the Maven 3.5.2.
I've no any clue why this issue occur.
EDIT 6
Since there is an exception about the wagon
Caused by: org.apache.maven.wagon.TransferFailedException:
Failed to transfer file: https://myhost/artifactory/libs-snapshot-local/com/test/test-maven/0.0.1-SNAPSHOT/test-maven-0.0.1-20180214.065633-7.pom. Return code is: 417, ReasonPhrase: Expectation Failed.
    at org.apache.maven.wagon.shared.http.AbstractHttpClientWagon.put (AbstractHttpClientWagon.java:635)
    at org.apache.maven.wagon.shared.http.AbstractHttpClientWagon.put (AbstractHttpClientWagon.java:557)
    at org.apache.maven.wagon.shared.http.AbstractHttpClientWagon.put (AbstractHttpClientWagon.java:539)
    at org.apache.maven.wagon.shared.http.AbstractHttpClientWagon.put (AbstractHttpClientWagon.java:533)
    at org.apache.maven.wagon.shared.http.AbstractHttpClientWagon.put (AbstractHttpClientWagon.java:513)

I've compared the wagon from maven_home/lib between Maven 3.3.9 and 3.5.2, and found that the 3.3.9 use wagon version 2.10 and 3.5.2 use wagon 2.12.
Try 1
I copy the maven_home/lib from Maven 3.3.9 to Maven 3.5.2, the mvn clean deploy works properly.
Try 2
Copy maven_home/lib from Maven 3.5.2 to Maven 3.3.9, the same exception occurs.
Try 3
I'm updating the pom to use the latest wagon 3.0.0 as the following: -
<properties>
    <my.wagon.vesion>3.0.0</my.wagon.vesion>
</properties>
<build>
    <extensions>
        <extension>
            <groupId>org.apache.maven.wagon</groupId>
            <artifactId>wagon-file</artifactId>
            <version>${my.wagon.vesion}</version>
        </extension>
        <extension>
            <groupId>org.apache.maven.wagon</groupId>
            <artifactId>wagon-http-shared</artifactId>
            <version>${my.wagon.vesion}</version>
        </extension>
        <extension>
            <groupId>org.apache.maven.wagon</groupId>
            <artifactId>wagon-http</artifactId>
            <version>${my.wagon.vesion}</version>
        </extension>
        <extension>
            <groupId>org.apache.maven.wagon</groupId>
            <artifactId>wagon-provider-api</artifactId>
            <version>${my.wagon.vesion}</version>
        </extension>
    </extensions>
</build>

Luckily when I execute mvn clean deploy -e -X against the wagon 3.0.0 there is a HTTP header/request/response printing so that I've found the response as
[DEBUG] http-outgoing-0 << "
Expectation Failed
[\n]"
[DEBUG] http-outgoing-0 << "
The expectation given in the Expect request-header[\n]"
[DEBUG] http-outgoing-0 << "field could not be met by this server.[\n]"
[DEBUG] http-outgoing-0 << "The client sent
[\n]"
[DEBUG] http-outgoing-0 << "    Expect: 100-continue[\n]"
[DEBUG] http-outgoing-0 << "
[\n]"
[DEBUG] http-outgoing-0 << "

Only the 100-continue expectation is supported.
[\n]"
[DEBUG] http-outgoing-0 << "[\n]"
[DEBUG] http-outgoing-0 << HTTP/1.1 417 Expectation Failed

Then I google the term Only the 100-continue expectation is supported. and found some significant from StackOverflow: Apache and mod_proxy not handling HTTP 100-continue from client HTTP 417.
Try 4
I've set the httpd.conf as mentioning from the thread above.
<IfModule mod_headers.c>
    RequestHeader unset Expect early
</IfModule>

At the moment I can execute the mvn clean deploy by using the Maven 3.5.2 properly.

A: Since the root cause is
[DEBUG] http-outgoing-0 << "
Expectation Failed
[\n]"
[DEBUG] http-outgoing-0 << "
The expectation given in the Expect request-header[\n]"
[DEBUG] http-outgoing-0 << "field could not be met by this server.[\n]"
[DEBUG] http-outgoing-0 << "The client sent
[\n]"
[DEBUG] http-outgoing-0 << "    Expect: 100-continue[\n]"
[DEBUG] http-outgoing-0 << "
[\n]"
[DEBUG] http-outgoing-0 << "

Only the 100-continue expectation is supported.
[\n]"
[DEBUG] http-outgoing-0 << "[\n]"
[DEBUG] http-outgoing-0 << HTTP/1.1 417 Expectation Failed

The StackOverflow answer advise to remove the Expect header by setting the Apache httpd.conf as
<IfModule mod_headers.c>
    RequestHeader unset Expect early
</IfModule>

At the moment I can execute the mvn clean deploy by using the Maven 3.5.2 properly.

A: If you can not fix your current problem, you can try other deployment mechanisms like maven Artifactory plugin or deploying from CI. In one of Artifactory's blog posts it is advised to deploy from Jenkins(or other CI in non-cloud environments) to aquire cleaner  pom.xml's.
https://www.jfrog.com/confluence/display/RTF/Maven+Artifactory+Plugin
https://jfrog.com/blog/dont-let-maven-deploy-plugin-trip-you/


text:
Q: Changing the constraint of an imageview in a cell programmatically I really tried to make this thing work. I read alot of articles but non of them gave a proper solution. All I want from xcode is to let me change the top constraint of an imageview in a cell programmatically. I have set my constraints for ipad full screen but I want to adjust few constraints for ipad Pro.
First i tried this:
- (void)updateConstraints
{
     [super updateConstraints];
     self.imageViewTopConstraint.constant = 300.f;
}
- (void)awakeFromNib {
//    // Initialization code
    [self setNeedsUpdateConstraints];
}

and it didnt work.
I then tried to put this line
self.imageViewTopConstraint.constant = 300.f;

in
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

Still didnt work. I resized cell height but it didnt work also.
Can you please help me out guys?
P.S: New to xcode.
Million thanks in advance.

A: Have you set imageView's bottom constraint to cell's bottom or chained with label to cell's bottom? And do you receive constraints conflict exceptions? You can add a symbolic breakpoint with symbo: UIViewAlertForUnsatisfiableConstraints, or search the console output for constraints conflict. If so, you need to adjust constraints and remove one of the bottom constraints.


text:
Q: Using a method from a 'this' object in an express post function I have a class with two methods:
var express = require('express');

class TestClass{
    constructor() {}

    first() {
        var app = express();
        var path = require('path');
        app.use( express.urlencoded({ extended: true }) )
        app.use( express.json() );

        app.post('/centroid', function(req, res) {
            this.second(req.body);
        });

        app.listen(4444);
    }
    second(data) { console.log(data) }
}

module.exports = TestClass;

When I try to reference the second method while using this, I get an error that this is undefined.
I have looked into .bind() method, but it seems that I can't use that with passing the req.body argument. Because it would require to bind it in the callback of the .post function.
How can i resolve this and use second() method in a callback of a post function?


text:
Q: Does Angular automatically remove template event listeners? In my template I have click events listeners attached:
<a class="link-component" href="{{displayURL}}" (click)="handleClick($event)">

I know I could use HostListener's, or Renderer2 as follows:
 this.clickListener = this.renderer.listen(this.htmlElement, 'click'........
 this.clickListener();

But, just in relation to the template bound event handlers, will they be removed automatically when the component is destroyed?

A: When angular creates view nodes it listens to element outputs such as click, focus, change etc. and adds disposable callback
 to disposables array of current view

Now when it's time to destroy view angular just runs all disposable callbacks
export function destroyView(view: ViewData) {
  if (view.state & ViewState.Destroyed) {
    return;
  }
  execEmbeddedViewsAction(view, ViewAction.Destroy);
  execComponentViewsAction(view, ViewAction.Destroy);
  callLifecycleHooksChildrenFirst(view, NodeFlags.OnDestroy);
  if (view.disposables) {
    for (let i = 0; i < view.disposables.length; i++) {
      view.disposables[i]();  <================================
    }
  }
  ...

So this way angular will remove all listeners of current view.

See also:

*

*Do you need to unsubscribe from @Output EventEmitter

A: Yes, everything you bind on template will be destroy with the component. Binding with @HostListener will be removed too. Only event listened manualy with addEventListener or derived syntaxe won't be removed automaticaly.


text:
Q: Cleaning stacks in target account by pipeline I am following this tutorial and i have problem with cleaning the infra in target account. The flow detail
1 : developer -commit-> github -> DeplopmentAccount:Pipeline pull the code then deploy the Aws Cloudformation stack to TargetAccount:cloudformation .
Test Cdk Pipeline will deploy the stack in TestAccount which is the good thing
2.But when we want to clean up with cdk destroy --all, it only destroys the Test CDK Pipeline , the stacks in Test Account still remains.
So my question is how do we destroy all stacks ?

A: The solution is mentioned in the tutorial you linked:

Clean up
Delete stacks using the command cdk destroy --all. When you see the following text, enter y, and press enter/return.

ProdDataLakeCDKBlogInfrastructurePipeline,
DevDataLakeCDKBlogInfrastructurePipeline (y/n)?

Note: This operation deletes stacks only in central deployment account
To delete stacks in development account, log onto Dev account, go to AWS CloudFormation console and delete the following stacks:

*

*Dev-DevDataLakeCDKBlogInfrastructureVpc

*Dev-DevDataLakeCDKBlogInfrastructureS3BucketZones

*Dev-DevDataLakeCDKBlogInfrastructureIam

Note:
Deletion of Dev-DevDataLakeCDKBlogInfrastructureS3BucketZones will delete the S3 buckets (raw, conformed, and purpose-built). This
behavior can be changed by modifying the retention policy in s3_bucket_zones_stack.py
To delete stacks in test account, log onto ~~Dev~~ Test account, go to AWS CloudFormation console and delete the following stacks:

*

*Test-TestDataLakeCDKBlogInfrastructureVpc

*Test-TestDataLakeCDKBlogInfrastructureS3BucketZones

*Test-TestDataLakeCDKBlogInfrastructureIam

Note:
The S3 buckets (raw, conformed, and purpose-built) have retention policies attached and must be removed manually when they are
no longer needed.
To delete stacks in prod account, log onto ~~Dev~~ Prod account, go to AWS CloudFormation console and delete the following stacks:

*

*Prod-ProdDataLakeCDKBlogInfrastructureVpc

*Prod-ProdDataLakeCDKBlogInfrastructureS3BucketZones

*Prod-ProdDataLakeCDKBlogInfrastructureIam

Note:
The S3 buckets (raw, conformed, and purpose-built) have retention policies attached and must be removed manually when they are
no longer needed.

It erroneously says that you have to log into the Dev account for Test and Prod, I have corrected it in the quote.
Alternatively, you can call cdk destroy --all with the --profile flag and set it to the dev/test/prod AWS credentials profile.


text:
Q: Material UI Date Picker Right now, implementation of a Material UI date picker gives the following error:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

*

*You might have mismatching versions of React and the renderer (such as React DOM)

*You might be breaking the Rules of Hooks

*You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

I think that it is calling in a different version of React from the one I'm using? Is anyone facing a similar issue.


text:
Q: Downcasting an implementation using an interface template I'm implementing a generic interface that can bridge different implementations of some base class.
The interface utility is written as follows:
// InterfaceUtils.h
//

// Base object class
class IBaseObject {
    virtual ~IBaseObject() = default;
};

// Unknown object adapter
class UnknownObject
{
public:
    UnknownObject() = default;
    UnknownObject(const UnknownObject& from);
    UnknownObject(UnknownObject&& from) noexcept;
    explicit UnknownObject(const IBaseObject& from);
    explicit UnknownObject(IBaseObject* from)
    {
         SetPointer(from);
    }
    virtual ~UnknownObject()
    {
         DeletePointer();
    }

    template<class Interface>
    const Interface* RetrieveInterface() const
    {
        if (!m_pObject)
            return nullptr;
        return dynamic_cast<const Interface*>(m_pObject);
    }
    template<class Interface>
    Interface* RetrieveInterface()
    {
         if (!m_pObject)
             return nullptr;
         return dynamic_cast<Interface*>(m_pObject);
    }
    UnknownObject& operator=(const UnknownObject& other);
    UnknownObject& operator=(UnknownObject&& other) noexcept;
    [[nodiscard]] bool IsNull() const
    {
        return m_pObject == nullptr;
    }
    void SetNull();
protected:
    [[nodiscard]] virtual const IBaseObject* GetPointer() const
    {
        return m_pObject;
    }
    virtual IBaseObject* GetPointer()
    {
        return m_pObject;
    }
    void SetPointer(ISymplektBaseObject* pObject)
    {
        m_pObject = pObject;
    }
    void DeletePointer() const
    {
        // Q: Unsafe for memory leaks ?
        // delete m_pObject;
    }
private:

    //>! stored pointer to object
    IBaseObject* m_pObject = nullptr;
};

// Generic object interface template
template <class Interface>
class ObjectInterface : public UnknownObject
{
public:
    explicit ObjectInterface(const IBaseObject& other)
        : UnknownObject(other) { }
    explicit ObjectInterface(IBaseObject* other)
        : UnknownObject(other) { }
    explicit ObjectInterface(const UnknownObject& other)
        : UnknownObject(other.RetrieveInterface<Interface>() != nullptr ? other : UnknownObject()) {  }
    explicit ObjectInterface(UnknownObject&& other) noexcept
        : UnknownObject(other.RetrieveInterface<Interface>() != nullptr ? std::move(other) : UnknownObject()) {  }
   ObjectInterface(const ObjectInterface<Interface>& other)
        : UnknownObject(other) { }
   ObjectInterface(ObjectInterface<Interface>&& other) noexcept
        : UnknownObject(std::move(other)) { }
   ~ObjectInterface() override
    {
          UnknownObject::~UnknownObject();
    }
    ObjectInterface& operator=(const ObjectInterface<Interface>& other)
    {
          return UnknownObject::operator=(other);
    }
    Interface* operator->()
    {
          return GetInterface();
    }
    const Interface* operator->() const
    {
          return GetInterface();
    }
    Interface* GetInterface()
    {
          return RetrieveInterface<Interface>();
    }
    const Interface* GetInterface() const
    {
          return RetrieveInterface<Interface>();
    }
};

If it's any use, I'll also write the contents of the *.cpp:
// InterfaceUtils.cpp
//
#include "InterfaceUtils.h"

void UnknownObject::DeleteInterface(UnknownObject& obj)
{
    if (obj.IsNull())
        return;

    obj.SetNull();
}

UnknownObject::UnknownObject(const UnknownObject& from)
{
    if (auto* fromObj = from.GetPointer(); fromObj != nullptr)
    {
        SetPointer(const_cast<IBaseObject*>(fromObj));
        return;
    }

    SetPointer(nullptr);
}

UnknownObject::UnknownObject(UnknownObject&& from) noexcept
{
    SetPointer(from.GetPointer());
    from.SetPointer(nullptr);
}

UnknownObject::UnknownObject(const IBaseObject& from)
{
    auto* pObject = &from;
    SetPointer(const_cast<IBaseObject*>(pObject));
}

UnknownObject& UnknownObject::operator=(const UnknownObject& other)
{
    if (this == &other)
        return *this;

    if (auto* fromObj = other.GetPointer(); fromObj != nullptr)
        SetPointer(const_cast<IBaseObject*>(fromObj));
    else
        SetPointer(nullptr);

    return *this;
}

UnknownObject& UnknownObject::operator=(UnknownObject&& other) noexcept
{
    DeletePointer();

    SetPointer(other.GetPointer());
    other.SetPointer(nullptr);
    return *this;
}

void UnknownObject::SetNull()
{
    DeletePointer();
    m_pObject = nullptr;
}

The purpose of classes IBaseObject, UnknownObject and ObjectInterface<> is to be able to extend IBaseObject to different implementations, for example:
class ITestClass : public IBaseObject
{
public:
    ITestClass() : IBaseObject() {}
    ITestClass(const double& val)
       : IBaseObject(), m_Value(val) { }

    void SetValue(const double& val)
    {
        m_Value = val;
    }

    [[nodiscard]] double GetValue() const
    {
        return m_Value;
    }

    [[nodiscard]] virtual double ProcessValue() const = 0;

protected:
    double m_Value = 0.0;
};

//
// test class implementation returning m_Value^2 with ProcessValue
//
class TestClassSquareImpl : public ITestClass
{
public:
    ~TestClassSquareImpl() override
    {}

    TestClassSquareImpl(const double& val)
        : ITestClass(val) {}

    [[nodiscard]] double ProcessValue() const override
    {
        return m_Value * m_Value;
    }
};

//
// test class implementation returning sqrt(m_Value) with ProcessValue
//
class TestClassSqrtImpl : public ITestClass
{
public:
    ~TestClassSqrtImpl() override
    {}

    TestClassSqrtImpl(const double& val)
        : ITestClass(val)
    {
    }

    [[nodiscard]] double ProcessValue() const override
    {
        return sqrt(m_Value);
    }
};

Used as follows:
const double dataValue = 3.0;
const auto testObjSqr = TestClassSquareImpl(dataValue);
const auto testObjSqrt = TestClassSqrtImpl(dataValue);

const auto iTestObjSqr = ObjectInterface<ITestClass>(testObjSqr);
const auto iTestObjSqrt = ObjectInterface<ITestClass>(testObjSqrt);

std::cout << iTestObjSqr->ProcessValue() << "\n";    // out: 9.0
std::cout << iTestObjSqrt->ProcessValue() << "\n";   //  out: 1.73205080...

The question is: From my previous experience method UnknownObject::DeletePointer should delete raw m_pObject to avoid memory leaks, but when it does, an exception is thrown because a memory block of a derived instance is about to be freed. Is it safe to just leave the m_pObject pointer undeleted? Does it get deleted anyway after UnknownObject is destroyed?
inb4: I've already tried using std::unique_ptr and std::shared_ptr resulting in inability to access methods from derived implementations (e.g. TestClassSquareImpl::ProcessValue or ITestClass::GetValue).
Edit: The exception thrown by free is: Invalid address specified to RtlValidateHeap( 0000016F756B0000, 00000004B0AFF988 ). I first encountered it when running an example in gtest, but the same thing happens whenever the program goes out of scope, resulting in DeletePointer call.

A: I took @Frank 's advice to remove the const_cast's and implement a Clone method, with abstract declaration:
[[nodiscard]] virtual IBaseObject* Clone() const = 0;

in IBaseObject which must be implemented in derived classes:
[[nodiscard]] IBaseObject* Clone() const override
{
    return (new TestClassSquareImpl(*this));
}

and analogously in TestClassSqrtImpl. The Clone method was required in copy construction and copy-assignment (whenever a different interface with its own instance, or a different instance itself are accessed and copied, e.g.: SetPointer(fromObj->Clone());)
also, there was repeated deletion caused by
~ObjectInterface() override
{
    UnknownObject::~UnknownObject();
}

invoking its base destructor.
With these adjustments, the delete m_pObject doesn't throw.
It should be noted, that putting std::shared_ptr<IBaseObject> m_pObject; limits the scope of accessing any members to IBaseObject members. Correct me if I'm wrong, but in this case, m_Value would need to be defined as a field in IBaseObject
Your insights are really appreciated.
EDIT: I found out I was reinventing the wheel. Specialized STL casts can easily perform the downcasting in the test example:
#include <iostream>
#include <memory>
#include <cmath>

class Base
{
public:
    Base(const double value)
        : m_Value(value) {}

    double& GetValue()
    {
        return m_Value;
    }

    void SetValue(const double value)
    {
        m_Value = value;
    }

    [[nodiscard]] virtual double ProcessValue() const = 0;
protected:
    double m_Value{ 0.0 };
};

class DerivedA : public Base
{
public:
    DerivedA(const double value)
        : Base(value) {}

    [[nodiscard]] double ProcessValue() const override
    {
        return m_Value * m_Value + m_SpecializedValueForA;
    }

private:
    double m_SpecializedValueForA = 1.0;
};

class DerivedB : public Base
{
public:
    DerivedB(const double value)
        : Base(value) {}

    [[nodiscard]] double ProcessValue() const override
    {
        return sqrt(m_Value) + m_SpecializedValueForB;
    }

private:
    double m_SpecializedValueForB = -1.0;
};

enum class [[nodiscard]] ImplementationType
{
    A = 0,
    B = 1
};

class BaseWithSwitchableImplementation
{
public:

    BaseWithSwitchableImplementation(const double value, const ImplementationType type)
    {
        InternalSetAndInitImplementationWithValue(type, value);
    }

    [[nodiscard]] double ProcessValue() const
    {
        return m_Impl->ProcessValue();
    }

    void SetAndInitImplementationWithValue(const ImplementationType type, const double value)
    {
        if (type == m_ImplType)
            return; // nothing happens

        InternalSetAndInitImplementationWithValue(type, value);
    }

private:
    void InternalSetAndInitImplementationWithValue(const ImplementationType type, const double value)
    {
        m_ImplType = type;
        m_Impl = nullptr;
        if (type == ImplementationType::A)
        {
            const auto implAPtr = std::make_shared<DerivedA>(DerivedA(value));
            m_Impl = std::static_pointer_cast<Base>(implAPtr);
        }
        else if (type == ImplementationType::B)
        {
            const auto implBPtr = std::make_shared<DerivedB>(DerivedB(value));
            m_Impl = std::static_pointer_cast<Base>(implBPtr);
        }
        else
        {
            std::cout << "ERROR: Invalid ImplementationType!\n";
        }
    }

    std::shared_ptr<Base> m_Impl;
    ImplementationType m_ImplType;
};

int main()
{
    const double value = 3.0;
    const auto instanceA = std::make_shared<DerivedA>(DerivedA(value));
    const auto instanceB = std::make_shared<DerivedB>(DerivedB(value));

    const auto basePtrA = std::static_pointer_cast<Base>(instanceA);
    const auto basePtrB = std::static_pointer_cast<Base>(instanceB);

    std::cout << "basePtrA->ProcessValue() = " << basePtrA->ProcessValue() << "\n";
    std::cout << "basePtrB->ProcessValue() = " << basePtrB->ProcessValue() << "\n";

    const auto switchableImplA = BaseWithSwitchableImplementation(value, ImplementationType::A);
    const auto switchableImplB = BaseWithSwitchableImplementation(value, ImplementationType::B);

    std::cout << "switchableImplA.ProcessValue() = " << switchableImplA.ProcessValue() << "\n";
    std::cout << "switchableImplA.ProcessValue() = " << switchableImplB.ProcessValue() << "\n";

    auto switchableImplAToB = BaseWithSwitchableImplementation(value, ImplementationType::A);

    std::cout << "switchableImplAToB.ProcessValue() = " << switchableImplAToB.ProcessValue() << "\n";

    switchableImplAToB.SetAndInitImplementationWithValue(ImplementationType::B, value);

    std::cout << "switchableImplAToB.ProcessValue() = " << switchableImplAToB.ProcessValue() << "\n";

    return 0;
}

outputs:
basePtrA->ProcessValue() = 10
basePtrB->ProcessValue() = 0.732051
switchableImplA.ProcessValue() = 10
switchableImplA.ProcessValue() = 0.732051
switchableImplAToB.ProcessValue() = 10
switchableImplAToB.ProcessValue() = 0.732051

Which is exactly what I needed.


text:
Q: Rails before filter not redirecting Any reason why this before action would not redirect when @user is nil?
def set_user
  @user ||= User.find(params[:id])
  redirect_to "/errors/404" unless @user
end

I can actually see it redirecting in the log (pasted below).
Redirected to http://localhost:3000/errors/404

but instead of rendering that error page and routing away from the controller action, it completes the action and causes an error saying @user is nil.

A: The find method never returns nil. Instead, if a record with that ID doesn't exist, it throws an ActiveRecord::RecordNotFound error.
The easiest fix would be to use rescue_from:
class YourController < ApplicationController
  rescue_from ActiveRecord::RecordNotFound, with: :redirect_to_not_found
  # Other code

  private
  def set_user
    @user ||= User.find(params[:id])
  end

  def redirect_to_not_found
    redirect_to "/errors/404"
  end
end

Now, the redirect_to_not_found method will be called whenever a user isn't found.


text:
Q: Is this function square-integrable? Able to be Fourier expanded? I want to do a 3-dimensional Fourier series expansion on this function$$\frac{\cos (x) \cos (y) \cos (z)-\sin (x) \sin (y) \sin (z)}{\left[(a+\sin (y)+\cos (z))^2+(b+\cos (x)+\sin (z))^2+(c+\sin (x)+\cos (y))^2\right]^{\frac{3}{2}}}$$ when $a,b,c\in(0,2)$, for which the denominator is possible to vanish at some points.
Is it really square-integrable on $[0,2\pi]\times[0,2\pi]\times[0,2\pi]$? Is the Fourier series expansion well-defined here?
Thanks in advance!


text:
Q: Install application and espresso test apk and run on device I am very new to android and learning it for the first time.
On my android project, when I do
gradle build
gradle assembleDebugAndroidTest
I get the application and test apks
So I have these two questions
1) How do I install them on a specific connected device/emulator?
2) How do I start the tests to run on the device ?
Thanks very much.

A: Run adb devices to see your connected devices:
List of devices attached
emulator-5554   device
emulator-5556   device

Then, use ANDROID_SERIAL to specify the one you want.
To install:
ANDROID_SERIAL=emulator-5554 gradle installDebug

To run tests:
ANDROID_SERIAL=emulator-5554 gradle connectedAndroidTestDebug


text:
Q: Find out if a very complicated function is always $\le 0$ On $\mathbb{R}^4$ put coordinates $x1,y1,x2,y2$ and consider the function $c:\mathbb{R}^4\rightarrow \mathbb{R}$ defined in the following way:
f1 = 1/(2 (x1^2 + y1^2));
f2 = 2/((x1 + Sqrt[3] x2)^2 + (y1 + Sqrt[3] y2)^2);
n = 100000;
f = Log[Exp[n*f1] + Exp[n*f2]]/n;
g = (1/2)*Log[f];
c = -D[D[g, x1], x1] - D[D[g, y1], y1] - D[g, x2]^2 - D[g, y2]^2;

I need to find out if the function $c$ is always $\le 0$ or if there are points in which it's $>0$.
This seems like a very complicated task for Mathematica. I tried to use Solve, Reduce and even Plot3D specifying values of $x1$ and $y1$, but everything failed. Is there a better way to do so?
Thank you


text:
Q: Visual Studio Code and Cygwin is not debugging. And have a problem with gdb I just started coding(?), I think... I was setting up Visual Studio Code for C programming and I was using Cygwin.
I'm writing a single Hello World print code. Yes, I can compile it with Ctrl+Shift+B. But when I tried the debugging with F5, it's giving this error down there;
GNU gdb (GDB) (Cygwin 9.2-1) 9.2
Copyright (C) 2020 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.
This GDB was configured as "x86_64-pc-cygwin".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
    <http://www.gnu.org/software/gdb/documentation/>.

For help, type "help".
Type "apropos word" to search for commands related to "word".
Warning: Debuggee TargetArchitecture not detected, assuming x86_64.
=cmd-param-changed,param="pagination",value="off"
ERROR: Unable to start debugging. Unexpected GDB output from command "-exec-run". Error creating process /cygdrive/c/Users/EM&ES BİLGİSAYAR/cworkings/fckworld/fckworld.exe, (error 193).
The program 'c:\Users\EM&ES BİLGİSAYAR\cworkings\fckworld\fckworld.exe' has exited with code 42 (0x0000002a).

I was using gdb v10 but after 6 hours of researching on the internet, I downgraded it to V9. Nothing is changed except "error 2" to "error 193".


text:
Q: What is the relation of scattering, extinction and absorption cross sctions with scattering parameters? In optics and electromagnetics, they frequently calculate the extinction, scattering or absorption cross sections of a single particle (e.g. a sphere). Scattering cross section which is the ratio of the amplitude of the scattered electric field to the incident electric field.
On the other hand, they also calculate the scattering parameters (or reflection and transmission coefficients) for an array of spheres, which is defined as the ratio of the transmitted energy to the incident energy.
My question is how are these two related to each other? (scattering cross section  and scattering parameters)
For example, we know that those extinction, scattering or absorption cross sections are far field parameters (right?). Now, are the scattering parameters based on far-field too?Or total field?
What is the relation between transmitted field and scattered field? Does a small transmittance mean a large scattering cross section or a small scattering cross section?