text:
Q: Warning: React does not recognize the `previousStep` prop on a DOM element

import React, { Component } from 'react';
import ChatBot from 'react-simple-chatbot';
import { Switch, Route, BrowserRouter } from 'react-router-dom';
import Dropzone from 'react-dropzone';

class Form extends Component {

  constructor(props){
    super(props);

    this.state = {
      // some other states
      file: ''
    };
  }

  onDrop(acceptedFiles){
    var file = acceptedFiles[0];
    const reader = new FileReader();
    reader.onload = () => {
      const fileAsBinaryString = reader.result;
      this.setState({
        file: fileAsBinaryString
      });

      //console.log(fileAsBinaryString);
    }

    reader.readAsBinaryString(file);

    //console.log(file);
  }

  render() {
    return(
      <ChatBot
        steps={[
          {
            id: '1',
            message: 'You can add custom components',
            trigger: '2',
          },
          {
            id: '2',
            component: (

                 <Dropzone onDrop={this.onDrop.bind(this)} />

            ),
            end: true,
          },
        ]}
      />
    )

  }

}

I am trying to use react-dropzone within react-simple-chatbot, but when I upload a file it shows 2 warnings:

*

*React does not recognize the previousStep prop on a DOM element.

*React does not recognize the triggerNextStepenter image description here prop on a DOM element.
I am able to find similar problems but their solutions are not working out for me. How should I make it work?
Edit: I have added an example similar to my approach.

A: Hello Dear your question is not not clear to me as it lacks lots of information,It would have better if you put your code here. I don't know did you follow react-dropzone documentation. In their documentation they cleared how to use it in your application. Try to do below procedure. In my case it is working without showing any warning.
import Dropzone from 'react-dropzone'
//OTHERS IMPORT FILE
// ... ... ...
class AddEmployee extends Component {
    constructor(props) {
        super(props);
        this.state = {
            photo: ""
        }
    }
    // OTHERS FUNCTIONS
    // ... ... ....
    onDrop(files) {
        const file = files.find(f => f)
        let reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => {
            this.setState({
                photo: reader.result,
            })
        }
    }

    render() {
        return (
            // OTHERS DIV
            // ... ... ... ...

                <Dropzone onDrop={(e) => this.onDrop(e)}>
                    {this.state.photo != "" ?  :
Try dropping some photo here or click to select files to upload

                    }
                </Dropzone>

            // OTHERS DIV
            // ... ... ... ...
        )
    }
}


text:
Q: undefined method 'hashed_password' Agile Web development with rails I'm following Iteration 13 of Agile Web development, for User login.
I create a migration to add 2 columns to my User model : hashed_password and salt.

*

*Creation of Users works

*login fails, due to this error undefined method 'hashed_password' in method 'authenticate'

The problem is that :

*

*In rails console, I can fetch User.first.hashed_password, what seems OK :-)

*I outputted the User that I fecth, and it is NOT nil

*I tried to output user.hashed_password as I did in the rails console, but that throws always the same error :

