text:
Q: LinkedHashMap complexity i have simple problem to find the first unique element in array A. But, what bothers me is the time complexity using different methods. I've tried this two methods so far.
First Method:
LinkedHashMap<Integer, List<Integer>> map = new LinkedHashMap<Integer, List<Integer>>();
for (int i = 0; i < A.length; i++)
{
    if (!map.containsKey(A[i]))
        map.put(A[i], new ArrayList<>());
    map.get(A[i]).add(i);
}

for (Map.Entry<Integer, List<Integer>> m : map.entrySet())
    if (m.getValue().size() == 1)
        return m.getKey();
return -1;

Second Method:
    for(int i=0; i< A.length; i++){
        boolean unique = true;
        nestedFor:for(int j=0; j< A.length; j++){
            if(i != j && A[i] == A[j]){
                unique = false;
                break nestedFor;
            }
        }
        if(unique)
            return A[i];
    }
    return -1;

Testing with array of 1000000 elements, the first method executes at ~2000ms, while the second at ~10ms. My question is: shouldn't the first method executes faster since its complexity is O(nLogn) compared to second method which complexity is O(n^2)? What am i missing here ? Below the test code:
    int[] n = new int[1000000];
    for (int i = 0; i < n.length; i++)
        n[i] = new Random().nextInt(2000000);

    long start = System.currentTimeMillis();
    firstUnique(n);
    System.err.println("Finished at: " + (System.currentTimeMillis() - start ) + "ms");

EDIT:
for (int i = 0; i < A.length; i++)
{
    if (!map.containsKey(A[i]))
        map.put(A[i], new ArrayList<>());
    map.get(A[i]).add(i);
}

Consumes 99% of execution time, while
for (Map.Entry<Integer, List<Integer>> m : map.entrySet())
    if (m.getValue().size() == 1)
        return m.getKey();

is always 1-3ms. So, yes filling the map is the most expensive operation.
What would you suggest as most efficient method for this kind of problem?

A: I suspect that you are not picking inputs which create "worst case" conditions for the second case.
For instance, if you construct the array such that all of the million elements have a duplicate (e.g. A[i] = 2 * i / A.length), then the second method is way, way slower than the first, since it has to check 10^12 combinations of elements.
You can make it a bit faster (roughly twice as fast) by changing the condition on the inner for loop to only check from j = i + 1, but 10^12 / 2 is still a pretty big number.
If you are simply picking random numbers to populate the array, there is a reasonable chance that the first element is unique, and a greater chance that one of the first and second elements is unique, etc. After a few elements, you'll reach near-certainty that the element is unique, so it will stop after a few iterations.

The 2 seconds taken for the first method is way too long. I can only think that you're not warming up your JIT correctly before the benchmark. But even without trying to do that, your first method only takes 40-50ms for me (dropping to 10-15ms after a few iterations).
Most of this time will be due to object creation - both in the autoboxing of the keys and values, and in the creation of the ArrayList instances.

A: Time complexity ignores coeffecients because often it is more useful to know how a function grows with increasing input sizes. Although your first function has a lower time complexity, at small input sizes, it will run much slower because you are making many ArrayList objects which is computationally expensive. Your second method however only uses array accesses which is much less expensive than instantiating an object.

A: Time complexity is meant to be understood in its asymptotic sense (i.e. as input sizes grow to googolplex), and nothing else.  If an algorithm has linear time complexity, that only means that there is some a,b such that executiontime (roughly !!!) = a * inputsize + b.  It says nothing about the actual magnitude of a and b, and two linear algorithms can still have massive performance differences because the magnitudes of their a/b differ vastly.
(Also, your example is a poor one because time complexity of an algorithm should take into account the complexity of all the underlying operations such as object creation and the like.  Others have hinted at that in their answers too.)

A: Consider using 2 sets instead:
public int returnFirstUnqiue(int[] a)
{
  final LinkedHashSet<Integer> uniqueValues = new LinkedHashSet<Integer>(a.length);
  final HashSet<Integer> dupValues = new HashSet<Integer>(a.length);

  for (int i : a)
  {
    final Integer obj = i;
    if (!dupValues.contains(obj))
    {
      if (!uniqueValues.add(obj))
      {
        uniqueValues.remove(obj);
        dupValues.add(obj);
      }
    }
  }

  if (!uniqueValues.isEmpty())
  {
    return uniqueValues.iterator().next();
  }
  return -1;
}

A: First as to why the benchmark isn't relevant:

*

*Even if we ignore inaccuracies caused by used method, GC etc., finding out that method 2 is faster on a million entries won't tell you anything about how it will perform on a billion of entries

*

