text:
Q: Calling virtual function from static function CASE
My base class "Control" subclasses WinAPI button control:
hWndControl = CreateWindowEx
(
      0
    , L"BUTTON"
    , L"Button"
    , WS_VISIBLE | WS_CHILD | BS_OWNERDRAW | WS_EX_TRANSPARENT
    , wndRc.left
    , wndRc.top
    , wndRc.right
    , wndRc.bottom
    , hWndParent
    , 0
    , hInstance
    , 0
);

void* p_this{reinterpret_cast<void*>(this)}; // avoiding C-style cast
SetWindowSubclass
(
      hWndControl
    , Control::ControlProc
    , 0
    , reinterpret_cast<DWORD_PTR>(p_this)
)

As far as I know this requires me to define the callback as static (which I do).
Here is the callback sample for reference:
LRESULT CALLBACK Control::ControlProc
(
      HWND hWnd
    , UINT msg
    , WPARAM wParam
    , LPARAM lParam
    , UINT_PTR uIdSubclass
    , DWORD_PTR dwRefData
)
{
    //  RETRIEVE POINTER TO THIS CLASS OBJECT
    void* p_thisV{reinterpret_cast<void*>(dwRefData)}; // avoiding C-style cast
    Control* const p_this{reinterpret_cast<Control*>(p_thisV)};

    // PROCESS MESSAGES
    switch (msg)
    {
        //  DRAWING
        case MY_DRAWITEM: // custom message forwarding WM_DRAWITEM from main window
        {
            p_this->DrawControl();
        }
        break;

        ...
    }
    return DefSubclassProc(hWnd, msg, wParam, lParam);
}

As far as here everything works fine if I do the drawing in the callback function, or in member function defined in the base class referenced in callback.
But I plan to inherit this base class for multiple different controls with different looks while using the same callback. So I thought I would create virtual functions called in specific points of the callback, which I can override in derived class with custom behavior for each derived class like so:
//  Base class header
class Control
{
    ...
    protected:
    virtual void DrawControl();
    ...
};

//  Derived class header
class CalendarItem : public Control
{
    ...
    protected:
    void DrawControl();
    ...
};

//  Derived class cpp
void CalendarItem::DrawControl()
{
    std::unique_ptr<DrawBg> drawBg = std::unique_ptr<DrawBg>(new DrawBg(Control::hWndControl));
    //  this is the actual drawing mechanism, works, not relevant
}

PROBLEM
I get exception in the callback function on line: p_this->DrawControl();
Exception text: p_this->**** was 0x75004D.
Can you please tell me how to fix this solution to work, or whether something like this is even possible?

A: ControlProc() expects to receive a Control* pointer, not a CalendarItem* pointer, or any other derived class pointer. So, when casting this, you need to convert it to a valid Control* pointer first, then cast that as-is to DWORD_PTR for SetWindowSubclass(), and then in ControlProc() you can cast the DWORD_PTR back to Control* directly. You don't need to, and should not, cast to an intermediate void* at all.
Control* p_this = this; // implicit conversion, no explicit cast needed
SetWindowSubclass
(
    hWndControl,
    Control::ControlProc,
    0,
    reinterpret_cast<DWORD_PTR>(p_this)
);

LRESULT CALLBACK Control::ControlProc
(
    HWND hWnd,
    UINT msg,
    WPARAM wParam,
    LPARAM lParam,
    UINT_PTR uIdSubclass,
    DWORD_PTR dwRefData
)
{
    // RETRIEVE POINTER TO THIS CLASS OBJECT
    Control* const p_this = reinterpret_cast<Control*>(dwRefData);
    ...
    return DefSubclassProc(hWnd, msg, wParam, lParam);
}

A: The correct solution was hinted at by RbMm - this pointer is on stack, we need heap pointer so that it stays in memory when the callback function runs (so current running function is already finished).
The correct solution:
Creating derived class object:
// provide base class pointer stored on heap
Derived* der = new Derived;
der->CreateInDerived(&(*der), ...); // "&(*der)" gets base class ptr from derived ptr

Derived class function:
void Derived::CreateInDerived(Base* ptr, ...)
{
    ptr->CreateInBase(ptr, ...);
}

Base class function:
void Base::CreateInBase(Base* ptr, ...)
{
    ...
    SetWindowSubclass
    (
          hWndControl
        , Control::ControlProc
        , 0
        , reinterpret_cast<DWORD_PTR>(ptr)
    )
    ...
}

Explanation:
The problem was not at all in the clash of virtual and static function, but in life length of transferred pointer. The pointer address was turned into a number in the function A, so that it can be given to callback function B through DWORD parameter.
When function B attempted to retrieve the pointer address back from the number, pointer defined in function A was alrady out of scope (and probably overwritten, since function A finished and released the memory).


text:
Q: Algorithm for grouping anagram words Given a set of words, we need to find the anagram words and display each category alone using the best algorithm.
input:
man car kile arc none like

output:
man
car arc
kile like
none

The best solution I am developing now is based on an hashtable, but I am thinking about equation to convert anagram word into integer value.
Example: man => 'm'+'a'+'n' but this will not give unique values.
Any suggestion?

See following code in C#:
string line = Console.ReadLine();
string []words=line.Split(' ');
int[] numbers = GetUniqueInts(words);
for (int i = 0; i < words.Length; i++)
{
    if (table.ContainsKey(numbers[i]))
    {
        table[numbers[i]] = table[numbers[i]].Append(words[i]);
    }
    else
    {
        table.Add(numbers[i],new StringBuilder(words[i]));
    }

}

The problem is how to develop GetUniqueInts(string []) method.

A: A Python version for giggles:
from collections import defaultdict
res = defaultdict(list)
L = "car, acr, bat, tab, get, cat".split(", ")

for w in L:
    res["".join(sorted(w))].append(w)

print(res.values())

A: Don't bother with a custom hash function at all. Use the normal string hash function on whatever your platform is. The important thing is to make the key for your hash table the idea of a "sorted word" - where the word is sorted by letter, so "car" => "acr". All anagrams will have the same "sorted word".
Just have a hash from "sorted word" to "list of words for that sorted word". In LINQ this is incredibly easy:
using System;
using System.Collections.Generic;
using System.Linq;

class FindAnagrams
{
    static void Main(string[] args)
    {
        var lookup = args.ToLookup(word => SortLetters(word));

        foreach (var entry in lookup)
        {
            foreach (var word in entry)
            {
                Console.Write(word);
                Console.Write(" ");
            }
            Console.WriteLine();
        }
    }

    static string SortLetters(string original)
    {
        char[] letters = original.ToCharArray();
        Array.Sort(letters);
        return new string(letters);
    }
}

Sample use:
c:\Users\Jon\Test>FindAnagrams.exe man car kile arc none like
man
car arc
kile like
none

A: I don't think you'll find anything better than a hash table with a custom hash function (that would sort the letters of he word before hashing it).
Sum of the letters will never work, because you can't really make 'ac' and 'bb' different.

A: You will need large integers (or a bit vector actually) but the following might work
the first occurrence of each letter get's assigned the bit number for that letter, the second occurence gets the bit number for that letter + 26.
For example
a #1 = 1
b #1 = 2
c #1 = 4
a #2 = 2^26
b #2 = 2 ^ 27
You can then sum these together, to get a unique value for the word based on it's letters.
Your storage requirements for the word values will be:
n * 26 bits
where n is the maximum number of occurrences of any repeated letter.

A: I wouldn't use hashing since it adds additional complexity for look-up and adds. Hashing, sorting and multiplications are all going to be slower than a simple array-based histogram solution with tracking uniques. Worst case is O(2n):
// structured for clarity
static bool isAnagram(String s1, String s2)
{
    int[] histogram = new int[256];

    int uniques = 0;

    // scan first string
    foreach (int c in s1)
    {
        // count occurrence
        int count = ++histogram[c];

        // count uniques
        if (count == 1)
        {
            ++uniques;
        }
    }

    // scan second string
    foreach (int c in s2)
    {
        // reverse count occurrence
        int count = --histogram[c];

        // reverse count uniques
        if (count == 0)
        {
            --uniques;
        }
        else if (count < 0) // trivial reject of longer strings or more occurrences
        {
            return false;
        }
    }

    // final histogram unique count should be 0
    return (uniques == 0);
}

A: I used a Godel-inspired scheme:
Assign the primes P_1 to P_26 to the letters (in any order, but to obtain smallish hash values best to give common letters small primes).
Built a histogram of the letters in the word.
Then the hash value is the product of each letter's associated prime raised to the power of its frequency.  This gives a unique value to every anagram.
Python code:
primes = [2, 41, 37, 47, 3, 67, 71, 23, 5, 101, 61, 17, 19, 13, 31, 43, 97, 29, 11, 7, 73, 83, 79, 89, 59, 53]

def get_frequency_map(word):
    map = {}

    for letter in word:
        map[letter] = map.get(letter, 0) + 1

    return map

def hash(word):
    map = get_frequency_map(word)
    product = 1
    for letter in map.iterkeys():
        product = product * primes[ord(letter)-97] ** map.get(letter, 0)
    return product

This cleverly transforms the tricky problem of finding subanagrams into the (also known to be tricky) problem of factoring large numbers...

A: I have implemented this before with a simple array of letter counts, e.g.:
unsigned char letter_frequency[26];