NoMethodError (undefined method hashed_password' for #<ActiveRecord::Relation:0x00000003e6c3c0>):
  app/models/user.rb:21:inauthenticate'
  app/controllers/sessions_controller.rb:6:in `create'
This is my User model :
require 'digest/sha2'

class User < ActiveRecord::Base
has_and_belongs_to_many :products
has_many :created_products, :class_name => "Product", :foreign_key => :product_id

default_scope :order => "username ASC"

# Attributs pour le login (Livre)
validates :username, :presence => true, :uniqueness => true
validates :password, :confirmation => true
attr_accessor :password_confirmation
attr_reader :password
validate :password_must_be_present

def User.authenticate(name, password)
    logger.debug "---------- Beginning of Authenticate"
    if user = User.where(:username => name)

      logger.debug "utilisateur = #{user.inspect}"   # THIS IS OK AND NOT NIL
      logger.debug "utilisateur hashed PW = #{user.hashed_password}" # ERROR

        if user.hashed_password == encrypt_password(password, user.salt)
            return user
        end
    end
end

def User.encrypt_password(password, salt)
    Digest::SHA2.hexdigest(password + "wibble" + salt)
end

def password=(password)
    @password = password
    if (password.present?)
        generate_salt
        self.hashed_password = self.class.encrypt_password(password, salt)
    end
end

private

    def password_must_be_present
        errors.add(:password, "Mot de passe manquant") unless hashed_password.present?
    end

    def generate_salt
        self.salt = self.object_id.to_s + rand.to_s
    end

end

A: User.where(:username => name) is returning an ActiveRecord::Relation object (hence the error message you are seeing).  Try changing your if statement to:
if user = User.where(:username => name).first

That will set take the first matching user, which will be an instance of User and so will have a hashed_password field.  If no user matches, you'll get nil.

A: put this in your model
   private
    def self.hash_password(password)
       Digest::SHA1.hexdigest(password)
    end

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there any implementation of Grassberger-Procaccia algorithm available? I am looking for an implementation of Grassberger-Procaccia algorithm in .NET/C/C++, MATLAB or Java. I have been searching for it for a while, but it appears that the actual implementation has not been published anywhere and I don't really want to implement it myself as it will require much testing.
This algorithm allows to estimate correlation dimension of time series data. There is some MATLAB code here, which does compute correlation dimension, but it seems to use some other algorithm for it.
My data is represented by {0,1,2} alphabet and is a non-linear signal with around 10^6 points per signal instance. I have around 100 sample signal instances which are grouped by some external characteristics. For these signals I need to calculate correlation dimensions and then apply some statistics to see if there is any differences between the groups. So the signal looks like this:
Signal1 = 0000000001000020010000001...
Signal2 = 0000001200000200200202000...
Signal3 = 2222220000000220000100011...

Any link would be much appreciated. Thanks!


text:
Q: How to obtain a parameter 'total_words' for model.train() of gensim's doc2vec As you might know, when you make a doc2vec model, you might do model.build_vocab(corpus_file='...') first, then do model.train(corpus_file='...', total_examples=..., total_words=..., epochs=10).
I am making the model w/ huge wikipedia data file. So, I have to designate the 'total_examples' and the 'total_words' for parameters of train(). Gensim's Tutorial says that I can get the first one as total_examples=model.corpus_count. This is fine. But I don't know how to get second one, total_words. I can see the # of total words in the last log from model.build_vocab() as below. So, I directory put the number, like total_words=1304592715, but I'd like to designate it like model.corpus_count manner.
Can someone tell me how to obtain the number?
Thank you,
:
2022-01-29 15:03:22,377 : INFO : PROGRESS: at example #1290000, processed 1253078267 words (6147969/s), 7881288 word types, 0 tags
2022-01-29 15:03:26,434 : INFO : PROGRESS: at example #1300000, processed 1277357579 words (5984975/s), 7959581 word types, 0 tags
2022-01-29 15:03:30,955 : INFO : collected 8039609 word types and 1309452 unique tags from a corpus of 1309452 examples and 1304592715 words
:

A: Similar to model.corpus_count, the tally of words from the last corpus provided to .build_vocab() should be cached in the model as model.corpus_total_words.


text:
Q: How to pass parameter to Linq Orderby I need pass parameter to linq query. My query is as follows:
var appointments = (from a in inMemContext.Appointments
                    join u in inMemContext.Users on a.UserId equals u.UserId into AppointmentAssignments
                    from aa in AppointmentAssignments.DefaultIfEmpty()
                    join l in inMemContext.Languages on a.PreferredLanguage equals l.LanguageKey
                    where a.BranchId == branchId
                    && a.AppointmentDate.Date == TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById(b.TimeZoneId)).Date
                    orderby a.AppointmentTime
                    select new AppointmentEntryDetailsDto
                    {
                        Id = a.AppointmentId.ToString(),
                        StartTime = (a.AppointmentTime).ToString("hh:mm tt", CultureInfo.InvariantCulture),
                        AppointmentType = a.AppointmentType.AppointmentTypeName,
                    });

In above query I'm taking data ordered by AppointmentTime. Now I need set dynamic sorted value as ascending or descending.
For this line:
orderby a.AppointmentTime [OrderParameter]

ascending or descending. How can I do this?

A: There is no such built in way.
You can create a custom extension method (thereby not using language integrated queries), or branch the entire statement, or order by the negative time (convert the time based on the parameter before ordering, subtract from 24:00:00 or similar).

A: This is achievable by creating an extension method which can dynamically change whether it's ascending or descending:
public static class LinqExtensions
{
    public static IEnumerable<TModel> OrderByDynamic<TModel, TKey>(this IEnumerable<TModel> source, Func<TModel, TKey> selector, bool ascending = true)
    {
        if (ascending) return source.OrderBy(selector);
        return source.OrderByDescending(selector);
    }
}

Usage:
var appointmentList = new List<Appointment>
{
    new Appointment { UserId = "1", PreferredLanguage = "English", BranchId = "1", AppointmentDateTime = new DateTime(2000, 1, 1, 0, 0, 0) },
    new Appointment { UserId = "2", PreferredLanguage = "Japanese", BranchId = "1", AppointmentDateTime = new DateTime(2000, 2, 1, 0, 0, 0) },
    new Appointment { UserId = "3", PreferredLanguage = "Spanish", BranchId = "2", AppointmentDateTime = new DateTime(2000, 3, 1, 0, 0, 0) },
};

// Order By Descending
var appointments = appointmentList.OrderByDynamic(selector: x => x.AppointmentDateTime, ascending: false);

This is not directly compatible with a Linq Query, but can be used on the results of any IEnumerable. I'll leave that up to you on how to use this for your specific case.


text:
Q: Is my MS SQL Server being attacked? I use MS SQL Server 2017 Express Database in windows 2016 server, I am seeing that the ERRORLOG file of MS SQL Server is increasing 600MB per day.
The below is from the ERRORLOG file.
Does this mean that my MS SQL Server 2017 Express Database is being attacked?
How can I fix this problem?
2019-12-22 03:36:09.34 Logon       Error: 18456, Severity: 14, State: 8.
2019-12-22 03:36:09.34 Logon       Login failed for user 'sa'. Reason: Password did not match that for the login provided. [CLIENT: 14.253.239.25]
2019-12-22 03:36:09.34 Logon       Error: 18456, Severity: 14, State: 8.
2019-12-22 03:36:09.34 Logon       Login failed for user 'sa'. Reason: Password did not match that for the login provided. [CLIENT: 59.127.222.102]
2019-12-22 03:36:09.42 Logon       Error: 18456, Severity: 14, State: 8.
2019-12-22 03:36:09.42 Logon       Login failed for user 'sa'. Reason: Password did not match that for the login provided. [CLIENT: 104.238.63.33]
2019-12-22 03:36:09.70 Logon       Error: 18456, Severity: 14, State: 8.
2019-12-22 03:36:09.70 Logon       Login failed for user 'sa'. Reason: Password did not match that for the login provided. [CLIENT: 14.253.239.25]
2019-12-22 03:36:09.70 Logon       Error: 18456, Severity: 14, State: 8.
2019-12-22 03:36:09.70 Logon       Login failed for user 'sa'. Reason: Password did not match that for the login provided. [CLIENT: 59.127.222.102]
2019-12-22 03:36:09.74 Logon       Error: 18456, Severity: 14, State: 8.
2019-12-22 03:36:09.74 Logon       Login failed for user 'sa'. Reason: Password did not match that for the login provided. [CLIENT: 104.238.63.33]
2019-12-22 03:36:10.06 Logon       Error: 18456, Severity: 14, State: 8.
2019-12-22 03:36:10.06 Logon       Login failed for user 'sa'. Reason: Password did not match that for the login provided. [CLIENT: 59.127.222.102]
2019-12-22 03:36:10.06 Logon       Error: 18456, Severity: 14, State: 8.
2019-12-22 03:36:10.06 Logon       Login failed for user 'sa'. Reason: Password did not match that for the login provided. [CLIENT: 104.238.63.33]
2019-12-22 03:36:10.06 Logon       Error: 18456, Severity: 14, State: 8.
2019-12-22 03:36:10.06 Logon       Login failed for user 'sa'. Reason: Password did not match that for the login provided. [CLIENT: 14.253.239.25]
2019-12-22 03:36:10.39 Logon       Error: 18456, Severity: 14, State: 8.
2019-12-22 03:36:10.39 Logon       Login failed for user 'sa'. Reason: Password did not match that for the login provided. [CLIENT: 104.238.63.33]
2019-12-22 03:36:10.41 Logon       Error: 18456, Severity: 14, State: 8.
2019-12-22 03:36:10.41 Logon       Login failed for user 'sa'. Reason: Password did not match that for the login provided. [CLIENT: 14.253.239.25]
2019-12-22 03:36:10.42 Logon       Error: 18456, Severity: 14, State: 8.

A:
Does it mean that MS SQL Server 2017 Express Database meet attack?

It looks like it, yes.

How can I fix the problems?

Block access to your SQL server from the internet. Why is it exposed to the internet?

A: Your SQL server is definitely getting a logon attack. This happens almost 100% of the time a computer with SQL Server is exposed to the internet.
Here is an option to allow only certain IP addresses (You might need to do some research on how this is done)
If you have RDP or SSH open to the internet:
If this is on a Linux server and you have SSH open to the internet you most likely are being attacked on SSH. Please look at this guide.
If you are on Windows Server and you have RDP open to the internet you are also probably being attached on RDP. Please look at this guide.
The best is not to have this open to the internet but if it is definately needed you need to make sure your security is setup correctly on the machine or with a firewall.


text:
Q: Scoping problems with comprehensions I want to perform some analytics on a series of combinations of values.
I have the following function, but for some reason, after the comprehensions are completed and at the end of the function body, the variable analytics is still an empty list, while it's not inside the comprehension on each iteration
Any ideas?
def handle_cast({:start}, state) do
    intervals = [7, 30, 90]
    groupings = ["day_of_week", "time_of_day"]
    aggregators = [
      %{
        domain: "support",
        metric: "new_conversations",
        func:   &App.get_new_conversations/2
      },
      %{
        domain: "support",
        metric: "closed_conversations",
        func:   &App.get_closed_conversations/2
      },
      %{
        domain: "support",
        metric: "median_response_time",
        func:   &App.get_median_response_time/2
      },
    ]

    Repo.transaction(fn ->
      Repo.delete_all(Analytic)

      analytics = []
      for interval <- intervals do
        for grouping <- groupings do
          for %{domain: domain, metric: metric, func: func} <- aggregators do
            analytic =
              func.(grouping, interval)
              |> Enum.map(fn %{"app_id" => app_id, "data" => data} = result ->
                %Analytic{app_id: app_id, domain: domain, metric: metric, grouping: grouping, interval_in_days: interval, data: data}
              end)

            analytics = [analytic|analytics]
          end
        end
      end
    end)

    {:noreply, state}
  end

A: Variables in Elixir are immutable but rebindable. What this means is that the line analytics = [analytic|analytics] is creating a new list and binding it to the variable named analytics for the scope of that block. When the block ends, the changes are not persisted in the next iteration of the for. For example:
iex(1)> x = 1
1
iex(2)> for i <- 1..3 do
...(2)>   IO.puts(x); x = x + i; IO.puts(x)
...(2)> end
1
2
1
3
1
4

For the code you've written, you can use the fact that for returns a list of the values of the last expression inside them and store the return value of the outermost for to analytics, but there's a slight problem: you'll end up with nested lists:
iex(1)> for i <- 1..2 do
...(1)>   for j <- 1..2 do
...(1)>     for k <- 1..2 do
...(1)>       {i, j, k}
...(1)>     end
...(1)>   end
...(1)> end
[[[{1, 1, 1}, {1, 1, 2}], [{1, 2, 1}, {1, 2, 2}]],
 [[{2, 1, 1}, {2, 1, 2}], [{2, 2, 1}, {2, 2, 2}]]]

But, there's a simple solution! for accepts multiple <- clauses in a single call and automatically returns a flat list:
iex(1)> for i <- 1..2, j <- 1..2, k <- 1..2 do
...(1)>   {i, j, k}
...(1)> end
[{1, 1, 1}, {1, 1, 2}, {1, 2, 1}, {1, 2, 2}, {2, 1, 1}, {2, 1, 2}, {2, 2, 1},
 {2, 2, 2}]

Using this method, your code becomes:
analytics =
  for interval <- intervals,
      grouping <- groupings,
      %{domain: domain, metric: metric, func: func} <- aggregators do
      func.(grouping, interval)
      |> Enum.map(fn %{"app_id" => app_id, "data" => data} = result ->
        %Analytic{app_id: app_id, domain: domain, metric: metric, grouping: grouping, interval_in_days: interval, data: data}
      end)
    end
  end
end

This should give you the same output you were most likely expecting from the original code.


text:
Q: Use protected hierarchy custom settings to store sensitive information We are thinking to store sensitive user specific keys in protected hierarchy custom settings. Is this secure place where only user can access data. We don't want this data to be visible to anyone other than user. let us know if it is right choice?

A: Use of Protected custom metadata types is one more option in list. Also, you can access them through SOQL query. If you are using this in appexchange application, you don't have to use any post install script. An Upgradable type metadata would be best.They can be upgraded through new release of package.

A: Protected Custom Settings are not available to the user through Salesforce Setup. Protected Custom Settings and Custom Metadata are available only to code within the boundary of the managed package owning that entity.
You can use this functionality as desired - in the case of Protected Custom Settings - if any only if you implement a custom UI that exposes each user's instance to them. It's available only in a managed package. Outside a managed package, you cannot use Protected metadata. There is no out-of-the-box functionality that exposes data to a single user only, and not to users that have View All Data permission.


text:
Q: taking $\log$ of a function $h(x)$ I was reading from Ordinary Differential Equations (Lesson 10C page 85) and came across these steps:

$ \frac{d\ h(x)}{h(x)} =  \frac{\bigg[\frac{\partial}{\partial y}
 P(x,y) - \frac{\partial}{\partial x} Q(x,y)\bigg]}{Q(x,y)} dx \quad
 (a)$
$F(x) =   \frac{\bigg[\frac{\partial}{\partial y} P(x,y) -
 \frac{\partial}{\partial x} Q(x,y)\bigg]}{Q(x,y)} \quad (b) $
then $\quad log[h(x)] = \int{F(x)\ dx}$

My confusion is, if we are to substitute (b) into (a) , we will get
$$ \frac{d\ h(x)}{h(x)} = F(x)dx $$
and I know (maybe I might be wrong)
$$ F(x)dx  = \int{F(x)dx} $$
Please how did they get
$$\quad log[h(x)] = \int{F(x)\ dx}$$

A: $$\frac {dh}{h}=F(x)dx$$
Integrate both sides :
$$\int \frac {dh}{h}=\int F(x)dx$$
$$\ln |h|+C=\int F(x)dx$$
This is because the integral of $f(x)=\dfrac 1 x$ is  $\ln x$ :
$$\implies I=\int \dfrac {dx}{x}=\ln |x|+C$$

For example you may have this:
$$\int \frac {dx^2y^3}{x^2y^3}=\ln |x^2y^3|+C$$
Because if you substitute $A=x^2y^3$ you will have :
$$\int \frac {dA}A=\ln |A|+C=\ln |x^2y^3|+C$$


text:
Q: Really disable exclusive mode for Bluetooth headphones in Windows 10? I have disabled exclusive mode for my Bluetooth headset using the following steps:

*

*Press win+R

*Type mmsys.cpl

*Click on my headphones device in the list

*Click the Properties button

*Select the Advanced tab.

*Uncheck "Allow applications to take exclusive control of the device"

*Click OK

However, it doesn't work. System sounds from a remote computer that I am accessing using VMWare Horizon still grab exclusive access to my Bluetooth headphones, and prevent me hearing music that I was listening to.

A: This is related to the difference between A2DP mode (stereo, no microphone) and HFP mode (mono, with microphone). The Bluetooth headset can only be in one mode at once.
It seems the VMWare Horizon application can't really distinguish between wanting to use audio for listening to a system sound and wanting to use audio for the microphone - it just wants to grab both. Which has the side-effect of switching the headset mode from A2DP to HFP.
So in this usage context, these headphones aren't great for listening to music and also using an application which expects the microphone to work, like VMware Horizon (if it is configured to pass microphone input through to the remote compute).
(With small earbud-type headsets, they also have small, low-capacity batteries, so it is also inadvisable to use them for listening to music anyway, as by the time the time comes to use them for a call, they may not have enough battery left to last for a full call!)
The best thing to do is probably to switch to different, dedicated headphones or speakers for listening to music!
Alternatively, if your headphones don't have a microphone, or if you don't want to use their microphone, right-click on the headphones in the Recording tab and choose Disable.


text:
Q: multiline Jinja statement app.py
@app.context_processor
def example():
    date=['2019','2020']
    return dict(ArrayDate=date)

template.html
<select>
{% for k in ArrayDate: %}
   <option value="{{ k }}" {% if {{ k }} == 2019 %} selected {% endif %} >{{ k }}</option>
{% endfor %}
</select>

I have this error
jinja2.exceptions.TemplateSyntaxError: expected token ':', got '}'

This code is the problem but i don't understand
{% if {{ k }} == 2019 %} selected {% endif %}

A: answer
<select>
{% for k in ArrayDate: %}
   <option value="{{ k }}" {% if k == '2019' %} selected {% endif %} >{{ k }}</option>
{% endfor %}
</select>


text:
Q: Does pushing a block of code to background in Bash result in parallelization? Lets say I have a block of code like this:
while condition; do
  {
   command 1
   command 2
   command 3
  }
done

Does pushing the block of code between the curly braces to background  like this { code } & results in parallelization. Is there any improvement in performance by doing this for CPU intensive code blocks.


text:
Q: What is the benefit of Xcode's seemingly over-complicated control/outlet workflow? I'm new to Objective-C, Cocoa, Xcode and Interface Builder. I've got some C background in the past, as well as a fair amount of RealBASIC experience.
I'm working through Mark and LaMarche's iPhone 3 Dev book and I'm really just sort of stunned about how tedious some things are. Maybe someone can shed some light on this for me. My question really is, why does the process for seemingly simple actions involve such a complicated number of steps? Is there a benefit to the complexity which I'll come to love later? Or is it just a brute fact that is unavoidable?
For example, in RealBASIC, if I want a slider's value displayed in a text box, I simply add:
myTextBox.text = mySlider.value

to the slider's Changed event. I can program this in well under 1 minute.
In Xcode/Interface Builder, I have to physically type a declaration for both the text box and the slider, then type a property/outlet declaration for each as well, then create a method declaration and implementation for the ValueChanged even, then set up a (relatively) complicated typecast of the slider's integer value into an NSString using initWithFormat. I then have to return to Interface Builder to link up the controls with the control and method outlets I typed in. I don't see how this can be done in much less than 10 minutes. Maybe 5.
So, what's the benefit of this? Why doesn't Interface Builder automatically create, or at least suggest, control declarations and @property statements, as well as method declarations and implementations? Why can't double-clicking a slider in IB offer you a list of events and offer to automatically insert a skeleton method into your .h and .m file? And why does IB even have to be a separate application?
I'm willing to accept that some of this is my unfamiliarity with all things Xcode, but is this really as efficient as the development environment can be?
My apologies if this is a dead-horse, flame-bait topic with opposing sides on full aggro. If so, please just say "yes, that it is" and move on.
Thanks,
-Rob

A: A lot of the reasons behind the way IB works will become more clear as you get used to the MVC paradigm.
Once you start using Cocoa Bindings, which update your model when the UI changes and vice versa, you should see an enormous productivity improvement.

A: I too used to think that Xcode and Interface Builder were unnecessarily complicated, until I worked through a book on both (specifically, Beginning iPhone Development: Exploring the iPhone SDK).
If you're serious about working with Xcode and Interface Builder and are as confused as I was when I started, I highly recommend picking up a book like the one I used. Granted, that was for iPhone development, but I think there is another book by the same publisher (or author) that is straight Mac programming.
Once you work through it and understand what is going on behind the scenes it starts to make a lot more sense. In some ways I prefer IB to things like Expression Blend or XAML for WPF programming in .NET.
Give a book a try and see if it helps :-)
Good luck!


text:
Q: Salesforce Marketing Cloud - How to keep track of historical email addresses tied to one subscriber? So, the problem in a nutshell is I need to be able to keep track of when subscribers change their email addresses and tie them all back to the single subscriber.
Here's what I did - I set the Subscriber Key value to be a numeric identifier.  I then created a data extension and I set ID as the Subscriber Key.  I imported a sample data file with ID of 62078213 tied to mmarks@salesforce.com.  I sent myself an email and then clicked Profile Center, and changed my email address.
Here's what happened.  Before I made my change, I checked _Subscribers and found my record that was newly added from the email send.  Awesome.  Okay, then I updated my email address to mike@mikemarks.net from the stock preference center.  I then checked _Subscribers again:
select * from Cxxxxxxx._Subscribers with (nolock) where ID = 62078213

Running this query brought back the UPDATED record in _Subscribers - which had email address as the updated mike@mikemarks.net email address.  Further, I did
select * from Cxxxxxxxx._Subscribers with (nolock) where EmailAddress = 'mmarks@salesforce.com'

Recall, this was the ORIGINAL email address that was sent the email.
No results.  So, I don't know where the "historical" email addresses are stored, or if they even are - several people I've talked to mentioned that this is the way to go about it if you want to tie a subscriber back to multiple email addresses.  I wonder if there's a business rule that needs to be turned on.  Any insight would be terrific, if you know of anything I'm missing.

A: Historical email addresses are not stored by default.  If there is a reason that this information is needed then a SendLog might be a good option as that will log the value used at send-time to a data extension.  This data extension can then be queried to find the different addresses that were sent to for a given subscriber but wouldn't catch if they updated their email address between sends.
Send Logging:
http://help.marketingcloud.com/en/documentation/exacttarget/subscribers/send_logging/


text:
Q: SSRS - using a where clause for a placeholder Using SSRS 2012 and I am trying to create a tablix.
I have a dataset which is querying a database for a set of results.  I want to use a where clause in my tablix to specify a client name.  This will be done on different columns.  So column A will have one client name and B another and so on.  My first column is the date and the tablix should group by the date as there are multiple entries for each day and I need to sum the results.
I have the following expression within my placeholder
=SUM(IIF(Fields!clientname.Value = "Bob", Sum(Fields!s1_Weight.Value), 0))

So I need to sum all weights by date for the specified client name by date (one row for each date)
When I display the report I get 0's where there is no data, which is fine but where there should be data I get #error.  If I add a where clause to my dataset so for example
where clientname = 'Bob'

it works.
As I am adding multiple columns which need to look at different client names I can use this in my where clause.
Thanks

A: Try below expression
= IIF (Fields!clientname.Value = "Bob", Sum(Fields!s1_Weight.Value),0)


text:
Q: Remove Widget from QSplitter A long time ago, someone asked the same question. How to remove...
This was the answer:

When you hide() a child its space will be distributed among the other children. It will be reinstated when you show() it again.

I've tried the QSplitter::hide(),show(),update() functions and also delete.
Nothing worked.
//class.cpp

void PlainView::addComponent(QWidget *widget)
{
  qDebug() << _splitOne->widget(1);

  //delete current widget on index 1
  delete _splitOne->widget(1);
  //add new widget on index 1
  _splitOne->addWidget(widget);

  qDebug() << _splitOne->widget(1);
}

//output
QObject(0x0)
QTextEdit(0xa0f580

The first widget was deleted and the new widget was added. But I can't see the new widget.
Has anyone an idea?

A: don't use delete but instead use deleteLater() and you'll need to remove the old widget first:
void PlainView::addComponent(QWidget *widget)
{
  qDebug() << _splitOne->widget(1);
  QWidget *old = _splitOne->widget(1);

  // deparenting removes the widget from the gui
  old->setParent(0);
  //delete current widget on index 1
  old->deleteLater()

  //add new widget on index 1
  _splitOne->insertWidget(1,widget);
  widget->show();

  qDebug() << _splitOne->widget(1);
}


text:
Q: eclipse does not match constructor method call when pressing ctrl+space in eclipse I remember it used to match the objects for the data type in the diamond operator. but it dosn't anymore . for example :
public static void main(String[] args) {
        HashMap<String, String> map = new HashMap<**MISSING**>()
    }
anyway to turn it back on?
thnx.

A: Maybe because you are using Java7 compiler, which does not require params in the diamond operator.
Read more about it here: http://docs.oracle.com/javase/7/docs/technotes/guides/language/type-inference-generic-instance-creation.html

A: Are you running Java 7 ?
It's a new feature they added called "Type Inference for Generic Instance Creation"

You can replace the type arguments required to invoke the constructor
  of a generic class with an empty set of type parameters (<>) as long
  as the compiler can infer the type arguments from the context. This
  pair of angle brackets is informally called the diamond.

Before Java 7 :
Map<String, List<String>> myMap = new HashMap<String, List<String>>();

Now you can do :
Map<String, List<String>> myMap = new HashMap<>();


text:
Q: git svn clone ending with error I can't figure out I'm getting this error while importing a large SVN repo into Git. It runs for a long time and then dies with the error below.
D       resources/images/display-manager/
W: -empty_dir: trunk/resources/images/display-manager
Checking svn:mergeinfo changes since r29645: 29 sources, 1 changed
YAML::XS::Load Error: The problem:

    found unexpected end of stream

was found at document: 1, line: 127922, column: 120
while scanning a quoted scalar at line: 127922, column: 3

Could not unmemoize function `check_cherry_pick2', because it was not memoized to begin with at /usr/share/perl5/Git/SVN.pm line 1723.
END failed--call queue aborted.

I'm just spinning my tires here. Any suggestions anyone?


text:
Q: Is a container sure to be a range conceptually? From the documentation of ranges-v3:

view::all
Return a range containing all the elements in the source.
  Useful for converting containers to ranges.

What makes me confused are:

*

*Under what scenarios are view::all used?

*Are standard containers (std::vector, std::list, etc.) not
ranges conceptually?

For example:
auto coll = std::vector{ 1, 2, 2, 3 };
view::all(coll) | view::unique; // version 1
coll | view::unique; // version 2

Is there any difference between version 1 and version 2?

A: Egad, that part of the documentation hasn't been updated since range-v3 switched terminology. Yes, a container is a Range (it has begin() and end() that return an iterator/sentinel pair). It is not a View (a Range with O(1) copy/move). So, the documentation for view::all should read:

view::all
Return a View containing all the elements in the source. Useful for converting containers to Views.

To answer your second question, no there is no difference between version 1 and version 2 in your code.


text:
Q: VSTS Licensing and Release Management I am trying to understand the pricing for Release Management. I understand it is included as part of VSTS. We have Visual Studio Professional Licenses. Does that give us VSTS and Release Management as well?

A: Visual Studio Licenses and VSTS (Visual Studio Team Services) Release are separate things.
And VSTS Release is free (for five users per account), so you can create a VSTS account and then manage/build/release your project by VSTS. Detail steps as below:

*

*You can create a VSTS account in https://www.visualstudio.com/team-services/.

*Create a team project in VSTS and you can select the version control type (Git or TFVC) when creating a team project.

*Push/checkin your code to your repo (Git or TFVC).

*Create build and release definition to build and deploy your code.

There has an CI build and CD deploy process in VSTS, you can refer CI/CD Hello world.


text:
Q: How to display Out Of Stock product for only One Category while hiding them in all other category magento 2
Hi @all actually i wanted to display Out of stock products only in one category(Parent Category and it's all child categories) with  "Display Out Of Stock" option "Yes" in the admin?

It means here i need to hide Out of stock products for all rest of the categories.
Here i tried to follow this link
If Anyone having any idea please help here.
Thanks in Advance.

A: You can create your own block that override

\Magento\Catalog\Block\Product\ListProduct

And inside of that include the collection for Out of Stock Products
 protected function _getProductCollection() {
 ... some code here ...
 }

Create a template in frontend dir :

view/frontend/templates/module/mytemplate.phtml

Call your block there with the customizations you want to make .
After those are done , you can create a Cms Page called for ex: Out Of Stock and add this on  the content :
{{block class="My\Module\Block\Product\ListProduct" template="My_Module::module/mytemplate.phtml"}}

Run magento commands for clearing contents and setup upgrade .

A:
Vendor\Module\etc\di.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\CatalogSearch\Model\Search\IndexBuilder">
       <plugin name="Custom_Layernavigation::CustomLayernavigation"
       type="Vendor\Module\Plugin\CatalogSearch\Model\Search\IndexBuilder" />
    </type>
</config>

Vendor\Module\Plugin\CatalogSearch\Model\Search\IndexBuilder.php

<?php

namespace Vendor\Module\Plugin\CatalogSearch\Model\Search;

use Magento\Framework\DB\Select;
use Magento\Framework\Search\Request\FilterInterface;
use Magento\Framework\Search\Request\Filter\BoolExpression;
use Magento\Framework\Search\Request\Query\Filter;
use Magento\Framework\Search\RequestInterface;
use Magento\Framework\Search\Request\QueryInterface as RequestQueryInterface;
use Magento\Framework\App\ResourceConnection;
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Model\CategoryFactory;

class IndexBuilder
{
    /**
    * @var \Magento\Framework\App\Config\ScopeConfigInterface
    */
    protected $scopeConfig;

    /**
    * @var \Magento\Store\Model\StoreManagerInterface
    */
    protected $storeManager;
    protected $_stockFilter;
    private $layerResolver;
    protected $categoryRepository;
    protected $_categoryCollectionFactory;
    /**
     * @var Magento\Catalog\Model\CategoryFactory
     */
    protected $_categoryFactory;
    protected $registry;
    protected $_request;

    public function __construct(
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
        \Magento\Catalog\Model\Product\Visibility $productVisibility,
        \Magento\Catalog\Helper\Category $categoryHelper,
        \Magento\Framework\Registry $registry,
        \Magento\CatalogInventory\Helper\Stock $stockFilter,
        \Magento\Catalog\Model\Layer\Resolver $layerResolver,
        CategoryRepositoryInterface $categoryRepository,
        \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory,
        CategoryFactory $categoryFactory,
        \Magento\Framework\App\Request\Http $request
    ) {
        $this->storeManager = $storeManager;
        $this->_productCollectionFactory = $productCollectionFactory;
        $this->_productVisibility = $productVisibility;
        $this->categoryHelper = $categoryHelper;
        $this->registry = $registry;
        $this->_stockFilter = $stockFilter;
        $this->layerResolver = $layerResolver;
        $this->categoryRepository = $categoryRepository;
        $this->_categoryCollectionFactory = $categoryCollectionFactory;
        $this->_categoryFactory = $categoryFactory;
        $this->_request = $request;
    }

    /**
    * Build index query
    *
    * @param $subject
    * @param callable $proceed
    * @param RequestInterface $request
    * @return Select
    * @SuppressWarnings(PHPMD.UnusedFormatParameter)
    */
    public function aroundBuild($subject, callable $proceed, RequestInterface $request) {
        $select = $proceed($request);
        $storeId = $this->storeManager->getStore()->getStoreId();
        $rootCatId = $this->storeManager->getStore($storeId)->getRootCategoryId();
        $productUniqueIds = $this->getCustomCollectionQuery();
        $select->where('search_index.entity_id IN (' . join(',', $productUniqueIds) . ')');

        return $select;
    }

    /**
    *
    * @return ProductIds[]
    */
    public function getCustomCollectionQuery() {
        $websiteId = $this->storeManager->getStore()->getWebsiteId();
        $collection = $this->_productCollectionFactory->create();
        $collection->addAttributeToSelect('*');
        $collection->addAttributeToSelect(array('entity_id','sku'));
        $collection->addWebsiteFilter($websiteId);
        $collection->setVisibility($this->_productVisibility->getVisibleInSiteIds());
        $collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
       /*You can write your custom logic here...*/

        $getProductAllIds = $collection->getAllIds();
        $getProductUniqueIds = array_unique($getProductAllIds);
        return $getProductUniqueIds;
    }

}

This code will work in all scenario as like: category filters, layered navigations products count.Happy Coding :)


text:
Q: How to build and deploy kubernetes cluster to Google Cloud using Cloud Build and Skaffold? I am new to micro-services technologies and getting troubled with Google Cloud Build.
I am using Docker, Kubernetes, Ingres Nginx and skaffold and my deployment works fine in local machine.
Now I want to develop locally and build and run remotely using Cloud Platform so, here's what I have done:

*

*In Google Cloud, I have set up kubernetes cluster

*Set local kubectl context to cloud cluster

*Set up an Ingress Nginx load balancer

*Enabled Cloud Build API (no trigger setup)

Here's my create deployment and skaffold yaml files look like:

When I run skaffold dev, it logs out: Some taggers failed. Rerun with -vdebug for errors., then it takes some time and my network bandwidth.
The image does get pushed to Cloud Container Registry and I can access the app using load balancer's IP address but the Cloud Build History is still empty. Where am I missing?
Note: Right now I am not pushing my code to any online repository like github.
Sorry If the information I provide is insufficient, I am new to these technologies.

A: Cloud Build started working:
First, In Cloud Build settings, I enabled kubernetes Engine, Compute Engine and Service Accounts.
Then, I executed these 2 commands:

*

*gcloud auth application-default login:  As google describes it This will acquire new user credentials to use for Application Default Credentials

*As mentioned in ingress nginx -> deploy -> GCE-GKE documentation, this will Initialize your user as a cluster-admin
kubectl create clusterrolebinding cluster-admin-binding \
  --clusterrole cluster-admin \
  --user $(gcloud config get-value account)


text:
Q: Android Studio - Gradle Manifest Merging Failed I am building a demo app using actionbar sherlock in android studio and i was facing problem , mentioned in following link :-
Previous Problem
now after following the replies posted on above link i did some changes and now i am facing this
Gradle: Execution failed for task ':SherlockTest:processDebugManifest'.
> Manifest merging failed. See console for more info.

my application manifest file is :-
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.sherlocktest"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="16" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.sherlocktest.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

and  actionbar sherlock manifest file is :-
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          android:versionCode="440"
          android:versionName="4.4.0"
          package="com.actionbarsherlock">

  <uses-sdk
          android:minSdkVersion="10"
          android:targetSdkVersion="16"/>

  <application/>

</manifest>

i am not able to figure out what is the problem here, please help

A: For what I can see, if you have a multi-module project with Android Studio and gradle, the IDE try to merge manifest files from every module into a Main manifest.
If you have a module A and a module B, and in the A manifest you declare some activity from B module, gradle will enconter a issue when merging.
Try removing cross-module reference in manifest files.

A: That worked for me when adding the Google Play Services
android {
    compileSdkVersion 17
    buildToolsVersion "17.0.0"

    defaultConfig {
        minSdkVersion 10
        targetSdkVersion 16
    }
}

A: Make sure that in all your build.gradle scripts the minSdkVersion and targetSdkVersion correspond to those you have in your manifests:
android {
    defaultConfig {
       minSdkVersion 10
       targetSdkVersion 16
    }
}

This worked for me, I hope it does the trick for you, cheers.

A: That works for me.
My library project AndroidManifest.xml miss a application element
add one will fix it.
<application
    android:allowBackup="true"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
</application>

I use gradle clean projectName --info get the error information, and solve it.


text:
Q: Moser and Smale-Birkhoff homoclinic theorems I have found in J. Moser "Stable and Random Motion in Dynamical Systems" the theorem about the topological conjugacy to the Bernoulli shift on a symbol space, and then again very well summarized and explained in S. Wiggins "Introduction to nonlinear dynamical systems and chaos". In the end, Wiggins states the Smale-Birkhoff homoclinic theorem, with some indications on the differences from Moser's theorem, without giving the proof. I was wondering if theres is and where i can find the proof of that theorem; i discovered the planar case in an article of Birkhoff, which is unfortunately unfindable, and the general case from Smale's article "Diffeomorphisms with many periodic points", which requires more topological background respect to how it is stated in Wiggins' book.
Any advice? Thanks in advance.


text:
Q: Number of leaves in a tree If a tree has 5 vertices of degree 2, 3 vertices of degree 3, 4 vertices of degree 4, then how many leaves are there in that tree?
I know the tree has at least 12 vertices and so it must have at least 11 edges.  Also the number of leaves must be odd but I could not proceed further.

A: If $k$ is the number of leaves then the total number of vertices in the tree is $12+k$ with $11+k$ edges and the sum of the degrees is $\sum\deg(v)=(5\times 2)+(3\times 3)+(4\times 4)+(k\times 1)=35+k$. Now by handshaking lemma,
$$35+k=2(11+k)\Rightarrow k=13.$$

A:
Note that the number of leaves will be independent of how the verticies of valency $2,3$ & $4$ are joined. We reckon $\color{red}{13}$.


text:
Q: How to Save iterable value to a text file and then upload it to google drive with Flutter(Dart) I want to save the value data1 which contains iterable value of CallLog.get() to data1.txt file. I want to know that, how to upload the data1.txt file to google drive. The reason to save the value data1 is to upload it to google drive. Here is the code:
class Data {
  Future<Iterable<CallLogEntry>> data1 = CallLog.get();
  Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();
    // For your reference print the AppDoc directory
    print(directory.path);
    return directory.path;
  }

  Future<File> get _localFile async {
    final path = await _localPath;
    return File('$path/data1.txt');
  }

  Future<File> writeContent() async {
    final file = await _localFile;
    // Write the file
    return file.writeAsString('$data1');
  }

  Future<String> readcontent() async {
  try {
    final file = await _localFile;
    // Read the file
    String contents = await file.readAsString();
    return contents;
  } catch (e) {
    // If there is an error reading, return a default String
    return 'Error';
  }
}

And after upload this, how can I access the data1.txt and show the call logs from data1.txt to a ListView. I have created a Listview to show this but it shows me an error. Here is the error:

Class 'String' has no instance method 'toList'. Receiver: "Error"
  Tried calling: toList()

Here is the code of my ListView:
FutureBuilder(
                  future: Data().readcontent(),
                  builder: (context, snapshot) {
                    if (!snapshot.hasData)
                      return Center(child: CircularProgressIndicator());

                    List<CallLogEntry> entries = snapshot.data.toList();
                    return Scrollbar(
                      child: ListView.builder(
                        itemBuilder: (context, index) {
                          var entry = entries[index];
                          var mono = TextStyle(fontFamily: 'monospace');
                          return Column(
                            children: <Widget>[
                              Divider(),
                              Text('NUMBER   : ${entry.number}', style: mono),
                              Text('NAME     : ${entry.name}', style: mono),
                              Text('TYPE     : ${entry.callType}', style: mono),
                              Text(
                                  'DATE     : ${DateTime.fromMillisecondsSinceEpoch(entry.timestamp)}',
                                  style: mono),
                              Text('DURATION :  ${entry.duration}',
                                  style: mono),
                            ],
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.start,
                          );
                        },
                        itemCount: entries.length,
                      ),
                    );
                  })


text:
Q: UpdateSingleSalesforceObject - when does it actually return 0 value? The Salesforce AMPscript function UpdateSingleSalesforceObject returns 0 for failure according to documentation. However, all failures of the function we have simulated (for example: invalid SF id, invalid field name etc...) resulted in ERROR 500 and no value has been returned. It seems the only method to get an indication of an error using this function is by using SSJS try{} catch{} functions.
Why the documentation states it can return 0 value when failed - can someone clear this up? Thanks

A: Failure and Error are two different things. As per the document 0 is displayed only in case of Failure but not in case of error.
Example: IF(condition, True, False) When the condition didn't meet the criteria, the result will be False because the record failed the given condition.
Error: The error normally arises in software; it leads to a change in the functionality of the program
Here ERROR 500 means something has gone wrong on the website's server, but the server could not be more specific on what the exact problem is


text:
Q: What's the smartest way to copy-rename (backup) several files in different folders at once in the shell? I want to copy-backup several files in different folder at once before updating ntpd.
Example (one file only): sudo cp /usr/sbin/ntpd /usr/sbin/ntpd.old
Files:
/usr/bin/sntp
/usr/bin/ntp-keygen
/usr/bin/ntpq
/usr/sbin/ntpdc
/usr/sbin/ntpdate
/usr/sbin/ntpd

Desired result:
/usr/bin/sntp
/usr/bin/sntp.old
/usr/bin/ntp-keygen
/usr/bin/ntp-keygen.old
/usr/bin/ntpq
/usr/bin/ntpq.old
/usr/sbin/ntpdc
/usr/sbin/ntpdc.old
/usr/sbin/ntpdate
/usr/sbin/ntpdate.old
/usr/sbin/ntpd
/usr/sbin/ntpd.old

Does a smart one-liner exist to accomplish this task?

A: Use xargs:
cat filelist | xargs -I {} cp {} {}.old

A: Using a shell loop
Something like a simple loop, iterating over two directories and then matching files:
for dir in /usr/bin /usr/sbin; do
  for file in "$dir/"*ntp*; do
    sudo cp "$dir/$file" "$dir/$file.old"
  done
done

This will copy all files matching the *ntp* pattern in both directories to the same file name, with .old appended.
Make sure to quote the variables correctly as a safeguard against files with whitespace in their name. The pattern *ntp* must not be quoted so that it can be expanded.
Using find
You could use find and -exec too:
find /usr/bin /usr/sbin -type f -iname '*ntp*' -exec sudo cp {} {}.old \;

The above would be safer since it only runs on files – but you're not expecting to have directories called ntp, so that's fine, I suppose.


text:
Q: Next js website's reload redirects to homepage on apache server I have a static next js website hosted on apache server(control panel) at first when i reloaded a page it gave me a 404 error but now when i'm reloading it always goes to the homepage i tried to include .htaccess file on my public folder but it doesn't work; here is my .htaccess file:
    Options -MultiViews
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]