*Big-O is a theoretical concept and has to be proved theoretically. Most a benchmark can do for you here is let you estimate the complexity, and that would be done not by comparing two methods on one input, but by comparing one method on multiple inputs, each an order of magnitude larger than the previous (and even then it's near impossible to draw any useful conclusions)

*Big-O is a worst-case complexity, but your random input is likely to be somewhere "in the middle" for the first method (map), while it will be far from worst case for the array - actually it has 50% chance of succeeding on first iteration, while the map has to be fully processed and will in average have about half a million entries

*

*the worst case for the "map" method would probably be all elements different but with equal hashcode (so you would need to read the whole list of added elements in each of the n iterations)

*the worst case for the "array" method is all elements being equal (need complete the whole nested iteration)

As to finding a good algorithm - you could use a Map<Integer, Boolean> instead of Map<Integer, List<Integer> since you only need to store the unique flag and not a list of values - add with True when you see the element first time, switch to False when you encounter a duplicity

*

*LinkedHashMap operations put, containsKey/get have big-O complexity O(n) (worst-case) making the whole algorithm O(n^2)

*However, the amortized complexity of put is O(1) (making amortized complexity of all insertions O(n)) and average complexity of get is constant (this depends on how well the hash function used works for the inputs given); unique value lookup is then O(n)

A: My observations:
Second method is much quicker because it is using Array with declared width. In First example there are changes of the size happenings.
Please try to define more accurate size of LinkedHashMap to set initial capacity equal to 1000000.
Next thing here is that Array is much simpler structure where GC is not trying to do anything. But when it comes to LinkedHashMap its more complex and cost of creating it and manipulating is far much complex in some cases than simple getting element at particular index from Array.


text:
Q: Angular 9 - Cannot find a differ supporting object 'getData() I am getting this error trying to bind my control to its data. Here is some relevant code.
Template.
<tree-control [nodes]="getData"></tree-control>

Component.
 public getData(): Observable<Array<any>> {
        const assets: any = this.service.get('url', headers);
        return assets;
    }

Anything I have found so far is not helping. Any idea what's wrong with my code?
Thanks

A: First of all, you assign a function (getData) to the nodes property. I assume you want to assign the data from getData to it instead.
Secondly, the call to this.service.get is probably not being executed. Reason for that is that you do not subscribe to, what I assume, is a http-call that returns an Observable.
To fix this, you can do the following:
export class Foo {
  nodeData: Observable<any>;

  constructor(
    private readonly service: YourService,
  ) {
    this.nodeData = this._getData();
  }

  private _getData() {
    return this.service.get(...);
  }
}

Inside your template you can then subscribe and unsubscribe to the data automatically by using the async pipe.
<tree-control [nodes]="nodeData | async"></tree-control>

For all that to work I assume your service.get method returns an Observable.

redpajama_set_name: RedPajamaStackExchange


text:
Q: JavaScript and wordpress (tried 2 solutions) I have a problem with linking javascript files to wordpress website. I would like to insert this code:

<!--====== Javascripts & Jquery ======-->
 <script src="js/vendor/jquery-3.2.1.min.js"></script>
 <script src="js/bootstrap.min.js"></script>
 <script src="js/owl.carousel.min.js"></script>
 <script src="js/masonry.pkgd.min.js"></script>
 <script src="js/main.js"></script>

I tried diffrent methods (adding code in functions.php, adding with a plugin) and none of them worked.
How enter this code correctly?
Thanks for your help!

A: You need to use the wp_enqueue_script function like this on your enqueue.php:
function themeslug_enqueue_script() {
   //add here all the plugins you wish to add
    wp_enqueue_script( 'masonry.js', 'masonry.pkgd.min.js', false );
    wp_enqueue_script( 'main.js', 'main.js', false );
}

add_action( 'wp_enqueue_scripts', 'themeslug_enqueue_script', 100);


text:
Q: Download xml file after login website automation The login website https://company.okta.com/login/default is sso authentication, once this is successful, it takes me to other page https://auth.p0rtal.com/login/callback then after few seconds it takes to the page https://clock.company.com/sitemap.xml.
i want to download the sitemap.xml from here, i.e right click on the page, click on save as and get the file.
below code works sucessfully to authenticate, I am new to python and selenium.
from selenium import webdriver
import yaml

conf = yaml.load(open('loginDetails.yml'))
myEmail = conf['user']['email']
myPassword = conf['user']['password']

driver = webdriver.Chrome('//Users/user.id/Desktop/website_login/chromedriver')

def login(url,usernameId, username, passwordId, password, submit_buttonId):
   driver.get(url)
   driver.find_element_by_id(usernameId).send_keys(username)
   driver.find_element_by_id(passwordId).send_keys(password)
   driver.find_element_by_id(submit_buttonId).click()
login("https://company.okta.com/login/default", "okta-signin-username", myEmail, "okta-signin-password", myPassword, "okta-signin-submit")

After this how do i automate the click and save as once authentication is success.
pyautogui?


text:
Q: PUT/POST/DELETE: 403 error forbidden + CORS error with AWS SAM I want to do a simple HTTP request but I get blocked by these errors :

zone.js:2969 OPTIONS http://127.0.0.1:3000/project/new 403 (FORBIDDEN)
Access to XMLHttpRequest at 'http://127.0.0.1:3000/project/new' from
  origin 'http://127.0.0.1:4200' has been blocked by CORS policy:
  Response to preflight request doesn't pass access control check: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource.

My SAM template :
AWSTemplateFormatVersion: '2010-09-09'
Transform: 'AWS::Serverless-2016-10-31'
Parameters:
   [my parameters]
Globals:
   Function:
       Runtime: nodejs6.10
       Handler: index.handler
       Timeout: 30
       AutoPublishAlias: live
       DeploymentPreference:
         Type: AllAtOnce
Resources:
  ## ApiGateway
  ApiGatewayRestApi:
    Type: 'AWS::Serverless::Api'
    Properties:
      Name: myAPI
      StageName: !Ref Stage
      Cors: "'*'"
      EndpointConfiguration: REGIONAL
      DefinitionBody:
        swagger: "2.0"
        info:
          version: "1.0"
          title: MyAPI
          host: !Ref Host
        schemes:
          - "https"
        consumes:
          - application/json
        produces:
          - application/json
        paths:
           put:
             responses: {}
             x-amazon-apigateway-integration:
                uri:
                  Fn::Join:
                    - ''
                    - - 'arn:aws:apigateway:'
                      - !Ref AWS::Region
                      - ':lambda:path/2015-03-31/functions/'
                      - !GetAtt CreateNewProjectFunction.Arn
                      - '/invocations'
                passthroughBehavior: "when_no_match"
                httpMethod: "PUT"
                type: "aws_proxy"

   ## Lambda functions
   CreateNewProjectFunction:
       Type: 'AWS::Serverless::Function'
       Properties:
         CodeUri: createNewProject/
         Handler: index.handler
         Runtime: nodejs6.10
         MemorySize: 128
         Timeout: 10
         Role: 'myRole'
         Events:
           CreateNewProject:
             Type: Api
             Properties:
               Path:  /project/{id}
               Method: PUT
               RestApiId: !Ref ApiGatewayRestApi
         Environment:
           Variables:
             tableName: !Ref ProjectsTableName
Outputs:
  Api:
    Description: 'API Gateway endpoint URL'
    Value: 'https://${ApiGatewayRestApi}.execute-api..../'

My Lambda :
exports.handler = (event, context, callback) => {
       var response = {
          "statusCode": 200,
          "headers": { "Access-Control-Allow-Origin": "*" },
          "body": "My lambda is OK"
       };
       return callback(null, response);
    }

PS: My URL is OK because I tested it with postman

A: Ok i find it.
We must to add a lambda function to template.yaml:
resLambdaLocalCorsStub:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.handler
      Runtime: nodejs6.10
      FunctionName: corsOptions
      CodeUri: corsOptions/
      Timeout: 30
      Events:
        loginOptions: # This block must be repeated for each endpoint that needs CORS support in SAM Local
          Type: Api
          Properties:
            RestApiId: !Ref ApiGatewayRestApi
            Path: /project/{id}
            Method: OPTIONS

and this in the apigateway
options:
                x-amazon-apigateway-integration:
                  type: mock
                  requestTemplates:
                    application/json: '{ "statusCode" : 200 }'
                  httpMethod: OPTIONS
                  responses:
                    default:
                      statusCode: 200
                      responseParameters:
                        method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key'"
                        method.response.header.Access-Control-Allow-Methods: "'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT'"
                        method.response.header.Access-Control-Allow-Origin:  "'*'"
                      responseTemplates:
                        application/json: '{}'
                responses:
                  '200':
                    headers:
                      Access-Control-Allow-Headers:
                        type: string
                      Access-Control-Allow-Methods:
                        type: string
                      Access-Control-Allow-Origin:
                        type: string

And to finish, create a lambda with :
"use strict";

// ***** This handler is used only in local development, for mocking the OPTIONS responses
// ***** This enables API Tests to pass CORS tests when running locally
exports.handler = (event, context, callback) => {
  callback(null, {
    statusCode: 200,
    headers: {
      "Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,Authorization,X-Api-Key",
      "Access-Control-Allow-Methods": "POST, GET, PUT, DELETE",
      "Access-Control-Allow-Origin": "*"
    },
    body: ""
  });
};


text:
Q: Shared state between CloudService instances Im creating a multiplayer game where one player hosts a game session and where others can join that session. The problem im having is how to make sure all players within a session has access to the current game state no matter what cloudservice instance theyve ended up connecting to.
Since this state has to be read pretty frequently, i dont want to put it in a database or storage since i want the fastest possible access time. Right now, its just a list of game sessions in memory within each instance. My first idea was to use the Azure cache functionality but as of this moment, its only available for cloudservice instances of the size Small and up, whereas my instances are extra small ones.
Is it possible to make sure that all joining players end up in the same instance as the hosting player by looking up what instance the hosting player created his game session and then get the endpoint for that instance and pass it back to the joining players to be used throughout the game session?
Or is there a better way to solve this?

A: Using Dedicated Cache and paying for Small instances is by far a better approach then to try doing the near-impossible task of trying to bring affinity to a load-balanced environment and also forcing a super bad architecture in place of a good one.
If cost is a concern, I suggest applying for Microsoft's Bizspark program that provides for 2 small instance for free per month.
http://www.microsoft.com/bizspark/


text:
Q: Prevent accessing files outside of given working directory I am trying to prevent the access on files outside of a given working directory.
My first attempt was to use chdir and chroot, but chroot can only be used by root users.
Is there any other possibility? I have heard something about another one, but I can't remember.
Perhaps a simple function to check if the path is outside of the working directory or second argument.
Some details about the program:

*

*shall be run on Linux

*simple shell programm without any interactive elements

*takes a directory argument, which is the working directory

Thanks for any advices.
EDIT:
After some research I found different aproachments, but I can't use any of them.

*

*pivot_root

*set_fs_root (linux kernel)

Is there any possibility to use that?
Perhaps there is a possibility to open a file which is contained by a given directory. So I call the function with the argument file path and the "root" path where to look.

A: I'm assuming that you're on a Linux/MacOSX platform. There are a couple of ways. One is to create a special user for your program who owns that directory, but doesn't have write permissions to anything else in the system*. The other option is to use a program like SELinux to only allow certain operations to the program, but that seems like overkill.
*: You must always give the user read permissions. How will your program run without read access to glibc?

A: You might want to look into a restricted shell; I think most of the common shells have options for a restricted mode that disables cd, prevents changes to certain environment variables, and some other things. For pdksh, it would be /bin/ksh -r. The option differ for other shells, though, so read the appropriate manual page.


text:
Q: fluentd cannot connect to elasticsearch I run the stack EFK through docker-compose, the stack starts, kibana and elasticsearch go through the initial setup. fluentd throws the following error at startup:
"The client is unable to verify that the server is Elasticsearch. Some functionality may not be compatible if the server is running an unsupported product."

kibana 8.2.0
elasticsearch 8.2.0
Maybe fluent can't log in over https, where to look for the problem?
Dockerfile fluentd:
FROM fluentd:latest

# Use root account to use apk
USER root

# below RUN includes plugin as examples elasticsearch is not required
# you may customize including plugins as you wish
RUN apk add --no-cache --update --virtual .build-deps \
        sudo build-base ruby-dev \
 && sudo gem install fluent-plugin-elasticsearch \
 && sudo gem sources --clear-all \
 && apk del .build-deps \
 && rm -rf /tmp/* /var/tmp/* /usr/lib/ruby/gems/*/cache/*.gem

COPY conf/fluent.conf /fluentd/etc/
COPY entrypoint.sh /bin/

USER fluent

fluentd.conf
<source>
  @type forward
  port 24224
  bind 0.0.0.0
</source>

<match *.**>
  @type elasticsearch
  host elasticsearch
  port 9200
  user fluent
  password 6M9eXThhypVjV8h
  logstash_format true
  logstash_prefix fluentd
  logstash_dateformat %Y%m%d
</match>

the username and password for fluent are created in kibana

A: The problem was solved by downgrading the EFK version and changing the Dockerfile
Dockerfile
FROM fluent/fluentd:v1.12.0-debian-1.0
USER root
RUN gem uninstall -I elasticsearch && gem install elasticsearch -v 7.17.0
RUN ["gem", "install", "fluent-plugin-elasticsearch", "--no-document", "--version", "5.0.3"]
USER fluent

docker-compose.yml
## EFK Stack
  fluentd:
    build: ./fluentd
    volumes:
      - ./fluentd/conf/fluent.conf:/fluentd/etc/fluent.conf
    ports:
      - "24224:24224"
      - "24224:24224/udp"
    depends_on:
      - elasticsearch
      - kibana
    networks:
      - efk

  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.13.1
    container_name: elasticsearch
    environment:
      - "discovery.type=single-node"
    expose:
      - "9200"
    ports:
      - "9200:9200"
    networks:
      - efk

  kibana:
    image: docker.elastic.co/kibana/kibana:7.13.1
    ports:
      - "5601:5601"
    depends_on:
      - elasticsearch
    networks:
      - efk

networks:
  efk:
    driver: bridge

fluent.conf
<source>
  @type forward
  port 24224
  bind 0.0.0.0
</source>

<match *.**>
  @type copy

  <store>
    @type elasticsearch
    host elasticsearch
    port 9200
    logstash_format true
    logstash_prefix fluentd
    logstash_dateformat %Y%m%d
    include_tag_key true
    type_name access_log
    tag_key @log_name
    flush_interval 1s
  </store>

  <store>
    @type stdout
  </store>
</match>


text:
Q: Database is not updated ADO.Net I have a customer class in my program and a customer table in an access database, i want to update customer balance in the database by given value.
I wrote all statements which seems to be correct, but unfortunately the database isn't affected.
This is the method which I use to update the DB
thanks in advance
public static bool UpdateCustomer(Customer customer)
{
   bool EditSucceeded = false;
   string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\GarageProTuning.accdb;";

   using (OleDbConnection _con = new OleDbConnection(connectionString))
   {
      string commandText = "UPDATE Customer SET Balance=@Balance WHERE CustomerID=@CustomerID";

      using (OleDbCommand _cmd = new OleDbCommand(commandText, _con))
      {
         _cmd.Parameters.AddWithValue("@CustomerID", customer.CustomerID);
         _cmd.Parameters.AddWithValue("@Balance", customer.Balance);
         _con.Open();
         int rowsAffected = _cmd.ExecuteNonQuery();
         if (rowsAffected > 0)
            EditSucceeded = true;
         _con.Close();
      }
   }
   return EditSucceeded;
}

A: You have:
public static bool UpdateCustomer(Customer customer)
{
   bool EditSucceeded = false;
   string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\GarageProTuning.accdb;";

   using (OleDbConnection _con = new OleDbConnection(connectionString))
   {
      string commandText = "UPDATE Customer SET Balance=@Balance WHERE CustomerID=@CustomerID";

      using (OleDbCommand _cmd = new OleDbCommand(commandText, _con))
      {
         _cmd.Parameters.AddWithValue("@CustomerID", customer.CustomerID);
         _cmd.Parameters.AddWithValue("@Balance", customer.Balance);
         _con.Open();
         int rowsAffected = _cmd.ExecuteNonQuery();
         if (rowsAffected > 0)
            EditSucceeded = true;
         _con.Close();
      }
   }
   return EditSucceeded;
}

What you need is:
public static bool UpdateCustomer(Customer customer)
{
   bool EditSucceeded = false;
   string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\GarageProTuning.accdb;";

   using (OleDbConnection _con = new OleDbConnection(connectionString))
   {
      string commandText = "UPDATE Customer SET Balance=@Balance WHERE CustomerID=@CustomerID";

      using (OleDbCommand _cmd = new OleDbCommand(commandText, _con))
      {
         _cmd.Parameters.AddWithValue("@Balance", customer.Balance);  // Explanation below
         _cmd.Parameters.AddWithValue("@CustomerID", customer.CustomerID);
         _con.Open();
         int rowsAffected = _cmd.ExecuteNonQuery();
         if (rowsAffected > 0)
            EditSucceeded = true;
         _con.Close();
      }
   }
   return EditSucceeded;
}

OleDbCommand.Parameters are a very particular animal when it comes to how they are added/processed.  From the documentation I linked:

Therefore, the order in which OleDbParameter objects are added to the OleDbParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text.

In a nutshell, you must add your parameters in the same order that they appear in your command text.


text:
Q: The inverse image of the intersection of two subsets of the codomain, is equal to the intersection between the inverse images of that subsets I have the following:
$f: A \rightarrow B \\ X, X' \subseteq A \\ Y,Y' \subseteq B$
I have to prove that:
$$f^{-1}(Y \cap Y') = f^{-1}(Y) \cap f^{-1}(Y')$$
What I have done is the following.
We have to prove actually two propositions:
$\Rightarrow ) \quad f^{-1}(Y \cap Y') \subseteq f^{-1}(Y) \cap f^{-1}(Y') \\
\Leftarrow ) \quad f^{-1}(Y) \cap f^{-1}(Y') \subseteq f^{-1}(Y \cap Y') $
I have tried to prove the first $(\Rightarrow)$:
what we have to demonstrate is
$\forall z \in f^{-1}(Y \cap Y') \Rightarrow z \in f^{-1}(Y) \cap f^{-1}(Y')$
hence, I consider an element $z$
$z \in f^{-1}(Y \cap Y') \Rightarrow z = f^{-1}(y) \mbox{ with } y \in Y \cap Y' \mbox{ i.e. } y \in Y \mbox{ and } y \in Y'$
since  $z = f^{-1}(y) \mbox{ with } y \in Y$ it means that $z = f^{-1}(y) \in f^{-1}(Y)$
and in simiar way,
since $z = f^{-1}(y) \mbox{ with } y \in Y'$ it means that $z = f^{-1}(y) \in f^{-1}(Y')$
therefore
$z \in f^{-1}(Y) \cap f^{-1}(Y')$
I think that is correct,
but, I have some problems in proving the converse.
Please, can you give me any suggestions? Many thanks!

A: Let
$$z\in f^{-1}(Y)\cap f^{-1}(Y')\Rightarrow z\in f^{-1}(Y)\text{ and }z\in f^{-1}(Y')$$
that is, by definition, $f(z)\in Y$ and $f(z)\in Y'$, thus
$$f(z)\in Y\cap Y'\Rightarrow z\in f^{-1}(Y\cap Y')$$
Notice that with this approach, you can reverse this argument to show the other implication.

A: What you have done so far is correct.
In case of second implication,
Let $z \in f^{-1}(Y) \cap f^{-1}(Y')$. This implies that $z$ is in inverse image of both $Y$ and $Y'$. Hence $f(z) \in Y \cap Y' \Rightarrow z \in f^{-1}(Y \cap Y').$


text:
Q: ASP.NET identify client device We are building an online ASP.NET time capture system which will be accessed by KIOSKs. The kisoks will be installed in multiple locations.
Some how we need to identify from which Kiosks the request is coming from so that we can can find the Kiosk details from persistent database.
The application will be hosted on internet. Could anyone suggest me how is it possible to identify each Kiosk in stateless?
1. I've already looked at permanent cookies.
2. IP range (could be tricky, given group of kiosk might go via specific firewall).
Any other suggestions will be appreciated.

A: If you have complete control over the kiosks, then the easiest thing to do would be to add a unique ID of some sort to the user-agent registry key. If you don't have complete control, then a permanent cookie might be your only route. If you go with the permanent cookie you could require the client to enter some sort of password/code/id to register the machine before populating the cookie. That would help identify the clients and also prevent unauthorized computers from accessing the system.


text:
Q: Vercel not deploying because of "@"? I've been seeking for a while, and, maybe it's because of how I made my researches, but nevermind I'll ask it anyway.
I'm working on a react.js/next environnement, then I worked on a library I had to customize, which is in Typescript. No problem to handle that, but when I deployed the final version on Vercel, I had  3 errors.
./helper/react-gutenberg/dist/blocks/common/audio.js
    13:06:35.878    Module not found: Can't resolve '@mantine/core' in '/vercel/path0/helper/react-gutenberg/dist/blocks/common'
    13:06:35.879
    13:06:35.879    Import trace for requested module:
    13:06:35.880    ./helper/react-gutenberg/dist/blocks/common/audio.js
    13:06:35.880    ./helper/react-gutenberg/dist/blocks/common/index.js
    13:06:35.881    ./helper/react-gutenberg/dist/blocks/index.js
    13:06:35.881    ./helper/react-gutenberg/dist/index.js
    13:06:35.881    ./helper/react-gutenberg/index.js
    13:06:35.881
    13:06:35.881    ./helper/react-gutenberg/dist/blocks/common/audio.js
    13:06:35.881    Module not found: Can't resolve '@material-ui/icons/ArrowRightAlt' in '/vercel/path0/helper/react-gutenberg/dist/blocks/common'
    13:06:35.881
    13:06:35.881    Import trace for requested module:
    13:06:35.881    ./helper/react-gutenberg/dist/blocks/common/audio.js
    13:06:35.881    ./helper/react-gutenberg/dist/blocks/common/index.js
    13:06:35.881    ./helper/react-gutenberg/dist/blocks/index.js
    13:06:35.881    ./helper/react-gutenberg/dist/index.js
    13:06:35.881    ./helper/react-gutenberg/index.js
    13:06:35.881
    13:06:35.882    ./helper/react-gutenberg/dist/blocks/common/audio.js
    13:06:35.882    Module not found: Can't resolve '@mantine/hooks' in '/vercel/path0/helper/react-gutenberg/dist/blocks/common'

The point seems to be that there is an "@" in the namespace, and when i build the file with tsc, the js file isn't handling this @ when it requires it. Thanks a lot for your help
I tried to deploy on Vercel but it didn't work at all, failed to compile.


text:
Q: Android room autoincrement do not working I try to integrate room in my project. I use standard room autorGenerate = true field bu it's not working. I add new object to db and then get from db. All fileds product_id is null somehow. All other fileds that I create on Product creation have values.It seems to me
 @PrimaryKey(autoGenerate = true)
        public Integer object_id;

do not generate anything. Why so?
@Entity
public class Prodcut {

    @PrimaryKey(autoGenerate = true)
    public Integer product_id;

    @ColumnInfo(name = "name")
    public String name;

    @ColumnInfo(name = "is_cloud")
    public Integer is_cloud;

    @ColumnInfo(name = "user_id")
    public Integer user_id;
    }

A: Please use int instead of Integer.


text:
Q: Examples of proofs that are easiest by double counting. What's an example of a proof that's easiest to do by double counting? I've read examples of double counting on Brilliant and Wikipedia, but most of claims seem to be more easily provable with direct proofs. I suspect I'm missing some of the rationale behind double counting as a proof strategy.
Does anyone know of some simple proofs that are easiest with double counting and harder with other proof techniques?


text:
Q: Adding WMode="Opaque" with a Simple Replace in Tumblr My knowledge of Javascript is pretty basic, so maybe the solution is obvious here. I've been trying to add wmode="opaque" to the Flash elements, specifically the audio players, rendered by Tumblr. I have a fixed header and the Flash elements overlap on scroll on Windows and Linux. The Javascript was supplied by a theme designer who is using the same hack in his own theme.
Any help would be very much appreciated. I'm at the end of my patience on this one.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>Escapology</title>
   <meta name="Robots" content="index,follow" />
   <meta name="description" content="This be a webjournalblog dedicated to experimental post-noise-ambivalent-pseudo-classical rock everywhere." />
  <link rel="shortcut icon" href="http://static.tumblr.com/txv6iau/xVhlhbgf4/favicon.ico"/>

<meta http-equiv="X-UA-Compatible" content="IE=8" />

AboutWhat is this place and who are these people? Get educated.

FeedFeeling hungry? Or maybe you just can't be arsed to visit us.

ArchiveGo ahead and dive into our early work. Before we sold out.

 {block:IndexPage}

Hello

This be a webjournalblog dedicated to experimental post-noise-ambivalent-pseudo-classical rock everywhere.

Enjoy. Or leave.

Submissions

Something we should hear? Shoot Andrew an email. He's a man of the people.

Writing

Articles

Interviews

Updates

Music

Ambient

Bass

Brass

Electronic

Live

Melancholy

Minimal

Post Rock

Strings

Vocals

{/block:IndexPage}

              {block:Posts}
              {block:IndexPage}

By {PostAuthorTitle} on {MonthNumberWithZero}.{DayOfMonthWithZero}.{ShortYear}

{block:HasTags}Buzzwords: {block:Tags}{Tag} {/block:Tags}
{/block:HasTags}

{/block:IndexPage}

                {block:Text}

                        {block:Title}

{Title}

                        {/block:Title}

{Body}

                        {block:More}
    Read On...
{/block:More}

                {/block:Text}

                {block:Photoset}

                        {block:Caption}

{Caption}

                        {/block:Caption}

                {/block:Photoset}

                           {block:HighRes}

                        {block:Caption}

{Caption}

                        {/block:Caption}

                {/block:HighRes}

                {block:Quote}

{Quote}

                        {block:Source}

- {Source}

                        {/block:Source}

                {/block:Quote}

                {block:Link}

{Name} »

                        {block:Description}

{Description}

                        {/block:Description}

                {/block:Link}

                {block:Chat}

                        {block:Title}

{Title}

                        {/block:Title}

                            {block:Lines}

                                    {block:Label}
                                        {Label}
                                    {/block:Label}

                                    {Line}

                            {/block:Lines}

                {/block:Chat}

               {block:Audio}

                   {block:AlbumArt}

{/block:AlbumArt}

                  {block:AlbumArt}
{/block:AlbumArt}

{AudioPlayerBlack}

{block:AlbumArt}
{/block:AlbumArt}
                                        {block:Caption}

{Caption}

                        {/block:Caption}

               {/block:Audio}

                {block:Video}

{Video-400}

                        {block:Caption}

{Caption}

                        {/block:Caption}

                {/block:Video}

                 {block:RebloggedFrom}
- via {ReblogParentName}
{/block:RebloggedFrom}

            {/block:Posts}

        {block:IndexPage}{block:Pagination}

{block:PreviousPage}
« Go Back{/block:PreviousPage}

                 {block:NextPage}
                 Onward »

            {/block:NextPage}
        {/block:Pagination}
        {/block:IndexPage}

A: I spent many an hour figuring this one myself, and it's still not a 100%. Even so, I'll share what I know.
I'm about to release this theme, Essentia, on the envato marketplace and wanted to change the audio player from the default rectangular bar to something that resembles a circular button. Poking around, I found that the following code works quite well (which looks quite similar to your jquery code when I think about it):
if(post.hasClass('audio')) {
var parent = post.find('.audio_player');
var html = parent.html();
var newEmbed = html.replace(/<embed\s/i, "<embed wmode='opaque' ");
parent.html(newEmbed);
}

BUT
You'll only find this code working when using {AudioPlayerWhite} in the Tumblr syntax - Don't ask me why, but I've spent many hour trying to fix it to no avail.
Lemme know if it helps :)

A: I tried many ways too, then I chained methods together in this particular order. This seems to fix the issue
$('embed')
 .css('display','none')
 .attr('wmode', 'transparent')
 .css('display','block');


text:
Q: How to share data between an application (console or service) and a web service? I have the following situation :

*

*A windows service that crunches data and maintains a data structure representing statistics and such

*A simple REST web service (asp.net webapi)
I would like so that given a web request handled by the mvc.net webapi controller, the data returned is provided by the windows service.
Simply put, I would like to avoid having to use a database only to pass data from the windows service to the web application controller.
The reason is for performance, since it is live data and quite a big amount of it so I want to avoid the bottleneck of real-time database read and writes...
Is that possible?
Is Redis the only option?
I would surely appreciate a more '.NET' way of caching data between applications than having to run an Ubuntu machine thru VirtualBox with a Vagrant setup...
Thanks!

A: This feels almost ideally what MSMQ was designed for.

A: I finally went the Redis way, thanks to Mati Cicero,
it looks pretty well suited to real-time needs.
I have to use ServiceStack since I am in C#, my only disappointment is that setup could have been simpler (Ubuntu server for Redis, running in a VirtualBox) .
And I hope this setup can hold in a production environment(Win Server for C# parts + Linux Server for Redis)...

A: Since the data is recoverable you can try a fast non-persistent NoSQL store.
Even better would be no shared data at all. Make the web service call into the Windows Server to request just the data that it needs right now. Maintaining shared state (for example in a database) is burdensome. If possible I'd avoid that entirely.
A very fast IPC mechanism would be WCF over named pipes.


text:
Q: Set an active class for magento2.1 wishlist I can add product to my Wish-list on product page Magnnto2.1, but after refresh the product page,I want to see this product already added to wish-list by changing color of wish-list icon (set active class for example)
what should i do if anyone idea share with me?

A: Replace content of

/app/design/frontend/Dapl/demo/Magento_Wishlist/templates/catalog/product/view/addto/wishlist.phtml

with
    <?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

/** @var \Magento\Wishlist\Block\Catalog\Product\View\AddTo\Wishlist $block */
?>
<?php if ($block->isWishListAllowed()) : ?>
    <?php $_product = $block->getProduct(); ?>
    <?php $isAdded = $this->helper('Magento\Wishlist\Helper\Data')->getWishlistItemCollection()->addFieldToFilter('product_id', $_product->getId())->count(); ?>
    <?php if($isAdded): ?>
    <?= $block->escapeHtml(__('Added to Wish List')) ?>
    <?php else: ?>
       <a href="#" class="action towishlist" data-post='<?= /* @noEscape */ $block->getWishlistParams() ?>' data-action="add-to-wishlist"><?= $block->escapeHtml(__('Add to Wish List')) ?>
    <?php endif; ?>
<?php endif; ?>

then add below code to your custom css file

.product-social-links .action.towishlist.already-added{color: red;}


text:
Q: Tracing with IDA: how to get around the 4 hardware breakpoints limitation? basically, the code I'm trying to disassemble has some function works like this:
counter=0;
do
{
    counter++;
    *dword*(2A2A2A+counter*64) = v;
}
while (counter<4096)

which created a good number of dups of v.
One or some of them is then accessed later in some fiddling way that I can't work out by reading the assembly, thus I came to the idea of tracing read on those points. However since read points are hardware breakpoints, I can't really set more than 4 of them active at one time - so how do i trace down which routine accessed those "v"s?
any suggestion is deeply appreciated.

A: IDA 6.3 adds page-level breakpoints which allow you to monitor any memory range for access.


text:
Q: How to avoid repeating a similar code several times? I'm doing a Subway restaurant like console application. It's heavily dependent on loops, and there's a specific kind of loop I've repeated lots of times.
Basically, I write the options, then I make the cursor be over the initial option. Whatever option the user presses enter while the cursor is over it, is the selected option.
Here's the first part of the code (it's kinda big, but that's why I'm asking here after all):
static int Row = 0; //To set the row of the cursor

    static void Menu()
    {
        Console.WriteLine("Hi, welcome to Subway!"); //Line 0
        Console.WriteLine(); //Line 1

        //Bread Selection
        string[] breadOptions =
        {
                        "Hearty Italian",       //Element 0
                        "9-Grain Honey Oat",    //Element 1
                        "Jalapeno Cheese",      //Element 2
                        "Monterey Cheddar",     //Element 3
                        "Parmesan Oregano",     //Element 4
                        "Roasted Garlic",       //Element 5
                        "Rosemary & Sea Salt",  //Element 6
                        "Rye Bread",            //Element 7
                        "Gluten-Free Bread",    //Element 8
        };

        Console.WriteLine("Choose you bread!"); //Line 2
        Console.WriteLine("[ ]" + breadOptions[0]); //Line 3
        Console.WriteLine("[ ]" + breadOptions[1]); //Line 4
        Console.WriteLine("[ ]" + breadOptions[2]); //Line 5
        Console.WriteLine("[ ]" + breadOptions[3]); //Line 6
        Console.WriteLine("[ ]" + breadOptions[4]); //Line 7
        Console.WriteLine("[ ]" + breadOptions[5]); //Line 8
        Console.WriteLine("[ ]" + breadOptions[6]); //Line 9
        Console.WriteLine("[ ]" + breadOptions[7]); //Line 10
        Console.WriteLine("[ ]" + breadOptions[8]); //Line 11

        Row = 3; //set the row to the first bread option
        int currentBread = 0; //a couter to keep track of the bread
        ConsoleKeyInfo breadKey = new ConsoleKeyInfo();

        do
        {   //Loop that goes with the cursor through the menu items
            for (Row = 3; Row < breadOptions.Length + 3; Row++)
            {
                //Highlight the current bread with the cursor in the box
                if (currentBread == Row - 3)
                    Console.SetCursorPosition(1, Row);
            }

            //reads the key
            breadKey = Console.ReadKey();
            switch (breadKey.Key)
            {
                case ConsoleKey.DownArrow:
                    //if the current item is the last one in the array, reset the counter.
                    if (currentBread == breadOptions.Length - 1)
                        //-1 because currentBread follows the array, and array starts at 0
                        //but the array lengh doensn't start at 0. 0 is an empty array
                        currentBread = 0;
                    //otherwise, add one to the counter
                    else
                        currentBread++;
                    break;

                case ConsoleKey.UpArrow:
                    //if the user presses Up in the first option, it goes to the last
                    if (currentBread == 0)
                        currentBread = breadOptions.Length - 1;
                    //otherwise, remove one from the counter
                    else
                        currentBread--;
                    break;
            }

        }
        //keep looping until the user presses enter
        while (breadKey.Key != ConsoleKey.Enter);

        Console.SetCursorPosition(0, 12); //set the cursor back to the next line after the last Console.WriteLine

        //make a string to store the selected bread and make it be the selected bread
        string bread = breadOptions[currentBread];

And, this do-while loop is repeated again several times, here's another example:
//Bread Size
        string[] sizeOptions = { "6-inches", "Footlong"};

        Console.WriteLine(); //Line 12
        Console.WriteLine("Choose a bread size."); //Line 13
        Console.WriteLine("[ ]" + sizeOptions[0]); //Line 14
        Console.WriteLine("[ ]" + sizeOptions[1]); //Line 15

        Row = 14;
        int currentSize = 0;
        ConsoleKeyInfo sizeKey = new ConsoleKeyInfo();

        do
        {
            for (Row = 14; Row < sizeOptions.Length + 14; Row++)
            {
                if (currentSize == Row - 14)
                    Console.SetCursorPosition(1, Row);
            }

            sizeKey = Console.ReadKey();
            switch (sizeKey.Key)
            {
                case ConsoleKey.DownArrow:
                    if (currentSize == sizeOptions.Length - 1)
                        currentSize = 0;
                    else
                        currentSize++;
                    break;
                case ConsoleKey.UpArrow:
                    if (currentSize == 0)
                        currentSize = sizeOptions.Length - 1;
                    else
                        currentSize--;
                    break;
            }
        } while (sizeKey.Key != ConsoleKey.Enter);

        Console.SetCursorPosition(0, 16);

        string size = sizeOptions[currentSize];

I was wondering if there's a way to not write this loop every time I need to choose an option.

A: You can use a method to do this:
    int GetOption(int startRow, string[] options)
    {
        int currentOption = 0;
        ConsoleKeyInfo sizeKey = new ConsoleKeyInfo();

        do
        {
            for (int i = startRow; i < options.Length + startRow; i++)
            {
                if (currentOption == i - startRow)
                    Console.SetCursorPosition(1, i);
            }

            sizeKey = Console.ReadKey();
            switch (sizeKey.Key)
            {
                case ConsoleKey.DownArrow:
                    if (currentOption == options.Length - 1)
                        currentOption = 0;
                    else
                        currentOption++;
                    break;
                case ConsoleKey.UpArrow:
                    if (currentOption == 0)
                        currentOption = options.Length - 1;
                    else
                        currentOption--;
                    break;
            }
        } while (sizeKey.Key != ConsoleKey.Enter);

        return currentOption;
    }

Usage:
    string[] sizeOptions = { "6-inches", "Footlong"};
    Console.WriteLine(); //Line 12
    Console.WriteLine("Choose a bread size."); //Line 13
    Console.WriteLine("[ ]" + sizeOptions[0]); //Line 14
    Console.WriteLine("[ ]" + sizeOptions[1]); //Line 15

    Row = 14;
    int currentSize = GetOption(Row, sizeOptions);
    Console.SetCursorPosition(0, 16);
    string size = sizeOptions[currentSize];

I can't test it right now, but I hope it helps you!

A: Take one of the chunks of the code which you want to re-use and move it into a new method with no parameters. Like the bit where you write out the options.
Ask yourself what is in that method which the other scenario doesn't want to be like that. In the list of options scenario, the thing which varies from one place to another is the actual list of things. So we need to turn that thing into a variable (so named because the value can vary). Specifically, if you make the list of things a parameter to the method, then you can call that method from each different place, passing the relevant list.
Note that by doing this, it can cause you other problems to overcome. For example, where you print the list, you are currently hard coding each index that you want to print, so you need to find a more flexible way of doing that - a way of listing all the items in a collection, regardless how many there are. Try looking up foreach as a way of doing this.
Moving code from one place to another to make it better is called refactoring, and is a really important skill to learn in software development. I have only shown one of the kinds of problems that occurs when refactoring, but it's a big topic. Hope this helps.


text:
Q: Use a validator for a QListWidgetItem I am using a QListWidget whose items can be edited by double-clicking (with item.setFlags(item.flags() | Qt.ItemIsEditable)). I would like to check if the name entered by the user is correct (I would check if it corresponds to a correct variable name using isidentifier() and if it isn't a Python keyword with iskeyword()). I'd rather not use a QListView because it would require a lot of changes in my code.
Below is an example:
from PyQt5.QtWidgets import QListWidget, QListWidgetItem
from PyQt5.QtCore import Qt

class MyListWidget(QListWidget):
    def __init__(self):
        super().__init__()

        item1 = QListWidgetItem('item 1')
        item2 = QListWidgetItem('item 2')

        item1.setFlags(item1.flags() | Qt.ItemIsEditable)
        item2.setFlags(item2.flags() | Qt.ItemIsEditable)

        self.addItem(item1)
        self.addItem(item2)

        self.show()

if __name__ == '__main__':
    from PyQt5.QtWidgets import QApplication
    import sys

    app = QApplication(sys.argv)
    win = MyListWidget()
    sys.exit(app.exec_())

The items can be changed to any value, even a string containing special characters or an empty string.


text:
Q: How to replace carriage return (CR) and not line feed (LF) on Nifi I have a text file to ingest but, some of the text fields os this file are coming with CR char in it. The official line break is LF so I figured I could replace all CR and normalize to files.
But I'm triyng to do this for a week now with no good results.
What I tried so far is using replaceText processor with several configurations. Line by line, entire text, already tried "\r", "\\r", "[\r]" but nothing seemed to work.
Do you have any suggestions or experience to share?

A: You can achieve same with ExecuteScript processor, where you can implement your custom cleaning logic with less limitations. Refer below python snippet to start with,
from org.apache.commons.io import IOUtils
from java.nio.charset import StandardCharsets
from org.apache.nifi.processor.io import StreamCallback
from org.apache.nifi.processors.script import ExecuteScript
from org.python.core.util.FileUtil import wrap
from io import StringIO
import re

# Define a subclass of StreamCallback for use in session.write()
class PyStreamCallback(StreamCallback):
    def __init__(self):
        pass

    def process(self, inputStream, outputStream):
        with wrap(inputStream) as f:
            lines = f.readlines()
            outer_new_value_list = []
            is_header_row = True
            for row in lines:
                if is_header_row:
                    is_header_row = False
                    outer_new_value_list.append(row)
                    continue
                char_list = list(row.strip())
                for position, char in enumerate(char_list):
                    // put your custom cleaning logic here
                    if char == '\\' or char == '^' or char == '"'  or char == '~' :
                        replace_char = '\\' + char
                        char_list[position] = replace_char

                new_data_line = ''.join([str(elem) for elem in char_list])
                outer_new_value_list.append(new_data_line + '\r\n')

            with wrap(outputStream, 'w') as filehandle:
                filehandle.writelines("%s" % line for line in outer_new_value_list)

# end class
flowFile = session.get()
if (flowFile != None):
    flowFile = session.write(flowFile, PyStreamCallback())
    session.transfer(flowFile, ExecuteScript.REL_SUCCESS)
# implicit return at the end

A: After a week of attempts, i was able to replace the carriage return in my file with a simple replacetext processor. Here is the print for you to try if needed.


text:
Q: UIWebView video should fill the frame size mentioned I am using uiwebview to display inline video using the following code :
UIWebView *webview =[[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 320)];
[webview setOpaque:NO];
webview.backgroundColor = [UIColor clearColor];

NSString *Str = [NSString stringWithFormat:@"<video controls id='myVideo' width='%fpx' height='%fpx' float:left webkit-playsinline preload=\"auto\"> <source src=\"%@\"> </video>",webview.frame.size.width,webview.frame.size.height,videoPath];
[webview loadHTMLString:Str baseURL:nil];
webview.allowsInlineMediaPlayback=YES;
webview.scrollView.scrollEnabled = NO;
webview.mediaPlaybackRequiresUserAction=NO;
[self addSubview:webview];

Video is playing inline, but the problem is video is getting displayed in rectangle and there is a black space on either side of the video please find attached image

Can anyone suggest me what is going wrong here, i need to display the video in full size (provide frame size) so that there is no spacing on either side.


text:
Q: Constructor of subclass does not compile I have an abstract class called Person and a subclass that extends Person called Employee. When i try to compile i get a constructor error. How do i write the constructor in the Employee class so it compile? Please let me know if u need more information on the issue. Thank you.
public abstract class Person {    //Person abstract class
   public String firstName;
   public String lastName;
   public char gender;

   public Person(String fname, String lname, char g) { //constructor
      firstName = fname;
      lastName = lname;
      gender = g;
   }
   public abstract void setDefaults();
}

public class Employee extends Person {   //Employee class that extends Person

   public Employee() {    //i thought super(); might solve the problem, but it didnt.
      super();
   }
   public void setDefaults() {}
}

A: You forgot to pass parameters to your super() declaration. Your abstract constructor needs parameters. Parameters in super() needs to be the same as your parent constructor. The only way you could use super() without any parameters would be if your parent constructor doesn't have any parameters at all.
public abstract class Person {    //Person abstract class
   public String firstName;
   public String lastName;
   public char gender;

   public Person(String fname, String lname, char g) { //constructor
      firstName = fname;
      lastName = lname;
      gender = g;
   }
   public abstract void setDefaults();
}

public class Employee extends Person {   //Employee class that extends Person

   public Employee(String fname, String lname, char g) {    //i thought super(); might solve the problem, but it didnt.
      super(fname, lname, g);
   }
   public void setDefaults() {}
}

A: this is it
public Employee(String fname, String lname, char g) {
    super(fname, lname, g);
...

A: It's because super(); without parameters is not available anymore since you defined your own constructor in Person.
You can fix it by revising the constructor definition in Employee to accept and pass the same parameters as the constructor you created in its superclass Person:
public Employee(String fname, String lname, char g) {
    super(fname, lname, g);
}

A: You're calling super() which equates to the super class' constructor. But you do not have a default (No argument) constructor. You can do
super("John", "Doe", 'M');


text:
Q: Posthoc test nested anova using multcomp in R my data is nested on a group level. There are five different treatments. Within every treatment, four participants are grouped. It is about donation behavior of those participants (dependent variable = Donation, metric, in €) under competition ( Explanatory variable = Treatment, ordinal). The data structure is like this:
Treatment   Session   player.cumulative_donation:
CG             uk4rlbdo         2.5
CG             uk4rlbdo         1.4
CG             uk4rlbdo         0
CG             uk4rlbdo         1
CG             dg0bqvit         0
CG             dg0bqvit         0
CG             dg0bqvit         0.5
CG             dg0bqvit         0
TG1            g6n3z46r         1
TG1            g6n3z46r         0
TG1            g6n3z46r         0
TG1            g6n3z46r         0.2

After computing the ANOVA based on Rcompanion, I want to perform a Posthoc test using the multcomp function.
however, if I run
library(multcomp)

posthoc = glht(model,
               linfct = mcp(Treatment="Tukey"))

I get this error message which I don't understand
Error in model.frame.lme(object) : object does not contain any data
Error in factor_contrasts(model) :
  no 'model.matrix' method for 'model' found!

There is data stored in model:
> model
Linear mixed-effects model fit by REML
  Data: NULL
  Log-restricted-likelihood: -166.8703
  Fixed: Donation ~ Treatment
 (Intercept) TreatmentTG1 TreatmentTG2 TreatmentTG3 TreatmentTG4
   0.7492227    1.3343727    0.2981268    1.4943010    0.5274175

Random effects:
 Formula: ~1 | Session
        (Intercept) Residual
StdDev:   0.1759392 1.651152

Number of Observations: 88
Number of Groups: 27

The variables are:
$ player.cumulative_donation: num  2.5 1.4 0 1 0 0 0.5 0 1 0 ...
$ player.treatmentgroup     : chr  "CG" "CG" "CG" "CG" ...
$ Session code              : chr  "uk4rlbdo" "uk4rlbdo" "uk4rlbdo" "uk4rlbdo" ...

EDIT:
The R command to create model:
library(nlme)

model = lme(Donation ~ Treatment, random=~1|Session,
            method="REML")

anova.lme(model,
          type="sequential",
          adjustSigma = FALSE)

Output of dput(head(SPSS_Data.df,10)):
structure(list(Participant_id = c(1, 2, 3, 4, 5, 6, 7, 8, 9,
10), participant.id_in_session = c(1, 2, 3, 4, 1, 2, 3, 1, 2,
3), participant.code = c("hcj5o43a", "ugiv2jlq", "53vepzb7",
"j2k7noqy", "njm1sr5d", "c2phh8p1", "5xaot5ii", "lvfkfw72", "05pjmgwp",
"o0yt5qbt"), `Session code` = c("uk4rlbdo", "uk4rlbdo", "uk4rlbdo",
"uk4rlbdo", "dg0bqvit", "dg0bqvit", "dg0bqvit", "8stn6uxo", "8stn6uxo",
"8stn6uxo"), player.cumulative_donation = c(2.5, 1.4, 0, 1, 0,
0, 0.5, 0, 1, 0), player.treatmentgroup = c("CG", "CG", "CG",
"CG", "CG", "CG", "CG", "CG", "CG", "CG"), TG_coded = c(0, 0,
0, 0, 0, 0, 0, 0, 0, 0), CG_Dummy = c(1, 1, 1, 1, 1, 1, 1, 1,
1, 1), TG1_Dummy = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), TG2_Dummy = c(0,
0, 0, 0, 0, 0, 0, 0, 0, 0), TG3_Dummy = c(0, 0, 0, 0, 0, 0, 0,
0, 0, 0), TG4_Dummy = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), Gruppe = c(1,
1, 1, 1, 2, 2, 2, 3, 3, 3), `Perceived Competition` = c(2, 1,
1, 1, 3, 1, 2, 2, 1, 1), `Influenced behavior` = c(2, 2, 1, 1,
3, 1, 4, 1, 1, 1), `Donate more` = c(3, 3, 1, 1, 1, 3, 2, 1,
1, 1), `Donate less` = c(3, 3, 1, 1, 3, 3, 3, 1, 1, 1)), row.names = c(NA,
10L), class = "data.frame")

A: The regression works if the data is a variable in the environment, but for downstream analysis, they required it to be stored as a data.frame inside the lme object:
For example, this works perfectly
library(nlme)
library(multcomp)

SPSS_Data.df = data.frame(
"player.treatmentgroup"=sample(c("TG1","TG2","TG3"),100,replace=TRUE),
"player.cumulative_donation"=rnorm(100),
"Session code" = sample(c("uk4rlbdo","dg0bqvit"),100,replace=TRUE),
check.names=FALSE)

df = setNames(SPSS_Data.df[,c("player.cumulative_donation",
"player.treatmentgroup","Session code")],
              c("Donation","Treatment","Session")
              )

model = lme(Donation ~ Treatment, random=~1|Session,data=df)
glht(model,linfct=mcp(Treatment="Tukey"))

Whereas when you put the variable into the environment, i get the same error:
Donation = df$Donation
Treatment = df$Treatment
Session =df$Session
model = lme(Donation ~ Treatment, random=~1|Session)
glht(model,linfct=mcp(Treatment="Tukey"))

Error in model.frame.lme(object) : object does not contain any data
Error in factor_contrasts(model) :
  no 'model.matrix' method for 'model' found!


text:
Q: Exasol: How to get the session queries executed in Exasol server I am have connect to Exasol server where queries are written in a reporting application. Now i want the list of queries executed in particular execution of my report.
Note: I am looking for tables or logs which holds the information of the executed application session after its execution also.

A: Take a look at tables EXA_DBA_AUDIT_SESSIONS and EXA_DBA_AUDIT_SQL in schema EXA_STATISTICS - these hold info about the session and the SQL that has been run. You may need to turn auditing on to tell the system to populate these tables.
There are many useful tables in EXA_STATISTICS giving info on resource usage etc.


text:
Q: How to prevent or avoid Cache in Angular 2 + Applications? I have a situation where i send parameters to an API which in turn generates dynamic pdf & API sends me the path of newly generated file. When i open the file in browser it shows newly generated file, but In my DOM I still see the old file untill & unless i close the browser & hit the API Again. I am previewing the generated pdf file as follows :
TS PART :
this.http.postMethod("report/auditAdmin", data).subscribe((res: any) => {
        this.toolbar = "#toolbar=0&navpanes=0";
        this.pdfSrc = res.filepath + this.toolbar;
        this.Url = this.sanitizer.bypassSecurityTrustResourceUrl(this.pdfSrc);
      });

HTML PART :
<object [data]="Url" type="application/pdf" width="100%" height="1000px"></object>

A: The issue is not with the API Cache or Angular, The issue is with the object control.
When we try to load the data like pdf file or any other external content object sends a get request to show the content (get request can be viewd in browser's network tab).
So the simple solution is append querystring to your pdf path.
this.http.postMethod("report/auditAdmin", data).subscribe((res: any) => {
            this.toolbar = "#toolbar=0&navpanes=0";
            let ramdom = Math.random();
            this.pdfSrc = res.filepath + "?v=" + random + this.toolbar;
            this.Url = this.sanitizer.bypassSecurityTrustResourceUrl(this.pdfSrc);
          });

Now whenever your object tries make a get request to pdf file each request will be fresh because of querystring and hence data will not get loaded from cache.

A: To prevent/avoid cache in Angular 2+ version you can achieve by overriding the RequestOptions.
Step 1 : Create Custom RequestOptions.
import { Injectable } from '@angular/core';
import { BaseRequestOptions, Headers } from '@angular/http';
@Injectable()
export class CustomRequestOptions extends BaseRequestOptions {
    headers = new Headers({
        'Cache-Control': 'no-cache',
        'Pragma': 'no-cache',
        'Expires': 'Sat, 01 Jan 2000 00:00:00 GMT'
    });
}

Step 2 Provide in Root AppModule.ts
@NgModule({
    ...
    providers: [
        ...
        { provide: RequestOptions, useClass: CustomRequestOptions }
    ]
})

Hope above solution will solve your problem!.


text:
Q: Как создать такой вид при такой HTML структуре? Привет есть такой вид блоков. Первый блок имеет 50% ширину всего контейнера и 100% высоту. А след 4 блока идут по 25% ширины и 50% высоты.
Внимание на скриншот

Проблема в том что мне требуется такая HTML структура, без сторонних Wrapperов

Какими стилями можно подогнать такой вариант разметки
Пожалуйста без доп библиотек. Требуется чистый HTML

A: Если без добавления оберток, то display: grid:

* {
  box-sizing: border-box;
}

html,
body {
  margin: 0;
  padding: 0;

  width: 100%;
  height: 100%;
}

.items {
  display: grid;
  grid-template-columns: 25% 25% 25% 25%;
  grid-template-rows: 50% 50%;
  grid-gap: 0 0;

  width: 100%;
  height: 100%;
}

.item:nth-of-type(1) {
  background: #03a9f3;

  grid-row: 1 / span 2;
  grid-column: 1 / span 2;

}
.item:nth-of-type(2) {
  background: #feeb3c;
}
.item:nth-of-type(3) {
  background: #ff5822;
}
.item:nth-of-type(4) {
  background: #4daf50;
}
.item:nth-of-type(5) {
  background: #9c28b0;
}

1

2

3

4

5

Или с помощью masonry grid:

$('.items').masonry({
  // options
  itemSelector: '.item',
  percentPosition: true,
  columnWidth: '.grid-sizer',
});
* {
  box-sizing: border-box;
}

html,
body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}

.items {
  width: 100%;
  height: 400px;
}

.grid-sizer {
  width: 25%;
}

.item {
  width: 25%;
  height: 50%;
  float: left;
}

.item:nth-of-type(1) {
  background: #03a9f3;
  width: 50%;
  height: 100%;
}

.item:nth-of-type(2) {
  background: #feeb3c;
}

.item:nth-of-type(3) {
  background: #ff5822;
}

.item:nth-of-type(4) {
  background: #4daf50;
}

.item:nth-of-type(5) {
  background: #9c28b0;
}

1

2

3

4

5

A: Можно и с float том ))

