Find all the macro declarations as string using clang preprocessor?

Question: #include<stdio.h>

#define engine_exhaust_gas_temperature_raw 100
#define engine_exhaust_gas_temperature_scaled 20

#define Sum(x, y) ( ( x )+ ( y ) )

int main(){

    printf("%d",engine_exhaust_gas_temperature_raw);

    return 0;
}

I am working on MISRA C Rule 5.4 Macro identifiers shall be distinct for which I need the list of the names of all the macros defined in a C program as strings.

For ex: In the above code I will need:
[ "engine_exhaust_gas_temperature_raw", "engine_exhaust_gas_temperature_scaled", "Sum"]

Is there any way to get this list using clang AST?
I have found that we can use clangs https://clang.llvm.org/doxygen/classclang_1_1Preprocessor.html Preprocessor class to get the iterator to macros but even this is not producing any output for me. I have used it in the below code. What am I missing here?
bool distinct_macro_identifier(CompilerInstance *C_I, ASTContext *Context){

  auto st= C_I->getPreprocessor().macro_begin()->getFirst()->getName();

  auto x= C_I->getPreprocessor().macro_begin()->first;

  llvm::outs()<<x->getName()<<"\n";

  auto p= C_I->getPreprocessor().getMacroInfo(x);

  p->dump();

  return true;
}

Answer: You can compile it with this command:
clang++ -E -dM  -nostdlib file.cpp


Does resetting and rebuilding EVs at level 100 (in Super Training) affect stats?

Question: In previous generations, EVs only took effect upon level up, meaning that a level 100 Pokemon was stuck with the EVs you had previously trained it with.
With the edition of Super Training, and specifically, 'Reset Bags', you can re-spec your EVs at any time. But do these new EVs still only take effect upon level up?
Say I have a Gardevoir with mixed EVs on level 100, and I want to respec them into Special Attack & Speed for example, is this now possible? or will Resetting & Reapplying do nothing?
Answer: Starting from Gen V, EVs are taken into account after every battle even when the Pokemon is at L100. And from my own experience with Super Training, those EVs are taken into account as they are gained, no need for leveling or a battle, so your L100 Gardevoir can be retrained through Super Training easily.
Comment: I think they're also recalculated immediately if you feed a Pokémon berries or vitamins.


Homebrew: Ignoring bigdecimal-1.3.2 because its extensions are not built

Question: Always when I run brew update the Ignoring bigdecimal-1.3.2 because its extensions are not built.  Try: gem pristine bigdecimal --version 1.3.2 warning shows up:
> brew update
Ignoring bigdecimal-1.3.2 because its extensions are not built.  Try: gem pristine bigdecimal --version 1.3.2
Ignoring bigdecimal-1.3.2 because its extensions are not built.  Try: gem pristine bigdecimal --version 1.3.2
Already up-to-date.

I'm using Homebrew v1.7.7 (Homebrew/homebrew-core (git revision 77cae; last commit 2018-10-19), Homebrew/homebrew-cask (git revision c95843; last commit 2018-10-19)) and rbenv v1.1.1.
I already did gem pristine bigdecimal --version 1.3.2 and it says:
> gem pristine bigdecimal --version 1.3.2
ERROR:  While executing gem ... (Gem::Exception)
    Failed to find gems ["bigdecimal"] = 1.3.2

Even gem pristine --all doesn't fixed it.
The gem environment is showing me 2 gem paths. Is that fine?
> gem environment
RubyGems Environment:
  - RUBYGEMS VERSION: 2.6.11
  - RUBY VERSION: 2.4.1 (2017-03-22 patchlevel 111) [x86_64-darwin16]
  - INSTALLATION DIRECTORY: /Users/ricardo/.rbenv/versions/2.4.1/lib/ruby/gems/2.4.0
  - USER INSTALLATION DIRECTORY: /Users/ricardo/.gem/ruby/2.4.0
  - RUBY EXECUTABLE: /Users/ricardo/.rbenv/versions/2.4.1/bin/ruby
  - EXECUTABLE DIRECTORY: /Users/ricardo/.rbenv/versions/2.4.1/bin
  - SPEC CACHE DIRECTORY: /Users/ricardo/.gem/specs
  - SYSTEM CONFIGURATION DIRECTORY: /Users/ricardo/.rbenv/versions/2.4.1/etc
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86_64-darwin-16
  - GEM PATHS:
     - /Users/ricardo/.rbenv/versions/2.4.1/lib/ruby/gems/2.4.0
     - /Users/ricardo/.gem/ruby/2.4.0
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :backtrace => false
     - :bulk_threshold => 1000
     - "gem" => "--no-rdoc --no-ri --user-install"
  - REMOTE SOURCES:
     - https://rubygems.org/
  - SHELL PATH:
     - /Users/ricardo/.rbenv/versions/2.4.1/bin
     - /usr/local/Cellar/rbenv/1.1.1/libexec
     - /Users/ricardo/.gem/ruby/2.4.0/bin
     - /Users/ricardo/.rbenv/shims
     - /usr/local/bin
     - /usr/bin
     - /bin
     - /usr/sbin
     - /sbin

Comment: Have you tried to uninstall it first?
Comment: @Casper Yes, I tried to uninstall the gem. `gem uninstall bigdecimal --version 1.3.2`: "_ERROR:  While executing gem ... (Gem::InstallError) gem "bigdecimal" is not installed_"
Comment: What about using `gem uninstall bigdecimal --all --force`?
Comment: You can also try `locate bigdecimal-1.3.4` to see where it is installed. Then move the folder and/or gemspec somewhere else for backup, then reinstall.
Comment: I run the `gem uninstall bigdecimal --all --force` and it successfully uninstalled `bigdecimal-1.3.5` but the issue persists.
Comment: I search for "bigdecimal*" folders and it found some old folders in `/Users/ricardo/.gem/ruby/2.3.0/gems/bigdecimal-1.3.2/ext/bigdecimal` and
`/Users/ricardo/.gem/ruby/2.3.0/gems/bigdecimal-1.3.2/lib/bigdecimal`. I deleted them but the issue persists.
Comment: Btw. isn't `brew` a Ruby program. Is this program using the system Ruby, instead of your rbenv Ruby. Then this bigdecimal issue is with the system Ruby and not with the rbenv Ruby. `head -1 $(which brew)` shows you which Ruby executable `brew` is running.
Comment: @Casper Yes, I thought it was Ruby program but it seems not. `head -1 $(which brew)` shows `#!/bin/bash`.
Answer: Make sure you're using the right gem. The following fixed it for me:
$ which ruby
/usr/local/bin/ruby
$ /usr/bin/gem uninstall bigdecimal --all --force

(edit: fixed "remove" to "uninstall")
Comment: Not working for me. It says: "ERROR:  While executing gem ... (Gem::CommandLineError) Unknown command remove"


What FICS chess clients are available?

Question: I have pychess but it seems to load the CPU excessively, even without the background evaluation tab.
I used to use xboard but by now the UI feels somewhat outdated.
I'm looking for good FICS integration rather than engines or analysis tools.
Answer: A bit late, but you may want to try Raptor (from code.google.com or github.com*)
You won't have a ppa but they provide .deb installers for 32 and 64 bit Ubuntu systems. Has a very nice and customizable interface and is regularly updated (has its own autoupdater which you can turn off if you want, of course)
Another option would be Eboard.
Last but not least, you can try Jin but you will need to install Oracle Java to solve an annoying sound problem with openjdk.
* The project has been moved to GitHub after the Google Code shutdown announcements.
Answer: It is possible to play chess on FICS using SCID.  It can be installed in the usual way:
sudo apt-get install scid

Answer: I think the best software for FICS/ICC is eboard (in the repositories).
Comment: @DavidFoerster this looks like an answer (if a short one).
Answer: I like PyChess the best of all the alternatives that I've tried (and I think I've tried them all by now!)
To install: sudo apt-get install pychess
I have had problems with previous versions, but there has been a lot of work done on it lately and I no longer have any problems with it

What FICS chess clients are available?


concat and drop duplicates from two Dataset and write a new column

Question: I have 2 datasets:
df1:
Col1  : (xyz, abc)
Col2  : (123,456)
df2:
Col1  : (xyz, abc, def)
Col2  : (567, 456, 123)
I want to see the rows which has differences from both the dataframes and an additional column to see from which dataframe this record came:
Below is a link of what I want. Can someone help plz
New finding:
enter image description here
This new link shows for an additional column with null, the result is showing me only df1 for all the rows.
Answer: Yo ucan do like this
<code>new_df = df1.append(df2).drop_duplicates(keep=False)
a = new_df['Col1']+new_df['Col2'].astype(str)
b = df1['Col1']+df1['Col2'].astype(str)
new_df['from_df'] = np.where(a.isin(b), 'df1','df2')
new_df
</code>
output
<code>   Col1     Col2    from_df
0   xyz     123     df1
0   xyz     567     df2
2   def     123     df2
</code>
Comment: The answer worked but if any of these columns has a Null it does not work. The From_df is returned with df1 only. Do I need to do a fillna?
Comment: Question is not clear. Update your question to include this scenario also.
Comment: So say if there is one more Column in both the Dataframe - Col3 and this column has NULLs in both the datasets, my result gives an output :
Comment: Col1     Col2   Col3 from_df
0   xyz     123               df1
0   xyz     567               df1
2   def     123               df1
Comment: Still not clear for me. You can edit your original question at the top itself (formatting here in the comments is difficult)
Comment: please check the new link provided..It shows me DF1 for all the rows with your query
Comment: it is working correctly for me even with another column which has null values. added a picture also. check.
Comment: I am trying with 7 fields out of these 2 are null and it returns DF1 for all the records. Can you please try with 7 fields and 2 fields with NULL. Is it because of some indexing that it changes the result.


Passing a conditional statement when pushing viewControllers using storyboards

Question: Let's say that I have view controller Origin and Destination. I would like to declare something like:
//origin.m file

-(void)pushNextView {

    self.conditional = YES;
    [self performSegueWithIdentifier:@"toDestination" sender:self];

}

Where I have set my conditional as:
//origin .h file
@propery BOOL conditional;

Now in my Destination view controller I'd like to set a conditional based on the property that I've set in my origin:
// destination .m file
#import "OriginViewController.h"

OriginViewController *origin = [OriginViewController alloc] init];

if (origin.conditional == YES){

self.navigationItem.hidesbackbutton = YES;

}else{

// Do Nothing

}

