const int = int const?

Question: For example, is
int const x = 3;

valid code?
If so, does it mean the same as
const int x = 3;

?
Comment: @Hamish: some compilers accept all sorts of invalid code; the only way to be sure that something's valid is to look in the standard, or ask.
Comment: Check out this: http://c-faq.com/decl/spiral.anderson.html , it should make it clearer how to read a declaration.
Comment: Well, one is a constant integer and the other is an integer that's constant... :-)
Comment: I would not want to use such compiler then. In any case, a compiler is my first line of defense.
Answer: They are both valid code and they are both equivalent.  For a pointer type though they are both valid code but not equivalent.
Declares 2 ints which are constant:
int const x1 = 3;
const int x2 = 3;

Declares a pointer whose data cannot be changed through the pointer:
const int *p = &someInt;

Declares a pointer who cannot be changed to point to something else:
int * const p = &someInt;

Comment: The pattern here becomes apparent if the definitions are **read in reverse**. For example: `[const int *]` = a pointer (`*`) to an `int` that is `const`. `[int * const]` = a `const` pointer (`*`) to an `int`.
Comment: @ T.E.D. : Not quite. Just get into the habit to write `const` always *after* the thing it applies to, and you're done. (Always-trailing is the only style that could be applied *consistently*.)
Comment: C syntax reads crappy no matter what you do. It wasn't designed to produce readable sources. You just have to learn the rules.
Comment: And ` const int * const p = &someInt` would give you a pointer that cannot be changed to a value that cannot be changed, if I'm not mistaken.
Comment: You should also include 'int const *' and just for a laugh 'int const * const'
Comment: **-1** This contrast is misleading. It works the same for pointer types if you put the `const` before or after the type. Moving it past the `*` is another thing altogether.
Comment: @JAB: Yes it will give you a pointer that can't be changed in addition to having data that can't be changed inside the pointer through that pointer.
Comment: @Brian R. Bondy - They can both be quite useful at times though. In particular I end up using `int const *` (a read-only view of some other variable or area of memory) in systems programming all the time.
Comment: It should also be noted that const int *p = &someInt, simply bars that pointer from modifying the int but the int value itself can still be changed. If someInt was declared int someInt = 0, and somewhere after p was declared, there can be code that says someInt = 5, it would compile and run without problems.
Answer: Yes, they are the same. The rule in C++ is essentially that const applies to the type to its left. However, there's an exception that if you put it on the extreme left of the declaration, it applies to the first part of the type.
For example in int const * you have a pointer to a constant integer. In int * const you have a constant pointer to an integer. You can extrapolate this to pointer to pointers, and the English may get confusing but the principle is the same.
For another dicussion on the merits of doing one over the other, see my question on the subject. If you are curious why most folks use the exception, this FAQ entry of Stroustrup's may be helpful.
Comment: Exactly what I was thinking. `const int x` is the exceptional form. `int const x` fits the same pattern as `int * const x`. If you need a constant pointer to a constant int, I usually write it as `int const * const` for consistency rather than `const int * const`.
Comment: @Cogwheel - Precisely. Once you realise the "normal" form of putting the `const` to the extreme left is actually making use of an exceptional case, the question arises as to which way actually makes the code clearer in the long run. Hence my question http://stackoverflow.com/questions/988069/in-c-is-const-after-type-id-acceptable
Comment: @T.E.D. **The rule in C++ is essentially that const applies to the type to its left.**  Is there any citation for this by known programming gurus or just kind of understood thing. Also in the "const int * p1". There is nothing to the left of const. How to apply the rule in this scenario.
Answer: Yes, that is exactly the same. However, there is difference in pointers. I mean:
int a;

// these two are the same: pointed value mustn't be changed
// i.e. pointer to const value
const int * p1 = &a;
int const * p2 = &a;

// something else -- pointed value may be modified, but pointer cannot point
// anywhere else i.e. const pointer to value
int * const p3 = &a;

// ...and combination of the two above
// i.e. const pointer to const value
const int * const p4 = &a;

Answer: From "Effective C++" Item 21
char *p              = "data"; //non-const pointer, non-const data
const char *p        = "data"; //non-const pointer, const data
char * const p       = "data"; //const pointer, non-const data
const char * const p = "data"; //const pointer, const data

const pointer: pointed value may be modified, but pointer cannot point
anywhere else

Answer: It is the same in meaning and validity.
As far as I know, const only get complex whenever it involves pointer.
int const * x;
int * const x;

are different.
int const * x;
const int * x;

are same.
Answer: I found that if always write const in right, it will becoming easier to read a complex pointer type, for fun.
For example:
// Just append const or pointer to
int x; // data
int const cx; // const data
int *px; // pointer to data
int const *pcx; //pointer to const data
int * const cpx; // const pointer to data
int const * const * * const cppcpcx; // const pointer to (pointer to (const pointer to const data))

Answer: I have an idea how to interpret (non)const pointers and data. Split it with *.

Data type
Star sign
Pointer type
Combine
Data
Pointer

int
*
p
int *p
non-const
non-const

const int
*
p
const int *p
const
non-const

int
*
const p
int *const p
non-const
const

const int
*
const p
const int *const p
const
const
Answer: // 1.

int x1 = 1;
int x2 = 2;

const int* p = &x1;
//*p = 3;          // variable data is CAN NOT BE changed through pointer
p = &x2;           // pointer CAN POINT to other variable

cout << *p << endl;   // OUTPUT: 2

// 2.

int y1 = 1;
int y2 = 2;

int* const t = &y1;
*t = 3;            // variable data is CAN BE changed through pointer
//t = &y2;         // pointer CAN NOT POINT to other variable

cout << *t<<endl;   // OUTPUT: 3

const int = int const?


CSS word-break does not work correctly in Microsoft edge

Question: It has come to my attention that in Microsoft Edge there is a problem with some css attributes, such as :
word-break: break-word;

Is there a way of fixing this or is there a way around this?
Answer: word-break: break-word is deprecated, and not supported by MS Edge or MS IE. See mozilla documentation about this.
word-break is supported by MS Edge and MS IE Here is a list of supported browsers.
Valid MS Edge and MS IE word-break properties are:
word-break: normal|break-all|keep-all|initial|inherit|unset;

Alternatively mozilla documentation specifies that overflow-wrap: break-word; acts the way that you want word-break: break-word to function.
Comment: Thank you so much, I really needed this help. I would rate your answer but I don't a high enough reputation too...
Comment: Don't forget to validate your CSS. You may want to recommend that in the answer because a good validator would have found the problem right away and explained the `break-word` value.
Comment: I had to use this technique: REALLYLONGCONTENTONEWORDONLY ...then in my CSS I used the word-wrap: break-word; and white-space: pre-line; (to get IE Edge working properly). NOTE: I use word-wrap NOT word-break here.
Comment: This isn't true anymore. `word-break: break-word;` is valid CSS but it's only supported in Webkit at the moment. https://developer.mozilla.org/en-US/docs/Web/CSS/word-break#Specifications
Answer: An alternative solution is to make use of the word-wrap property which IMHO behaves more 'intelligently' - meaning the word break will only be applied when the word is too long to fit into a line width, and won't be applied to words that can simply be moved in whole to the next line.
CSS:
word-wrap: break-word;

The word-wrap property is supported by most browsers and as of today I can certainly confirm it works in Microsoft Edge, IE11, Chrome, Firefox, Opera and Safari.
Note, word-wrap has now been renamed to overflow-wrap, with word-wrap now being an alternative name for that property, however overflow-wrap is not understood by Microsoft Edge so stick with using word-wrap for cross-browser compatability.
Answer: The thing is that you have to provide width for container/text in order to use word-break: break-word property. The only way to avoid this is to use unofficial WebKit/Blink only word-wrap: break-word property: https://caniuse.com/#search=word-break
Answer: It's also worth mentioning, that while word-break: break-word; is improper property , it's undocumented and non-standard property value in WebKit. This makes the word wrapping behave like word-wrap: break-word, but works with dynamic widths.
Answer: Use  -ms-word-break: break-all;
before word-break: break-word;
Comment: Your answer would be much better if you would explain why it works or point to some sources that can give more insight into this topic.
Answer: overflow-wrap: break-word;

is the way to go, it works also for Edge now.
Thanks @David for mentioning it!
Comment: The problem is that overflow-wrap: break-word; does not work on Firefox so you'll fix it for one browser but break it for another.
Answer: word-wrap: break-word;
display: inline-block;
width: 100%;

try this
Comment: Please refrain from answering with code-only. Note that you are not only answering to the OP, but also to any future readers of the question. Thus, please edit the post to contain an explanation as to why this line of code works.

Also, please refrain from answering with "try this". A good answer will always have an explanation of what was done and why it was done in such a manner, not only for the OP but for future readers of the question.


Auto-completing sign up forms using email enrichment API

Question: I am building a professional network and I am considering whether I should pre-fill sign-up form with the data that we obtain from the email enrichment API.
The current sign-up flow is:

User gives their email.
We send an email, which is used to authenticate user.
Once they are authenticated, they are brought to the onboarding flow.
The onboarding flow asks them questions such as: "What is your name?" "What is your Twitter?", etc.

This question is regarding the last step.
In theory, we don't need to ask the user to enter most of this data because we can pull it from email enrichment APIs. Just by having user's email (90% of the time) we can already pull their full name, their social profiles, and most of the other typical information about user's public presence. Therefore, should we just pre-fill this information for the user?

If we were to follow this pattern, the first thing that the user would see after clicking on the link we've sent to their email would be this form with their first name and last name pre-filled and advising about the source of the information.
Has anyone done it before?
How was this perceived?
What are the possible downsides?
Comment: With the raising focus on user privacy, I am pretty sure this wouldn't be a clever solution. Also you'd need to follow quite a lot of different of privacy / data protection laws all across the globe.

Imo, it is not worth it, especially not if the user would need to manually delete all the given information if it's autofilled wrongly. That feature has basically no benefit that would justify everything you have to be concerned about to be legally safe to use it.

Also consider, you would need to make people in the EU opt-in into that function and also five them the ability to opt-out of it.
Comment: If a user data is pulled from your own system where user had supplied it before, then I don't see a concern on pre-filling the user data. In fact, it would make their life easier in filling the form.
Comment: If you implemented this, would you consider answering your own question and telling the community how it went? Thanks.
Answer: It is no doubt a very good idea that you can incorporate.
There are plenty of benefits doing such a thing. Let me list down the top 2.

Boost up the completion time.
Dramatically decrease the cognitive load on a user by decreasing the amount of objects on the screen.