body {
  padding: 0;
  margin: 0;
}
.items {
  position: relative;
}
.item {
  outline: 1px solid #f00;
  display: inline-block;
  width: 25%;
  min-height: 50vh;
  float: left;
  font-weight: 700;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
      -ms-flex-pack: center;
          justify-content: center;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
}
.item-1 {
  outline: 1px solid #f00;
  float: left;
  width: 50%;
  min-height: 100vh;
  font-weight: 700;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
      -ms-flex-pack: center;
          justify-content: center;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
}
<!DOCTYPE html>

 <meta charset="UTF-8">
 <title>Document</title>
 <link rel="stylesheet" href="style.css">

width-50%
height-100%

width-25%
height-50%

width-25%
height-50%

width-25%
height-50%

width-25%
height-50%


text:
Q: Cannot get the values in time period using SQL Server Management Studio Let me explain the process:

*

*We've got a scanned questionnaries.

*The OCR system processes these questionnaries to get data.

*Then all recognized data(form_id, question_number, answer etc) goes into database.

*For each form there are about 120-150 rows in database:

*

*53453, 1, A, 2016-10-30 23:54:18.590

*53453, 2, B, 2016-10-30 23:54:18.690

*53453, 3, C, 2016-10-30 23:54:18.790 so on

As you can see, it is difficult enough to find duplicate of a questionnarie form in the database. SQL is not my strong point so I need your help) I need to select ID according to the condition: insertionTime difference of 1 min is not a duplicate. But if the ID exists somwhere else in another Time it would be a dublicate.
P.S. I did my best trying to explain my issue. Excuse me for my english)