in another project thus .htaccess file worked just fine but now its not working; i use npm build & export &
I don't use any ssr function on my code. i'll be happy if you help me out what did i do wrong this time.


text:
Q: How to filter nested collection Entity Framework objects? Here is the problem:
I need to return a collection of objects with filtered nested collections.
E.g: there is a store with orders and I need to return a collection with stores that includes nested collections with orders but without orders from customers that are marked as deleted.
Here is what I try to do. But still no luck. Any suggestions are appreciated :)
public List<StoreEntity> GetStores(Func<Store, bool> storeFilter, Predicate<OrderEntity> orderFileter)
{
    IQueryable<StoreEntity> storeEntities = Context.Stores
        .Include(o => o.Order)
        .Include(cu => cu.Orders.Select(c => c.Customer))
        .Where(storeFilter)
        //.Where(rcu=>rcu.Orders.Select(cu=>cu.Customer.Deleted==false)) //just test this doesn't work
        .AsQueryable();

    List<StoreEntity> storeEntities = storeEntities.ToList();

    //storeEntities.ForEach(s => s.Orders.ToList().RemoveAll(c=>c.Customer.Deleted==true)); // doesn't work

    foreach (StoreEntity storeEntity in storeEntities)
    {
        storeEntity.Orders.ToList().RemoveAll(r=>r.Customer.Deleted==true);
    }

    return storeEntities;
}

