text:
Q: Target vs Control using Automation Studio We are creating campaigns using automation studio due to campaign complexity. However, in these campaigns we are trying to implement Target vs control population.
The issue is we can't use the random Data Extension in the Automation Studio as it cannot be refreshed like a filtered Data Extension - through a filter activity.
Anyone have a suggestion on how to randomly segment our audience without a random Data Extension? Thank you

A: I would suggest creating the dedicated flag (Boolean field; or number field, if you plan to have more than two segments) and populate it i.e. with SQL activity from Automation Studio.
Using that flag you could segment leads for those who are in target and control population.
Sample scenario:
If you want to have always 10 percent of population marked as the control group, you can additionally put one SQL activity in your automation, and make query something like:
SELECT TOP 10 PERCENT
s.SubscriberKey,
'1' AS IsControlGroup
FROM [Data Extension] s WITH (nolock)
ORDER BY NEWID()

And set that query to update. It will take 10 percent of all subscribers that are in you DE, sort them semi-randomly and change the control group flag to true. The important part is to add to the query Primary Key of that table, to be able to update records.

A: @Grzegorz
To ensure that queries are executed without blocking from other SQL updates, query activities use SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED. This is equal to WITH (NOLOCK). Using the NOLOCK query hint is unnecessary.


text:
Q: Opencart where are extension status and position set? Quick question about open cart, where are extension status and position set? I can see in the code
$postion = $this->config->get($extension . '_position');

and also
'status'      => $this->config->get($extension . '_status')

However I can't see where these are defined?

A: At first, look into your  extension file ( for example 'payment/free_checkout.php') and search for something like that
$this->model_setting_setting->editSetting( 'free_checkout', $this->request->post);

This is where settings stored into database ( you can go deeper into setting model, if you want )
After that, open admin/index.php and look at lines 38 - 48.
You can see, system gets data from database and store data into config object.

A: In Opencart Positions are used by Modules. They are set in admin unders extensions/modules. When you click save - it saves them to the database table oc_settings under the modulename_module
When Opencart is launched - in INDEX.php there is this code
// Settings
$query = $db->query("SELECT * FROM " . DB_PREFIX . "setting WHERE store_id = '0' OR store_id = '" . (int)$config->get('config_store_id') . "' ORDER BY store_id ASC");

foreach ($query->rows as $setting) {
    if (!$setting['serialized']) {
        $config->set($setting['key'], $setting['value']);
    } else {
        $config->set($setting['key'], unserialize($setting['value']));
    }
}

it creates the config - a massive array of all the settings for the current store id.
Afterwards the position controllers (column_left.php, column_right.php, content_top.php and content_bottom.php) go through the extensions in the table oc_extension and finds all the modules that will need to be shown.
then it goes through this massive array CONFIG and collects the settings for these modules - this all is stored in a array $module_data
then the controller uses these settings to basicly launch every controller of the module that should be shown. It passes the controller route and $settings for every module in a foreach loop and in result gets a render of the modules.
You can access the config anywhere in the php file - it can be another controller, a model or even tpl file.
$this->config->get(...)

If you want - you can go directly to the databes oc_settings and get the data from there with these functions
$this->load->model('setting/setting'); // remeber to always load the model.
$this->model_setting_setting->editSetting( 'free_checkout', $this->request->post);

Hope this helps.
Also you can use this module to expend the number of positions for your opencart SUPER easy
Extra positions Unlimited

redpajama_set_name: RedPajamaStackExchange


text:
Q: The difference between series and parallel LC circuit I wanted to know if there is a difference between a series LC circuit and a parallel LC circuit, like these:
I noticed that the tuned circuit is all the time a series LC circuit, and I wondered if it could be a parallel LC circuit.
Also, I wanted to know if the series LC circuit works excatly as a parallel LC circuit (regarding the way they interchange the energy between both of them).

A: Both parallel and series L-C circuits are used.  They have opposite impedance characteristics of each other.
A inductor and capacitor in series has infinite impedance at 0 and infinite frequency, and 0 impedance at the resonant frequency.
A inductor and capacitor in parallel has 0 impedance at 0 and infinite frequency, and infinite impedance at the resonant frequency.
You don't have to just remember which case is which.  You can easily see from inspection whether the circuit has zero or infinite impedance at zero or infinite frequency.  In the series case, the impedance will obviously be infinite at DC due to the capacitor.  The inductor likewise has infinite impedance at infinite frequency.  In the parallel case, the inductor is a short at DC and the capacitor a short at infinite frequency.