In case you have customer retention as goal or objective that would also add so much more value to it.
On the part of how it is perceived, mostly the since the info is pre-filled user expectation is to see something more of such sort if there are more questions asked and user has to provide inputs.
Answer: I've not tested this so cannot be sure but I think it's useful to fill out the information for the user if you can reliably do it as it speeds up the process for them.
As long as you tell the user where you got it from so it's not surprising and let them correct any mistakes (like if they changed their name or there's a typo).
I can see you are telling the user but I think you could do with make it clear by making it more prominent (larger text, put it above the form etc).
Answer: its efficient if you are okay with API Pricing
also allow user to overwrite the fields if they want to
just add a info icon on the text below
no other downsides i can see
Comment: Please answer the questions the OP asked. Implementation is not the focus of this question but rather how the feature would be perceived and possible UX downsides.
Comment: UX focussed answers would add more meaning and value to the question rather than telling about implementation


How does one gain access to Colossus Boulevard?

Question: I have seen multiple forum posts where users state that you need to defeat the main bosses on Cyclops Lane, Triton Avenue, and Firecat Alley, and the Headmaster will give you the quest to go to Colossus Boulevard. I have defeated almost all of the bosses in those streets, and the quest has not unlocked.
What are the requirements to get into Colossus Boulevard?
Comment: I had also did this, I just kept going with the main quests. Seemed to solve it.
Answer: You have to defeat almost all the bosses in Wizard City

Defeat the Harvest Lord, the Kraken and Sergeant Skullsplitter (all of whom are located in Triton Avenue).
Complete Cyclops Lane by defeating General Akilles and Eyus Maximus.
Vanquish all enemies located in Firecat Alley (Melweena Smite, Bastila Gravewynd, Alicane Swiftarrow and/or Wormguts).
Venture to Olde Town and defeat Foulgaze in the field of battle.
Obtain 750 crowns or purchase a game membership. Without one of the two, you cannot enter Colossus Boulevard.
Speak to Merle and he will send you on a quest to find Private O'Doyle. The private has the key to Colossus Boulevard.

Here you can read throught all the information given on this subject from itstillworks


Binding errors in MVVM

Question: When binding to a ViewModel the framework handles some of the validation by default, for example if a text field is bounded to an int property and the user enters a letter the input's border turns red. I've read about IDataErrorInfo and INotifyDataErrorInfo but couldn't implement them successfully (that is this approach is what I need).
 so if this is my model:
public class TestModel : ObservableObject
{
    public int ModelId { get; set; }
    public string ModelName { get; set; }

    private int _modelNumber;
    public int ModelNumber
    {
        get { return _modelNumber; }
        set
        {
            _modelNumber = value;
            RaisePropertyChanged();
        }
    }

}

my ViewModel:
public class TestViewModel : ObservableObject
{
    private TestModel _selectedModel;
    public TestModel SelectedModel
    {
        get { return _selectedModel; }
        set
        {
            _selectedModel = value;
            RaisePropertyChanged();
        }
    }

    private ICommand _doSomthingCommand;

    public ICommand DoSomthingCommand
    {
        get
        {
            if (_doSomthingCommand == null)
            {
                _doSomthingCommand = new CommandBase(doSomthing, canDosomething);
            }
            return _doSomthingCommand;
        }
    }

    private bool canDosomething(object arg)
    {
        //check here if an error exists
    }

    private void doSomthing(object obj)
    {
        throw new NotImplementedException();
    }
}

how would I know that there's an error in the view and return false from the canexecute method?
Comment: There are lot of articles spanning over the net for how to implement IDataErrorInfo like [here](http://codeblitz.wordpress.com/2009/05/08/wpf-validation-made-easy-with-idataerrorinfo/) and [here](http://www.eidias.com/Blog/2012/7/2/simple-validation-in-wpf-mvvm-using-idataerrorinfo) Have you tried any of them?
Comment: @RohitVats I did, however, the validation here is made on the model and I can't get the value of it in the `ViewModel`
Answer: I'm not an mvvm expert myself. But I would say that your model should not be raising property changed events. That property should be in your view model.
private int _modelNumber;
public int ModelNumber
{
    get { return SelectedModel.ModelNumber; }
    set
    {
        SelectedModel.ModelNumber = value;
        RaisePropertyChanged();
    }
}

To implement IDataErrorInfo obviously add it as an interface
public class TestViewModel : ObservableObject, IDataErrorInfo

and implement the interface
   public string Error
   {
       get { return string.Empty; }
   }

    public string this[string propertyName]
    {
        get { return GetErrorForProperty(propertyName); }
    }

    private string GetErrorForProperty(string propertyName)
    {
        switch (propertyName)
        {
            case "ModelNumber":
                if (test bool property here)
                {
                   //if false
                   return "string";
                }
                else
                {
                   //if true
                   return string.Empty;
                }
            default:
                return string.Empty;
     }

In the view bind like so:
Text="{Binding ModelNumber, ValidatesOnDataErrors=True}"

Comment: Well firstly you should be binding to your view model so that you can use IDataErrorInfo and validate your view model. Validation logic such as IDataErrorInfo should not be in your model, your model should just hold an object and its properties. http://en.wikipedia.org/wiki/Model_View_ViewModel#mediaviewer/File:MVVMPattern.png using that link you can also see that the mvvm pattern means your view talks only to your viewModel and the viewmodel communicates data up from the model. at the moment it looks like your view is talking directly to the model
Comment: Why shouldn't I raise the `PropertyChanged` event in the model?

Binding errors in MVVM


How do I change the SQL query on the basis of user input in C#?

Question: This is my code where I am receiving the props from ui and it is a boolean value that I am receiving. From the UI, I'm passing true and false:
public void AlterTableColumn(int instanceid, bool IsHidden)
{
    var sqlQuery2 = String.Format("Update {0} set {1} = 1 where Id = {2};", "Mytable", "IsHidden", instanceid);

    string connString = System.Configuration.ConfigurationManager.AppSettings["DBConnection"].ToString();
    // getConnectionStringById(instanceId.ToString());

    using (SqlConnection connection = new SqlConnection(connString))
    {
        connection.Open();

        SqlCommand sql_cmnd = new SqlCommand(sqlQuery2, connection);
        sql_cmnd.CommandType = CommandType.Text;
        sql_cmnd.CommandTimeout = 10000;

        sql_cmnd.ExecuteNonQuery();

        sql_cmnd.Connection.Close();
    }
}

How do I change the sqlQuery2 mentioned above in terms of true or false? Right now it is making 1 in the SQL table for true or false
Comment: convert the bool to int and use that value 0 or 1
Comment: Change your `1`  to reflect the value of `IsHidden`. Also you're using `IsHidden` as the column name you're wanting to update... FWIW use parameters, helps prevent SQLi and would make this query easier. Finally you added the `mysql` tag, it doesn't appear you are using `mysql` rather `sql`, please remove that tag if not applicable.
Comment: right now everything is 1 be it false or true , i just need condition for sqlQuery2
Comment: Use a parameterized query, set proper param values.
Comment: parameterized query as in ?
Comment: Be aware: your code is subject to [sql injection](https://stackoverflow.com/questions/14376473/what-are-good-ways-to-prevent-sql-injection)
Answer: The way it is written now, the value of sqlQuery2 will be:
Update Mytable set IsHidden = 1 where Id = /*the value of the passed in instanceId*/
You're never using the passed in bool, IsHidden. You're always setting the IsHidden column to 1, regardless of what you pass the IsHidden function parameter.
In order to update the database to 1 or 0 based on the IsHidden parameter you need to set an int based on the value of that parameter. You also need to update the query itself to use the int rather than always setting the value to 1.
int isHiddenDbValue = IsHidden ? 1 : 0;
var sqlQuery2 = string.Format("Update {0} set IsHidden = {1} where Id = {2}",
   "Mytable", isHiddenDbValue, instanceId);

That being said, rather than using string.Format and putting the values in the query directly like you're doing, you should use a parameterized query. This will protect you from SQL injection attacks.
For example:
public void AlterTableColumn(int instanceid, bool IsHidden)
{
    int isHiddenDbValue = IsHidden ? 1 : 0;
    var sqlQuery2 = "Update Mytable set IsHidden = @IsHidden where Id = @Id";
    string connString = System.Configuration.ConfigurationManager.AppSettings["DBConnection"].ToString();
    using (SqlConnection connection = new SqlConnection(connString))
    {
        connection.Open();
        SqlCommand sql_cmnd = new SqlCommand(sqlQuery2, connection);
        sql_cmnd.CommandType = CommandType.Text;
        sql_cmnd.CommandTimeout = 10000;
        sql_cmnd.Parameters.AddWithValue("IsHidden", isHiddenDbValue);
        sql_cmnd.Parameters.AddWithValue("Id", instanceId);
        sql_cmnd.ExecuteNonQuery();
        sql_cmnd.Connection.Close();
    }
}


Using service beans and dependency Injection in Geb Functional Tests

Question: I would like to use a service inside my Geb test to populate some sample data. The sample data is large and complex, and we have already written the code to create it for other controllers and services. Thus a simple mock is out of the question. How can I access this service inside of my Geb test?
Let's assume the name of my Service is testDataService, and looks something like this...
class TestDataService {

    def otherService

    void importData() {
        otherService.getData()
    }
}

Something like the following in Geb would be ideal...
class testSpec extends GebReportingSpec {

    @Shared def testDataService

    def setupSpec() {
        testDataService.importData()
    }

    def test1() {
        ...some test...
    }
}

From what I understand, this should work for a normal integration test. Since it is a functional test, things are quite different and it returns null.
I found a lot of suggestions for the Grails Remote Control plugin, but I would like to know how to do this without it.
A few side notes...
The service class is located inside src/groovy. Though I am sure I  wired it in properly as it works as expected when called by other services. Only in functional tests does it not work.
Grails Version: 2.4.5
Geb 0.10.0
Answer: For Grails 2.4.5
def testDataService = Holders.applicationContext.getBean("testDataService")

So our testing spec could look like this...
class testSpec extends GebReportingSpec {

    @Shared def testDataService = Holders.applicationContext.getBean("testDataService")

    def setupSpec() {
        testDataService.importData()
    }

    def test1() {
        ...some test...
    }
}

Note that all injected dependencies from other services should be present.
Answer: there is the remote-control plugin: http://grails.org/plugin/remote-control; instructions are on https://github.com/alkemist/grails-remote-control/
you would add a RemoteControl instance in your test and run remote.call{ /* server side code */ } in your test (note this must return something serializeable).
in functional tests in grails you basically no longer take part in all the IoC and grails magic; you get treated like a regular client, that interacts with the server.
Comment: Thanks for the response cfrick, though in my case I don't want to use  grails remote control plugin due to a conflict it has with the Spring Security plugin. When I try to use it I get a io.remotecontrol.RemoteControlException due to java.io.StreamCorruptedException: invalid stream header. Upon looking around, I found [this](https://github.com/alkemist/grails-remote-control/issues/4), though time currently does not allow me to learn the inns and outs of the spring security plugin.


How can I change Git username when I want to pull or push repo?

Question: The default account that used to pull or push on git is not my account. Every time I do git push, it automatically uses the default account to do this. I searched a lot and successfully changed the username and email in ~/.gitconfig. But it's still not woking, when I try to do push or pull, it's still not asking me to input my password and do the work using the default account which is not mine.
I'm confused about this. How can I fix this?
Comment: `~./gitconfig` is not a valid location. I assume you mean `~/.gitconfig`? Each project can have it's config at `/.git/config`. I'd check if that file exists, and you may need to change that as git starts there and works its way up the directory tree.
Comment: If that doesn't work, it may be configured to use SSH, which may be how it's authenticating. Run `git remote -v` and see if the repo link you're pushing to is via `https` or `ssh`.
Comment: I have checked '/.git/config' and it does exist and I didn't see any settings about the default account the setting is like this[core]
 repositoryformatversion = 0
 filemode = true
 bare = false
 logallrefupdates = true
 ignorecase = true
 precomposeunicode = true
[remote "origin"]
 url = https://git.kaka.io/kaka/pockettutor.git
 fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
 remote = origin
 merge = refs/heads/master . The pushing way is via https.
Comment: Links that start with `git` mean that it's over SSH. Check `~/.ssh/config` for a github setting.
Comment: I have done what you said.but I don't have '~/.ssh/config' and the link starts with 'https' but when I copy here,It become like this.Does this still mean it's over SSH?
Comment: I don't see a link, but rereading you post, if it's asking your for a password (as long as it's not looking for a password to the SSH key or for access to the key), it must be SSH. However, this is definitely an SSH url: `git.kaka.io/kaka/pockettutor.git`, but you may be referring to a different URL. Also, check if any folders between your repo and `~` have a `.gitconfig` file. Otherwise, I'm at a loss :)
Comment: Ok,thanks a lot.In fact,It looks like this"remote.origin.url='h't't'p's':'/'/'git.kaka.io/kaka/pockettutor.git".every time I push a change,it finished automatically.for example.My username is Jack,but after I do push.I go to git and just find the name Bob do the push except Jack(me),even I change the git config as my name and email   :(
Comment: I finally figured it out by the help of nwinkler,thanks for your attention and patience too :)
Answer: On Mac OS X (as you indicated in your question), the username/password for accessing Git repos using HTTP(S) is stored in the Keychain Access application.
To remove the stored username entries, open the Keychain Access application, then select the login keychain in the top left. In the bottom left part of the window, select Passwords. Next, type the name of your Git server in the top right Search box.
Once the stored entries are shown, select the ones you're interested in. Double-clicking them will open them to show details about the stored username and URL. You can also show the password from this screen.
When you have found the entries that use the wrong username, you can simply delete them. On the next push/pull, Git should ask you for your username/password, as long as the username is not part of the remote's URL.
Comment: Oh!It works!!!Thank you very much!I got confused for a long time.You helped me a lot!thanks again :)
Comment: Good to hear. Just a minor comment - you might want to use the space bar after a full stop or exclamation mark - makes it easier to read :-)
Comment: Oh, and after a comma, too :-)


