text:
Q: Abnormal cooling fan speed My laptop is a Dell Inspiron 3521, dual booted Windows 7 with Ubuntu 18.04 LTS.
Two days ago I installed Ubuntu, when I start Ubuntu the fan speed is at 0 RPM. It eventually increases when the temperature rises (1200 -> 2600 -> 3200 -> 4800). But the problem is that the fan speed goes to max (4800 RPM) at about 55 °C and it never decreases. The temperature drops to a minimum of 42 °C.
All readings are taken from lm-sensors and psensor. In Windows, at 42 °C the fan doesn't even start, and I've barely seen it goes to max speed (monitored with HWiNFO).
So I'm a bit worried about this matter. I've read some other articles about fan speeds, and as they suggest I don't want to mess with the fan speed by manually overriding it unless it's absolutely necessary. Laptop's specs are here.

*

*What would be the cause to fan to run continuously at max speed?

*Besides the sound, is it a problem to let fan continue at this speed?

A: Install i8kutils:
sudo apt install i8kutils

Next add to file /etc/modules the new line i8k:
echo "i8k" | sudo tee -a /etc/modules

Create and add to i8k.conf file new line options i8k force=1
echo "options i8k force=1" | sudo tee -a /etc/modprobe.d/i8k.conf

Now force i8k kernel module to load:
sudo modprobe i8k force=1

or just reboot your laptop.
Open file /etc/i8kmon.conf with nano text editor:
sudo nano /etc/i8kmon.conf

Add to the file the following strings:
# Run as daemon, override with --daemon option
set config(daemon)      0

# Automatic fan control, override with --auto option
set config(auto)        1

# Report status on stdout, override with --verbose option
set config(verbose) 1

# Status check timeout (seconds), override with --timeout option
set config(timeout) 20

# Temperature thresholds: {fan_speeds low_ac high_ac low_batt high_batt}
set config(0)   {{-1 0}  -1  40  -1  40}
set config(1)   {{-1 1}  30  60  30  60}
set config(2)   {{-1 2}  53  128  53  128}

# For computer with 2 fans, use a variant of this instead:
# Temperature thresholds: {fan_speeds low_ac high_ac low_batt high_batt}
# set config(0) {{-1 0}  -1  52  -1  65}
# set config(1) {{-1 1}  41  66  55  75}
# set config(2) {{-1 1}  55  80  65  85}
# set config(3) {{-1 2}  70 128  75 128}

# end of file

Now you can run i8kmon to check the cpu temperature and control the fan speed:
i8kmon

More information on i8kmon available from Ubuntu Manpage.


text:
Q: Extend Dockerfile with additional pip install commands I'm not a docker expert and I've been searching for an answer to this as it seems like it should be pretty simple -- specifically as a multi-stage build.  But if so, it's still not clear to me how I pull off what I'm trying to do within the multi-stage build framework.
original Dockerfile:
FROM python:3.8.5

RUN mkdir /src
WORKDIR /src

RUN apt-get update && apt-get install -y --no-install-recommends \
    git \

COPY api/requirements.txt /src/

RUN pip install pip
RUN pip install -r requirements.txt

COPY . /src/

Additional commands that I'd like effectively inserted after the two RUN pip install lines:
COPY api/requirements-dev.txt /src/
RUN pip install -r requirements-dev.txt

Ideally the second couple of lines would (with whatever FROM ... AS statements might be needed) be in Dockerfile-dev, and then I could just build from Dockerfile-dev to capture whatever changes might be in Dockerfile and tack on my dev dependencies.
Obviously I could just copy the original Dockerfile, add the extra lines, call the result Dockerfile-dev, and build from that.  However I'm trying to corral all of the dev dependencies into their own files that explicitly inherit the "prod" files as much as possible, as with docker-compose.yml-like inheritance/overrides.  That lets me leave the "prod" code untouched and avoid e.g. conflicts when I merge it in, and makes it clear via additional files what stuff is being added to make my dev environment.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to enforce changing homepage of Internet Explorer? So, my friend installed some super awesome free game which he totally enjoys playing. But when installing it, he checked "change my home page to superawesomegames.com"
Now whenever he opens the IE, he is directed to the homepage of the game. I tried to change the home page in IE settings, but after a restart, the gaming home page appears.
So far, I found solution in tweaking the shortcut on the desktop to "iexplore.exe" desiredhomepage.com which opens IE and loads the desired home page.
However, I would like to do better change. I know that probably uninstalling the game and installing it again would solve my problems, but my friend does not want to lose all his gaming records (which uninstall claims to do)
Is there for instance system registry I could change to enforce default homepage to something my friend wants?
P.S.: Recommending other browser is also not an option, since my friend is very conservative as of internet browser choice


text:
Q: Auto Layout iOS 11 Toolbar UIBarButtonItem with customView Recently in our project there was a problem with a UIBarButtonItem that was using a customView. Before iOS 11 we did the layout via flexible spacing items. This didn't work anymore and so nothing was displayed.
Because I didn't find an answer here on SO that really solved the issue for me, I looked into it and came up with a (admittedly kind of hacky) solution I wanted to share with you.
Maybe it can help you or you have some feedback. This is mixed objc and swift code, hope you don't mind.

A: As shown in the WWDC Video Updating Your App for iOS 11:

"And so now in iOS 11, UI toolbar and UI navigation bar both have
  intricate and express support for auto layout."

So my first step was to use layout constraints on he custom view itself:
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:customView];
    [barButtonItem.customView.widthAnchor constraintEqualToConstant:375].active = YES;
    [barButtonItem.customView.heightAnchor constraintEqualToConstant:44].active = YES;

This resulted in the toolbar showing the customView. The problem was that left and right of the view, there was a gap. And you could see it.
So I looked in the View Hierarchy Debugging tool and realized, there is a UIToolbarContentView on the toolbar. This contentView had the right size (especially width) and I began wondering. I looked at the only subview the contentView had and it was a UIBarButtonStackView. This stackView was somehow limiting my customView in terms of width.
So it looks like this:
contentView |<-fullWidth-------->|
stackView     |<-reducedWidth->|
customView    |<-reducedWidth->|

What made me curios was, that the customView is not a subview of the stackView. This is probably a consequence of the customView being included in UIBarButtonItem. Any (additional) constrains on the customView remained without change (or crashes because the views aren't in the same hierarchy).
After learing all this, I added an extension to the UIToolbar:
extension UIToolbar {
    private var contentView: UIView? {
        return subviews.find { (view) -> Bool in
            let viewDescription = String(describing: type(of: view))
            return viewDescription.contains("ContentView")
        }
    }

    private var stackView: UIView? {
        return contentView?.subviews.find { (view) -> Bool in
            let viewDescription = String(describing: type(of: view))
            return viewDescription.contains("ButtonBarStackView")
        }
    }

   func fitContentViewToToolbar() {
        guard let stackView = stackView, let contentView = contentView else { return }
        stackView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
        stackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
        stackView.widthAnchor.constraint(equalTo: contentView.widthAnchor).isActive = true

    }
}

So what it does is this:
It gets the contentView from the subviews by comparing the names to "ContentView" and gets the stackView by doing the same on the contentView.
Probably a return subviews.first would do the same, but I wanted to be sure.
Then the layout constraints are set and voila: it works in the full width.
I hope someone may find this useful. If there's comments: I'm very open to feedback on this one. Maybe I missed something and all this isn't even necessary.
Edit: The 'find' function is an extension to Sequence. It does 'filter.first' and looks like this:
extension Sequence {
    func find(_ isIncluded: (Self.Element) throws -> Bool) rethrows -> Self.Element? {
        return try filter(isIncluded).first
}

}


text:
Q: Cardinality of the union of a countable number of countable, well-ordered sets I know that the Axiom of Choice is required to show that the union of a countable number of countable sets is countable. However, what if the sets are well-ordered, i.e. we have a particular well-ordering for each set. Are we then able to show that the union is countable without the AoC?
Someone here mentions we can only show that it is at most $\aleph_1$ rather than $\aleph_0$, but I don't know whether this is correct or, if so, how one would show that.
Suppose that $S = \{A_n \,|\, n < \omega\}$ is our countable system of sets. Clearly then, since each $A_n$ is well-ordered, it is isomorphic to a unique ordinal number $\alpha_n$ where obviously $|\alpha_n| \leq \aleph_0$. Obviously if $\alpha_n = \omega$ then we can form a sequence whose range is $A_n$, but the problem is that it could be that $\alpha_n > \omega$ and still be the case that $\alpha_n$ is countable (for example the ordinal $\omega \cdot 2$ is still countable). In this case I don't see how we can generally choose a sequence whose range is $A_n$, which is what we need to do if the AoC is to be avoided.
I am actually trying to prove something more general: if $S = \{A_\beta\}_{\beta < \aleph_\gamma}$ is a transfinite sequence of well-ordered sets, and each $A_\beta$ in $S$ is at most $\aleph_\gamma$, then the union $\bigcup_{\beta < \aleph_\gamma} A_\beta$ is also at most $\aleph_\gamma$. However, I do not think there is any chance of proving this without choice if the case where $\gamma = 0$ (i.e. the case above where everything is countable) cannot even be proven without choice.

A: It is indeed possible that the countable union of countable, well-ordered sets can be uncountable. What's needed isn't a specific well-ordering, but rather a specific injection into $\omega$, for each of the sets involved.
To get a sense of what's going on here, notice that there is no canonical bijection between a infinite countable ordinal $\alpha$ and $\omega$. Even though we have a specific well-ordering of $\alpha$ in hand, we don't have a "certificate of countability"!
The snappiest way to describe this situation is probably:

It is consistent with ZF that $\omega_1$ (= the least uncountable ordinal) is singular (= is a union of countably many countable ordinals).

Now I've just said that it's consistent; can I prove it?
Well, not in this answer box, unfortunately. Consistency proofs in set theory are hard: even when we're just proving consistency with ZFC, we tend to need forcing, and for interesting violations of choice we need the further technique of symmetric submodels.
That said, here's a few words on the subject: a model of ZF + "$\omega_1$ is singular" was produced by Feferman and Levy very early on (I don't recall the exact date). The Feferman-Levy model is described in detail in a number of places, including Jech's book on the axiom of choice.
Actually, what Feferman-Levy showed was that their model satisfied "$\mathbb{R}$ is the countable union of countable sets," but this implies that $\omega_1$ is singular: in ZF, we can show that there is a (very simply defined) surjection $s:\mathbb{R}\rightarrow\omega_1$, so if $\mathbb{R}$ is the union of countably many countable sets, then so is $\omega_1$. Now let $\omega_1=\bigcup_{i\in\omega} C_i$, where each $C_i$ is countable. Either some $C_i$ is cofinal in $\omega_1$, in which case we're done, or the sequence $\alpha_i=\sup(C_i)$ is cofinal in $\omega_1$, in which case we're also done.