A: To store energy, a circulating path must exist. The parallel LC has that path. A CLC PI (or LCL PI) also provide that circulating path. Hence well-intentioned VDD filtering with 2 caps in parallel and the inevitable small wiring/trace inductance between the 2 caps......is also a resonator. Consider 100uF and 0.1uf in parallel (will not resonate), connected with 4" wire on a breadboard.
We expect low impedances, but a high-frequency peak in impedance will occur; value of 100UF in series with 0.1uF is 0.1uF (minus 0.1%), which resonates with 0.1uH (4" wiring) to ring/resonate at 1.59MHz. Is this easy to dampen?
Z(0.1uF at 1.59MHz) = 1.00 ohms, so this is difficult to dampen. {at times, the ESR of the 2 capacitors, or even PCB trace resistance, is adequate to achieve Q=1 or 2. The necessary Rdampen is 2*sqrt(L/C) for Q=1 ; knowing Omega_Ring is 1/sqrt(L*C) and Zl = Omega_Ring * L, we substitute and wanting R = Zl for Q=1, we find R = Zl = (1/sqrt(L*C)) * L = sqrt(L/C) }
Now consider the series LC resonant circuit. [Shorting the source produces a parallel LC, which will store energy.] Simply inserting a seriesLC into a random point of a larger circuit, and expecting a null in voltage at Fresonant is poor design because the seriesLC impedance will interact with the larger circuit's impedances and produce surprises, unless the larger circuit is resistive at frequencies near the resonance; any extra L or C will shift the null's frequency. Any resistance will reduce the nulling, by dampening.


text:
Q: How can I decode a QR code after preprocessing the given image? I'm trying to detect and decode a QR code given in a number of images. The images are unique IDs. I'm using OpenCV to detect the QR code present in that image.
def detectQR(filepath):
    img = cv2.imread(filepath)
    qrdetect = cv2.QRCodeDetector()
    decodedText, points, _ = qrdetect.detectAndDecode(img)
    if points is not None:
        print(points)
        print(decodedText)
        #plt.imshow(img)
    else:
        print("QR code not detected")

With the above code, openCV is not detecting a QR code present anywhere in the image. So I thought of cropping the image in such a way that I only get the QR code. As the images are sometimes of different sizes, I resize them keeping the scaling of the image same, and then crop accordingly:
if img.shape[0] != 337:
    percentage = 33700/img.shape[0]
    width = int(img.shape[1] * percentage/100)
    height = int(img.shape[0] * percentage/100)
    dim = (width, height)
    img = cv2.resize(img, dim)

#print(img.shape)

crop_img = img[50:160, 10:110]
#plt.imshow(crop_img)

After the above code I then pass the image to a similar function above. In that function the filepath is not passed, but the cropped image is. The main functionality remains the same.
When I run the code, be it cropping a particular image manually to check, or resizing the images to same dimensions and then cropping those, I do just get the QR code, but however, I do not get the text.
Example:

I get the points, I get only the QR code which is being detected as well, but it doesn't print the decoded text.
I also tried scanning the same cropped image on my phone, and even the resized and cropped image, but it doesn't give me any output. However, if I scan the original image with the ID, I get the required text.
I'm not exactly sure at what point I'm going wrong. After checking the documentation, other stackoverflow questions and blogs, I've realised that the code is the same everwhere that I've written, but for all of them, the original image only contains the QR code and no other text so it gets decoded easily. There is no preprocessing done in anything I've checked before.
UPDATE: I just looked at this blog. They've used Pyzbar and Zbar to decode a QR image.
I made the following changes:

*

*Resize to a generic size and cropped the image so that I get QR code for all images. Empty list returned.

*Kept the original ID (with image, text etc). Empty list returned.

*Cropped for each QR code separately (as the images are of different sizes), and then I get the desired result.

So does resizing the image and then cropping it ruin the QR code? If so, how can I still manage to get the QR code from the original image for any ID without resizing the same?
NOTE: The idea behind it is that the user will be uploading his/her/their ID. So the size, lighting and stuff could differ.


text:
Q: Expectation of conditional probability generating function I have an expression for a conditional probability generating function (pgf) $P_{Y|N}(z)=(1-q+qz)^{Nm}$, where $N\overset{d}{\sim}Bi(n,p)$.
I need to use this to find the pgf for Y, $P_Y(z)$.
I know that $P_Y(z)=E[P_{Y|N}(z)]$, but it is here that I run into a conceptual problem in that how do I find the expectation of a conditional pgf?

A: $$\begin{align}\mathsf G_Y(z)~=~& \mathsf E(z^Y) & \textsf{by definition of pgf} \\[1ex] =~&\mathsf E(\mathsf E(z^Y\mid N)) & \textsf{via Iterated Expectation}\\[1ex] =~& \mathsf E(\mathsf G_{Y\mid N}(z)) & \textsf{by definition of conditional pgf} \\[1ex]=~& \mathsf E((1-q+qz)^{mN}) & \textsf{for the given pgf of }(Y\mid N) \\[1ex]=~& \mathsf G_N((1-q+qz)^m) & \textsf{by definition of pgf} \\[1ex] =~& (1-p+p(1-q+qz)^m)^n &\textsf{for the given pgf of }N\end{align}$$
That is all.


text:
Q: C++ Pimpl Idiom Incomplete Type using std::unique_ptr I apologize for the large amount of code required to demonstrate the issue.  I am having a problem using the pimpl idiom with std::unique_ptr.  Specifically the problem seems to occur when one class (which has pimpl'ed implementation) is used as member data in another composite class with pimpl'ed implementation.
Most of the answers I've been able to find deal with a lack of explicit destructor declaration, but as you can see here, I have declared and defined the destructors.
What is wrong with this code, and can it be modified to compile without changing the design?
Note: the error seems to occur in the definition of SomeComposite::getValue() and that the compiler cannot see the error until compile time.  The error is encountered in memory.h and the message is Invalid application of 'sizeof' to an incomplete type 'pimplproblem::SomeInt::impl'.
SomeInt.h
#pragma once
#include <iostream>
#include <memory>

namespace pimplproblem
{
    class SomeInt
    {

    public:
        explicit SomeInt( int value );
        SomeInt( const SomeInt& other ); // copy
        SomeInt( SomeInt&& other ) = default; // move
        virtual ~SomeInt();
        SomeInt& operator=( const SomeInt& other ); // assign
        SomeInt& operator=( SomeInt&& other ) = default; // move assign
        int getValue() const;

    private:
        class impl;
        std::unique_ptr<impl> myImpl;
    };
}

SomeInt.cpp
#include "SomeInt.h"

namespace pimplproblem
{
    class SomeInt::impl
    {
    public:
        impl( int value )
        :myValue( value )
        {}

        int getValue() const
        {
            return myValue;
        }
    private:
        int myValue;
    };

    SomeInt::SomeInt( int value )
    :myImpl( new impl( value ) )
    {}

    SomeInt::SomeInt( const SomeInt& other )
    :myImpl( new impl( other.getValue() ) )
    {}

    SomeInt::~SomeInt()
    {}

    SomeInt& SomeInt::operator=( const SomeInt& other )
    {
        myImpl = std::unique_ptr<impl>( new impl( other.getValue() ) );
        return *this;
    }

    int SomeInt::getValue() const
    {
        return myImpl->getValue();
    }
}

SomeComposite.h
#pragma once
#include <iostream>
#include <memory>
#include "SomeInt.h"

namespace pimplproblem
{
    class SomeComposite
    {

    public:
        explicit SomeComposite( const SomeInt& value );
        SomeComposite( const SomeComposite& other ); // copy
        SomeComposite( SomeComposite&& other ) = default; // move
        virtual ~SomeComposite();
        SomeComposite& operator=( const SomeComposite& other ); // assign
        SomeComposite& operator=( SomeComposite&& other ) = default; // move assign
        SomeInt getValue() const;

    private:
        class impl;
        std::unique_ptr<impl> myImpl;
    };
}

SomeComposite.cpp
#include "SomeComposite.h"

namespace pimplproblem
{
    class SomeComposite::impl
    {
    public:
        impl( const SomeInt& value )
        :myValue( value )
        {}

        SomeInt getValue() const
        {
            return myValue;
        }
    private:
        SomeInt myValue;
    };

    SomeComposite::SomeComposite( const SomeInt& value )
    :myImpl( new impl( value ) )
    {}

    SomeComposite::SomeComposite( const SomeComposite& other )
    :myImpl( new impl( other.getValue() ) )
    {}

    SomeComposite::~SomeComposite()
    {}

    SomeComposite& SomeComposite::operator=( const SomeComposite& other )
    {
        myImpl = std::unique_ptr<impl>( new impl( other.getValue() ) );
        return *this;
    }

    SomeInt SomeComposite::getValue() const
    {
        return myImpl->getValue();
    }
}

A: You can't use defaulted constructors and assignment operators (such as SomeInt( SomeInt&& other ) = default;) declared in header file with Pimpl classes, because the default implementations are inline, and at the point of declaration SomeInt's declaration SomeInt::impl is incomplete, so unique_ptr complains. You have to declare and define out of line (that is, in implementation file) all special member functions yourself.
That is, change SomeInt and SomeComposite declarations as follows:
// SomeInt.h
SomeInt( SomeInt&& other ); // move
SomeInt& operator=( SomeInt&& other ); // move assign

// SomeInt.cpp
// after definition of SomeInt::impl
SomeInt::SomeInt( SomeInt&& other ) = default;
SomeInt& operator=( SomeInt&& other ) = default;

Another option is to create your own Pimpl pointer, as suggested in this answer.


text:
Q: Making a simple Keras classification with a low sample size I am trying to learn Keras and rather than starting with a large dataset I dont understand, I figured it would be better to create a simple dataset that in theory should be abe to have a 100% succesful prediction rate, but it only predicts 16.67% correct (?).
I tried to adjust some of the the epoc and batch_size values, but nothing works. What should I do here. Thanks in advance.
X = [0,1,2,3,4,5,6,7,8,9,10,11,12]
Y = [0,0,0,0,0,0,0,1,1,1,1,1,1]
le = 1

encoder = LabelEncoder()
encoder.fit(Y)
encoded_Y = encoder.transform(Y)

def create_baseline():

    model = Sequential()
    model.add(Dense(le, input_dim=le, kernel_initializer='normal', activation='relu'))
    model.add(Dense(1, kernel_initializer='normal', activation='sigmoid'))

    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
    return model

estimator = KerasClassifier(build_fn=create_baseline, epochs=1, batch_size=12, verbose=0)
kfold = StratifiedKFold(n_splits=2, shuffle=True, random_state=seed)
results = cross_val_score(estimator, X, Y)
print("Results: %.2f%% (%.2f%%)" % (results.mean()*100, results.std()*100))


text:
Q: Matplotlib is working but the images are super small I have a plot working I think, but when I go to plt.show() it just prints off tiny images. I cant really see what it is. The raw image size is 160X60. How can I make the images larger so I can see what they are? The score is a number and the resultID is a name of the image
Thank you for any help
Here is the code that I am using.
n_retrieval = len(result)
fig = plt.figure(figsize=(2*n_retrieval, 4))
fig.suptitle("Image Retrieval (k={})".format(n_retrieval), fontsize=25)

# Plot the Query image
ax = plt.subplot(2, n_retrieval, 0 +1)
q_img = mpimg.imread(queries + "0002_c1s1_000451_03.jpg")
plt.imshow(q_img)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
for axis in ['top', 'bottom', 'left', 'right']:
    ax.spines[axis].set_linewidth(4)  # increase border thickness
    ax.spines[axis].set_color('black')  # set to black
ax.set_title("query",  fontsize=14)  # set subplot titl

for i, (score, resultID) in enumerate(results):
    result_path = resultID.split('\\')[1]
    image_path = dataset+ result_path
    img = mpimg.imread(image_path)
    ax = plt.subplot(2, n_retrieval, n_retrieval + i + 1)
    plt.imshow(img)
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
    for axis in ['top', 'bottom', 'left', 'right']:
        ax.spines[axis].set_linewidth(1)  # set border thickness
        ax.spines[axis].set_color('black')  # set to black
    ax.set_title("Rank #%d" % (i+1), fontsize=14)  # set subplot title

plt.show()

A: Use big numbers in figsize.
fig = plt.figure(figsize=(18, 10))

A: Never Mind. For some reason if you double click on the image in Jupiter it will enlarge it. Its so weird.


text:
Q: LCS ALGORITHM ( example ) There's a dynamic programming algorithm to find the Longest Common Subsequence of two sequences. How can I find the LCS algorithm of two sequences X and Y. (Test of correctness)
(a)   X  = ABEDFEESTYH  Y=ABEDFEESTYHABCDF

(b)  X =  BFAAAABBBBBJPRSTY  Y=ABCDEFGHIJKLMNOPRS

(c)  X = ϕ (Empty Sequence), Y = BABADCAB

A: Here is an online calculator
http://igm.univ-mlv.fr/~lecroq/seqcomp/node4.html
Java
public class LCS {

    public static void main(String[] args) {
        String x = StdIn.readString();
        String y = StdIn.readString();
        int M = x.length();
        int N = y.length();

        // opt[i][j] = length of LCS of x[i..M] and y[j..N]
        int[][] opt = new int[M+1][N+1];

        // compute length of LCS and all subproblems via dynamic programming
        for (int i = M-1; i >= 0; i--) {
            for (int j = N-1; j >= 0; j--) {
                if (x.charAt(i) == y.charAt(j))
                    opt[i][j] = opt[i+1][j+1] + 1;
                else
                    opt[i][j] = Math.max(opt[i+1][j], opt[i][j+1]);
            }
        }

        // recover LCS itself and print it to standard output
        int i = 0, j = 0;
        while(i < M && j < N) {
            if (x.charAt(i) == y.charAt(j)) {
                System.out.print(x.charAt(i));
                i++;
                j++;
            }
            else if (opt[i+1][j] >= opt[i][j+1]) i++;
            else                                 j++;
        }
        System.out.println();

    }

}

A: EDIT: C++ implementation: http://comeoncodeon.wordpress.com/2009/08/07/longest-common-subsequence-lcs/
There's a dynamic programming algorithm to find the Longest Common Subsequence of two sequences (assuming that's what you meant by LCS): http://en.wikipedia.org/wiki/Longest_common_subsequence_problem
Here's the recurrence (from Wikipedia):

and the pseudocode (also from Wikipedia):
function LCSLength(X[1..m], Y[1..n])
    C = array(0..m, 0..n)
    for i := 0..m
       C[i,0] = 0
    for j := 0..n
       C[0,j] = 0
    for i := 1..m
        for j := 1..n
            if X[i] = Y[j]
                C[i,j] := C[i-1,j-1] + 1
            else:
                C[i,j] := max(C[i,j-1], C[i-1,j])
    return C[m,n]

It's then possible to reconstruct what the longest subsequences are from the C array (see the Wikipedia article).

A: I have written a implementation in Ruby. It's a extension of String Class :
class String

def lcs_with(str)
    unless str.is_a? String
        raise ArgumentError,"Need a string"
    end

    n = self.length + 1
    m = str.length + 1

    matrix = Array.new(n, nil)
    matrix.each_index  do |i|
        matrix[i] = Array.new(m, 0)
    end

    1.upto(n - 1) do |i|
        1.upto(m - 1) do |j|
            if self[i] == str[j]
                matrix[i][j] = matrix[i - 1][j - 1] + 1
            else
                matrix[i][j] = [matrix[i][j - 1], matrix[i - 1][j]].max
            end
        end
    end
    matrix[self.length][str.length]
end

end

puts "ABEDFEESTYH".lcs_with "ABEDFEESTYHABCDF"


text:
Q: script in bash not understood using terminal in Ubuntu 12.04 Can anyone tells me what does this script means found in a .sh file:
[ ! -n "$T_R" ] && echo "Message Appear" && exit 1;

A: Edit: Correcting for misinformation pointed out by tripleee
The brackets [ ]
    are an alias for 'test', which tests whether a condition is met. Not to complicate matters, but do note that this is discrete from the the bash shell keyword   [[ ]] (Thanks, tripleee for clearing that up!).  See This post for further details. These days, most people seem to use the latter due to its more robust feature set.
Between the brackets, the script is testing to determine whether the variable "$T_R" is an empty string.

*

*The -n operator returns true if the length of the string passed to it as an argument is non-empty.

*The ! inverts the case (the test succeeds if the result is not
true). So in this case, test suceeds (returns 0) if the length of
the string variable "$T_R" is **not non-zero ** (i.e. if the
variable is an empty-string, or is non-existant).

The double-ampersand, && operator means only execute the subsequent code in the event of success, so the message "Message Appear" will only be echoed in the event the test succeeds (again, if "$T_R" is empty or unset).
Finally, the && exit 1 says to exit returning status 1 after successfully echoing the Message Appear message.
The bash and test man pages are extremely helpful  on all of these topics and should be consulted for further details.

A: The chained && is a common short-circuit idiom.
Instead of writing
if true; then
  if true; then
    echo moo
  fi
fi

you can abbreviate to just true && true && echo moo.
echo will usually succeed so true && echo moo && exit 1 will execute both the echo and the exit if true succeeds (which obviously it always will).
(There are probably extreme corner cases where echo could fail, but if that happens, you are toast anyways so I don't think it makes sense to try to guard against those.)
The [ is an alias for test which is a general comparison helper for shell scripts (in Bash, it's even a built-in).  test -n checks whether a string is non-empty.
! is the general negation operator, so it inverts the test to checking for an empty string.
(This is slightly unidiomatic, because there is a separate test -z "$T_R" which checks specifically for the string being empty.)


text:
Q: Paging Library without Room All examples of the new paging library have been with Room library and Room creates a Data Source for us. In my own case, I need to create my custom data source.
Here is a method in my view model class that ought to return the live data. My livedata always returns null.
 LiveData<PagedList<ApiResult>> getData(){

    LivePagedListProvider<Integer,ApiResult> p = new LivePagedListProvider<Integer, ApiResult>() {
        @Override
        protected DataSource<Integer, ApiResult> createDataSource() {
            return new DataClass();
        }

    };

    listLiveData = p.create(0,new PagedList.Config.Builder()
            .setPageSize(5) //number of items loaded at once
            .setPrefetchDistance(0)// the distance to the end of already loaded list before new data is loaded
            .build());
    return listLiveData;
}

And here is the Data class
public class DataClass extends TiledDataSource<ApiResult> {

    private List<ApiResult> result = new ArrayList<>();

    @Override
    public int countItems() {
        return result.size();
    }

    @Override
    public List<ApiResult> loadRange(int startPosition, int count) {

        Call<String> call = NetworkModule.providesWebService().makeRequest();
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
                Log.i(DataClass.this.getClass().getSimpleName() + " - onResponse", String.valueOf(response));
                result = parseJson(response.body());
            }

            @Override
            public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
                Log.i(DataClass.this.getClass().getSimpleName() + " - onFailure", t.getMessage());
            }

        });

        return result;
    }

}