Can you make rune words out of Wirt's Leg?

Question: I remember when I used to play Diablo II that I often find a socketed Wirt's Leg when obtaining it from Tristram. Could you make a rune word out of it? Or was it just socketed sometimes because it was considered a weapon? I'd find it out for myself, but I don't have the game anymore at the moment.
Comment: Nah you never could. Wirts Leg is a unique item and you can't make runewords from unique items.
Comment: I hate that I didn't consider that it was unique. I guess its been much too long since I played that great game
Comment: Heh yeah. I was just talking about D2 with a buddy of mine yesterday about how I put 1000 hours into this one.
Comment: @ChaseC: Wirt's leg is not a unique (gold) item; it is a quest item.  It is a quest item that comes in normal (white) and socketed (grey) forms naturally.  There are magic (blue) and rare (yellow) versions of it created from cube recipes or from imbuing.  In previous versions you could make rune words from it but no longer.
Answer: According to the Diablo Wiki (here and here), you can not put a rune word in Wirt's Leg.
I only remember picking up a single socket Wirt's Leg. It may be that you are only able to pick up a Wirt's Leg with 1 socket, making it impossible to create a rune word. It may be that the developers have removed the ability for rune words to 'activate' on the item. Since one of the requirements in activating runewords is its application on a specific weapon, I would say it is the later.
Comment: I've found Wirt's Leg with 2 sockets before. Can also drop with 3
Answer: It is no longer possible to make a runeword in Wirt's Leg.  Wirt's Leg does drop in socketed versions (1, 2 or 3 sockets possible.)  In earlier versions (1.09, perhaps just 1.07) it was possible to make a runeword in Wirts Leg but not in the current version.


What do each symbol mean? (For exponentials)

Question: As you know, Clicker Heroes is an idle game all about exponential numbers and... A lot of waiting.
However, when the number gets big, they start representing them with symbols and not letters (for example, 500k = 500,000), and I'm seeing numbers like 71,668%.
Question:
What are the symbols used and their exponential equalivants?
For consistency sake, please also include the metric symbols; K = kilo for numbers in thousands.
Answer: If you use the webversion this is on the right side:
Legend of Large Numbers
1K  =   1,000   =   One Thousand
1M  =   1,000K  =   One Million
1B  =   1,000M  =   One Billion
1T  =   1,000B  =   One Trillion
1q  =   1,000T  =   One Quadrillion
1Q  =   1,000q  =   One Quintillion
1s  =   1,000Q  =   One Sextillion
1S  =   1,000s  =   One Septillion
1O  =   1,000S  =   One Octillion
1N  =   1,000O  =   One Nonillion
1d  =   1,000N  =   One Decillion
1U  =   1,000d  =   One Undecillion
1D  =   1,000U  =   One Duodecillion
1!  =   1,000D  =   One Tredecillion
1@  =   1,000!  =   One Quattuordecillion
1#  =   1,000@  =   One Quindecillion
1$  =   1,000#  =   One Sexdecillion
1%  =   1,000$  =   One Septendecillion
1^  =   1,000%  =   One Octodecillion
1&  =   1,000^  =   One Novemdecillion
1*  =   1,000&  =   One Vigintillion
A lot   >   1,000*  <   A lot
Comment: Actually.. Nevermind... What I was meant to say was: **"Strange. My game doesn't have 1& and up. After 1^, it's 1e+[60-something]"**
Comment: it looks pretty organized to me, how would you want to change that?
Answer: Here's a quick version I keep in a note:

1K=103 , 1M=106 , 1B=109 ,
1T=1012, 1q=1015, 1Q=1018,
1s=1021, 1S=1024, 1O=1027,
1N=1030, 1d=1033, 1U=1036,
1D=1039, 1!=1042, 1@=1045,
1#=1048, 1$=1051, 1%=1054,
1^=1057, 1&=1060, 1*=1063

I do this because don't find words like "Tredecillion," or knowing the basic sequence, as useful as knowing the order of magnitude.
You can quickly see why no one can easily memorize this list:
K, M, B, T follow metric then U.S. definitions, q:Q and s:S follow each other but d:D do not. O, N, and U don't have a pair. None of these letters are consistently ordered say by alphabet, only the !...* symbols have a knowable order if you use a US keyboard layout.


How to compute cumulative and one specific column in R?

Question: I have the data about sales by years and by-products, let's say like this:
Year <- c(2010,2010,2010,2010,2010,2011,2011,2011,2011,2011,2012,2012,2012,2012,2012)
Model <- c("a","b","c","d","e","a","b","c","d","e","a","b","c","d","e")
Sale <- c("30","45","23","33","24","11","56","19","45","56","33","32","89","33","12")
df <- data.frame(Year, Model, Sale)

Firstly I need to calculate the "Share" column which represents the share of each product within each year.
After I compute cumulative share like this:

In the 3rd step need to identify products that accumulate total sales up to 70% in the last year (2012 in this case) and keep only these products in the whole dataframe + add a ranking column (based on last year) and summarises all the rest of products as category "other". So the final dataframe should be like this:
Comment: What did you try so far?
Answer: This is a fairly complex data wrangling task, but can be achieved using dplyr:
library(dplyr)

df %>%
  mutate(Sale = as.numeric(Sale)) %>%
  group_by(Year) %>%
  mutate(Share = 100 * Sale/ sum(Sale),
         Year_order = order(order(-Share))) %>%
  arrange(Year, Year_order, by_group = TRUE) %>%
  mutate(Cumm.Share = cumsum(Share)) %>%
  ungroup() %>%
  mutate(below_70 = Model %in% Model[Year == max(Year) & Cumm.Share < 70]) %>%
  mutate(Model = ifelse(below_70, Model, 'Other')) %>%
  group_by(Year, Model) %>%
  summarize(Sale = sum(Sale), Share = sum(Share), .groups = 'keep') %>%
  group_by(Year) %>%
  mutate(pseudoShare = ifelse(Model == 'Other', 0, Share)) %>%
  arrange(Year, -pseudoShare, by_group = TRUE) %>%
  ungroup() %>%
  mutate(Rank = match(Model, Model[Year == max(Year)])) %>%
  select(-pseudoShare)
#> # A tibble: 9 x 5
#>    Year Model  Sale Share  Rank
#>   <dbl> <chr> <dbl> <dbl> <int>
#> 1  2010 a        30 19.4      2
#> 2  2010 c        23 14.8      1
#> 3  2010 Other   102 65.8      3
#> 4  2011 c        19 10.2      1
#> 5  2011 a        11  5.88     2
#> 6  2011 Other   157 84.0      3
#> 7  2012 c        89 44.7      1
#> 8  2012 a        33 16.6      2
#> 9  2012 Other    77 38.7      3

Note that in the output this code has kept groups a and c, rather than c and d, as in your expected output. This is because a and d have the same value in the final year (16.6), and therefore either could be chosen.
Created on 2022-04-21 by the reprex package (v2.0.1)
Comment: is it possible to add a rank column too?
Comment: @user15330237 yes, but it's even more complex. Do you need the rank to be the rank of the Models in the final year?
Comment: exactly, based on final year
Comment: @user15330237 see my update
Comment: I know it seems difficult but is it possible to do ranking based on real models and categorise 'other' as the last in the ranking? For instance to be a=1, a =2, other=3, instead of a=1, other=2, a =3 (according to last year)
Comment: @user15330237 but that's not what you have in your expected output. You want to change your expected output to something different now?
Comment: yes, only this ranking part
Answer: Year <- c(2010,2010,2010,2010,2010,2011,2011,2011,2011,2011,2012,2012,2012,2012,2012)
Model <- c("a","b","c","d","e","a","b","c","d","e","a","b","c","d","e")
Sale <- c("30","45","23","33","24","11","56","19","45","56","33","32","89","33","12")
df <- data.frame(Year, Model, Sale, stringsAsFactors=F)