The problem is that the filter is not applied. Customers that have deleted flag set as true stay in the collection.

A: You can't do that directly in a "neat" way, but you have a few options.
First of all, you can explicitly load the child collection after you've fetched the stores. See the Applying filters when explicitly loading related entities section.
If you don't want to make extra trips to the database, you will have to construct your own query and project the parent collection and the filtered child collections onto another object manually. See the following questions for examples:
Linq To Entities - how to filter on child entities
LINQ Query - how sort and filter on eager fetch
Edit
By the way, your first .Where(rcu=>rcu.Orders.Select(cu=>cu.Customer.Deleted==false)) attempt doesn't work since this way you are applying a filter to your parent collection (stores) rather than the nested collection (e.g. all the stores that don't have deleted customers).
Logically, the code filtering the nested collection should be placed in the Include method. Currently, Include only supports a Select statement, but personally I think it's time for the EF team to implement something like:
.Include(cu => cu.Orders.Select(c => c.Customers.Where(cust => !cust.IsDeleted)));

A: The problem with the code you currently have is this line:
storeEntity.Orders.ToList().RemoveAll(r=>r.Customer.Deleted==true);

storeEntity.Orders.ToList() returns a new List<OrderEntity> with the contents of storeEntity.Orders. From this new list, you remove all deleted customers. However, this list isn't used anywhere after that.
However, even if it would do what you want to, this would also remove those customers from the database, because your StoreEntity objects are still connected to the data context!
You really want to use a filter as you first tried in the commented Where. Please see Yakimych's answer for help on that.