A: I think this can help:
 1. countItems() should return DataSource.COUNT_UNDEFINED
 2. loadRange(int startPosition, int count): You can directly execute your query.
 3. So now you can delete result global variable
Also, turnoff placeholders:
listLiveData = p.create(0,new PagedList.Config.Builder()
        .setPageSize(5) //number of items loaded at once
        .setPrefetchDistance(10) //Must be >0 since placeholders are off
        .setEnablePlaceholders(false)
        .build());

Here is the updated code for Data Class:
public class DataClass extends TiledDataSource<ApiResult> {

@Override
public int countItems() {
 return DataSource.COUNT_UNDEFINED;
}

@Override
public List<ApiResult> loadRange(int startPosition, int count) {

 Call<String> call = NetworkModule.providesWebService().makeRequest();
 Response<String> response = call.execute();
 return parseJson(response.body());
}

You can check an example project here:
https://github.com/brainail/.samples/tree/master/ArchPagingLibraryWithNetwork

A: You can create a Custom Data Source, usually we built backend API to fetch data that takes pagenumber as a parameter to return the specified page.
For this situation you can use PageKeyedDataSource. Here is a sample code of PageKeyedDataSource using the StackOverflow API. The below code is using Retrofit to get the data from the StackOverflow API.
public class ItemDataSource extends PageKeyedDataSource<Integer, Item> {

    //the size of a page that we want
    public static final int PAGE_SIZE = 50;

    //we will start from the first page which is 1
    private static final int FIRST_PAGE = 1;

    //we need to fetch from stackoverflow
    private static final String SITE_NAME = "stackoverflow";

    //this will be called once to load the initial data
    @Override
    public void loadInitial(@NonNull LoadInitialParams<Integer> params, @NonNull final LoadInitialCallback<Integer, Item> callback) {
        RetrofitClient.getInstance()
                .getApi().getAnswers(FIRST_PAGE, PAGE_SIZE, SITE_NAME)
                .enqueue(new Callback<StackApiResponse>() {
                    @Override
                    public void onResponse(Call<StackApiResponse> call, Response<StackApiResponse> response) {
                        if (response.body() != null) {
                            callback.onResult(response.body().items, null, FIRST_PAGE + 1);
                        }
                    }

                    @Override
                    public void onFailure(Call<StackApiResponse> call, Throwable t) {

                    }
                });
    }

    //this will load the previous page
    @Override
    public void loadBefore(@NonNull final LoadParams<Integer> params, @NonNull final LoadCallback<Integer, Item> callback) {
        RetrofitClient.getInstance()
                .getApi().getAnswers(params.key, PAGE_SIZE, SITE_NAME)
                .enqueue(new Callback<StackApiResponse>() {
                    @Override
                    public void onResponse(Call<StackApiResponse> call, Response<StackApiResponse> response) {

                        //if the current page is greater than one
                        //we are decrementing the page number
                        //else there is no previous page
                        Integer adjacentKey = (params.key > 1) ? params.key - 1 : null;
                        if (response.body() != null) {

                            //passing the loaded data
                            //and the previous page key
                            callback.onResult(response.body().items, adjacentKey);
                        }
                    }

                    @Override
                    public void onFailure(Call<StackApiResponse> call, Throwable t) {

                    }
                });
    }

    //this will load the next page
    @Override
    public void loadAfter(@NonNull final LoadParams<Integer> params, @NonNull final LoadCallback<Integer, Item> callback) {
        RetrofitClient.getInstance()
                .getApi()
                .getAnswers(params.key, PAGE_SIZE, SITE_NAME)
                .enqueue(new Callback<StackApiResponse>() {
                    @Override
                    public void onResponse(Call<StackApiResponse> call, Response<StackApiResponse> response) {

                        if (response.body() != null) {
                            //if the response has next page
                            //incrementing the next page number
                            Integer key = response.body().has_more ? params.key + 1 : null;

                            //passing the loaded data and next page value
                            callback.onResult(response.body().items, key);
                        }
                    }

                    @Override
                    public void onFailure(Call<StackApiResponse> call, Throwable t) {

                    }
                });
    }
}

Here you can see we are getting the result by making a Retrofit call and then we are pushing the result to callback.
For a detailed, step by step explanation go through this Android Paging Library Tutorial.


text:
Q: How to solve System.Runtime.CompilerServices.Unsafe FileNotFoundException Google Protobuf? (Using C++ and C#) In Unity After having changed my C++ code through my previous question, I found myself unable to display the data within Unity. It has a Debug.Log function which should display the 'array' I sent through from C#. Now this issue had evolved into a FileNotFoundException, tying into the currently asked question.
The error is as follows:
FileNotFoundException: Could not load file or assembly 'System.Runtime.CompilerServices.Unsafe, Version=4.0.4.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies.
Google.Protobuf.CodedInputStream.ReadFloat () (at <817bcbeeba124ec59e5347ee91ea8025>:0)
Sphere.Sphere+Types+Position.MergeFrom (Google.Protobuf.CodedInputStream input) (at Assets/Scripts/Test/Sphere/Sphere.cs:385)
Google.Protobuf.ParsingPrimitivesMessages.ReadRawMessage (Google.Protobuf.ParseContext& ctx, Google.Protobuf.IMessage message) (at <817bcbeeba124ec59e5347ee91ea8025>:0)
Google.Protobuf.ParsingPrimitivesMessages.ReadMessage (Google.Protobuf.ParseContext& ctx, Google.Protobuf.IMessage message) (at <817bcbeeba124ec59e5347ee91ea8025>:0)
Google.Protobuf.CodedInputStream.ReadMessage (Google.Protobuf.IMessage builder) (at <817bcbeeba124ec59e5347ee91ea8025>:0)
Sphere.Sphere.MergeFrom (Google.Protobuf.CodedInputStream input) (at Assets/Scripts/Test/Sphere/Sphere.cs:199)
Google.Protobuf.ParsingPrimitivesMessages.ReadRawMessage (Google.Protobuf.ParseContext& ctx, Google.Protobuf.IMessage message) (at <817bcbeeba124ec59e5347ee91ea8025>:0)
Google.Protobuf.ParsingPrimitivesMessages.ReadMessage (Google.Protobuf.ParseContext& ctx, Google.Protobuf.IMessage message) (at <817bcbeeba124ec59e5347ee91ea8025>:0)
Google.Protobuf.FieldCodec+<>c__DisplayClass32_0`1[T].<ForMessage>b__0 (Google.Protobuf.ParseContext& ctx) (at <817bcbeeba124ec59e5347ee91ea8025>:0)
Google.Protobuf.Collections.RepeatedField`1[T].AddEntriesFrom (Google.Protobuf.ParseContext& ctx, Google.Protobuf.FieldCodec`1[T] codec) (at <817bcbeeba124ec59e5347ee91ea8025>:0)
Google.Protobuf.Collections.RepeatedField`1[T].AddEntriesFrom (Google.Protobuf.CodedInputStream input, Google.Protobuf.FieldCodec`1[T] codec) (at <817bcbeeba124ec59e5347ee91ea8025>:0)
Sphere.Spheres.MergeFrom (Google.Protobuf.CodedInputStream input) (at Assets/Scripts/Test/Sphere/Sphere.cs:704)
Google.Protobuf.MessageExtensions.MergeFrom (Google.Protobuf.IMessage message, System.IO.Stream input, System.Boolean discardUnknownFields, Google.Protobuf.ExtensionRegistry registry) (at <817bcbeeba124ec59e5347ee91ea8025>:0)
Google.Protobuf.MessageParser`1[T].ParseFrom (System.IO.Stream input) (at <817bcbeeba124ec59e5347ee91ea8025>:0)
Sphere_receive.Start () (at Assets/Scripts/Test/Sphere/Sphere_receive.cs:22)

EDITED The corresponding Sphere.cs block appeared to be to big for the body in its entirety, if you want to look at it please ask.
Now my own C# implementation of the original idea looked something like this:
using System.Collections;
using System.IO;
using UnityEngine;
using Sphere;
using Google.Protobuf;
using System.Runtime.CompilerServices;

public class Sphere_receive : MonoBehaviour
{
    private GameObject blockObj1, blockObj2, blockObj3;
    private Vector3 position1, scale1, position2, scale2, position3, scale3;
    private Spheres sphereCollection;
    private string String;

    // Start is called before the first frame update
    void Start()
    {

    using(var input = File.OpenRead("./Assets/Scripts/sphereData.dat"))
    {
        sphereCollection = Spheres.Parser.ParseFrom(input);
    }

    Debug.Log(sphereCollection.ToString());

    }

    // Update is called once per frame
    void Update()
    {

    }
}

I dont know exactly whether the fact my Debug.Log not showing could be related to the thrown error, or if my implementation is simply wrong.

A: Okay so, after some very painful experimentation what has appeared to be the proper solution for me here was the following:

*

*I looked up System.Runtime.CompilerServices.Unsafe v4.5.3 on the NuGet Gallery and dowloaded the package. (Version 4.5.3 is also assembly version 4.0.4.1)

*Changed the downloaded .nupkg to a .zip (Don't know if it's a relevant step or not though)

*Extracted it and located the System.Runtime.CompilerServices.Unsafe.dll file within the lib/netstandard2.0 folder

*Dragged this .dll into the project folder

Seems the solution appeared a lot more simplistic than I had originally foreseen.


text:
Q: A problem of normal distribution If $X_i \sim \mathcal{N}(0,\sigma^2)$ for $i=1,2, \ldots, 2n$ then what is the distribution of
$\dfrac{\sum\limits_{i=1}^{n} X_i^2}{\sum\limits_{i=n+1}^{2n} X_i^2}$  ?
Unfortunately I can't figure out how to start working with this problem. Any help?

A: It's a non-normalized F-distribution.
The F-distribution (on rare occasions called the Beta distribution of the second kind) is usually defined as that of the quotient
$$
\frac{\sum_{i=1}^n X_i^2/n}{\sum_{i=1}^m Y_i^2/m}
$$
where $n$ and $m$ are called the numbers of degrees of freedom in the numerator and the denominator, and the $X$s and $Y$s are independent and distributed as $\mathcal{N}(0,1)$.
"Non-normalized" means only that the divisions by $n$ and $m$ are not done.  It just re-scales the thing.
There is an immense literature on these, and they are introduced in any statistics textbook that discusses ANOVA.


text:
Q: Why is EditText.setOnFocusChangeListener firing several times? I'm using an EditText in a row in a ListView. There is no code to programatically request focus. When the ListView is populated none of the EditText views are focused. When I tap on one of them to give it focus, this is the log output:
Comments field focus changed. hasFocus=true
Comments field focus changed. hasFocus=false
Comments field focus changed. hasFocus=true

This is on a Nexus 7 running Lollipop 5.01 and the soft keyboard. All three lines relate to the exact same EditText View.
If I run the same build on a Nexus 5 also running 5.01 I see this, which is the behaviour I'd expect:
Comments field focus changed. hasFocus=true

This is the listener:
    commentsView.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            Timber.i("Comments field focus changed. hasFocus=" + hasFocus);
            }
        }
    });