years <- unique(df$Year)

shares <- c()
cumshares <- c()

for (year in years){
  extract <- df[df$Year == year, ]
  sale <- as.numeric(extract$Sale)
  share <- 100*sale/sum(sale)
  shares <- append(shares, share)
  cumshare <- rev(cumsum(rev(share)))
  cumshares <- append(cumshares, cumshare)

}

df$Share <- shares
df$Cumm.Share <- cumshares

df

gives
> df
   Year Model Sale     Share Cumm.Share
1  2010     a   30 19.354839 100.000000
2  2010     b   45 29.032258  80.645161
3  2010     c   23 14.838710  51.612903
4  2010     d   33 21.290323  36.774194
5  2010     e   24 15.483871  15.483871
6  2011     a   11  5.882353 100.000000
7  2011     b   56 29.946524  94.117647
8  2011     c   19 10.160428  64.171123
9  2011     d   45 24.064171  54.010695
10 2011     e   56 29.946524  29.946524
11 2012     a   33 16.582915 100.000000
12 2012     b   32 16.080402  83.417085
13 2012     c   89 44.723618  67.336683
14 2012     d   33 16.582915  22.613065
15 2012     e   12  6.030151   6.030151

I don't understand what you mean by step 3, how do you decide which products to keep?
Comment: as you see in Cum.Share column, e + d +c give you 67% of the share so <70%. Now I need to keep only these 3 (e ,d,c) and categorise/summarise a+b as 'other'


Implicit equation - $G(x,y)=0$

Question: I'm confused about some points in  implicit equation ...
From my recitation class   -

$G(x,y)=0$ provides  - $y=f(x)$ .
And $f'(x)=\frac{dy}{dx}$
and about $G'(x,y)=0$ we use  -

How would be look $f'(x)$ in case of the follow  implicit equation ? -
Answer: You have
$$G(x,y)=3x^7+2y^5-x^3+y^3-3=0 $$
so
$$\frac{\partial G}{\partial x}=21x^6-3x^2 $$
$$\frac{\partial G}{\partial y}=10y^4+3y^2 $$
therefore
$$\frac{dy}{dx}=-\frac{\frac{\partial G}{\partial x}}{\frac{\partial G}{\partial y}}=-\frac{21x^6-3x^2}{10y^4+3y^2} $$
Answer: I have usually seen this called an implicit function.  You are not guaranteed the ability to transform it into the form $y=f(x)$, but you can do implicit differentiation.  From $3x^7+2y^5-x^3+y^3-3=0$ you take a derivative with respect to $x$ to get $21x^6+10y^4y'-3x^2+3y^2y'=0, y'=-\frac{21x^6-3x^2}{10y^4+3y^2}$

Implicit equation - $G(x,y)=0$


Configure NFS server for PersistentVolume either via DNS or static ClusterIP

Question: I have a kubernetes cluster running on google container engine that defines a Pod running a NFS-Server, which I want to access in other Pods via various PersistentVolumes.
What is the best way to configure the NFS Service, if it is in the same cluster?
According to various documentation ive found its not possible to rely on kube-dns for this, because the node starting the kubernetes pod is not configured to use it as its DNS.
So this is out of question (and really does not work - ive tested it, with various different hostname/FQDN...)
apiVersion: v1
kind: PersistentVolume
metadata:
  name: xxx-persistent-storage
  labels:
    app: xxx
spec:
  capacity:
    storage: 10Gi
  nfs:
    path: "/exports/xxx"
    server: nfs-service.default.svc.cluster.local  # <-- does not work

I can start the NFS Server and check its ClusterIP via kubectl describe svc nfs-service and then hardcode its Endpoint-IP for the PV (this works):
apiVersion: v1
kind: PersistentVolume
metadata:
  name: xxx-persistent-storage
  labels:
    app: xxx
spec:
  capacity:
    storage: 10Gi
  nfs:
    path: "/exports/xxx"
    server: 10.2.1.7  # <-- does work

But this feels wrong - as soon as I need to recreate the NFS-Service ill get a new IP and i have to reconfigure all the PVs based on it.

What is the best-practice here? Im surprised i did not find any example for it, because i supposed thats quite a normal thing to do - isnt it?
Is it possible to set a kind of static IP for a service, so that i can rely on having always the same IP for the NFS service?
Answer: You are on the right track. To make sure that your Service is using a static IP just add clusterIP: 188.8.131.52 under the spec: section of the Service.
From the canonical example:

In the future, we'll be able to tie these together using the service names, but for now, you have to hardcode the IP.
Comment: Thank you - i was hoping I made something wrong and there is a more nicer solution available. Dont like the idea of the hardcoded IP, if I want to easily reuse the definition file between prod and testing for example


I have a static sub-domain for my site that holds the images/css/js and whenever I try and point the code to it....nothing workds

Question: I can't get anything to show up right.
This is the head of one of my pages:

<link type="text/css" rel="stylesheet" href="static.wkara.com/css/menu.css"  />

<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Home!</title>

<meta name="keywords" content="" />
<meta name="description" content="" />
<link rel="stylesheet" type="text/css" href="static.wkara.com/css/default.css"   />

The sub-domain points to a folder called static that is in the root of the website.

root

static (static.wkara.com points to here)

css

all the css stuff

When I link to the css stuff like this "static/css/blahh.css" it works though.
Answer: That's not a relative URL, so you need to specify a protocal.

Incorrect: static.wkara.com/css/menu.css
Correct: http://static.wkara.com/css/menu.css
Even better: //static.wkara.com/css/menu.css (Thanks Samus)

Some browsers may be "smart" enough to do it automatically, but I wouldn't count on it.

The logical reason for this is http://wkara.com/current/page/static.wkara.com/css/menu.css is a valid URL.  If you give a protocol (HTTP, FTP, etc.) it knows you're referring to an absolute location.
Comment: I've heard of a trick that is to use `//` only as protocol and let the browser figure it out, not sure how reliable it is but it's what people recomment when you have both http and https.
Comment: I added a note at the bottom with my guess as to "Why?"
Comment: @Samus_, yes, that's better.  I forgot about it, but I updated my answer.


QML change views on Click

Question: i'm working on a project with my team.
My job is to create a Gui with QML and C++ for an Embedded System.
I have for each View a qml file.
But now i want to navigate between them.
This mean when i'm clicking on a Button, the view should switch.
Every View will have a back button, so i could go back to my Main View.
Is this possible in qml?
If not i have to solve it with c++
Comment: You can do it with QT Stacked Widgets easily. Check this out, https://doc.qt.io/qt-6/qstackedwidget.html
Answer: You can create a class deriving from QDeclarativeView in C++ and use:
void setSource ( const QUrl & url )

to change the qml file that is currently displayed. You can than call this method multiple times when a button is clicked.

There is also a solution using QML only. Take a look at the Loader element:
 import QtQuick 1.0
 Item {
   width: 200; height: 200

   Loader { id: pageLoader }

   MouseArea {
     anchors.fill: parent
     onClicked: pageLoader.source = "Page1.qml"
   }
 }

Comment: You do not need to add Loader to each file. Its enough to have a main qml with one Loader and you can change its contents each time a button is clicked in each view. To pass data from loaded view to main qml you can call a method of an object in the main.
Comment: Thanks JuliusG for your answer, but i think with your version there should be in every View a Loader?
Or where the pageloader know that i mean it?
Comment: Thanks i have tested it :)
But i think the QDeclarativeView should be right for me
Comment: Thanks a ton @JuliusG your comment saved my day
Answer: Another option is to have a main qml where you instantiate those qml views, and you change between them using states.
Main {
  View1{id:viewid1}
  View2{id:viewid2}
  View3{id:viewid3}
  states: [
    State {
        name: ""
    },
    State {
        name: "view1"
        PropertyChanges {target: viewid1; state: "focused"}
    },
    State {
        name: "view2"
        PropertyChanges {target: viewid2; state: "focused"}
     ...
    }
  ]
}

The difference between these option and the one already presented is that this one is permanent, and the other charges your QML every time (which means parsing and instantiation...).
Comment: Another difference between this solution and @JuliusG 's solution is that this solution instantiates all the QML at startup while his solution only instantiates each QML page when the source gets changed. This could be helpful or harmful depending on your application needs.
Comment: Thanks for your answer :)
But i used JuliusGs answer, but yours look well too
Answer: One more example
import QtQuick 2.1
import QtQuick.Controls 1.1
import QtQuick.Window 2.1

ApplicationWindow {
    title: qsTr("My super app")
    width: 640
    height: 480

    Button {
        id: settingsButton
        x: 370
        y: 0
        text: qsTr("Settings")
        /* just change `visible` property by click */
        onClicked: {
            statusView.visible     = false
            settingsView.visible   = true
        }
    }

    Button {
        id: statusButton
        x: 171
        y: 0
        text: "Status"
        /* toggle */
        onClicked: {
            statusView.visible     = true
            settingsView.visible   = false
        }
    }

    Item {
        /* use id for access */
        id: statusView
        x: 0
        y: 50
        width: 640
        height: 430
        /* visible: true */

        Text {
            anchors.centerIn: parent
            text: "status"
        }
    }

    Item {
        id: settingsView
        x: 0
        y: 50
        width: 640
        height: 430
        /* invisible */
        visible: false

        Text {
            anchors.centerIn: parent
            text: "settings"
        }
    }
}

Comment: Thanks! The most pragmatic one :-)

QML change views on Click


table data reloading issue

Question: see below code, it removes object from array but it not reloading table
- (void)tableView:(UITableView *)aTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@" commitEditingStyle");
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        NSLog(@" commitEditingStyle Delete ");
        [self.arry removeObjectAtIndex:indexPath.row];
        [tableView reloadData];
    } else if (editingStyle == UITableViewCellEditingStyleInsert)
    {
        NSLog(@" commitEditingStyle Insert ");
        [self.arry insertObject:@"New Row" atIndex:[arry count]];
        [tableView reloadData];
    }
}

also i have [tableView reloadData] written in ViewWillAppear & ViewDidLoad but it not reloading.
TableView is added tothe ViewController through the storyboard & IBoutlet is added to .h file
Comment: You must either send your message to your outlet (if you have one i.e.  `self.tableView`) or directly to the tableview that called the delegate method: `[aTableView reloadData];` (notice the `a`)
Comment: From where you are getting the self.arry data ? Where are you adding that data ?
Comment: you check insert and remove both not work ??? for insert `[self.arry insertObject:@"New Row" atIndex:[arry count]+1];`
Comment: @iPatel:both are not working
Comment: create NSMutableArray in viewWillAppear Method
Comment: @Alladinian:yes ,now it is reloading ,what is that "aTableView"?
Comment: @RavindraBagale That is the name of your tableView instance that is passed to you on your delegate method (take a closer look at the method signature): `- (void)tableView:(UITableView *)aTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath`
Comment: @RavindraBagale I've also added this as an answer
Answer: - (void)tableView:(UITableView *)aTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle

forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
    [arryData removeObjectAtIndex:indexPath.row];
    [tblSimpleTable reloadData];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
    [arryData insertObject:@"Mac Mini" atIndex:[arryData count]];
    [tblSimpleTable reloadData];
}

}
use something like that
Answer: You must either send your message to your outlet (if you have one i.e. self.tableView) or directly to the tableview that called the delegate method: [aTableView reloadData]; (notice the a).
If you take a closer look at the method signature, you'll see that the tableView instance is passed to you as aTableView :
-(void)tableView:(UITableView *)aTableView...

table data reloading issue


How can I get working days given a date interval

Question: Given a date interval I need to get only working days without weekends and holidays.
Most of this non-working days are fixed (so I can store them inside an holidays table), but what about Easter?
What's the best and performant way to generate a dynamic calendar using a TSQL function?
Comment: Which version of sql server do you use? Functions change in 2012
Comment: @Kuzgun SQL Server 2008
Answer: The best you can do for Easter is store the future dates in a configuration file.  You can get ta list of them here: http://en.wikipedia.org/wiki/Easter.  Don't try and calculate it yourself.  The list at that URL goes up to 2021.  Plenty of time for you to patch your application at a later date :)


Activity Background based on weather image from flickr like Yahoo weather

Question: I want to show images from the current city based on weather as android app's background just like Yahoo! weather does.
Is there an API to get such images? I have been through Yahoo weather's developer resources and got to know that they don't provide any such feature.
update
This is not duplicate of how to get 7 day or one day data, I am asking for how to get Images that are from local places and according to weather?
Comment: Minus ONE for What? Can you explain? I am not asking about getting weather data!
Comment: Bah, silly me! Apologies!
Answer: Images on the Yahoo Weather app are aggregated from Flickr. Yahoo provides a Flickr API which you can plug into.
see https://code.google.com/p/flickrj-android/


Monit not send alert message and give error ' Alert handler failed, retry scheduled for next cycle'

Question: We use monit to monitor server like (space usage ,cpu usage etc). When resource limit exceed , monit not deliver alert message and give following error- Sendmail error: 534-5.7.9 Please log in with your web browser and then try again.
Alert handler failed, retry scheduled for next cycle.
Answer: Your SMTP server is rejecting monit connection, and doesn`t send mail
<code>Sendmail error: 534-5.7.9 Please log in with your web browser and then try again.
</code>
You should configure a SMTP relay server that trusts you and don't ask you for login from the server IP
Answer: I had same issue. Problem was, as Raul commented before, the SMTP. In my case, the problem was the Postfix.
Because I just wanted SMTP to send the emails from monit it was ok for me to remove default Postfix installation and installed again:
# apt-get remove --purge postftix
# apt-get install postfix
then I choose "Internet Site"
Automatically Monit was able to send mails, no more errors in var/log/monit.log
Hope it helps


How can I minimize Gnome GUI?

Question: Applications have all kind of clutter such as Games that I do not need when studying. How can I remove them? I mean the panel with Applications, Places and System.
Answer: Which version are you running?  I'm running 10.04, and I can right-click on any of the menus (Applications, Places, or System) and see the option to "Edit Menus."
That gives me a window with options to hide certain entries via checkbox.
Comment: +1 Thank you! Worked well, you need to mouse-right-click the panel.

How can I minimize Gnome GUI?


Are there any methods to get fast exp in Construction, Prayer, and Thieving without a high money cost?

Question: Construction, Prayer, and Thieving skills usually take a long time to level up. Is there an easy, fast, and cheap way to level these skill up?
By the way my levels in those are Construction:49, Prayer:32, and Thieving:43.
Comment: It depends... how cheap are you looking for here?
Answer: Construction
There is no easy, fast or cheap way to level this skill.  Getting construction experience requires too many steps, and many of those steps have a built in gold cost, since the skill was partially designed as a "cash sink" for players with large amounts of gold.  Consider all the steps required to train construction:

Obtain wood either through chopping down trees (takes time) or buying from other players (takes gold).
Obtain nails either by making them yourself (takes a ton of time) or buying them from a vendor (takes a little bit of gold).
Turn the wood into planks, which always takes a substantial amount of gold and can take a lot of time, if you make the run to the sawmill yourself.  Alternatively, you can pay even more gold to have your servant make the run to the sawmill for you.
Construct the items for experience (takes time), though once again, you can trade money for time by paying your servant to go to the bank.

Unfortunately, training construction is going to take time and it is going to take gold.  There is no way around it.
Prayer
Training prayer can be done for cheap, but that takes a lot of time, or it can be done quickly, but that takes a lot of gold.
If you decide to train prayer quickly, you need to be willing to pay a lot of money for the high level bones, and you will likely need to pay someone for access to a high level altar in their house, unless you are lucky enough to have one in your own house (or have a good friend with one).  With this method, you can train as quickly as you can make bank runs to and from the house; either by yourself or by paying your servant.
If you decide to train prayer cheaply, you need to be willing to spend the time obtaining bones, which means a lot of combat.  The upside to this method is that you get to train your combat skills at the same time, but it is not fast.  Then you need to use the extremely slow Ectofuntus process to turn the bones into prayer experience.  As this requires grinding all the bones, obtaining all the slime and a lot of walking, it can take a very long time.
Thieving
I'm not sure why you've included this skill in this question, as it is extremely easy, fast and cheap to gain experience in thieving.  You do not have to pay a thing to train thieving - all you have to do is stand in one spot and repeatedly steal from someone.  In fact, thieving will earn you money as you train it - it won't earn you a lot, but something is better than nothing.
It still takes time to level the skill, since the exponential experience required to level means that you have to steal a ton of stuff to get to level 99, but since there aren't any bank runs or secondary steps, levelling isn't going to get any faster than this skill.
Also, thieving has a couple of decent mini-games, Pyramid Plunder and Sorceress' Garden, that give out really good thieving experience and are fun to play, so you can actually enjoy yourself while grinding up the levels.
Answer: As of 3 January 2013, the Distraction and Diversion God Statues was released. Every month (resets on the 1st), you can build a statue devoted to a god in four different locations:

Lumbridge - Located west of the cow pen - Commander Zilyana
Taverly - East of the Stone Circle - Juna
Canifis - Right next to the Canifis Lodestone - K'ril Tsutsaroth
Yanille - South of the Yanille Lodestone - General Graardor

After building each statue, you will get a certain amount of experience (depending on your Construction level) and either prayer experience or slayer experience. If you build a statue devoted to the god in the area, you will get prayer experience; otherwise you will get slayer experience for killing a god fanatic that will appear.
For example, in Lumbridge, if you build a Saradomin statue, you will get prayer experience. However, building a Zamorak, Guthix, or Bandos statue, you will have to kill a fanatic for slayer experience.
If you want some prayer experience, you can go to The Nexus which was released on 14 May 2013. However, it's typically aimed at lower prayer levels (Your prayer level is perfect for it).

As for thieving, well, that doesn't cost any direct money. Pyramid Plunder is a great source of experience if you are heading for 99.


Mathematical analysis - problem with calculating limit

Question: I need to calculate one limit and I have big problems. I would be very thankful if someone could help me...
This is the limit I need to find:
$$
\lim_{n\rightarrow\infty}\frac{2^n + n\sin{n}}{\log_2{n} + e^n}
$$
Any hint/explanation would be very helpful!
Comment: Are $n$ the variable of your functions? If the variable is $n$, then the limit is the same expression, because $n$ is a constant recpect to $x$.
Answer: $$0\le\lim_{n\to\infty}\frac{2^n +n\sin n}{\log_2n+e^n} \le \lim_{n\to\infty}\frac{2^n +n}{e^n}=\lim_{n\to\infty}\left(\frac{2}{e}\right)^n+\lim_{n\to\infty}\frac{n}{e^n}=0+0=0.$$
Comment: Thank you very much! That was really helpful!
Comment: I forgot, I'm sorry... Thank you very much again!
Answer: hint: $0 < f(n) < 2\cdot \dfrac{2^n}{e^n}= 2\cdot \left(\dfrac{2}{e}\right)^n, n \ge N_0$


loading heavy js widgets causing the browser to stop responding

Question: I'm using an external js heavy widgets into my page which causing the browser to stop responding.
i want to create a delay between them to give time to loading by using setTimeout. But still load at the same time. I'm looking for a way to insert and load the widgets one by one.
function setWidgets(){
  var div = document.getElementById("content");
  var subDiv = div.getElementsByTagName('div');
  var id;
  var arr = [];

  for(var i = 0; i < subDiv.length; i++) {
    var elem = subDiv[i];
    if(elem.className == "info" ) {
      setTimeout( setWidget(elem) , 600);
    }
  }
}

function setWidget(elem) {
  var para = elem.innerHTML.split(",");
  var divId = para[2];
  var widget = getWidget(para);
  var elemnt = document.getElementById(divId);

  $(elemnt).html(widget);
}

function getWidget(para){

  var pair = para[0];
  var frame = para[1];
  var elemId = para[2];
  var widget = [];

  widget.push(
    '


express.session undefined in typescript

Question: I am very new to typescript/javascript, I am trying to build backend rest apis with session
following is app.ts file
import express from "express";
import { applyMiddleware, applyRoutes } from "./utils";
import routes from "./services";

const app = express();

    var ses= {
        secret: "secret_session",
        resave: true,
        saveUninitialized: true,
        cookie: { maxAge: 3600000,secure: false, httpOnly: true
}
if (app.get('env') === 'production') {
    app.set('trust proxy', 1)
    ses.cookie.secure = true
}

app.use(session(ses));

applyRoutes(routes, app);

I have started the server and applied the middlewares for error handling but those are not related to question in my opinion so I'm not adding code for it. Following is my routes.ts code where I'm trying to set the session.
import { Request, Response } from "express";
import { getAll, getByKeyword, addNewProduct } from "./productControllers";
{
path: "/api/v1/getAllProducts",
method: "get",
handler: [
  (req: Request, res: Response) => {
    getAll()
      .then((row: any) => {
       var sess = req.session;
       sess.views = 1;
        res.status(200).json({ data: row });
      })
      .catch(err => {
        res.json({
          message: err
        });
      });
  }
]
}

I'm getting error at sess.views = 1;
I have tried the suggested questions before asking it, none of them were of any help to me.
EDIT:
I have created an index.ts
import searchRoutes from "./products/routes";

export default [...searchRoutes];

I have another util class
export const applyRoutes = (routes: Route[], router: Router) => {
  for (const route of routes) {
    const { method, path, handler } = route;
    (router as any)[method](path, handler);
  }
}

Comment: Reading `express-session` docs I've encounter the following, which may be relevant:

"Be careful when using this setting if the site is available both as HTTP and HTTPS, as once the cookie is set on HTTPS, it will no longer be visible over HTTP".
Comment: What is the error?
Comment: @hurricane it gives object is possibly undefined for sess variable
Comment: Where did you define your routes? You should define your routes after `app.use(session(ses))`. Could you update your code to show us where do you use routes.ts?
Comment: It is good but still, I am not able to see do you run applyRoutes(routes, app) after app.use(session(ses)); or not? Where does the`app` variable coming from?
Answer: You are using an interface which is Request for express.js. But it doesn't have type definition for session. So typescript throws a compile error. To solve it you need to define session type under Request interface.
You could define a session.d.ts file under your project. And create required types & interfaces. Like:
declare global {
  namespace Express {
    interface Request {
      session?: Session;
      sessionID?: string;
    }
  }
}

interface Session{
  mySessionVarible:string
}

But the good thing is we have DefinitilyTyped project which you can find many type definitions. This needs to solve your compile problem.
npm install --save-dev @types/express-session

And don't forget to change your import for Request.
import { Request, Response } from "@types/express-session";

Comment: Just try to install @types/express-session without writing any code.
Comment: I'm sorry but it's not working even if I changed `declare global` to `export declare module global` it is not able to find the module
Comment: I have installed it.
Comment: @rookieDeveloper use `import { Request, Response } from "@types/express-session";`
Comment: `Module '"../../../node_modules/@types/express-session"' has no exported member 'Response'.`
Comment: @hurricane Are you providing wrong information ? I have same issue as @rookieDeveloper. `import { Request, Response } from "@types/express-session";` produces `Module '"../../../node_modules/@types/express-session"' has no exported member 'Response'.`
Comment: I'm having the same issue any did anyone managed to figure it out?
Comment: @tosh installing @types/express-session would help.

express.session undefined in typescript


having problem to shift into GUI from virtual terminal

Question: I purged python3 due to some problems. After doing that, it removed a lot of packages.I installed Firefox and visual studio then I restarted the laptop but it switch into the virtual terminal. I searched many times but could not find the solution. I tried sudo apt install --reinstall ubuntu-desktop but it shows
package have unmet dependencies , and unable to correct problem, you held broken package

Please help me I am in trouble.
Comment: If you did remove `python3`, quite a lot of built-in Ubuntu tools will no longer work, so repairs will be very manual (eg. `dpkg` will work, but you may find `apt` and like front ends that sit above & automate download & install via `dpkg` no longer work). The obvious first step is `sudo apt -f install` but I suspect you'll keep finding normal fix tools don't work as needed unless `python3-minimal` is installed.  A re-install may be a faster fix
Answer: Since python3 is a requirement for almost anything in Ubuntu I would advice to reinstall your system. You can do that WITHOUT picking the format option in the "something else" part of setting up partitions. Only mount your partitions. It will overwrite all system related files and packages but leave your personal files alone.
Mind to make sure the backups you have can be restored before attempting this. In case you pick the wrong setup during the re-install.


Unable to install 11.10 to a new OCZ Agility 3 SSD

Question: I know the discussion here where they are not getting the same error as me.
I use Lenovo ThinkPad X60.
The default partition table: sd1 ext4 53.91GB, sd2 extended 1.99GB and sd5 swap 1.99GB.
I get Input/output error during read on/dev/sda` when trying to install from live CD -mode and when trying to install directly. I get the error normally at the stage of choosing time zone or very last at choosing the keyboard layout. Then there is the box with buttons: Back, Ignore and Continue. None of them enable the procedure to go forward, so I need to cancel it.
How can you install Ubuntu to an SSD?
Answer: SSD contains more electronics than an usual hdd, be sure that the firmware of your SSD is up to date otherwise this can be considered "a normal behaviour"; from this point of view the standard hdd are way more reliable than an SSD.
check the download page for your product http://www.ocztechnology.com/ocz-agility-3-sata-iii-2-5-ssd.html
Comment: The easiest way to solve the problem at this time is to buy Intel's  quality SSD drives, since OCZ has severe problems in heat management. The sleep of OCZ is just awful in relation to Intel.