A: Old topic, but I ran into a rather similar problem. I've searched a lot, and the MSDN link provided by Yakimych finally hinted me to a solution : explicitely disable lazy loading, and then do queries to filter the navigation properties. The result will then be "attached" to the main query, which would give something like that :
Context.Configuration.LazyLoadingEnabled = false;

var filteredOrders = Context.Orders.Where(x => x.Customer.Delete == false);

IQueryable<StoreEntity> storeEntities = Context.Stores
.Include(o => o.Order)
.Include(cu => cu.Orders.Select(c => c.Customer))
.Where(storeFilter)
.AsQueryable();


text:
Q: javascript class calling XMLHttpRequest internally, then handling onreadystatechange this thing almost works:
function myClass(url) {

this.source = url;
this.rq = null;
this.someOtherProperty = "hello";

// open connection to the ajax server
this.start = function() {
    if (window.XMLHttpRequest) {
        this.rq = new XMLHttpRequest();
        if (this.rq.overrideMimeType)
        this.rq.overrideMimeType("text/xml");
    } else
        this.rq = new ActiveXObject("Microsoft.XMLHTTP");

    try {
        this.rq.onreadystatechange = connectionEvent;
        this.rq.open("GET", this.source, true);
        this.rq.send(null);
        this.state = 1;
    } catch (err) {
        // some error handler here
    }

}

function connectionEvent() {
    alert("i'm here");
    alert("this doesnt work: " + this.someOtherProperty);
}

} // myClass
so it's nothing more than having the XMLHttpRequest object as a member of my class, instead of globally defined, and invoking it in the traditional way. however, inside my connectionEvent callback function, the meaning of "this" is lost, even though the function itself is scoped inside myClass. i also made sure that the object that i instantiate from myClass is kept alive long enough (declared global in the script).
in all the examples of using javascript classes that i saw, "this" was still available inside the inner functions. for me, it is not, even if i take my function outside and make it a myClass.prototype.connectionEvent. what am i doing wrong? thank you.