Then store that in a database table together with each word. Words that have the same letter frequency 'signature' are anagrams, and a simple SQL query then returns all anagrams of a word directly.
With some experimentation with a very large dictionary, I found no word that exceeded a frequency count of 9 for any letter, so the 'signature' can be represented as a string of numbers 0..9 (The size could be easily halved by packing into bytes as hex, and further reduced by binary encoding the number, but I didn't bother with any of this so far).
Here is a ruby function to compute the signature of a given word and store it into a Hash, while discarding duplicates. From the Hash I later build a SQL table:
def processword(word, downcase)
  word.chomp!
  word.squeeze!(" ")
  word.chomp!(" ")
  if (downcase)
    word.downcase!
  end
  if ($dict[word]==nil)
    stdword=word.downcase
    signature=$letters.collect {|letter| stdword.count(letter)}
    signature.each do |cnt|
      if (cnt>9)
        puts "Signature overflow:#{word}|#{signature}|#{cnt}"
      end
    end
    $dict[word]=[$wordid,signature]
    $wordid=$wordid+1
  end
end

A: Assign a unique prime number to the letters a-z
Iterate your word array, creating a product of primes based on the letters in each word.
Store that product in your word list, with the corresponding word.
Sort the array, ascending by the product.
Iterate the array, doing a control break at every product change.

A: In C, I just implemented the following hash which basically does a 26-bit bitmask on whether the word in the dictionary has a particular letter in it.  So, all anagrams have the same hash.  The hash doesn't take into account repeated letters, so there will be some additional overloading, but it still manages to be faster than my perl implementation.
#define BUCKETS 49999

struct bucket {
    char *word;
    struct bucket *next;
};

static struct bucket hash_table[BUCKETS];

static unsigned int hash_word(char *word)
{
    char *p = word;
    unsigned int hash = 0;

    while (*p) {
        if (*p < 97 || *p > 122) {
            return 0;
        }
        hash |= 2 << (*p - 97);
        *p++;
    }

    return hash % BUCKETS;
}

Overloaded buckets created and added as linked list, etc.  Then just write a function that makes sure that the words that match the hash value are the same length and that the letters in each are 1 to 1 and return that as a match.

A: I will generate the hasmap based on the sample word and the rest of the alphabets I won't care.
For example if the word is "car"
my hash table will be like this:
a,0
b,MAX
c,1
d,MAX
e,MAX
...
..
r,2
.
As a result any has greater than 3 will consider as not matching
(more tuning...)
And my comparison method will compare the hash total within the hash calculation itself. It won't continue once it can identify the word is not equal.
public static HashMap<String, Integer> getHashMap(String word) {
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        String[] chars = word.split("");
        int index = 0;
        for (String c : chars) {
            map.put(c, index);
            index++;
        }
        return map;
    }

    public static int alphaHash(String word, int base,
            HashMap<String, Integer> map) {
        String[] chars = word.split("");
        int result = 0;
        for (String c : chars) {
            if (c.length() <= 0 || c.equals(null)) {
                continue;
            }
            int index = 0;
            if (map.containsKey(c)) {
                index = map.get(c);
            } else {
                index = Integer.MAX_VALUE;
            }
            result += index;
            if (result > base) {
                return result;
            }
        }
        return result;
    }

Main method
  HashMap<String, Integer> map = getHashMap(sample);
        int sampleHash = alphaHash(sample, Integer.MAX_VALUE, map);
        for (String s : args) {
                if (sampleHash == alphaHash(s, sampleHash, map)) {
                    System.out.print(s + " ");
                }
            }

A: Anagrams can be found in following way:

*

*Length of word should match.

*Perform addition of each character in terms of integer value. This sum will match if you perform same on anagram.

*Perform multiplication of each character in terms of integer value. Evaluated value will match if you perform same on anagram.

So I thought through above three validations, we can find anagrams. Correct me if I'm wrong.

Example: abc cba
Length of both words is 3.
Sum of individual characters for both words is 294.
Prod of individual characters for both words is 941094.

A: Just want to add simple python solution in addition to the other useful answers:
def check_permutation_group(word_list):
    result = {}

    for word in word_list:
        hash_arr_for_word = [0] * 128  # assuming standard ascii

        for char in word:
            char_int = ord(char)
            hash_arr_for_word[char_int] += 1

        hash_for_word = ''.join(str(item) for item in hash_arr_for_word)

        if not result.get(hash_for_word, None):
            result[str(hash_for_word)] = [word]
        else:
            result[str(hash_for_word)] += [word]

return list(result.values())

A: python code:
line = "man car kile arc none like"
hmap = {}
for w in line.split():
  ws = ''.join(sorted(w))
  try:
    hmap[ws].append(w)
  except KeyError:
    hmap[ws] = [w]

for i in hmap:
   print hmap[i]

output:
['car', 'arc']
['kile', 'like']
['none']
['man']

A: JavaScript version.  using hashing.
Time Complexity: 0(nm) , where n is number of words, m is length of word
var words = 'cat act mac tac ten cam net'.split(' '),
    hashMap = {};

words.forEach(function(w){
    w = w.split('').sort().join('');
    hashMap[w] = (hashMap[w]|0) + 1;
});

function print(obj,key){
    console.log(key, obj[key]);
}

Object.keys(hashMap).forEach(print.bind(null,hashMap))

redpajama_set_name: RedPajamaStackExchange


text:
Q: SwiftUI navigation link does not load When clicking on the navigation link in my SwiftUI application, the screen freezes and I can see the memory doubing every second - almost getting to a 1GB of memory before I terminate the application.
I have a simple navigation link as follows:
NavigationLink {
    FeedbackView(viewModel: .init())
} label: {
    HStack {
        Label("Feedback", systemImage: "bubble.left.circle")
            .fontWeight(.semibold)
        Spacer()
        Image(systemName: "chevron.right")
    }
}

Upon clicking on this navigtion link, the screen does not go to the next view and instead freezes. I am unable to tap anything else in the iOS simulator. The memory skyrockets and continues to do so until I stop the application.
The view model is it initializing in the FeedbackView call is as follows.
import Foundation
import Dependencies

class FeedbackViewModel: ObservableObject {

}

The view is below.
import SwiftUI

struct FeedbackView: View {
    @ObservedObject var viewModel: FeedbackViewModel

    var body: some View {
        Text("loaded feedback")
    }
}

If I remove .init() from the FeedbackView call within the NavigationLink, and instead initialize the FeedbackViewModel in the FeedbackView itself, I also get the same issue. I am rather new to iOS development and am not sure of which xCode tools to use that could help me diagnose this bug.

A: First: use @StateObject instead:
struct FeedbackView: View {
    @StateObject var viewModel: FeedbackViewModel

    var body: some View {
        Text("loaded feedback")
    }
}

Why: unlike @ObservedObject, @StateObject won't get destroyed and re-instantiated every time the view struct redraws. Never create @ObservedObject from within the view itself (Check this article for more details)
Second: how to initialize the @StateObject?
Really depends on your use case, but you could do this:
struct FeedbackView: View {
    ...
    init(_ providedViewModel: ViewModel = ViewModel()) {
        _viewModel = StateObject(wrappedValue: providedViewModel)
    }
...

The "special notation" _viewModel refers to actual property wrapped inside StateObject property wrapper.
This way parent can either pass the model in (if there's some data it needs to initialize), or let the default model to be created:
NavigationLink {
    FeedbackView()
}


text:
Q: Remove all tables from document I need to do a wordcount of my thesis that excludes tables, but not their legends. I need to remove all of my tables, ideally with a command in the preamble. I am currently using Foxit reader's wordcount tool.
MWE:
\documentclass{article}
\usepackage{multirow}

\begin{document}

        \begin{table}[h!]
            \centering
            \begin{tabular}{l l l l}
                \hline
                Foo & Bar \\ bar bar bar & Sum & Foo \\ \hline
                Foo & Bar & Sum & Foo \\
                Foo & Bar & Sum & Foo \\
                Foo & Bar & Sum & Foo  \\ \hline
            \end{tabular}
            \caption[Contexts]{Le Table}
            \label{table:tisch}
        \end{table}

The table is Table \ref{table:tisch}.

\end{document}

A: As suggested in the comments tabular environments are now ignored through redefinition of this command with the comment package. This is based on this answer.
\documentclass{article}
\usepackage{multirow}
\usepackage{comment}
\excludecomment{tabular}
\let\endtabular\relax

\begin{document}
\begin{table}[h!]
    \centering
    \begin{tabular}{l l l l}
      \hline
      Foo & Bar \\ bar bar bar & Sum & Foo \\ \hline
      Foo & Bar & Sum & Foo \\
      Foo & Bar & Sum & Foo \\
      Foo & Bar & Sum & Foo  \\ \hline
    \end{tabular}
    \caption[Contexts]{Le Table}
    \label{table:tisch}
\end{table}
The table is Table \ref{table:tisch}.
\end{document}

A: One solution is to use TeXcount, which should most likely come along with your TeX installation, which defaults to ignoring tables but counting their captions. By default, headlines, regular text, and caption texts are counted separately, but this can be modified if desired.
It is possible to call TeXcount from the TeX/LaTeX document, and include the word count: see details in the FAQ, or StackExchanges questions here and here.


text:
Q: Delay a javascript function until a css animation is complete I am trying to make a modal object library that will create and open a div, iframe, img, similar to colorbox. I am doing this in pure javascript, so please do not recommend jQuery.
The problem is, when a user creates a new modal using var myModal = new modal(options, width, height), I want it to check if a modal already exists, close it, wait for the close animation,  then continue to create the new modal. I can already do everything, but I'm having an issue waiting to create the new modal until the old one is gone. I am aware of webkitTransisionEnd and firing custom events, but that is not the issue. I need the actual code to wait until the old modal is finished closing until it continues on to finish the rest of the function and still return the correct object to the user. Here are some of the things I've tried:

*

*Creating a transisionEnd listener waiting for the animation to end then creating the new modal. (this worked but considering it then becomes a nested function, it's hard to return the correct object).

*Using a try, catch block. (this didn't work for my purposes)

*Using a countless number of variations of the same thing where I use recursive functions

If anyone has ideas, please feel free to post them. I have tried a lot of things, but apparently not the one thing that I need to. Thanks.
EDIT:
I was able to figure it out.  All I had to do was attach a transitionEnd listener to the modal that is already open, then create an additional function outside of the class that would then recall the modal with the same constructor. The code looks a bit like this:
function create(options, width, height) {
    return new modal(options, width, height);
}

function modal(options, width, height) {
    if (modal != null) {
        modal.close();
        modal.addEventListener('webkitTransitionEnd', function() {
            create(options,width,height);
        });
    }
    return;
}

A: var animationDuration = 1000;
setTimeout(function(){
    // Animation done!
}, animationDuration);

A: You can't cause code to wait (e.g. pause execution of the current thread of execution) until some future event occurs.  Javascript simply does not support that or work that way.  It does not have a way to block the current thread of execution other than a couple modal functions like alert().
What you can do is use callbacks to notify some calling code of a future event.  But, the calling code will register its callback and be returned to immediately and continue executing so the calling code has to be written to handle the callback implementation.
If you're trying to do all the work inside your library, then it should not be that tough.  When the caller creates a new modal, you just have to check for a pre-existing modal dialog.  If one is not up you proceed as normal.  If one is up, then you register a callback notification with the previous one, store the contents of the constructor, but don't actually create the new modal dialog.  Then, when your callback gets called to indicate the previous modal dialog has completed, you finish putting up the new modal.
If these modal dialogs are all of your own creation, then you need to implement completion notification on them so that when they are closed, they can notify any listeners that they're done now.  If they use an animation to close and you want to wait for the close notification until the animation is complete, then you can implement that also.  If you're using CSS3 animations, then as you appear to already know, you can use the transtionEnd event to know when an animation is done or if you know the timing of the animation and you don't need to be ms precise, you can also just use a setTimeout() to know approx when the animation is complete.


text:
Q: letting the user upload a picture to my kivy app I started this week my first app in kivy platform.
One basic functionality I want to have is the ability to let the user upload a picture to the app and then storing it in my SQLITE3 DB .
All the solutions I found was how to show an image and not how to let the user upload one as input
After a long search on the web I haven't found any solution to my problem.
Thx for the help!


text:
Q: Django ListView Page Redirect into custom URL I'm trying to redirect a page after submitting a post with the object id placed into the urlpattern. Currently it is returning the following error:

Reverse for 'create_quotation_add_product' with keyword arguments '{'kwargs': {'pk': 43}}' not found. 1 pattern(s) tried: ['create_quotation/quotation-id-(?P\d+)/$']

The first view is for the user to input details and submit it into the database. The second view needs to take the data into the url to bring up the submitted object's primary key for use as a foreign key in a separate table.
Views.py
class CreateQuotation(ListView, ModelFormMixin):
    model = Quote
    form_class = QuoteForm
    template_name='quotations/create_quotation.html'

    def get(self, request, *args, **kwargs):
        self.object = None
        self.form = self.get_form(self.form_class)
        return ListView.get(self, request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        self.object = None
        self.form = self.get_form(self.form_class)

        if self.form.is_valid():
            self.object = self.form.save(commit=False)
            self.object.created_by = request.user
            self.object.created_date = timezone.now()
            self.object.save()

            return redirect('create_quotation_add_product', kwargs={'pk': self.object.pk})

        return self.get(request, *args, **kwargs)

class QuotationAddProduct(ListView, ModelFormMixin):
    model = Quote_Products
    form_class = QuoteProductForm
    template_name='quotations/quotation_add_products.html'

    def get(self, request, *args, **kwargs):
        self.object = None
        self.form = self.get_form(self.form_class)
        return ListView.get(self, request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        self.object = None
        self.form = self.get_form(self.form_class)

        if self.form.is_valid():
            self.object = self.form.save(commit=False)
            self.object.quote_id = Quote.objects.get(pk=self.kwargs['pk'])
            self.object.save()

            self.form = self.get_form(self.form_class)

        return self.get(request, *args, **kwargs)

    def get_context_data(self, *args, **kwargs):
        context = super(QuotationAddProduct, self).get_context_data(*args, **kwargs)

        context['form'] = self.form
        context['quote_pk'] = Quote.objects.get(pk=self.kwargs['pk'])
        context['quote_products'] = Quote_Products.objects.filter(
            quote_id=Quote.objects.get(pk=self.kwargs['pk'])
        )

        return context

The two urls work fine at the moment, I'm having trouble linking the two together.
urls.py
urlpatterns = [
    url(r'^create_quotation/$', CreateQuotation.as_view(), name='create_quotation'),
    url(r'^create_quotation/quotation-id-(?P<pk>\d+)/$',
    QuotationAddProduct.as_view(),
    name='create_quotation_add_product'
    ),
]

Is there something I'm not doing properly in the html form?
quotations/create_quotation.html
<form action="" method="POST">
      {% csrf_token %}

        {{ form.as_p }}

      <input type='submit' value='CONFIRM DETAILS'/>
</form>

Sorry if the terms I use aren't correct, only started learning recently.

A: Try below reverse method of django for URL
from django.urls import reverse
from django.http import HttpResponseRedirect
return HttpResponseRedirect(reverse('create_quotation_add_product', args=(self.object.pk,)))

A: According to the redirect shortcut, if you want to pass any arguments to the create_quotation_add_product url via the redirect shortcut method, you should do it like this:
return redirect('create_quotation_add_product', pk=self.object.pk, another_key=another_value).

The way you do it, refers to the reverse built-in function of Django.


text:
Q: Android Studio .apk build ZipException Error This issues is resolved.
I deleted all *.jar file and add below code.
This is edit my gradle code
compile group: 'org.apache.httpcomponents', name: 'httpclient-android', version: '4.3.5'

compile (group: 'org.apache.httpcomponents', name: 'httpmime', version: '4.3.6') {

    exclude module: 'org.apache.httpcomponents:httpclient'

}

all.
I have an error but I don't know how to fix it.
I need your kind help.
I'm not so used to StackOverflow site.
because I hope you to understand my mistakes on my post.
This is the error:

Error:Execution failed for task ':app:transformClassesWithJarMergingForRelease'.
com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: org/apache/http/MessageConstraintException.class

and my build.gradle code:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "24.0.0"
defaultConfig {
    applicationId "com.example.daehwankim"
    minSdkVersion 19
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
    multiDexEnabled true
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
packagingOptions {
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'
}

useLibrary 'org.apache.http.legacy'

}

dependencies {

compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile files('libs/httpclient-4.3.1.jar')
compile files('libs/httpclient-android-4.3.5.jar')
compile files('libs/httpcore-4.3.jar')
compile files('libs/httpmime-4.3.1.jar')
compile 'com.android.support:appcompat-v7:24.2.0'
compile 'com.google.android.gms:play-services:9.4.0'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.google.firebase:firebase-messaging:9.4.0'
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.github.chrisbanes:PhotoView:1.3.0'
compile 'com.android.support:multidex:1.0.0'
compile 'com.google.android.gms:play-services-ads:9.4.0'
compile 'com.google.android.gms:play-services-auth:9.4.0'
compile 'com.google.android.gms:play-services-gcm:9.4.0'
}

apply plugin: 'com.google.gms.google-services'

A: do you need both of these ?
compile files('libs/httpclient-4.3.1.jar')
compile files('libs/httpclient-android-4.3.5.jar')
i think both have MessageConstraintException class inside, but not sure. try to remove first library (if the second one is enough)


text:
Q: Google Analytics - Get All Events Occurrences With Exact Time I'm kind of new to google analytics. I have a site where every time a logged user sends a request to the server I'm sending the event to google analytics.
This event contains this fields: {category: 'api_request', action: request url, label: the logged user id'}.
I am wondering if it is possible to see all sent requests for a specific route for a specific user. I will like to get the specific date-time of each request for this route.
I tried to do this in google analytics and found that I can group by action & date, but it doesn't contain the exact time (make sense). Can I achieve this behavior with google analytics or ga-dev-tools?

A: Be aware of high cardinality
https://support.google.com/analytics/answer/1009671?hl=en
If you start to collect unique data timestamp with every hit, you can soon reach cardinality limit, taht is 50.000 unique dimension values perday. Once you reach this limit, all other collected values will be treated as other.
Consider that day have 86400 seconds.
Date.now()

Date now return time in miliseconds. So every hit will probably have different timestamp and you will reach limit soon.
So if you want to do this, use at least seconds.
Date.now() / 1000;

A: You have to configure (and send on each event) a custom dimension hit level that contains the current timestamp (i.e. Date.now()).


text:
Q: Apply one input to tensorflow session and get output I am running the sample MNIST handwritten numbers tutorial.
How can I activate the session with the first test MNIST image and hopefully get the expected output?
When I do this:
print(sess.run(tf.convert_to_tensor(mnist.test.images[0])))

I get a 784-long tensor with weights(guessing):
...
...
...
0.94901967  0.99607849  0.99607849  0.20392159  0.          0.          0.
0.          0.          0.          0.          0.          0.          0.
0.          0.          0.          0.          0.          0.          0.
0.          0.          0.          0.          0.          0.
0.47450984  0.99607849  0.99607849  0.8588236   0.15686275  0.          0.
0.          0.          0.          0.          0.          0.          0.
0.          0.          0.          0.          0.          0.          0.
0.          0.          0.          0.          0.          0.          0.
0.47450984  0.99607849  0.81176478  0.07058824  0.          0.          0.
0.          0.          0.          0.          0.          0.          0.
0.          0.          0.          0.          0.          0.          0.
0.          0.          0.          0.          0.          0.          0.
0.          0.          0.          0.          0.          0.          0.
0.          0.          0.          0.          0.          0.          0.
...
...
...

My expected output would be 7 in this format:
[ 0.  0.  0.  0.  0.  0.  0.  1.  0.  0.]

A: Well, the images (mnist.train.images) are 784 = 28 x 28  dimensional vectors. What you are looking for are labels (mnist.test.labels), which are indeed 10-dimensional:
In [29]: mnist.test.labels[0]
Out[29]: array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.])

By the way, these arrays are just regular numpy arrays, you don't need to use tf session to print them.

A: I think you are looking for the predictions, wich have been stored to y in this phase :
y = tf.matmul(x, W) + b

They are probabilities (thanks to softmax) and you have to take the best to get predicted answer:
tf.argmax(y, 1)

In your case this should give you the prediction for the first image:
tf.argmax(y[0],1)


text:
Q: How to Run a Single Line in RStudio I am used to using the standard R GUI but I'm trying to make the switch to RStudio. However, it's driving me nuts that I can't figure out how to run a single line with a keyboard shortcut. For instance, if I have the two lines,
c <- a +
     b

I would like to press ^R to run the first line and then have to press ^R again to run the second line to complete the assignment. This is the default setting in the standard R GUI. Unfortunately, RStudio only seems to want to execute a statement to it's completion. Is there any way around this?

A: If you want this to be the default behavior, go to "Tools -> Global Options -> Code -> Editing" and uncheck the box "Execute all lines in a statement" under "Execution".

A: Select the first line (by clicking on it three times), then Ctrl-Enter will run the selection, not the statement.


text:
Q: CSS - the content protrudes outside the main frame I have problem with the CSS. I'm changing dynamically one div's content. The problem is, it protrudes outside the main frame, as below:

This's the result I expect. How to achieve that ?

Edit
jsFiddle's code

A: Give maxwidth to your div:
div
{
 max-width: 100px;//The width of your div
}

A: use word-wrap:break-word for the container element


text:
Q: C#, where is the App.config come from? I inherited a simple C# project without a App.config file. I need it now. How should I create one? manually or VS 2008 can do it for me?

A: In VS 2008, right click the project, click Add -> new Item. Find 'Application Configuration File' under Templates. Click 'Add' and your done.

A: You can do it either way.  Right-click the project, select Add New Item, and then click on the Application Configuration item.
Simple.

A: You can do either; manually create it in the root of the project, or just add it using New Item and choosing application config file.


text:
Q: The impacts of increase column's size in Oracle I've a script
SQL script: alter table xx_vms.es_lot_updates modify (routing_list varchar2(1000));

The previous size of this column is 255. Now I increase its size to 1000.
But in this table, the routing_list column often is NULL. Occasionally, it has value.
Does the increment size of this column make performance issues? I'm very confused! Please help. Thanks.

A: No, there is no performance issue. All you have done is allow bigger text strings to be inserted in that column.
Keeping in mind that you should always try to be as strict as possible to what you want to allow in your tables, you are free to make the columns as big as you need. (max 4000 bytes for varchar2)

A: It depends. Tables with varchar2(1000) use greater amount of database blocks for storage, so full table scans are probably going to be more expensive as you're going to read more blocks. Here's a simple test for this:
17:48:25 HR@sandbox> create table c1000 (txt varchar2(1000));

Table created.

Elapsed: 00:00:00.21
17:48:37 HR@sandbox> create table c255 (txt varchar2(255));

Table created.

Elapsed: 00:00:00.03

-- for this test we assume that only 10% of columns are filled with data
17:50:21 HR@sandbox> ed
Wrote file S:\spool\sandbox\BUFFER_HR_32.sql

  1   insert into c255
  2   select decode(mod(rownum,10), 0, lpad('x', 255,'x')) from dual
  3*  connect by rownum <= 1e5
17:50:24 HR@sandbox> /

100000 rows created.

Elapsed: 00:00:01.26
17:50:47 HR@sandbox> ed
Wrote file S:\spool\sandbox\BUFFER_HR_32.sql

  1   insert into c1000
  2   select decode(mod(rownum,10), 0, lpad('x', 1000,'x')) from dual
  3*  connect by rownum <= 1e5
17:50:51 HR@sandbox> /

100000 rows created.

Elapsed: 00:00:01.45
17:50:52 HR@sandbox> commit;

Commit complete.

Elapsed: 00:00:00.01
17:51:20 HR@sandbox> select table_name, blocks from user_tables where table_name in ('C255', 'C1000');

TABLE_NAME                         BLOCKS
------------------------------ ----------
C1000                                1756
C255                                  622

Elapsed: 00:00:00.20
17:53:28 HR@sandbox> set autotrace traceonly statistics
17:53:37 HR@sandbox> select * from c1000;

100000 rows selected.

Elapsed: 00:00:01.30

Statistics
----------------------------------------------------------
          1  recursive calls
          0  db block gets
       1901  consistent gets
       1694  physical reads
          0  redo size
   10586458  bytes sent via SQL*Net to client
       2552  bytes received via SQL*Net from client
        201  SQL*Net roundtrips to/from client
          0  sorts (memory)
          0  sorts (disk)
     100000  rows processed

17:53:50 HR@sandbox> select * from c255;

100000 rows selected.

Elapsed: 00:00:00.63

Statistics
----------------------------------------------------------
          1  recursive calls
          0  db block gets
        825  consistent gets
        295  physical reads
          0  redo size
    3107206  bytes sent via SQL*Net to client
       2552  bytes received via SQL*Net from client
        201  SQL*Net roundtrips to/from client
          0  sorts (memory)
          0  sorts (disk)
     100000  rows processed

Look at consistent gets stat. Full scan of c1000 peforms twice as much IOs compared to full scan of c255.
However, in case you select only a few rows using primary key, I don't think you'll notice a significant difference.

A: No it has not much to do with performance , the varchar2 maximum size is 4000.
once you alter the table do remeber to compile all dependencies ,as they will be invalid for example
procedures and packages


text:
Q: How to create dynamically a simple json array? I know this questions exists like 100 times, but I just can't transfer the solutions to my code, so I hope you can help me. This should be pretty easy but I just don't get it working.
This is just my code with other variable because of reasons:
My Code:
for (var key in array) {
}

The JSON I want:
[{
    key: "One",
    y: 5
}, {
    key: "Two",
    y: 2
},];

Pseudo JSON:
[{
    key: key,
    y: array[key].data
},{
    key: key,
    y: array[key].data;
},];

A: I don't understand what is 'array'. Is it an object or an array?
I think what you want might be this, if 'array' is an array:
var new_arr = [];

your_array.forEach( function(entry) {
  new_arr.push({key: entry, y: entry.data}); // you should change it according to your need.
})

return JSON.stringify(new_arr);

Or if 'array' is just an object, you may need this:
var new_arr = [];

for (key in array) {
  new_arr.push({key: key, y: array[key].data}); // you should change it according to your need.
}

return JSON.stringify(new_arr);

A: You can try this solution:
var data = [];
for (var key in array) {
  data.push({
    key :  key,
    y : array[key].data
  });
}

console.log(data);

But, what about Pseudo JSON:?
DEMO - See console (chrome) for output

A: JSON is just a syntax for expressing objects and arrays independently of a scripting language's syntax.
Apparently you want to convert your array into another structure and have this expressed in JSON. The conversion to JSON is usually performed by the built-in function JSON.stringify.
Assuming your array isn't really an array (which has only numeric indices, usually without gaps), but more an object-like structure, I'd suggest the following code:
var data = []
for (var key in array)
{
    data.push({key: key, y: array[key].data});
}
var json = JSON.stringify(data);
//...

If array really was an array you shouldn't use a for-in-loop. Otherwise you should consider renaming it to avoid confusion.

A: you can use following line to create an array of json
var jsonArr = [];

then you can create json object from following line
var obj = new Object();

put data in json object as following
obj['id'] = 123;
obj['name'] = 'ABC';

then put json object in json array as
jsonArr.push(obj);

you want to add multiple objects in json array then simply create json object and add one by one using push method.
[{"id":"123","name":"ABC"}]


text:
Q: Bash: How to get the call chain on errors? I have a back trace function in bash that works well enough (code below) but the problem is that bash itself when it hits an error, it doesn't give a back trace or any kind of info that would help determine the caller, which can help in debugging the issue.
e.g.:

./c.sh: line 23: urgh: command not found

function backtrace () {
    local deptn=${#FUNCNAME[@]}

    for ((i=1; i<$deptn; i++)); do
        local func="${FUNCNAME[$i]}"
        local line="${BASH_LINENO[$((i-1))]}"
        local src="${BASH_SOURCE[$((i-1))]}"
        printf '%*s' $i '' # indent
        echo "at: $func(), $src, line $line"
    done
}

Is it possible to trap bash on such errors so I could call my own function to get output like this?
 at: c(), ./c.sh, line 22
  at: b(), ./c.sh, line 11
   at: main(), ./b.sh, line 5

Update: final working version from suggestions and traceback trap on error:
function backtrace () {
    local deptn=${#FUNCNAME[@]}

    for ((i=1; i<$deptn; i++)); do
        local func="${FUNCNAME[$i]}"
        local line="${BASH_LINENO[$((i-1))]}"
        local src="${BASH_SOURCE[$((i-1))]}"
        printf '%*s' $i '' # indent
        echo "at: $func(), $src, line $line"
    done
}

function trace_top_caller () {
    local func="${FUNCNAME[1]}"
    local line="${BASH_LINENO[0]}"
    local src="${BASH_SOURCE[0]}"
    echo "  called from: $func(), $src, line $line"
}

set -o errtrace
trap 'trace_top_caller' ERR

A: Absolutely -- this is exactly what error traps are for:
trap backtrace ERR

In the past, I vaguely recall finding it necessary to make that something more like trap 'backtrace "${#BASH_SOURCE[@]}" "${BASH_SOURCE[@]}" "${#BASH_LINENO[@]}" "${BASH_LINENO[@]}"' ERR to work around a bug (and reading array values off the function's argv); however, I don't remember at present just what that bug would be and which versions it impacted.


text:
Q: VirtualBox drive does not expand automatically I have a strange problem with my VDI based drive in VirtualBox, which is that the drive does not expand and this has for some reason also resulted in my x not being able to load.
df -H
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda1       4.3G  4.3G     0 100% /
udev            1.1G  4.1k  1.1G   1% /dev
tmpfs           421M  750k  420M   1% /run
none            5.3M     0  5.3M   0% /run/lock
none            1.1G     0  1.1G   0% /run/shm
none            105M  8.2k  105M   1% /run/user
overflow        1.1M     0  1.1M   0% /tmp

And the drive size:

Is there a way for Ubuntu to reallocate its actual space?
GParted:

Attempt to expand not possible:

A: By using GParted i simply copied the partition i wanted to resize and pasted it into the unallocated partition and resized it. It started copying the partition over and problem was solved.
Since i have already done this i am unable to viualize by screenshots, but there is an copy and paste function when you right click on a partition, so the procedure is simply:

*

*Right click on the partition you wish to expand and click on Copy

*Right click on the unallocated partition and click Paste.

*A screen should popup where you can set the new size

*GParted will start copying the partition into the new resized partition

*Test the new partition before deleting the old one.

An image of the right click menu:

As you can see on the image above /dev/sda1 is the old partition that was too small. The new partition which i am booting from currently is /dev/sda3.
If you delete your old partition, you will need to install grub in the new one (no, it isn't copied together with your data). Boot with a live CD and run the following commands:
sudo mount /dev/sda3 /mnt
sudo grub-install --root-directory=/mnt /dev/sda

A: I guess the problem here is that you have created a very small partition for / that has now run out of space. To solve your problem you need to expand the root partition (/dev/sda1 and filesystem on it). To do that, I'd go this way:

*

*Boot your VM from a live CD

*and extend /dev/sda1 (together with the FS) using GParted - it will take care of everything.

As for me the above approach is little more safe, however you can handle this without live CD as well - have a look at Søren Løvborg's answer here - How can I resize an ext root partition at runtime? or if it is just the matter of resizing a partition, then CodeAddict's answer.


text:
Q: How to parse xmlElements with Jackson? How to parse xmlElements with Jackson?
for example my xml is:
<channel>
  <title>Title</title>
  <link>http://example.com</link>
   <item>
     <category>Categ</category>
     <guid>http://1294796429.html</guid>
     <rian:priority xmlns:rian="http://example.com">3</rian:priority>
   </item>
   ...
   <item>... </item>
   ...
</channel>

classes are:
@JacksonXmlRootElement(localName = "channel")
 public static class Channel {
    @JacksonXmlProperty(localName = "title")
    public String title;
    @JacksonXmlProperty(localName = "link")
    public String link;
    @JacksonXmlProperty(localName = "item")
    public List<Item> items;
 }
 public static class Item{
    @JacksonXmlProperty(localName = "category")
    public String category;
    @JacksonXmlProperty(localName = "guid")
    public String guid;
    @JacksonXmlProperty(localName = "rian:priority")
    public String rian:priority;
 }

I'm using it to parse
XmlMapperxmlMapper = new XmlMapper();
Channel mChannel = xmlMapper.readValue(stringXML, Channel.class);

But it doesn't work. Error is Can't cust String to Item

A: Just need to create class
@JacksonXmlRootElement(localName = "channel")
public class Channel

{
    private String title;
    private String link;
    public Channel(){
    }
    @JacksonXmlProperty(localName = "item")
    @JacksonXmlElementWrapper(useWrapping = false)
    public List<Item> items;
    //----getters...settters
 }

Item class:
public  class Item {
    private String guid;
    private String category;
    public Item(){

    }

}
run
JacksonXmlModule module = new JacksonXmlModule();
        module.setDefaultUseWrapper(false);
        XmlMapper xmlMapper = new XmlMapper(module);
        xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        Channel mChannel = xmlMapper.readValue(in, Channel.class);
        Log.e(LOG_TAG, "getItemsSize: " + mChannel.getItems().size());


text:
Q: Learning the difference between Parse Geopoint and CoreLocation I am new to programming and trying to learn swift, although I am now trying to broaden on location services and how to access a users location.
I am creating an app where I use Parse backend to store users, and I also want it to store the users locations, and then be able to project those users locations as annotations onto a map. Theres a lot of documentation out there which can be quite overwhelming which shows you how to get a users location with both Parse geopoint and coreLocation. If somebody could help explain the actual benefits of using each one and how/why I could use this maybe in what I am trying to achieve?
Thanks in advance.

A: From the documentation
The purpose of Core Location framework is defined as :

The Core Location framework lets you determine the current location or heading associated with a device. The framework uses the available hardware to determine the user's position and heading.

The Purpose of PFGeopoint is defined as:

PFGeoPoint may be used to embed a latitude / longitude point as the value for a key in a PFObject. It could be used to perform queries in a geospatial manner using [PFQuery whereKey:nearGeoPoint:].

CoreLocation is a framework, PFGeoPoint is a class. This is to say that broadly CoreLocation is a suite of tools used to interface with a device's hardware and ask it questions about it's current position (where is it, what direction is it facing) and the classes that provide those services. PFGeoPoint on the other hand, is a class that is part of Parse's framework, used to interface with Parse and store/query your Parse back end for geographic information. Parse provides a connivence method:
+ (void)geoPointForCurrentLocationInBackground:(void ( ^ ) ( PFGeoPoint *geoPoint , NSError *error ))geoPointHandler

which would use CoreLocation under the hood to get the PFGeoPoint that represents the current device's current location. If ultimately you're looking to plot these points on a map, really what you're looking for is a pair of numbers, a latitude and a longitude that represent the current user. You can get this by going through Parse via the method above (each PFGeoPoint object has a lat and a lon), or through using CoreLocation directly (each CLLocation has a CLLocationCoordinate2D object which has a lat and lon).
Hopefully this get's you pointed in the right direction. I know the docs can be daunting at first but hang in there and don't fear them, it all starts to make sense the more you read and explore.


text:
Q: Why does my pre-rendered react website not work with Javascript disabled? I have created, using create-react-app, this website
I use react snapshot to pre-render each route which I serve to the browser. I did this for web crawlers and so the initial render is quicker.
I first test this with postman to check that each route actually renders the content. The HTML for each route contains the content I want.
However, when I test this with google dev tools and disable Javascript the root route renders correctly but all the others only render the header, background picture and the footer. I have no idea why this is. I see, using google console fetch and render, that google crawler also don't see these pages correctly.
Does anyone have any idea what I'm doing wrong?
Thanks in advance


text:
Q: Is it posible to turn android status bar fully transparent with Xamarin Forms? I'm looking for a way to turn Android StatusBar completely transparent with Xamarin Forms. I can easily make it semitransparent by setting android:windowTranslucentStatus to true . It will be black with an opacity of about 50% but anyway its background will be visible, which is not what I want.
I found this article, and this is exactly what I need as a result
https://learnpainless.com/android/material/make-fully-android-transparent-status-bar
but the problem is that there seems to be no obvious way to achieve the same in Xamarin Forms. I just haven't found a way to set decor flags like that nor a way to do this in styles.xml

I've also seen this topic (which was suggested to me while I was creating mine) Android transparent status bar and actionbar and googled this one Xamarin Forms background image with transparent status bar and several others.
But all those solutions end up with a semitransparent status bar as well.
So I'm completely stuck with this

A: I've just found an easy solution.
I just need to set a colorPrimaryDark with alpha component. I was setting alpha component at the end of a hex value (like on android) but I needed to set it at the begining in xamarin.
So the solution is like this:
<item name="colorPrimaryDark">@color/statusTransparent</item>

And the color itself (in colors.xml) is
<color name="statusTransparent">#26ff9b76</color>

Where 26 is the HEX alpha component. Which means 15% alpha, but if I change it to 00 I get fully transparent status bar
I got the values here Hex transparency in colors

LATER
Well, it's not a completely working solution. Even though the status bar turns transparent, xamarin doesn't draw its pages under this status bar, only the activity's background is visible

The only way to make xamarin draw its contents under the status bar is to make it semitransparent via android:windowTranslucentStatus
But in this case it looks like this:

And it's not what I want. So the question is still open

A: You can do this in the OnCreate method of MainActivity.cs
This will remove the status bar from all screens.
// On Create in the activity
protected override void OnCreate (Bundle bundle)
{
    base.OnCreate (bundle);
    this.Window.ClearFlags(WindowManagerFlags.Fullscreen);
    SetContentView (Resource.Layout.YourLayout);
}

if you want for both platforms, I would prefer you do it in the code behind file :
public partial class MyPage : ContentPage
{
      public MyPage()
      {
         InitializeComponent();
         NavigationPage.SetHasNavigationBar(this, false);
      }
}


text:
Q: Unable to load data in Netezza from excel source using SSIS fast Load option I am using SSIS(Fast Load option) to import data into Netezza from excel source. The package is running fine but I could not see any data inserted into the destination table. The number of columns and column order differs in source file and table. Is there any fix for this?
Thanks in advance.

A: Did you check the mapping and verify that you have to un-check the over write option


text:
Q: Simple doubt about Cauchy and convergent sequences. Everything that follows below is under the context we are working on normed vector spaces.
Some context. When trying to prove a subspace $S \subset X = (X,\| \cdot\|_X)$ is closed, the first intuition would be to show that $S = \overline{S}$, where $\overline{S} = S \cup S'.$ The inclusion $S \subset \overline{S}$ comes simply by definition of $\overline{S}.$ Normally, the only thing one has to do is to show that $\overline{S} \subset S$ and thus the subspace $S$ is closed.
To do so, we pick an arbitrary element of $\overline{S}$, say $s \in \overline{S}$ and certainly there is a convergent sequence $(s_k)_{k \in \Bbb N} \subset S$ such that $s_k \rightarrow s$, as $k \rightarrow \infty$.
It is also well known that every convergent sequence is also a Cauchy sequence and here urges my question. We know that the sequence $(s_k)_{k \in \Bbb N}$ is a sequence where each element is in the subspace $S$ and at the same time it converges to an element $s \in \overline{S}.$
Can we say $(s_k)_ {k\in \Bbb N}$ is a cauchy sequence in $S$ or/and can we say that $(s_k)_{k \in \Bbb N}$ is a cauchy sequence in $\overline{S}$? If so, why?
In other words, if a sequence is defined in a set $S$ but converges to a point not necessarily in $S$ is it a Cauchy sequence on $S$?
Thanks for any help in advance.


text:
Q: how to read int and string at the same line? Java Scanner class I must ask the user to enter a province and number for 0-100 on the same line.
Here's the code:
import java.util.Scanner;

public class Main
{
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String prov = in.next();
        int tax = in.nextInt();

    }
}

I want the input to take in both the prov and tax on the same line despite them being different data types. The code seems to still take in the values at different lines.
Input Example:
NY 15
where NY represents the prov variable and the "15" represents the tax variable.

A: Read an entire line and parse that instead of trying to read two values from a line. A complete example might look something like,
Scanner in = new Scanner(System.in);
String line = in.nextLine();
String prov = line.substring(0, line.indexOf(' '));
int tax = Integer.parseInt(line.substring(prov.length() + 1));
System.out.printf("prov = %s, tax = %d%n", prov, tax);

A: This is just another option for this task which also contains User entry validation. If the User enters the required data incorrectly then that User is informed of such and given the opportunity to attempt the entry again or enter q to quit.
The provided runnable demo below allows for single country state or province two letter abbreviations or overall North American (Canada, USA, and Mexico) abbreviations which the demo actually utilizes. The means to easily modify the demo code for a single specific country is only a few keystrokes away.
The tax rate is of double data type and the code validates User entry for unsigned integer or floating point values from 0 to 100 (percent) only. Floating point entry is allowed since US states contain a floating point sales tax rate.
When the entry prompt is displayed, the User is expected to enter a two letter abbreviation (in any letter case) of a state or province and on the same entry line, the tax rate for that same state or province separated with a whitespace or tab. The following would be valid entries:
QC 14.975       [Quebec, Canada]
MO 8.25         [Missouri, USA or Morelos, Mexico]
bc    12        [British Columbia, Canada or Baja California, Mexico]
sk 11           [Saskatchewan, Canada]
ON  13          [Ontario, Canada]
GR 0            [Guerrero, Mexico]
q               [Used to quit the application]

Invalid entries might be:
QC14.975        [No whitespace]
MO, 8.25        [comma used]
ZA 6f           [A non-digit in tax rate]
bv    12        [No such state or province]
sk 101          [Tax rate out of range (0 to 100 allowed only)]
ON  -13         [signed tax rate value]
7.5             [no state or province supplied]
YU              [no tax rate supplied (minimum 0 to be supplied)]
                [nothing supplied (just Enter key was hit)]

Here is the runnable code:
public class StateProvinceAbbrevAndTaxRateDemo {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        java.util.Scanner in = new java.util.Scanner(System.in);

        /* North American Postal Abbreviations used for entry validation...
           Select your flavor or use all three as used in this demo:                       */
        String canada = "\\bnl|pe|ns|nb|qc|on|mb|sk|ab|bc|yt|nt|nu\\b";

        String usa = "\\bAL|AK|AZ|AR|CA|CO|CT|DE|FL|GA|HI|ID|IL|IN|IA|KS|KY|LA|"
                   + "ME|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|OH|OK|OR|"
                   + "PA|RI|SC|SD|TN|TX|UT|VT|VA|WA|WV|WI|WY\\b";

        String canadaUSA = "\\bAL|AK|AZ|AR|AB|BC|CA|CO|CT|DE|FL|GA|HI|ID|IL|IN|"
                          + "IA|KS|KY|LA|ME|MD|MA|MI|MN|MS|MO|MT|MB|NE|NV|NH|NJ|"
                          + "NM|NY|NC|ND|NL|NS|NB|NT|NU|OH|OK|OR|ON|PA|PE|QC|RI|"
                          + "SC|SD|SK|TN|TX|UT|VT|VA|WA|WV|WI|WY|YT\\b";

        String mexico = "\\bAG|BC|BS|CM|CS|CH|CO|CL|DF|DG|GT|GR|JA|EM|MI|MO|"
                      + "NA|NL|OA|PU|QT|QR|SL|SI|SO|TB|TM|TL|VE|YU|ZA\\b";
        // =======================================================================

        /* Used for entry Validation:
           Desired abbreviations added to Regular Expression (regex).
           The regex below covers abbreviations for all of North America
           (Canada/USA/Mexico). Modify the expression to suit your needs.   */
        String regEx = "(?i)q|(" + canada + "|" + usa + "|" + mexico + ")" // valid abbbreviation
                     + "\\s+"                                              // must have 'at least' one space (could have more)...
                     + "(\\b([0-9]|[1-9][0-9]|100)(\\.\\d*)?\\b)";         // tax rate must be inclusively between 0 and 100 percent.
        String input = "";
        while (input.isEmpty()) {
            System.out.println("Enter the state or province postal abbreviation and tax");
            System.out.println("rate separated with a space (ex: BC 7 or: ny 8.52).");
            System.out.print(  "Enter 'Q' to quit: --> ");
            input = in.nextLine();
            if (!input.matches(regEx)) {
                System.out.println("Invalid Entry (" + input + ")! Please try again...");
                System.out.println();
                input = "";
            }
        }
        System.out.println();

        // Is 'q' (to quit) supplied?
        if (input.equalsIgnoreCase("q")) {
            System.out.println("Quitting... Bye-Bye");
            System.exit(0);
        }
        /* Split the User's data entry into a String Array  */
        String[] inputParts = input.split("\\s+");

        /* Apply the String Array elements to their respective
           variables (converting where required).          */
        String stateProv = inputParts[0].toUpperCase();
        double tax = Double.parseDouble(inputParts[1]);

        // Display results within the Console Window.
        System.out.println("State/Province: --> " + stateProv);
        System.out.println("Tax Rate:       --> " + tax + "%");
    }

}

In the above code, the String#matches() method (along with a rather intense Regular Expression) is used on the User entered string to carry out entry validation. The string variable regEx holds the Regular Expression used:
String regEx = "(?i)q|(" + canada + "|" + usa + "|" + mexico + ")" // valid abbbreviation
             + "\\s+"                                              // must have 'at least' one space (could have more)...
             + "(\\b([0-9]|[1-9][0-9]|100)(\\.\\d*)?\\b)";         // tax rate must be inclusively between 0 and 100 percent.


text:
Q: calling relation with a parameter in the view i know this has been asked alot , but none of the solution works for me as i want to use this in the view
i have 3 tables
Languages : id , title
Blog : id
BlogLanguage : blog_id , language_id , title , text

so when i list the blogs in the view , for each blog i want to show what languages has been stores for this Blog
basically i want to do something like this
$blogs = Blog::all();
$languages = Language::all();
return view('blog-index' , compact('blogs' ,'languages));

in the view
@foreach($blogs as $blog )

  id : {{$blog->id}}
  @foreach($languages as $lang )
   {{$lang->title}} : {{ $lang->HasThisBlog($blog->id) ? 'yes' : 'no' }}
  @endforeach

@endforeach

here is what im stuck
{{ $lang->HasThisBlog($blog->id) ? 'yes' : 'no' }}

if i can have this relation in the Language model
function HasThisBlog($id){
 return $this->hasOne(BlogLanguage::class )->where('blog_id' , $id ) ;
}

of course this doesn't work and gives me some weird object like
HasOne {#706 ▼
  #foreignKey: "blog_languages.language_id"
  #localKey: "id"
  #query: Builder {#705 ▶}
  #parent: Language {#560 ▶}
  #related: BlogLanguage {#667 ▶}
  #withDefault: null
}

A: You just need to define a relation on you Blog model. As you already have pivot table for the following relationships
Blog belongsToMany Language(s)
Language belongsToMany Blog(s)

class Blog extends Model
{
    public function languages()
    {
        return $this->belongsToMany(Language::class);
    }

    //....other code of the class
}

class Language extends Model
{
    public function blogs()
    {
        return $this->belongsToMany(Blog::class);
    }

    //... other code of the class
}

Then in blade view
@foreach($blogs as $blog)

{{ $blog->id }}

    @foreach($languages as $language)

{{ $language->title }}: {{ $blog->languages->contains('id', $language->id) ? 'Yes' : 'No' }}

    @endforeach

@endforeach


text:
Q: Convert java.lang.Number using NumberAxis to DoubleAxis() with javafx and scala I try to make a linechart with javafx and scala, but i have some problem converting Number to Double.
My probleme is here, NumberAxis extends Number (java.lang.Number)
val xAxis = new NumberAxis()
val yAxis = new NumberAxis()

You can also see api here : http://docs.oracle.com/javafx/2/api/javafx/scene/chart/NumberAxis.html
In my program, i want to create a new LineChart[Double,Double] and not LineChart[Number,Number], so my convert problem is here, LineChart cannot convert NumberAxis to Double.
//Type mistmatch
new LineChart[Double,Double](xAxis, yAxis)

Is there possible to define a DoubleAxis ? or IntAxis ?
Instead of that, i create all my XYChart with java.lang.Number type :
val xAxis = new NumberAxis()
val yAxis = new NumberAxis()

val linechart = new LineChart[Number, Number] (xAxis, yAxis)
val mySeries = new XYChart.Series[Number, Number]()

// here you can the implicit conversion between Number and Double,
// not bad, but i don't know how the conversion is made ... :/

val myData: XYChart.Data[Number, Number] = new XYChart.Data(1.0, 2.0)

mySeries.getData().add(myData)

linechart.getData().add(mySeries)

Do you think there is a better way to do that in scala ?


text:
Q: Theorems of properties of rational right triangles proving Pythagorean triples Let's say we have a triple of integers $(a,b,c)$ which is assumed to be a Pythagorean triple, so that $$a^2+b^2=c^2.\tag{$\star$}$$
Without using ($\star$) directly or indirectly — but using other properties and theorems related to rational right triangles — what are ways of proving that $(a,b,c)$ is or is not a Pythagorean triple? I'm thinking of theorems on areas, medians, incircles and outcircles, triangle points, infinite ternary tree constructions, etc.
As a concrete example, consider the triple $(3,4,7)$. Without using the fact that $3^2+4^2 \ne 7^2$, how would one prove that $(3,4,7)$ is not a Pythagorean triple?
More to the point, consider the indeterminate triple $$(14x^3,(x^3-7)y^2, x^3y^2+7y^2-14x^3),\tag{$\dagger$}$$
which is derived from the Mordell equation $y^2=x^3+7$. That equation has no integer solutions (as proved using other algebraic methods) — I'm trying to find out if triangle properties can be used to prove the same result.


text:
Q: Ace editor version upgrade I'm a member of a team with more than 20 developers. The ACE editor is the one main editor we used from long time now.
Now, We want to upgrade the ACE editor version, but I don't know which version of ace editor they have used. The current ace version is 1.4.2 but I can't see any version details in the cdn js, and it was taken from this below link :
https://github.com/ajaxorg/ace-builds/blob/master/src-noconflict/ace.js
and the latest version cdn also doesn't have any version details and the team also don't have any version history.
I know, cdnjs is build generated and If I want to update ace, I need to update the followings too :

*

*ace

*ext-language_tools

*mode-javascript

*theme-clouds

*theme-monokai

*worker-javascript

If I update to the newer one,  ext-language_tools throws me an error, few of the events were missed in the newer one.
Is there's any performance update over the older one with a new version of ace editor, with old ace editor version team have done few custom things with ext-language_tools.js.
Things I want to know before updating this :

*

*Is there's any performance update over the older one with a new version of ace editor

*Can I update all the 6 files with new version except ext-language_tools.js, because it has some customized events.

Any help on this really helpful.

A: https://github.com/ajaxorg/ace-builds/blob/master/src-noconflict/ace.js always points to the latest version of the editor published to ace-builds so it doesn't help. But you can get the version of ace by running ace.version in the console, unless it is a very old version it should be defined.
If you have to modify ext-language_tools.js to add events, then it is better to open an issue on ace bugtracker asking to add those events


text:
Q: Tokbox Error ListDictionaryInternal thows message "Error with request submission" We are facing intermittent errors. Exception is "Error with request submission"
It happens on onCreate method.
session = openTok.CreateSession("", (callmode == callmode_auto ? MediaMode.ROUTED:MediaMode.RELAYED)).Id;

Following Tokbox SDK, it is launched here:
https://github.com/opentok/Opentok-.NET-SDK/blob/c27f590dfe383bc37c0352882262a6cc34aff05f/OpenTok/Util/HttpClient.cs#L131
Stacktrace:
OpenTokSDK.Exception.OpenTokWebException: Error with request submission
   in OpenTokSDK.Util.HttpClient.DoRequest(String url, Dictionary`2 specificHeaders, Dictionary`2 bodyData)
   in OpenTokSDK.OpenTok.CreateSession(String location, MediaMode mediaMode, ArchiveMode archiveMode)

Error data: System.Collections.ListDictionaryInternal
It happens in production, not on the test server. I think it happens because there are some users who are creating few sessions and somehow, it breaks the system.
Any ideas?

A: In the end it was a problem with the local time of the server. Our server was few minutes late and TokBox SDK crashed when he had to compare with local time.
Update the server clock to real time, moving it few minutes ahead, solved the problem.


text:
Q: Subgroups generated by 2 elements of $\mathbb{Q}$ I have already proven that $\mathbb{Q}$ is not finitely generated by showing that every finitely generated subgroup of $\mathbb{Q}$ is cyclic and then using proof by contradiction to show that it is not finitely generated.  I was then asked to describe all subgroups of $\mathbb{Q}$ that are generated by 2 elements. Isn't that contradictory or am I perhaps misunderstanding the question?
Thanks in advance for any insight.


text:
Q: Anyway to separate at whitespaces but avoid separating at file paths? I am trying to separate this string into a list using regex:
-y -hwaccel cuda -threads 8 -loglevel error -hide_banner -stats -i - -c:v hevc_nvenc -rc constqp -preset p7 -qp 18 C:\Users\User\Documents\Python\Smoothie\test 124\Resampled_vid.mp4

I am using the following method to separate it:
split(r'(?!\\)'+'\s+',f"{Settings[1]}".format(Input=InFile,Output=OutFile))

Output:
['-y', '-hwaccel', 'cuda', '-threads', '8', '-loglevel', 'error', '-hide_banner', '-stats', '-i', '-', '-c:v', 'hevc_nvenc', '-rc', 'constqp', '-preset', 'p7', '-qp', '18', 'C:\\Users\\User\\Documents\\Python\\Smoothie\\test', '124\\Resampled_vid.mp4']

Desired Output:
['-y', '-hwaccel', 'cuda', '-threads', '8', '-loglevel', 'error', '-hide_banner', '-stats', '-i', '-', '-c:v', 'hevc_nvenc', '-rc', 'constqp', '-preset', 'p7', '-qp', '18', 'C:\\Users\\User\\Documents\\Python\\Smoothie\\test 124\\Resampled_vid.mp4']

Is there anyway, I can exclusively avoid splitting at a file path?

A: I would use an re.findall approach here:
inp = "-y -hwaccel cuda -threads 8 -loglevel error -hide_banner -stats -i - -c:v hevc_nvenc -rc constqp -preset p7 -qp 18 C:\Users\User\Documents\Python\Smoothie\test 124\Resampled_vid.mp4"
parts = re.findall(r'[A-Z]+:(?:\\[^\\]+)+\.\w+|\S+', inp)
print(parts)

['-y', '-hwaccel', 'cuda', '-threads', '8', '-loglevel', 'error', '-hide_banner',
 '-stats', '-i', '-', '-c:v', 'hevc_nvenc', '-rc', 'constqp', '-preset', 'p7',
 '-qp', '18',
 'C:\\Users\\User\\Documents\\Python\\Smoothie\test 124\\Resampled_vid.mp4']

The regex pattern used here says to match, alternatively:
[A-Z]+:(?:\\[^\\]+)+\.\w+  a file path
|                          OR
\S+                        any group of non whitespace characters

The trick here is to eagerly try to match a file path first.  Only that failing do we try to match one word/term at a time.


text:
Q: How to handle the null values for Datetime in c# How can I check Start is blank or empty:
Employee.CurrentLongTermIncentive.StartDate

I have tried the below things:
Employee.CurrentLongTermIncentive.StartDate!=null // Start is empty it's falied.

Employee.CurrentLongTermIncentive.StartDate.HasValue // Start is empty it's falied.

how can I check the null or blank value for Start date and assign to the string value.
Startdate is having the datetime format.

A: An object of type DateTime cannot be set to null.  That is the reason why your code may be failing.
You can try using DateTime.MinValue to identify instances where a value has not been assigned.
Employee.CurrentLongTermIncentive.StartDate != DateTime.MinValue;

You can however configure DateTime to be nullable using the following Declaration.
DateTime? mydate = null;

if (mydate == null) Console.WriteLine("Is Null");
if (mydate.HasValue) Console.WriteLine("Not Null");

Note : the ? - this allows a non-nullable value to assigned as null.
You seem to be using DateTime? for start time, so try the following
if (!Employee.CurrentLongTermIncentive.StartDate.HasValue) {
  Employee.CurrentLongTermIncentive.StartDate = (DateTime?) DateTime.Parse(myDateString);
}

where myDateString is a string representing the date you want to assign.

A: I think you might want if Employee.CurrentLongTermIncentive.StartDate != DateTime.MinValue

A: If you're trying to display it in a textbox just do something like this, just make sure both Employee and CurrentLongTermIncentive are not null:
txtStartDate.Text = GetStartDate(Employee.CurrentLongTermIncentive.StartDate);
private string GetStartDate(DateTime? startDate)
{
        if (startDate != null)
        {
            return startDate.Value.ToShortDateString();
        }
        return "";
}


text:
Q: express serve js files separately My webapp loads far too slowly when using the express.static middleware to serve
all my js files so I wanted to try to serve each js file only when needed (when serving the html from jade that uses the js file). I've tried using .sendFile() but it doesn't seem to be working, though I can't tell if that's because it can't be used for my purpose or if I just don't know how to use it.
Is there a way to dynamically serve up js files so as not to require load time until necessary, or should I just suck it up, minimize my js, and serve it all up staticly at the beginning?

A: I think that the simplest solution for you problem is to use the
async attribute in script tag
http://www.w3schools.com/tags/att_script_async.asp
 A script that will be run asynchronously as soon as it is available:
<script src="demo_async.js" async></script>

Or use defer attribute
http://www.w3schools.com/tags/att_script_defer.asp
A script that will not run until after the page has loaded:
<script src="demo_defer.js" defer></script>

A: if you use in server, setup nginx for serve static file :D


text:
Q: Java pass in string and return string Would some one be able to help me please?
If I have a class like this
public class a {

public String b (String c){
String d = "e";
return d;

}

}

When I call a f = new a();
f.b();

I'm unable to have the string d returned. I get the error  "cannot be applied to ()"
I'm sure I'm doing something stupid but I cant work it out.

A: You have
public String b (String c){

but call b() without any parameter. That's what the error wants to tell you...

A: method b takes a parameter. so try
f.b("some string c");

A: Your method b requires a String to be passed into it.
When you call f.b() it looks for a method with a signature similar to
public String b(){
 // your code
}

A: You have to call like
f.b(aStringVariable);

or
f.b("Some String");

You have to pass the variable while calling the function.

A: Add ... to your method parameter declaration. This will make String parameter optional.
public String b (String... c){
  String d = "e";
  return d;
}

and then new a().b().

A: When you call f.b() you're not passing a string to the method. You declared your function as public String b(String c). That means you have to pass a string when you call f.b.
If you change you declaration to public String b() you do not have to pass a string.
Another solution is simply passing a string, i.e f.b("a string").

A: You are passing String c into your b method
public String b (String c)

you are getting that error because there needs to be a string variable like
a f = new a();  f.b(c);

Where c is some predefined string.

A: Use some string parameter and it will work: f.b("String")


text:
Q: How to create an element after directive element in Angular 4 I have one directive in angularjs which is working fine but it uses jQuery and now I want tot convert it in Angular 4
Old Directive (AngularJS)
app.directive('errName', function () {
    return {
        link: function (scope, element, attrs) {
            element.bind('error', function () {
                if (attrs.src != attrs.errName) {
                    var name = attrs.errName.split(' ');
                    var attr = '?';
                    if (name.length == 1)
                    {
                        attr = name[0].substring(1, 0);
                    }
                    if (name.length > 1)
                    {
                        attr = name[0].substring(1, 0) + name[1].substring(1, 0);
                    }
                    $(element).hide();
                    $(element).after('' + attr.toUpperCase() + '');
                }
            });
        }
    }
});

it simply check there's an error in image on load then it hide that element and create one span after that I changes its name in Angular 4 to show initials I'm getting value hiding element as well but can't able to create span after that
New Directive which I try to build :
export class ShowInitialsDirective {

    @Input() initials;

    constructor(el: ElementRef, renderer:Renderer) {
        var element = el.nativeElement
        renderer.listen(el.nativeElement, 'error', (event) => {
            var initial_default = '?';
            var name = this.initials;
            name = name.split(' ');
            if (name.length == 1)
            {
                initial_default = name[0].substring(1, 0);
            }
            if (name.length > 1)
            {
                initial_default = name[0].substring(1, 0) + name[1].substring(1, 0);
            }
            this.initials = initial_default;
            renderer.setElementStyle(el.nativeElement,'display','none');
           // element.after('' + this.initials.toUpperCase() + '');
        })
    }
}

Is there any way to create span in it and put this html code in it

A: In Angular 2+, you should create a component when you want to change html. Components are directives with html templates. The directive you are creating here is an attribute directive. Attribute directives do not contain html templates. For more information, please refer angular website.

A: Sure, but you might think about rewriting it all together, and creating it into a component. If you really really don't want that, you can use the insertBefore on the parent of nativeElement, and with a little trickery:
const div: HTMLDivElement = document.createElement('div');
div.innerHTML = '' + this.initials.toUpperCase() + '';
const insert: HTMLElement = div.firstChild as HTMLElement;
const before: HTMLElement = el.nativeElement.nextElementSibling;
const parent: HTMLElement = el.nativeElement.parentElement;
if (before) {
   parent.insertBefore(insert, before);
} else {
   parent.appendChild(insert);
}

But again, way prettier would be to create a completely new component doing all this awesome work for you


text:
Q: Pairs of integer series with fixed asymptotic ratio Consider the two integer series $a(n)=n*2^n,b(n)=2^n$. Clearly $a=\Theta(b \log b)$. Another example with the same ratio would be $a(n)=n!\sum_{i=1}^{n}{1/i},b(n)=n!$. Which is even worse in sheer size of the numbers ($n!$ might be replaced with $LCM({1,\dots,n})$ but that doesn't exactly help). Of course $a(n)=\lfloor{n\log n}\rfloor,b(n)=n$ would be a minimum size solution, but it kinda cheats in two ways (the second being the repeating numbers).
Do you have an idea for $a=\Theta(b\log b)$ with no rounding and smallish numbers? ($a=\Theta(b\log\log b)$ would be even more interesting.)


text:
Q: Помогите разобраться с callback функциями Только вникаю в js и дошел до callback функций. Везде приводится такой пример.
function first(callback) {
    setTimeout(function() { console.log("1"); }, 1000);
    callback();
}

function second() {
    console.log('2');
}

first(function () {
    second()
});

Но я не понимаю зачем передавать функцию second в качестве аргумента callback функции first если функцию second я могу и так вызвать без использования параметра.
function first() {
    setTimeout(function() { console.log("1"); }, 1000);
    second();
}

function second() {
    console.log('2');
}

first();

A: Коллбеки это вариант привязаться к определенной точке выполнения. Предположим Вы хотите что бы childFunc() начала выполняться только после того как функция parentFunc() будет завершена:
function parentFunc(callback) {
    // ... какой-либо синхронный код
    callback()
}

function childFunc() {
    console.log("Следующая фунция")
}

parentFunc(childFunc)

Или для асинхронного кода это возможность начать выполнения следующей функции только после того как асинхронная операция будет завершена:
function parentFunc() {
    setTimeout(childFunc, 1000)
}

function childFunc() {
    console.log("Следующая фунция")
}

В JavaScript на системе коллбеков основано многое, например промисы это не что иное как те же самые коллбеки, только в более удобном виде.


text:
Q: Moderation analysis plot: can I use my moderating variable on the x axis I was wondering if anyone could tell me if this is right/ wrong (and if so, how can I fix it). So, I have 3 variables: X (binary), M (continuous moderating variable) and Y (continuous). I conducted a linear regression with interaction and it was all significant. I am now trying to plot it. I read this paper (Baron & Kenny, 1986) and it showed a conceptual graph of a binary X and continuous M.

I have tried to base my own graph on this:

So, I put the moderator on the X axis and my outcome variable on the Y axis. The two lines then show the performance of the 2 groups (which is my X binary variable). However, I am not sure if this conveys the effect of a moderation/ interaction? Does it not look like I just used my binary X variable as the moderators?

A: My answer is yes. The slop (combined red and green) reflects the effect of moderation which appears very strong significance from the plot (as linear lines showed). The gap/distance between red and green lines reflects the effect of the binary X (it appears also very significant). The interaction effect will be reflected by whether the two lines, red and green, parallel or not. If parallel, it means no interaction effect. Statistically, the more of the two lines non-parallel, the stronger effect of interaction (the plots shows there is some level of interaction between X and moderation).


text:
Q: If two pointers point to the same memory address, do you only need to use free(ptr) once or twice? Say we have a struct...
struct node{
    int data;
    struct node *next;
};

struct node *new_node = malloc(sizeof(node));

struct node *temp_node = new_node;

If I use free...
free(temp_node);

Is new_node free as well (since the address no longer exists) or does new_node simply point to NULL (in which case I would need to free new_node as well) ?
Cheers!

A: You don't free pointers but the memory block(s) that you allocated - whose address a pointer points to.
With malloc, it returns pointer to a chunk of memory allocated that looks like this:
             +--------+
             |        |
new_node --> | 0x1000 |
             |        |
             +--------+

If 0x1000 is the starting address of that block of memory, that's what new_node points to (i.e., new_node == 0x1000).
When you assign new_node to temp_node, temp_node points to the same block of memory (i.e., temp_node == 0x1000):
             +--------+
             |        |
new_node --> | 0x1000 | <-- temp_node
             |        |
             +--------+

But there's just one block of memory that you have allocated. So once you free it via either pointer, the other is automatically invalidated and you are no longer allowed access that block of via either pointer.
In the same way, you can assign it to any number of pointers but as soon as it's free'd via one pointer, it's done. That's why care is needed when copying pointers around (because if you free one, it may still be inadvertently used).
P.S.: Free'd pointer may or may not point to NULL afterwards - it's simply undefined behaviour to access free'd memory.

A: The way to think about is like: pointers point to a memory location.
free() returns memory pointed to by a pointer back to the system.
Thus if you have two pointers - once free is called the memory is returned to the system. You still have two pointers. And they still point to the same memory location. It's just now it is not your memory but system's :)
In short - free as many times as you malloc'd.

A: There are plenty of exceptions, but as a general rule, there should be exactly one call to free for every call to malloc.
When you assign one pointer variable to another, you are copying the pointer value -- you are not allocating more memory.  So a pointer copy does not imply the need for a second call to free.

A: Because you are freeing memory and I see just one malloc here, you should only free() once.
In general, for each malloc, there has to be one and only one free.
Otherwise, you will get a double free error.

A: For one memory address, you only need to call free once.
Once you call free, that tells the operating system that the memory you allocated can be used again. You do not need to call free on it a second time (and shouldn't, because that's undefined behavior).

A: A few notes on the code

*

*The declarations struct *next and struct *temp_node point to an
unnamed struct that has no instances.

*node is just a structure tag used to name the structure and
cannot be used in an expression like this malloc(sizeof(node)).

If this is what you originally meant:
struct node{
  int data;
  struct node *next;
};
struct node * new_node = malloc(sizeof(struct node));
struct node * temp_node = new_node;

Then the answers provided before this post are completely accurate.

A: #include<stdio.h>
#include<stdlib.h>

struct Node
{
    int data;
    struct Node * next;
}* first=NULL;

int main()
{
    first=(struct Node *)malloc(sizeof(struct Node));
    first->data=5;
    first->next=NULL;

    struct Node * t=first;

    printf("%d",t->data);

    free(first);

    printf(" %d ",t->data);
}

In this scenario though First is freed in main then too t prints the data.
Which says that the allocated memory block can be further used for the different allocation but it's still there and can be used if a pointer is pointing to it.
But in case new allocation is made then that memory block may be allocated to the other variable. Hence after freeing the memory it's behaviour is undefined.


text:
Q: Argument of type '(prev: Phone[]) => Phone[]' is not assignable to parameter of type 'Phone[]' So I' m using useState with callback as an argument: setLikedGadgets((prev: Phone[]) => [...prev, info]);
but I recieve errors:
Argument of type '(prev: Phone[]) => Phone[]' is not assignable to parameter of type 'Phone[]'. Type '(prev: Phone[]) => Phone[]' is missing the following properties from type 'Phone[]': pop, push, concat, join, and 28 more.
on the other hand , if I use instead of prev code:  setLikedGadgets([...likedGadgets, info]);
it all works.
But how to make it work in typescript in normal way?
import { useContext } from 'react';
import { likedContext } from '../context/LikedContext';
import { Phone } from '../types/Phone';

export const useLikes = () => {
  const {
    likedGadgets
    arrayOfLiked,
    setLikedGadgets,
    setArrayOfLiked,
  }
    = useContext(likedContext);

  const addToLiked = (info: Phone) => {
    if (arrayOfLiked.includes(info.id)) {
      return;
    }

    if (arrayOfLiked.length === 0) {
      setLikedGadgets([info]);
      setArrayOfLiked([info.id]);
    } else {
      setLikedGadgets((prev: Phone[]) => [...prev, info]);
    }
  };

  return { addToLiked };
};

by the way , type of setLikedGadgets is (value: Phone[]) => void
which I cannot change , because, thats how I defined it during createContext() initialization.
type LikedContextInterface = {
  likedGadgets: Phone[];
  setLikedGadgets: (value: Phone[]) => void;
  arrayOfLiked: string[];
  setArrayOfLiked: (value: string[]) => void;
};

A: type LikedContextInterface = {
  likedGadgets: Phone[];
  setLikedGadgets: (value: Phone[]) => void;
  arrayOfLiked: string[];
  setArrayOfLiked: (value: string[]) => void;
};

In this definition, setLikedGadgets is a function that takes in an array of phones.  Passing a function to setLikedGadgets violates the type, so typescript shows you an error.
Based on the way you're using it, it appears that setLikedGadgets is a react state-setter function. That would mean it can either take the new value, or it can take a function which computes the new state from the old state. If you want to preserve that behavior, then that information will need to be included in the type.
If you want to import the types from react, they are:
import { Dispatch, SetStateAction } from 'react';

type LikedContextInterface = {
  likedGadgets: Phone[];
  setLikedGadgets: Dispatch<SetStateAction<Phone[]>>;
  arrayOfLiked: string[];
  setArrayOfLiked: (value: string[]) => void; // <--- this may want similar treatment
};

Or if you want to write it yourself, you could do:
setLikedGadgets: (value: Phone[] | ((prev: Phone[]) => Phone[])) => void;

A: Thanks to Nicholas Tower, here is solution to the problem, summed up.
So, bug was in createContext initialization, more specificly type defentition of initial values. Here is already FIXED code.
import { createContext, useState } from 'react';
import { Phone } from '../types/Phone';

type LikedContextInterface = {
  likedGadgets: Phone[];
  setLikedGadgets: (value: Phone[] | ((prev: Phone[]) => Phone[])) => void;
  likedGadgetsID: string[];
  setLikedGadgetsID: (value: string[] | ((prev: string[]) => string[])) => void;
};

export const likedContext = createContext<LikedContextInterface>({
  likedGadgets: [],
  setLikedGadgets: () => {},
  likedGadgetsID: [],
  setLikedGadgetsID: () => {},
});

type Props = {
  children: React.ReactNode;
};

export const LikedContextProvider: React.FC<Props> = ({ children }) => {
  const [likedGadgets, setLikedGadgets] = useState<Phone[]>([]);
  const [likedGadgetsID, setLikedGadgetsID] = useState<string[]>([]);

  return (
    <likedContext.Provider value={
      {
        likedGadgets, setLikedGadgets, likedGadgetsID, setLikedGadgetsID,
      }
    }
    >
      { children }
    </likedContext.Provider>
  );
};

in type of LikedContextInterface I wrongly set type of state-setter functions setLikedGadgets and  setArrayOfLiked:
before
setLikedGadgets: (value: Phone[]) => void;

which meant that it was allowed only to recieve argument of type Phone[]
after
setLikedGadgets: (value: Phone[] | ((prev: Phone[]) => Phone[])) => void;

now it can recieve either value: Phone[]  , or ((prev: Phone[]) => Phone[])) - callback , that with argument of type Phone[], and return Phone[].
also Dispatch<SetStateAction<Phone[]>> wasn't working for me , since type defenition was outside function component.


text:
Q: Why are some some resources in Java not garbage collected and must be closed or autoclosed? If you are lucky some of these classes implement AutoClosable but sometimes you just have to be careful and inspect the existing methods to notice that there is a close, destroy or shutdown method (or what ever the author decided to name it).
This is a major source of resource leaks in Java.
I was discussing this with a colleague and wondered too: why can this not be automated in some way ?
In theory you can use finalize for such cases, but it is not recommended. So why is there no way to just use some of those closable resources and let the GC autoclose them when the instance is no longer reachable without having to remember to explicitely write some close handling code (like try ...) ?
Is this because the system may have been resource starved (File descriptors, ...) before the GC kicks in ?
NOTE: I use autoclose when possible and check my code for memory leaks using FindBugs (+ FB contrib), but still, I wonder ...
Also of interest (as discussed in the answers): deprecation of finalize.

A: The Garbage Collector's only job is to collect memory that is no longer used. Adding closing of resources will have negative effects on the performance of the Garbage Collector and is currently done by the Finalizer thread that is called by the Garbage Collector anyway in order to allow implementations to clear resources before being collected. It's worth noting that this mechanism is declared deprecated because it wasn't the best solution for this kind of thing from the start, but for the time being it's possible to implement your classes to clean themselves up before they are going to be collected.
The Finalizer (or the new mechanim in Java 9) might be extended to check if the class to be collected implements AutoClosable (an interface added with Java 1.7, so it's not that old anyway) and call it in addition to finalize. This would have a similar effect as you proposed without the need to change the behavior and the role of the Garbage Collector. Maybe that's already happening (haven't tested it myself, yet).

A:
why this cannot be automated in some way ?

Because, in general, a class can do anything: there is no easy way for the compiler to know that something was "opened", and thus should be "closed", because Java has no strong notion of ownership of values.
Even if you have a field which is of a type that needs closing, you can't easily guarantee that it won't be returned from a getter, say, to something else which is responsible for closing it.
The only really consistent way to indicate that instances of a class need closing is by implementing the AutoCloseable interface (or Closeable, or some other interface which extends it). If you're using these, IDEs may be able to provide warnings about leaked resources; but these are going to be on a best-effort basis.

A: You can create your own auto-close resource if you like, but you will need to put in a little work.
You could code a manager/factory class that keeps a weak reference to an object representing each closable object.  You hand out this "Representative" facade class to clients and the client uses this representative class to access the resource (It would contain a reference to the closable and act as a delegate).
This implies that the factory starts a thread and keeps a map of:
<WeakReference<Representative>, Closable>

that it can iterate over.  If the representative has been garbage collected (the WeakReference would return a null), close the closable and remove it from the map--Anything left in the collection can also be closed on VM shutdown with a hook--This is probably the most dangerous part since a thread could still be interacting with the Closable during shutdown, but we have all the tools to manage the problem.
Your closable resource itself is never held by anything outside it's Representative and the Manager/Factory so it's behavior is predictable.
I've never seen this done--probably because it seems like a lot more work than just making an object "Closable" (and would be much easier to implement incorrectly), but I don't know why it wouldn't work.
It would be quite difficult for Java to implement this as a pattern/language feature, but by giving us the WeakReference it gives us the tools to make it possible.

A: To me it looks like all the answers are missing the main point: While the GC can take care of the resource closing, it can't do it fast enough.
An example is the rather unsolved problem of memory mapped files. They mapping get cleared when they're no more references to them, but in the meantime, you may run out of file descriptors or virtual memory (this indeed can happen as it's limited to a few TB).

*

*The GC gets only invoked when the heap memory is exhausted, which may be long after other resources are exhausted.

*It's impossible to efficient collect garbage as soon as an object becomes unreachable. This would require reference counting, which is way slower than generational GC and requires some additional treatment for circular references.

*It's impossible to efficiently collect resources in some separated GC cycles, so that resource closing works fast enough.

This is why IMHO this answer is wrong. You can handle resources this way (or using finalize or whatever), but it's not good enough.

A: If you are developing a common module(or a common util class), you can use execute around method pattern to handle resources that needs to be closed. So this way users of your module don't have handle these resource's closing.(Probably prevents many bugs, because people may forget to close the resource.)
There is a great presentation by Mr Venkat, that he talks about this problem. Watch the next 10 minute, he explains this beautifully.https://youtu.be/e4MT_OguDKg?t=49m48s
Here is the sample code from the presentation;
public class Resource {
    /*
     * This represents a resource that needs to be closed.
     * Since opening and closing the resource are done through use()  method,
     * Users of this resource don't have to care about resource is being closed or not.
     * They just have to pass operations that they want to execute on the resource.
     */
    private Resource() {System.out.println("created..");}
    public Resource op1() {System.out.println("op1");return this;}
    public Resource op2() {System.out.println("op2");return this;}
    private void close() {System.out.println("closed..");}

    public static void use(Consumer<Resource> consumer) {
        Resource resource = new Resource();
        try {
            consumer.accept(resource);
        }
        finally {
            resource.close();
        }
    }
}

public class SampleResourceUser {
    /*
     * This represents the user of the Resource,
     * User only cares about which operations that needs to be done on the resource.
     * Opening and closing the resource wrapped around the operation methods by the owner of the Resource.
     *
     */
    public static void main(String[] args) {
        Resource.use(resource->resource.op1().op2());
    }
}