rake db:create:all FATAL : password authentication failed

Question: I am trying to follow this railscast tutorial. Now I am in the step, where you create the database with rake db:create:all, but I got this error message :
FATAL:  password authentication failed for user aldila

I made the user aldila through pgAdmin, by right-clicking the login role and add user aldila with password.
So, here is my database.yml :
development:
   adapter: postgresql
   host: localhost
   encoding: unicode
   database: my_app_development
   pool: 5
   username: aldila
   password: *mypass*

test:
   adapter: postgresql
   host: localhost
   encoding: unicode
   database: my_app_test
   pool: 5
   username: aldila
   password: *mypass*

production:
   adapter: postgresql
   host: localhost
   encoding: unicode
   database: my_app_production
   pool: 5
   username: aldila
   password: *mypass*

Here is my pg_hba.conf
# TYPE  DATABASE        USER            ADDRESS                 METHOD

# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
#host    replication     postgres        127.0.0.1/32            md5
#host    replication     postgres        ::1/128                 md5

Maybe there is something's wrong with the installing of PostreSQL, because if I type
psql --version on my command, this is what I got :
'psql' is not recognized as an internal or external command,
operable program or batch file.

But I have no idea what went wrong. I install it from here and pick download the installer from EnterpriseDB for all supported versions.
I know there are already similar questions like this, but I follow this one and this one, but I still get the same error message. I would be really appreciated, if anyone could help. Thanks
Comment: Are you using `devise`? Maybe you forgot to add `password_confirmation`.
Comment: No, I don't. Do you mean to create the login role for database? I used pgAdmin and add login role through pgAdmin, if that's what you mean.
Comment: What OS are you using?
Answer: Your postgresSQL password didn't match your database.rb's password.. it depends on what environment you are using..


Lines not disappearing after being drawn in OpenGL

Question: I am creating a Bezier curve tool in OpenGL and every time my program draws something in motion with cursor coordinates I see the previously drawn lines on the screen for a second or two before they disappear as shown below:

This is how it should look:

Below are my mouse motion functions and render function. I am using a double buffer and swap buffers each frame.
void passiveMotion(int x, int y)
{
    Point Cursor;
    Cursor.setxy(x, SCREEN_HEIGHT - y);
    if ((pointsVector[0].x != NULL) && (pointsVector[0].y != NULL))
    {
        drawLine(pointsVector[points], Cursor);
    }
    glutSwapBuffers();
}

void motion(int x, int y)
{
    Point Cursor;
    Cursor.setxy(x, SCREEN_HEIGHT - y);
    drawLine(pointsVector[points], Cursor);
    Point reverseCursor;
    reverseCursor.x = (2 * pointsVector[points].x) - Cursor.x;
    reverseCursor.y = (2 * pointsVector[points].y) - Cursor.y;
    drawLine(pointsVector[points], reverseCursor);

    vector<Point> finalPoints = final4Points();

    Point p1;
    p1.setxy(pointsVector[0].x, pointsVector[0].y);

    if ((finalPoints[1].x != NULL) && (finalPoints[1].y != NULL))
    {
        // draw bezier curve
        for (float i = 0; i < 1; i += 0.01)
        {
            // The Green Lines
            int xa = getPt(finalPoints[0].x, finalPoints[1].x, i);
            int ya = getPt(finalPoints[0].y, finalPoints[1].y, i);
            int xb = getPt(finalPoints[1].x, reverseCursor.x, i);
            int yb = getPt(finalPoints[1].y, reverseCursor.y, i);
            int xc = getPt(reverseCursor.x, finalPoints[3].x, i);
            int yc = getPt(reverseCursor.y, finalPoints[3].y, i);

            // The Blue Line
            int xm = getPt(xa, xb, i);
            int ym = getPt(ya, yb, i);
            int xn = getPt(xb, xc, i);
            int yn = getPt(yb, yc, i);

            // The Black Dot
            int x2 = getPt(xm, xn, i);
            int y2 = getPt(ym, yn, i);

            Point p2;
            p2.setxy(x2, y2);

            drawLine(p1, p2);
            p1 = p2;
        }
    }
    glutSwapBuffers();
}

void myDisplay()
{
    glClear(GL_COLOR_BUFFER_BIT);
    for (int i = 1; i < points; i++)
    {
        // draw main line & dot
        glColor3f(255, 0, 0);
        drawDot(pointsVector[i]);
        glColor3f(0, 0, 0);
        drawLine(pointsVector[i], pointsVector[i + 1]);

        // draw tangent lines and tangent dots
        glColor3f(0, 255, 0);
        drawLine(controlPoints[i + 1], reverseControlPoints[i + 1]);
        glColor3f(0, 0, 255);
        drawDot(controlPoints[i + 1]);
        drawDot(reverseControlPoints[i + 1]);

        vector<Point> finalPoints = final4Points();

        Point p1;
        p1.setxy(pointsVector[0].x, pointsVector[0].y);

        if((finalPoints[2].x != NULL) && (finalPoints[2].y != NULL))
        {
            // draw bezier curve
            for (float i = 0; i < 1; i += 0.01)
            {
                // The Green Lines
                int xa = getPt(finalPoints[0].x, finalPoints[1].x, i);
                int ya = getPt(finalPoints[0].y, finalPoints[1].y, i);
                int xb = getPt(finalPoints[1].x, finalPoints[2].x, i);
                int yb = getPt(finalPoints[1].y, finalPoints[2].y, i);
                int xc = getPt(finalPoints[2].x, finalPoints[3].x, i);
                int yc = getPt(finalPoints[2].y, finalPoints[3].y, i);

                // The Blue Line
                int xm = getPt(xa, xb, i);
                int ym = getPt(ya, yb, i);
                int xn = getPt(xb, xc, i);
                int yn = getPt(yb, yc, i);

                // The Black Dot
                int x2 = getPt(xm, xn, i);
                int y2 = getPt(ym, yn, i);

                Point p2;
                p2.setxy(x2, y2);

                drawLine(p1, p2);
                p1 = p2;
            }
        }
    }
    glutSwapBuffers();
}