A: The reason it's not working is that in Javascript, this is defined entirely by how a function is called, not where it's defined. This is different than some other languages.
To have this mean what you expect, you'd have to ensure that explicitly by "binding" it:
this.start = function() {
    var self = this; // Set up something that survives into the closure

    /* ...lots of stuff omitted... */

    this.rq.onreadystatechange = function() {
        // Call `connectionEvent`, setting `self` as `this` within the call
        connnectionEvent.call(self);
    };

There's more information about this management in this blog post, but basically: When a function is called without any particular effort made to set this, this within the function will always be the global object (window, on browsers). There are two ways to set this when making a call:

*

*Using Function#call (or Function#apply) as I did above, passing in the object reference to use as this as the first parameter. That calls the function and sets this to whatever you passed in. The difference between #call and #apply is how you supply further arguments to pass into the function. With #call you supply them as further arguments to the #call call (e.g. func.call(thisArg, arg0, arg1, arg2)), whereas with #apply you supply them as an array in the second argument (func.apply(thisArg, [arg0, arg1, arg2])).

*Using dotted notation: If you have an object that has a property with a function assigned to it (like your start property), calling it by using the object instance, a dot, and the property name (this.start() or foo.start(), etc.) will call the function and set this to the object instance within the call. So the dotted notation does two entirely distinct things: Looks up the property and finds a function as its value, and calls the function such that this is set to the object during the call. Literally it's like: var f = obj.func; f.call(obj).

Slightly off-topic, but: Barring a really good reason to, I wouldn't reinvent this wheel. There are lots of libraries out there to simply XHR calls. jQuery, Prototype, Closure, and nearly all the rest.


text:
Q: How to organize my classes/inheritance/implementation correctly? I am currently working on a school project. In this project, we are supposed to first model the world seen from a doctor's perspective, including his patients, different pharmaceutical drugs (with interfaces such as liniment, pills and injections), prescriptions for drugs and containers for prescriptions and persons.
This is what the first part of the assignment says:
A pharmaceutical drug has a name, unique number and a price. A pharmaceutical drug is of type A (narcotic with an associated int representing how narcotic/potent the drug is), type B (strongly addictive with an associated int representing how addictive the drug is) or type C ("normal" without the associative int that the two other types have).
Types A, B and C are supposed to be implemented as interfaces. My problem is the way that I'm supposed to structure the classes; I strongly disagree that this is the best way to organize the classes, but upon researching different approaches, I find myself puzzled as to what is the best implementation.
I want to do something like this. Pharmaceutical drug could be an abstract class with 3 concrete subclasses:
                               PharmaceuticalDrug

                            /           |           \

                       Liniment        Pill       Injection

My problem is how do I implement type A, type B and type C because of the instance variables associated with those types. Types A and B require an extra instance variable to represent their "potency", whereas C does not. I could simply include the instance variable and set type C's instance variable to a non-functional value (like -1) to indicate that that value is not to be used, but this approach does not seem like a pretty solution to me, as I am to write prescriptions with all info to files later on and would like an easy way to loop through and do this without unnecessary tests and special cases for type C.
I've tried to think out several ways to solve this. The instructors have stated that we could use Type A, B and C as interfaces and implement them accordingly, but to my knowledge I cannot implement an interface depending on whether it's this type or implement the another one if it's the other type. I read into dynamic proxying, but it didn't seem like the exact same thing. Maybe I am wrong. If so, I apologize for my ignorance.
I would, in that case, like to do something like this:
(NOTE: I know this isn't working/real code and that implements should be after the class's name and inheritance from PharmaceuticalDrug, but it's just in order to illustrate what it is I'd like to do).
    public class Liniment extends PharmaceuticalDrug {
        ...

        public Liniment( String type ) {
            if ( type.equals( "A" ) ) {
                // make this class implement type A
            } else if ( type.equals( "B" ) {
                // make this class implement type B
            } else if ( type.equals( "C" ) { // type C
                // make this class implement type C **WITHOUT INSTANCE VARIABLE!**
            } else {
                System.out.println( "Error!" );
            }
        }

        ...
    }

Another way I thought could work, is to make Types A, B and C enums. However, I still don't know how I should tackle the unwanted instance variable I'd have for type C. I only want the instance variables associated with types A and B, as type C should have no extra features/instance variables.
The last way I thought I could do this: Make subclasses of Liniment, Pill and Injection, I.E. LinimentTypeA, LinimentTypeB, LinimentTypeC, PillTypeA, ..., InjectionTypeC. While this works, this looks ugly, makes a lot of repetitive code and makes me feel like there is a much simpler solution to my problem.
I want to be able to implement type A, B or C depending on which drug it is AND add/have an extra instance variable if the type is A or B, but NOT if the drug is of type C
Any ideas as to how I could best solve this problem?

A:
I could simply include the instance variable and set type C's instance
  variable to a non-functional value (like -1)

That is indeed a bad way. Just do it the "logical" way. Inheritance is the "is a" relation.  Type A, B and C are Drugs. So indeed they are subclasses of Drug. A and B have indeed an int property extra. It's even best to name the properties different: int potency for type A and int addictivity for type B.

The instructors have stated that we could use Type A, B and C as
  interfaces and implement them accordingly

That means that Drug is the super interface. TypeA, TypeB and TypeC are also interfaces that extends Drug. Implement them accordingly means that you have to create at least one concrete class that implements each Type.
The interfaces should contain the getters for the necessary properties.
One of the advantages of using interfaces is that you can inherit from more than one interface in Java. So you can implement for example concrete class: public class Marjuana implements TypeA, TypeB

A: For your drug type problems, you could do something like this:

*

*a general interface for drugs that holds all common methods

*an extension of the above interface for the A and B types that have that potency thing, with some getPotency()-like methods

*then you can create the A and B types as extensions of the above, and C as an extension of the general interface

*after that, your concrete drug implementations will be able to implement multiple drug types

Then, for your concrete LinimentTypeA and the like, you could try implementing a Factory pattern, which spits out instances of different extensions of your Liniment class (for example), depending on your type. An example:
class DrugFactory {
  public Liniment getLinimentInstance(String type) {
    switch (type) {
    case "A": return new Liniment() { // your overrides and other stuff here } ;
    // etc
    default: return null;
  }

  public Pill getPillInstance(String type) {
    // similar
  }

  // other stuff you might want
}

A: You might consider:

*

*Add a potency variable to the superclass for drug

*Define three interfaces (TypeA, TypeB, TypeC)

*Define interfaces for Liniment, Pill, Injection

*Then create subclasses of PharmaceuticalDrug like: TypeALiniment, TypeBLiniment, TypeCLimiment, etc.

where you use public class TypeALiniment extends PharmaceutialDrug implements TypeA, Liniment {xxx}


text:
Q: Building snap parts from subdirectories using different plugins I'm trying to create a snap for one of our projects. The project repository contains two directories and I want to build one with go plugin and the other with nodejs plugin. I tried building them as separate parts and using source-subdir but it did not work as I expected. So my question is how do I tell plugin to step into a directory before starting a build?
We normally build this project using docker go and node containers or using a build machine with build tools pre-installed. It has a working Makefile for this but I'm trying to avoid managing build dependencies externally (either on go/nodejs or docker) and use go/nodejs tools provided by snap craft plugins.
Update:
Here is a sketch of project structure:
./go-module-1/...
./go-module-2/...
./go-module-3/...
./go-module-main/static/package.json
./go-module-main/static/...
./go-module-main/main.go
./go-module-main/...
./pkg-build.sh
./...

So, the normal process for building this project would be:
(cd go-module-main && go build .)
(cd go-module-main/static && npm run build)
./pkg-build.sh

The go portion of project exposes restful API and nodejs part is actually only used for compiling client side app (Angular/SASS/bower/gulp).


text:
Q: C# Parse xml into arrays I have 400+ records of data in this format inside :
<rs:data>
   <z:row ows_ID='360' ows_LinkTitle='GEI Survey data to Sharepoint' ows_Project_x0020_Priority='0' ows_AssignedTo='615;#Jeremy, Ron' ows_Status='In Progress' ows_Priority='(2) Normal' ows_DueDate='2012-04-27 00:00:00' ows_PercentComplete='0.700000000000000' ows_Modified='2012-04-30 10:44:15' ows_Alignment='TSS Delivery Mgmt' ows_SME='44;#Lewis, Clark' />

   <z:row ows_ID='378' ows_LinkTitle='Create back end and environment to support User demographic reporting' ows_Project_x0020_Priority='0' ows_AssignedTo='615;#Sam, Johns' ows_Status='In Progress' ows_Priority='(2) Normal' ows_DueDate='2012-05-11 00:00:00' ows_PercentComplete='0.800000000000000' ows_Modified='2012-05-09 13:50:17' ows_Alignment='Team Internal' ows_SME='7;#CORP\sscer;#9;#CORP\vreer' />

   <z:row ows_ID='249' ows_LinkTitle='Training Material to Muti Media' ows_AssignedTo='620;#Jenkins, Kristen' ows_Status='Not Started' ows_Priority='(2) Normal' ows_DueDate='2012-08-10 00:00:00' ows_PercentComplete='0' ows_Modified='2012-05-16 11:20:29' ows_Alignment='Diver Support' ows_SME='1;#CORP\vsswer;#7;#CORP\adder' />

</rs:data>

how do I create indivisual array to store the values of ows_ID, ows_LinkTitle annd so on?

foreach (System.Xml.XmlNode node in activeItemData)
        {
            if (node.Name == "rs:data")
            {
                for (int i = 0; i < node.ChildNodes.Count; i++)
                {
                    if (node.ChildNodes[i].Name == "z:row")
                    {
                        string [] resultTitle;
     resultTitle = (node.ChildNodes[i].Attributes["ows_Title"].Value).ToArray();
                        Console.ReadLine();
                    }
                }
          }
      }

Its throwing error Error Cannot implicitly convert type 'char[]' to 'string[]' at resultTitle. How do I correct it? Thanks.
I did
char[] resultTitle;
resultTitle = (node.ChildNodes[i].Attributes ["ows_Title"].Value).ToArray();
string s = new string(resultTitle);
Console.ReadLine();

how do I do it for all the values of ["ows_Title"]. ? Thanks.

A: This code
char[] resultTitle;
resultTitle = (node.ChildNodes[i].Attributes ["ows_Title"].Value).ToArray();
string s = new string(resultTitle);
Console.ReadLine();

Takes a string value turns into a character array. ).ToArray() and then immediately converts the character array back into a string.
This is the same thing without the extra memory allocation
string s = node.ChildNodes[i].Attributes ["ows_Title"].Value;

If I were you however I would just use linq to xml. I'd also want to end up with a List<string>
XNamespace z = "#RowsetSchema";
List<string> list = (from row in xdoc.Descendants(z + "row")
                     select (string)row.Attribute("ows_LinkTitle")
                    ).ToList();

Complete sample
    static void Main(string[] args)
    {
        string xstring = @"<xml xmlns:rs='urn:schemas-microsoft-com:rowset'
                         xmlns:z='#RowsetSchema'>
                            <rs:data>
                                <z:row ows_ID='360' ows_LinkTitle='GEI Survey data to Sharepoint' ows_Project_x0020_Priority='0' ows_AssignedTo='615;#Jeremy, Ron' ows_Status='In Progress' ows_Priority='(2) Normal' ows_DueDate='2012-04-27 00:00:00' ows_PercentComplete='0.700000000000000' ows_Modified='2012-04-30 10:44:15' ows_Alignment='TSS Delivery Mgmt' ows_SME='44;#Lewis, Clark' />
                               <z:row ows_ID='378' ows_LinkTitle='Create back end and environment to support User demographic reporting' ows_Project_x0020_Priority='0' ows_AssignedTo='615;#Sam, Johns' ows_Status='In Progress' ows_Priority='(2) Normal' ows_DueDate='2012-05-11 00:00:00' ows_PercentComplete='0.800000000000000' ows_Modified='2012-05-09 13:50:17' ows_Alignment='Team Internal' ows_SME='7;#CORP\sscer;#9;#CORP\vreer' />
                               <z:row ows_ID='249' ows_LinkTitle='Training Material to Muti Media' ows_AssignedTo='620;#Jenkins, Kristen' ows_Status='Not Started' ows_Priority='(2) Normal' ows_DueDate='2012-08-10 00:00:00' ows_PercentComplete='0' ows_Modified='2012-05-16 11:20:29' ows_Alignment='Diver Support' ows_SME='1;#CORP\vsswer;#7;#CORP\adder' />
                          </rs:data>
                          </xml>";

        XDocument xdoc = XDocument.Parse(xstring); // there are other ways to construct your xdoc
        XNamespace z = "#RowsetSchema";
        List<string> list = (from row in xdoc.Descendants(z + "row")
                            select  (string)row.Attribute("ows_LinkTitle")
                            ).ToList();

        foreach (var item in list)
            Console.WriteLine(item);

    }

A: Simple just use
char[] resultTitle;

instead of
string [] resultTitle;


text:
Q: Warning: mysqli_stmt:: bind_result(): Number of bind variables doesn't match number of fields in prepared statement when calling stored procedure I'm trying to call a stored procedure that inserts a new record and returns the last id.
When I call the page I receive the above-mentioned error, with a reference to line 6.
$Str = 'Hello world';
$parentId = 1;

$lastId = 0;
$statement = $con->prepare('call createRecordReturnsId( ? , ? )');
$statement->bind_param("si",$Str,$parentId);
$statement->bind_result($lastId);
$statement->execute();

A: I just had to move the bind statement (line 7) to after the execute statement (line 8)
The following order works:
$Str = 'Hello world';
$parentId = 1;

$lastId = 0;
$statement = $con->prepare('call createRecordReturnsId( ? , ? )');
$statement->bind_param("si",$Str,$parentId);
$statement->execute();
$statement->bind_result($lastId);

The right order of operations is important, because when calling a stored procedure, mysqli does not know the number of variables that will be returned until the statement is executed.


text:
Q: Instance Url related error when connecting to SOAP API using Access Token in Python I am using salesforce-python-toolkit to connect to Salesforce SOAP API. I know how to connect to it using [user, password and security token]. But recently I have learned that I can connect to soap api using access token too. I just have to set access token in session header.
So I tried below code.
from sforce.partner import SforcePartnerClient
wsdl = '/path/to/partner.wsdl.xml'
fieldsDict = {}
fieldsDict[packagePrefix + 'external_field__c'] = externalField
fieldsDict[packagePrefix + 'status__c'] = deliveryStatus
client = SforcePartnerClient(wsdl)
header = client.generateHeader('SessionHeader')
header.sessionId = accessToken
header.serverUrl = serverUrl
client.setSessionHeader(header)
sObjects = []
sObject = client.generateObject(packagePrefix + 'package__c')
for (k,v) in fieldsDict.items():
    setattr(sObject, k, v)
result = client.upsert(packagePrefix + 'external_field__c', sObject)

But I am getting an error saying
Destination URL not reset. The URL returned from login must be set in the SforceService

I checked that the header only has sessionId attribute.
# ipython prompt
In [14]: header = client.generateHeader('SessionHeader')
In [15]: header
Out[15]:
(SessionHeader){
   sessionId = None
}

So there is no point in setting location/serverUrl attributes in header.
If it's any help, we can do number of operations on client (using salesforce-python-toolkit)
In [16]: client.
client.convertLead                    client.getServerTimestamp            client.setAllowFieldTruncationHeader
client.create                         client.getSessionId                   client.setAssignmentRuleHeader
client.delete                         client.getUpdated                     client.setCallOptions
client.describeGlobal                 client.getUserInfo                    client.setEmailHeader
client.describeLayout                 client.invalidateSessions             client.setLocaleOptions
client.describeSObject                client.login                          client.setLoginScopeHeader
client.describeSObjects               client.logout                         client.setMruHeader
client.describeTabs                   client.merge                          client.setPackageVersionHeader
client.emptyRecycleBin                client.process                        client.setPassword
client.generateHeader                 client.query                          client.setQueryOptions
client.generateObject                 client.queryAll                       client.setSessionHeader
client.getConnection                  client.queryMore                      client.setStrictResultTyping
client.getDeleted                     client.resetPassword                  client.setUserTerritoryDeleteHeader
client.getLastRequest                 client.retrieve                       client.undelete
client.getLastResponse                client.search                         client.update
client.getLocation                    client.sendEmail                      client.upsert

Can you tell me where to put this url? I am not sure which url the error is referring to either. Is it
https://login.salesforce.com/id/xxxxxxxxxx/yyyyyyyyyyyy   OR
https://na15.salesforce.com/......................

Please help me out here. Thanks.

A: I think you need to call
client._setEndpoint(serverUrl)

The Partner API Server URL should be of the form
https://{instance_url}/services/Soap/u/{version}/{orgid}

For example
https://na1.salesforce.com/services/Soap/u/31.0/00D50000000IZ3Z

If you've done OAuth, you can easily obtain the Partner API Server URL by calling the Identity Service. Append ?version=latest to the id property of the OAuth response, passing the access token in the Authorization HTTP header - see the documentation on Identity URLs for details. The Partner API Server URL is in the response, at urls.partner.


text:
Q: Entire extension of a function on a set with an accumulation point While thinking about the identity theorem the following question came in my mind:

Let $A\subset \mathbb{C}$ be a set with an accumulation point in $\mathbb{C}$.
  What properties does a function $f:A\to \mathbb{C}$ need, such that we can find an extension $\tilde{f}:\mathbb{C}
\to \mathbb{C}$ with $\tilde{f}(z)=f(z)$ for all $z\in A$ and $\tilde{f}$ is an entire function ?

My actual thoughts are:

*

*$f$ must be local lipschitz continuous

*We could try to calculate the coefficients of the Taylor Series, (my first thought is doing something like a limit of polnoymial interpolation, so taking a converging sequence $(b_n)_{n\in \mathbb{N}}$ with values in $A$ and solving $V_{(b_n)_{n\in \mathbb{N}}}\cdot (a_n)_{n\in \mathbb{N}}= (f(b_n))_{n\in \mathbb{N}}$, where
$V$ is an $\infty \times \infty$  Vandermonde-matrix). If this work we have the only possible canditate for $\tilde{f}$ namely $$\tilde{f}(z)=\sum_{n=0}^\infty a_n \cdot z^n$$ because of the identity theorem. So we just need to check whether $f(z)=\tilde{f}(z)$ for all elements of $A$, and wheter the radius of convergence of $\tilde{f}$ is infinity. From my very naive point of view this should  work iff $f$ admits such an extension, because the sums in the linear equation are unconditional convergent. So what are conditions for the equation to have a solution?

A: In fact one can compute potential coefficients of the power series of $\tilde{f}$.
We have the accumulation point $x$ and from definition we have a sequence $(z_n)_{n\in
\mathbb{N}}$ which converges to $z$ and $z_k\neq z$ for all $k\in \mathbb{N}$.
Now we know that
$$f\left( \lim_{n\to \infty} z_n \right)=\lim_{n\to \infty} f(z_n)$$
must hold else there can't be an continuous extension and furthermore no holomorphic one.
Wlog we can say that $x=0$. Let
$(a_n)_{n\in \mathbb{N}}$ be the coefficients of the power series representation of $\tilde{f}$.
From the given values we already can compute the coefficients. We get $a_0$ from the
continuity and furthermore we know that whenever $f$ admits an holomorphic extension
\begin{align*}
\lim_{z\to 0} \frac{\tilde{f}(z)-\sum_{k=0}^{n-1} a_k z^k }{z^n} &=
\lim_{z\to 0} \frac{\sum_{k=n}^\infty a_k z^k}{z^n}\\
& =\lim_{z\to 0} \sum_{k=n}^\infty a_k z^{k-n} \\
&= a_n
\end{align*}
must hold.
So taking our sequence which is a to $0$ converging sequence we can compute those coefficients starting
with $a_1$, $a_2$ and so on.
For sure this is only possible when those limits exist, but furthermore the existence of the limits
doesn't imply that our function admits an holomorphic extension, even if the radius of convergence
of $\sum_{n=0}^\infty a_n \cdot z^n$ is infinity. Here taking $f(z)=\exp\left(-\frac{1}{z^2}\right)$
and $A=\{ \frac{1}{n}: n \in \mathbb{N}\}$ gives a counter example, as all coefficients will
be zero, but obviously our function is not zero.


text:
Q: React Material-Table, How to bind data that is obtained remotely? The question comes from a issue where I need data binding and save it to a reducer so I can use pusher to modify the data when needed and it changes in real-time. The problems I find are that:

*

*I am new in react and I don't really know much about how to bind data variables.

*I am using remote data with fetch so the data can be refreshed but it can't seem to find a way to properly bind or even save it to a reducer.
Below, the relevant code:
class MainTable extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <MaterialTable
        tableRef={this.tableRef}
        columns={columnsSetup}
        options={materialTableOptions}
        data={query =>
          new Promise((resolve, reject) => {
            pageQuery = query.page;
            pageSizeQuery = query.pageSize;
            let url = GET_ORDERS_URL;
            url += 'qtt=' + pageSizeQuery;
            url += '&page=' + pageQuery;

            fetch(url)
              .then(response => response.json())
              .then(result => {
                resolve({
                  data: result.data,
                  page: result.page,
                  totalCount: result.totalElems
                });
              });
          })
        }
      />
    );
  }
}

A: Data fetching should be done in one of the react lifecycle methods. These are build-in functions that will be called on specific "life" events of your component, for example when it gets mounted (componentDidMount).
You should read the docs thoroughly to really get the hang of it.
To give you an example of the implementation of a lifecycle method, I fixed your code below.
A couple of important, but also opinionated, subjects to look into are: lifecycle methods, state, Async/await (instead of promises), Components: classes and hooks.
class MainTable extends React.Component {
  state = {
    data: {}
  };

  componentDidMount() {
    this.fetchData();
  }

  fetchData = async query => {
    let url = `${GET_ORDERS_URL}qtt=${query.pageSize}&page=${query.page}`;

    const response = await fetch(url);
    const result = response.json();

    this.setState({
      data: {
        data: result.data,
        page: result.page,
        totalCount: result.totalElems
      }
    });
  };

  render() {
    return (
      <MaterialTable
        tableRef={this.tableRef}
        columns={columnsSetup}
        options={materialTableOptions}
        data={this.state.data}
      />
    );
  }
}

Below is a functional component (exactly the same logic as above) that uses hooks:
import React, { useEffect, useState } from 'react';

function MainTable() {
  const [data, setData] = useState({});

  useEffect(() => {
    const fetchData = async query => {
      let url = `${GET_ORDERS_URL}qtt=${query.pageSize}&page=${query.page}`;

      const response = await fetch(url);
      const result = response.json();

      setData({
        data: result.data,
        page: result.page,
        totalCount: result.totalElems
      });
    };
    fetchData();
  }, [data]);

  return (
    <MaterialTable
      columns={columnsSetup}
      options={materialTableOptions}
      data={data}
    />
  );
}

A: Material-table is a fantastic out the box soloution for tables however, I don't particularity like the way the pagination is handled. I use await and async operators rather than promises and wanted my component to be responsible for managing the state rather than these promise methods that material-table wants you to provide. Material-table provide a way to completely override their pagination logic so this is what I did.
material-table's Pagination component appears to just be a wrapper Material UI's TablePagination component.
const [data,setData] = React.useState([])
const [pagination, setPagination] = React.useState({take: 20, page: 0})
const [count, setCount] = React.useState(0)

React.useEffect(() => {
  async function fetch() {
      var {result, count} = await someAsyncCallToServer()
      setData(fetch)
      setCount(count)
    }
    fetch()
  }
  ,[pagination])

const handleChangePage = (event, newPage) => {
    setPagination(old => ({...old, page: newPage}))
  }

...
<MaterialTable
  data={data}
  ...
  components = {{
     Pagination : props =>
       <TablePagination
         rowsPerPage={pagination.take}
         onChangeRowsPerPage={take => setPagination(old=> ({...old, take}))}
         page={pagination.page}
         count={count}
         onChangePage={handleChangePage}
        />
  }}
/>


text:
Q: next build throws error related to webpack When i run next build i get following error:

./node_modules/leaflet/dist/images/layers-2x.png
Module parse failed: Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)