You'll see from the code that aside from logging to Timber (logcat) the event is not doing anything. Why is the View gaining, then losing and then gaining focus again on the N7? I need to use this event to trigger a data save and this behaviour is causing problems.
Any ideas?


text:
Q: Android Phonegap with jQuery Mobile - back button results in scroll to top of page My mobile app behaves as expected on iOS, but under android the any overflow divs that were scrolled before a link to a new page is tapped, are scrolled back to the top upon return.  The pages do not appear to be reloaded, just scrolled to the top before transition is complete.
I seem to be experiencing the issue discussed here.  None of the proposed workarounds posted there have helped.
I'm using Phonegap 2.0.0 and jQuery Mobile 1.2.0
Anyone have a solution?

A: Android back button messes up much with the PhoneGap. What I did was simply disabled the back button in the Android.
$(function(){
    document.addEventListener("deviceready", onDeviceReady, false);
})

// PhoneGap is loaded and it is now safe to call PhoneGap methods
//
function onDeviceReady() {
    // Register the event listener
    document.addEventListener("backbutton", onBackKeyDown, false);
}

// Handle the back button
//
function onBackKeyDown() {
    console.log("Back button pressed but nothing happened");
}

It's my choice of approach. If you wanna utilize the back button then this solution is not for you.

A: Disabling the back button is not a workable solution for me, and since history.back() is employed within the jQM framework for back navigation, the same result persists anyway.  Even the use of Phonegap's navigator.history.back() alternative still yields the ill effects.  In the end I added handlers like so, which admitedly could be improved (suggestions welcome):
/* ANDROID WORKAROUND */
$('div').on('pagebeforehide', function(event, ui) {
    var scrollPos = $(this).find('.scrolldiv').scrollTop();
    $(this).jqmData('scrollPos',scrollPos );
});

$('div').on('pagebeforeshow', function(event, ui) {
    var page = $(this);
    setTimeout(function(){
        //using animate becuse I could not get scrollTo() to work (?)
        $(page).find('.scrolldiv').animate({scrollTop: $(page).jqmData('scrollPos')}, 0);
    },1); //add it to the JS process stack
});


text:
Q: The disk algebra and continuous homomorphisms The disk algebra is the set of continuous functions $f: D \to \mathbb C$ where $D$ is the closed unit disc in $\mathbb C$ and $f$ is analytic on the interior of $D$. It is endowed with the $\sup$-norm.
Let $A$ denote the disk algebra.
I read that every continuous homomorphism $\varphi : A \to \mathbb C$ is of the form $f \mapsto f(z_0)$ for some $z_0 \in D$. The problem is I tried to look up the proof but I can't remember where I read it and I also can't find an alternative source. I also can't seem to prove it. I'm even starting to doubt the truth of the statement. How to prove this?

A: Let $\varphi : A\to \mathbb{C}$ be a continuous homomorphism, and let $f \in A$ be the function $z\mapsto z$, and let $z_0 := \varphi(f)$. Then for any polynomial
$$
g(z) := \sum_{k=0}^n \alpha_k z^k \Rightarrow g = \sum_{k=0}^n \alpha_k f^k
$$
we have
$$
\varphi(g) = \sum_{k=0}^n \alpha_k z_0^k = g(z_0)
$$
Now the set of such polynomials is dense in $A$ (by Stone-Weierstrass), and hence $\varphi(g) = g(z_0)$ for all $g\in A$.


text:
Q: Curl missing in big sur macos I'd like to install this 2017 package that would allow me to update firmware of a cardo suo-1 audio set.
But IMO bigsur is too new :D and the lib is missing. I tried to install it following different tutorials but that didn't work, I guess I'm missing a point.
I'm no developper so please be simple in explanations :D
enter image description here
enter image description here
enter image description here


text:
Q: Is my flow good enough for securing REST API? I'm new in web development. I want to write a backend for my game and I want to authenticate it with Facebook. I'm not sure if my thinking is correct and secure enought. Of course https is a must.

*

*User everytime app is launched sends /init request with fb user id and token.

*Server check if this user id and token is valid by making request to fb api.

*If everything is correct server check for user in database.

*If user do not exists generate token using app secret, fb token, fb id and current date/time save it to database and send to client.
OR If user with this fb id exists send to user previously generated token stored in database.

*Client is communicating with api using this token.

If this approach is correct I have few question.
Is sending user id and token everytime user launch application secure?
I want to veryfi user token and id with fb every time he use /init request due to fb access tokens not beeing alive for more than 60 days. Is this correct approach?
Now if user have his token to access my API. Every time he make a request should I veryfi it by making calls to database? Isn't this slow/expensive?


text:
Q: Need some help using I2C on Beaglebone I'm a beginner at I2C communication and I am trying to hook up communication with an I2C device a (mpu6050) using librobotcontrol http://strawsondesign.com/docs/librobotcontrol/group___i2_c.html i2c library in C. The code Excluding stuff not I2C related I have:
#define I2C_ADDRESS 0x68
#define I2C_BUS 1

void setupMPU();
float recordAccelRegisters();

int main(){

    float ax = 0;
    while(1){
        ax = recordAccelRegisters()
    }

    float recordAccelRegisters(){
        float Xg = 0;
        float Xa = 0, Ya, Za;
        unsigned char data;

        printf("Recording Accel Data\n");

        rc_i2c_init (I2C_BUS,I2C_ADDRESS);
        rc_i2c_read_bytes(I2C_BUS, 0x3B, 6, data);
        rc_i2c_close(I2C_BUS);

        //Xa = 8 << data;
        //Xa = (float)Xa;
        //Xg = Xa/16384.0;
        return Xg;
        }

    void setupMPU(){
        printf("Initalizing Mpu\n");

        // init I2C Bus
        rc_i2c_init (I2C_BUS,I2C_ADDRESS);

        //Wake up setup
        rc_i2c_write_byte(I2C_BUS, 0x6B, 0x00);
        rc_i2c_close(I2C_BUS);

        printf("Configuring Accelerometer\n");
        printf("Initalizing Mpu\n");

        //Accel Config
        rc_i2c_init (I2C_BUS,I2C_ADDRESS);
        rc_i2c_write_byte(I2C_BUS, 0x1C, 0x00);

        printf("Done with Accel Config\n");
        rc_i2c_close(I2C_BUS);
        }
   }

I am trying to figure out if I need to close and reopen the port every time like in an Arduino using wire library or if I can just initialize it once.  I have tried many different types of code configurations. For instance only initializing the communication only once, using send words instead of send bytes, sending only 1 byte at a time ect... but I am still unable to get data from the device. I am also struggling with weather or not to use read words or read bytes. It keeps returning a -1 bytes as seen by this error message when using
read bytes:
ERROR: in rc_i2c_read_bytes, received -1 bytes from device, expected 1

and this error when using read words:
ERROR: Segmentation Fault
Fault address: (nil)
Address not mapped.
Segmentation fault

Any help on this will be much appreciated.

A: According to the documentation you linked, the function rc_i2c_read_bytes takes a pointer where it will store the bytes read:
int rc_i2c_read_bytes (int bus, uint8_t regAddr, size_t count, uint8_t *data);
Reads multiple bytes from a device register

Thus, in your recordAccelRegisters function, you should define an array to store the bytes:
float recordAccelRegisters(){
        float Xg = 0;
        float Xa = 0, Ya, Za;
        unsigned char data[6];

        printf("Recording Accel Data\n");

        rc_i2c_init (I2C_BUS,I2C_ADDRESS);
        rc_i2c_read_bytes(I2C_BUS, 0x3B, 6, data);
        rc_i2c_close(I2C_BUS);

        //Xa = 8 << data;
        //Xa = (float)Xa;
        //Xg = Xa/16384.0;
        return Xg;
}

Same applies if you use rc_i2c_read_word, it also requires a pointer (to a uint16_t):
float recordAccelRegisters(){
        float Xg = 0;
        float Xa = 0, Ya, Za;
        uint16_t data;

        printf("Recording Accel Data\n");

        rc_i2c_init (I2C_BUS,I2C_ADDRESS);
        rc_i2c_read_word(I2C_BUS, 0x3B, &data);
        rc_i2c_close(I2C_BUS);

        //Xa = 8 << data;
        //Xa = (float)Xa;
        //Xg = Xa/16384.0;
        return Xg;
}