Comment: Your function "passive_motion" is calling drawing functions and then glutSwapBuffers, without a call to "glClear", that is the origin of your trails (drawing without clearing buffer). As a suggestion, I would decouple input reading and rendering. E.g. Render everything in myDisplay and in motion() and passiveMotion() cache the mouse input values and deal with them in myDisplay when it's time to draw.
Comment: As suggested I would only have 1 rendering function (a rendering function in this case is something that clears the render buffer, draws to it and then calls some kind of present() function to display it). If you insist on making your input handling functions into rendering functions (again, not recommended) then you need to replicate how myDisplay() works by putting the glClear at the start of the function. However the graphics you drew in myDisplay will be destroyed by the graphics drawn in motion(), this is why it's a bad idea to couple input and rendering so tightly as in your example.
Comment: I explained why that is. I do not recommend your current strategy of rendering things in input functions. Store the input values into variables and move whatever it was you wanted to draw inside into a single render function.
Comment: Also, having all the drawing code coming from a single call means you can composite things correctly (draw in correct order). The temporary line section which is currently drawn inside motion() can be correctly drawn after the glClear and the bezier curve so that it appears on top of it.
Comment: At what line should I call `glClear()`? I will look into implementing those suggestions, thank you!
Answer: Although not ideal after reading PaulHK's answer and solution in the coments I decided to call glClear(COLOR_BUFFER_BIT) at the start of the passive motion function, motion function, and display function. I then iterate through my points variable starting at i = 1; (this is very specific to my code) and draw all geometry I was having trouble with in the loop. This works perfectly and is fast. Based on mouse movement each time there is a callback I draw the entire geometry for each mouse function. glClear(COLOR_BUFFER_BIT) clears the screen each frame.
void passiveMotion(int x, int y)
{
    glClear(GL_COLOR_BUFFER_BIT);
    Point Cursor;
    Cursor.setxy(x, SCREEN_HEIGHT - y);
    if ((pointsVector[0].x != NULL) && (pointsVector[0].y != NULL))
    {
        drawLine(pointsVector[points], Cursor);
    }

    for (int i = 1; i < points; i++)
    {
        // draw main line & dot
        glColor3f(255, 0, 0);
        drawDot(pointsVector[i]);
        glColor3f(0, 0, 0);
        drawLine(pointsVector[i], pointsVector[i + 1]);

        // draw tangent lines and tangent dots
        glColor3f(0, 255, 0);
        drawLine(controlPoints[i + 1], reverseControlPoints[i + 1]);
        glColor3f(0, 0, 255);
        drawDot(controlPoints[i + 1]);
        drawDot(reverseControlPoints[i + 1]);

        vector<Point> finalPoints = final4Points();

        Point p1;
        p1.setxy(pointsVector[0].x, pointsVector[0].y);

        if ((finalPoints[2].x != NULL) && (finalPoints[2].y != NULL))
        {
            // draw bezier curve
            for (float i = 0; i < 1; i += 0.01)
            {
                // The Green Lines
                int xa = getPt(finalPoints[0].x, finalPoints[1].x, i);
                int ya = getPt(finalPoints[0].y, finalPoints[1].y, i);
                int xb = getPt(finalPoints[1].x, finalPoints[2].x, i);
                int yb = getPt(finalPoints[1].y, finalPoints[2].y, i);
                int xc = getPt(finalPoints[2].x, finalPoints[3].x, i);
                int yc = getPt(finalPoints[2].y, finalPoints[3].y, i);

                // The Blue Line
                int xm = getPt(xa, xb, i);
                int ym = getPt(ya, yb, i);
                int xn = getPt(xb, xc, i);
                int yn = getPt(yb, yc, i);

                // The Black Dot
                int x2 = getPt(xm, xn, i);
                int y2 = getPt(ym, yn, i);

                Point p2;
                p2.setxy(x2, y2);

                drawLine(p1, p2);
                p1 = p2;
            }
        }
    }

    glutSwapBuffers();
}

void motion(int x, int y)
{
    glClear(GL_COLOR_BUFFER_BIT);

    Point Cursor;
    Cursor.setxy(x, SCREEN_HEIGHT - y);
    drawLine(pointsVector[points], Cursor);
    Point reverseCursor;
    reverseCursor.x = (2 * pointsVector[points].x) - Cursor.x;
    reverseCursor.y = (2 * pointsVector[points].y) - Cursor.y;
    drawLine(pointsVector[points], reverseCursor);

    vector<Point> finalPoints = final4Points();

    Point p1;
    p1.setxy(pointsVector[0].x, pointsVector[0].y);

    if ((finalPoints[1].x != NULL) && (finalPoints[1].y != NULL))
    {
        // draw bezier curve
        for (float i = 0; i < 1; i += 0.01)
        {
            // The Green Lines
            int xa = getPt(finalPoints[0].x, finalPoints[1].x, i);
            int ya = getPt(finalPoints[0].y, finalPoints[1].y, i);
            int xb = getPt(finalPoints[1].x, reverseCursor.x, i);
            int yb = getPt(finalPoints[1].y, reverseCursor.y, i);
            int xc = getPt(reverseCursor.x, finalPoints[3].x, i);
            int yc = getPt(reverseCursor.y, finalPoints[3].y, i);

            // The Blue Line
            int xm = getPt(xa, xb, i);
            int ym = getPt(ya, yb, i);
            int xn = getPt(xb, xc, i);
            int yn = getPt(yb, yc, i);

            // The Black Dot
            int x2 = getPt(xm, xn, i);
            int y2 = getPt(ym, yn, i);

            Point p2;
            p2.setxy(x2, y2);

            drawLine(p1, p2);
            p1 = p2;
        }
    }

    for (int i = 1; i < points; i++)
    {
        // draw main line & dot
        glColor3f(255, 0, 0);
        drawDot(pointsVector[i]);
        glColor3f(0, 0, 0);
        drawLine(pointsVector[i], pointsVector[i + 1]);

        // draw tangent lines and tangent dots
        glColor3f(0, 255, 0);
        drawLine(controlPoints[i + 1], reverseControlPoints[i + 1]);
        glColor3f(0, 0, 255);
        drawDot(controlPoints[i + 1]);
        drawDot(reverseControlPoints[i + 1]);

        vector<Point> finalPoints = final4Points();

        Point p1;
        p1.setxy(pointsVector[0].x, pointsVector[0].y);

        if ((finalPoints[2].x != NULL) && (finalPoints[2].y != NULL))
        {
            // draw bezier curve
            for (float i = 0; i < 1; i += 0.01)
            {
                // The Green Lines
                int xa = getPt(finalPoints[0].x, finalPoints[1].x, i);
                int ya = getPt(finalPoints[0].y, finalPoints[1].y, i);
                int xb = getPt(finalPoints[1].x, finalPoints[2].x, i);
                int yb = getPt(finalPoints[1].y, finalPoints[2].y, i);
                int xc = getPt(finalPoints[2].x, finalPoints[3].x, i);
                int yc = getPt(finalPoints[2].y, finalPoints[3].y, i);

                // The Blue Line
                int xm = getPt(xa, xb, i);
                int ym = getPt(ya, yb, i);
                int xn = getPt(xb, xc, i);
                int yn = getPt(yb, yc, i);

                // The Black Dot
                int x2 = getPt(xm, xn, i);
                int y2 = getPt(ym, yn, i);

                Point p2;
                p2.setxy(x2, y2);

                drawLine(p1, p2);
                p1 = p2;
            }
        }
    }
    glutSwapBuffers();
}


I want to create a database using SQLiteOpenHelper but i am facing some problems

Question: I have created a sub class (DatabaseHelper) of SQLiteOpenHelper Class.Its has a constructor and two overriden methods
 public DatabaseHelper(Context context) {
            super(context, dbName, null,33);
            // TODO Auto-generated constructor stub
        }
public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL("CREATE TABLE "+ quizTable +"("+quizCol1+" INTEGER PRIMARY KEY,"+
                quizCol2+" TEXT,"+ quizCol3 +" TEXT,"+ quizCol4 +" INTEGER," + quizCol5 + " DATETIME )");

        db.execSQL("CREATE TABLE "+ questionTable +"("+questionCol1+" INTEGER PRIMARY KEY,"+
                questionCol2+" INTEGER,"+ questionCol3 +" TEXT,"+ questionCol4 +" TEXT," + questionCol5 + " TEXT," +
                questionCol6 + " TEXT," + questionCol7 +" TEXT," + questionCol8 +" TEXT)");

        db.execSQL("CREATE TABLE "+ playedQuizzes +"("+playedQuizCol1+" INTEGER PRIMARY KEY,"+
                playedQuizCol2+" TEXT,"+ playedQuizCol3 +" TEXT,"+ playedQuizCol4 +" TEXT," +
                playedQuizCol5 + " TEXT)");
        System.out.println("this is onCreate method");
        InsertQuiz();
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS "+questionTable);
        db.execSQL("DROP TABLE IF EXISTS "+playedQuizzes);

        onCreate(db);
    }

In my Activity subclass i have called the constructor of above class using
 public void onStart(){
        try{
            super.onStart();
             dbHelper = new DatabaseHelper(this);
        }catch(Exception ex){
            CatchError(ex.toString());
        }
    }

But when i run my Activity class and open my DDMS perspective then i did not find any database created under /data/data/
Is there something wrong with my knowlege or my code? If yes please tell me.
Comment: follow the link to clear your concepts about android database  http://hackaday.com/2010/07/21/android-development-101-part-3introduction-to-databases/
Answer: In your code you didn't open the database....
to create, write or open database getWritableDatabase()
or to create & open the database getReadableDatabase() is necessory.....
Answer: From the documentation of the SQLiteOpenHelper class:

Create a helper object to create, open, and/or manage a database. This
  method always returns very quickly. The database is not actually
  created or opened until one of getWritableDatabase() or
  getReadableDatabase() is called.

So the database doesn't get created before not calling getWritableDatabase() or getReadableDatabase().


Escape single quotes in JDBC (getting error: You have an error in your SQL syntax ...)

Question: I'm trying to insert data into mysql using jdbc. I have something like this:
    Connection conn = DriverManager.getConnection(urlDB, userDB, passwordDB);

    String postTitle = "Post title";
    String postContent = "A Linux's distributions";

    String sql = "INSERT INTO posts VALUES ( '"+postTitle+"', '"+postContent+"')";
    PreparedStatement statement = conn.prepareStatement(sql);
    statement.executeUpdate();
    conn.close();

But I'm getting an error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's