for some reason this conditional statement does not work. Does this have to do anything with storyboards?
Comment: Like that it can't work. You alloc/init a NEW `OriginViewcontroller`. It's `.conditional` property will be `NO` at this point - always. You would have to check the reference to the original `OriginViewcontroller` (the sender). Or better yet, do it like described in one of the answers, by passing the value to the destination viewController in `prepareForSegue`
Answer: With the setup you seem to have it would be most easy to do this. You could directly access destination.hidesbackbutton when executing the segue:
//in origin.m
-(void) prepareForSegue.... {
   if ([segue.identifier isEqualToString: @"identifierString"]) {
       DestinationVC *destination = (DestinationVC*)[segue destinationViewController];
       destination.hidesbackbutton = self.conditional; //you can set the .hidesbackbutton property here directly, no need for another property, if your setup is just as simple as in the given example
    }
 }

Like this, the destination doesn't check the origin's state and then set it's state, instead the origin just sets the destination's state.
You can do it both ways, but this way is more common.
Of course hidesbackbutton has to be a public property declared in DestinationVC .h file.
And as already mentioned, it should really be hidesBackbutton Or hidesBackButton.
(This all assumes that the class of your DestinationViewController is called DestinationVC)
Comment: And `hidesBackButton` is a valid property of `navigationItem` (as long as it's spelled correctly of course). Maybe you want to edit that? (`destination.navigationItem.hidesBackButton = self.conditional`)
Comment: This is even better than my solution, as far as it is that simple. If the `conditional` state is more complex, I would handle any effects in the `viewDidLoad` (or `viewWillAppear`) of the destination VC.
Comment: Good catch. +1 Maybe he does mean navigationItem
Answer: Two things: hidesbackbutton looks like there's some camelCase missing. This should at least give a warning, doesn't it?
Also from an architectural point of view, I would not ask for the condition. Pass the state to the destination view controller and implement a BOOL variable there.
Draft:
// origin.m
- (void)prepareForSegue...
{
    if([segue.identifier isEqualToString:"yourIdentifier"]) {
        [(XYZViewController *)segue.destinationViewController setConditional:YES];
    }
}

Answer: you should pass the state from your main controller to destination controller where you should handle this View state like and you have to define
//destination.h file
@propery BOOL conditional;

so when you push the controller from main you can set the destination controller view state in
- (void)viewDidLoad
{
    [super viewDidLoad];

    if (origin.conditional == YES) {
        self.navigationItem.hidesBackButton = YES;
    } else {
    }
}

Comment: Now you have a `conditional` property in the destination view controller but still ask for the bool in the origin VC? Where does `origin` in the `viewDidLoad` come from? This does not make any sense.
Comment: Not in original controller its in destination so that it could be initialise and used in viewDidLoad


If $x,y,z$ are positive numbers, then prove that $\frac {x}{x+y} + \frac{y}{y+z} +\frac {z}{z+x} \le 2$

Question:
If $x$, $y$ and $z$ are positive numbers, then prove that $$\frac {x}{x+y} + \frac{y}{y+z} +\frac {z}{z+x} \le 2.$$

Though I have solved a lot of problems on AM-GM inequality, I am unable to solve this one. I am also not showing my working because I do not think that they will be of any help.
Comment: @MichaelRozenberg I see, sorry for my foolishness.
Comment: How is *this question* a duplicate of [*that question*](https://math.stackexchange.com/questions/980751/proof-of-nesbitts-inequality-fracabc-fracbca-fraccab-ge-fr)?
Comment: $2$ is sharp, but unattainable. Let $(x,y,z)=(1,t,t^2)$ and let $t\to0$.
Answer: $$\sum_{cyc}\frac{x}{x+y}\leq\sum_{cyc}\frac{x+z}{x+y+z}=2$$
Comment: How did you get $\frac {a}{b} \le \frac {a+c}{b+c}$?
Comment: @Amitayas Banerjee I used $x(x+y+z)<(x+z)(x+y)$.
Comment: Oh! I got it now. Thank you very much.
Comment: @Amitayas Banerjee You are welcome! I have found also a solution by C-S. I can post it if you wish.
Comment: Yes, please post that too
Answer: Solution by C-S.
We need to prove that:
$$\sum_{cyc}\left(\frac{x}{x+y}-1\right)\leq-1$$ or
$$\sum_{cyc}\frac{y}{x+y}\geq1,$$
which is true because by C-S
$$\sum_{cyc}\frac{y}{x+y}=\sum_{cyc}\frac{y^2}{xy+y^2}\geq\frac{(x+y+z)^2}{\sum\limits_{cyc}(xy+y^2)}\geq1.$$
But the previous idea is still better:
$$\sum_{cyc}\frac{y}{x+y}\geq\sum_{cyc}\frac{y}{x+y+z}=1.$$
Answer: Alternatively: let $a = x+y, b = y+z, c = z+x$, then $a,b,c$ are the lengths of the sides of a... triangle From this: $x = (x+y+z) - (y+z) = \dfrac{a+b+c}{2} - b = \dfrac{a+c-b}{2}, y = \dfrac{a+b+c}{2} - c = \dfrac{a+b-c}{2}, z = \dfrac{a+b+c}{2}-a = \dfrac{b+c-a}{2}\implies LHS = \dfrac{a+c-b}{2a}+\dfrac{a+b-c}{2b}+\dfrac{b+c-a}{2c}\le 2=RHS\iff \dfrac{c-b}{a}+\dfrac{a-c}{b}+\dfrac{b-a}{c}\le 1$. Assume $0 < a \le b\le c$, then observe: $\dfrac{b-a}{c} < \dfrac{c}{c} = 1$, and $\dfrac{c-b}{a}+\dfrac{a-c}{b} = \dfrac{bc-b^2+a^2-ac}{ab}= \dfrac{(b-a)(c-a-b)}{ab}\le 0$ since $a \le b, c < a+b$. Thus $\dfrac{c-b}{a}+\dfrac{a-c}{b}+\dfrac{b-a}{c} < 1$, and the inequality is proven...
Answer: If you want to do this more by hand write $$2=\frac {x+y}{x+y}+\frac {y+z}{y+z}$$ and the inequality becomes $$\frac z{x+z}\le\frac y{x+y}+\frac z{y+z}$$
If you now clear denominators (everything is positive) and expand the expression is homogeneous and not too difficult to work with. On the left you get $z(x+y)(y+z)=xyz+xz^2+y^2z+yz^2$ and it is easy to spot that these will appear on the right with other positive terms.


Credit calculator in Python - how to show result in GUI

Question: Im stuck with showing the results of "Amount of interest for repayment" and "Final Debt Amount" in GUI. "Show" button should draw the result on place marked on picture. Thanks in advance!

from tkinter import *

master = Tk()
master.title("Credit calculator")

Label(master, text="Principal:").grid(row=0)
Label(master, text="Interest rate p(%):").grid(row=1)
Label(master, text="Repayment period in years:").grid(row=2)

Label(master, text="Amount of interest for repayment:").grid(row=3)
Label(master, text="Final Debt Amount:").grid(row=4)

e1 = Entry(master)
C0=e1.grid(row=0, column=1)

e2 = Entry(master)
p=e2.grid(row=1, column=1)

e3 = Entry(master)
n=e3.grid(row=2, column=1)

#Amount of interest for repayment:
# K=(C0*p*n)/100

#Final Debt Amount:
# Cn=C0*(1+(p*n)/100)

Button(master, text='Quit', command=master.quit).grid(row=5, column=0, sticky=E, pady=4)
Button(master, text='Show', command=master.quit).grid(row=5, column=1, sticky=W, pady=4)

mainloop( )

Comment: Why not just show it as labels?
Comment: `Canvas` can be used for drawing.
Comment: To be more precise...i need to show the results of "K" and "Cn" by pressing the "Show" button. Result should be visible on place marked on picture.
Answer: Based on your code:
from tkinter import *

master = Tk()
master.title("Credit calculator")

Label(master, text="Principal:").grid(row=0)
Label(master, text="Interest rate p(%):").grid(row=1)
Label(master, text="Repayment period in years:").grid(row=2)

Label(master, text="Amount of interest for repayment:").grid(row=3)
Label(master, text="Final Debt Amount:").grid(row=4)

e1 = Entry(master)
e1.grid(row=0, column=1)

e2 = Entry(master)
e2.grid(row=1, column=1)

e3 = Entry(master)
e3.grid(row=2, column=1)

K = Entry(master, state=DISABLED)
K.grid(row=3, column=1)
Cn = Entry(master, state=DISABLED)
Cn.grid(row=4, column=1)

def calc(K, Cn):
    # get the user input as floats
    C0 = float(e1.get())
    p = float(e2.get())
    n = float(e3.get())
    # < put your input validation here >

    #Amount of interest for repayment:
    K.configure(state=NORMAL) # make the field editable
    K.delete(0, 'end') # remove old content
    K.insert(0, str((C0 * p * n) / 100)) # write new content
    K.configure(state=DISABLED) # make the field read only

    #Final Debt Amount:
    Cn.configure(state=NORMAL) # make the field editable
    Cn.delete(0, 'end') # remove old content
    Cn.insert(0, str(C0 * (1 + (p * n) / 100))) # write new content
    Cn.configure(state=DISABLED) # make the field read only

Button(master, text='Quit', command=master.quit).grid(row=5, column=0, sticky=E, pady=4)
Button(master, text='Show', command=lambda: calc(K, Cn)).grid(row=5, column=1, sticky=W, pady=4)

mainloop()

Tested on ubuntu 16.04 with Python 3.5.2 with results:

Keep in mind that I don't know a whole lot about economics so I don't know if my testing inputs are good. Still it shouldn't matter in this case.
Comment: Thanks! I will analyze this and maybe try to update with new features.


How to handle path and arguments in Angular Routing?

Question: I've got a SPA which requires some arguments passed to launch.
The clients launch the SPA using direct link like https://myapp.com/index.html?test=123&test2=12314 or https://myapp.com/?test=123&test2=12314
The SPA has an Angular Router setup with path /s/m/12345 which allows the client to open up a specific page.
I need to be able to create a direct link to the https://myapp.com/s/m?test=123&test2=12314 page, however, I don't know how to create a direct link.
https://myapp.com/s/m/?test=123&test2=12314
https://myapp.com/index.html/s/m?test=123&test2=12314
won't work.
How can I do this?
Answer: Have you look at ActivatedRouter with queryParams ? to get test and test2 as parameters..
    constructor(
    private readonly route: ActivatedRoute,
  ) {}

this.currentTest = JSON.parse(this.route.snapshot.paramMap.get('test'));
this.currentTest2 = JSON.parse(this.route.snapshot.paramMap.get('test2'));

Comment: but where is this constructor in?
Comment: in your component that youa re trying to display...


How to get total object value when we filter child object

Question: I am new for mulesfot and I want to filter below payload total object when characters[].data[] array "name": "priority" and "value": 1
Can some one help me please?.
json payload
--
<code>{
  "offers": [
    {
      "id": 100,
      "name": "Test1",
      "category": {
        "characters": [
          {
            "data": [
              {
                "name": "priority",
                "value": 1
              },
              {
                "type": "ILL",
                "result": "pass"
              }
            ]
          }
        ]
      }
    },
    {
      "id": 200,
      "name": "Test2",
      "category": {
        "characters": [
          {
            "data": [
              {
                "name": "priority",
                "value": 2
              },
              {
                "type": "ILL",
                "result": "Fail"
              }
            ]
          }
        ]
      }
    },
    {
      "id": 300,
      "name": "Test3",
      "category": {
        "characters": [
          {
            "data": [
              {
                "name": "priority",
                "value": 3
              },
              {
                "type": "ILL",
                "result": "Pass"
              }
            ]
          }
        ]
      }
    }
  ]
}
</code>
Expected result
--
<code>{
      "id": 100,
      "name": "Test1",
      "category": {
        "characters": [
          {
            "data": [
              {
                "name": "priority",
                "value": 1
              },
              {
                "type": "ILL",
                "result": "pass"
              }
            ]
          }
        ]
      }
    }
</code>
Below code i tried but not suitable to my requirement
--
<code>(payload.offers map {
    (($$): $) if((flatten($.category.characters.data) filter ((item, index) -> item.name=="WBB" and item.priority==1)))
}) - {}
</code>
Comment: Can there be multiple instances of name WBB and priority 1?
Comment: Does this answer your question? [How to apply filter for nested arrays in mulesoft dataWeave](https://stackoverflow.com/questions/73710764/how-to-apply-filter-for-nested-arrays-in-mulesoft-dataweave)
Answer: If multiple instances of name ="WBB" and priority = 1 doesn't exist , the following can get you to your goal
<code>%dw 2.0
output application/json

var interim = (payload.offers  map {
    (($$): "true") if((flatten($.category.characters.data).name contains "priority") and (flatten($.category.characters.data).value contains 1))
}) - {}
---
payload.offers[(1 - sizeOf(interim))]
</code>
if you happen to have multiple sections with name=priority and value 1 then you could use the below modified version (this will return an array of objects)
<code>%dw 2.0
output application/json

var interim = (payload.offers  map {
    (($$): "true") if((flatten($.category.characters.data).name contains "priority") and (flatten($.category.characters.data).value contains 1))
}) - {}
---
interim map {
       a: payload.offers[($$)]
}.a
</code>
Comment: Hi @Salim khan  i have edited my question , Can you please check once?
Comment: my json payload can contains multiple instances of  name= "priority" and value 1
Comment: I have updated my json payload as well as expected payload
Comment: you changed your ask quite a bit.
Comment: Your input contains only instance of name="priority" and value=1


How can i redirect port 80 to https in aws ALB

Question: I am using  Amazon ALB with TargetGroups
I have ALB Listener on HTTPS which goes to TargetGroup1.
TargetGroup1 goes to ECS Service
Now i want if someone come from port 80 then should get redirected to HTTPS listener on ALB. Is there any easy way for this?
Answer: Assuming your performing ssl termination on the ALB you need your ecs to conditionally redirect based on the value of the header x-forwarded-proto added by the ALB (its value is either http or https). This variable desribes the request sent to the ALB and allows you to act accordingly.
Answer: Since there's no answer and this is a relatively recent question, the answer is that this is now supported out of the box by ELB.  Add a listener on port 80 with an action of Redirect and HTTPS is now an option.
Comment: is it available on ALB or only ELB ?


Where is core animation defined?

Question: I can't figure out where core animation on iPhone OS 3.1.2 is defined.
Anybody know?
Answer: Actually, it is recommended that you use
<code>#import <QuartzCore/QuartzCore.h>
</code>
and then add the QuartzCore framework to your project to make use of low-level Core Animation classes.
Even though all it does is effectively import CoreAnimation.h on the iPhone, on the Mac QuartzCore also includes Core Image and Core Video, so Apple may add these and other capabilities to the QuartzCore framework on the iPhone in the future.  Frankly, Apple recommends using the above include for Core Animation, so I defer to them.
Answer: it is defined in QuartzCore/CoreAnimation.h

Where is core animation defined?


BackgroundWorker in MDI app

Question: I am trying to use the BackgroundWorker in my MDI application to handle the process of uploading a file to FTP server and displaying the progress on a progress bar.
When I tried to do it on a separate proof-of-concept application with a simple window and one button - it worked OK. But when I am trying to do it in my real app - the doWork sub does not run. Instead of it the app immediately runs the RunWorkerCompleted sub and shows me "Upload complete" without doing the actual job.
Is there something about MDI that prevents the BackgroundWorker to run the same way as with regular window app?
Thanks in advance for your help
Code:
<code> Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    bWorker.RunWorkerAsync()

End Sub

Private Sub bWorker_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bWorker.DoWork

    Dim source = Application.StartupPath + "\Db\test.mdb"
    Dim NameToUpload As String = Path.GetFileName(source)

    NameToUpload = NameToUpload.Replace(".", DateTime.Now.ToShortTimeString() + ".")

    Dim request As FtpWebRequest = DirectCast(WebRequest.Create(Host + "/" + txtLogin.Text + "/" + NameToUpload), FtpWebRequest)
    request.Method = WebRequestMethods.Ftp.UploadFile
    request.Credentials = New NetworkCredential(txtLogin.Text, txtPassword.Text)
    Dim FileStream() As Byte = File.ReadAllBytes(source)
    Dim requestStream As System.IO.Stream = request.GetRequestStream()

    For offset As Integer = 0 To FileStream.Length Step 1024
        bWorker.ReportProgress(CType(offset * ProgressBar1.Maximum / FileStream.Length, Integer))
        Dim chSize As Integer = FileStream.Length - offset
        If chSize > 1024 Then chSize = 1024
        requestStream.Write(FileStream, offset, chSize)
    Next
    requestStream.Close()
    requestStream.Dispose()
End Sub

Private Sub bWorker_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs)
    ProgressBar1.Value = e.ProgressPercentage

End Sub

Private Sub bWorker_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs)
    MsgBox("Upload complete")
End Sub
</code>
Comment: So if you set a breakpoint on the `bWorker_DoWork` event it doesn't get hit? On another note you shouldn't be trying to access the UI thread from the background worker, pass these values into the do work event. It may not be a problem because your not updating the UI...but it's still good practice as the background worker is a different thread than the UI.
Answer: You need to check e.Error in the RunWorkerCompleted event as it's most likely having an exception. As @Zaggler mentions you're accessing UI controls on the background thread which will cause this.

BackgroundWorker in MDI app


UIButton highlighted background image is not showing

Question: I have to create a layout programmatically with several buttons, I create my buttons using the following code:
let myButton = UIButton(type: .Custom)
myButton.frame = CGRectMake(100,100,100,100)
myButton.setTitle("Normal", forState: .Normal)
myButton.setTitle("Selected", forState: [.Selected,.Highlighted])
myButton.setBackgroundImage(UIImage(named: "normal.png"), forState: .Normal)
myButton.setBackgroundImage(UIImage(named: "selected.png"), forState: [.Selected,.Highlighted])
self.view.addSubview(myButton)

The title and image are not changing once pressed.
The same code works if I refer to a UIButton created in the Storyboard.
Is there any other property that I need to set?
Thank you
Comment: Is the button reacting when you tap on it (turns grey)?
Comment: Yes. I can see the change of status
Comment: have you tried to remove .Selected and just using .Highlighted ?
Comment: try to use or | like .Highlighted | .Selected
Answer: Try splitting the combined setBackgroundImage call into two:
myButton.setBackgroundImage(UIImage(named: "selected.png"), forState: [.Highlighted])
myButton.setBackgroundImage(UIImage(named: "selected.png"), forState: [.Selected])

Comment: That works, but I can't realize why the same syntax works with UIButtons created in the Storyboard
Comment: @Ivan what do you mean the same syntax works on storyboard ? I thought storyboard splits up the diffrent states (highlighted and selected).


What is the first 21-digit prime number after the decimal point of Pi

Question: We know the recent computers are 64-bit, and the maximum integer number is 18446744073709551615, whether you can find the first 21-digit prime number after the decimal point of $\pi$?
Please show me.
Comment: There are many ways to represent numbers in computers.  You are right you can't put a 21 decimal digit number into a 64 bit register, but Alpha, Maple, Python, and many others have the ability to handle larger integers.
Comment: You mean if we can find the first 21-digit prime in the decimal representation of $\pi$? What is that supposed to have to do with 64bit computers?
Comment: Notice that the number size is out of the range of the maximum computer integer number.
Answer: You can certainly start taking the batches of $21$ decimals and check them for primality.  You start with $141592653589793238462$ which is clearly not prime as it is even.  The first odd batch is $592653589793238462643=7^2×11×17203×624683×102317113$.  One would expect about one in $45$ numbers of this size to be prime, so you shouldn't have to look far.  You can check your favorite with Alpha
The first one I find is $338327950288419716939$, checked with Alpha.  Alpha is able to fully factor numbers of this size quickly.
Answer: What you are looking for is sometimes called an infinite precision math library that allows you to extend the size of your numbers beyond the maximum representable by the word size of your CPU.
Sometimes this is called an arbitrary precision library.
Languages like Java, and say Python provide such capabilities. Computer Algebra Systems like Mathematica (as does WolframAlpha), Maple, Maxima and Gp/PARI have this capability built in.
This and the answer by Ross should get you moving forward.
You also need to decide on a primality test to use against your numbers and that should be something like Miller-Rabin followed by Lucas or other choices too depending on your needs.
Regards.
Comment: Just wanted to reinforce this by pointing out that $2^{2281}-1$, a 687-digit prime, was already found 60 years ago by a computer having less than 10 kilobits of RAM (in the form of vacuum tubes).  Today, there's probably more computing power inside a $5 pedometer, let alone a 64-bit computer.
Comment: Apparently the specific announcement was published by Lehmer as an followup note in _Mathematics of Computation_ ([AMS link](http://www.ams.org/journals/mcom/1953-07-041/S0025-5718-53-99371-5/S0025-5718-53-99371-5.pdf)).  For the capacity of the computer (named SWAC) I just looked up Wikipedia.
Comment: @ErickWong: Eric, thanks for the tidbit, I actually wasn't aware that they had done such a large prime at that time. Do you have a reference for this? I recall the good old days when we had to be so careful with using the very limited resources we had and were forced to do efficient things. Regards
Comment: Nice, Amzoti! +1


What are the optional objectives in Street Sweep missions for?

Question: When you start a Street Sweep mission, an optional objective, like "don't use weapons", is displayed, but after this point the game never seems to bring it up again. What does completing these objectives do?
Answer: If you open the map it shows the objective, if you fail the objective it will display that you've failed.
Once you finish the mission, it will tell you whether you completed the optional objective:

For regular missions it will give you an additional street tag. (One tag for completing the mission, another for the objective)
For the 4 hour challenge missions it gives you additional 20000 points.
Answer: I found a video of someone completing one of these missions and getting the optional objective of not using any weapons.
When the leaderboard shows up, he gets additional points for completing the optional objective. So at least for this specific mission, it's a point bonus.
Comment: [I found another video from the same user](https://www.youtube.com/watch?v=Vq3KD53vf3M), which covers the "no killing," "remain undetected," and the "under five minutes" challenges, and it looks like completing the optional objectives doesn't really do anything besides add more difficulty and complexity. The previous video I found with the "no weapons" objective seems to have a score tied to it, but I didn't see anything in this video that implies that there is a score tied to the other objectives. I don't personally have the DLC, so I can't do more research. Sorry about that!


Rails 3 ignore Postgres unique constraint exception

Question: What's the correct way to rescue an exception and simply continue processing?  I have an app that has Folders and Items, with a habtm relationship through a join table called folders_items.  That table has a unique constraint ensuring that there are no duplicate item/folder combinations.  If the user tries to add an item to the same folder several times, I obviously don't want the additional rows added; but I don't want to stop processing, either.
Postgres automatically throws an exception when the unique constraint is violated, so I tried to ignore it in the controller as follows:
rescue PG::Error, :with => :do_nothing

def do_nothing

end

This works fine on single insertions. The controller executes the render with a status code of 200.  However, I have another method that does bulk inserts in a loop.  In that method, the controller exits the loop when it encounters the first duplicate row, which is not what I want.  At first, I thought that the loop must be getting wrapped in a transaction that's getting rolled back, but it isn't -- all the rows prior to the duplicate get inserted.  I want it to simply ignore the constraint exception and move to the next item.  How do I prevent the PG::Error exception from interrupting this?
Answer: In general, your exception handling should be at the closest point to the error that you can do something sensible with the exception. In your case, you'd want your rescue inside your loop, for example:
stuff.each do |h|
  begin
    Model.create(h)
  rescue ActiveRecord::RecordNotUnique => e
    next if(e.message =~ /unique.*constraint.*INDEX_NAME_GOES_HERE/)
    raise
  end
end

A couple points of interest:

A constraint violation inside the database will give you an ActiveRecord::RecordNotUnique error rather than the underlying PG::Error. AFAIK, you'd get a PG::Error if you were talking directly to the database rather than going through ActiveRecord.
Replace INDEX_NAME_GOES_HERE with the real name of the unique index.
You only want to ignore the specific constraint violation the you're expecting, hence the next if(...) bit followed by the argumentless raise (i.e. re-raise the exception if it isn't what you're expecting to see).
Comment: Thanks, mu.  It looks like that worked. I had tried embedding 'next' in the do_nothing method referred to be rescue_with, but that gave me an error.  In any event, it's definitely a PG::Error, and I'm not talking directly to the db.  It's just a plain old habtm join table with no custom SQL insert.  Perhaps ActiveRecord::RecordNotUnique only gets called on model tables?
Comment: I spoke too soon.  Tested it again and it's definitely still terminating the loop on the first duplicate it encounters.  The interesting this is that if I insert the begin/rescue block in the controller method and remove the rescue_with from the controller, then the exception is not caught at all.  So, for some reason, this is apparently not caught at the controller method level at all.
Comment: You don't want to catch it at the controller level, that's too far from where you can do something about the exception. What does your code look like?
Comment: OK, finally got it working.  Changed the PG::Error to ActiveRecord::RecordNotUnique (as you originally suggested) and that fixed it.  It's strange, though.  The console log only makes reference to the PG::Error.  No mention of the ActiveRecord exception.
Answer: If you put a Rails validator on your model, then you can control your flow without throwing an exception.
class FolderItems
  belongs_to :item
  belongs_to :folder
  validates_uniqueness_of :item, scope: [:folder], on: :create
end

Then you can use
FolderItem.create(folder: folder, item: item)

It will return true if the association was created, false if there was an error.  It will not throw an exception.  Using FolderItem.create! would throw an exception if the association is not created.
The reason you are seeing PG errors is because Rails itself thinks that the model is valid on save, because the model class does not have a uniqueness constraint in Rails.  Of course, you have a unique constraint in the DB, which surprises Rails and causes it to blow up at the last minute.
If performance is critical then perhaps ignore this advice. Having a uniqueness constraint on a Rails model causes it to perform a SELECT before every INSERT in order for it to do uniqueness validation at the Rails level, potentially doubling the number of queries your loop is performing.  Just catching the errors at the database level like you are doing might be a reasonable trade of elegance for performance.
(edit) TL;DR: Always have the unique constraint in the DB. Also having a model constraint will allow ActiveRecord/ActiveModel validation before the DB throws an error.
Comment: A Rails uniqueness validation should **always** be backed by a uniqueness constraint inside the database. All the ActiveRecord validations are subject to race conditions so the logic has to be in the database and you have to deal with exceptions if you don't want broken data.
Comment: You are absolutely correct, I didn't mean to imply otherwise. When talking of model validation, I definitely mean it as in addition to the unique constraint in the database. You need the constraint in the database for integrity, and the constraint in Rails for ActiveRecord/ActiveModel validation.


Unbound descriptor tables and descriptors for fat root signatures

Question: Unbound descriptor tables
If a D3D12_VERSIONED_ROOT_SIGNATURE_DESC defines N D3D12_ROOT_PARAMETERs (with ParameterType set to D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) that are each visible to a single (non-compute) shader stage, does each of these require a corresponding ID3D12GraphicsCommandList::SetGraphicsRootDescriptorTable invocation (with an allocated shader visible descriptor range) after binding the ID3D12RootSignature and ID3D12PipelineState, even if the latter does only use a subset of the (non-compute) shader stages (e.g., no geometry shader, etc.)? Stated differently, does ID3D12GraphicsCommandList::SetGraphicsRootDescriptorTable need to be invoked for root parameters associated with shader stages that are not defined for the ID3D12PipelineState but are part of the ID3D12RootSignature?
Unbound descriptors
If a shader uses say 2 SRVs, but up to 64 SRVs could be potentially bound for the ID3D12RootSignature, is it necessary that the 62 unused SRVs, which are part of the same shader visible descriptor range(s), are actually associated with an existing SRV of a resource that is still alive (which is not automatically guaranteed if the shader visible descriptor heaps are used in a ring buffer fashion, as initially the descriptors are unused and later on could be reused)? Or does one for example need to use an SRV of a dummy resource that is kept alive?
Answer: Everything is allowed to be left unbound / invalid / uninitialized as long as the shader doesn't try to look at it. However, if the shader does try to look at it, it could trigger a GPU crash / TDR.
In practice, it may be a good idea to explicitly clear out descriptors that you know aren't going to be valid: either setting them to a null descriptor, or pointing to a dummy resource. Loading/sampling from a null SRV/UAV descriptor in a descriptor table is defined to just return 0 and not crash. Likewise, stores to a null UAV descriptor are dropped on the floor without crashing.
However, this guarantee doesn't apply to descriptors directly in the root signature; trying to load/sample from a null root descriptor can crash the GPU. Likewise trying to read from a null descriptor table can crash. See the D3D12 functional spec for more.
Comment: No, I meant that in addition to null root descriptors (root SRVs etc), also another thing that causes crashes is null/unbound descriptor tables.
Comment: Shouldn't the second to last line read: _Likewise trying to read from a null **root descriptor** can crash._, because if I understand correctly _descriptors directly in the root signature_ refers to `D3D12_ROOT_DESCRIPTOR` (as opposed to `D3D12_ROOT_DESCRIPTOR_TABLE`)?
Comment: Wasn't that already assumed by the first paragraph: if the shader looks at a CBV/SRV/UAV the associated root descriptor or root descriptor table needs to be bound, and only in case of the latter it may point to a null descriptor with a matching format (_and the other contiguous descriptors in that same table can be unbound / invalid / uninitialized if not being looked at in the shader_). I was a bit confused with a _null descriptor table_ as `SetGraphicsRootDescriptorTable` expects the base offset descriptor.
Comment: AFAIK nothing prevents you from setting a null descriptor to SetGraphicsRootDescriptorTable as well. I'm just pointing out that if a shader attempts to retrieve a descriptor out of a null descriptor table then bad things may happen, there isn't a guranteed fallback for that case in the way that there is for e.g. loading from a buffer described by a non-root null descriptor. Also note the difference between a _null_ descriptor and one that's _invalid_ (but non-null) by virtue of pointing to an invalid memory address / a resource that's been deleted or unmapped, etc.


Jquery Autocomplete w/ Categories search, limited to Category chosen by user

Question: The jquery Autocomplete demo page with category shows the following :

I want the user to choose the category (Products or People) in a separate button (dropdown list), and then the jquery search to return only the matches in the category chosen by user.
Expected result :
screenshot 2
I am new to jquery, but according to my research I think this could be possible using "functions" as inputs, as said in the answer here (even though the question was different) :
Jquery UI Autocomplete: search from multiple attributes of one array
However I don't know what to do next.
My current code is the code from official doc :
<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Autocomplete - Categories</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">

Search:
<input id="search">

Comment: This seems like overkill. I would just set your source to a unique category of data when the select is changed. Will prepare an example answer.
Answer: Using the example data, there was a bit more work to be done to setup the data to work better for this. If you have control over the data format, you can prepare it before hand to work better.
Working example: https://jsfiddle.net/Twisty/uy5f2fta/
HTML
Search:
<select id="categories">
  <option value="none"></option>
</select>
<input id="search">

jQuery
var data = [{
  label: "anders",
  category: ""
}, {
  label: "andreas",
  category: ""
}, {
  label: "antal",
  category: ""
}, {
  label: "annhhx10",
  category: "Products"
}, {
  label: "annk K12",
  category: "Products"
}, {
  label: "annttop C13",
  category: "Products"
}, {
  label: "anders andersson",
  category: "People"
}, {
  label: "andreas andersson",
  category: "People"
}, {
  label: "andreas johnson",
  category: "People"
}];

$(function() {
  // Set Variables
  var cats = [],
    labels = {},
    sel = $("#categories"),
    search = $("#search");

  // Sift out specific Categories
  $.each(data, function(k, v) {
    if (v.category !== "") {
      cats.push(v.category);
      console.log("Found Cat: " + v.category);
    }
  });
  $.unique(cats);
  console.log("All Cats: ", cats);

  // Set Categories into Select element
  $.each(cats, function(k, v) {
    sel.append("<option value='" + v + "'>" + v + "</option>");
  });

  // Create Object of various data
  labels.none = [];
  $.each(cats, function(k, v) {
    labels[v] = [];
  });
  for (var i = 0; i < data.length; i++) {
    $.each(cats, function(k, v) {
      if (data[i].category == "") {
        labels.none.push(data[i].label);
      }
      if (data[i].category == v) {
        labels[v].push(data[i].label);
      }
    });
  }
  $.each(labels, function(k, v) {
    $.unique(labels[k]);
  });
  console.log("All Labels: ", labels);

  // Set Autocomplete with variable data based on category selection
  search.autocomplete({
    delay: 0,
    source: function(req, res) {
      var cat = sel.val();
      var data = labels[cat];
      var results = [];
      $.each(data, function(k, v) {
        if (v.indexOf(req.term) == 0) {
          results.push(v);
        }
      });
      res(results);
    }
  });
});

I first sifted out the categories that we knew would be in the data. This was then used to populate the Select element with a special "none" option. You could go back and adjust the none data to include all labels.
Next we parse all the labels and sort them into an object that has child arrays with the name of each category as the index. We will populate each array with the data for that category.
Finally, we use a function for the source so that we can pick which data set we want to read from. req.term is the data that was entered in the field, and we need to return an array of the matching data. The use of indexOf() is helpful here. This will return 0 when the term is at the beginning of the string. We then pass the resulting array to our res callback function.
So using your example, if category is "none" and we type "an", we get a resulting 'anders', 'andreas', and 'antal'. If we then type "and", the results drop to 'ansders' and 'andreas' as expected.
Comment: Here is an example with `none` populate with all labels: https://jsfiddle.net/Twisty/uy5f2fta/2/


Using PropTypes when immutable-js in react-js

Question: I am using immutable-js and react-immutable-proptypes in React.
// CommentBox.jsx
getInitialState() {
    return {
        comments: Immutable.List.of(
            {author: 'Pete Hunt', text: 'Hey there!'},
            {author: 'Justin Gordon', text: 'Aloha from @railsonmaui'}
        )
    };
},
render(){
    console.log(this.state.comments.constructor);
    return (

Comments

        <CommentForm url={this.props.url} />
        <CommentList comments={this.state.comments} />

    );
}

// CommentList.jsx
propTypes: {
    comments: React.PropTypes.instanceOf(Immutable.List),
},

// CommentStore.js
handleAddComment(comment) {
    this.comments.push(comment);
}

When the page initialization, it's no problem,all is ok,no warning.
The console log shows the comments is function List(value).
When I add a new comment, it looks work well,but there is a warning

Warning: Failed propType: Invalid prop comments supplied to
  CommentList, expected instance of List. Check the render method of
  CommentBox.

and the console log shows that the comments is function Array().
So, why does the comments constructor change from List to Array?
And and I have read http://facebook.github.io/react/docs/advanced-performance.html#immutable-js-and-flux.

The messages store could keep track of the users and messages using
  two lists:
this.users = Immutable.List();
this.messages = Immutable.List();

It should be pretty straightforward to implement functions to process
  each payload type. For instance, when the store sees a payload
  representing a new message, we can just create a new record and append
  it to the messages list:
this.messages = this.messages.push(new Message({
  timestamp: payload.timestamp,
  sender: payload.sender,
  text: payload.text
});

Note that since the data structures are immutable, we need to assign
  the result of the push function to this.messages.
Comment: `this.comments.push(comment)` expression returns a new list but does not modify the list in place (by definition, since it's immutable)
Comment: I learned this way from http://facebook.github.io/react/docs/advanced-performance.html#immutable-js-and-flux.
Comment: In that very article they assign the result of the call to the property itself.
Comment: "Note that since the data structures are immutable, we need to assign the result of the push function to this.messages." Please go through that article one more time.
Comment: Thank you.I think I misunderstood the immutable.
Comment: I found the problem.Using `push` for immutable record is no problem, it always return a new immutable record.Before the constructor of CommentStore.`constructor(){this.comments = []}`.
Comment: It always indeed returns a new immutable, but you don't assign it to anywhere.
Comment: No.So the `comments constructor` was `function Array()`.I have changed the CommentStore to `constructor(){ this.comments = Immutable.List(); }`.There is no warning now.
Comment: @Brad did you really add the solution to the question?
Answer: I came here looking to find a solution that would allow either an array or any sort of iterable object from ImmutableJS to be passed as the prop. In case anyone else finds this useful, here's what I came up with:
PropTypes.oneOfType([
  PropTypes.instanceOf(Array),
  PropTypes.instanceOf(Immutable.Iterable)
]).isRequired

Answer: You can specify a custom validator.

propName: function(props, propName, componentName) {
  if (!List.isList(props[propName]) && !Array.isArray(props[propName])) {
    return new Error(
      'Invalid prop `' + propName + '` supplied to' +
      ' `' + componentName + '`. Validation failed.'
    );
  }
}


How to make a full backup of ubuntu 16.04?

Question: I ve spent some time to install Ubuntu 16.04 in my Laptop and replace Win10 (single boot).
However, I had to install within Ubuntu VMWare with Win10 (as Virtual Machine), because too many files strongly linked to Office Excel.
Everything is running well and now I want to make a full backup of my Laptop (am normally using Macrium with Windows, but not available for Linux).
What is available for Ubuntu and working well (probably many)?
What is the best?
Thanks for your advice.
Serros
Comment: Possible duplicate of [How to make a disk image and restore from it later?](https://askubuntu.com/questions/19901/how-to-make-a-disk-image-and-restore-from-it-later)
Comment: There is a built-in Backup application
Comment: ok, what is the name and running well?
Comment: I believe it's simply called *Backup*. You can search for it using the Dash.
Comment: In terminal I typed :
sudo apt install openafs-client
A backup is now installing
Comment: not very sure it will do what I need!
I actually need to make a bootable backup which can be restored, not only backup for files.
more advice from someone? ;-)
Comment: How big is your Ubuntu partition? Is your home directory in a separate partition? Anyway you can use a live Ubuntu USB to create partition image using Disks application.
Comment: Actually am using fully the 220GB of HD SSD for Ubuntu (encrypted from the beginning in the installation process)
Comment: See [How to make a disk image and restore from it later](http://askubuntu.com/a/589060/255257)
Answer: If you have a spare drive you can always use clonezilla to clone the hard drive. It will backup everything and allow for a redeployment.
http://clonezilla.org/
Comment: It works well. I like the fact that it's a bit by bit. It copies everything, including the OS. We used it to deploy windows computers and I have used it to redeploy my Ubuntu box a few times. I personally reclone my PC every 2 months.
Comment: Clonezilla itself is a bootable disk that create an image of a target computer. All settings and such gets copied. This includes the VM machine. You store the image elsewhere.
Comment: ok thanks
Working well, I already tried it?
Actually some limitations:
Recovery Clonezilla live with multiple CDs or DVDs is not implemented yet. Now all the files have to be in one CD or DVD if you choose to create the recovery iso file.
Since my backup is about 200GB, stored in external Drive, I do need to have a boot disk first and restore after booting (like Macrium does).
Comment: ok, but you does it work?
can you make a boot DVD?
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/609680)
Comment: @andrea lazzarotto I am seeing I also need to include most of the steps as well. I will remember this for next time.
Comment: The BIG problem with Clonezilla clone, is that it WILL NOT clone, or RESTORE, to a smaller drive... even if there's only 1 block difference!
Comment: @David not next time, this time. :) Please [edit] the answer and include the relevant information, otherwise it risks getting deleted.
Comment: @heynnema of course, Clonezilla does not resize partitions. But why would you want to restore on a smaller drive? If you need that, you just have to reduce the partition before cloning.
Comment: @AndreaLazzarotto example: you have two 1TB hard drives. You Clonezilla **clone** them for backup. It works fine. Then your primary hard disk's software gets corrupted for some reason, and you think, that's OK, I've got a bootable clone that I can restore from. Wrong. Turns out the backup drive was 1 block larger than the primary drive, so cloning worked fine. But if you boot the backup drive, and try to clone/restore back to the original drive, it won't work, because the destination drive is smaller than the source drive.
Comment: @AndreaLazzarotto another example: you have two 1TB drives. They differ in size by 1 block. You adjust the partitions on the primary drive so that 10G unallocated space is at the end of the drive. That will easily fit on either drive. You clone the primary drive. You'll still end up with the same problem as above, because Clonezilla **ONLY** compares the last available block numbers to determine that one drive is still smaller than the other, and clone/restores will still fail.
Comment: @heynnema do you have first person experience in this 1-block difference problem? It seems quite weird to me. In the past I have cloned drives with Clonezilla and I remember reducing the size of a partition to clone to a smaller drive. It worked.
Comment: @AndreaLazzarotto yes, personal experience. You can check at clonezilla.org and review the FAQ's and the forum for other's experience on the same. The reason your experience worked is because you were probably working at the partition level. It would have failed if you tried to clone the drive, even though the data/partition would have fit on the destination drive. It's the reason that I stopped using Clonezilla and went looking for different backup softare... and I settled on Macrium Reflect. Cheers, Al
Answer: Macrium Reflect running under Windows will backup Ubuntu partitions. Might as well use what you already have installed.
Comment: Interesting, but how do I run Reflect to launch the backup?
Also from CV ROM?
Comment: You boot into Windows and start Reflect like you normally do. Or, you can boot to a Reflect CD that you've built using the Reflect application. Cheers, Al


Update Uniform.js input not working

Question: I'm using Uniform.js on all selects, input:checkbox, input:text elements.
The problem I'm running into is that the actual values of the elements that are using Uniform are not updating.  I have a form containing these various elements, I change their values, and then call $.uniform.update() before the form is submitted (I've also tried updating individual elements), but the element value is not actually changed.
For example, if I have a select w/ the options Yes and No, if I select Yes the only thing that is changed is the span that is generated by Uniform.  So when I the form is submitted I get no value.
(using jquery 1.6.1)
Answer: for load() if fix promblem this way:
$('#dialog').load(url + ' #forload',
    function() {
        $('#dialog').find('select').uniform(), $('#dialog').find('input:checkbox').uniform()
    })

Update Uniform.js input not working


How to add Time series queries with grafana and MySQL?

Question: I'm new to grafana and playing around to see if it could fit my needs for a research lab.
I'm using grafana-server Version 4.5.2 (commit: ec2b0fe)
I tried to follow the grafana documentation about mysql datasources (sorry I'm not allowed to post more than two links, just try to search in your favorite search engine...)
I have succefully added a MySQL data source.
Here is my database :
mysql> DESC meteo;
+-------------+----------+------+-----+---------+----------------+
| Field       | Type     | Null | Key | Default | Extra          |
+-------------+----------+------+-----+---------+----------------+
| id          | int(100) | NO   | PRI | NULL    | auto_increment |
| date_insert | datetime | NO   |     | NULL    |                |
| temperature | float    | NO   |     | NULL    |                |
+-------------+----------+------+-----+---------+----------------+

Following the documentation I've added a panel "Table" with the following query...
SELECT
  date_insert as 'Date',
  temperature as 'Temperature'
 FROM meteo

...and choosen "Format as Table"
The result is ok as you can see.
Grafana Panel Format Table
Now I would like to have a graph like this :
Grafana Panel Format Time series
How can I achieve this with my database ? I don't understand the doc which says :

If you set Format as to Time series, for use in Graph panel for example,
then there are some requirements for what your query returns.
Must be a column named time_sec representing a unix epoch in seconds.
Must be a column named value representing the time series value.
Must be a column named metric representing the time series name.

How can I apply this with my database ? Is it just possible ?
Answer: Here is the solution, thanks to the Grafana team !
daniellee's answer
Comment: Answers should include more than a naked link


How to use the Playstation shop when it's not available in your region?

Question: While I am a proud PS3 owner, I live in a country where the PSN isn't really available and as a direct result have absolutely no access to the Playstation Shop, unless I create a fake account which "lives" in some other country which does have access to the shop. Of course, from what I understand, that won't get me far since my credit card won't match my declared location.
I know there are ways around it and to my best of knowledge this circumvention of the system does not constitute as anything illegal, correct me if I'm wrong (after all, I'm just trying really hard to give them money in exchange for services).
I am aware there are guides for this, but plenty are outdated and some not so trustworthy.
I'd much rather rely on the experience of the fine people of this site (or on their recommendations of a specific guide).
Also, there are some specific issues which concern me more than others:

Where is a recommended place to buy PSN prepaid cards online. Why is said place recommended?
Are there any considerations regarding multiplayer/region/whatever when buying PSN games in this "illegitimate" manner?
Will the games I buy with my fake account behave nicely on my actual account?
What if at some point in the future the Playstation store becomes available over here? Will it affect me in some adverse manner?
Answer:
Where is a recommended place to buy
PSN prepaid cards online. Why is said
place recommended?

I use http://maximuscards.com/ to buy US PSN cards, instant delivery by e-mail.

Are there any
considerations regarding
multiplayer/region/whatever when
buying PSN games in this
"illegitimate" manner?

All the multiplayer games works on all regions (at least all that I played so far), but...
Be carefull about DLCs.
The only consideration (and the only problem I had so far) is with DLCs from different regions.
I have games from various regions (US, EU, Asia) and in some of them, like for example, Little Big Planet, Killzone 2, Rock Band, etc the DLCs for one region doesn't work on the other.
I bought a EU LBP and then bought the Metal Gear Solid pack in the US store. It didn't work, the game couldn't find the DLCs
So be carefull about buying DLCs from other regions, most will work, but some will not and you will lose your money, that's the only problem about this kind of deal.

Will the games
I buy with my fake account behave
nicely on my actual account?

Yes, the game will work just fine on other accounts on the same PS3, but if you delete the account the owns the game all the games will become unacessible, so you MUST keep you "fake" account in order to play the games.

What if
at some point in the future the
Playstation store becomes available
over here? Will it affect me in some
adverse manner?

That I can't answer because PSN isn't available here yet (Brazil), common sense tells that it will not affect you (if you already have an account in your country), but anyway I doubt that IF the Playstation Store is available here in some far far away future it will have the same content as the US or EU Store, so basically everybody will have 2 accounts or just stick with the old account.
Answer: You can buy PSN prepaid cards on Amazon. It's a little cheaper than the original price tag.
Comment: Not anymore....
Comment: I bought one three days ago.
Comment: > PSN has been [very recently] taken down indefinitely.  You're not in North America, but I **thought** the entire network had been taken down.  Can you still access it?
Comment: @GnomeSlice yes, I know because of the crack incident. But they will open up again and hopefully it will work.
Comment: Can you still buy them there? I can't find any.


Black stains on oak after rain

Question: I have made a DIY mailbox from oak wood boards a year ago.
But recently after heavy rains the oak turned black at the grains, looking like this:

I did cover the oak with couple of coats of stain and a couple of coats of spar urethane to protect it.
However somehow that did not work.
Here's some close ups on what happened to the wood:

Questions:

Any ideas on what exactly happened? My understanding was that oak by itself is resistant of the moisture, and with additional staining and spar urethane I was expecting it to last long.
Is there any restoration that can be done here?

One suspicion that I have is that the metal sign (755 lakemead) has added to this - last year it wasn't there yet and mailbox survived the rain season without issues; this year with the sign on - this happened. I read somewhere that stainless steal on oak can react when moisture added. Curious if anyone can confirm that is this problem based on pictures.
Comment: That's what oak does when it gets wet. Unless you  manage to perfectly seal every  edge and penetration (and maintain that seal over time) it's inevitable. It's why oak isn't commonly used for outdoor things.
Comment: When water penetrates oak it reacts with the high tannin content within oak, resulting in 'blackening'.  https://www.wood-finishes-direct.com/blog/what-everyone-should-know-about-finishing-oak/
Answer: I don't know the science behind this (chemists, please chip in!) but I would agree with the point about the presence of metal (particularly iron?).
For a few years now I've been making stuff out of some old oak fence posts that a friend of mine was throwing out.  Anywhere that metal fixings were in the wood was stained black.
The fact that the worst stained boards are directly below the sign would, imho, lend weight to that.

Black stains on oak after rain


Cart organization - should I combine delivery and collection together or keep them separate?

Question: I'm currently working on creating UX for online food ordering service and I'm stuck at one point.
The service provides 2 kinds of order processing: the user can order food for delivery or for pickup (this depends on restaurants abilities).
The question is how to combine these two flows (delivery and pickup) or it would be better not to mix them at all and consider the processing type 'order-wide'?
The processing type is set on checkout page, and if there are some items, that are not available for the selected processing type, they will be either dropped from the order (with notification) of moved to the separate (new) order, which can be placed after the current one is finished.
Update:
Here is what I came up with:

So this is the case, the user adds two items with different fulfillment options selected.
What do You think? Is clear enough?
Answer: You may want to look at this site again and perhaps make a minor change that could make all the difference. Instead of prompting them during the checkout for whether or not the want delivery or pick-up ask them at the beginning of the ordering process. When they navigate to start ordering have the site ask whether they would want it delivered or they pick-up. This would enable you to filter out the products that they could choose from due to availability rather than the user making a large grocery list only to find out that some of the products selected can't be delivered or picked-up which in turn makes them frustrated and they have to re-make their list or leave your site all together. Just an idea, hope it helps.
Comment: I got this, but the meal details page can be reached from different entry points with no pre-set fulfillment type, so I thought allowing to set this later, on checkout stage, but now, I consider to put it on a meal level.
Comment: @Myro looks like the site came out really well and overall clear. Goodjob
Answer: Technically this is more a type of fulfillment for the customer which entails specific system side processing. You'll get higher conversion by providing an item level choice of fulfillment rather than an order level method of fulfillment. With the requisite fulfillment options or specifications determined in the checkout flow. This means you will have varying levels of checkout steps depending on the order.
If that is not possible then you should message which items are available for what type of fulfillment, my assumption is there are delivery only, pickup only and mixed fulfillment options (delivery and pickup) available for some product. When the user makes a selection send the remainder to a saved for later area.
Comment: Yes! That make sense, I'll try to allow the user to choose the fulfillment option on the meal level, not the order one.
Comment: @myro: If you are going to allow fulfillment options at the meal level, you may also want to consider delivery addresses at the meal level to cater for large(r) organisations with multiple buildings or meeting rooms. For the latter you may not need a full delivery address, a note would suffice. Of course, before implementing, check whether there is a real need for it. I just thought of it because if you might want to pick up some and have others delivered, you are probably ordering for other people and destination might differ as well.
Comment: Thanks, Marjan! That's the way, I would consider after the main functionality will be great.
Answer: Having done a few of these the standard approach is to split the flow at the pick up / delivery point. You can use various techniques like progressive display if you're doing things on one page but essentially it's simpler to just show what the user wants.
If there are standard delivery options for all items its normal to dispatch all those items together to keep the checkout simple.
Having said that it is possible to have a screen that provides different options then the user steps through each of the different 'batches' - effectively doing the pickup then the delivery process. It's messy but unavoidable if you have multiple items in a basket that have different delivery options.
It does depend partly on your audience. If you're dealing with customers who have large complex orders of technical items then more options are useful. If it's a general audience simple is often best.
Answer: Here my two cents:

I think that the horizontal alignment of the elements on the page is good. The items summaries are registered and scannable
Vertical alignment and logical grouping of the information is ambiguous mostly because of proximity.
I think that the break line used to separate the elements on the page
does not break down the page into the relative steps.  Ex: The pickup
step seems to contain the whole order summary

Suggestion:
 - reorder each step as a modules having the same wireframe structure.
 - gives enough space between steps so that they will be perceived sequential, separate objects.
Ex:

I hope you'll find this useful :)
Comment: Thanks for pointing out the issue with proximity, I agree adding more space will bring more structure to layout. Also flipping the 'summary' and 'form sections' is a good idea, because of LTR reading for target audience.
Thanks again, appreciate this.


Accessing properties of html element inside javascript function using $(this) gives undefined

Question: I am calling a function test() on an anchor tag like this:-
Hello

And I am trying to access the class of the anchor inside the function test():-
function test()
{
  alert($(this).attr("class"));
}

But this alerts undefined. I know that calling onclick=test(this); instead and having the following function works:-
function test(obj)
{
  alert($(obj).attr("class"));
}

But, I wanted to access the properties of the element (on which the function is called) without passing a this. Just be able to get/set properties of the element (on which the function is called). Is it possible? How to do this?
Answer: this is "The object on which this function was called", so for foo.test(), this is foo inside test. If you don't specify an object, it defaults to window so in your code this === window since you are calling (implicitly) window.test().
Forget about intrinsic event attributes. They are ugly and do not lend themselves to unobtrusive JavaScript.
Instead, use JavaScript to assign your event handlers. jQuery, which you are already using, provides a number of ways to do this, including click. Pass the function you want to call as the argument to it.
jQuery('.link').click(test);

When the click event fires, it will now call something akin to HTMLElementNode.test() instead of HTMLElementNode.onclick() so this will be what you want.
Answer: In this scenario we need to make sure that HTML element owns that function which you wanna call upon click. What u actually doing is that u are using onclick attribute which just takes string parameter and completely oblivious of everything else.
In order to make HTML element owner of the function you need to map onclick property completely with your own custom function. In JavaScript you do that like that
element.onclick = doSomething;

So our code will be something like

Click

here is the working example http://www.jsfiddle.net/VMCmb/1/.
Also please take a look at http://www.quirksmode.org/js/this.html.
Comment: Simpler answer and nice links... Thanks
Answer: Because "this" is a special free variable in Javascript: it is bound by the context of the caller.
Passing this is a better and safer way of doing the job.
Answer: You could also use this method -
Pass this as a parameter -
Hello

Jquery code will be -
function test(obj)
{
  alert($(obj).attr("class"));
}


Is there a way to do this with double integration?

Question: If $0 < h < a$, then the plane $z = a - h$ cuts off a spherical segment of height h and radius b from the sphere $x^2 + y^2 + z^2 = a^2$.
a) Show that $b^2 = 2ah - h^2$
b) Show that the volume of the spherical segment is $V = \frac{1}{6}\pi h(3b^2+h^2)$
Part a is pretty straightforward but I'm looking for how to approach (b). I've seen it done with triple integration. Is it possible to do it for 2 integrals?
What I have so far is $\int_{0}^{2\pi}\int_{0}^{b} (\sqrt{1-r^2} - (a-h))rdrd\theta$.
Answer: What you are talking about is spherical cap. Yes you can find with single / double integral. There seems to be some mistake in how you have written it.
You know radius of the circle at any given $z$ is $\sqrt{a^2-z^2}$. You use the knowledge of perimeter of the circle or the area of the circle at a given $z$ to make this a double or single integral.
$\displaystyle 2\pi \int_{(a-h)}^{a} \int_0^{\sqrt{a^2-z^2}} r \, dr \, dz$
or you can write it as
$\displaystyle \pi \int_{(a-h)}^{a} (a^2 - z^2)  \, dz$


If a sequence $(f_n)$ converges in $L^2$, then $g'(x)\int_0^x f_n(t)\,dt$ converges in $L^1$

Question: The first: Suppose $g$ is increasing and differentiable on $[0,1]$. For every $f\in L^2(0,1)$ define $f^*(x)$, for $x\in [0,1]$, by:
$$f^*(x)=g'(x)\int_0^x f(t)\,dt .$$
If $f_n\to f$ in $L^2(0,1)$, then prove that $f_n^*\to f^*$ in $L^1(0,1)$.
I started like this: First notice that since $g$ increasing, $g'(x)\geq 0$. Now let $\epsilon>0$. Let
$$f_n^*(x)=g'(x)\int_0^x f_n(t)\,dt .$$
We need to prove:
$$\int_0^1|f_n^*-f^*|\,dx<\epsilon, $$
provided
$$\left(\int_0^1 |f_n-f|^2 \,dx\right)^{1/2}<\epsilon_1. $$
\begin{align}
\int_0^1|f_n^*-f^*|\,dx&\leq\int_0^1 g'(x)\int_0^x\left|f_n-f\right|\,dt\,dx\\
&\leq \int_0^1 g'(x)\int_0^1 \left|f_n-f\right|\chi_{\{x\ge t \ge 0\}}(t)\,dt\,dx\\
&\leq \int_0^1 g'(x)\left(\int_0^1 |f_n-f|^2\,dt\right)^{1/2}\left(\int_0^x 1 \,dt\right)^{1/2}\,dx\qquad\text{Holder's}\\
&=\epsilon_1 \int_0^1 \sqrt{x}\,\,g'(x) \,dx
\end{align}
If that was right, then what after?
Comment: Separate them in two questions.
Comment: They may be related, which means you should link to this question when posting the other. But not put them both in the same question.
Comment: I think they are kinda related. That's why I posted them together
Comment: I will separate them. Thanks.
Answer: You're almost done.  Note that $g'(x)$ dominates $\sqrt{x} g'(x)$ on this interval, and the integral of $g'(x)$ is less than or equal to $g(1)-g(0)$.  This doesn't require absolute continuity for $g$.  See Proposition 22 here.
Comment: Yea I know this proposition for increasing functions. So just need to assume $\epsilon_1<\dfrac{\epsilon}{g(1)-g(0)}$, right?
Comment: Yup. Then you're done.


mod_rewrite Remove .php from specific file and prevent access to the original file

Question: I would like to change:
www.foo.com/bar.php

To:
www.foo.com/bar

And after that, prevent direct access to /bar.php but allow /bar:
www.foo.com/bar.php    404 Not Found

I want access to bar.php to give a 404 error.
Basically, I want it to look like "bar" is a directory.
Is this even possible?
My current code is:
RewriteEngine On
RewriteRule ^bar/?$ bar.php [NC]

Comment: Your "current code" already appears to do the main part - any problem with this? Presumably the URL has already been changed to `/bar` in your application?
Answer: You can use this :
RewriteEngine on
#prevent direct access to /bar.php
#return a 404 error if /bar.php is direct accessed
RewriteCond %{THE_REQUEST} /bar\.php [NC]
RewriteRule ^ - [R=404,L]
#rewrite /bar to /bar.php
#this will internally forward http://example.com/bar to http://example.com/bar.php
RewriteRule ^bar$ /bar.php [L]

Comment: Thank you, it works! Just a question, what does the [L] flag do? The NC flag seems to work aswell
Comment: @SveaNils https://httpd.apache.org/docs/current/rewrite/flags.html#flag_l


.NET: Send a text message to all instances of the same application and read it

Question: I need ability to reliably sync some chunks of textual data between all running instances of my application. What's the best way to make it?
Comment: Can you give more information?  Is this some application with multiple conncurrent users, or are you talking multiple instances on the same machine?
Comment: Multiple instances on the same machine. I thought of using window messages provided in Windows API, is that possible?
Answer: Generally speaking you need the Observer Pattern. You need something to act as a server. After that it depends whether if a change happened at some application should notify the observer or the observer should request change summary from every client (at some intervals), merge it and return it to the clients. It is too complex to answer with such minimum information you provided.


Why sscanf is taking more than desired value in C?

Question: Why sscanf is taking more than the desired value?
Sample code:
int main()
{
    char *str="a:b:c:d:g:s:d";
    int a[4]={0};
    int ret;
    ret = sscanf(str,"%x:%x:%x:%x",&a[0],&a[1],&a[2],&a[3]); /*It prints 4 but in input I have given 7 values(a,b,c,d,g,s,d)*/
    if(ret==4)
    {
        printf("success\n");// it prints success anyways!
    }
    return 0
}

I wanted to go inside the if condition only if the *str contains 4 octets(a:b:c:d - only Hex values).
NOTE: If I give less than 4 octets it isn't going inside the if condition.
Comment: `sscanf()` doesn't have to use the whole string.  You gave 4 valid hex numbers (`0x0A`, `0x0B`, `0x0C`, and `0x0D` separated by colons as the format required.  The residue is unparsed.  You can use `%n` to find out how far the parsing progressed.  Remember, `sscanf()` is non-destructive — it does not modify the string that it is processing.  That means. you can rescan the string with different formats if you wish, or if you need to because the first attempt didn't work as expected.
Comment: after doing the normal `sscanf()` do an additional one; if it succeeds then print error...
Answer: Your string didn't give seven values since "g" and "s" are not valid hexadecimal values. So fix that first:
char *str="a:b:c:d:e:f:1";

Then try to read more than four values:
ret = sscanf(str,"%x:%x:%x:%x:%x",&a[0],&a[1],&a[2],&a[3],&ret);

Now, if there are more than four values, this code will read five of them, and the if will fail. I re-used ret because the assignment of the return value is guaranteed to happen after. But if that scares or confuses you, you can do this:
int dummy;
ret = sscanf(str,"%x:%x:%x:%x:%x",&a[0],&a[1],&a[2],&a[3],&dummy);

Comment: `dummy` remains as it was when only 4 are scanned.
Comment: what if there is only 4 values in the string? will `sscanf()` even return?
Comment: @user12986714 It will return 4 since it will only read 4 values.
Comment: @chux-ReinstateMonica The point of dummy is just to ensure that 5 is returned if there are 5 values. The idea is not to ever look at its value.
Comment: @DavidSchwartz dummy is returning 0 even if there are 4 or more than 4 values.
Comment: @kavinhuh There's no reason to look at dummy's value. It's only purpose is that `sscanf` requires a valid pointer that it can use. If `ret` is 4, `dummy` was never filled with a value. If `ret` is anything other than 4, that's an error condition and there's no reason to look at any values.


Combinational division in HDL

Question: I am trying to come up with a way to estimate the gate count if I were to implement a purely combinational 64-bit division.
I can't get my synthesis tool to generate a combinational 64-bit/64-bit integer division.
Comment: I seriously doubt you'd want to remove all registers from a 64-bit division...
Comment: Apparently some synthesis tools implement / and some don't. I understand it will be huge. I just want to know how huge.
Answer: a 64bit/64bit divider fully combinational is leading to a huge design. this will use a lot of resources and lead to poor speed achievements. I'd suggest to implement the division with several register stages instead of fully combinational.
however, if you'd like to try, the following code would be synthesisable (as "/" operation is given by numeric_std library). check with a synthesis tool the recources needed for it (for synthesis the use of std_logic_vector in entities is suggested):
<code>library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.numeric_std.ALL;

entity divideComb is
Port ( a : in  STD_LOGIC_VECTOR (63 downto 0);
       b : in  STD_LOGIC_VECTOR (63 downto 0);
       c : out  STD_LOGIC_VECTOR (63 downto 0));
end divideComb;

architecture Behavioral of divideComb is

begin

    c<=std_logic_vector(signed(a)/signed(b));

end Behavioral;
</code>
the above code leads to the following synthesis results with Xilinx ISE 13.4:

inferred 131 Adder/Subtractor(s)
inferred  65 Comparator(s)
inferred 4036 Multiplexer(s)

when using Spartan 6 architecture, this leads to 6982 Slice LUTs (and 0 FlipFlops, of course!)

Combinational division in HDL


How can a user get 'Strunk & White' Badge whose suggested edits are below 80?

Question: How did this user got Strunk & White badge as his suggested edits are below 80 ?
As of my understand, every user need to have at least 80 'suggested edits' to get this badge.
I got some knowledge on this badge from the following posts.
How to get Strunk & White badge?
Is the "Strunk & White" badge not given anymore?
Did I miss any thing to understand about this badge?
Comment: Not only suggested edit, the count is also for normal edit to the post! After 2000 rep users no need to wait in review queue, their edit will appear immediately. So anil made more than that, suggested edit only count if user below 2000K rep.
Comment: @Bala  - Great! thanks bala, now it's clear. So after 2k reputation, user can't able to see their edits under his 'suggested edits' tab, right?
Comment: Yes suggested edits are only for < 2k users only!.
Comment: @Bala - Thanks bala, it's clear now. When you have time please make your comment as answer.There is typo in your first comment. ( 2k not 2000k) ;)
Answer: The edits count is not only for suggested edits, but also for normal edits. Once their reputation reach 2000, users don't need to suggest edits; their edits directly apply to the posts they change.
That is the case of Anil Sagar.


The digital root of a tower of exponents, $d(\underset{\text{The number of }2 \text{'s is }2013}{\underbrace{2^{2^{2^{.^{.^{.^{2}}}}}}}})$

Question: For a natural number $n$, the digital root of $n$ is the value obtained by an iterative process of summing digits. The digital root of $n$ is denoted by $d(n)$.
Examples; $d(142)=7$, $d(123785)=8$

In $2013$, I attended a hard mathematical tournament. In this tournament, no one answered this question, and I am curious to know the key of solving it. Any help will be appreciated.

If $d(n)=n-9\left \lfloor \frac{n-1}{9} \right \rfloor$, find the value of $d(\underset{\text{The number of }2 \text{'s is }2013}{\underbrace{2^{2^{2^{.^{.^{.^{2}}}}}}}})$.
Comment: @automaticallyGenerated:  yes, it is the same.  $d(19)=19-9\lfloor \frac{19-1}9\rfloor=19-9\cdot 2=1$, which is the same as $1+9=10,1+0=1$
Comment: Are you sure that it was asking for the digital root? Because $d(n)=n-9\left \lfloor \frac{n-1}{9} \right \rfloor$ is not the same as the digital root. Consider $n = 19$.
Comment: At a (very brief) first glance I would try using modular arithmetic, maybe reducing this big old number mod 9 or something. The floor function here is interesting because those always emerge naturally in division algorithms. What have you tried?
Comment: We need to find the value of "two to the power two to the power two to... (many times, a finite number)" modulo $9$. Two is prime to $9$. Euler. So we need to know the value of "two to the power two to... (many times, a finite number)" modulo $6=\phi(9)$. The above number is divisible by $2$. So we need  (Chinese R.T.) the value of "two to the power two to... (many times, a finite number)" modulo $3$, the other factor of $6$. We can go on with Euler / Fermat, but note that $2=-1$ modulo $3$, and we have an even power. Putting all together we get the answer...
Comment: Whoops, I didn't realize that $10 \ge 10$
Comment: Related: [What is the sum of sum of digits of $4444^{4444^{4444}}$](https://math.stackexchange.com/q/169857)
Answer: I have found a suspiciously simple answer to this problem, so I would appreciate it if you could check my work. Let us define $\textrm{tow}(2, k)$ to indicate a power tower of $2$s of height $k$. We know that $2^6 \equiv 1 \mod 9$. Thus, $\textrm{tow}(2, 2013) \equiv 2^{a}\mod 9$, where $a \equiv \textrm{tow}(2, 2012) \mod 6$. However, note that $2^{2k} \equiv 4 \mod 6$ when $k>0$. $\textrm{tow}(2, 2012)$ is obviously even, so it follows that $\textrm{tow}(2, 2013) \equiv 2^{4}\equiv 7\mod 9$. Using the formula for $d(n)$ that you provided, we see that our final answer is indeed just $7$.
Comment: it really is just applying Euler's totient theorem twice. with a bit of nuance once you want to go back down the chain.


Differences between "stasis" and "stopped"?

Question: So, in Heroes of the Storm, there are those two effects who look the same to a certain extent, like when you're put into stasis or into stopped, your hero can't do anything and can't be attacked.
Sometimes that saves you, sometimes that sets up enemies to combo you.
But are there other things that can happen between a self/ally stasis and an enemy stasis?
The only thing I could think of is self/ally stasis doesn't freeze your cooldowns where as enemy stasis does, but is there anything else, like your regen?
Answer: Time Stop is an effect that makes the target Invulnerable while unable to do anything for a short duration of time. The target is locked into his position and can't be interacted with. Unlike Stasis, Cooldowns and Damage over Time effects don't refresh during Time Stop. Time Stop can affect Invulnerable and Unstoppable heroes, but not heroes in Stasis.
Stasis is an effect that makes the target immune to damage and untargetable, but also makes them unable to use their abilities and in (most cases) move for a short duration of time. Stasis also removes existing debuffs, including Armor debuffs and hero specific debuffs like Jaina's "Chill". Most abilities that grant self-Stasis can be cancelled to end the effect early. Stasis still allows Cooldowns to refresh as opposed to Time Stop. Unlike Invulnerable targets, heroes in Stasis can not be affected by friendly abilities. Zagara's Devouring Maw is the only stasis effect that allows damage to be dealt to the target and targetting Unstoppable enemies.
Think of these abilities as pauses - time stop makes you pause the game and your character is removed from the game for a bit, then comes back the exact same as when it had been removed - stasis makes you pause the game your character is NOT removed from the game but just in a timeout.


consuming an deployed Azure ML model in PowerBI

Question: I have issues while interfacing Azure ML with PowerBI. I deployed a model from Auto ML, and tried to consume it in PowerBI. I successfully completed the following tutorials create a predictive model by using auto ML and consume a model in PowerBI . But when it comes to implement my proper model, I  can choose the targeted model, and use the right inputs, with the right data type, but I get this error :
Unable to parse the response from the Azure ML Web Service

I have to add that my model forecasts time series. On the contrary, the model was a regression in the Microsoft tutorials. And I didn't use R or Python script, I used exactly the same method as the second tutorial about PowerBI.
Thank you very much for your help ! don't hesitate to ask me if you need more information.
Mary
Comment: please share Scoring file and Conda file to check.
Answer: Good practice to use error handling:
def run(data):
try:
        result = model.predict(data)
        return result.tolist()
    except Exception as e:
        result = str(e)
        return json.dumps({"error": result})
    return json.dumps({"result": result.tolist()})

If you instead used the pandas dataframe as the input schema, this should generate the swagger with the column names as separate input parameters with known data types which Power Bi can then use to map to columns in your data flow.
Comment: Hello, I don't use python to interface Azure ML and PowerBI. I want to do it with the graphical interface.


Short syntax for using local image in React without webpack?

Question: I am able to display a local image with html img like this:
import youtube from "./youtube.png"

and

However, I have got like hundreds of images I want to use import, so I don't want hundreds of import statements.
Is there a shorter syntax for img src to refer to local images in React? And if webpack is the only way out, will webpack take much time to set up? And since I am on this topic, how does a website typically display images? Do devs download the images and upload these files when the website is deployed or do they straight up use src="https://....."?
Sorry if that is too many questions, I am really only concerned about the syntax to refer to local images, thank you.
Comment: Are you looking for a shorter syntax for `` or `import`?
Comment: A shorter syntax for directly referencing to a local img src :) So I don't want to import from another package but directly refer to it like <img src="./localimages/youtube.png", but that doesn't work. Anyways, Tenza's response works.
Answer: You could put them all in the public folder and access them that way if you don't want to use web pack.
As far as I know, there is not shorter way than the method you mentioned to import images, of course you can use web pack as well and once that's set up you can reference it.
As a side note this is from the React docs on usage of the public folder:

You have thousands of images and need to dynamically reference their paths.

You can read more about it here: https://facebook.github.io/create-react-app/docs/using-the-public-folder


Pointer of array pointer objects in QT

Question: In C++, I have a array pointer of objects like this:
vector<Articulation*> artic;

I have the next problem. When I send that vector to another class like &artic. So I have the pointer and not all the array duplicated. The problem is the next. In the new class, i have a ponter of array pointer objects
vector<Articulation*>* pArtic;

In the new class I do pArtic[i]->move(). The method is implemented in Articulation. When I do the method mov(), QT tell me that the type std::vector<_Ty> dont have an operator ->. That is because, I think, I cant access to the Articulation objects and I am trying to do move() over a vector.
Anyone knows what I must do to acces to the Articulation objects and do the move() method?
Example:
Class A:
vector<Articulation*> artic;

void A::initVector(){...}
void A::sendInfoToB(){
B nuevo();
B.send(&artic);
}

Class B:
vector<Articulation*>* pArtic
void B::send(vector<Articulacion*>* art){
pArtic=art;
}
void B::sendToC()
{
C nuevo();
C->sendTheLast(pArtic);

}

Class C:
void C::sendTheLast(vector<Articulation*>* artic)
{
string data=artic[i]->move();
//Move returns a String
}

That is the example.
Comment: Please provide simple move() method body.
Comment: Can you provide a **small** sample illustrating what you want to do and reproducing the problem? I can't make any sense out of your question.
Answer: The problem is, that you are calling the method move() of the i-th position of pArtic, which is a pointer to a vector of pointers. What you want to do is calling the method move of the pointer at the position i of the vector.
(*pArtic)[i]->move()

that is what you want to do, but care, this is not really safe I guess...
a better way would be to give away only the reference artic by expecting a vector<>& reference, not a pointer.
Comment: I dont understand your solution  :S
Comment: instead of calling `pArtic[i]->move()` you call `(*pArtic)[i]->move()` and it works.
Comment: It works, thanks!! But I have one question, why it works? I dont understand.
Comment: I updated the answer, the first paragraph should explain it... in short: you had a pointer to an array and tried to get the i-th element, but in fact you were looking in the i-th memory cell after the one of the pointer. By dereferencing the pointer (adding *) you do actually get the pointer to the i-th element and can call the method ;)
Answer: Store QT objects directly on containers (unless there is a real need of using pointers). This is because QT implements implicit sharing and COW (Copy-On-Write) which eradicates copy-overhead of containers everytime you pass them across. By passing the containers either by value or reference as need be, makes the interface simpler and easy to use.
Again, using raw-pointers in C++ is always dangerous when you have better mechanisms (like smart pointers). Smart pointers makes your program exception safe while managing the life of raw pointers.

Pointer of array pointer objects in QT