text:
Q: How to run linux terminal command in python in new terminal I read multiple answers regarding how to run the linux shell command using subprocess module in python. In my case, i need to run linux shell commands inside my python code in such a way that these commands should get executed in new terminal.
subprocess.call(["df","-h"]

I'm running say xyz.py in base terminal, when i execute above command, it overwrites on the output of xyz.py in the same terminal. I want this command to be executed in different terminal, or i want to store output of this command in a text file.
subprocess.call(["df","-h",">","somefile.txt"])

Above command is not working.
Edit-1:
If i save the output in a text file, i also have to display it through python.
Thanks!

A: import subprocess
fp = open("somefile.txt", "w")
subprocess.run(["df", "-h"], stdout=fp)
fp.close

Use a file handle.
If you want to print the output while saving it:
import subprocess
cp = subprocess.run(["df", "-h"], stdout=subprocess.PIPE)
print(cp.stdout)
fp = open("somefile.txt", "w")
print(cp.stdout, file=fp)
fp.close()

A: have you tried the os.system?
os.system("gnome-terminal -e 'your command'")

A: file = open("somefile.txt", "w")
subprocess.run(["df","-h"], stdout = file)
os.system("gnome-terminal -e 'gedit somefile.txt' ")

Above code is working. If there are any simple/efficient way to do the same it'll be helpful.


text:
Q: Python Selenium Script not working on crontab I have a Python Selenium Script that works fine when I manually run it on my server but when I try to run it in a .sh using Crontab(via the cron.weekly folder) I keep getting the following error:
selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.
I found this very weird because in my sh, before running the program, I did
export PATH=$PATH:/path/to/geckodriver      (with the correct path)
Any ideas why this is happening?


text:
Q: Filtering on Include in EF Core I'm trying to filter on the initial query. I have nested include leafs off a model. I'm trying to filter based on a property on one of the includes. For example:
using (var context = new BloggingContext())
{
    var blogs = context.Blogs
        .Include(blog => blog.Posts)
            .ThenInclude(post => post.Author)
        .ToList();
}

How can I also say .Where(w => w.post.Author == "me")?

A: Not sure about Include() AND ThenInclude(), but it's simple to do that with a single include:
var filteredArticles =
    context.NewsArticles.Include(x => x.NewsArticleRevisions)
    .Where(article => article.NewsArticleRevisions
        .Any(revision => revision.Title.Contains(filter)));

Hope this helps!

A: Although it's (still in discussion) not doable with EF Core, I've managed to do it using Linq to Entities over EF Core DbSet. In your case instead of:
var blogs = context.Blogs
        .Include(blog => blog.Posts)
            .ThenInclude(post => post.Author)
        .ToList()

.. you'll have:
await (from blog in this.DbContext.Blogs
           from bPost in blog.Posts
           from bpAuthor in bPost.Author
           where bpAuthor = "me"
           select blog)
.ToListAsync();

A: Not doable.
There is an on-going discussion about this topic:
https://github.com/aspnet/EntityFramework/issues/1833
I'd suggest to look around for any of the 3rd party libraries listed there, ex.: https://github.com/jbogard/EntityFramework.Filters

A: Entity Framework core 5 is the first EF version to support filtered Include.
How it works
Supported operations:

*

*Where

*OrderBy(Descending)/ThenBy(Descending)

*Skip

*Take
Some usage examples (from the original feature request and the github commmit)
:

Only one filter allowed per navigation, so for cases where the same navigation needs to be included multiple times (e.g. multiple ThenInclude on the same navigation) apply the filter only once, or apply exactly the same filter for that navigation.

context.Customers
    .Include(c => c.Orders.Where(o => o.Name != "Foo")).ThenInclude(o => o.OrderDetails)
    .Include(c => c.Orders).ThenInclude(o => o.Customer)

or
context.Customers
    .Include(c => c.Orders.Where(o => o.Name != "Foo")).ThenInclude(o => o.OrderDetails)
    .Include(c => c.Orders.Where(o => o.Name != "Foo")).ThenInclude(o => o.Customer)

Another important note:

Collections included using new filter operations are considered to be loaded.

That means that if lazy loading is enabled, addressing one customer's Orders collection from the last example won't trigger a reload of the entire Orders collection.
Also, two subsequent filtered Includes in the same context will accumulate the results. For example...
context.Customers.Include(c => c.Orders.Where(o => !o.IsDeleted))

...followed by...
context.Customers.Include(c => c.Orders.Where(o => o.IsDeleted))

...will result in customers with Orders collections containing all orders.
Filtered Include and relationship fixup
If other Orders are loaded into the same context, more of them may get added to a customers.Orders collection because of relationship fixup. This is inevitable because of how EF's change tracker works.
context.Customers.Include(c => c.Orders.Where(o => !o.IsDeleted))

...followed by...
context.Orders.Where(o => o.IsDeleted).Load();

...will again result in customers with Orders collections containing all orders.
The filter expression
The filter expression should contain predicates that can be used as a stand-alone predicate for the collection. An example will make this clear. Suppose we want to include orders filtered by some property of Customer:
context.Customers.Include(c => c.Orders.Where(o => o.Classification == c.Classification))

It compiles, but it'll throw a very technical runtime exception, basically telling that o.Classification == c.Classification can't be translated because c.Classification can't be found. The query has to be rewritten using a back-reference from Order to Customer:
context.Customers.Include(c => c.Orders.Where(o => o.Classification == o.Customer.Classification))

The predicate o => o.Classification == o.Customer.Classification) is "stand alone" in the sense that it can be used to filter Orders independently:
context.Orders.Where(o => o.Classification == o.Customer.Classification) // No one would try 'c.Classification' here