A: Let me also add something which is implicit in Noah's answer. It is definitely not correct that the countable union of countable sets has cardinality of at most $\aleph_1$.
It is true that if $\bigcup\{A_n\mid n<\omega\}$ can be well-ordered, and each $A_n$ is countable, then the cardinality is at most $\aleph_1$. But it is most certainly possible that the cardinality is not even comparable with $\aleph_1$, and if by countable you allow also finite, then it can even be Dedekind-finite.
What is true, however, is that if you take any function from a countable union of countable sets to the ordinals, then its range must have cardinality of at most $\aleph_1$. Because the image of a countable set is countable, and so we return to the case of a countable union of countable sets which can be well-ordered (the union can).
But wait, there's more! A very old result by Douglass B. Morris, stating the following is consistent with $\sf ZF$:

For every $\alpha$, there is a set $X_\alpha$ which is the countable union of countable sets, such that $\mathcal P(X_\alpha)$ can be mapped onto $\omega_\alpha$.

So there's no real bound on how large, and how odd, a countable union of countable sets can be. Or how strange a universe without choice can be.

Let me point out that you are right about the general theorem. It is always possible to arrange that the successor of $\aleph_\gamma$ has cofinality $\aleph_\gamma$, at least when $\aleph_\gamma$ is regular. Or even a countable cofinality if you prefer.
The key point is that just being well-ordered is not enough, one needs to have a distinguished bijection with the cardinal itself. Here is where the axiom of choice is used.
But similar to the countable case, you can prove that the union of $\aleph_\gamma$ sets of cardinality $\aleph_\gamma$, if well-orderable, has cardinality of at most $\aleph_{\gamma+1}$.


text:
Q: Selecting a row based on another column's condition I have the following output:
ApplicationNumber ApplicationStatusCode CreatedOn      AppStat_Disbursed/Unc

1                 AnnuledCL             1.3.2019 8:44  Uncompleted
2                 AnnuledCL             1.3.2019 8:45  Uncompleted
3                 Paid                  1.3.2019 8:54  Disbursement
3                 Paid                  1.3.2019 8:54  Uncompleted
4                 Paid                  1.3.2019 8:59  Disbursement
4                 Paid                  1.3.2019 8:59  Uncompleted
4                 Paid                  1.3.2019 8:59  Uncompleted
5                 Paid                  1.3.2019 9:03  Uncompleted
6                 RejectedAS            1.3.2019 9:04  Uncompleted

What I am trying to achieve is to remove duplicate application_numbers with the following condition. If there is more than one entry for an ApplicationNumber (i.e. duplicate entries) it should select and prioritise rows that have "Disbursement" status over "Uncompleted". However, if there is no "Disbursement" Status for that applicationNumber it should take any row from the "Uncompleted" status.
That is the desired outcome:
ApplicationNumber ApplicationStatusCode CreatedOn     AppStat_Disbursed/Unc
1                 AnnuledCL             1.3.2019 8:44  Uncompleted
2                 AnnuledCL             1.3.2019 8:45  Uncompleted
3                 Paid                  1.3.2019 8:54  Disbursement
4                 Paid                  1.3.2019 8:59  Disbursement
5                 Paid                  1.3.2019 9:03  Uncompleted
6                 RejectedAS            1.3.2019 9:04  Uncompleted

A: One way to approach this would be adding a ROW_NUMBER partitioned by the ApplicationNumber and then additionally ordered by the AppStat_Disbursed/Unc
SELECT ApplicationNumber
      ,ApplicationStatusCode
      ,CreatedOn
      ,[AppStat_Disbursed/Unc]
  FROM (
            SELECT *
                  ,ROW_NUMBER() OVER (PARTITION BY ApplicationNumber
                                          ORDER BY ApplicationNumber, [AppStat_Disbursed/Unc])
                             AS rn
              FROM YOURTABLE
       ) A
 WHERE rn = 1


text:
Q: Deeply rename a variable inside a large PR stack I have a PR with 100 commits, which will be submitted as a number of smaller PRs.
At the bottom of the PR stack, I chose a variable name that I now find odd, and would like to change it throughout each commit, but don't want to tediously resolve merge conflicts everywhere.
Is there a way to automate this, using some cli commands to search+replace the variable name?

A: Here's one huge, ugly, but magical command:
git rebase --empty=drop --exec "ag -0 -l 'YourOldUndesirableString' | xargs -0 sed -ri.bak -e 's/YourOldUndesirableString/YourShinyNewString/g'; git clean -f '**/*.bak'; git add .; yarn prettier --write \$(git diff HEAD^..HEAD --name-only) && git add . && git commit --amend --no-verify --no-edit" --strategy recursive --strategy-option theirs <your-base-sha>

*

*The ag command is the_silver_searcher, brew install the_silver_searcher

*This command is generally suited for osx.

*Replace YourOldUndesirableString and YourShinyNewString with your actual strings

*Be sure to replace <your-base-sha> with something like 1a2s3d4f

*Note 90% of this command is inside a rebase --exec "string", maybe there's a way to avoid passing a huge string to git rebase --exec, allowing for better formatting of this code.


text:
Q: scrollViewDidScroll never called I have a Scrollview within View. I want to use the function scrollViewDidScroll to check and update the arrows (left right).
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    NSLog(@"Did scroll");
    [self updateButtons];
}

It seems scrollViewDidScroll won't be called when I scroll left or right. I searched everything but didn't found a solution.
Hope someone has a solution.

A: The typical error is that "one does not simply set the delegate of a view". What you have probably forgotten is
theScrollView.delegate = self;

A: I had this "symptom" as well and lost about 2 hours of my life on it.  I clearly had the delegate set correctly...but I did NOT know about setting the contentSize property on the scroll view. -.-
If you don't set that property, then the scroll view doesn't think there is anything to scroll to, and therefore will NOT trigger the expected scroll view methods.


text:
Q: How to find the last word in a String in Java? How can I find the last word of a string? I am not trying to find a fixed word, in other words, I would not know what the last word is, however I want to retrieve it.

A: Here is my code:
myString = myString.trim();
String[] wordList = myString.split("\\s+");
System.out.println(wordList[wordList.length-1]);

A: Providing you consider words in a sentence to be delimited by whitespace and punctuation (particularly commas, spaces, new lines, brackets, and so on), which means punctuation can appear at the end of the sentence, and you want to include non-ASCII characters in the words, then the following will find you the last word in a string without the punctuation included:
static String lastWord(String sentence) {
    Pattern p = Pattern.compile("([\\p{Alpha}]+)(?=\\p{Punct}*$)", Pattern.UNICODE_CHARACTER_CLASS);
    Matcher m = p.matcher(sentence);
    if (m.find()) {
        return m.group();
    }
    return ""; // or null
}

The regular expression uses look-ahead to find zero-or-more punctuations at the end of the string and matches the alphabetical word before it.
If you want to also allow numbers in the word, change {Alpha} to {Alnum}.

A: Read the String API for various methods you might use.
For example you could:

*

*Use the lastIndexOf(...) method to find where the start of the word is

*Then use the substring(...) method to get the word

A: Use the StringTokenizer for this
    StringTokenizer st = new StringTokenizer("this is a test");//Take any      String
        int count = st.countTokens();//it will count the number of token in that particular String
String[] myStringArray = new String[count];
for (int i = 0; i < count; i++) {
        `myStringArray[i] = st.nextToken();`//insert the words/Tken in to the string array
    }
    `System.out.println("Last Word is--" +  myStringArray[myStringArray.length - 1])`;//get the last words of the given String

A:     System.out.println("enter the string");
    Scanner input = new Scanner(System.in);
    String instr = input.nextLine();
    instr = instr.trim();
    int index = instr.lastIndexOf(" ");
    int l = instr.length();
    System.out.println(l);
    String lastStr = instr.substring(index+1,l);
    System.out.println("last string .."+lastStr);


text:
Q: How to use easing in the jQuery plugin jQuery.ScrollTo? The website only mentions the easing option:
# easing: Name of the easing equation.

But there's no example.
How to use this feature?

A: The examples are here: http://demos.flesler.com/jquery/scrollTo/
Use like so:
$.scrollTo( '#options-examples', 800, {easing:'easeOutQuad'} );

These easing functions don't come built in though. You can use the jQuery Easing plugin. This then supplies the following easing functions:

*

*jswing

*easeInQuad

*easeOutQuad

*easeInOutQuad

*easeInCubic

*easeOutCubic

*easeInOutCubic

*easeInQuart

*easeOutQuart

*easeInOutQuart

*easeInQuint

*easeOutQuint

*easeInOutQuint

*easeInSine

*easeOutSine

*easeInOutSine

*easeInExpo

*easeOutExpo

*easeInOutExpo

*easeInCirc

*easeOutCirc

*easeInOutCirc

*easeInElastic

*easeOutElastic

*easeInOutElastic

*easeInBack

*easeOutBack

*easeInOutBack

*easeInBounce

*easeOutBounce

*easeInOutBounce

A: You can find the default usage here: http://gsgd.co.uk/sandbox/jquery/easing/
Here is an example of 'easeOutQuad':
function (){
 jQuery.easing.def = 'easeOutQuad';

 $('#options-examples').on('click','a', function() {
   $('#another-option-examples').slideToggle(1000);
   return false;
 });
}


text:
Q: ArrayList remove function has bug? This is my code
  public void onClick(View view){
            Logger.debug(TAG, view.getId()+"-->ID");
            ImageView img = (ImageView)hasID.get(view.getId());
            ImageView sameple = (ImageView)hasID.get(isample);

        Logger.debug(TAG, "----------------------");
        Logger.debug(TAG, listFruit.size()+"--->list size");
        Logger.debug(TAG, img.getId() + "--->id");
        Logger.debug(TAG, sameple.getId() +"--->sample id");
        Logger.debug(TAG, hasName.get(img.getId()) +"--->name");
        Logger.debug(TAG, hasName.get(sameple.getId())+ "---> sample name");
        Logger.debug(TAG, "----------------------");
        if(view.getId() == isample){
            String oldScore = this.score.getText().toString();
            int newscore = Integer.valueOf(oldScore) + 1;
            this.score.setText(String.valueOf(newscore));
            boolean b = listFruit.remove(sameple);
            Logger.debug(TAG, "result:"+b);
            scorrect.start();
            change_number_click(0);
            img.setVisibility(View.INVISIBLE);
            randomSample();
        }else{//click wrong
            swrong.start();
        }
    }

public void randomSample(){
    isample = random.nextInt(listFruit.size());
    for(int i = 0;i<listFruit.size();i++){
        int id = getApplicationContext().getResources().getIdentifier(fruit.get(i).file, "drawable",
                getApplicationContext().getPackageName());
        Logger.debug(TAG, hasName.get(id)+"-->name");
    }
    Logger.debug(TAG, "------create sample------");
    Logger.debug(TAG, listFruit.size()+"-->list size");
    Logger.debug(TAG, isample+"-->sample");
    int id = getApplicationContext().getResources().getIdentifier(fruit.get(isample).file, "drawable",
            getApplicationContext().getPackageName());
    Logger.debug(TAG, id +"-->id sample");
    Logger.debug(TAG, hasName.get(id)+"-->name");
    this.sample.setImageResource(id);
    this.sample.setVisibility(View.VISIBLE);
    isample = id;
    Logger.debug(TAG, "-------------------------");
}