A: Make sure your last column's data type is DATETIME the do:
SELECT tA.*
FROM MyTable tA INNER JOIN MyTable tB ON (tA.ID = tB.ID AND tA.question_number = tB.question_number AND tA.answer = tB.answer)
WHERE DATEDIFF(minute,tA.DateColumn,tB.DateColumn) < 2 -- DATEDIFF returns INT

A: You check only ID or also question and answer? I wrote my query for only ID and Date because You said If ID exists in other row with different time ( difference is more than minute - it is duplicate)  you don't say anything about checking answer / question. In last row I modified time.
DECLARE @TMP TABLE (
    ID INT,
    VALUE INT,
    VALUE2 VARCHAR(5),
    DATES DATETIME
)

INSERT INTO @TMP
SELECT 53453, 1, 'A', '2016-10-30 23:54:18.590'

INSERT INTO @TMP
SELECT 53453, 2, 'B', '2016-10-30 23:54:18.690'

INSERT INTO @TMP
SELECT 53453, 3, 'C', '2016-10-30 23:56:20.590'

SELECT ID, MIN(DATES) DATES
INTO #TMP_ID
FROM @TMP
GROUP BY ID

-- MORE THAN MINUTE
SELECT *
FROM @TMP T
WHERE EXISTS (

    SELECT NULL
    FROM #TMP_ID X
    WHERE DATEDIFF(second, x.dates, t.DATES) > 60
    and x.id = t.id

)