This restriction may change in later EF versions than the current stable version (EF core 5.0.7).
What can (not) be filtered
Since Where is an extension method on IEnumerable it's clear that only collections can be filtered. It's not possible to filter reference navigation properties. If we want to get orders and only populate their Customer property when the customer is active, we can't use Include:
context.Orders.Include(o => o.Customer.Where( ... // obviously doesn't compile

Filtered Include vs filtering the query
Filtered Include has given rise to some confusion on how it affects filtering a query as a whole. The rule of the thumb is: it doesn't.
The statement...
context.Customers.Include(c => c.Orders.Where(o => !o.IsDeleted))

...returns all customers from the context, not only the ones with undeleted orders. The filter in the Include doesn't affect the number of items returned by the main query.
On the other hand, the statement...
context.Customers
    .Where(c => c.Orders.Any(o => !o.IsDeleted))
    .Include(c => c.Orders)

...only returns customers having at least one undeleted order, but having all of their orders in the Orders collections. The filter on the main query doesn't affect the orders per customer returned by Include.
To get customers with undeleted orders and only loading their undeleted orders, both filters are required:
context.Customers
    .Where(c => c.Orders.Any(o => !o.IsDeleted))
    .Include(c => c.Orders.Where(o => !o.IsDeleted))

Filtered Include and projections
Another area of confusion is how filtered Include and projections (select new { ... }) are related. The simple rule is: projections ignore Includes, filtered or not. A query like...
context.Customers
    .Include(c => c.Orders)
    .Select(c => new { c.Name, c.RegistrationDate })

...will generate SQL without a join to Orders. As for EF, it's the same as...
context.Customers
    .Select(c => new { c.Name, c.RegistrationDate })

It gets confusing when the Include is filtered, but Orders are also used in the projection:
context.Customers
    .Include(c => c.Orders.Where(o => !o.IsDeleted))
    .Select(c => new
    {
        c.Name,
        c.RegistrationDate,
        OrderDates = c.Orders.Select(o => o.DateSent)
    })

One might expect that OrderDates only contains dates from undeleted orders, but they contain the dates from all Orders. Again, the projection completely ignores the Include. Projection and Include are separate worlds.
How strictly they lead their own lives is amusingly demonstrated by this query:
context.Customers
    .Include(c => c.Orders.Where(o => !o.IsDeleted))
    .Select(c => new
    {
        Customer = c,
        OrderDates = c.Orders.Select(o => o.DateSent)
    })

Now pause for a moment and predict the outcome...
The not so simple rule is: projections don't always ignore Include. When there is an entity in the projection to which the Include can be applied, it is applied. That means that Customer in the projection contains its undeleted Orders, whereas OrderDates still contains all dates. Did you get it right?

A: You can also reverse the search.
{
    var blogs = context.Author
    .Include(author => author.posts)
        .ThenInclude(posts => posts.blogs)
    .Where(author => author == "me")
    .Select(author => author.posts.blogs)
    .ToList();
}

A: I used below package
Use Z.EntityFramework.Plus
IncludeFilter and IncludeFilterByPath two methods are which you can use.
var list = context.Blogs.IncludeFilter(x => x.Posts.Where(y => !y.IsSoftDeleted))
                .IncludeFilter(x => x.Posts.Where(y => !y.IsSoftDeleted)
                    .SelectMany(y => y.Comments.Where(z => !z.IsSoftDeleted)))
                .ToList();

Here is the example https://dotnetfiddle.net/SK934m
Or you can do like this
GetContext(session).entity
                .Include(c => c.innerEntity)
                .Select(c => new Entity()
                {
                    Name = c.Name,
                    Logo = c.Logo,
                    InnerEntity= c.InnerEntity.Where(s => condition).ToList()
                })

A: Interesting case and it worked!!
If you have table/model user(int id, int? passwordId, ICollection<PwdHist> passwordHistoryCollection) where collection is history of passwords. Could be many or none.
And PwdHistory(int id, int UserId, user User). This has a quasi relationship via attributes.
Needed to get user, with related current password record, while leaving historical records behind.

User user = _userTable
    .Include(u => u.Tenant)
    .Include(u => u.PwdHistory.Where(p => p.Id == p.PwdUser.PasswordId))
    .Where(u => u.UserName == userName)
    .FirstOrDefault();

Most interesting part is .Include(u => u.PwdHistory.Where(p => p.Id == p.PwdUser.PasswordId))

*

*works with user and many passwords

*works with user and no passwords

*works with no user

A: We can use by extension
public static IQueryable<TEntity> IncludeCondition<TEntity, TProperty>(this IQueryable<TEntity> query, Expression<Func<TEntity, TProperty>> predicate, bool? condition) where TEntity : class where TProperty : class
{
    return condition == true ? query.Include(predicate) : query;
}

Usage;
_context.Tables.IncludeCondition(x => x.InnerTable, true)

A: This task can be accomplished with two queries. For example:
var query = _context.Employees
            .Where(x =>
                x.Schedules.All(s =>
                    s.ScheduleDate.Month != DateTime.UtcNow.AddMonths(1).Month &&
                    s.ScheduleDate.Year != DateTime.UtcNow.AddMonths(1).Year) ||
                (x.Schedules.Any(s =>
                     s.ScheduleDate.Month == DateTime.UtcNow.AddMonths(1).Month &&
                     s.ScheduleDate.Year == DateTime.UtcNow.AddMonths(1).Year) &&
                 x.Schedules.Any(i => !i.ScheduleDates.Any())));

        var employees = await query.ToListAsync();

        await query.Include(x => x.Schedules)
            .ThenInclude(x => x.ScheduleDates)
            .SelectMany(x => x.Schedules)
            .Where(s => s.ScheduleDate.Month == DateTime.UtcNow.AddMonths(1).Month &&
                        s.ScheduleDate.Year == DateTime.UtcNow.AddMonths(1).Year).LoadAsync();


text:
Q: Why some dynamic systems can undergo sudden changes? Everybody has observed that the weather may change from beautiful sunshine to extremely bad weather (heavy rain, stormy winds, ...) within less than half hour. What is the fundamental reason for this?
And there are many other natural systems that change extremely rapidly. Even in rock climbing, for example, if you have placed the feet on a hold, they may slip off in a fraction of a second in case of improper foot placement. What are the reasons for ultra-rapid changes in time, i.e. that for a (field) quantity $X(t)$, the value
$$S_X(t) := \lim_{\epsilon \rightarrow 0} (X(t+\epsilon)-X(t))$$
does not tend to zero?

A: In the context of dynamical systems, there are at least three main mechanisms that can lead to sudden changes:

*

*chaos;

*multistability;

*bifurcation.

In the first case, chaos, your $S_X$ diverges trivially, from the definition itself $-$ in the chaotic regime nearby trajectories in phase space diverge exponentially. That's probably the explanation most closely related to the weather "instability". The prototypical scheme of two trajectories diverging exponentially in phase space is:

where $\lambda$ is the Lyapunov exponent.
Multistability means that more then one outcome is allowed by the dynamics, with the system's initial condition determining which one is eventually attained. The region in phase space whose points evolve to a given attractor is called its basin of attraction. In the double well potential, for instance, each of the two local minima is an attractor in the presence of dissipation, with their basins of attraction looking something like:

This situation can lead to sudden changes when the system finds itself close to the boundary between two basins of attraction. And when the basin of the desired outcome is relatively small, it's hard not to be close to the boundary. Not falling, in the rock climbing example, could be seen as the desired basin, and it's a rather small one, given the typical safety margins of a few millimeters or less.
In a bifurcation, the system experiences a qualitative change in behavior with the variation of a parameter. In some sense it's then not exactly the same system as before. For example, if in a $1$-D system, the point $0$ is an attractor for negative values of its parameter $r$, but a repellor for $r>0$ (where two other attractors arise), the system undergoes a bifurcation at $r=0$ and its bifurcation diagram (attractors and repellors as a function of a parameter) can look like:

Thus, in a system close to a bifurcation, a small change in the parameter can lead to a sudden global change. In the weather, or rather climate example, that could correspond to, say, an ice age being precipitated by a small change in the concentration of a gas in the atmosphere or a small change in Earth's orbit.


text:
Q: Preferred domain (www vs non-www) setting mismatched in Wordpress & Google Webmaster Tools Looking for some advice on what appears to be a fairly ambiguous topic:
In the admin panel for my site (settings >> general), I have the WordPress Address (URL) set to http://www.my-site.com
In Google's Webmaster Tools, I have both the www and non www versions of my site verified, and have specified my domain preference to be the non www version : my-site.com
I have added rewrite rules to my .htaccess file only to handle pretty permalinks:
#BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
 #END WordPress

I am also using the Yoast SEO plugin, which is placing the following canoniclazation in my site head:  As I understand it, the plugin is doing this based on the way I have my WordPress Address (URL) and permalinks structure set.
When I look at the Google Webmaster tools, the non www version of my site is showing that there is no structured data on my site, and that my links are being redirected to the www version of my site. The www version appears with all of the structured data I expect, and without redirects. I understand that it is redirecting from non www to www because of the way I have my WordPress Address (URL) set.
According to Moz Local's documentation, it will benefit my site's SEO health if I make my preferred domain name in Google Webmaster Tools and my WordPress Address (URL) match.
I know that the preferred domain name is just that: my preference. I prefer non-www version, but not if sticking to that comes at the expense of any SEO work I've already completed.
Bottom line: I need the Google Webmaster Tools domain preference and my WordPress Address(URL) to match. I understand that I have a few options for accomplishing this, but I do not know what the potential fallout for each of those options is.

*
*Is there any detriment to changing my WordPress Address (URL) to the non www version of my domain name?

*If I do this, do I need to add rewrite rules to my .htaccess file to handle the www-to-non-www change?

OR

*
*Should I simply add a rule to my .htaccess file to rewrite www to non www, without changing the WordPress Address (URL) in the admin settings for my page?

OR

*
*Is it better to change my preferred domain in Google's Webmaster tools from the non www version to the www version?

*and if I do that, will it hurt the SEO progress I've made in the last few months? (it may be important to note that all of my local directory listings and social media profiles use the non www version of my domain.)

Any insight is greatly appreciated.


text:
Q: Order by rating not works in wp_query I need to sort my products by rating in a wp_query loop:
this is my code:
switch($ordering){
    case 'default':
        $meta_key = '';
        $order = 'asc';
        $orderby = 'menu_order title';
        break;
    case 'popularity':
        $meta_key = '';
        $order = 'desc';
        $orderby = 'total_sales';
        break;
    case 'low_to_high':
        $meta_key = '_price';
        $order = 'asc';
        $orderby = 'meta_value_num';
        break;
    case 'high_to_low':
        $meta_key = '_price';
        $order = 'desc';
        $orderby = 'meta_value_num';
        break;
    case 'newness':
        $meta_key = '';
        $order = 'desc';
        $orderby = 'date';
        break;
    case 'rating':
        $meta_key = '';
        $order = 'desc';
        $orderby = 'rating';
        break;
}

$args_products_sorting = array(
    'post_type' => 'product',
    'posts_per_page' => -1,
    'orderby' => $orderby,
    'order' => $order,
    'meta_key' => $meta_key
);

Where is the error ?
If i set in url ?orderby=rating it works correctly.
Thanks.

A: Seems like there are a lot of meta keys you can order by (here is a list I've found). However I couldn't find anything rating related. I searched for rating in the WooCommerce source code and found this line: includes/abstracts/abstract-wc-product.php#L1087
So here is what finally worked for me in the context of using the WooCommerce PHP REST API client:
function getProducts(WP_REST_Request $request) {
    global $wc_api_client;

    $category = $request->get_param('category');
    // $filters = $request->get_param('filters');
    $orderby = $request->get_param('orderby');

    $args = null;

    $wc_query = new WC_Query();
    switch ( $orderby ) {
        case 'date':
            $args = array(
                'filter[limit]' => 6,
                'filter[category]' => $category,
                'filter[orderby]' => 'date',
                'filter[order]' => 'DESC'
            );
            break;
        case 'price':
            $args = array(
                'filter[limit]' => 6,
                'filter[category]' => $category,
                'filter[orderby]' => 'meta_value_num',
                'filter[order]' => 'ASC',
                'filter[orderby_meta_key]' => '_price'
            );
            break;
        case 'price-desc':
            $args = array(
                'filter[limit]' => 6,
                'filter[category]' => $category,
                'filter[orderby]' => 'meta_value_num',
                'filter[order]' => 'DESC',
                'filter[orderby_meta_key]' => '_price'
            );
            break;
        case 'popularity':
            $args = array(
                'filter[limit]' => 6,
                'filter[category]' => $category,
                'filter[orderby]' => 'meta_value_num',
                'filter[order]' => 'DESC',
                'filter[orderby_meta_key]' => 'total_sales'
            );
            break;
        case 'rating':
            $args = array(
                'filter[limit]' => 6,
                'filter[category]' => $category,
                'filter[orderby]' => 'meta_value_num',
                'filter[order]' => 'DESC',
                'filter[orderby_meta_key]' => '_wc_average_rating'
            );
            break;
        default:
            $args = array(
                'filter[limit]' => 6,
                'filter[category]' => $category
            );
    }

    try {
        $raw = $wc_api_client->products->get('', $args);
        return $raw['products'];
    } catch (Exception $e) {
        return new WP_Error('no_products', 'Couldn't find any products', array('status' => 404));
    }
}

A: You should use 'orderby'   => 'meta_value_num' and 'meta_key'  => 'rating' as specified by the WordPress Codec. Using meta_value_num with the assumption your ratings are numeric values
Reference: Orderby Parameters

A: I used something like that and it works

switch ($order_by){
                case 'price':
                    $args['orderby'] = 'meta_value_num';
                    $args['meta_key'] = '_price';
                    $args['order'] = 'asc';
                    break;

                case 'price-desc':
                    $args['orderby'] = 'meta_value_num';
                    $args['meta_key'] = '_price';
                    $args['order'] = 'desc';
                    break;

                case 'rating':
                    $args['orderby'] = 'meta_value_num';
                    $args['meta_key'] = '_wc_average_rating';
                    $args['order'] = 'desc';
                    break;

                case 'popularity':
                    $args['orderby'] = 'meta_value_num';
                    $args['meta_key'] = 'total_sales';
                    $args['order'] = 'desc';
                    break;
            }

A: Try this . Use WC_Shortcode_Products to generate the wc loop with sort parameters were used at default wc shop page
for($i=1;$i<=$num;$i++){
    $atts = array_merge(array(
        'columns' => $columns,
        'orderby' => $order_by,
        'order' => $sort_by,//rating , population , price high to low ,....
        'rows' => $rows,
        'page' => $i,
    ));
    $shortcode = new WC_Shortcode_Products($atts, 'recent_products');
    echo $shortcode->get_content();
}

A: use this codefor arg
$args = array(
            'post_type' => 'product',
            'orderby'   => $args = array(
                'filter[limit]' => 6,
                'filter[category]' => $category,
                'filter[orderby]' => 'meta_value_num',
                'filter[order]' => 'DESC',
                'filter[orderby_meta_key]' => '_wc_average_rating'
            ),
            'tax_query' => array(
                array(
                    'taxonomy'  => 'product_cat',
                    'field'     => 'id',
                    'terms'     => $category
                )
            ),
            'posts_per_page' => $product_number
        );


text:
Q: Importing data from TXT file with while loop My problem is I don´t know how to finish while loop when all rows are imported. This is Drupal 7.
If I set this while condition: while ($row = $regs->fetchAssoc()) it never get inside of the loop.
If I use this condition to break loop:
  $cadena = array();
  while (1) {
  $row = $regs->fetchAssoc();
  $cadena[] = $row;
  if (count($cadena)<0){
  break;}

I get this error: Fatal error: Allowed memory size of 1073741824 bytes exhausted (tried to allocate 64 bytes)
The full code is:
 $operations = array();
 $items = array();
 $limit = 25;
 $i = 0;

$regs =  db_query("SELECT * FROM {table_import_apunte} WHERE field_processed = :processed", array(':processed' => 0));

    while ($row = $regs->fetchAssoc()) {
            if ($i < $limit) {
                $items[] = $row;
                $i += 1;
            } else {
                $operations[] = array('csvImporter_create_nodes', array($items, 'apunte'));
                $items = array();
                $items[] = $row;
                $i = 1;
           }
        }

        $batch = array(
        ...
        );

A: Your approach with while(1) { ... } creates a infinity loop, since attaching an element to the array 'cadena' causes the count to be higher than 0 plus the count cant be lower than 0
You can try to use a foreach instead of a while
foreach ($regs as $row) { ... }


text:
Q: XSL-FO different column-gap on same page I'm flowing text across four columns per page, using XSL-FO, with a typical definition like:
<fo:simple-page-master master-name="sample" page-height="8.5in" page-width="11.0in" margin="8mm">
 <fo:region-body column-count="4" column-gap="4mm"/>
</fo:simple-page-master>

Is it possible to set the column-gap between the second and third column (for example) to be a different size than the column-gaps between the other columns?
If there is no official way of doing this, is there a way to "fake it"?

A: It's not part of the spec for column-gap (https://www.w3.org/TR/xsl11/#column-gap), and I don't know of any XSL formatter that implements it.
One way to fake it would be to use multiple fo:region-body and a flow map that directs the content to each region in turn.  See https://www.w3.org/TR/xsl11/#fafm.  For your different column gap between the second and third columns, you would need two two-column fo:region-body.  Not every XSL formatter implements flow maps, however, plus you couldn't have content with span="all" that would span across all the columns: at best, it would span across all of the columns in one of the fo:region-body.


text:
Q: Grep and SED not working in PowerShell I am trying to replace a url in more than 1000 files (using PowerShell).
That is replace thomas.corp.test.com:81/gt/se.ashx with george.corp.test.com:91/gt/se.ashx.
I am able to execute it in a linux machine using the following command.
grep -lr http:\/\/thomas\.corp\.test\.com:81\/gt\/se\.ashx . |
  xargs sed -i '' 's/http:\/\/thomas\.corp\.test\.com:81\/gt\/se\.ashx/https:\/\/george\.corp\.test\.com:91\/gt\/se\.ashx/g'

Need help in finding out an equivalent for PowerShell.

A: try Something like this :
$odl="thomas.corp.test.com:81/gt/se.ashx"
$new="george.corp.test.com:91/gt/se.ashx"

select-string -Path "c:\temp\*.*" -Pattern $odl -SimpleMatch | %{$curpath=$_.path; (get-content $curpath -Raw) -replace $odl, $new | Out-File $curpath}

A: $old="thomas.corp.test.com:81/gt/se.ashx"
$new="george.corp.test.com:91/gt/se.ashx"
get-childitem c:\somedir -recurse -include . |
select -expand fullname |
  foreach
{
            (Get-Content $) -replace $old,$new |
             Set-Content $
}


text:
Q: Which is better, constants or variables? We can assign values to constant or variables. Which one is better from a memory and optimization point of view?
define("X",5);

or
$x = 5;

Does in both case integer occupy same memory? Which one take more memory space and faster to run?
I have analyzed this task 100k times in php.exe on command prompt and explaining here...
//Defining a constant Test
$DefConst_TimeStart = microtime();
$DefConst_MemStart = memory_get_usage();
for($i=1;$i<=100000;$i++){
    define("x$i",$i);
}
$DefConst_MemEnd = memory_get_usage();
$DefConst_TimeEnd = microtime();
//Variable test
$Variable_TimeStart = microtime();
$Variable_MemStart = memory_get_usage();
for($i=1;$i<=100000;$i++){
    ${"x".$i} = $i;
}
$Variable_MemEnd = memory_get_usage();
$Variable_TimeEnd = microtime();

//Output of the results
echo "Define Constant: Time: ".($DefConst_TimeEnd - $DefConst_TimeStart)." ms | Memory: ".($DefConst_MemEnd - $DefConst_MemStart)." Bytes\n";
echo "Setting Variable: Time: ".($Variable_TimeEnd - $Variable_TimeStart)." ms | Memory: ".($Variable_MemEnd - $Variable_MemStart)." Bytes\n";

And according to analysis:
Time taken: Variable is faster in execution rather than constant
Memory usage: Constant occupy less memory than variable
Output image

You can download file from github to test it
Benchmark example to test speed and memory usage
let me know am i on right track or not?

A: The difference between assigning a single variable and defining a single constant is likely to be so tiny that it would be dwarfed by random variation in the rest of the program.
Both are high-level constructs registering an association between a name and a value in a complex type structure, subject to all sorts of optimisations and special cases in the underlying engine.
If you had hundreds of such definitions, you might begin to notice a small difference, but at that point there's something wrong with the design of your program.

A: I would prefer using the Variable simply because declaring the variable itself doesn't need to call a function while define is a function that will define a value.


text:
Q: I have some trouble pass an event to another function in my plugin When I try get the event, I got:

Uncaught TypeError: Cannot read property 'type' of undefined

I'm trying to pass the options in the Constructor Itoggle to mouseInOut and then get options inside the Itoggle.prototype.mouseInOut. The code works fine before I try pass any arguments to mouseInOut, now I can't get the event anymore. Even if I try pass event as argument too or any argument.
The Error:

Uncaught TypeError: Cannot read property 'type' of undefined makeup-itoggle.js:18
  Itoggle.mouseInOut  makeup-itoggle.js:18
  b.event.special.(anonymous function).handle
  b.event.dispatch
  v.handle

;(function ($) {

  "use strict";

  var Itoggle = function (el, options) {
    $(el).on('mouseenter mouseleave', mouseInOut(event, options);
  };

  Itoggle.prototype.mouseInOut = function (event, options) {
    var $this = $(this)
      , selector = $this.attr('data-target')
      , target = $('#' + selector);

    var opt = $.extend({}, $.fn.itoggle.defaults, options);
    console.log(opt.titleActive); // ok

    if (event.type == 'mouseover') {//here's come the error. Cannot read property 'type' of undefined
      $this.addClass(opt.elementActive);
      $this.find('.nav-button-title').addClass(opt.titleActive);
      target.show();
    }
    else if (event.type == 'mouseout') {
      $this.removeClass(opt.elementActive);
      $this.find('.nav-button-title').removeClass(opt.titleActive);
      target.hide();

      target.mouseenter( function () {
        $this.addClass(opt.elementActive);
        $this.find('.nav-button-title').addClass(opt.titleActive);
        target.show();
      });

      target.mouseleave( function () {
        $this.removeClass(opt.elementActive);
        $this.find('.nav-button-title').removeClass(opt.titleActive);
        target.hide();
      });

   }
   else { console.log('invalid event'); }

 };

 /* ITOGGLE PLUGIN DEFINITION
  * ========================= */

  $.fn.itoggle = function () {
    return this.each( function () {
      var $this = $(this)
        , data = $this.data('itoggle')
        , options = typeof option == 'object' && option;
      if (!data) { $this.data('itoggle', (data = new Itoggle(this, options)));}
    });
  };

  $.fn.itoggle.defaults = {
    elementActive: 'nav-outer-button-active',
    titleActive: 'nav-button-title-active'
  };

  $.fn.itoggle.Constructor = Itoggle;

})(window.jQuery);

A: You pass a function result instead of function:
// wrong, function executes immediately,
// event is undefined atm, so it throws an error
$(el).on('mouseenter mouseleave', mouseInOut(event, options));

// correct way?
$(el).on('mouseenter mouseleave', mouseInOut);

Though I'm surprised that works. Normally, you have to pass a function like this:
$(el).on('mouseenter mouseleave', this.mouseInOut);

But apparently, if it works your way - then I'm wrong.
And remember that context of execution will be HTMLElement, which triggered the event, not an instance of Itoggle.


text:
Q: JWT in http only cookie is getting undefined I am setting access_token in login route but I am getting undefined.
Lines commented below in the code gives undefined why so? How to access the cookie when it is set ? There is another GET route /transactions which gets called on home page after login is success in that route as well I am getting undefined why so? I have also used cookie-parser in server.js file but still not working
transaction GET route https://pastebin.com/DP0NZL5W
const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');

const User = require('../models/userSchema');

router.post('/login', (req, res) => {

    const {email, password} = req.body;

    console.log("Server Login email: ", email);
    console.log("Server Login password: ", password);

    User.find({email: email})
        .exec()
        .then(user => {

            console.log("User login user: ", user);

            if(user.length < 1){
                console.log("user length less")
                return res.status(401).json({
                    message: 'Auth failed'
                });
            }

            bcrypt.compare(password, user[0].password, (err, result) => {
                if(err){
                    return res.status(401).json({
                        message: 'Auth failed'
                    });
                }
                if(result){
                    const token = jwt.sign({
                        email: user[0].email,
                        userId: user[0]._id
                    }, 'secret', {
                        expiresIn: "1h"
                    })

                    console.log("Cookie token: ", token);

                    res.cookie('access_token', token, { maxAge: 9000000, httpOnly: true });

                    // console.log("req.cookies: ", req.cookies)

                    // console.log("req.cookies['access_token']: ", req.cookies['access_token'])

                    return res.status(200).json({
                        message: 'Auth successful',
                        token: token
                    })
                }
                return res.status(401).json({
                    message: 'Auth failed'
                });
            })

        })
        .catch(err => {
            console.log(err);
            res.status(500).json({
                error: err
            })
        })

});

A: app.use({
 credentials: true, // enable cookie receiving
 origin: "url of client side" // how can use your api
})


text:
Q: jquery update page status to server if it is active or not Hi i am building a Phonegap app in which user can chat with each other and i am also sending push notification to  receiver user if he is not active in chat window. i am using Php and sending messages via ajax. i can't figured it out that how can i find if receiver is active or not. what i tried is make in new table where when user enter in chat window i update active but it fails when he closes suddenly app or navigate to some other page then it still remain active.
if (page.name == 'chat-window') {

   $.get('http://web.com/d/c_staus.php', {id:userid}, function (data) {

   console.log(data);

     });

 }

A: when user navigates it to some other page, you need to check the condition everytime the page is loaded like below given example:
$(document).ready(function() {

    if (page.name == 'chat-window') {
        $.get('http://web.com/d/c_staus.php', {id:userid}, function (data) {
           console.log(data);
        });
    } else {
        console.log('not active');
    }
});


text:
Q: How to get the click through URL of native custom template ad I am implementing native custom template ad in my android app and below is the code I am using for fetching and rendering custom template ad in my view. I want to open the a webview when user clicks on the ad with the click through URL that I set in my dfp portal but I don't see any method or documentation on how to get hold of that URL. Please help me with this
private void fetchAd(final View convertView, final int position) {

       templateAdLoadedListener = new NativeCustomTemplateAd.OnCustomTemplateAdLoadedListener() {
                    @Override
                    public void onCustomTemplateAdLoaded(NativeCustomTemplateAd nativeCustomTemplateAd) {
                        populateAd(nativeCustomTemplateAd, convertView);
                        nativeCustomTemplateAd.recordImpression();
                    }
                };

                templateAdClickListener = new NativeCustomTemplateAd.OnCustomClickListener() {
                    @Override
                    public void onCustomClick(NativeCustomTemplateAd nativeCustomTemplateAd, String s) {
                        Intent intent = new Intent(context, AboutWebActivity.class);
                        intent.putExtra("TYPE", "AD");
                        intent.putExtra("TITLE", nativeCustomTemplateAd.getText("Advertiser"));
                        Log.d(TAG, "onCustomClick: s = " + s);
                        intent.putExtra("URL","url will go here");
                        context.startActivity(intent);
                    }
                };
                adLoader = new AdLoader.Builder(context, ad_unit_id)
                        .forCustomTemplateAd(ad_template_id, templateAdLoadedListener, templateAdClickListener)
                        .withAdListener(new AdListener() {
                            @Override
                            public void onAdFailedToLoad(int errorCode) {
                                Log.d(TAG, "onCustomTemplateAdFailedToLoad: error code");
                            }
                        }).build();

                adLoader.loadAd(new PublisherAdRequest.Builder().build());
            }
        };
}

A: I solved this by sending the click-through-URL as a text from DFP server as an ad asset.
You can get reference to that URL using the method
CharSequence calltoactionURL = nativeCustomTemplateAd.getText(AdConstants.DFP_CALL_TO_ACTION_URL);
Now you can use this value to perform any operation.


text:
Q: how to print after the keyword from python? i have following string in python
b'{"personId":"65a83de6-b512-4410-81d2-ada57f18112a","persistedFaceIds":["792b31df-403f-4378-911b-8c06c06be8fa"],"name":"waqas"}'

I want to print the all alphabet next to keyword "name" such that my output should be
waqas

Note the waqas can be changed to any number so i want print any name next to keyword name using string operation or regex?

A: First you need to decode the string since it is binary b. Then use literal eval to make the dictionary, then you can access by key
>>> s = b'{"personId":"65a83de6-b512-4410-81d2-ada57f18112a","persistedFaceIds":["792b31df-403f-4378-911b-8c06c06be8fa"],"name":"waqas"}'
>>> import ast
>>> ast.literal_eval(s.decode())['name']
'waqas'

A: It is likely you should be reading your data into your program in a different manner than you are doing now.
If I assume your data is inside a JSON file, try something like the following, using the built-in json module:
import json

with open(filename) as fp:
    data = json.load(fp)
print(data['name'])

A: You can convert the string into a dictionary with json.loads()
import json
mystring = b'{"personId":"65a83de6-b512-4410-81d2-ada57f18112a","persistedFaceIds":["792b31df-403f-4378-911b-8c06c06be8fa"],"name":"waqas"}'
mydict = json.loads(mystring)
print(mydict["name"])
# output 'waqas'

A: if you want a more algorithmic way to extract the value of name:
s = b'{"personId":"65a83de6-b512-4410-81d2-ada57f18112a",\
"persistedFaceIds":["792b31df-403f-4378-911b-8c06c06be8fa"],\
"name":"waqas"}'

s = s.decode("utf-8")

key = '"name":"'
start = s.find(key) + len(key)
stop = s.find('"', start + 1)

extracted_string = s[start : stop]
print(extracted_string)

output
waqas

A: First you need to convert the string into a proper JSON Format by removing b from the string using substring in python suppose you have a variable x :
import json
x = x[1:];
dict = json.loads(x) //convert JSON string into dictionary
print(dict["name"])


text:
Q: create multidimentional array from singledimentional array Ok, so i have this string array that looks something like this:
myArray[0] = "a0,b0,c0,d0"
myArray[1] = "a1,b1,c1,d1"
myArray[2] = "a2,b2,c2,d2"
myArray[3] = "a3,b3,c3,d3"
etc...

I want to create a multidimentional array that uses the first part of each element as "key". In short:
myMultiArray:
x/y|  0   |  1   |  2   |  3   |
------------------------
 0 | "a0" | "a1" | "a2" | "a3" |
 1 | "b0" | "b1" | "b2" | "b3" |
 2 | "c0" | "c1" | "c2" | "c3" |
 3 | "d0" | "d1" | "d2" | "d3" |

this is what I've got:
 private String[,] resultsParser(String[] inputArray)
    {
        String[] splittedString = null;
        String[,] outputString = null;
        for (int i = 0; i < inputArray.Length; i++ )
        {
            splitString = inputArray[i].Split(',');
            for (int j = 0; j < outputArray.GetLength(0); j++)
            {
                if (splitString[0] == outputArray[j, 0])
                {
                    for (int k = 1; k < splitString.Length; k++)
                    {
                        outputArray[j, k] = splitString[k];
                    }
                }
            }
            for (int k = 0; k < splitString.Length; k++)
            {
                outputArray[outputArray.GetLength(0), k] = splitString[k];
            }
        }
        return outputArray;
    }

*

*Problem1: it doesn't work

*Problem2: the code is fugly

Is there some easy way of doing this?

A: It seems to me you need to separate this into two stages:

*

*Determining the size

*Splitting each row and copying the results

Each of these is reasonably simple, but you'll find the code much simpler if you separate them. Something like:
public static string[,] SplitResults(string[] input)
{
    int columns = input[0].Split(',').Length;
    string[,] output = new string[input.Length, columns];

    for (int row = 0; row < input.Length; row++)
    {
        string[] split = input[row].Split(',');
        for (int column = 0; column < columns; column++)
        {
            output[row, column] = split[column];
        }
    }
    return output;
}

However, you should add validation:

*

*input should not be null

*input should not be empty

*Every row should be the same size

Note that the code above splits the first row twice (once to find the size, and once to populate the data). While you could fix that to be more efficient, it would make the code more ugly - I wouldn't do it unless you really found it to be a bottleneck.

A: Do you have to create a multidimensional array, string[,]? Because it's pretty easy to create a jagged array, string[][]:
string[][] newArray = new string[inputArray.Count][];
for (int i = 0; i < inputArray.Count; ++i)
{
    newArray[i] = inputArray[i].Split(',');
}

A: private String[,] resultsParser(params String[] input){
    String[,] array = new String[input.Length, input[0].length];//x is the total elements, y is the elements in each array
    for ( int i = 0 ; i < input.Length ; i++ ){
        array[i] = input[i];
    }
    return array;
}

this is not tested but I believe it should work


text:
Q: appending many variables to MySQL with python insert_basic = '""' + '"INSERT INTO info VALUES (' + "'" + testid + "','" + username + "','" + fullname + "','" + firstnumber + "','" + secondnumber + "','" + floatnumber + "','" + posts + "','" + country + '","' + bio + '","' + link + '");'
cur.execute(insert_basic)
try:
    db.commit()
except:
    db.rollback()
cur.execute("""SELECT * FROM basic;""")
print cur.fetchall()

Hello, I have done a lot of research and I cannot seem to get the syntax right for submitting to SQL. Some of the variables are integers and some are strings with one being a float.

A: This is what parameterized queries are for:
parameters = (testid, username, fullname, firstnumber, secondnumber, floatnumber, posts, country, bio, link)
query = """
    INSERT INTO
        info
    VALUES
        (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"""
cur.execute(query, parameters)

When you do it this way, you are letting your MySQL database driver to handle the type conversions between Python and MySQL automatically.
And, you are also protecting yourself from SQL injection attacks that would be easy to apply to your initial code where you string concatenate your query.

I would also specify the table column names in this case explicitly:
INSERT INTO
    info
    (column_name1, column_name2, ...)
VALUES
    (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)


text:
Q: Scraping data using cheerio and promise on node I would like to be able to

*

*be able to get the data I am asking for

*be able to post it as a JSON file so I could loop through it and post it to a site.

I'm not currently getting any error messages.
I've tried using cheerio, promises, puppeteer and jsdom. I'm finding that every single time I can't get any data. I found most of how to build this template from https://www.donnywals.com/build-a-simple-web-scraper-with-node-js/

// client-side js, loaded by index.html
// run by the browser each time the page is loaded

console.log("hello world :o");

// define variables that reference elements on our page

var request = require("request");
var cheerio = require("cheerio");
var Promise = require("promise");
var fs = require("fs");

request(
  "https://www.google.com/",
  function(error, result, html) {
    if (error) {
      console.log("An error occurred");
      console.log(error);
      return;
    }

    var $ = cheerio.load(html);

    var promises = [];

    $(".video-detailed-info .video-info-row").each(function(i, dataTable) {
      var race = $(dataTable)
        .find(".div")
        .text();
      var $userinfo = $(dataTable).find(
        ".usernameWrap .subscribers-count .pstar-list-btn .categoriesWrapper .productionWrapper .tagsWrapper .white"
      );

      promises.append(scrapeUnits($userinfo));
    });

    Promise.all(promises).then(function(promiseResults) {
      var data = {};

      // use the promiseResults to populate and build your data object...

      // write the JSON file to disk
      fs.writeFile("public/units.json", JSON.stringify(data), function(err) {
        if (err) {
          console.log(err);
        }
      });
    });
  }
);

function scrapeUnits(unitUrls) {
  return new Promise(function(fulfil, reject) {
    var units = [];
    units = $(".video-detailed-info..video-info-row.usernameWrap");
    unitUrls = document.querySelector("score");

    // some code that loads a new page with request

    // some code that uses querySelectors and cheerio to extract data
    // some code that creates a unit object and eventually adds units to the array

    // eventually we're done with grabbing data for our units and we do this:
    fulfil(units);
  });
}

// fetch the initial list of dreams

// a helper function that creates a list item for a given dream


text:
Q: CSS/JS positioning a button in dynamic ul So, I have a dropdown menu with ul and li structure as below:

    Fixed Button

Then in JS, I simply append dynamic li to the content_container:
$('span.content_container').html(li_content);

Giving...

Something

    Fixed Button

I am trying to position a fixed area with a button as below image:

The ul has max height of 800px. When there are lots of li, then it is fairly simple to position the fixed_area button as below:
span.fixed_area {
   height: 48px;
   width: 100%;
   position: fixed;
   background-color: red;
   top: 750px;
}

I can simply position the fixed button to the bottom of the max height container.
The problem:
The problem is that since I am getting the li dynamically, there are times when not enough li is loaded, yet the fixed button is still positioned at top:750px, thus often not visible or misplaced.
What I am trying to do:
I can re-structure the html portion. I need to position the fixed button always at the bottom of the visible container regardless how long the lists are as shown in image, both A and B.
Hope this makes sense.
Any help will be much appreciated!

A: You could constraint only the .content_container and let the button right below it.

Something

    Fixed Button

The css:
.content_container {
  overflow-x: scroll;
  max-height: 750px; // reduced because it doesn't count the button.
}

You don't need any position:
.fixed_area {
   display: inline-block; // if you want to set the height;
   height: 48px;
   width: 100%;
   background-color: red;
}

A: Add a list name in the  input box and press button to append it to the menu. That fixed button is still at the bottom while the options are being added at the top.

document.getElementById('press').addEventListener('click', press);
ul_container = document.getElementsByClassName('container')[0];
dummy = document.getElementById('dummy');
var inp = document.getElementById('in');

function press() {
  div = document.createElement('div');
  div.innerHTML = inp.value;
  console.log(ul_container, dummy, div)
  ul_container.insertBefore(div, dummy);

}
.container {
  display: none;
  position: absolute;
  top: 15px;
  max-height: 200px;
  overflow: auto;
  padding: 0px;
  width: 200px;
}
.container:hover {
  display: auto;
}
#menu {
  border: solid black;
  background: red;
  display: inline-block;
}
#fixed_btn,
#dummy {
  list-style-type: none
}
#fixed_btn:hover {
  cursor: pointer;
  background: green;
}
#menu:hover>ul {
  display: block;
}
li {
  padding: 0px;
  margin: none;
}
.container li:hover {
  cursor: pointer;
  background: blue;
}
<button id='press'>
  press