As far as I know the prepareStatement method should escape single quotes (Мaybe I'm wrong). I'll be glad for any suggestions.
Comment: you got only these 2 fields in table??
Comment: Why are you using a prepared statement without using the benefits (parametrized queries). Your current query is prone to SQL injection.
Comment: @AnilOlakkal No, I have a lot of fields in the table
Answer: To use prepared statements correctly, you need to use parameter placeholders (?) and set the values on the statement. This will automatically give you protection against SQL injection.
You need to change your code to:
String sql = "INSERT INTO posts VALUES (?, ?)";
try (PreparedStatement statement = conn.prepareStatement(sql)) {
    statement.setString(1, postTitle);
    statement.setString(2, postContent);
    statement.executeUpdate();
}

See also JDBC Basics - Using Prepared Statements for examples of how to use PreparedStatement.
I have also changed your code to use try-with-resources, as this will always close the statement correctly (even if an exception occurs), which the code in your question does not.
Note that it would be better if you explicitly specify the columns you are inserting to. This protects your code against columns changing order or new - optional - columns added:
INSERT INTO posts(title, content) VALUES (?, ?)

Answer: You shouldn't use concatenation for inserting parameter values in a SQL query. Use question marks and set* methods. This will ensure escaping.
PreparedStatement pstmt = con.prepareStatement("UPDATE EMPLOYEES SET SALARY = ? WHERE ID = ?");
pstmt.setBigDecimal(1, 153833.00)
pstmt.setInt(2, 110592)

See the docs: https://docs.oracle.com/javase/8/docs/api/java/sql/PreparedStatement.html
Answer: replace
String sql = "INSERT INTO posts VALUES ( '"+postTitle+"', '"+postContent+"')";

with
String sql = "INSERT INTO posts VALUES ( '"+postTitle.replace("'","''")+"', '"+postContent.replace("'","''")+"')";

Comment: This is not the right way to use a prepared statement.


Can I disable ViewCell.ContextActions based on a condition

Question: Hi I using a Xamarin Forms ListView and I want to know if I can disable the Context Actions based on a certain binding or in the code behind.
I am using one GroupedListView for the whole application but it displays different data based on what the user is doing. There is a "Manage your Favorites" feature where I want the user to be able to swipe-to-delete on iOS or long-press on android to remove a ListItem, but I do not want this behavior if the list is displaying some search result or something else
<ViewCell.ContextActions>
    <MenuItem Text="Delete" IsDestructive="true" CommandParameter="{Binding .}" Command="{Binding Path=BindingContext.OnDeleteCommand, Source={x:Reference Name=ListViewPage}}"/>
</ViewCell.ContextActions>

This did not disable it...
<ViewCell.ContextActions IsEnabled="false"> //This IsEnabled does nothing
    <MenuItem Text="Delete" IsDestructive="true" CommandParameter="{Binding .}" Command="{Binding Path=BindingContext.OnDeleteCommand, Source={x:Reference Name=ListViewPage}}"/>
</ViewCell.ContextActions>

How can I disable the ContextActions? I dont wan't the user to always be able to swipe
Answer: For what I wanted to achieve I did the following...
In the XAML
<ViewCell BindingContextChanged="OnBindingContextChanged">

In the code behind
private void OnBindingContextChanged(object sender, EventArgs e)
{
    base.OnBindingContextChanged();

    if (BindingContext == null)
        return;

    ViewCell theViewCell = ((ViewCell)sender);
    var item = theViewCell.BindingContext as ListItemModel;
    theViewCell.ContextActions.Clear();

    if (item != null)
    {
        if (item.ListItemType == ListItemTypeEnum.FavoritePlaces
           || item.ListItemType == ListItemTypeEnum.FavoritePeople)
        {
            theViewCell.ContextActions.Add(new MenuItem()
            {
                Text = "Delete"
            });
        }
    }
}

Based which type of list item we are dealing with, we get to decide where to place the context actions
Comment: Don't call `base.OnBindingContextChanged`. That's for the page's binding context. This is an event handler, not a virtual method override.
Comment: I was young and reckless. It was a different time in my life
Answer: There are a couple of ways to go about this.

You can remove the MenuItem form the ContextActions based on your conditions. This cannot be done by pure XAML, you're going to have to do some code-behind.
Another option is to look at the DataTemplateSelector. This lets you select a template for your ViewCell (or Cells) at runtime. In that template you can choose to add the ContextActions or not.
Comment: Thank you for your help, I looked into the DataTemplateSelector and it looks like a good solution to my problem. I found another way to do this by using 'BindingContextChanged' on the ViewCell
Comment: @GeraldVersluis can i help with  please https://stackoverflow.com/questions/61370263/how-delete-an-menu-item
Answer: Simply disabling the cell works, but for Android only not iOS. Tested with a Xamarin Forms (2.0.5782) project on both iOS and Android.
<ViewCell IsEnabled="false">

Notice it is on the ViewCell and not the ViewCell.ContextActions like you have in your sample.
Comment: But you can not just disabled it as there is a condition to check
Comment: Xamarin Forms 3.6.x throws an exception if you try to set or bind IsEnabled


Ubuntu, Windows 7 and virtualization

Question: I have a Windows 7 and Ubuntu 12.04 installed on my machine.
I'd like to know if it's possible to start my Windows 7 from WITHIN an opened Ubuntu session.
The same way I would open a virtual machine with Virtual Box, but without having to create a virtual machine (Why would I recreate a windows 7 installation (approx 25GB), when I already have one installed on my computer...?)
I need to do some tests with IE9 and the other windows browsers...
Answer: What you need is not to start Windows without Vbox, but for your vbox to use the existing disk instead of a disk image. In other words, your Windows will still run within VirtualBox (there is no way around it!) but instead of installing it on a virtual disk image (VDI), you use an existing partition with an existing Windows installation.
You still have to create the virtual machine, but make it use a real disk.
As far as I can tell, this is possible. However, you might want to read the Virtualbox manual.
Comment: At the end it didn't work for me, I can create everything following his tutorial, but when I start the virtual machine it just hangs... I accept your answer anyway since it's the closest thing I could find to what I need
Answer: No, it won't work.

Do not experiment with this on a productive machine

Ubuntu and Windows 7 are different operating systems. They can by definition not be run at the same time without the help of a virtualization software. As it may be possible to access a physical hard drive from a virtual machine (see this question) it is

very unlikely you can actually boot the same Windows on both, a real machine and a virtual machine.
not recommended to do so as anything writing to your system files may damage the OS to become inoperable.

You may convert an existing Windows to a virtual machine (see this question) but then it is not much more than an additional VM that will probably clutter your hard disk space more than a newly created machine.
My recommendation in case you still need to dual boot to Windows would therefore be to sacrifice the hard disk space needed for a newly created Window 7 virtual machine for testing Windows 7 applications while still running Ubuntu. You may want to consider to install a reduced version of Windows 7 in this machine. This can be done with RT seven Lite.
Comment: I'm not sure you understood my question. I have a working dual boot. I just want to be able to use my Windows partition in Ubuntu like any other Virtual Machine. My Windows is not actually booted...
Comment: @Piero: you will soon see that it will not work the way you want it to. **Doing so puts your Windows at risk.** It may be possible to run Ubuntu from a raw disk in a VM but even this is not safe and thus not recommended.
Comment: Ok... Anyway it doesn't work so :) But I think it's too bad!
Comment: @Piero: its not to be expected that a Windows installation can easily run on a different computer (nothing else is your VM) - just saying... Look at the gentoo page linked in the other answer. They don't tell you how to do it. The *"Prepare Windows..."* part is blank - guess why ;).
Answer: I've done this in the past with VMWare Player.  Before this was a pretty manual process, but now you can add a physical HDD easily.  There is a trick to initial creation, however.
First create the new virtual machine, you will be forced to create a virtual disk, just set the size to 0.
Afterwards, edit the newly created VM, remove the HDD and add a new one.  Choose 'Physical Device' and choose the device or partition.

And now the catch.  The hardware on this will be different than the hardware on your actual machine.  It's very likely Windows will have no trouble setting this up as VMPlayer uses pretty generic hardware, but you can never be sure if you trip some Windows Genuine Advantage crap.  I never had much trouble with it, but you never know.
This really is no different than pulling the hard drive out and plugging it into another motherboard or something.
Comment: Also, vmplayer will allow you to set Windows into Unity mode, where the applications look like native applications.

Ubuntu, Windows 7 and virtualization


Handling axios requests that take 10+ seconds

Question: I hope this question isn't too general but I've got a post request that uploads a high-res image, then on the server side, several operations take place with that image to generate thumbnails and watermarks. The server takes a good 10-20 seconds before it finally returns a response. Should I be returning some kind of interim response? Is there a best practice here?
For the sake of illustration, here's a rough outline of the client-side code:
axios.post('/upload', hugePhoto, { headers: { 'Content-Type': 'multipart/form-data' } })
.then(res => { /* takes 10-20 seconds before I get a response here */ })
.catch(err => { /* handle error */ })

And the server-side code, note I am creating a bunch of different size images here and uploading them to S3, which is what takes so long:
router.post('/upload', upload.single('file'), (req, res) => {
  sharp(req.file.path).metadata()
  .then(m => /* reading metadata */)
  .then(() => /* some db operations */)
  .then(() => /* uploading original file to S3 */)
  .then(() => /* resizing the file with sharp */)
  .then(() => /* uploading that to S3 */)
  .then(() => /* resizing the file with sharp */)
  .then(() => /* uploading that to S3 */)
  .then(() => /* resizing the file with sharp */)
  .then(() => /* uploading that to S3 */)
  .then(() => res.json({ success: true }))
  .catch(err => res.status(400).send(err.message))
})

Thank you!
Comment: 1 alternative is for the server to immediately respond with an endpoint the client can then poll for the response once it's ready. Though this may not buy you anything given the details you've provided so far.
Comment: Can you post your server code as well please
Comment: It's a bit complicated for the comment section, but once you fire the first request, you'd kick off a task on the server to process the image, then immediately return a "check back later" response.  Then you'd set up either a socket or `setInterval` to an endpoint that can update the client when the task is complete
Comment: I can post something that gives you the general idea...standby
Comment: @junvar how does the client know when the endpoint is ready? I am not familiar with poll?
Comment: Thanks @Phix I get what you're saying. Maybe that is the best way to go with these large files.
Answer: This is a perfect use case of using serverless event driven architecture. There is no need for client to wait till you create and upload different resolutions of the images. There are multiple ways you could reduce the time.

Do things in parallel instead of sequentially. something like this (no change required in your current architecture)

router.post('/upload', upload.single('file'), (req, res) => {
  sharp(req.file.path).metadata()
  .then(m => /* reading metadata */)
  .then(() => /* some db operations */)
  .then(() => /* uploading original file to S3 */)
  .then(() => Promise.all([funcResolution1(), funcResolution2(), funcResolution3()]))
  .then(() => res.json({ success: true }))
  .catch(err => res.status(400).send(err.message))

If you are happy to change the architecture, you could leverage serverless technologies here. something like AWS Lambda (https://aws.amazon.com/lambda/). You basically take the file from endpoint and after that raise some events for the function to do the other stuff for you. OR have a trigger on s3 to trigger the function as and when there is file. that lambda function can do the thumbnails etc for you. (https://aws.amazon.com/blogs/compute/resize-images-on-the-fly-with-amazon-s3-aws-lambda-and-amazon-api-gateway/)
You could delegate the task to some other application which gets triggered as soon as there is a file.

Hope it gives you some idea.
Comment: Man I have been reasearching this the last couple of days and thinking like nah, building the lambda functions is overkill, but the further I get on this project, the better that option seems. Thank you!