> Build error occurred
Error: > Build failed because of webpack errors
    at /app/node_modules/next/dist/build/index.js:397:19
    at async Span.traceAsyncFn (/app/node_modules/next/dist/telemetry/trace/trace.js:60:20)
    at async Object.build [as default] (/app/node_modules/next/dist/build/index.js:77:25)
#

my next.config.js seems to be configured to process .png files. Project uses leaflet and react-leaflet libraries. Error says nothing about images that I put in /public/images
const { i18n } = require('./next-i18next.config');
const theme = require('./app/styles/antdoverrides');

module.exports = {
    webpackDevMiddleware: (config) => {
        config.watchOptions = {
            poll: 800,
            aggregateTimeout: 300,
        };
        return config;
    },
    module: {
        loaders: [
            {
                test: /\.(png|jpg|gif)$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {},
                    },
                ],
            },
        ],
    }
};

A: One common issue with using react leaflet with nexjs is that it will not work with ssr. Are you loading your leaflet component in with dynamic?
import dynamic from "next/dynamic";
import React from "react";
import { LeafletMapProps } from "src/components/Map/Leaflet/LeafletMap";
import { LeafletMarkerProps } from "src/components/Map/Leaflet/LeafletMarker";

// Load every leaflet component since they dont work with ssr
interface MapProps extends LeafletMapProps {}