</button>
<input type="text" id="in">

  Menu Name

BUTTON


text:
Q: Server to Server communication with IBM SBT I would  like to use the IBM SBT for server to server communication instead of displaying data from , for instance, connections at the user. In this particular usecase I would like to have data updated in Connections whenever a user saves or edits data.
Because we are not using oAuth we would like to use Basic authentication without prompting the user for authentication. Are there any examples how to do is?

A: yes there are some examples of using Pure Java, no J2EE.
http://bastide.org/2014/01/28/how-to-develop-a-simple-java-integration-with-the-ibm-social-business-toolkit-sdk/
and
https://github.com/OpenNTF/SocialSDK/blob/master/samples/java/sbt.sample.app/src/com/ibm/sbt/sample/app/BlogServiceApp.java
Essentially, you'll need the dependent jar files.
once, you have the jar files you need to configure your class so you can get an Endpoint
once you have the endpoint you can use the endpoint in one of the top level services such
as ForumsService
then you can use the ForumsService to call back to Connections


text:
Q: Error compiling modular code in VSC using gcc I've a problem compiling the following programm:
// hauptteil.c (main part)
#include "nebenfkt.h"
#include <stdio.h>
#include <stdlib.h>

int main (void)
{
    int x =10;
    int ergebnis=0;
    ergebnis =ver(x);
    printf("Doubled number: %d", ergebnis);
    return 0;
}