-- LESS THAN MINUTE
SELECT *
FROM @TMP T
WHERE NOT EXISTS (

    SELECT NULL
    FROM #TMP_ID X
    WHERE DATEDIFF(second, x.dates, t.DATES) > 60
    and x.id = t.id

)

DROP TABLE #TMP_ID


text:
Q: How to disable Swipe Gesture recognizer when a button is pressed? I set up the recognizer like this:
    @IBAction func changeSeq(_ recognizer: UISwipeGestureRecognizer) {

    if (recognizer.direction == UISwipeGestureRecognizerDirection.left)
    {
    print ("nice")
    }
}

I need it disabled when the start button is pressed and enabled again when the pause is triggered. I don't want to disable all user interaction. How do I handle the swipe specifically?

A: In your start button IBAction code, set the gesture recognizer's enabled property to false, and in the pause button's IBAction, set enabled = true.
That's cleaner than setting the delegate to nil.

A: If you are using swipe gesture delegates, change to nil and self according to button presses.


text:
Q: CSS Visiblity none vs collapse What is difference between the below two?

*

*visibility:none;

*visibility:collapse;
visibility: collapse is only used in case of tables? Or am I wrong?

A: Yes you are right, visibility: collapse is only used in table elements.

hidden The box is invisible (fully transparent, nothing is drawn), but still affects layout.  Descendants of the element will be visible
  if they have visibility:visible (this doesn't work in IE up to version
  7).