const Map: React.FC<MapProps> = (props) => {
  const Map = React.useMemo(
    () =>
      dynamic(() => import("src/components/Map/Leaflet/LeafletMap"), {
        loading: () =>
A map is loading
,
        ssr: false,
      }),
    []
  );
  return <Map {...props} />;
};

interface MarkerProps extends LeafletMarkerProps {}
const Marker: React.FC<MarkerProps> = (props) => {
  const Marker = React.useMemo(
    () =>
      dynamic(() => import("src/components/Map/Leaflet/LeafletMarker"), {
        ssr: false,
      }),
    []
  );
  return <Marker {...props} />;
};

export { Map, Marker };


text:
Q: OpenERP logs are in UTC -- how to get them in the same timezone as the server? My OpenERP logs are showing timestamps in the UTC timezone, even though the actual server is in the America/Los_Angeles timezone.  This makes comparing the OpenERP logs against any of the other logs on the server a pain.
How can I get the OpenERP logs to be in the correct timezone?

A: This is a side effect of the decision to force the OpenERP server into the UTC timezone.  There is a bug report with a patch against the 7.0 sources that will get the logs back into the proper timezone.
For the curious, the heart of the fix is to replace logging.Formatter.converter with a function smart enough to adjust back to the local timezone:
def adjust_logging_timezone():
    logger_tz = pytz.timezone(config['timezone'] or detect_server_timezone())
    if logger_tz.zone != 'UTC':
        def converter(secs=None):
            dt = datetime(*time.localtime(secs)[:6])
            dt = UTC.localize(dt).astimezone(logger_tz)
            return dt.timetuple()
        logging.Formatter.converter = staticmethod(converter)


text:
Q: How do I create an instance of a class with two generic types? I'm trying to create an instance of a class ZipIterator which takes two arbitrary arrays as arguments and sets them equal to two private fields K[] and V[] via the constructor. In my Testing class' main method, I'm writing
import java.util.Iterator;

public class ZipIterator<K,V>
{
    private K[] arr1;
    private V[] arr2;
    private int pos = 0;

    public ZipIterator(K[] arr1, V[] arr2) {
        this.arr1 = arr1;
        this.arr2 = arr2;
    }

}

In my Testing class' main method, I'm trying to create a ZipIterator object like this
int[] arr1 = {1,5,3,1,6};
double[] arr2 = {2.3,42.1,1.6,6.43};
ZipIterator<int[],double[]> zip =  new ZipIterator<int[],double[]>(arr1,arr2);

but I keep getting the error:
error: incompatible types: int[] cannot be converted to int[][]

I'm not exactly sure what I am doing wrong. If anybody can help, it would be greatly appreciated!

A: Think about the signature of ZipIterator<K[], V[]> when K is int[] and V is double[].
What you need to instantiate is ZipIterator<Integer, Double>; you cannot parametrize a class with a primitive type.
Yes, it's inefficient because of boxing/unboxing. If you want higher performance, make wrapper classes that keep an array of a primitive type as an instance variable. Will be tricky to make it nicely parametric, though.

A: Look closely what happens:
You are using int[] as generic type K:
ZipIterator<int[], double[]> zip = new ZipIterator<int[],double[]>(arr1, arr2);

Your constructor, however, is accepting an array of K, so an array of int[] would require int[][]:
public ZipIterator(K[] arr1, V[] arr2) { ... }

Notes:

*

*You shouldn't use arrays with generics, use the List interface instead:
public ZipIterator(List<K> arr1, List<V> arr2) { ... }

Or, like 4castle mentioned, you can even use the Iterable interface.

*Unlike what others said, an array is always an object, even if it is an array of a primitive type. So using int[] for K is perfectly valid, whilst int is not.

A: It should be
ZipIterator<int,double> zip =  new ZipIterator<int,double>(arr1,arr2);

A: Use the wrapper classes
Integer[] arr1 = {1,5,3,1,6};
Double[] arr2 = {2.3,42.1,1.6,6.43};
ZipIterator<Integer,Double> zip =  new ZipIterator<>(arr1,arr2);

Edited my answer based on the comment by @4castle


text:
Q: required power supply for nichrome heating element? I am very new to electrical power math.  So please be friendly.  :-)
I am getting 28 gauge nichrome wire to make my own heating element.  Here are the specs and numbers of what I am attempting to do and what I know.  I would appreciate a second pair of eyes confirming my numbers and also help recommending the correct power supply.
A.  10ft of 28 gauge wire, straight  = Ohms Resistance 42.52.  I plan to coil the wire myself and then loop the coil through ceramic insulators
B.  I need to reach temperatures of 450 F (I don't need over, but I def need to consistently hit this temperature.

Using the above info, an online calculator has provided me the following:
Volts = 55.276

Required Amps.  1.3
Required Watts: 71.85
Resistance per foot: 4.252
Total Resistance: 42.52.

Questions:

*

*Is 55.276 volts the amount of volts needed going into my power supply, or the amount of volts coming out of my power supply?

*I have a spare (universal) HP laptop power supply with the following specs, is this power supply sufficient for my needs? :
 Input: 100-240v,  50-60Hz, 2.0A
 Output: 18.5v --- 6.5A, 120W

*When I cut the laptop connector off I assume I am going to see at least 2, probably three wires.  black, white and green (maybe red).  Do I connection both black/white to one end of the nichrome wire or do I connect black to one end and white to the other end?

A quick diagram:
110      Power Supply (PS)          PS split      Nichrome Wire
     _________________________
3]---|>>100/240v | 18v/120W>>|____/---black---o---{Wire EndA}--\
     -------------------------    \---white---o---{Wire EndB}--/

*I may have to get 26 or 30 gauge wire...knowing the above, will my power supply still be sufficient with those gauge wires for what I am looking to do?

*Lastly, what, if anything am I missing or possibly not understanding?

Thank you in advance.  This is all to make my own homemade plastic vacuum molding device.

A:
Is 55.276 volts the amount of volts needed going into my power supply,
  or the amount of volts coming out of my power supply?

That is the voltage you need to put across the nichrome wire, so it will be the output. You're not going to find a 55.276V power supply on the shelf, you're going to have to make your own.

I have a spare (universal) HP laptop power supply with the following
  specs, is this power supply sufficient for my needs? : Input:
  100-240v, 50-60Hz, 2.0A Output: 18.5v --- 6.5A, 120W

18.5V < 55.276V, so no.

When I cut the laptop connector off I assume I am going to see at
  least 2, probably three wires. black, white and green (maybe red). Do
  I connection both black/white to one end of the nichrome wire or do I
  connect black to one end and white to the other end?

It won't work like you want, so don't bother, but even if it would work, there is no standard for the color or number of wires in laptop power supplies.

I may have to get 26 or 30 gauge wire...knowing the above, will my
  power supply still be sufficient with those gauge wires for what I am
  looking to do?

Your power supply isn't sufficicent, but 26 or 30 gauge nichrome wire will have slightly different resistivity than 28 gauge. You'll need to redo your calculations for the gauge you're actually going to use.
It seems like you're pulling a lot of numbers out of thin air. Further, I would be very cautious trusting an online calculator's calculation. The 450F is probably the wire temperature itself. Is that what you really want?

A: 18.5 volt x 6.5 amps is 120 watts this is to much power you need the volt x amps to add to the correct wattage  so your looking for something to put out 72 watts of power any combo of amps x volts will do as long as you hit the correct wattage.


text:
Q: Multivalue input from chosen field giving patchy input strings from ArcPy? I made a small tool that can be run from a toolbox. It has a validation code to choose multiple values from a specified field from a specified feature layer. It looks quite ordinary:

The validation code is:
def updateParameters(self):
   if self.params[1].altered:
      if self.params[1].value:
         values = set()
         inlayer = self.params[0].value.value
         fieldname = self.params[1].value.value

         cursor = arcpy.SearchCursor(inlayer, None, None, infield)
         for row in cursor:
            values.add(row.getValue(infield))

         self.params[2].filter.list = sorted(values)

It gives me a nice multivalue list of values. But when I check some of them and run a simple script:
import arcpy
# Variables
inlayer = arcpy.GetParameterAsText(0)
infield = arcpy.GetParameterAsText(1)
invalues = arcpy.GetParameterAsText(2)
arcpy.SetParameter(3, invalues)

selected_values = invalues.split(";")

for selected_value in selected_values:
    arcpy.AddWarning(selected_value)

then it returns some unicode strings with an apostrophe and some not. I found out that if there is a gap in the value, it returns an unicode string with an apostrophe. I don´t get it why? There´s a example output of the forementioned script:

In this tool window I can see that these apostrophes already figure as input values!
Why is that, and how do I avoid it?
These inputs with apostrophes troubles me further in my script because
if "withoutgap":
  # returns True but
if "with gap":
  # returns False because the unicode string has apostrophes

running on Windows 8.1, ArcGIS for Desktop 10.1 Basic, Python 2.7

A: I'm not a python expert so your code looks OK to me, I assume you are using a set() as a way of removing duplicates? If not and your dataset really does have only 4 rows in it then try using a list as all the examples in the ESRI help file uses lists...
Before you try that I would spoof up a second dataset which YOU have created and typed in those words that you want in the list. If that works as expected then it would suggest its a problem in the source dataset. Now this would not surprise me if the dataset has originated from say EXCEL which allows users to type and copy anything into it... So visually everything looks the same but behind the scenes it could have non-visible characters.