And this is result on console:
07-20 02:33:50.694    annona-->name
07-20 02:33:50.694    apple-->name
07-20 02:33:50.694    banana-->name
07-20 02:33:50.694    ------create sample------
07-20 02:33:50.694    3-->list size
07-20 02:33:50.694    0-->sample
07-20 02:33:50.694    2130837563-->id sample
07-20 02:33:50.694    annona-->name
07-20 02:33:50.694    -------------------------
07-20 02:33:50.694    2130837563-->sample
07-20 02:33:50.786    Tick...
07-20 02:33:51.794    Tick...
07-20 02:33:52.694    2130837563-->ID
07-20 02:33:52.694    ----------------------
07-20 02:33:52.694    3--->list size
07-20 02:33:52.694    2130837563--->id
07-20 02:33:52.694    2130837563--->sample id
07-20 02:33:52.694    annona--->name
07-20 02:33:52.694    annona---> sample name
07-20 02:33:52.694    ----------------------
07-20 02:33:52.694    result:true
07-20 02:33:52.698    annona-->name
07-20 02:33:52.698    apple-->name
07-20 02:33:52.698    ------create sample------
07-20 02:33:52.698    2-->list size
07-20 02:33:52.698    0-->sample
07-20 02:33:52.698    2130837563-->id sample
07-20 02:33:52.698    annona-->name
07-20 02:33:52.698    -------------------------

As you see. listFruit is Arraylist
List<ImageView> listFruit = new ArrayList<>();

and this is list value
07-20 02:33:50.694    annona-->name
07-20 02:33:50.694    apple-->name
07-20 02:33:50.694    banana-->name

First, it creates a sample object
07-20 02:33:50.694    ------create sample------
07-20 02:33:50.694    3-->list size
07-20 02:33:50.694    0-->sample
07-20 02:33:50.694    2130837563-->id sample
07-20 02:33:50.694    annona-->name

is annona, in onClick function I remove if user click on sample object
//hasID is hashtable, with key is id, and value is object in listFruit
ImageView sameple = (ImageView)hasID.get(isample);

it return true
But I see it always remove last item in listFruit ArrayList
07-20 02:33:52.694    result:true
07-20 02:33:52.698    annona-->name
07-20 02:33:52.698    apple-->name

Actually, It must remove annona at first item, but not. What's wrong?
More information*
I changed my code to this
  Logger.debug(TAG, "----------------\n");
                Logger.debug(TAG, "Before remove:");
                for(int i = 0;i<listFruit.size();i++){
                    int id = getApplicationContext().getResources().getIdentifier(fruit.get(i).file, "drawable",
                            getApplicationContext().getPackageName());
                    Logger.debug(TAG, hasName.get(id)+"-->name");
                }
                Logger.debug(TAG, "remove ID:"+ksample);
                listFruit.remove(ksample);
                Logger.debug(TAG, "After remove:");
                for(int i = 0;i<listFruit.size();i++){
                    int id = getApplicationContext().getResources().getIdentifier(fruit.get(i).file, "drawable",
                            getApplicationContext().getPackageName());
                    Logger.debug(TAG, hasName.get(id)+"-->name");
                }
                Logger.debug(TAG,"------------------\n");

I remove by index, and this is result:
07-20 03:05:59.694     Before remove:
07-20 03:05:59.694     annona-->name
07-20 03:05:59.694     apple-->name
07-20 03:05:59.694     remove ID:0
07-20 03:05:59.694     After remove:
07-20 03:05:59.694     annona-->name