collapse For table rows, columns, column groups, and row groups the row(s) or column(s) are hidden and the space they would have
  occupied is (as if display: none were applied to the column/row of the
  table). However, the size of other rows and columns is still
  calculated as though the cells in the collapsed row(s) or column(s)
  are present. This was designed for fast removal of a row/column from a
  table without having to recalculate widths and heights for every
  portion of the table. For XUL elements, the computed size of the
  element is always zero, regardless of other styles that would normally
  affect the size, although margins still take effect. For other
  elements, collapse is treated the same as hidden.

reference:https://developer.mozilla.org/en-US/docs/Web/CSS/visibility


text:
Q: How to use overloaded operator== to check if 2d point and 3d point are identical in C++? I would like to check wether my 2d point and 3d points are identical using operator== that returns true if they are.
How can I implement that?
Do I need to add overloaded operator into both classes or what?
How to compare 2 arguments x and y?
My code:
#include <iostream>

using namespace std;

class Point2D {
public:
    Point2D();
//  ~Point2D();
    void SetX(double x);
    void SetY(double y);
    double GetX();
    double GetY();

protected:
    double m_x, m_y;
};
class Point3D :Point2D {
public:
    Point3D() :Point2D() { m_z = 0.0; };
protected:
    double m_z;
};
Point2D::Point2D() {
    m_x = 0.0;
    m_y = 0.0;
}