//nebenfkt.h
int ver(int x);

#include "nebenfkt.h"
#include <stdio.h>
#include <stdlib.h>

int ver(int x)
{
    int rueck;
    rueck= x*2;
    return rueck;
}

VSC gives me the feedback "* undefined reference to `ver'
collect2.exe: error: ld returned 1 exit status*"
Solution
The problem occurred because I only used the command "gcc hauptteil.c -o function"
Instead of "gcc hauptteil.c nebenfkt.c -o function"

A: My mistake was discovered by Eugene Sh.
My mistake was that I only used the command "gcc hauptteil.c -o function" Instead of "gcc hauptteil.c nebenfkt.c -o function".


text:
Q: Contact form 7 attachments not sending I am having intermittent problems with contact form 7 - it sometimes sends and sometimes does not. The attachments seem to be the problem.
The form is routed via gmail SMTP.
I can submit one minute get an error and then send again 30 seconds later with success.
The error I am getting is the general - "Sender's message was failed to send"
Any help would be appreciated.

A: I dont think it comes from the plugin contact form 7, I can't put my finger on it but it surely comes from the communication between your SMTP server and your Form.
because Contact Form 7 is only a plugin, not the server, it can be blocked from time to time by the server, so they inform you by that message.
I can't help you much but it's surely the server.