I removed at position 0 - annona but it still remove last item :(

A: When you print out the contents of your list with this code you are reading from the fruit list rather than the listFruit list, you only use listFruit to get the size.
for(int i = 0;i<listFruit.size();i++){
        int id = getApplicationContext().getResources().getIdentifier(fruit.get(i).file, "drawable",
                getApplicationContext().getPackageName());
        Logger.debug(TAG, hasName.get(id)+"-->name");
    }

Since you don't remove any item from fruit then it doesn't change, so when you print it out it just prints out one less item (because listFruit is now one item smaller).
To fix this issue you need to ensure that the items in fruit are in the same order as listFruit, and remove an item from fruit at the same time you remove an item from listFruit.


text:
Q: jquery selector - ignore child element How do I select only the Text within the span but ignore the child span.

   My Text for A
   *

I would like to select only the text.  i.e. "My Text for A"...not  "My Text for A *" and if there are more than one it should return as an array like a normal selector.
$('.a').text();


text:
Q: Large folder copy between two local drives stuck at 98% I just got a new hard drive and I am moving some files over from one internal drive to another, both NTFS. The file copy was going fine until this point:

Then the transfer rate dropped to 0 bytes/sec and has been like that for about an hour. I'm afraid to cancel the operation because I don't want to lose/corrupt any files. This is a copy operation, not cut, so worst case I can just cancel and redo it, but it's ~300GB so I don't want to do that.
I'm pretty sure the files it is copying are not in use (it would have told me if they were, right?). I'm running Windows 8.1 64bit. Is there anything I can do at this point to get the transfer going again?
Thanks!


text:
Q: Why *ngFor make infinite loop when I use function to return value and crashing browser? I don't understand why *ngFor make infinite loop when I use function to return value.
I use Angular 8
Chat View HTML Template

Chat View Component
private chatMessages:Observable<Array<any>>;

ngAfterViewInit() {
    this.chatMessages = this.chatMessagesService.getMessages();
}

getChatMessageText(chatMessage) {
    if (chatMessage.type == 'text' || chatMessage.type == 'info') {
      console.log('TYPE TEXT');
      return chatMessage.value;
    }
    if (chatMessage.type == 'image') {
      let img_obj = `<div class="conpeek_msg_img_outer"><img src="${chatMessage.value}"></div>`;
      return img_obj;
    }
    if (chatMessage.type == 'file') {
      let file_obj = `<a>${chatMessage.filename}</a>`;
      return file_obj;
    }
  }

Chat Messages Service
private chatMessages = [];
private chatMessagesStream = new BehaviorSubject(this.chatMessages);

constructor(private dialogInfoService: DialogInfoService) {
    this.dialogInfoService.getDialogMembers().subscribe(members => {
      this.dialogMembers = members;
    });
}

getMessages(): Observable<any> {
   return this.chatMessagesStream.asObservable();
}

addMessage(chatMessage) {
    if (chatMessage.type != 'info') {
      for (let member of this.dialogMembers) {
        if (member.member_uuid == chatMessage.sender_dialog_uuid) {
          chatMessage.sender_name = member.member_presentation_name;
          chatMessage.avatar_id = member.avatar_id;

          if (member.member_uuid == this.dialogInfoService.getOwnDialogUUID()) {
            chatMessage.sender_type = 'contact';
            chatMessage.status = 'sending';
          } else {
            chatMessage.sender_type = 'consultant';
          }
        }
      }
    }

 this.chatMessages.push(chatMessage);
 this.chatMessagesStream.next(this.chatMessages);
}

After init this component and receive first message, I get infinite loop of messages console.log('TYPE TEXT'); in console
When I use it to make request for an image message type to download a blob, my chrome browser is crashing.
Why is it happening, and how to fix it?

EDITED
I found the clue why I have "infinite" loop over here. I recreate the app with minimum additional code and all works almost good. But when I added WebSocket to my app, and when this webscoket make some action (open connection, send message, close connection etc.) my loop make iteration. The infinite loop is just a ping-pong messages which my websocket do with server to detect connections problems vert quickly.
Here I show the problem, check console logs after every action WS makes, or send ws msg by click the button.
I read something about it, and every change detection event like button click, http request or websocket action cause this loop iteration.
https://stackblitz.com/edit/angular-xpb5hw

A: *

*You haven't closed the class quote

*Your chatMessagesService return an observable so you need to subscribe to it

 // this.chatMessages = this.chatMessagesService.getMessages();
    this.chatMessagesService.getMessages().subscribe(messages=>{
      this.chatMessages=messages
    })

*As you have a behaviour subject with a default value you can safely subscribe before view has been initialised to avoid content checking errors. replace ngAfterViewInit() with ngOnInit()
I'm not sure how you were testing the addMessage function, but there's a chance that was accidentally within the observable itself which would cause the infinite loop.
As an extra point, once you receive the data from the service that would be a good time to populate the message text, instead of relying on function called from the html template.
Here's a minimal working reproduction: https://stackblitz.com/edit/angular-xnrupp

A: are you changing the value of chatMessages in getChatMessageText(chatMessage). if so, it my be the source of this problem

A: Try adding this in your component:
chatMessageSubscription: Subscription;

    constructor(private chatMessageService: ChatMessagesService) {}

ngOnInit() {
    this.chatMessageSubscription = this.chatMessageService.chatMessagesStream .subscribe((messages: data) => {
            this.chatMessages = data;
        }
}

A: I resolved the problem by putting *ngFor part of code to new component and add to this component decorator changeDetection: ChangeDetectionStrategy.OnPush option.
On init have function to stop detect changes (detach()). Loop iterate now only when new messages from service comes (I added detachChanges in subcribe fn as below).
I need to isolate this component because in Angular every button click, request or WebSocket message trigers a Detection Change in whole application, now I controll this.
ChatMessagesViewComponent
@Component({
  selector: 'chat-messages-view',
  template: `... *ngFor html here only ...`,
  styleUrls: ['./chat-messages-view.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})

constructor(private chatMessagesService: ChatMessagesService, private cd: ChangeDetectorRef) {
}

ngOnInit() {
  this.chatMessages = this.chatMessagesService.getMessages();
  this.cd.detach();
}

ngAfterViewInit() {
  this.chatMessagesService.getMessages().subscribe(messages => {
    this.cd.detectChanges();
    this.scrollMessagesToBottom(true);
  });
  this.scrollMessagesToBottom(false);
}


text:
Q: Rich Text Area fields do not display correctly in Visualforce email template I have an email template that I built as a visualforce template. In my template. I am using rich TextArea field where user can write text in any formate(i.e. It can have bullet points or paragraphs). But when templates fetch the value from VF component, it converts the whole field value in single paragraph.
For Example : if below is my field value
Testing XYZ:

• Testing 1
• Testing 2
• Testing 3

Another paragraph with few lines:

• Line 1
• Line 2

It converts the whole field value like below, which does not looks good while reading :
Testing XYZ:• Testing 1• Testing 2• Testingt 3Another paragraph with few lines:• Line 1• Line 2

Is there any way to keep the format of the field to as it is?


text:
Q: How to handle two spring forms in one page with respective submit actions? I have two spring forms on one page with their own submit actions:
JSP:
<form:form id="frm_user_login" class="animated fadeIn" method="post" action="./loginsubmit.htm" commandName="useSignInFm">

<form:form id="frm_user_register" class="animated fadeIn" method="post" action="./registersubmit.htm" commandName="userRegistrationForm">

And their respective mappings in one Contoller:
Contoller:
@RequestMapping(value = "/loginsubmit.htm", method = RequestMethod.POST)
public ModelAndView signIn(@ModelAttribute("useSignInFm") SignInForm signInForm, BindingResult bindingResult,
        Model model, HttpServletRequest request)

@RequestMapping(value = "/registersubmit.htm", method = RequestMethod.POST)
public ModelAndView userRegistration(@ModelAttribute("userRegistrationForm") UserRegistrationForm userRegistrationFm,
        BindingResult bindingResult,Model model, HttpServletRequest request)

Submitting one form (userRegistrationForm) gives exception of other form:
Neither BindingResult nor plain target object for bean name 'useSignInFm' available as request attribute.

How can I handle this?

A: Since you're rendering two forms in one page, you need to bind them both in your controller mappings, otherwise the unbinded one will get lost while returning to the view, causing that error. The form backing objects must both exists when rendering the view.
So try this, it worked in my case, very similar to yours:
@RequestMapping(value = "/loginsubmit.htm", method = RequestMethod.POST)
public ModelAndView signIn(@Valid @ModelAttribute("useSignInFm") SignInForm signInForm,
BindingResult bindingResult, @ModelAttribute("userRegistrationForm")
UserRegistrationForm userRegistrationFm, Model model, HttpServletRequest request)

@RequestMapping(value = "/registersubmit.htm", method = RequestMethod.POST)
public ModelAndView userRegistration(@Valid @ModelAttribute("userRegistrationForm")
UserRegistrationForm userRegistrationFm, BindingResult bindingResult,
@ModelAttribute("useSignInFm") SignInForm signInForm, Model model, HttpServletRequest request)

Notice that I added the @Valid annotation because I assume that you want to validate the first form in each request mapping. Also be careful at the position of the bindingResult parameter: it must follow the @ModelAttribute parameter whose binding results you want to consider.

A:
Neither BindingResult nor plain target object for bean name 'useSignInFm' available as request attribute

means that , there is no element with id/name matching "useSignInFm". You should start fixing that first.


text:
Q: How to make a choropleth map with a slider using Plotly? I'm recreating the example choropleth and trying to add a slider that, when dragged, would change from year to year. Another user asked a similar question but they didn't receive a reply. I did some more searching and found an example where the user generated random values for the additional years and created a slider but it's in JavaScript and I'm not sure how to translate it into Python.
Here's the code in JavaScript:
Plotly.d3.csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv', function(err, rows){
  function unpack(rows, key) {
    return rows.map(function(row) { return row[key]; });
  }

  var randomize = z => z.map(d => Math.pow(Math.random(), 2) * 30000);
  var data = unpack(rows, 'total exports');
  var frames = [{
    data: [{z: unpack(rows, 'total exports')}],
    traces: [0],
    name: '1990',
    layout: {title: '1990 US Agriculture Exports by State'}
  }, {
    data: [{z: randomize(data)}],
    traces: [0],
    name: '1995',
    layout: {title: '1995 US Agriculture Exports by State'}
  }, {
    data: [{z: randomize(data)}],
    traces: [0],
    name: '2000',
    layout: {title: '2000 US Agriculture Exports by State'}
  }, {
    data: [{z: randomize(data)}],
    traces: [0],
    name: '2005',
    layout: {title: '2005 US Agriculture Exports by State'}
  }]

  var data = [{
    type: 'choropleth',
    locationmode: 'USA-states',
    locations: unpack(rows, 'code'),
    z: unpack(rows, 'total exports'),
    text: unpack(rows, 'state'),
    zmin: 0,
    zmax: 17000,
    colorscale: [
      [0, 'rgb(242,240,247)'], [0.2, 'rgb(218,218,235)'],
      [0.4, 'rgb(188,189,220)'], [0.6, 'rgb(158,154,200)'],
      [0.8, 'rgb(117,107,177)'], [1, 'rgb(84,39,143)']
    ],
    colorbar: {
      title: 'Millions USD',
      thickness: 0.2
    },
    marker: {
      line:{
        color: 'rgb(255,255,255)',
        width: 2
      }
    }
  }];

  var layout = {
    title: '1990 US Agriculture Exports by State',
    geo:{
      scope: 'usa',
      showlakes: true,
      lakecolor: 'rgb(255,255,255)'
    },
    xaxis: {autorange: false},
    yaxis: {autorange: false},
    sliders: [{
      currentvalue: {
        prefix: 'Year: ',
      },
      steps: frames.map(f => ({
        label: f.name,
        method: 'animate',
        args: [[f.name], {frame: {duration: 0}}]
      }))
    }]
  };

  Plotly.plot('graph', {
    data: data,
    layout: layout,
    frames: frames,
    config: {showLink: false}
  });
});

Is there a way to do this in Python?

A: The code below is virtually a trimmed down version of the choropleth example for Python and the sliders code.
Randomized data is created based on the first data and each slider entry shows a different part of the data list.
import pandas as pd
import plotly
import numpy as np

plotly.offline.init_notebook_mode()
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv')

data = [dict(type='choropleth',
             locations = df['code'].astype(str),
             z=df['total exports'].astype(float),
             locationmode='USA-states')]

# let's create some additional, random data
for i in range(5):
    data.append(data[0].copy())
    data[-1]['z'] = data[0]['z'] * np.random.rand(*data[0]['z'].shape)

# let's create the steps for the slider
steps = []
for i in range(len(data)):
    step = dict(method='restyle',
                args=['visible', [False] * len(data)],
                label='Year {}'.format(i + 1980))
    step['args'][1][i] = True
    steps.append(step)

sliders = [dict(active=0,
                pad={"t": 1},
                steps=steps)]
layout = dict(geo=dict(scope='usa',
                       projection={'type': 'albers usa'}),
              sliders=sliders)

fig = dict(data=data,
           layout=layout)
plotly.offline.iplot(fig)


text:
Q: mapping 2-D array in react-native Attached JSON:-

[
  {
    "category":"Faces",
    "items": [
      {
        "name": "Oh well!",
        "art" : "¯\\_(ツ)_/¯"
      },
      {
        "name": "Disapproving Look",
        "art":  "ಠ_ಠ"
      },
      {
        "name": "Disapproving Look 2",
        "art":  "ఠ_ఠ"
      },
      {
        "name": "Glasses Smile",
        "art":  "ʘ‿ʘ"
      },
      {
        "name": "Devious Smile",
        "art":  "ಠ‿ಠ"
      },
      {
        "name": "Frowning",
        "art": "ಠ╭╮ಠ"
      },
      {
        "name": "Yelling",
        "art": "ಠoಠ"
      },
      {
        "name": "Mustache Man",
        "art": "ಠ▃ಠ"
      },
      {
        "name": "Blank Stare",
        "art": "ರ_ರ"
      },
      {
        "name": "HUH?",
        "art":  "ლ(`ー´ლ)"
      },
      {
        "name": "Rosy Cheeks",
        "art":  "(。◕‿◕。)"
      },
      {
        "name": "hehehe",
        "art":  "( ¬‿¬)"
      },
      {
        "name": "Pointing Out",
        "art":  "☜(⌒▽⌒)☞"
      },
      {
        "name": "Haha!",
        "art":  "☜(゚ヮ゚☜)"
      },
      {
        "name": "Run Away Crying",
        "art":  "ε=ε=ε=┌(;*´Д`)ノ"
      },
      {
        "name": "Cheers",
        "art":  "( ^_^)o自自o(^_^ )"
      },
      {
        "name": "Up All Night",
        "art":  "۞_۞"
      },
      {
        "name": "High",
        "art":  "q(❂‿❂)p"
      },
      {
        "name": "Dazed & Confused",
        "art":  "⊙﹏⊙"
      },
      {
        "name": "No Clue!",
        "art":  "¯\\_(⊙︿⊙)_/¯"
      },
      {
        "name": "I Dunno",
        "art":  "¯\\(°_o)/¯ "
      },
      {
        "name": "Staring Eyes",
        "art":  "Ꙭ"
      },
      {
        "name": "Cat Eyes",
        "art": "ф_ф"
      },
      {
        "name": "Winking",
        "art": "◕‿↼"
      },
      {
        "name": "Reaching Down",
        "art":  "(,,Ծ‸Ծ,,)"
      },
      {
        "name": "Just Woke up",
        "art":  "╰(´・`)ノ"
      },
      {
        "name": "Sleep Walking",
        "art":  "(¬º-°)¬"
      },
      {
        "name": "Disappointed Look",
        "art":  "(-_-)"
      }
    ]
  },
  {
    "category": "Emotions",
    "items": [
      {
        "name": "Angry",
        "art":  "{{|└(>o< )┘|}}"
      },
      {
        "name": "Why, God, WHY!?",
        "art":  "щ(゚Д゚щ)"
      },
      {
        "name": "In Love",
        "art":  "♥(。✿‿✿。)❤"
      },
      {
        "name": "In Love 2",
        "art":  "♥‿♥"
      },
      {
        "name": "Puzzled",
        "art":  "く(^_・)ゝ"
      },
      {
        "name": "Mad",
        "art":  "( ゚Д゚)"
      },
      {
        "name": "Whatever",
        "art":  "(^~^)ノ"
      },
      {
        "name": "Happy",
        "art":  "ヽ(´▽`)/"
      },
      {
        "name": "Love at First Sight",
        "art":  "꒰♡ˊ͈ ु꒳ ूˋ͈꒱.⑅*♡"
      },
      {
        "name": "Need A Hug",
        "art":  "ヽ(´ー`)ノ"
      },
      {
        "name": "So Beautiful!",
        "art":  "ಥ_ಥ"
      },
      {
        "name": "Sad / Crying",
        "art":  "ಥ﹏ಥ"
      },
      {
        "name": "Embarrased",
        "art":  "(﹡⌒▽⌒﹡)"
      },
      {
        "name": "Extra Embarrased",
        "art":  "(/ω\)"
      },
      {
        "name": "No Thanks",
        "art": "(ღ˘⌣˘ღ)"
      },
      {
        "name": "I've Seen The Light",
        "art": "•✞_✞•"
      }
    ]
  },]

Attempt in React-Native

class Textables extends Component{
  constructor(){
    super()
    this.state={data:[]}
  }

  getData(){
    return fetch('https://raw.githubusercontent.com/OTGApps/Textables/master/resources/content.json')
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({data: responseJson});
      })
      .catch((error) => {
        console.error(error);
      });
  }

  componentDidMount(){
    this.getData();
  }

 render()
 {
      let articles= this.state.data.map(function(articleData, index){
        let articles1 = articleData.map(function(meow, j){
          return(<content>
            <Card><CardItem>
            <Text>{meow.items.name}</Text></CardItem></Card>
            <Card><CardItem>
            <Text>{meow.items.art}</Text></CardItem></Card></content>
          );
        });
        return(

            <Card><CardItem>
            <Text>{articleData.category}</Text></CardItem></Card>
        );
      });
        return(
          <Content>
          {articles}
        </Content>
        )
 }
}

Error:- undefined is not a function (evaluating 'articleData.map')
I'm trying to map the the items one by one by looping through each array.
Should I use index.map instead of articleData.map?

A: articleData points to the object in the data array.  It looks like:
{
    "category": "Emotions",
    "items": [],
}

You want to use articleData.items.map.
Additionally, that getData function will probably not work how you want.  Since it's not bound to the class scope, it won't be able to access this.setState.  You'll probably want to either add this to your constructor:
this.getData = this.getData.bind(this)

or, you can change the function declaration:
getData = () => { /* your function */ }


text:
Q: onclick remove selected and show/hide the delete button and dropdown title Use this jsFiddle instead of Stack Snippet

$(".dropdown li a").dblclick(function(){
  //alert('Long pressed');
  $(this).parent().toggleClass('selected');
  if ($('.dropdown li').hasClass('selected')) {
    // alert('1 Item selected');
    $(this).parent().parent().parent().parent().parent().parent().find('.header').find('.dropdown-title').addClass('hide');
    $(this).parent().parent().parent().parent().parent().parent().find('.deleteli').removeClass('hide');
    $(this).parent().parent().parent().parent().parent().parent().find('.deleteli').addClass('show');
  }
  else {
    $(this).parent().parent().parent().parent().parent().parent().find('.header').find('span').removeClass('hide');
    $('.delete').removeClass('show');
    $('.delete').addClass('hide');
    // alert('1 Item dis selected');
  }
});
$('a#deletelibtn').click(function () {
  // body...
  // alert('deletelibtn clicked')
  $(this).parent().parent().find('.selected').remove();
  $(this).parent().find('.dropdown-title').removeClass('hide');
  $(this).parent().find('.dropdown-title').addClass('show');
})
/*Dropdown Messages*/
.messages-dropdown{
    width: 300px;
}
.messages-dropdown .header{
    padding: 15px;
    border-bottom: 1px solid #ccc;
}
.messages-dropdown .header small{
    float: right;
}
.messages-dropdown .header small a{
    font-style: 9px;
    margin-left: 5px;
}
.messages-dropdown .footer{
    text-align: center;
    border-top: 1px solid #ccc;
}
.messages-dropdown .footer a{
    padding: 15px;
}
.messages-items{
    list-style: none;
    padding: 0;
    padding-left: 0px;
    margin: 0;
}
.messages-items .Mitem {
    padding: 10px;
    padding-left: 10px;
    border-left: 3px solid transparent;
}
.messages-items .Mitem:hover {
    background: #f0f0f0;
    border-color: #3a3f51;
}
.messages-items .Mitem a {
    display: inline-block;
    width: 100%;
}
.messages-items .Mitem a:hover {
    text-decoration: none;
    background: #f0f0f0;
}
.messages-items .Mitem a b{
    color: #444;
    letter-spacing: 1px;
}
.messages-items .Mitem a small{
    color: #999;
    letter-spacing: 1px;
}
.messages-items .Mitem img{
    float: left;
    margin-right: 10px;
    border-radius: 100% !important;
    padding: 5px;
    border: 1px solid #ccc;
    width: 40px;
    height: 40px;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
        Toggle navigation

      </button>

            4

                heading

                delete

                      content

                      content

                      content

                      content

When I select the messages the deletelibtn option is enabled and I'm able to delete the messages, but after deleting the messages the deletelibtn button is not hiding and then again if am selecting the messages again the delete option is not showing.

When the deletelibtn option is showing the dropdown-title should be hidden, similarly when the dropdown-title is visible the deletelibtn button should be hidden.
I hope I explained what I need exactly.

A: I changed several little things which wouldn't affect functionality but are 'best practice'.  There were a couple of small targeting issues as well which are what caused the functional problem.  The reason it was so hard to debug is because your html was a but jumbled and you reused the same words over and over making it hard to follow the logic.  Here is the corrected js.
$('.dropdown-menu li').on('click', function(event){
//The event won't be propagated to the document NODE and
// therefore events delegated to document won't be fired
event.stopPropagation();
});
$("ul.messages-items a").dblclick(function(){
$(this).closest('ul.messages-items').parent().addClass('selected');
  var $container = $(this).closest('div.container-fluid')
  if ($('li.dropdown').hasClass('open')) {
    $container.find('.header').find('.dropdown-title').removeClass('show').addClass('hide');
    $container.find('.deleteli').removeClass('hide').addClass('show');
  }
  else {
      $container.find('.header').find('span').removeClass('hide').addClass('show');
      $('.delete').removeClass('show').addClass('hide');
  }
});
$('a#deletelibtn').click(function () {
    var $this = $(this);
    $('#message').find('li.selected').remove();
    $this.parent().find('.dropdown-title').removeClass('hide').addClass('show');
    $this.find('i.deleteli').removeClass('show').addClass('hide');
})

https://jsfiddle.net/xctgo71x/23/
You can add this off-click event to reset the dropdown.
$(document).click(function(e){
  //console.log(e);
  if(true)
    ResetDropdown();
});
function ResetDropdown(){
    $('span.dropdown-title').removeClass('hide').addClass('show');
    $('i.deleteli').removeClass('show').addClass('hide');
    $('#message').find('li.selected').removeClass('selected');
}

It works ok on the jsfiddle but on your actual code you may need to tweak it a little.
https://jsfiddle.net/xctgo71x/29/


text:
Q: OnboardSDK: mission management and HomePoint initialization I am having Matrice 210 and use OSDK for uploading mission. But the OSDK will not allow uploading if the HomePoint of  the aircraft was not initialized.
I got error "WAYPOINT_MISSION_POINTS_TOO_FAR" if turning on the drone only, and I have to turn on RC and connect DJI GO application for the HomePoint being created.
If I understand correctly, the mission manager only accept mission when the drone has strong GPS signal, but the document do not say anything about the HomePoint initializing.
I try to find in the SDK a function to tell the drone get it current GPS as HomePoint, but there is no such thing available in the code. Do I miss something?
Update:
Here is how I setup the mission manager:
void setWaypointInitDefaults(WayPointInitSettings* fdata)
{
   fdata->maxVelocity = 10;
   fdata->idleVelocity = 5;
   fdata->finishAction = 0;
   fdata->executiveTimes = 1;
   fdata->yawMode = 0;
   fdata->traceMode = 0;
   fdata->RCLostAction = 1;
   fdata->gimbalPitch = 0;
   fdata->latitude = 0;
   fdata->longitude = 0;
   fdata->altitude = 0;
}
...
bool InitWaypointMission(Vehicle* vehicle, int numberWaypoints, double maxSpeed, double turnSpeed, bool usePointsHeading)
{
   WayPointInitSettings fdata;
   setWaypointInitDefaults(&fdata);
   fdata.indexNumber = numberWaypoints;
   fdata.maxVelocity = maxSpeed;
   fdata.idleVelocity = turnSpeed;
   if ( usePointsHeading )
      fdata.yawMode = 3;

   ACK::ErrorCode initAck = vehicle->missionManager->init(DJI_MISSION_TYPE::WAYPOINT, responseTimeout, &fdata);
   if (ACK::getError(initAck))
   {
        ACK::getErrorCodeMessage(initAck, __func__);
        return false;
   }
   vehicle->missionManager->printInfo();
   return true;
}

A: On DJI drones, the Homepoint is automatically acquired when the drone has visibility of enough GPS satellites. A method that can tell the drone to get its' current position as homepoint will not be useful - if the drone can indeed get a good fix on its' current location in GPS co-ordinates, it has already set it as a homepoint, or will do so in the next few seconds.
There may be many reasons why you are getting the WAYPOINT_MISSION_POINTS_TOO_FAR error, but you will need to provide more context to help us narrow it down. Some things that are useful to report:

*

*After powering on the drone, how long are you letting it sit in clear
skies before trying to upload the mission?

*When you initialize your waypoint mission through the MissionManager, have you made sure to set the RCLostAction to Keep Going?

*Is the behavior reproducible in simulation?


text:
Q: How to write multiple outputs of different formats in a hadoop reducer? How do you use the MultipleOutputs class in a reducer to write multiple outputs, each of which can have its own unique configuration? There is some documentation in the MultipleOutputs javadoc, but it seems limited to Text outputs. It turns out that MultipleOutputs can handle the output path, key class and value class of each output, but attempts to use output formats that require the use of other configuration properties fail.
(This question has come up several times but my attempts to answer it have been thwarted because the asker actually had a different problem. Since this question has taken more than a few days of investigation for me to answer, I'm answering my own question here as suggested by this Meta Stack Overflow question.)

A: I've crawled through the MultipleOutputs implementation and have found that it doesn't support any OutputFormatType that has properties other than outputDir, key class and value class.  I tried to write my own MultipleOutputs class, but that failed because it needs to call a private method somewhere in the Hadoop classes.
I'm left with only one workaround that seems to work in all cases and all combinations of output formats and configurations:  Write subclasses of the OutputFormat classes that I want to use (these turn out to be reusable).  These classes understand that other OutputFormats are in use concurrently and know how to store away their properties.  The design exploits the fact that an OutputFormat can be configured with the context just before being asked for its RecordWriter.
I've got this to work with Cassandra's ColumnFamilyOutputFormat:
package com.myorg.hadoop.platform;

import org.apache.cassandra.hadoop.ColumnFamilyOutputFormat;
import org.apache.hadoop.conf.Configurable;
import org.apache.hadoop.conf.Configuration;

public abstract class ConcurrentColumnFamilyOutputFormat
                        extends ColumnFamilyOutputFormat
                        implements Configurable {

private static String[] propertyName = {
        "cassandra.output.keyspace" ,
        "cassandra.output.keyspace.username" ,
        "cassandra.output.keyspace.passwd" ,
        "cassandra.output.columnfamily" ,
        "cassandra.output.predicate",
        "cassandra.output.thrift.port" ,
        "cassandra.output.thrift.address" ,
        "cassandra.output.partitioner.class"
        };

private Configuration configuration;

public ConcurrentColumnFamilyOutputFormat() {
    super();
}

public Configuration getConf() {
    return configuration;
}

public void setConf(Configuration conf) {

    configuration = conf;

    String prefix = "multiple.outputs." + getMultiOutputName() + ".";

    for (int i = 0; i < propertyName.length; i++) {
        String property = prefix + propertyName[i];
        String value = conf.get(property);
        if (value != null) {
            conf.set(propertyName[i], value);
        }
    }

}

public void configure(Configuration conf) {

    String prefix = "multiple.outputs." + getMultiOutputName() + ".";

    for (int i = 0; i < propertyName.length; i++) {
        String property = prefix + propertyName[i];
        String value = conf.get(propertyName[i]);
        if (value != null) {
            conf.set(property, value);
        }
    }

}

public abstract String getMultiOutputName();

}
For each Cassandra (in this case) output you want for your reducer, you'd have a class:
package com.myorg.multioutput.ReadCrawled;

import com.myorg.hadoop.platform.ConcurrentColumnFamilyOutputFormat;

public class StrongOutputFormat extends ConcurrentColumnFamilyOutputFormat {

    public StrongOutputFormat() {
        super();
    }

    @Override
    public String getMultiOutputName() {
        return "Strong";
    }

}

and you'd configure it in your mapper/reducer configuration class:
    // This is how you'd normally configure the ColumnFamilyOutputFormat

ConfigHelper.setOutputColumnFamily(job.getConfiguration(), "Partner", "Strong");
ConfigHelper.setOutputRpcPort(job.getConfiguration(), "9160");
ConfigHelper.setOutputInitialAddress(job.getConfiguration(), "localhost");
ConfigHelper.setOutputPartitioner(job.getConfiguration(), "org.apache.cassandra.dht.RandomPartitioner");

    // This is how you tell the MultipleOutput-aware OutputFormat that
    // it's time to save off the configuration so no other OutputFormat
    // steps all over it.

new StrongOutputFormat().configure(job.getConfiguration());

    // This is where we add the MultipleOutput-aware ColumnFamilyOutputFormat
    // to out set of outputs

MultipleOutputs.addNamedOutput(job, "Strong", StrongOutputFormat.class, ByteBuffer.class, List.class);

Just to give another example, the MultipleOutput subclass for FileOutputFormat uses these properties:
    private static String[] propertyName = {
        "mapred.output.compression.type" ,
        "mapred.output.compression.codec" ,
        "mapred.output.compress" ,
        "mapred.output.dir"
        };

and would be implement just like ConcurrentColumnFamilyOutputFormat above except that it would use the above properties.

A: I have implemented MultipleOutputs support for Cassandra (see this JIRA ticket, and it is currently scheduled for release in 1.2.  If you need it now, you can apply the patch in the ticket.  Also check out this presentation on the topic which gives examples on its usage.


text:
Q: How can I turn my four perfect hash basic pseudocode methods into workable code? I am trying to figure out how I can turn my 4 basic pseudocode methods inside of my perfect hash class into workable methods that will eventually be used inside of a main method of my PerfectHash class. I know I haven't created the instance of the class yet, but I will.
You know like when you call the 4 methods using a stack, for example, you input parameters inside the methods, but my application will be able to take the key that's entered by the user and insert, fetch, delete, or update on it inside of the structure.
Do I need to put more thought into these methods or is the pseudocode enough to work for now? Here's what I have done so far. I know the first class compiles fine, but I am having trouble with the second class as I have already indicated above.
public class PerfectHash
{

  private StadiumTickets[] data;

  public boolean insert(StadiumTickets newStadiumTicket)
  {
      // the direct insert hashed algorithm

       pseudoKey = preProcessing(targetKey);
       ip = pseudoKey; // direct hashing function

       // insert the new ticket
        data[ip] = newStadiumTicket.deepCopy();
  }

  public StadiumTickets fetch(String targetKey)
  {

    // the fetch algorithm
    // access the primary storage area

     pseudoKey = preprocessing(targetKey);
     ip = pseudoKey; // direct hashing function

    if(data[ip]== null)
     {
         return null;
     }
     else
     {
        return data[ip].deepCopy();
     }
   }

   public boolean delete(String targetKey)
   {
      // the delete direct hashed algorithm

      // access the primary storage area

         pseudoKey = preprocessing(targetKey);

       ip = pseudoKey; // direct hashing function

      if(data[ip]== null)
      {
         return false;
       }
      else
      {
        data[ip]= null;
        return true;
      }
    }
    public boolean update(String targetKey, StadiumTickets newStadiumTicket)
    {
        // the update direct hashed algorithm

       if(delete(targetKey) == false)
           return false;
       else
        {
           insert(newStadiumTicket)
             return true;
         }
     }

}

import java.util.Scanner;

public class StadiumTickets
{

     int ticketNumber; // keyfield

     String purchaserName;

  public void input()
  {

     Scanner input= new Scanner(System.in);

      // key values ranges between 2000 to 100,000

      System.out.print("Please enter a ticket number between 2000 to 100,000: ");

      // a variable to hold the answer

       ticketNumber= input.nextInt();

        // error checking to make sure the user doesn't enter a key outside of the lower or upper ranges

       if(ticketNumber < 2000 && ticketNumber > 100000)
        System.out.println("This number is not a valid entry to input into the structure.");
     }

  public StadiumTickets(int ticketNumber, String purchaserName)
  {

       this.ticketNumber= ticketNumber;
       this.purchaserName= purchaserName;
   }

   public StadiumTickets deepCopy()
   {

      StadiumTickets clone= new StadiumTickets(ticketNumber, purchaserName);
       return clone;
   }
}


text:
Q: Feynman, Hibbs Perturbations and Energy I am currently self-studying from Feynman & Hibbs' Quantum Mecahnics and Path Integrals, but having an issue understanding a step in their development of first-order perturbations. They define
$$V_{mn}(t)=\int_{-\infty}^\infty \phi_m^*(x)V(x,t)\phi_n(x)\,dx,$$
where $\phi_m(x)$ is an unperturbed eigenfunction with energy $E_m$, and $V(x,t)$ is a perturbing potential. This gives (eventually) the probability of transition from state $n$ to $m$ within time $T$ as
$$P(n\rightarrow m)=\frac{|V_{mn}|^2}{(E_m-E_n)^2}\left[4\sin^2\frac{(E_m-E_n)T}{2\hbar}\right]$$
This all makes sense to me. But on p150, they specialise to the case where values of the final energy, $E_m$, lie in a continuum, defining $\rho(E)\,dE$ as the number of states with energy lying between $E$ and $E+dE$. We now have, as the probability of any transition:
$$\int|V_{mn}|^2\frac{4\sin^2[(E_m-E_n)T/2\hbar]}{(E_m-E_n)^2}\rho(E_m)\,dE_m$$
At this point, they spend some time demonstrating that the final states that contribute most to this integral will be those with energy $E_m$ that is in the neighbourhood of, nearly, or approximately the same as $E_n$ (all three descriptions are used). They then use the approximation that $|V_{mn}|$ and $\rho(E_m)$ vary slowly enough in this neighbourhood that we can treat them as constant, taking them outside the integral. Using $\int_{-\infty}^\infty[(sin^2 x)/x^2]\,dx = \pi$, they write (p151) "we obtain the result that the probability for a transition to some state in the continuum is
$$P(n\rightarrow m)=\frac{2\pi}{\hbar}|V_{mn}|^2\rho(E_n)T,$$
and that the energy in the final state is the same as the energy in the initial state." (emphasis mine).
I have no issue following the mathematics up to this final result, but I cannot see why they have moved from describing the final energy as lying in the continuum, approximately equal to the initial energy, to claiming the result that it is the same. A few paragraphs later, they explicitly replace $\rho(E_n)$ with $\delta(E_m-E_n)$, but again, I can't see why.
They have not indicated that this result arises from $T\rightarrow\infty$; could that be what I am missing?

A: If the contribution is from state close to $E_n$, they can assume that the level density doesn't vary much in that within that range in energy. Replace $\rho(E_m)$ with its value at $E_n$. The delta comes from
$\frac{\sin^2(xT)}{Tx^2} \rightarrow \pi \delta(x), T \rightarrow \infty.
$


text:
Q: bookshelf.js not loading relation Im new to bookshelfjs and i want to get the data from other table using the ID from other table.
Im using this sample data:
/* User's Table */
----------------+-------------------+----------
   lastname     |    firstname      |   id
----------------+-------------------+---------
Dela Cruz          Juan                1
Pendoku            Pedro               2

/* Logs's Table */
----------------+--------------+----------
     userid     |    time      |   id
----------------+--------------+---------
  1                 8:00           1
  2                12:00           2
  1                 9:00           3

Question: how i can query the logs of specific user thru bookshelf.js?
so the result should be like this:
----------------+--------------+----------
     lastname   |    time      |   id
----------------+--------------+---------
 Dela Cruz          8:00           1
 Dela Cruz          9:00           3

My query:
new User({'lastname': 'Dela Cruz'})
  .logs()
  .fetch()
  .then(function(timelog) {
    console.log(timelog.toJSON());
});

My models
var User, Log;

User = bookshelf.Model.extend({
  tableName:'user',
  logs: function() {
     return this.hasMany(Log, 'userid');
  }
});

Log = bookshelf.Model.extend({
  tableName:'log',
  user: function(){
    return this.belongsTo(User, 'userid');
  }
});

Log Error:
{ __cid: '__cid1',
  method: 'select',
  options: undefined,
  bindings: [undefined],
  sql: 'select log.* from log where log.userid = ?'
}

A: Change the user model to this:
User = bookshelf.Model.extend({
  tableName:'user',
  logs: function() {
     return this.hasMany(Log);
  }
});

And try this
new User({'lastname': 'Dela Cruz'})
  .fetch({withRelated:['logs']})
  .then(function(timelog) {
    console.log(timelog.toJSON());
});

A: Try adding the {idAttribute: 'UserId'} to your User model
I found mine was case sensitive to the FieldNames so 'userid' resulted in no returned data but 'UserId' did. So make sure it matches the field in your db
So change your model to
User = bookshelf.Model.extend({
  tableName:'user',
  idAttribute: 'userid',
  logs: function() {
     return this.hasMany(Log);
  }
});

And try the query as shown in uglycode's answer


text:
Q: Django: IntegrityError at /accounts/accounts/myprofile UNIQUE constraint failed: accounts_userprofile.user_id When I am trying to update an existing userprofile i get this error,
IntegrityError at /accounts/accounts/myprofile
UNIQUE constraint failed: accounts_userprofile.user_id
I have searched for solutions, but it does not work for me.
model:
class UserProfile(models.Model):
is_deligate = models.BooleanField(default=True)
is_candidate = models.BooleanField(default=False)

user = models.OneToOneField(CustomUser,
on_delete=models.CASCADE)

name = models.CharField(max_length=200)
stud_id = models.IntegerField(primary_key = True)
course_year_and_section = models.CharField(max_length=200)

def __str__(self):
    return self.name

Form:
class UserProfileForm(ModelForm):
class Meta:
    model = UserProfile
    fields = ['name','stud_id','course_year_and_section']

view:
def UserProf(request):
user = request.user
ls2 = UserProfile.objects.get(user_id=user.id)
form = UserProfileForm()

if request.method == 'POST':
    form = UserProfileForm(request.POST)
    if form.is_valid():
        profile = form.save(commit=False)
        profile.user = request.user
        profile.save()
context = {'form':form,'ls2':ls2}
return render(request,"accounts/myprofile.html", context)

def UpdateUserProf(request):
form = UserProfileForm()
try:
    prof = request.user
except UserProfile.DoesNotExist:
    prof = UserProfile(user=request.user)
if request.method == 'POST':
    form = UserProfileForm(request.POST,instance=prof)
    if form.is_valid():
        form.save()

        return redirect("myprofile.html")
else:
     form = UserProfileForm(instance=prof)
context = {'form':form}
return render(request,"accounts/myprofile.html", context)

A: CustomUser can only have one UserProfile,that's what OneToOneField means, maybe you are trying to set a UserProfile for a CustomUser with an existing one. Check whether this helps.

class UserProfile(models.Model):

    is_deligate = models.BooleanField(default=True)
    is_candidate = models.BooleanField(default=False)

    user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, related_name="profile")

    name = models.CharField(max_length=200)
    stud_id = models.IntegerField(primary_key = True)
    course_year_and_section = models.CharField(max_length=200)

    def __str__(self):
        return self.name

def UserProf(request):
    user = request.user
    ls2 = UserProfile.objects.get(user_id=user.id)
    form = UserProfileForm()

    if request.method == 'POST':
        form = UserProfileForm(request.POST, instance=user.profile)
        if form.is_valid():
            profile = form.save()
    context = {'form':form,'ls2':ls2}
    return render(request,"accounts/myprofile.html", context)


text:
Q: Template lite - incrementing a variable is it possible in html side increase a variable ?
i mean
{$i++} in template lite does not work
What i want is that if i is multiple of four , it must add a

 {foreach from=$books value=book}

 {/foreach}


text:
Q: VB.NET byte <-> string conversion error/problem I am reading data from a socket (as bytes) and storing this data in a string. Then later i need to access specific bytes within the string and do some math with them. However the bytes that I read back from the string are not what I am expecting.
Here's code to demonstrate my problem:
    Dim bytTest() As Byte = {131, 0}
    Dim strTest As String
    strTest = System.Text.ASCIIEncoding.ASCII.GetString(bytTest)
    MsgBox(bytTest(0) & " = " & Asc(strTest.Substring(0, 1)))

This produces "131 = 63", but I would have expected it to produce "131 = 131". Can somebody explain to me why and how I can fix this? Thanks

A: ASCIIEncoding is limited to the first 7 bits (characters 0-127), so trying to store character with a value of 131 isn't going to work as expected.
Use UTF-8 instead.

A: The ASCII encoding only uses the lower 7 bits of a byte for each character. Thus, if you pass a byte with value 131 to it, you will get unexpected results, since the high bit is set for that value.


text:
Q: ASP - Determine if current Script is being run as an include Lets say I have the following pages:
# Include.asp
<%
Response.Write IsIncluded() & "<br>"

%>

# Outside.asp
<!--#include file="Include.asp" -->

I need this to work such that if I access http://Example.com/Include.asp directly, I see "True", yet if I access http://Example.com/Outside.asp I see False.  I'd perfer not to have to add anything to Outside.asp.  Can anyone think of a way to create such an IsIncluded function in ASP?  I was able to create such a function in PHP by comparing __FILE__ to $_SERVER['PHP_SELF'], but that won't work here becasue ASP doesn't have anything like __FILE__ that I am aware of.

A: Try checking the URL requested and match it against the include. Example provided in JavaScript
function IsIncluded() {
  var url = String(Request.ServerVariables("URL"));
  url = url.substring(0, url.indexOf("?")).substring(0, url.indexOf("#")).substr(url.lastIndexOf("/"));
  return (url == "Include.asp")
}

A: Generally in ASP its not good practice to have an include file also available as something that can be fetched by the client.  If you specifically want to prevent the client fetching an include file then place your includes in a folder (called say "Includes") then block access to that folder in IIS.
OTH if you do want the user to be able to access the include file pretty much as it is and also allow other pages to include it then create a "host" page for the include.  E.g.:-
# /Includes/Include.asp
<%
%>

# IncludeHost.asp
<!-- #include virtual="/Includes/Include.asp" -->

# Outside.asp
<!-- #include virtual="/Includes/Include.asp" -->
<%
   '' #Other content/code here
%>

You could now move code and content that were unique to "include.asp" when it was being accessed directly to the IncludeHost.asp file.


text:
Q: Meaning of "To all whom these presents come, greetings" You see this a lot on formal government and institutional documents such as declarations and diplomas. What, exactly, is being said?

A: It is a very formal (or dated) version of "to whom it may concern". You write it in particular on letters patent, such as royal, presidential, diplomatic proclamations. Because these are not sent to a named recipient, but open letters intended to proclaim or attest of something, and thus be presented to the public at large. As you noted, they are also used in diplomas and academic degrees.

A: The word "presents" does not refer to time, but a presentment, or what is presented. An instrument is being presented for the value it represents.

A: F'x is correct in the main, but it is useful to note that these presents is a legal term that makes specific reference to the document in which the words being read are contained.
As NOAD gives it:

these presents formal Law — this document : the premises outlined in red on the Plan annexed to these presents.

And the etymology:

ORIGIN Middle English : via Old French from Latin praesent- 'being at hand,' present participle of praeesse, from prae 'before' + esse 'be.'


text:
Q: Recently moved from Java to JavaScript on Node.js, how to maintain code? I recently moved from Java to JavaScript on Node.js.  I was very excited, opened up my IntelliJ IDE for an existing Node.js project only to find I cannot know what the parameters I see functions receiving actually are except for their names (in java I could click the parameter type and see what it is..), I cannot use Ctrl-Alt-H in most cases in order to show call hierarchy, and found myself doing textual search all over the place wasting most of my time on an existing project, while in Java I could navigate easily with the help of the IDE and find almost everything I want to discover about the codebase in seconds, so possibly in Java there was more "ceremony" and writing the code was taking longer time, but now when I want to maintain it I could do that in seconds and find my way there in seconds.
Is it possible at all to maintain a large code base in JavaScript for code you did not write?
I'm really scared now this is what I'm going to do 100% of my time, maintaining Node.js projects, help me get out of the plain text search which wastes most of my time in trying to discover the flows inside the JavaScript project.
It's not code I wrote, I'm trying to maintain others code and it's super extremely difficult to understand the flows. (in Java I could easily find the flows with the help of the IDE)

A: If you do not mind recompiling your code, I recommend you to look at TypeScript, developed by Microsoft. It has a C#-like syntax and is a supertype to pure JavaScript, which TypeScript compiles to.
Other than that, in combination with modern JS many modern IDEs, I have had a great experience with WebStorm by JetBrains (though it is very likely other IDEs support it as well), analyze JSDoc provided to functions and give you auto-completion based on the types of parameters you defined.
class A {
    /**
     * @param {Number} value
     */
    constructor(value) {
        this.value = value;
    }

    increaseValue() {
        ++this.value;
    }

    /**
     * @returns {Number}
     */
    getValue() {
        return this.value;
    }
}

class B {
    /**
     * @param {A} instanceOfA
     */
    constructor(instanceOfA) {
        // both increaseValue and getValue methods are available through
        // auto-completion in WebStorm
        instanceOfA.increaseValue();
        this.value = instanceOfA.getValue();
    }

    /**
     * @returns {Number}
     */
    getValue() {
        return this.value;
    }
}

Obviously, this is not a fool-proof solution and will not give you compile-time checking like TypeScript does, but it is better than nothing and definitely increases readability.


text:
Q: iPhone- Multiple pages I have a view based app going here with 3 different pages, I can't for the life of me get all the pages linked together correctly or completely.
Its just a home page with 2 buttons linking to the first and send page.... then back to the home page.
I have a mock up of what I am working with if someone could look at it and tell me what I am doing wrong here:
files.me.com/bolinger/0i1isa
thanks mates!

A: Sounds like you can probably make do with a "Navigation-based Project" Xcode can generate for you. As for sample code, TableViewSuite is a good place to start.
Basically, the UINavigationController class takes care of most of the bookkeeping; you just push or pop views as the user taps the buttons in your app.


text:
Q: Issues rendering data correctly using flask-sqlalchemy Background: Having issues querying data from flask sqlalchemy database correctly. In the html template, I'm using the html5 datalist tag in a for loop to render each field listed under column1 of my table. Table is classList and column1 if field1.
Issue: Currently the data renders in a cluster, meaning the whole entire column will render for every field in the dropdown list. I'm trying to get it to render each cell only, under column 1. I tried trailing the results variable with .first() but I get an "AttributeError: 'str' object has no attribute 'field1'" error. Any help is much appreciated. Thank you.
views.py
@app.route('/', methods=['GET', 'POST'])
def index():
    classList = db.Table('classList', db.metadata, autoload=True, autoload_with=db.engine)
    results = [i.field1 for i in db.session.query(classList)]
    return render_template('index.html', results=results)

html template
{% block content %}
    <input type="text" list="classlist" Placeholder="Search list..">
    <datalist id="classlist">
    {% for i in results %}
        <option>{{ results }}</option>
    {% endfor %}
    </datalist>
{% endblock %}

A: @Kruspe provided the solution. Change results in the  tag to i.
<option>{{ i }}</option>


text:
Q: How can I test my webpage using different browsers? I just found out about the Yahoo UI Reset CSS tool/file and I'm using it on my website.
On my machine I have Internet Explorer 7 and Firefox 3.01 and my webpage looks the same on these two browsers.  A friend is using Internet Explorer 6 and the page is completely a mess.
I have two questions:

*

*Am I that poor/stupid in writing CSS?

*How can I test my webpage using different browsers on my machine?

A: If you are not particular about testing in your machine, you could try https://browsershots.org or https://blisk.io. These are free and provide screenshots of your site in various browsers on Linux/Windows/Mac OS/BSD.

A: A reset CSS--of which YUI's is only one example--aim to remove browser differences in default CSS properties for HTML elements, like some browsers will have a default 8 pixel padding on the html element (it was a surprise to me to find the html element was even styled when I first found out).
Your IE6 issues are entirely separate to that. Without examples of the site itself it's impossible to say why this might be but the obvious guess is that you're relying on reasonably advanced CSS features (eg a > b selectors, :hover on non-anchors, certain positioning schemes and so on).

A: For IE you can use this tool (Multiple IE) to test your website in old versions.
For the Reset CSS i redirect you to this question.

A: Just because your website looks terrible in Internet Explorer 6 does not mean you are terrible at CSS.  There are several documented bugs in Internet Explorer's rendering engine in regards to CSS.  Web designers and developers have been struggling with these bugs for years.  Several well known websites like Digg and YouTube are no longer going to support IE6.
You have several options to test your website in multiple browsers.  The easiest way is to install all the browsers you want to test against on a local machine.  There are 5 major browsers, and they all require different methods to install multiple versions.
Microsoft Internet Explorer
If you are using Windows XP, you can use Multiple IEs to install Internet Explorer versions 3, 4.01, 5, 5.5 and 6.
If you are using Windows Vista or Windows 7 (or Windows XP for that matter) you can download virtual machine images from Microsoft that contain a fully licensed Windows operating system with Internet Explorer.  These virtual machine images expire every 90 to 120 days.  They offer the following images:

*

*Windows XP SP3 with IE6

*Windows XP SP3 with IE7

*Windows XP SP3 with IE8

*Windows Vista with IE7

*Windows Vista with IE8

These images can all be used with the free Virtual PC 2007.
Mozilla Firefox
You can install multiple versions of Firefox on the same operating system, but it is highly advised that you create a new profile for each version you are going to install.  You can use the steps outlined on Rob Cherny's blog to set this up (the article is referring to Firefox 2, but it works for Firefox 3 and 3.5 too).  Alternatively, you can use MultiFirefox.
Google Chrome
There really isn't an easy way to run multiple versions of Google Chrome on the same machine. Chrome installations are user account-specific, and standalone versions of Chrome have been made available (see question 3785991), so you can create a new Windows/Mac user account for each old version of Chrome you want to test.
However, the fact that updates are applied automatically and silently means that you really shouldn't worry to much about designing your website for older versions of Chrome.  If this is unacceptable, you will need to use multiple user accounts, or virtual images as advised for Internet Explorer previously.
Apple Safari
Safari is similar to Google Chrome in that there isn't an easy way to run multiple versions on the same machine.  Michel Fortin has an article that details how to get multiple versions running on Mac OS X.  You can refer to this Stack Overflow question for the lowdown on Windows.  Virtual images, again, seem to be the only way to go.
Opera
You can install older versions of Opera without issue, so long as they are installed to different directories.

A: For testing various IE versions I use ietester
It allows different ie versions in each browser tab and it's free.

A: The purpose of it is that HTML(edit: the browsers have predefined properties for the elements.ty Zack) has some predefined properties for its elements like the built-in padding/margin for the paragraph element. The point of using the reset cheat sheet is to start with default values that are equal for all elements : size, margin, padding etc.
 I use the reset file in my project but not in its original form. You should decide which elements in the sheet to use and you can always assign other default values for the tags there.

edit: You can test your web-page by installing most of the browsers available. Here is the latest statistics representing the usage of browsers.
My advice is to use Mozilla as your 1st choice testing browser and every now and then test the page on other browsers: IE6, IE7, IE8, Opera, Chrome and Safari (at least).
Here is a reference to a discussion about multiple IEs on one PC.
Best of luck!


text:
Q: NetBeans 7 to MS Sql Server 2008R2 Connection I'm looking for an easy way to connect my NetBeans application to an SQLServer 2008 R2 database...
I tried with JDBC:ODBC but this doesn't work... I tried other ways but appears to be deprecated or too old for the jre 1.7...
Does anybody have any suggestion? I'm googlig for hours but nobody talks about it, the only things i found are about SQL Server 2000 an other ancient systems!
Thank you very much!

A: You can use the official Microsoft JDBC Driver or the JTDS open source driver each of these two works fine ...

A: Use jtds as the jdbc driver.. and here's some more fluff


text:
Q: Get Wordpress Settings Email Im trying to get the email stored udner 'settings' in wordpress. I know there was an old function for this: get_settings but this is depreciated. I can't find a replacement - is there a reason for this? What is the best practice method for returning the settings email in wordpress?

A: Instead of using get_settings(), use get_option().
Example:
$email = get_option('admin_email');


text:
Q: Can I build UWP with .NET Core? As I know that the .net-core can run UWP,  can we build or write UWP with Core?
I've read the https://msdn.microsoft.com/en-us/magazine/mt694084.aspx

A: UWP apps will be able to use libraries you have created in .net core as long as you target the .netstandard1.6 (or higher) framework moniker.
UWP is only for the windows ecosystem.
See this article.


text:
Q: Сравнение двух строк с разной последовательностью слов Есть две строки, которые по своей сути (почти) идентичны. Пример
s1 = "Variant 2 IBC-Solar Module + 1x SMA WR Stand - Eon Aura 19.01.2017"

s2 = "19.01.2017 Variant 2 IBC-Solar Module + 1 x SMA WR Stand - Eon Aura Some Extra Words"

Можно заметить, что в этих строках пости все слова одинаковые. Какую метрику можно применить для сравнения этих строк?
difflib не предлагать. Нужно просто определить, какая часть совпадает и какие отличия. То есть должна быть метрика, которая, например скажет что 80% слов совпадают и вторая строка больше первой.

*

*Пробовал переводить строки в списки и сравнивать элементы,

*Пробовал применять множество, но это не корректно, поскольку в одной сроке может быть несколько одинаковх слов, в другой могут не повторяться.

Визуально они выглядят одинаково, т.е. содержат одинаковые элементы, последовательность их не так важна. Однако, например в первой строке написано 1x, а во второй1 x
Как быть?


text:
Q: Android: How to put Class type in a Bundle? Is it possible to put a Class type in a Bundle ?
public static <T> Intent newInstance(Class<T> EventClass) {
    Bundle args = new Bundle();
    args.putXXXX(EventClass);
    Intent intent = new Intent(MyApplication.getInstance(), MyActivity.class);
    intent.putExtras(args);
    return intent;
}

Thanks guys !

A: You can simply use Class<T>.getCanonicalName() and then instantiate the class by that name when reading it from the Bundle.
The scenario makes sense if for example you want to communicate between Android components which singleton classes to use.
As an example you could have an action interface
public interface Action {
    void run(List<String> args, Context context);
}

that should perform specific tasks in a Fragment and you want to initialize Fragments with different sets of actions. Then your Fragment's instantiation methods can simply take Action classes as parameter:
public static void newInstance(String someParameter, Class<? extends Action>... actions) {
    Bundle arguments = new Bundle();
    String[] actionNames = new String[actions.length];
    for (int i = 0; i < actionNames.length; i++) {
        actionNames[i] = actions[i].getCanonicalName();
    }
    arguments.putStringArray(ARG_ACTIONS, actionNames);
}

Having defined some classes MyActionA implements Action and MyActionB implements Action you would create a Fragment with these actions in the following way:
Fragment myFragment = MyFragment.newInstance("some parameter", MyActionA.class, MyActionB.class)

The Fragment itself can use a list of actions (List<Action> action) as member variable which is initialized from the Bundle in onCreate():
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    for (String actionName : getArguments().getStringArray(ARG_ACTIONS)) {
        try {
            Class<? extends Action> actionClass = (Class<? extends Action>) Class.forName(actionName);
            Action action = actionClass.newInstance();
            actions.put(action.getName(), action);
        } catch (java.lang.InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}

This by the way would fail with anonymous classes when trying to instantiate them as getCanonicalName() returns null for anonymous classes. So this method cannot be used to pass around anonymous classes, which I doubt to be possible at all.

A: It is not possible to put any object into a bundle. You can put only two types of classes into a bundle: those which implement Serializable or Parcelable.


text:
Q: Prove that $f:\mathbb{R}^{n}→\mathbb{R}$ is affine if and only if it is convex and concave I would like you to evaluate the following proof that $f:\mathbb{R}^{n}\rightarrow \mathbb{R}$ is affine if and only if its convex and concave:
From the convexity of f we have for $x_1, x_2 \in \mathbb{R}^{n}$ and $\lambda \in [0,1] f(\lambda x_1+ (1−\lambda)x_2)\leq\lambda f(x_1)+(1 - \lambda)f(x_2)$
and for concavity we have $f(\lambda x_1+ (1−\lambda)x_2)\geq\lambda f(x_1)+(1 - \lambda)f(x_2)$
Thus it follows that f convex and concave is $f(\lambda x_1+(1−\lambda)x_2)=\lambda f(x_1)+(1 - \lambda)f(x_2)$
And F is affine if $f(x)=ax+b$
Going:
$$
f(\lambda x_1+ (1−\lambda)x_2)=\lambda f(x_1)+(1 - \lambda)f(x_2)=\lambda (ax_1+b)+(1-\lambda)(ax_2+b)=\lambda ax_1+\lambda b+ax_2-\lambda ax_2+b-\lambda b=a(\lambda x_1+x_2-\lambda x_2)+b=a(\lambda x_1+(1-\lambda)x_2)+b
$$
Back:
$$
f(\lambda x_1 + (1-\lambda)x_2)=a(\lambda x_1+(1-\lambda)x_2)+b=a(\lambda x_1+x_2-\lambda x_2)+b=\lambda ax_1+ax_2-\lambda ax_2+b=\lambda ax_1+ax_2-\lambda ax_2+b+\lambda b-\lambda b=\lambda(ax_1+b)+(1-\lambda)(ax_2+b)=\lambda f(x_1)+(1-\lambda)f(x_2)
$$


text:
Q: how many session-keys while man-in-the-middle-attack Hey everyone we got a cheeky question, can you help me please?
How many sessions keys would be created, if there where two man-in-the-middle-attackers on a TTP connection between a Webrowser and a Webserver? And would the attackers see each other? Explain you answer.
I think there would be 4 keys, one for each connection. But im not sure.

A: original communication:
Alice<------->Bob
intercepted communication:
Alice<-->Mallet<-->Marvin<-->Bob
as you can see there are 3 channels, which would lead us to 3 separate communication channels that would require keys in respect to the used protocol
for example if the communication was RSA encrypted on each channel there would be 2 keys ...
since you mentioned communication between a browser and a webserver i suppose TTP shall mean HTTP ... now here is the cheeky problem: HTTP does not feature encryption at all... that would be HTTPS ... so if you are asking for HTTP the answer is "0 session keys are used because there is no encryption. MITM attacks in this setup are transparent, so the attackers do not know of each other just by looking at the connection data"
in the HTTPS case for each connection the two parties calculate a pre-master secret and then derive the master secret which can be seen as the session key since all relevant other secrets are derived from it.... so there is one such master secret per channel, times 3 channels => 3
the thing about "do the attackers see each other?" gets a little bit more tricky here, it depends on what they know about the PKI and the webserver: let's assume the attacker do not have any other secret information from the PKI, especially they do not have access to a valid and trusted CA secret key, and noone in the whole scenario does something like certificate pinning.
in sthis case the browser will notice that the connection has been tempered with and will show a warning (the client knows... that the connection is being tampered with, but does not know how many attackers there are)
the first attacker as seen from client side knows like the client, that the connection is being manipulated, since he knows that he is manipulating the connection he knows that at least one more party is involved on the upstream path to the server. (in out setup, this attacker is the only attacker knowing of 2 attacks)
the second attacker can not distinguish between the client and the first attacker... he sees the server traffic is unmodified and will most likely suspect that this is a single MITM scenario (does not see attacker 1)
the server does not see any of this...
let's change the things a bit: from now on the attackers have access to a trusted CA secret key
now both attackers can issue their own valid certificates
as long as noone is actually monitoring the certificates and looking for changes in the certificates being used, everything is as transparent as in the plain HTTP case ... the client will not notice anything ... both attackers will only know of their own manipulation
but ... since this looks like homework ... maybe i added a mistake here and there ... maybe not ... there is only one way to be sure: check it...


text:
Q: How to log to stdout from spark workers using python logging module? Can I use the python logging module to log to stdout on a master spark instance from functions that are executed in rdd.map and other functions that are distributed to worker nodes?
Specifically, I am using yarn in client mode and would like to be able to collect logs from all the workers. So if any worker runs a line such as
  logger.log("Starting to do something...")

It will be printed to stdout/other loggers on the master as if it was not executing on a node. It is acceptable to have the logs print at the end of the job when the execution is complete.

A: The first reply in this answers your question, it contains a coding example (code link).

A: A way to do so is to use the java virtual machine logger:
log4jLogger = spark._jvm.org.apache.log4j
LOGGER = log4jLogger.LogManager.getLogger(__name__)
LOGGER.info(" pyspark script logger initialized")