inline form validation when user tabs out of an empty field

Question: My question is similar to Should inline validation check empty fields if user only tab the field but do nothing and skip to next field?, but a bit different.
Let's say I have a form containing a few text fields. Each of these fields are mandatory and information about that "mandatoriness" is very obvious in copy as well as in the code. if a field is filled with invalid data, an error message shall appear along that field.
The error message can be triggered either if

The user blur/tabs out of an empty field, or
The user types something incorrect and then blur/tabs out of the field.

When a keyboard-user tabs trough this form, (s)he will get an error message on each field just by navigating in the form. It seems odd to show an error message when a user has not yet done anything.
Question: When shall we do that inline validation? On 1 or 2?
Answer: I'd vouch for showing the error message even if a user is only navigating through a form.
Users are less likely to unintentionally skip required fields
Leaving optional fields empty even if interacted with, results in a blank field with no error messages. Doing the same for fields that do require input, leads to a potential misunderstanding that the field is optional and can be ignored. This is not the case, so it's better to be clear about that and prevent users from submitting the form and getting a ton of errors back.
Users can locate 'mistakes' easier
Telling users about any errors right away ensures users won't be confused when the form is unable to be sent later on. Many forms disable the submit button if a required field is ignored. Sure, users can scroll back up scan for blank fields, but they will be once again be subjected to the mental load of processing forms.  We want to make users take less time filling in our forms, not more.
These same principles apply to inline validation in  general.


Breeze: Track changes on new object