void Point2D::SetX(double x) {
    m_x = x;
}
void Point2D::SetY(double y) {
    m_y = y;
}
double Point2D::GetX() {
    return m_x;
}
double Point2D::GetY() {
    return m_y;
}

int main() {
    Point2D T;

    cout << T.GetX() << " " << T.GetX() << endl;

    return 0;
}

A: First, you probably want public inheritance:
class Point3D : public Point2D {
// ~~~~~~~~~~~~~^

Once you have that, you can rely on polymorphism to handle things for you and only implement comparison operator for Point2D:
// the arguments should be const, but your classes are not const correct
bool operator== (/*const*/ Point2D& lhs, /*const*/ Point2D& rhs)
{
    return lhs.GetX() == rhs.GetX() && lhs.GetY() == rhs.GetY();
}

int main() {
    Point2D p2;
    Point3D p3;
    std::cout << std::boolalpha << (p2 == p3);
}

You can further improve it by making your functions const:
class Point2D {
public:
    Point2D();
    void SetX(double x);
    void SetY(double y);
    double GetX() const; //here
    double GetY() const; //here

protected:
    double m_x, m_y;
};

double Point2D::GetX() const { //and here
    return m_x;
}
double Point2D::GetY() const { //and here
    return m_y;
}

//now you can pass arguments by const reference, no accidental modifications in the operator
bool operator== (const Point2D& lhs, const Point2D& rhs)
{
    return lhs.GetX() == rhs.GetX() && lhs.GetY() == rhs.GetY();
}


text:
Q: PHP mysqli is this the easiest way? The code snippet is meant to return the minimum and maximum id from each round in this table  I'm just wondering if there is a less clunky way of doing this.
$query = "SELECT round FROM $tablename";
$rounds = Array();
if ($result = $Login->mysqli->query($query)) {
    while ($row = $result->fetch_array(MYSQL_ASSOC)) {
        $rounds[] = $row['round'];
    }
}
$rounds = array_unique($rounds);
$rounds = array_values($rounds);
$roundBound = Array();
foreach ($rounds as $roundNum) {
    $query = "SELECT MIN(id), MAX(id) FROM $tablename WHERE round = $roundNum;";
    $result = $Login->mysqli->query($query);
    $row = $result->fetch_row();
    $roundBound[] = $row[0];
    $roundBound[] = $row[1];
}

hurr...
Changed to,
$query = "SELECT MIN(id), MAX(id) FROM $tablename GROUP BY round";
    if($result = $Login->mysqli->query($query)) {
        while ($row = $result->fetch_row()) {
            $roundBound[] = $row[0];
            $roundBound[] = $row[1];
        }
    }

A: How about doing this in a single query:
SELECT MIN(id), MAX(id) FROM $tablename GROUP BY round

A: It'd be more efficient to run a single query and use a WHERE round IN (....) clause:
$round_clause = implode(',', $rounds);

$query = "SELECT round, MIN(id), MAX(id) FROM $tablename WHERE round IN ($round_clause) GROUP BY round";

As a general rule, doing a single query that returns a "large" number of rows is going to be more efficient than doing a series of smaller/single queries that only return few or one rows at a time. You only scan the indexes once, you only have to retrieve the data once.

A: use group by
using query in foreach is the worst practice I ever seen
SELECT Min(id), Max(id) FROM $tablename GROUP BY round


text:
Q: Display the product count in categories with static block in magento I want to display product count of available in product category. In my website i added H1 title through static block, so i want to know the technique to show product count near to H1 title.
See blow my website image-

Please suggest me how can I product count like below added image -

Please let me know any code to show count

A: Welcome to Magento.SE!
What're you going to need is a custom block.
Create the block
Create a Magento module. Declare a block short code in config.xml; for ease we'll be using demo:
    <models>
        <demo>
            <class>YourModule_Demo_Block</class>
        </demo>
    </models>

We can now refer to any block class in that path with a short code. Let's define the new class. Because we don't need to render a template and we'll be using some text generated by a resource model's query we don't need to use a template block.
<?php

class YourModule_Demo_Block_Productcount extends Mage_Core_Block_Text
{
    protected function _construct()
    {
        $productCount = $this->getProductCount();
        $this->setText($productCount);
    }

    /**
     * @return int
     */
    public function getProductCount()
    {
        $collection = Mage::getModel('catalog/product')->getCollection();
        return (int)$collection->getSize();
    }
}

How does this work?

*

*The _construct method is called right at the beginning of the block creation and calls setText on the getProductCount method.

*getProductCount queries the database to get the total product count

What this does not do is filter that collection to be targeted for the category that you're viewing. I can't do all your work for you!! ;)
Adding to a static block
So the hard work is done. Now to add to the static block. In your static block text you'll want to insert the following code:
{{block type="demo/productcount" name="catalog.productcount"}}

And that's it! It should work.
More work
Your next feat will be to modify your Class to pass in and filter by the currently viewed category. I won't do this for you - but here's a hint:
Mage::registry('current_category')

That function should return the category model for the currently visible category :)
Happy Magento-ing!


text:
Q: Can't find where form is processed? I'm using a wordpress theme that i want to customize and i cannot find where the custom post type Services form $_POST values are processed.  The form action returns to the same page but when looking at the page and the wrapper page, i cannot see any functions that process $_POST values?
Here is the form action
<form id="edit-service" class="edit-service" enctype="multipart/form-data" method="post" action="http://example.com/add-service/?step=edit-info&hash=427d72b2fe6d0e70a9cb" novalidate="novalidate"></form>

How do i debug this to find where $_POST values are being processed?

A: This will be bit tricky to find, you can try searching for something like $_POST['edit-info'] or $_REQUEST['edit-info'] in entire code, use eclipse IDE, Press ctrl + h and search for above, it will help you

A: In the add-service (controller?) you can either do the following:
echo "<pre>";
var_dump($_POST);
echo "</pre>";
exit;

If you are using firefox you could also use the Tamper Data extension, which let's you view and edit all POST data.


text:
Q: how to link laravel presence channel with nodejs socket.io I'm trying to make a SPA with vuejs in frontend and laravel in backend and nodejs server to serve socket.io connections.
I can broadcast events from laravel public and private channels to socket.io through redis and emit it to the client side.
Previously When I made an app with laravel and vuejs that comes with laravel I managed to implement a chat room using laravel echo and laravel echo server but in SPA I couldn't find a way to do it. Laravel Echo has methods .here().joining().leaving() that allow you to build a chatroom. but how can I implement this methods with socket.io ?
on client side I'm using vue-socket.io.
This is vue component that listen to events from socket.io server.
<template>
    <div class="container products">
        <products></products>
    </div>
</template>

<script>

import Products from './products/Products.vue'

export default {

    created() {
        this.$http.post('auth/token', {
            xhrFields: {
                withCredentials: true
            }
        })
        .then(response => {
            this.$socket.emit('authenticate', {
                token: response.data.token
            });
        })
        .catch(error => {
            console.log(error.response)
        });
    },

    components: {
       'products':  Products
    },
    sockets: {
        message(msg) {
            console.log(msg)
        }
    }
}
</script>

<style>
    .products {margin-top:60px}
</style>

MessageSentEvent.php
<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Support\Facades\Auth;

class MessageSentEvent implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $message;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($message)
    {
        $this->message = $message;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        if(Auth::check())
            return new PresenceChannel('Chat');
    }

    public function broadcastAs()
    {
        return 'message';
    }
}

routes/channels.php
<?php

use Illuminate\Support\Facades\Auth;

Broadcast::channel('Chat', function() {
    if(Auth::check())
        return Auth::user();
});

This is nodejs server
server.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var redis = require('redis');
var socketioJwt = require('socketio-jwt');
require('dotenv').config({
    path: '../backend/.env'
});

// Accept connection and authorize token
io.on('connection', socketioJwt.authorize({
    secret: process.env.JWT_SECRET,
    timeout: 15000
}));

/* When authenticated, listen to events that come from laravel throug redis */
io.on('authenticated', function (socket) {

    console.log('a user connected');
    socket.emit('id', socket.decoded_token.sub);

    var redisClient = redis.createClient();
    redisClient.subscribe('presence-Chat');
    redisClient.on('message', (channel, message) => {
        console.log('channel: ' + channel + '\nmessage: ' + message);
        socket.emit('message', JSON.parse(message).data.message);
    });

    socket.on('logout', () => {
        redisClient.quit();
        console.log('a user quit');
    });
});

io.on('disconnect', function (){
    console.log('a user disconnected');
});

server.listen(3000, function() {
    console.log('listening on port 3000');
});


text:
Q: Cannot read property 'username' of null, when trying to access id-data I want to pass a users data on to its profile. I get the full data from the api and I can fetch and display it on the users page. But when I want to display the data from the user on the users profile page I get this error:

TypeError: Cannot read property 'username' of null

The routing works. But somehow I don't have access to the users info which I want to store in information. And I think this line should store the data of the user:
this.userService.getUserDetails(id).subscribe(result => {
       this.information = result;
     });

How can I fix that?
Here is my code:
user.service
 // get a list of users
  getList(): Observable<any> {
    return this.http.get(`${this.url}/users`);
  }

 // get a user's profile
  getUserDetails(id): Observable<any> {
    return this.http.get(`${this.url}/users/?i=${id}`); // why add ?i
  }

user.page.ts
 getAllFriends() {
    this.friendsList = this.userService.getList()
    .pipe(map(response => response.results));
  }

profile.page.ts
information = null;
    ...
ngOnInit() {

         // Get the ID that was passed with the URL
         let id = this.activatedRoute.snapshot.paramMap.get('id');

         // Get the information from the API
         this.userService.getUserDetails(id).subscribe(result => {
           this.information = result;
         });
       }

profile.page.html
<ion-label text-wrap>

{{information.username}}, 22, 3589

</ion-label>

A: your component start with information = null; so it's normal that in {{ information.username }} you have this error.
A quick solution is:
{{ information?.username }}


text:
Q: Reorganized local Picture subfolders but changes not showing in Onedrive I'm synced my Picture folder with Onedrive last week but today I reorganized my local 'Pictures' Folders. The changes are not reflecting in Onedrive even after I click 'Sync' the folder in Onedrive.
Any ideas?

A: You should try updating your Windows (Windows update) or get Windows 8.1 from the store