Question: I am able to create an entity object, set some default values and add it to the manager. Now I want to track the changes to it using manager.hasChanges(). For some reason, this always returns true. Should I be checking something else too when tracking newly created entities that are not in the database?
Answer: EntityManager treats an entity with EntityState.Added as a 'changed' entity. This is why HasChanges will always return true.
In this case, you should listen to EntityManager.entityChanged event to track changes.
See http://www.breezejs.com/sites/all/apidocs/classes/EntityManager.html#event_entityChanged
Answer: As soon as you 'Add' it to the EntityManager, by definition, it has changes because it is in an 'Added' state. To breeze 'hasChanges' means that it needs to be saved because it is 'different' from what was provided by your persistence service ( in this case the entity hasn't yet been 'saved').
What you can do is 'Attach' your entity to the EntityManager in an 'Unchanged' state.
myEntityManager.attachEntity(newEntity, breeze.EntityState.Unchanged);

In this case, any changes you make will work the way you want, BUT ...
Breeze will now consider your newly attached entity to already have been persisted and if you try to save it, then the save will fail because breeze will try to 'modify' the persisted entity instead of creating a new one.
If you really want to accomplish your request you will need to use 'attach' but also keep track of these entities and mark them 'added' before you attempt to save them.

Breeze: Track changes on new object


Religion specific units in Fall from Heaven 2?

Question: In Fall from Heaven 2, there are religion specific units such as the "Fawn".  To build these units do you need the religion in the city you're building them, or that religion as your state religion, or both?
Answer: There isn't a clear cut answer to this, since the answer is sometimes.
For example,
Ashenveil
As City Religion, you can build

Savant
Temple of the Veil

As State Religion, you can build

Beast of Agares
Demons' Altar
Diseased Corpses
Infernal Pact
Profane
Ritualist
Sacrifice the Weak

However, Ritualists and Beasts require a Temple of the Veil.  Now a Temple of the Veil doesn't require the City religion be Ashenveil to use, but it does require to be built.
The rule of thumb is:

Units which spread religion require that religion on the city where they're built
Building a temple requires the city have that religion
Some units  that require the Temple, don't require the City religion (unless they spread)
Other units require the State Religion
Comment: Is there a way to tell the difference from the Civlopedia entry? Unless I'm mistaken, they both show the same icon there.
Comment: @Cross I don't believe so. However, its usually very easy to identify the ones that spread religion as they have the following properties:
Starts With:
Cannot Pillage,
Medic I,
Can spread X,
Can sacrifice for 15 Science.  Outside of them you can see which ones require temple pretty easily.


how to split all the files in a directory in to 4gb files to a different directory?

Question: I have a directory containing several large files that are each greater than 4gb.   I want to copy all of those files to a different directory (happens to be a fat32 usb drive mounted), but split the files down to 4gb (since the destination drive is limited to that size files).
I tried this:
split -b 4096G /var/lib/backuppc/images/* /usbdrive/

but I get a
split: extra operand `/var/lib/backuppc/images/xxxxxxxxxmyfilesname.tib'

Am I doing something wrong?   (also tried  "4G" instead of 4096G, no difference)
Comment: Did you try with `4G` ?
Comment: yes, just did, no difference
Answer: My suggestion would be to first create a tar file:
tar -cf /tmp/bigfile.tar /var/lib/backuppc/images/*

then split that:
cd /usbdrive
split -b 4G /tmp/bigfile.tar

If you want to avoid use of the temporary tar file you can pipe tar directly to split:
tar -cf - /var/lib/backuppc/images/* | split -b 4G

To reconstruct this when you get to the destination, recreate and unarchive the tar file:
cat /usbdrive/x* >bigfile.tar
tar -xvf bigfile.tar

Again, to do this without the temporary file:
cat /usbdrive/x* | tar -xvf -

Answer: split can't take more than one input file as an argument.
You can try using find for this
cd /var/lib/backuppc/images && find . -maxdepth 1 -type f -exec split -b 4G '{}' "/usbdrive/images/{}" \;

Comment: getting there, now getting: /usbdrive/images//var/lib/backuppc/images/Acer_Veriton_X498G_Desktop_Win_7_Pro_OA_FACTORY_BU.tibaa: No such file or directory     (and my /usbdrive/images/ directory does exist)
Comment: Sorry, forgot to take spaces into account, please see the edited command.
Comment: Or, if you don't insist on `split` and preserving permissions etc, use *7z* for example: `7z -v4g -mx0 a /usbdrive/images/images.7z /var/lib/backuppc/images`.


How to speed up a SQL query with HAVING

Question: I have the following query:
SELECT u.amount_limit
     , SUM( t.amount ) AS approved
  FROM table_transactions AS t
     , table_users AS u
 WHERE t.uid = u.id
   AND t.status = 1
   AND u.status = 1
   AND u.amount_limit != 0
 GROUP
    BY t.uid
 HAVING approved >= u.amount_limit

In a database with 1000 users and 1000000 transactions, it take about 7-8 seconds.
There is a way to optimize / speed up this sql query?
PS: I need the amount and the number of users that reached the limit, which I currently get with PHP mysql_num_rows().
UPDATE: HERE IS THE TABLES STRUCTURE
CREATE TABLE IF NOT EXISTS table_users (
  `id` varchar(32) COLLATE utf8_bin NOT NULL,
  `amount_limit` float DEFAULT NULL,
   ....
  PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

CREATE TABLE IF NOT EXISTS `table_transactions` (
  `id` varchar(32) COLLATE utf8_bin NOT NULL,
  `uid` varchar(32) COLLATE utf8_bin NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT '0',
  `amount` float NOT NULL DEFAULT '0',
  ....
  PRIMARY KEY (`id`),
  KEY `uid` (`uid`),
  KEY `status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

Comment: First, you need to write a query that makes sense.  You have `SELECT` columns that have nothing to do with the `GROUP BY` columns; you have unaggregated columns in the `HAVING`.  The arcane `JOIN` syntax doesn't affect the logic, but it looks quite awkward.
Comment: Add table definitions so we don't have to guess what indexes are in place and and explain plan.
Comment: Please provide `EXPLAIN SELECT ...`
Comment: Check this question https://stackoverflow.com/questions/44023382/slow-query-with-having-clause-can-i-speed-it-up
Comment: Pls include the create table statements for the relevant tables, as well as the output of the explain of the sql query.
Comment: added the tables structure as per your suggestion
Comment: Grouping by t.uid doesn't make a lot of sense to me - you may get a bunch of limits but no idea who they apply to.
Comment: Without "GROUP BY t.uid" the query doesn't work unfortunately, if you have a better solution I'm all ears. thanks
Answer: Plan A:
SELECT  u.amount_limit, x.approved
    FROM ( SELECT  uid, SUM(amount) AS approved
            FROM  transactions
            WHERE  status = 1
         ) AS x
    JOIN  users AS u  ON u.id = x.uid
    WHERE  u.amount_limit != 0
      AND  u.status = 1
      AND  x.approved >= u.amount_limit

Plan B, possibly faster if a lot of users have limit=0 or status != 1:
SELECT  u.amount_limit,
        ( SELECT  SUM(amount) AS approved
            FROM  transactions
            WHERE  status = 1
              AND  uid = u.id
        ) AS approved
    FROM  users AS u
    WHERE  u.amount_limit != 0
      AND  u.status = 1
      AND  approved >= u.amount_limit

Both would benefit from these composite indexes:
users:        INDEX(status, amount_limit, id)
transactions: INDEX(status, uid, amount)

If id and uid are "random" number like UUIDs or hashes, access will be random and slow.  The indexes I provided will be "covering" thereby compensating significantly for the problem.
Suggest you rethink the design of the ids.
FLOAT and DOUBLE should be avoided for monetary values.  See DECIMAL(m,n), instead.
Indexing a 'flag' (such as status) by itself is rarely useful.  Having it as a part of a composite index is may be useful.

How to speed up a SQL query with HAVING


django, property update a model instance

Question: 1. instance.save()

2. instance.foo = foo; instance.save(update_fields=['foo'])

3. InstanceClass.objects.filter(id=instance.id).update(foo=foo)

I found that #3 is sometimes not reliable.
after I run #3, occasionally foo is not properly set (not commited?)
I used to use #3 when I don't want to run signal handlers.
When to use each of the above 3?
Answer: If you're just updating a record and don't need to do anything with the model object, the most efficient approach is to call update(), rather than loading the model object into memory. For example, instead of doing this:
instance = Entry.objects.get(id=10)
instance.comments_on = False
instance.save()

do this:
Entry.objects.filter(id=10).update(comments_on=False)

NB :

Using update() also prevents a race condition wherein something might change in your database in the short period of time between loading the object and calling save().*
update() does an update at the SQL level and, thus, does not call any save(), so if you have an overrided save() method you have to use the first way with get() and save().

Check the Queryset documentation, it's all explained here.


Flutter url_launcher send sms not loading number in the imessenger

Question: Hi I am trying to send sms using url_launcher package in an iOS mobile device. The user clicks a button on my app and the url launcher triggers the iMessage and populates the phone number and message to be sent. Following is the code I am using for button click:
final Uri smsLaunchUri =
      Uri(scheme: 'sms', path: '3939393939', queryParameters: <String, String>{
    'body': Uri.encodeComponent('Example Subject & Symbols are allowed!'),
  });
  if (await canLaunchUrl(smsLaunchUri)) {

    launchUrl(smsLaunchUri);
  } else {
    throw 'Could not launch';
  }
}

I have following in the info plist file:
<key>LSApplicationQueriesSchemes</key>
    <array>
        <string>sms</string>
        <string>tel</string>
    </array>

But once the messenger is launched the 'To:' filed has 'No Name' and loading circle. Also there is no message in the message field. That number is saved in the simulator device with a 'test contact'.
Answer: I was having the same problem, but when I ran it on an actually ios device it worked fine. Seems like it has something todo with the simulator.


auto reference to address in C++

Question: I'm studying some C++ features, trying to play around with some experiments. However, I stuck in a place where it compiled error:
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string str = "some string";
    auto &c = str.begin(); // compile error
    *c = toupper(*c);
    cout << *c << ", str: " << str << endl;
}

I'm not sure why it was not acceptable. My thought was that c had type char * (a pointer to a char), so that's why I had written as above. But why it failed in compiling?

Error C2440   Cannot transform 'std::_String_iteratorstd::_String_val<std::_Simple_types<_Elem>>' to'std::_String_iterator<std::_String_val<std::_Simple_types<_Elem

PS: Another method which I had tried first was OK.
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string str = "some string";
    auto &c = *str.begin(); // success
    c = toupper(c);
    cout << c << ", str: " << str << endl;
}

Comment: In questions about compiler errors, do include the actual error message! StackOverflow can often find an answer for you even while you are still writing your question. But you need to help out a bit.
Comment: Why do you need `c` to be a reference?
Comment: @JimRhodes No special intention, just for practicing and confirming my understanding of those mechanism.
Answer: begin() returns an iterator by value, not a reference. You are not allowed to form a non-const lvalue reference.
Making it const would prolong the life of the returned iterator and the program would then compile:
const auto &c = str.begin();

On the other hand, iterators are supposed to be cheap to copy and iterators from contiguous containers are often implemented as pure pointers. The idiomatic approach is:
auto c = str.begin();

In your second example, the idiomatic approach to form a reference to the first element would be:
auto& c = str.front();

Comment: @Eric You're welcome. Yes, I think you could make that comparison. It'd be ok to do `const auto& c = 123;` though :-)
Comment: I think I get it. So in my first example, writing `auto& c = str.begin()` is similar to writing something like `auto &c = 0x....` or `auto &c = 123`, which does not make sense right? Also, thank you for the compliment of the idiomatic way, which is quite useful to me!

auto reference to address in C++


Linking two applications in Cloud Foundry

Question: My application is split in two different applications (microservices?). One is deployed to CF as a docker container and another is deployed as a regular WAR file (grails application). The docker container is a Python/Flask application that exposes a REST API. The WebApp Uses this rest API.
Previously I had these applications as two separate docker containers and would execute them using the docker --link flag but now I'm looking to put these applications in Cloud Foundry. In the docker world I used to do the following.
docker run -d --link python_container -p 8080:8080 --name war_container war_image

The above command would create environment variables in war_container that would expose the ip address and port for the python_container. Using these environment variables I could communicate to the python_container from my WAR application. These environment variables would look like this:
PYTHON_CONTAINER_PORT_5000_TCP_ADDR=<ipaddr>
PYTHON_CONTAINER_PORT_5000_TCP_PORT=<port>

Question
Is it possible to do something similar in Cloud Foundry? I have the docker container already deployed in CF. How can I link the my WAR application such a way that the environment variables get created that get linked to the python_container as soon as I push the war file.
Currently I push the docker container to PCFDev using this:
cf push my-app -o 192.168.0.102:5002/my/container:latest

Then I push the war file using
cf push cf-sample -n cf-sample

The manifest.yml for cf-sample is:
---
applications:
  - name: cfsample
    memory: 1G
    instances: 1
    path: target/cf-sample-0.1.war
    buildpack: java_buildpack
    services:
      - mysql
      - rabbitmq

Answer: How would does the Docker way work if you had multiple instances of your Python app, and hence multiple IPs/ports?
For PCF, you could just have the Java app talk to your Python app "through the front door": https://my-python-app.local.pcfdev.io.
You can also try to discover your Python app's IP and port (see https://docs.run.pivotal.io/devguide/deploy-apps/environment-variable.html#CF-INSTANCE-IP for instance) and then pass these values to your Java app as environment variables, but this is a very brittle solution.
If you're interested in direct container-to-container networking, you might be interested in reading about and giving feedback on this proposal.


It's checking only firs row in table. help someone :) C# winForm

Question: SqlConnection con = new SqlConnection(@"Data Source=(local)\SQLEXPRESS; Integrated Security= SSPI;" + "Initial Catalog = CarRent_vaxo;");
con.Open();
string strSQL = "select * from AccesList";
SqlCommand myCommand = new SqlCommand(strSQL, con);
using (SqlDataReader myDataReader = myCommand.ExecuteReader())
{
    myDataReader.Read();
    {
        if (usertextBox.Text == myDataReader["User"].ToString() && paswordTextBox.Text == myDataReader["Password"].ToString())
        {
            this.Hide();
            ResultForm rf = new ResultForm();
            rf.Show();
        }
        else if (usertextBox.Text == "" || paswordTextBox.Text == "")
        {
            Notificarion2.Text = "PLEASE FILL THE BOXES !!!";
        }
        else
        {
            Notificarion2.Text = "WRONG USER OR PASSWORD !!!";
            usertextBox.Text = "";
            paswordTextBox.Text = "";

        }
    }
}

Answer: You should read from SqlDataReader in a while loop as
 while (myDataReader.Read())
 {
   //your code goes here
 }

 myDataReader.Close();

http://msdn.microsoft.com/en-us/library/haa3afyz%28v=vs.110%29.aspx
Comment: And they should probably encrypt their passwords


C# (.Net 4.8 Framework) How to change the querystring parameters in an API POST Call from header to body and open PDF in new tab

Question: [OP Comment/edit]
I thought I had this wrapped up, but I saved the PDF after getting this code working (huge thanks to @User9938). I can save the PDF, but when I go to open the file it does not open, but gives an "improperly encoded error"... Here is the code that creates the file (but does not allow me to save it)!! Any thoughts?
using (WebClient wc = new WebClient())
{
    //wc.Headers.Clear(); // Did not help
    wc.Headers.Add("Content-Type", "application/xml");
    wc.Encoding = System.Text.Encoding.UTF8;

    //var data = wc.UploadString(URI, QS1);
    //Worked with ASCII & UTF8, but UTF8 is far superior and will save you pain if you have any international symbols (non USA letters)
    Byte[] buffer =  wc.UploadData(URI, "POST", System.Text.Encoding.UTF8.GetBytes(QS1));
    //Byte [] buffer = wc.UploadValues(api.BaseURI, myCol);
    if (buffer != null)
    {
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-length", buffer.Length.ToString());
        Response.BinaryWrite(buffer);
    }
}

Encoding Error when I try to reopen the PDF (after saving).

[End OP Comment/edit]
My C# (.NET Framework 4.8 Code) API call returns a PDF from a URI.
The company updated their API and now I have to pass the parameters in the body (and not the querystring). This is the current "POST" version and opens the PDF in a new browser tab. How do I pass the parameters in the body (and not the Querystring)? This perfect solution took tons of digging to get it working and is a no go with the new system.
    using (WebClient wc = new WebClient())
    {
        WebClient client = new WebClient();
        Byte[] buffer = client.DownloadData(https://destinationAPI.com/Request?A=Works&B=In&C=OldVersion);
        if (buffer != null)
        {
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-length", buffer.Length.ToString());
            Response.BinaryWrite(buffer);
        }
    }

My attempts: (I put notes next to lines that failed.) Thanks to a comment by  @user9938, I tried various versions of this this, but still got 415 Errors.
string QS1 = "A=this&B=is&c=EasyOnceYouGetTheRightAnswer";
Uri URI = "https://Mypost.com/RequestMyPDF";
string strURI = "https://Mypost.com/RequestMyPDF";

using (WebClient wc = new WebClient())
            {
                //These 3 attempts get a 415 Error
                //Byte[] buffer =  wc.UploadData(URI, "POST", System.Text.Encoding.ASCII.GetBytes(QS1)); //415 Error
                //Byte[] buffer = wc.UploadData(URI, "POST", System.Text.Encoding.UTF8.GetBytes(QS1));//415 Error
                Byte[] buffer = wc.UploadData(strURI, "POST",System.Text.Encoding.UTF8.GetBytes(QS1));//415 Error
                if (buffer != null)
                {
                    Response.ContentType = "application/pdf";
                    Response.AddHeader("content-length", buffer.Length.ToString());
                    Response.BinaryWrite(buffer);
                }
            }

Another attempt (original attempt) I have this code that pulls the data into a streamreader, but the "Context-Type" of "text/plain" works ("application/pdf" returns a 415 Error).  If I can get the streamreader into a byte[], I think I can use the code above to output my PDF in a new window.
try
{
    System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
    //req.ContentType = "application/pdf" //This generates a 415 Error
    req.ContentType = "text/plain"; //This returns data,  but I don't think it will work with a PDF.
    req.Method = "POST";
    //We need to count how many bytes we're sending. Post'ed Faked Forms should be name=value&
    byte[] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
    req.ContentLength = bytes.Length;
    System.IO.Stream os = req.GetRequestStream();
    os.Write(bytes, 0, bytes.Length); //Push it out there
    os.Close();
    System.Net.WebResponse resp = req.GetResponse();
    if (resp == null) return null;

    System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
    //READ to PDF and post in new window

    // Use ANSI encoding -also known as Encoding.GetEncoding(1252)??
    Encoding objEncoding = Encoding.Default;

    //StreamReader objSR = new StreamReader(sr.ReadToEnd().Trim(), objEncoding);

    //I want to open the pdf in a new tab, this is just an attempt to get ito to work...
    //This creates an EMPTY PDF
    StreamWriter objSW = new StreamWriter(@"c:\temp\Destination123.PDF", false, objEncoding);
    objSW.Write(sr.ReadToEnd().Trim());
    objSW.Close();

    //Byte[] buffer = ?? How to convert StreamWriter to BYTE!?!// (Old code was "Byte[] buffer = client.DownloadData(api.URI);")
    //if (buffer != null)
    //{
    //    Response.ContentType = "application/pdf";
    //    Response.AddHeader("content-length", buffer.Length.ToString());
    //    Response.BinaryWrite(buffer);
    //}

    return "Have we a PDF?!?!";
}
catch (Exception ex)
{
    return  ex.Message;
}

My stacktrace on the last 415 error:
[WebException: The remote server returned an error: (415) Unsupported Media Type.]
System.Net.WebClient.UploadDataInternal(Uri address, String method, Byte[] data, WebRequest& request) +317
System.Net.WebClient.UploadData(Uri address, String method, Byte[] data) +160
System.Net.WebClient.UploadData(String address, String method, Byte[] data) +38
MyApp.Controllers.StatementsController.GetIndividualPDF(List1 model) +5328 lambda_method(Closure , ControllerBase , Object[] ) +103 System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +157
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +27 System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22 System.Web.Mvc.Async.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32 System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +50 System.Web.Mvc.Async.<>c__DisplayClass48.<InvokeActionMethodFilterAsynchronouslyRecursive>b__41() +228 System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10 System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34 System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26 System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100 System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27 System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36 System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26 System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10 System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9836613
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +50
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163
Comment: You need to specify the encoding: `wc.Encoding = System.Text.Encoding.UTF8;` before calling "UploadData". `See https://learn.microsoft.com/en-us/dotnet/api/system.net.webclient?view=netframework-4.8
Comment: "How to post data to specific URL using WebClient in C#": https://stackoverflow.com/questions/5401501/how-to-post-data-to-specific-url-using-webclient-in-c-sharp
Comment: @user9938 - Thanks for that. I still get a 415. I will modify my question to include this. Seems like this should work. I get a good reply on Fiddler, but plain/text (which will not allow me to render a PDF (as far as I know).
Comment: Here's another post: https://stackoverflow.com/questions/39010572/use-webclient-to-post-query-and-download-file
Comment: @user9938 Thanks so much. I'm trying everything in every way I can think to do it and have no idea what I'm missing. These all work for other people. I've double checked and I get data from Fiddler. I can pull data with my last script, but it's text/plain, so like I said... That's not going to work for a PDF (I don't think?)
Answer: !!! The following code creates the PDF and it looks perfect. I can save the PDF, but when i try to reopen the saved file, I get the following encoding error !!
Hope this saves someone else some trouble. See comments on OP from @User9938 who was a huge help and saved me a lot of time. Thank you! Frankly, now that I have the headers correct, some of my other attempts might work also. I left them in save others from having to look each one up individually.:
using (WebClient wc = new WebClient())
{
    //wc.Headers.Clear(); // Did not help
    wc.Headers.Add("Content-Type", "application/xml");
    wc.Encoding = System.Text.Encoding.UTF8;

    //var data = wc.UploadString(URI, QS1);
    //Worked with ASCII & UTF8, but UTF8 is far superior and will save you pain if you have any international symbols (non USA letters)
    Byte[] buffer =  wc.UploadData(URI, "POST", System.Text.Encoding.UTF8.GetBytes(QS1));
    //Byte [] buffer = wc.UploadValues(api.BaseURI, myCol);
    if (buffer != null)
    {
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-length", buffer.Length.ToString());
        Response.BinaryWrite(buffer);
    }
}


how to get as400 spool files to text in c#

Question: I'm trying to code a console application to get the spool file from as400 to a different destination as a text file. I have been looking around but I haven't found a small code to start from there, I been searching around and haven't found anything close.
You guys have any idea or suggestion on how to start this?
Comment: [CPYSPLF](https://www.ibm.com/support/knowledgecenter/ssw_ibm_i_73/cl/cpysplf.htm) and [CPYTOSTMF](https://www.ibm.com/support/knowledgecenter/en/ssw_ibm_i_72/cl/cpytostmf.htm) are good places to start.  There are also third-party tools like [SPLAMATIC/SPLCONVERT](http://www.gumbo.com/Licpgm/Spool-a-Matic.html) from Gumbo Software.  You can save the file to a shared IFS directory (mapped to a Windows drive) and have your c# program get it from there.
Comment: Are you using anything from C# to call AS400 programs currently? Your best best is to do like @Mike suggested and call a program already on the 400 to convert the spool file to a shared IFS directory. From that point, you can grab the file from that shared IFS directory in C#. I would recommend testing out both parts separately before you merge them into a single program. Figure out the command you need to run on the 400 by doing it manually in the green screen. Then, put a file in a shared directory and test pulling that into your program. At the end, you can put those together.
Comment: I'm not sure about AS400, but on system z there is typically an FTP service that can be used to retrieve job spool files. Check with your system admin to find out which options are available for fetching job output. Once you know the options, you'll be better equipped to figure out how to handle the problem in C#.
Comment: If FTP is an option, it seems there is a good tutorial on using the AS400 FTP here: http://www.go4as400.com/FTP-SNDNETF-stream-file-STMF-in-as400/file_transfer.aspx?cid=22. It also seems like there are some classes to support FTP interaction in C#. See https://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest(v=vs.110).aspx
Comment: There are many different ways to go about this. I think we probably use 4 or 5 of them at my work.  Do you need to do this from a C# program or would it make sense to run a program on the IBM system that sends the spool file out instead?
Comment: Another way to approach this is to have your C# program use the cwbx.dll objects:  the AS400System class to log onto the system, and the Program class to issue a `CALL` command that would execute whatever RPG or CL program creates/copies the spool file.  You could also use the Command class if you want to execute commands like `CPYSPLF`.  That can be like writing a CL script in C# (which is not as insane as it might sound).
Comment: @Player1st Yes, I need to do this in c# I need to export the spool file into a text file. I'm still doing random stuff with the code but I'm not getting anywhere.
Comment: What can you do now on the AS400 from c#?
Answer: I have the same problem. I'm using the API calls QUSRTVUS to get the spooledfile list and want to open a specific spooled file with information of the previous API call.
After getting the file list I create a new userspace with QUSCRTUS. Then I want to open the file with QSPOPNSP but that is my problem.
Sourcecode to open a file
After opening the file I would read the content with QSPGETSP which copies the file in the userspace where I could read it.
That's the plan but without opening the file the rest doesn't work.
I get the error directly when calling the API, this is not an error message during the work of the call. Changing the parameters don't change the error message.
Maybe someone has a hint?
UPDATE: I found out the mistake. Despite the misleading error message, it was an authorization problem. I wasn't allowed to call the APIs.
Comment: What information are you trying to get from the spooled file?  An AFP fIle has an intricate format.  If you only need textual data, the [CPYSPLF](https://www.ibm.com/support/knowledgecenter/ssw_ibm_i_73/cl/cpysplf.htm) command gets rid of fonts, barcodes, overlays, and images to leave only the textual data.  You can dump the results into a QTEMP library and parse it simply.


How does Diablo still exist?

Question: At the end of Diablo II, the soulstones of both Diablo and Mephisto were destroyed at the Hellforge.  It's been a couple of years since I've played the game, but if I remember correctly, it was explained that this would forever destroy the essence of the two Prime Evils.  (I'm pretty sure Baal's soulstone was also destroyed at the end of the expansion.)

 I just reached Act IV of Diablo III, however, and it becomes obvious that Diablo was less than vanquished.

Do they ever explain how this was the case?  In particular, if his essence was never completely destroyed, how did it come to be entrapped within the Black Soulstone (along with the essences of the other five Great Evils destroyed in Diablo II)?
Also, I would prefer it answers to this question would not include spoilers for Act IV (and beyond).
Answer: There is the scene where the black soulstone is completed in Act II. It is explicitly stated by Adria and accompanying adventurers that that is what she has been doing all the years of Leah's life. Going around and marking the souls of the three previous prime evils so that when the black soutstone was completely they would be sucked into it.
So the current in-game explanation is that the souls were never destroyed, they were then sucked up by the black soulstone when it was completed.
Comment: The lesser evils that had been killed earlier (Andariel and Duriel) must have been marked also not only the 3 prime evils.
Comment: @Blem That is possible. I just reached that part in the storyline where all of this happened in ACT II not to long ago and it was just the 'Oh that is what you have been doing all this time!' sort of revelation.
Answer: If you want spoiler-free lore background, I can only recommend this video of the Blizzcon 2011 Diablo 3 Lore Panel. To put it in a nutshell, you can't really kill the great evils, only their manifestation in Sanctuary.
The soulstones where created to capture the essence of the demons, and bind them, since they were almost indestructible. Chris Metzen said in an interview that the whole idea of the soulstone was influenced by the "exorcist" idea of sacrificing yourself as a vessel to capture a demon. That is why the hero from Diablo 1 becomes the dark wanderer in Diablo 2.
Comment: This is just a bit of a nitpick, but after several retcons, the warrior from D1 becomes the dark wanderer in D2. Horazon is the sorcerer from D1, and Blood Raven is the rogue from D1.

How does Diablo still exist?


Can Ubuntu Touch be installed on a iPad one

Question: I have an iPad one and would simply like to know if Ubuntu touch can be installed on it and where I can find information on how to do this, I have done many searches on Utube and google! so far nada.
Please help if you can.
Best regards Susan.
Comment: you cant https://askubuntu.com/questions/6263/how-can-i-install-ubuntu-on-an-ipad and ubuntu touch is no longer maintained so forget about it https://wiki.ubuntu.com/Touch, unless you want to use ubports but again you cant
Comment: That's easy: No, it cannot.
Comment: @Lynob post that as an answer, short and to the point.
Answer: Ubuntu touch is no longer maintained, and it won't work on IPads anyway. Ubports are developing ubuntu touch now, IPads is not on their list of supported devices either.


How to implement a State Pattern for Blazor pages using multiple components to build a page?

Question: I have a Blazor page that utilizes multiple components within it - how can I implement a State pattern (ideally per-page) that would be able to handle the current state of a page?
Currently I have all of the state and state-manipulation being done on the page (and via injected Services), but I imagine it would be cleaner to implement a state pattern where each page has some kind of State object which then allows you to manipulate the page and its components in a strict manner.
Ideally the State object would implement INotifyPropertyChanged and be able to dynamically have its State updated, but I also don't hate the idea of having the State object relegate State-manipulation to methods on the object to make sure state isn't just 1-off updated on the Blazor page.
I've already tried to implement some kind of MVVM pattern, but that turned into more questions than answers.
I started to create a State object for the current page being worked on, but I'm not sure if I should basically just be putting most of the logic that was on the Blazor page in the State object, or if I should still have some data, but delegating the heavy lifting to the State.
eg: I have some code that used to be in the "OnAfterRenderAsync" function on the Blazor page, but I'm in the process of moving basically everything in there to a "LoadMatterDetails()" function in the State object that is handling that. Does this make sense, or should I only really have object State in the state object, and writing to & reading from the State object when particular pieces of information are available?
public class MatterDetailsState : IMatterDetailsState
{
    private readonly IMatterDetailsService matterDetailsService;
    private readonly NavigationManager navigationManager;

    public bool EditMode { get; private set; } = false;
    public int EditMatterId { get; private set; } = 0;
    public Matter Matter { get; set; } = new();
    public MatterPaymentOptionDetails PaymentDetails { get; set; } = new();

    public List<MatterStatus> MatterStatuses { get; private set; } = new();

    public MatterDetailsState(
        IAppState appState,
        IMatterDetailsService matterDetailsService,
        NavigationManager navigationManager)
    {
        this.matterDetailsService = matterDetailsService;
        this.navigationManager = navigationManager;
    }

    public async Task LoadMatterDetails()
    {
        // Query Params handling
        var uri = navigationManager.ToAbsoluteUri(navigationManager.Uri);
        var decryptedUri = HelperFunctions.Decrypt(uri.Query);
        var queryParamFound = QueryHelpers.ParseQuery(decryptedUri).TryGetValue("MatterID", out StringValues uriMatterID);

        if (queryParamFound)
        {
            EditMatterId = Convert.ToInt32(uriMatterID);
            EditMode = !String.IsNullOrEmpty(uriMatterID) && EditMatterId > 0;
        }

        await LoadMatterStatuses();

        if (EditMode)
        {
            Matter = await matterDetailsService.GetMatterByIdAsync(EditMatterId);
            PaymentDetails = await matterDetailsService.GetMatterPaymentInfoByMatterId(EditMatterId);
        }
    }

    private async Task LoadMatterStatuses()
    {
        MatterStatuses = await matterDetailsService.GetAvailableMatterStatusesAsync();
    }
}

Basically, should I instead of having more or less the entire function in the State object, or only make the calls like setting Matter & PaymentDetails go through functions in the State object? Not sure what the standard for this is.
Answer: I've used Fluxor, which is a Flux/Redux library for Blazor, and have liked it. It holds all your state in an object which you can inject into your component for read access. You then manage state by dispatching actions from your components which are processed by effects or reducers which are essentially methods that process the action and make changes to state. It keeps everything neat, separated and very testable in my experience.
https://github.com/mrpmorris/Fluxor
Answer: There isn't a "standard", but applying good coding practices such as the "Single Responsivity Principle" and Clean Design principles drives you in a certain direction.
I divide the presentation and UI code into three:

UI - components and UI logic
State - data that you want to track state on.
Data Management - getting, saving,....

Each represented by one or more objects (Data Management is the ViewModel in MVVM).
You can see an example of this in this answer - https://stackoverflow.com/a/75157903/13065781
The problem is then how do you create a ViewModel instance that is scoped the same as the Form component.  You either:

Scope the VM as transient - you can cascade it in the form if sub components need direct access to it.  This is the approach in the referenced example.

Create an instance from the IServiceProvider using ActivatorUtilities and deal with the disposal in the form component.

If the VM implements IDisposable/IAsycDisposable the you have to do the second.
The following extension class adds two methods to the IServiceProvider that wrap up this functionality.
public static class ServiceUtilities
{
    public static bool TryGetComponentService<TService>(this IServiceProvider serviceProvider,[NotNullWhen(true)] out TService? service) where TService : class
    {
        service = serviceProvider.GetComponentService<TService>();
        return service != null;
    }

    public static TService? GetComponentService<TService>(this IServiceProvider serviceProvider) where TService : class
    {
        var serviceType = serviceProvider.GetService<TService>()?.GetType();

        if (serviceType is null)
            return ActivatorUtilities.CreateInstance<TService>(serviceProvider);

        return ActivatorUtilities.CreateInstance(serviceProvider, serviceType) as TService;
    }
}

Your form then can look something like this:
public partial class UIForm: UIWrapperBase, IAsyncDisposable
{
    [Inject] protected IServiceProvider ServiceProvider { get; set; } = default!;

    public MyEditorPresenter Presenter { get; set; } = default!;

    private IDisposable? _disposable;

    public override Task SetParametersAsync(ParameterView parameters)
    {
        // overries the base as we need to make sure we set up the Presenter Service before any rendering takes place
        parameters.SetParameterProperties(this);

        if (!initialized)
        {
            // Gets an instance of the Presenter from the Service Provider
            this.Presenter = ServiceProvider.GetComponentService<MyEditorPresenter>() ?? default!;

            if (this.Presenter is null)
                throw new NullReferenceException($"No Presenter could be created.");

            _disposable = this.Presenter as IDisposable;
        }

        return base.SetParametersAsync(ParameterView.Empty);
    }

//....
    public async ValueTask DisposeAsync()
    {
        _disposable?.Dispose();

        if (this.Presenter is IAsyncDisposable asyncDisposable)
            await asyncDisposable.DisposeAsync();
    }
}


Edit the subject of a forwarded message using Applescript - encountering error when editing subject line

Question: I have been trying to write some Applescript to forward a message and to edit the subject. Currently I am working on the forwarding and the populating of the recipient and the subject line.
When I run this it gives me the error:
"Mail got an error: Can't set subject of item to any."
Here is the code:
tell application "Mail"
    set theSelection to selection
    set theForwardedMessage to forward (item 1 of theSelection) with opening window
    tell theForwardedMessage
        make new to recipient with properties {address:"firstname.lastname@example.com"}
        set subject to "blahblahblah"
    end tell
end tell

I can't figure out why it's telling me it can't edit the subject line. Any pointers?
Answer: i hope this will help a little bit, but i don't fully understand your script and question.
set recipientName to "ZWEKKERBOY"
set recipientAddress to "firstname.lastname@example.com"
set theSubject to "Subject here"
set theContent to "Content"

--Mail Tell Block
tell application "Mail"

--Create the message
set theMessage to make new outgoing message with properties {subject:theSubject, content:theContent, visible:true}

    --Set a recipient
tell theMessage
        make new to recipient with properties {name:recipientName, address:recipientAddress}

    --Send the Message
    send

end tell
end tell

-- credit to maker!
You can change the
set theSubject to "Subject here"

line
to
set theSubject to subject
-- that's "blahblahblah"


compare wscript.arguments and string

Question: I want to compare an wscript.argument that I got to the vbs to a string, so depending in that comparation one action or another is performed. I have tried this, but I get an error. How can I solve it? How can I make the type comparation?
Set args = Wscript.Arguments
Set accessPath = args.Item(5)
    If accessPath = "-" Then
    objExcel.Cells(15, 3).Value = " "
    Else
    objExcel.Cells(15, 3).Value = accessPath
    End If

Answer: Use this instead:
Dim accessPath : accessPath = Wscript.Arguments(5)

If accessPath = "-" Then
    objExcel.Cells(15, 3).Value = " "
Else
    objExcel.Cells(15, 3).Value = accessPath
End If

Bear in mind that arguments start at 0, so by looking at Wscript.Arguments(5) you're actually looking at the sixth entry on the command line.
Finally you may want to also check the value of Wscript.Arguments.Count to ensure you have had enough arguments passed, otherwise an error will be thrown.

compare wscript.arguments and string


comparing an element with all elements in a list

Question: I'm learning Scala now, and I have a scenario where I have to compare an element (say num) with all the elements in a list.
Assume,
val MyList = List(1, 2, 3, 4)

If num is equal to anyone the elements in the list, I need to return true. I know to do it recursively using the head and tail functions, but is there a simpler way to it (I think I'll be able to do it using foreach, but I'm not sure how to implement it exactly)?
Answer: There is number of possibilities:
val x = 3
MyList.contains(x)
!MyList.forall(y => y != x) // early exit, basically the same as .contains

If you plan to do it frequently, you may consider to convert your list to Set, cause every .contains lookup on list in worst case is proportional to number of elements, whereas on Set it is effectively constant
val mySet = MyList.toSet
mySet.contains(x)

or simply:
mySet(x)

Comment: The runtime complexity of contains for sets depends on the implementation. The best worst case performance is O(log n)
Answer: A contains method is pretty standard for lists in any language. Scala's List has it too:
http://www.scala-lang.org/api/current/scala/collection/immutable/List.html
Answer: As others have answered, the contains method on the list will do exactly this, and it's the most understandable/performant way.
Looking at your closing comments though, you wouldn't be able to do it (in an elegant fashion) with foreach, since that returns Unit.  Foreach "does" something for each element, but you don't get any result back.  It's useful for logging/println statements, but it doesn't act as a transformation.
If you want to run a function on every element individually, you would use map, which returns a List of the results of applying the function.  So  assuming num = 3, then MyList.map(_ == num) would return List(false, false, true, false).  Since you're looking for a single result, and not a list of results, then this is not what you're after.
In order to collapse a sequence of things into a single result, you would use a fold over the data.  Folding involves a function that takes two arguments (the result so far, and the current thing in the list) and returns the new running result.  So that this can work on the very first element, you also need to provide the initial value to use for the ongoing result (usually some sort of zero).
In your particular case, then, you want a Boolean answer at the end - "was an element found that was equal to num".  So the running result would be "have I seen an element so far that was equal to num".  Which means the initial value is false.  And the function itself should return true if an element has already been seen, or if the current element is equal to num.
Putting this together, it would look like this:
MyList.foldLeft(false) { case (runningResult, listElem) =>
   // return true if runningResult is true, or if listElem is the target number
   runningResult || listElem == num
}

This doesn't have the nice aspect of stopping as soon as the target value has been found - and it's nowhere near as concise as calling MyList.contains.  But as an instructional example, this is how you could implement this yourself from the primitive functional operations on a list.
Answer: List has a method for that:
val found = MyList.contains(num)


How do I avoid random Wireless LAN disconnects?

Question: I am presently experiencing random disconnections from my wireless network. It looks like it is becoming more and more frequent (however I have not seen any clear pattern).
This is killing me...
Basically at some point the wifi network stops being detected and i CANNOT SEE ANY NETWORK ANYMORE like if the network card was shut down
Below is some information that should help as well as one attempt to fix it (from Ubuntu forums).
Machine: Acer Aspire S3 (exact model no. Aspire S3-951-2464G34iss)
statquant@euclide:~$ lsb_release -d
Description:    Ubuntu 12.04.1 LTS

statquant@euclide:~$ uname -mr
3.2.0-33-generic x86_64

statquant@euclide:~$ sudo /etc/init.d/networking restart
* Running /etc/init.d/networking restart is deprecated because it may not enable again some interfaces
* Reconfiguring network interfaces...

statquant@euclide:~$ lspci
02:00.0 Network controller: Atheros Communications Inc. AR9485 Wireless Network Adapter (rev 01)

statquant@euclide:~$ lsusb
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 001 Device 004: ID 064e:c321 Suyin Corp.
Bus 002 Device 003: ID 0bda:0129 Realtek Semiconductor Corp.

statquant@euclide:~$ ifconfig
wlan0     Link encap:Ethernet  HWaddr 74:de:2b:dd:c4:78
          inet addr:192.168.1.3  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::76de:2bff:fedd:c478/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:913 errors:0 dropped:0 overruns:0 frame:0
          TX packets:802 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:873218 (873.2 KB)  TX bytes:125826 (125.8 KB)

statquant@euclide:~$ iwconfig
wlan0     IEEE 802.11bgn  ESSID:"Bbox-D646D1"
          Mode:Managed  Frequency:2.437 GHz  Access Point: 00:19:70:80:01:6C
          Bit Rate=65 Mb/s   Tx-Power=16 dBm
          Retry  long limit:7   RTS thr:off   Fragment thr:off
          Power Management:on
          Link Quality=56/70  Signal level=-54 dBm
          Rx invalid nwid:0  Rx invalid crypt:0  Rx invalid frag:0
          Tx excessive retries:0  Invalid misc:71   Missed beacon:0

statquant@euclide:~$ dmesg | grep "wlan"
[   17.495866] ADDRCONF(NETDEV_UP): wlan0: link is not ready
[   17.498950] ADDRCONF(NETDEV_UP): wlan0: link is not ready
[   20.072015] wlan0: authenticate with 00:19:70:80:01:6c (try 1)
[   20.269853] wlan0: authenticate with 00:19:70:80:01:6c (try 2)
[   20.272386] wlan0: authenticated
[   20.298682] wlan0: associate with 00:19:70:80:01:6c (try 1)
[   20.302321] wlan0: RX AssocResp from 00:19:70:80:01:6c (capab=0x431 status=0 aid=1)
[   20.302325] wlan0: associated
[   20.307307] ADDRCONF(NETDEV_CHANGE): wlan0: link becomes ready
[   30.402292] wlan0: no IPv6 routers present

statquant@euclide:~$ sudo lshw -C network
[sudo] password for statquant:
*-network
   description: Wireless interface
   product: AR9485 Wireless Network Adapter
   vendor: Atheros Communications Inc.
   physical id: 0
   bus info: pci@0000:02:00.0
   logical name: wlan0
   version: 01
   serial: 74:de:2b:dd:c4:78
   width: 64 bits
   clock: 33MHz
   capabilities: pm msi pciexpress bus_master cap_list rom ethernet physical wireless
   configuration: broadcast=yes driver=ath9k driverversion=3.2.0-33-generic firmware=N/A ip=192.168.1.3 latency=0 link=yes multicast=yes wireless=IEEE 802.11bgn
   resources: irq:17 memory:c0400000-c047ffff memory:afb00000-afb0ffff

statquant@euclide:~$ iwlist scan
wlan0     Scan completed :
      Cell 01 - Address: 00:19:70:80:01:6C
                Channel:6
                Frequency:2.437 GHz (Channel 6)
                Quality=56/70  Signal level=-54 dBm
                Encryption key:on
                ESSID:"Bbox-D646D1"
                Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 6 Mb/s
                          9 Mb/s; 12 Mb/s; 18 Mb/s
                Bit Rates:24 Mb/s; 36 Mb/s; 48 Mb/s; 54 Mb/s
                Mode:Master
                Extra:tsf=000000125fb152bb
                Extra: Last beacon: 40020ms ago
                IE: Unknown: 000B42626F782D443634364431
                IE: Unknown: 010882848B960C121824
                IE: Unknown: 030106
                IE: IEEE 802.11i/WPA2 Version 1
                    Group Cipher : TKIP
                    Pairwise Ciphers (2) : CCMP TKIP
                    Authentication Suites (1) : PSK
                IE: WPA Version 1
                    Group Cipher : TKIP
                    Pairwise Ciphers (2) : CCMP TKIP
                    Authentication Suites (1) : PSK
                IE: Unknown: 2A0100
                IE: Unknown: 32043048606C
                IE: Unknown: DD180050F2020101820003A4000027A4000042435E0062322F00
                IE: Unknown: 2D1A4C101BFF00000000000000000000000000000000000000000000
                IE: Unknown: 3D1606080800000000000000000000000000000000000000
                IE: Unknown: DD0900037F01010000FF7F
                IE: Unknown: DD0A00037F04010000000000

I did the following (after looking for fixes of similar problems), but unfortunately
this fails to fix my issue.
sudo modprobe -r iwlwifi
sudo modprobe iwlwifi 11n_disable=1

This is a snapshot I obtained via iwscanner, as you can see even when the wifi is working there is small losses

I did this following the following this thread, worked well for a few hour but I got a disconnection :(
Here is what I did:
statquant@euclide:~$ sudo modprobe -rfv ath9k
[sudo] password for statquant:
rmmod /lib/modules/3.2.0-34-generic/kernel/drivers/net/wireless/ath/ath9k/ath9k.ko
rmmod /lib/modules/3.2.0-34-generic/kernel/net/mac80211/mac80211.ko
rmmod /lib/modules/3.2.0-34-generic/kernel/drivers/net/wireless/ath/ath9k/ath9k_common.ko
rmmod /lib/modules/3.2.0-34-generic/kernel/drivers/net/wireless/ath/ath9k/ath9k_hw.ko
rmmod /lib/modules/3.2.0-34-generic/kernel/drivers/net/wireless/ath/ath.ko
rmmod /lib/modules/3.2.0-34-generic/kernel/net/wireless/cfg80211.ko

statquant@euclide:~$ sudo modprobe -v ath9k nohwcrypt=1
insmod /lib/modules/3.2.0-34-generic/kernel/net/wireless/cfg80211.ko
insmod /lib/modules/3.2.0-34-generic/kernel/drivers/net/wireless/ath/ath.ko
insmod /lib/modules/3.2.0-34-generic/kernel/drivers/net/wireless/ath/ath9k/ath9k_hw.ko
insmod /lib/modules/3.2.0-34-generic/kernel/drivers/net/wireless/ath/ath9k/ath9k_common.ko
insmod /lib/modules/3.2.0-34-generic/kernel/net/mac80211/mac80211.ko
insmod /lib/modules/3.2.0-34-generic/kernel/drivers/net/wireless/ath/ath9k/ath9k.ko nohwcrypt=1

Comment: Do you have any entries in your `/var/log/syslog` when this happens? Another thing you could try is `sudo tshark -w dump.pcap`. This writes all your network traffic to that file. Maybe shortly before there is some special packet. Last option: Install `dstat`, start it in a console and look what happens around the disconnect. Maybe there is some suspicious system activity.
Comment: `iwlwifi` solutions are not what you're looking for. You don't have an Intel WiFi adapter, but an Atheros one, managed by `ath9k`.
Comment: What's your model of S3? (eg aspire 34347-5643US). This matters because this line has different cards. I noted that one of them has an Atheros AR5BWB225 card that works out of the box.
Comment: Thanks for the `iwscanner` graph! Are other devices in your wireless network also affected by this issue? It seems that your AP is completely gone (reboot? crash? hardware fault?) for a little while.
Comment: @gertvdijk: Hey, yeah I think the big "hole" is a little bit fake. By the way I had iwscanner installed on my wife's laptop (an HP running Ubuntu 10.04), which does NOT have the problem. We also see some little stops... I am a bit lost
Answer: Here's what you can do check the frag and rts settings on your gateway. I believe the defaults are frag 2346 rts 2347 so do this command:
sudo iwconfig wlan0
frag 2346 rts 2347

Hope this helps!
Answer: As mentions in here: http://ubuntuforums.org/showthread.php?t=2018238
There is a easy way to fix your problem
Try these command
sudo modprobe -rfv ath9k
sudo modprobe -v ath9k nohwcrypt=1

If it work, make it permanent by add these line to /etc/rc.local
Or create (or edit) /etc/modprobe.d/ath9k.conf
by this command
gksudo gedit /etc/modprobe.d/ath9k.conf

and add this to /etc/modprobe.d/ath9k.conf
options ath9k nohwcrypt=1
Comment: Ok I tried... It was promissing but I got a disconnection after a few hours :(. As usual when it happen I CANNOT find any wifi network so my only solution is to reboot
Comment: OK what I did was that I made the changes permanent as noted, if executing the command lines did not fix, the permanent file solution seem to have fixed it. THANKS
Answer: Can you try the backported 3.5.x kernel? Install it with sudo apt-get install linux-image-generic-lts-backport-quantal. It is in the repository. Maybe the new kernel has newer drivers for your card.
Off: At our dormitory a 3.0.0 -> 3.2 upgrade solved a problem like this.


Is it safe to substitute html

Question: (I am still very new to Javascript and JQuery) I am trying to keep my code clean by creating one js file per html file. I also have a couple of common js file containing code used by page-specific js files.
I was searching for solutions to import/include other js files in a given js file and I came accross this one. It refers to $.getScript().
Instead of using multiple  as imports/includes in my html pages, could I move them to my js files and use $.getScript(...) instead? I mean, is it safe? Is it a good practice?
EDIT
Is it safe regarding cyclic references?
EDIT II
To make it more clear, let's imagine I have a1.js, a2.js and a3.js.
For a1.js:
$.getScript("a2.js");
$.getScript("a3.js");
...

For a2.js:
$.getScript("a3.js");
...

For a3.js:
$.getScript("a2.js");
...

There is a potential infinite loop between a2.js and a3.js. Should I handle it with something like this in each js file:
var vari;

if (typeof vari === 'undefined') {
    vari = 1;
}

Comment: that's what google.load() does.
Answer: Regarding good Practice that answer is as always... it depends.
Your Page Style
Contra:

If you for example use a script to substitute some page fonts, the effect will be that the font change will be even more visible for the user.
If your script changes the height of some elements, this will be very noticeable.

PRO:

If you load a Script to handle a specific form, that the user first has to edit, there is no problem at all
If you load a Script that starts animation that can be substituted with a single loading animation you can do this.
If your page is a application with many views and models, you can use getScript like getJson, in this case your page speed will greatly improve.

Your Coding Style

Not every Page and Script is structured to be used this way. JQuery's  $(document).ready() fires every registered handler once, even after the event occurred. This does not necessarily mean every handler works this way, certainly not the DOM2 Events.
If you have anywhere inline Scripts it will no longer work.
You can no longer guarantee a certain order your initialization code will have, so you can run in problems have to add more checks, that e.g. a expectedly visible container is still visible.

Whats the reward?
On high performance pages, you gain some thats clear. But script tags at the end of the page can do the same thing with half the work (mainly: remove inline scripts). In my opinion getScript is something like a last reward, you should not overuse it, because the potential to not only scare other developers but also your customers away is clearly there. I would only use it in the environment of a web application, because here are the real benefits
UPDATE response to your comment
Using getScript on your page should look like this:
//since you need it there will be some kind of wrapper
var initClosure = function() {...}

if(typeof optionalNamespace == 'undefined') {
    $.getScript('/foo.js', initClosure);
} else {
    initClosure();
}

All depending code is in initClosure, and you check a namespace, or variable name (even something like window['blub'] or simply blub will work). You will need this, since the on getScript depending function, wich typically sets default values or appends something to the dom should only be called once.
Nevertheless I don't really see the point in cyclic references, because this would mean:
load script 1 -> wait -> loaded ->load script 2 -> wait ->loaded -> [...] ->load script 1
This situation should be avoided for at least 2 reasons

The browser can not predict this. If there are several script tags, your browser will take care of parallel downloads, so the overall speed (simplified & rough) is the time the biggest file will need to load. In my Example it will take the sum of the script loads.
Initialization of your scripts will be handled twice, so any state will get lost.
Comment: What is your answer to the main question? Yes or No? I have updated the question with more information to explain the issue.
Comment: OH... If you are thinking about loading in a hierarchical  order the answer is **no**. Loading 3 scripts without any possibility for parallelization as really slow. I think a good rule of thumb is: If the user klicks a button he expects to wait for something, so you can load a script, if your scripts are expecting something that isn't there, change your scripts.
Comment: Ok, but I see a contradiction here. How come it would be safe to load js files with circular references from the HTML page and not with $.getScript() for js files instead?
Comment: I have edited a little bit, but I am not sure I really got the _files with circular references from the HTML_ completely...
Comment: I am referring to the case where function f1 belonging to a1.js calls f2 belonging to a2.js, and where f2 calls f1 too.
Comment: Ok, I found out about wro4j and Google's Closure compiler, so this point is becoming moot.

Is it safe to substitute html


Extreme cold: Pipes seem ok, except hot water for bathtub which only trickles, despite being closest to water heater. Can it be frozen? Burst?

Question: Situation as described in the question. We have a peer & beam foundation. I already went under the house to check for a possible leak. The bathtub pipes are impossible to get close to, but from about 6-8 feet away I couldn't see any signs of a leak, nor could I hear any water drip or squirt or anything. The hot water pressure on the bathroom sink, which is downstream from the tub, has always been weak but seems normal.

Any ideas on what is likely to cause the lack of hot water for the bathtub?
Should I keep running the hot water trickle, in the bathtub and the bathroom sink? Or should I rather shut off the main and try to drain all pipes?

Unfortunately, I can't access the 5 or so feet of pipes where the problem has to originate from.
Thanks for y'all's advice,
Hannes
Comment: One of the reasons it might have froze despite being the closest is that it might be the least used lines so the stagnant water was more likely to freeze
Comment: With a house on piers, all water pipes should be well insulated .
Comment: @blacksmith37: Most of them have some insulation, the problem is that the rest are hard to access. We live in Austin, TX, though, so addressing this hadn't been on the top of our priority list...
Comment: As an aside, if you do end up needing to inspect the 6-8 feet away pipes better than you can currently, I'd recommend getting a borescope -- they've become surprisingly affordable these days, and would be perfect for this.  I have this one and it works well: https://www.amazon.com/DEPSTECH-Waterproof-Inspection-Megapixels-Smartphone/dp/B01MYTHWK4/
Comment: @NateS. Thanks, it's great to know that's an option!
Answer: If it's frozen the water will not trickle.  It may be PARTIALLY frozen in which case running the water should eventually melt the ice and clear the line.  Run it slowly so that you don't dislodge the ice and have it block elsewhere.
Any water that is running in your pipes will be > 32F (0C) and should melt any ice it runs past.
Comment: Thanks! Yeah, I've been running it for so long now, and the trickle is so steaming hot, that I can't imagine it wouldn't have melted any potential ice by now. But then, what else could be causing the continuing lack of water coming through??
Comment: Is this the only tap you have open, others are closed?  Only a trickle out of one tap is one of three things, leak in pipe, blockage in pipe, or other pipes/taps are open and pressure has dropped to that tap.
Comment: @crip659 I've closed and opened the other taps open without noticing much difference, certainly not account for the issue. After four years without pressure issues in the bathtub pipe, now, over night (and a record cold snow storm night at that), there's only a tiny stream of hot water coming through.
Comment: Sounds like a leak.  Insulation will dampen the sound of water, but check the shutoff valves.  Is this only the hot water tap or is the cold water the same?
Comment: Sorry, meant to say "not enough to account for the issue." It's only the hot water tap, cold water is fine.


Pentaho Reporting Module: cannot publish the report on server

Question: I have the error that I can't publish reports on pentaho.
The full log you can find it here: http://pastebin.com/7yU6Dz8x
The error is: java.lang.RuntimeException: org.pentaho.reporting.designer.extensions.pentaho.repository.util.PublishException: The File exists and override has not been specified.
What am I missing? I am using latest Pentaho CE, and the data source of the report is a mondrian scheme. (MDX Query)
Answer: Solved with the upload of the report from pentaho web interface.
Comment: Hi, Im getting the exact same error, can you elaborate on the solution


How do I repair exterior window casing after burglar bar removal?

Question: A previous contractor damaged the exterior wood casing around a vinyl replacement window while removing burglar bars. The window is now quite drafty and there may be some moisture ingress as well. What are my options for repairing the damage or replacing the casing entirely?
A few options I have considered so far:

patch holes with wood filler, reseal edges with silicone caulk
cut around damaged areas, patch with fresh lumber, reseal w/ caulk
replace or cover over with a vinyl casing replacement

Given the nature of this damage, are there any other window components that may require repair? E.g. flashing
Answer: It's hard to tell much from that image, but I'd suggest that

Yes, it's probably safe to assume there's other damage. Inspect carefully.
Covering the casing will allow it to rot without you ever knowing and will be loud! We have aluminum covered window casing and I hate it - rain drops sound like they're pounding on the covers - vinyl would be quieter but still...

You can patch holes, but the bigger the hole, the more effort it will take to get it right. I can't tell how big those holes are from this image.

If they're big enough, you could drill them out slightly to match the diameter of the next larger size of dowel and fill them with a dowel. Much better quality patch than trying to fill a large hole with wood filler.

Patching in new wood to replace a section with several holes is a good idea, but it needs to be a snug fitting patch to ensure no water works it's way through the joints and gets behind the wood, rotting it from the back side. I've done this for a couple of interior pieces, but never exterior.
Full replacement of all the casings is probably the "gold standard" answer, but is also the most expensive and time consuming.
Comment: Thanks. My repairs will probably require a mix of wood dowels for smaller holes at the top and new wood patches for the larger damage near the bottom.

For new wood patches, do you recommend wood glue for a snug fit at the joints? I've also read that an angled joint, sloping down to the exterior, will help keep moisture out.

When installing the patches, should I apply anything underneath the new wood to help with waterproofing or air sealing? E.g. caulk, brick/mortar sealant, or expanding foam
Comment: Absolutely glue in any patches! Be sure to use a water resistant/proof glue, like Titebond™ III or similar. If you can bevel the cuts so that any moisture that might get into the joint has a nice, downhill path to get out, that's definitely a good option. As you pull a piece out that you're replacing, take a look at what's between the wood & brick - that'll give you an idea of how it was waterproofed/flashed to begin with - you'll probably want to replicate that. If you have additional questions about that, please [ask a whole new question](https://diy.stackexchange.com/questions/ask).
Answer: Get some epoxy based wood filler to double as an adhesive for filling that bit of delamination down low. After sneaking some inside the delaminated area, wedge a chunk of wood across there to close the gap as well as possible. Now strike the surface flat. The rest of the holes are easy to handle in one go with the epoxy based wood filler.
Prime and paint. Paint is the best protection to avoid further weather damage, so stay on top of that maintenance. It doesn't look like the delaminated area can survive much more exposure.


Is it possible to run Nuget update-package in parallel

Question: I have a large solution with about 30 subprojects. Each subproject depends on a nuget package which gets updated regularly. So I end up typing for example
Update-Package AcmeWunderLib
every few days. The problem is this process takes about 10 minutes to run with the result being a very small change in each package.config and $name$.csproj file. Is it possible to do this operation in parallel for some performance improvement or will any attempt cause Nuget to corrupt itself?
Comment: https://github.com/NuGet/Home/issues/1909#issuecomment-282645449
Answer: The package update time is consist of downloading package and uninstalling/installing package. The downloading action will execute only once when first time download it, so the uninstalling/installing action will occupy almost all update time.
According to your log, NuGet takes under a second to gather dependency info, but take too long time to uninstall/install package. It`s only takes 2-5 second to update a package for one project in my test. So please check your machine performance at first when you  encounter this issue.
For this issue, I would like provide you some troubleshootings:

Update your NuGet, NuGet team have more improvements in the pipe for 3.5rc and 3.4.5.
Clean the old version packages in your package feed and NuGet cache.
Disable other NuGet repositories except nuget.org, perhaps one of them is timing out.
Test this issue on other workstations or build servers, and you can create some projects in a new solution to verify this issue.

Hope that can help you.
Comment: In my book, 2 to 5 seconds is still pretty long for what should be a simple write to disk...
Answer: Here is the real solution.
DONT RUN UPDATE-PACKAGE FROM WITHIN VISUAL STUDIO

Close visual studio
Open up powershell from the desktop or start menu
Make sure nuget is on your path
Run the following command substituting devdept.eyeshot for your package and WeinCAd.Net.sln for your solution file.

nuget update -Verbosity detailed -Id devdept.eyeshot .\WeinCad.Net.sln

The whole process lasted less than 10 seconds.
EDIT
I have been warned that this does not do all the same things that running nuget update from within Visual Studio does. All the above does is change the base path for the DLLs. It can't add and remove references. However this is enough for my use case.
Comment: I can't mark it as the answer yet. There is a timeout when you answer your own question. But you can upvote it :)
Comment: Glad to know that you have resolved this issue. Please mark your answer which is benefit to other communities who has the same problem when you free.


solving Work distribution related problem easily

Question: If Mar, Rox, & Haz writes 9, 4 & 10 hours respectively, then 7 stories are made. If Mar writes 3 hours, Rox writes 8 hours, then 5 stories are made. If Rox writes 6 hours, Haz writes 5 hours, then 4 stories are made. How long does it take each writer to make 1 story writing alone?
is there any general rule to solve this question? How will I solve this?
Answer: Let $\frac{1}{m}$ the number of stories that Mar writes in 1 hour. $\frac{1}{r}$ and $\frac{1}{h}$ have similar meanings.
Mar writes in 9 hours $\frac{9}{m}$ stories. Rox writes in 4 hours $\frac{4}{r}$ stories. Haz writes in 10 hours $\frac{10}{h}$ stories. Together they write in $9,4$ and $10$ hours 7 stories respectively. Therefore the equation is
$$\frac{9}{m}+\frac{4}{r}+\frac{10}{h}= 7$$
The other two equations have to be set up similarly. Then you have three variables and three equations. This  equation system has a unique solution.


How to change envelope sender address using phpmailer?

Question: With php mail() I can write
mail('email@example.com','subject!','body','From: email@example.com','-f firstname.lastname@example.com');

But how can I do the same with phpmailer ?
Answer: The relevant line in Theolodis answer is:
$mail->SetFrom('email@example.com', 'First Last');

There is no need to use AddReplyTo() this is something completely different.
You only need to set your from address (and name optionally) by using SetFrom(). If you look at the code, SetFrom() takes three parameters:
/**
 * Set the From and FromName properties
 * @param string $address
 * @param string $name
 * @param boolean $auto Whether to also set the Sender address, defaults to true
 * @throws phpmailerException
 * @return boolean
 */
public function SetFrom($address, $name = '', $auto = true) {
....

the third parameter (defaults to true) and therefor the envelope sender gets set to the same address as the sender.
It gets interesting if you want to set different addresses as envelope sender and From Address. This is the way how to CHANGE envelope sender. Therefor you have to set the $sender property of your PHPMailer instance like this:
  $pMail->firstname.lastname@example.com';
  $pMail->SetFrom('email@example.com', 'First Last', FALSE);

Answer: This example shows how.
the relevant lines:
$mail->SetFrom('email@example.com', 'First Last');
$mail->AddReplyTo('firstname.lastname@example.com', 'First Last');

As Hannes Morgenstern correctly suggested, the answer is:
$pMail->email@example.com';
$pMail->SetFrom('email@example.com', 'First Last', FALSE);

Comment: I don't believe that `SetFrom()` or `AddReplyTo()` address the OP's questions of *envelope* sender. See the bottom of https://stackoverflow.com/a/18053334/4692205 regarding `Sender` variable.
Answer: The -f flag is set with $email->Sender
This is the Envelope From which allows the email server to evaluate the sender's email address before receiving the rest of your email data
SetFrom - this is what email address the end user will see as the message coming from
AddReplyTo - this is what email address will pop up if they reply to the email
Sender needs to be clean to pass spam filters
SetFrom needs to be clean to pass spam filters
AddReplyTo doesn't really matter.  This allows a service to send an email on behalf of a user with an email address not managed by the service.
Comment: This is the ONLY correct answer. The other answers set the "From" header... NOT... the actual sender in the mail envelope - as per the question. That being said, I think the OP actually wanted to change the "From" header.
Answer: What worked for me (obscurely) using
$mail->SetFrom('email@example.com', 'Rupert Bear');

was to use localhost rather than directly access the smtp server e.g.
$email->Host='localhost'; // SMTP server this way you get from name (don't know why)

Now mails arrive in Outlook from 'Rupert Bear' [email@example.com]
Answer:
As Hannes Morgenstern correctly suggested, the answer is:

$pMail->email@example.com';
$pMail->SetFrom('email@example.com', 'First Last', FALSE);

The order is important. First
$pMail->firstname.lastname@example.com';

second
$pMail->SetFrom('firstname.lastname@example.com', 'First Last', FALSE);

Otherwise it won't work as Sender gets overwritten.


mysql rollback by error HANDLER not working

Question: I just build a stored procedure to test transaction in mysql.
But somehow it's not working.
Here is my code:
USE `test`;
DROP procedure IF EXISTS `testTran`;
DELIMITER $$
USE `test`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `testTran`()
BEGIN
    DECLARE EXIT HANDLER FOR SQLEXCEPTION rollback;
    START TRANSACTION;
    INSERT INTO `test`.`books`(`name`,`number`) VALUES ('asd', 20);
    ALTER TABLE `test`.`books` ADD COLUMN `name` VARCHAR(45) NULL  AFTER `number` ;
    COMMIT;
END$$
DELIMITER ;

Inside transaction, the second command is create an exist column which will be fail. What I expect is the first insert will be rollback. But actually, it's not. The insert do work.
Can anyone help?
Answer: In order to use transactions you need to convert the tables to a transaction table like InnoDB.
Optionally, you can rollback changes made by your stored procedure using SAVEPOINT.
DECLARE EXIT HANDLER FOR SQLEXCEPTION ROLLBACK TO identifier;

SAVEPOINT identifier;

START TRANSACTION;

INSERT INTO `test`.`books`(`name`,`number`) VALUES ('asd', 20);
ALTER TABLE `test`.`books` ADD COLUMN `name` VARCHAR(45) NULL  AFTER `number` ;

COMMIT;

Comment: Thanks for help. The table is using InnoDB. And I try your solution. But I got this error "Error Code: 1305. SAVEPOINT identifier does not exist"
Answer: The ALTER TABLE statement causes an implicit COMMIT before it is executed.


Ordering columns in 2D char array

Question: I have a 2D array where the top row is a row of letters (the alphabet) and the bottom row is the frequency that the letter above it occurs in a string. The idea is to place the letters in order of frequency along the top row.
At the moment:
input:
quickbrownfoxjumpsoverthelazydog
output:
abcdefghijklmnopqrstuvwxyz
11112111111111411211211111
Desired output:
oeruabcdfghijklmnpqstvwxyz
42221111111111111111111111
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<conio.h>

main()
{
    char string[100];
    char s[26][2];
    int c = 0, count[26] = {0};

    printf("Enter a string\n");
    gets(string);

    while ( string[c] != '\0' )
    {
        if ( string[c] >= 'a' && string[c] <= 'z' )
        count[string[c]-'a']++;

        c++;
    }

    for ( c = 0 ; c < 26 ; c++ )
    {
        if( count[c] != 0 )
        {
            s[c][1]=c+'a';
            s[c][2]= (char)(((int)'0')+count[c]);
            gotoxy(c,1);
            printf("%c",s[c][1]);
            gotoxy(c,2);
            printf("%c",s[c][2]);
        }
    }

    return 0;
}

Comment: You looked around for an elegant solution , so you don't want to sort the count arr ?
Answer: You should find the maximum every iteraton. You can use some fast sort algorithm, but a simple solution is:
for (c=0;c<26;c++) {
 int max=-1,letter,i;
 for (i=0;i<26;i++)
  if (count[i]>max) {
   max=count[i];
   letter=i;
  }
 count[letter]=-1;
 gotoxy(c,1);
 s[c][0]='a'+letter;
 printf("%c",s[c][0]);
 gotoxy(c,2);
 s[c][1]='0'+max;
 printf("%c",s[c][1]);
}

(Of course, assuming that max<10)
Comment: So you can print it as a digit.
Comment: OK. then you should save in the array the value of `max`. not `'0'+max`.
Answer: Here is one approach: take each count, shift it left by five, and bitwise-or the number of the letter in the lower five bits. Sort the resulting numbers, and convert their least-significant five bits back to the letter by and-ing with 0x1F and adding 'a'.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int compare (const void * a, const void * b) {
    int ia = *(int*)a;
    int ib = *(int*)b;
    return (ia>>5) == (ib>>5) ? ia-ib : ib-ia;
}

int main(int argc, char* argv[]) {
    char string[100] = "quickbrownfoxjumpsoverthelazydog";
    int c = 0, count[26];
    memset(count, 0, sizeof(count));
    while ( string[c] != '\0' ) {
        if ( string[c] >= 'a' && string[c] <= 'z' ) {
            count[string[c]-'a']++;
        }
        c++;
    }
            // Shift the letter ordinal into the lower five bits of the count*32
    for ( c = 0 ; c < 26 ; c++ ) {
        count[c] = (count[c] << 5) | c;
    }
            // Sort the results using the custom compare function
    qsort(count, 26, sizeof(int), compare);
            // Print the letters by taking the lower five bits
    for ( c = 0 ; c < 26 ; c++ ) {
        printf("%c", 'a'+(count[c]&0x1F));
    }
    printf("\n");
            // Print the counts by ignoring the lower five bits
    for ( c = 0 ; c < 26 ; c++ ) {
        printf("%d", count[c] >> 5);
    }
    return 0;
}

Answer: A couple of things:

Arrays in C are zero-origin, which is to say that your indexes should be s[c][0] and s[c][1] - your code isn't crashing b/c you're lucky.
Typically, the array would be ordered the other way around: c[2][26]

As to the sorting … since we're only working with 26 elements and not 2.6 million, how and when you do it is of little consequence.  You can get away with doing a bubble sort.  You could get fancy and build some sort of doubly-linked list and sort it as you go, shuffling elements around.  Have fun with it!
Comment: Thanks very much - will look into bubble sorting

Ordering columns in 2D char array


Have no idea how to imlpement Quicksort

Question: I am trying to implement quicksort in this for just research. But i have no idea how quicksort works im looking at this algorithm but have no idea what or how to implement it right now im using bubble sort but how do i go ahead and implement quicksort?
# choose pivot
swap a[1,rand(1,n)]

# 2-way partition
k = 1
for i = 2:n, if a[i] < a[1], swap a[++k,i]
swap a[1,k]
→ invariant: a[1..k-1] < a[k] <= a[k+1..n]

# recursive sorts
sort a[1..k-1]
sort a[k+1,n]

This is my code below
int main()
{
srand(time(NULL));
    int length = 250000;
    double arr[length];
    for(int i = 0; i<length; ++i) arr[i] = rand();
   // mergeSort2(arr, arr+length-1);

        for(int i = 0; i < (length-1); i++)
    {
        for(int j = i+1; j < length; j++)
     {
           if( arr[i] > arr[j])
            {
               swap(arr[i], arr[j]);
            }
        }
    }

    ofstream ofs("input.txt");
    for(int i = 0; i<length; ++i) ofs << i << " " << arr[i] << endl;
}

Comment: Have you look at this first?
http://www.csanimated.com/animation.php?t=Quicksort
Comment: There is nothing wrong looking at the code right now. People usually forget the actual implementation in a matter of 5 seconds. What matter is understand the mechanism (how QS works).
Comment: Using Bubble Sort (or even thinking about), is not recommended. What is the trouble with your code anyway?
Answer: This animation is really helpful.
The heart of quick sort (Dive and Conquer) is simply the following:

Pick an element as pivot

In practice most of the time we don't care which one. As you will see by proof, picking a pivot randomly (instead of front / end / mid) will minimize the possibility of running into the worst-case.
For test purpose, pick the middle guy is a good choice.

Partitions   (l = left, r = right)
The goal is to partition your original array into two sets (virtually!!)
S_left = { x in S - {pivot} :  x less than or equal to pivot }
S_right = { x in S - {pivot} : x greater than or equal to pivot }
To ease the notation:

a[l]....a[i-1] are less than or equal to a[i]
a[i+1]...a[r] are greater than or equal to a[i]
and hence, at the end, a[i] (the pivot element) should be in its proper place.

Strategy
There are two common ways to program QS, but in general QS takes three parameters (Array, low, high), where low is the left-end index of the array, and high is the right-end index of the array (could be 2,3, 5,10, not necessarily 0, length-1)
Initially
l = low-1
r = high

advances l when A[l] less than or equal to pivot
decrements r when A[r] is greater than or equal to pivot
swap A[l] and A[r]
repeat this process until l is greater than or equal to r, and swap (pivot, A[l])
Call QuickSort(A, left, l-1)
Call QuickSort(A, l+1, right)

I am giving you most of the implementation.
Just work out with a small example (size 9 seems reasonable to me) on paper. Don't use rand until your implementation is correct.
Try this array:

myArray = 9,6,2,5,11,4,20,1,3

I can write more tomorrow.

Have no idea how to imlpement Quicksort


Can I restore my wiped out Religion in Civ 6?

Question: I was late to the religion party, so my neighbour snuck in and converted all my cities to his religion. Now I seem to be unable get my own religion back.
In the previous edition, I could use a Great Prophet, or just rely on my Holy City's strong pressure, but neither of these options seems to be available in Civ 6 (I have no Great Prophets available under Great People, it seems like they are only used to found a religion now?).
I have thousands of stored faith, but any unit I buy will have the dominant religion (my neighbour's).
I've tried looking through the civilopedia, to no avail.
Has anyone found a way of clawing back your own religion from destruction?
Answer: I believe you have lost the religious war, friend.
You are correct about Great Prophets; there are indeed a limited quantity of them. In my 6-player game on Prince difficulty, there were 4 Great Prophets. I believe you are also correct in saying they are used strictly for founding a Religion. I did not notice any other options for that unit during my game.
As you have mentioned, buying units with faith corresponds to the dominant religion in that city. If you still have citizens following your religion, there may be some small hope for the pressure to bubble and your religion to become dominant again, but that is unlikely at best. Cities spread pressure based on how many followers are in that city; the dominant religion will almost always be emitting the most pressure. If you chose traits that increase pressure in some way, your religion might resurface. Otherwise, I believe it has been lost to the waves of time.
DISCLAIMER: This game is a new release, and this evidence is almost all anecdotal from gameplay experience.
Comment: If Jerusalem is in the game, you can possibly "resurrect" your religion by becoming suzerain of that city; this automatically causes Jerusalem to become your founded religion and spread it as though it were the holy city. You probably have to get a little lucky to get your religion to spread past Jerusalem though.
Comment: That's pretty much what I though too. Accepting this pending someone discovering something we may have missed.
Comment: Does this mean its a race to convert the enemies cities with religous units. Once the majority they will start spreading your religion and cannot remove the religious buildings they build that now that assist your victory?
Comment: Maybe? Nothing will force them to keep spreading your religion once converted. Also religious units can now fight against other religious units via "religious battle", so you can actually defend against enemy religions more than before.
Comment: If you clear your holy city of any hostile religions, you can also resurrect your religion by building the Mahabodhi Temple wonder. This wonder grants you two apostles of your religion.
Answer: You actually might still have a chance. Killing religious units reduces that religion in a radius by up to 250. So just declare war on who ever is the majority and run over all the missionaries and apostles with horseman.
Comment: I believe winning in theological combat both decreases theirs and increases yours, while using a military unit just decreases theirs.
Comment: You can definitely trigger this effect by killing an enemy religious unit with one of your own military units, so in theory this approach could work. Presumably though you'd need the enemy civ to spam you with enough religious units first.
Comment: I thought that only applied if they lost a religious combat, not a normal combat. And since my religion is wiped out, I can't fight them with missionaries etc.
Comment: Yes, you are totally correct, only just managed to confirm this for myself today.


How to change the border-radius of everything in Bootstrap

Question: I found this answer, but I need change to square everything in Bootstrap (buttons, text fields, images, ...all)
I think this:

Or I have to specify each class to do this change like in the other answer?
Which is the best way to do it?
Comment: Compile your own mix http://getbootstrap.com/customize/ - you can change many attributes e.g. border-radius
Comment: Your best option is to edit and recompile the LESS files.
Answer: I think
html ~ * {
  border-radius: 0px !important;
  moz-border-radius: 0px !important;
  webkit-border-radius: 0px !important;
}

could do the job.


How can you use a function that is defined below its usage?

Question: I always thought that function a(){} is identical to a = function(){};
However, these two snippets behave differently:
a();
function a() {
  alert("Booya");
}

Prints Booya.
a();
a = function() {
  alert("Booya");
}

Fails with an exception, which makes sense, since a is really not defined when called.
So - what kind of 'magic' lets the first snippet work, even though a() is defined below its point of usage?
Answer: This is the difference between function declaration and function expression. This difference described well for example here.
Answer: In JavaScript all the declarations are hoisted. Means the variable can be used before it has been declared and function can be used before its declared.
  It's JavaScript's default behaviour to move all the declarations at top of the current script.
But this feature may lead to bugs in application so we use strict mode directive to avoid bugs. Strict mode does not allow to use variables without declaration.
more info at here
Answer: See this article for an explanation: http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting

Function declarations and variable declarations are always moved ("hoisted") invisibly to the top of their containing scope by the JavaScript interpreter.
Answer: No magic, proper coding is required. AFAIK

document is loaded and parsed, functions are 'loaded'. The the script is being executed. So far no problem _a() _ is found.
no function is 'maped'. The script si executed line by line. It tries to call a() and THEN assign function to a global variable a
Answer: Functions are defined global. But if you assign a function to a variable, as you do in the second case, the scope rules for variables come into effect: You can not call the function before its variable was defined.
Comment: Functions are not defined global - they are defined within the current scope. Take `function a() { function b() {} }` for example: `b()` is not available outside the `a()`-context. It's not a question about *global* or *not global* it's a question between *declaration stage* and *execution stage*.


SASS mixin using SASS rgba() function not working with interpolation

Question: The SASS documentation says rgba function can be called in 2 ways.
I created a codepen to demonstrate the rgba function in a mixin I am having problems with:
<code>$hd-color1: #366dbd;    // heading color
$hd-shadow1: 0.24;      // text shadow opacity

@mixin ColorAndTextShadow($color, $opacity) {
  color: $color;
  text-shadow: 3px 1px rgba( #{$color}, #{$opacity} );
}

h2 {
  @include ColorAndTextShadow ( #{$hd-color1}, #{$hd-shadow1} );
  font-family: Circular, Helvetica, Arial, sans-serif;
  font-size: 50px;
  font-weight: bold;
  text-transform: uppercase;
}
</code>
Thanks in advance for taking a look
Answer: I believe it's just a syntax error. You can pass in the variables in directly.
Please see the codepen
<code>$hd-color1: #366dbd;    // heading color
$hd-shadow1: 0.24;      // text shadow opacity

@mixin ColorAndTextShadow($color, $opacity) {
  color: $color;
  text-shadow: 3px 1px rgba($color, $opacity );
}

h2 {
  @include ColorAndTextShadow ( $hd-color1, $hd-shadow1 );
  font-family: Circular, Helvetica, Arial, sans-serif;
  font-size: 50px;
  font-weight: bold;
  text-transform: uppercase;
}
</code>
Comment: That worked.  I removed the interpolation from mixin but not from the @include in an earlier attempt to get it to work.  Thank you.


Is it possible to emulate Vulkan on a non Vulkan compatible gpu?

Question: I don't think there is much to explain here, since the question is pretty much in the title, but i'll try to explain myself better:
My current laptop's gpu does not support Vulkan, so i was wondering if it was possible to do something like d3d12 does, where if a specific function is not able to be performed by the gpu, it can be emulated by the cpu, while maintaing the program running and functioning, at the obvious cost of performance.
Can I achive something like that using Vulkan?
Answer: It's possible to emulate Vulkan on a sufficiently capable non-Vulkan API.  This is the point of the Vulkan Portability Initiative.  Indeed, there is already a Vulkan implementation on top of the Apple proprietary API Metal, and there is work being done to implement Vulkan on top of D3D12.
It probably would be possible to implement a version of Vulkan that ran partially on a GPU (to which you had some other API access) and partially in software on the CPU, but unless you're working with some kind of mobile device with integrated memory, the performance of such a system would probably be utter garbage.
If your goal is to better understand and develop for Vulkan, I'd suggest you investigate some of the existing efforts at creating a fully software Vulkan implementation.
If you're just trying to get some game to run better, I suggest you get a better laptop.
Comment: Do you have a few pointers to those existing efforts - assuming that we're indeed talking about *CPU*-based implementations, or ones that offload to OpenGL where that's possible? I've been looking at such projects but nowadays all one seems to find are projects that implement some other API on top of Vulkan...
Comment: This chart covers a lot of the "Vulkan implemented on top of X" projects:  https://github.com/KhronosGroup/Vulkan-Guide/blob/master/chapters/portability_initiative.md#translation-layer

I don't know of any concerted effort to implment a fully software Vulkan system.  If it exists it's probably part of the Mesa project:  https://www.mesa3d.org/
Comment: There's Google's Swiftshader project which claims to be CPU-based but which isn't 100% that on all supported platforms. On Mac, it depends on both Metal and MoltenVK...
Answer: Yes this is exactly what Mesa does. Also note that many older GPU's (prior to 2015, when Vulkan got released) support Vulkan (approx 2012, both nVidia and AMD), although this isn't the case for the Laptop variants. ymmv.
Comment: FWIW, Mesa's implementation is strictly X11 and Wayland, and requires DRI3 in the former. It does seem to work quite nicely.