ms-windows-store:WindowsUpgrade

with the link in gray.
Also, check sync settings again. Check OneDrive and your device.


text:
Q: Fixed width div between two fluid divs with Bootstrap I'm trying to create a layout with a fixed width div centered between two fluid divs. The configuration should fit within a Bootstrap row. How would I do this?
Here's an illustration:

A: You could make this easily with tables, but here is a div version for you:
<!DOCTYPE>

I'm trying to create a layout with a fixed width div centered between two fluid divs. The configuration should fit within a Bootstrap row. How would I do this? Here's an illustration:

I'm trying to create a layout with a fixed width div centered between two fluid divs. The configuration should fit within a Bootstrap row. How would I do this? Here's an illustration:

I'm trying to create a layout with a fixed width div centered between two fluid divs. The configuration should fit within a Bootstrap row. How would I do this? Here's an illustration:

As the divs are inline-block, don't add space or new line between them.


text:
Q: Is there a way to increase the performance of PHP's tidy function? I wanted to ask you if you know a way to increase the performance of PHP's tidy function?
Using it like this at the moment:
while($ds = mysql_fetch_assoc($qry))
{
    $tidy = tidy_parse_string($ds['description']);
    $html =  tidy_parse_string($tidy, array('show-body-only'=>true, 'indent'=>true));
    $sql = "UPDATE tbl_*** SET description = '".mysql_real_escape_string($html)."' WHERE id = '".mysql_real_escape_string($ds2['id_artikel'])."'";
    sql4query($sql);

    $allerr = $allerr + tidy_error_count($tidy);
    $allwar = $allwar + tidy_warning_count($tidy);
    $msg .= $ds['id'].":\n".$tidy->errorBuffer."\n\n\n";
}

But it's just too slow, with more than 10 million data sets.

A: As other comments already said, there's probably no reasonable way to make the tidy extension doing its work any faster.

the problem is, that I need to clean these records once. The new ones will be cleaned by inserting into the database.

So how many "old" records are we talking about  – thousands, tenthousands, …?
If you can not get it done "all in one go" (cronjob, no execution time limit, run during a maintenance phase "over night") – then the alternative is to do each record individually, once – when it is "needed" for the first time.
You add a column to your table, still_needs_to_be_cleaned or something, and set that to true/1 for all existing records. On inserting a new record you simply set it to false/0.
Now, when a record is requested (by visitor of the site or whatever), you check whether the flag still_needs_to_be_cleaned is still set to true – if so, you let tidy run on that single record, and update it in the database afterwards – setting still_needs_to_be_cleaned to false while doing so.
If the record has still_needs_to_be_cleaned set to false already – then no tidy-action and no update is needed, you can proceed with outputting that record straight away.
Yes, this will mean a small delay for the first user requesting a certain record – but most likely, it will hardly be noticeable, if at all.

And if you want, you can even check from time to time, how many records still have the still_needs_to_be_cleaned flag set to true. If there's none left, you could remove that extra logic again.


text:
Q: How can i get the clicked button's row values on silverlight telerik radgridview button column? I have a hyperlink button colum in silverlight telerik radgridview, as a cell template.
I am using MVVM.
When i click on the hyperlink button, how can i get its row's values(atleast in the code behind)..?
Thanks in advance..

A: You need to use the ParentOfType extension method to get hold of the row containing the button.
Once you have the row you can cast the item type to your viewmodel and access the properties of it.
Make sure you have a using statement for the extension method:
using Telerik.Windows.Controls;

 private void Button_Click(object sender, RoutedEventArgs e)
{
    var parent = (sender as Button).ParentOfType<GridViewRow>();
    var rowVM = parent.Item as YourVmClass;
}

If you are using MVVM you can also use the EventToCommandBehavior.
This allows you to execute all events as commands. You can then handle the command in your viewmodel.


text:
Q: WordPress throwing 500 error when importing blogs from blogger I've got quite a large blogger site (6k posts, 23k comments). I've downloaded the blogger import tool from WordPress's site and installed it. The tool basically requests permission from your Google account to look up your blog data,then gives you the options to import them.
The import starts, it gets all the blog posts, and does about 3.5k comments, then appears to stop. I've opened my browsers console and it's saying
public_html/wp-admin/admin.php?import=blogger&noheader=true
Failed to load resource: the server responded with a status of
500 (Internal Server Error)

If i try to reimport them again, it does the same thing.
Does anyone know solutions to this?

A: Problem solved.
If you use Plesk Panel or CPnael, WHM...
Change the PHP Settings :
Memory Limit : 128M
Max Execution Time : 10000
Post Max Size : 16M
Upload Max Filesize : 16M
and import data success!
Detail : WordPress Importing problem

A: I switch from a physical server to a virtual server and run into the same problem and found a solution.
The reason why you get this error is because the php scripts reading the xml file and making the mysql database entries might be too slow for the server time executing levels set. My benchmark for 2000posts xml (4MB file) 20secs. process time for a physical server and around 5min for the same upload on a virtual server. Virtual servers are processing slow and at the same time have tiny process time limits. This throws 500 internal server errors, simple not because your php script is wrong, but the process time ist too long.
To change this you have to edit these limits and enter higher (way higher) numbers, in these files:
1) php.ini: set "max execution time" up (at least to 5-10 minutes, depending on estimated processing time)
2)fcgid.conf: set "FcgidIOTimeout" to at least 90 or 120
You find this file here: /etc/httpd/conf.d/fcgid.conf or for Debian systems here /etc/apache2/mods-enabled/fcgid.conf
Obviously these changes require root access to the server. If you don't have ask your hosting provider.
For me only changes in fcid.conf solved the problem and a coffee break waiting for the upload. I checked mysql database in the meantime and saw there are more files in wp_post... So I knew, its working... but slowly...

A: in functions.php
@ini_set( 'upload_max_size' , '64M' );
@ini_set( 'post_max_size', '64M');
@ini_set( 'max_execution_time', '300' );
@ini_set( 'upload_max_filesize', '256M');


text:
Q: Visual proof that $\lim_{x\to \infty} \frac{x^r}{a^x} = 0$ I am looking for a visual proof (in this sense: https://mathoverflow.net/questions/8846/proofs-without-words) for the fact that
$$
    \lim_{x\to \infty} \frac{x^r}{a^x}  = 0
$$
($r > 0,a>1$)
Or at least for a simple (high school level) argument that makes this relation plausible (but it doesn't have to be a rigerous mathematical proof - I know to proof it rigerously, but that's not what I am looking for).

A: Every time $x$ increases by $1$, the bottom gets multiplied by $a$ and the top gets multiplied by $$\left(\frac{x+1}{x}\right)^r = \left(1+\frac{1}{x}\right)^r \approx 1+\frac{r}{x}$$
So the bottom keeps growing by the same factor while the factor that the top grows by gets smaller and smaller, and will eventually get smaller than $a$. In the long run (i.e. as $x \to\infty$) the bottom will win out, driving the whole expression to $0$. (This does make an appeal to a binomial theorem approximation.)
It's not intuitive, and probably doesn't have the "Aha!" appeal of a visual proof, but I think it would help high schoolers start to think about comparing different rates of growth and help them build their intuition.
And if I were presenting this to high schoolers I would definitely start off showing how it worked in a specific simple example, like $\frac{x^2}{2^x}$. Write ten terms of $x^2$, note that they're increasing, but then write ten terms of $2^x$ and note how the crush the terms on the top. Then make the generalization, and maybe note that if $a$ is close to $1$ and $r$ is large it will take more terms for the bottom to win, but it will eventually, and we are going to $\infty$.

A: Let $a^{1/r}=1+b.$ Then $b>0$ if $a>1$ and $r>0.$ For any $y$ let $[y]$ denote the largest integer not exceeding $y.$
Apply a result from the Binomial Theorem:  $(1+b)^n>b^2\binom {n}{2}$ when $b>0$ and $2<n\in \mathbb N$.
For $\frac {x}{r}\geq 3$ we have  $$0<\frac {x^r
}{a^x}=\left(\frac {x}{(1+b)^{x/r}}\right)^r\leq  \left(\frac {x}{(1+b)^{[x/r]}}\right)^r<$$     $$<\left(\frac {x}{b^2\cdot \binom {[x/r]}{2}}\right)^r<$$ $$< \left(2rb^{-2}\cdot \frac  {\frac {x}{r}}{(\frac{x}{r}-1)(\frac{x}{r}-2)}\right)^r$$

A: I guess that we can do the following:
$$ 0 = \lim_{x \rightarrow \infty} \frac{x^r}{a^x} =  \lim_{x \rightarrow \infty} \frac{\ln x^r}{\ln a^x} = \lim_{x \rightarrow \infty} \frac{r \ln x}{x \ln a} = \frac r {\ln a} \lim_{x \rightarrow \infty} \frac{\ln x}{x} = \lim_{x \rightarrow \infty} \frac{\ln x}{x} $$
Using the last limit we can make visual proof.


text:
Q: In keras how to get epoch and validation loss from model checkpoint? From here (https://keras.io/callbacks/#modelcheckpoint) you can save the best model according to the validation error by setting save_best_only.
I know you can save the corresponding epoch and validation error by writing it to the checkpoint's file name. However, this means a lot of models could be saved and I expect this to result in memory error on my GPU.
Is there a way to get the epoch and val loss corresponding to the final best model without having to write it in the filename?

A: Depends on what you want to do with the epoch and validation error and at what time in the training, but you can implement your own callback functionality quite easily. What you want to get the training metrics is the logs object, which is passed to the callback in each of the callback events (see here).
If for example you need to call a certain function f with the epoch and validation error at the end of every epoch, you could implement this using the LambdaCallback:
keras.callbacks.LambdaCallback(on_epoch_end=lambda epoch, logs: f(epoch, logs['val_loss']))

If instead you want to use the ModelCheckpoint callback but don't want it to write to file, you can create a custom CallBack that rewrites the ModelCheck callback and changes the save behavior (code here).
(Don't know if that answers your question, not entirely sure what the requirements are)


text:
Q: how to prevent from spammers while submitting web form in asp.net? i am working on a project developed in asp.net. In that one page holds the order details. Validation works well while form values filled up normally but some spammers are by pass that validations (All validations are done from client-side).
For example, i have one dropdown as "ProductName" and default value is "Please Select Product" and it is required field validator (validation on client-side only), but for some reason some spammers are by pass validation with that default selected value "Please Select Product".
It looks somthing like this:
ProductId: 1
ProductName: Please Select Product <== here it must be a product name
Address: As Specified Above

How to resolve this problem ?
Thanks

A: First You should have CAPTCHA implemented on every input form page available to Un-Authenticated/Public Users.
secondly, you should validate your inputs on server side as well.
in ASP.Net with Page.IsValid  and in MVC.Net ModelState.IsValid