Unity/Firebase - Project Bundle ID does not match any bundle IDs in your google-services.json files

Question: I'm making a mobile game on Unity, Android first.
And now I'm integrating firebase analytics.
After set info on Firebase Console and put google-services.json file into Unity project, Unity shows an error saying :
Project Bundle ID com.RetroSpirit.ToiletRush does not match any bundle IDs in your google-services.json files
This will result in an app that will fail to initialize.

Available Bundle IDs:

You need to either:
* Fix your app's bundle ID under "Player Settings --> Bundle Identifier"
or:
* Add another app to your firebase project
  Goto https://firebase.google.com/docs/unity/setup#add_firebase_to_your_app_1
  and add the new configuration file to your project.

UnityEngine.Debug:LogError(Object)
Firebase.Editor.GenerateXmlFromGoogleServicesJson:LogErrorIfEnabled(String)
Firebase.Editor.GenerateXmlFromGoogleServicesJson:FindGoogleServicesFile(SortedDictionary`2, String, LogMessage, LogMessage)
Firebase.Editor.GenerateXmlFromGoogleServicesJson:FindGoogleServicesFile(String, LogMessage, LogMessage)
Firebase.Editor.GenerateXmlFromGoogleServicesJson:UpdateJson(Boolean, LogMessage, LogMessage)
Firebase.Editor.GenerateXmlFromGoogleServicesJson:OnPostprocessAllAssets(String[], String[], String[], String[])
UnityEditor.AssetPostprocessingInternal:PostprocessAllAssets(String[], String[], String[], String[], String[])
UnityEditorInternal.InternalEditorUtility:ProjectWindowDrag(HierarchyProperty, Boolean)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

Here's the part of google-services.json,
 "client": [
    {
      "client_info": {
        "mobilesdk_app_id": "*:***********:android:****************",
        "android_client_info": {
          "package_name": "com.RetroSpirit.ToiletRush"
        }
      },
      "oauth_client": [
        {
          "client_id": "***********-********************************.apps.googleusercontent.com",
          "client_type": 1,
          "android_info": {
            "package_name": "com.RetroSpirit.ToiletRush",
            "certificate_hash": "****************************************"
          }

I don't know what should I check.
Project Bundle ID (the Package name on Build Settings - Other Settings - Identification) is exactly same as package_names in google-services.json.
Any ideas?
Answer: I understand you have fixed this by re-installing Windows but this is how I got passed this problem in case anyone else runs into this:
Make sure you have set your Package Name in Unity player settings (Edit > Project Settings > Player > Other Settings > Identification > Package Name).
Set to the same one you set up in Firebase (looks like com.CompanyName.ProductName).
Make sure you have imported the Firebase assets into your Unity project as described here https://firebase.google.com/docs/unity/setup and that the Firebase folder exists in Assets > Firebase. Changing the location of this folder seems to break things.
Answer: My case was in Unity and to fix it I added the google-services.json from the firebase project to the assets folder. I had only the GoogleService-Info.plist before.
Answer: Little bit funny to answer myself...
I found the reason of problem accidently. There was something wrong with my VC runtime so generate_xml_from_google_services_json.exe couldn't extract package name from google-services.json. (vc90.crt.manifest could not be extracted!)
Unfortunately, I couldn't fix that runtime error despite so many re-install of Visual Studio, VC Runtime and .net frameworks. Finally I re-installed Windows 10 and the problem just gone away... Still don't know what caused this error.
Answer: In our case we solved the issue by requesting a new google-services.json file from a collegue who has admin rights.
Answer: In my case, the issue was with the Package Name. So I followed the following steps and solved the problem:

Change the package name (com.companyname.appname) [everything in lowercase]
Delete the existing keystore
Add a new keystore and generating a fingerprint with Keytool
Delete the current app from the Firebase console
Add a new app with the correct package name and the generated fingerprint
download google-services.json again and Import to Unity under the Assets folder

Done! It works!!
Answer: hey everyone I found a fix to this issue I'm using mac pro m1
step to fix

reinstall visual studio
download Microsoft.NET.Sdk.Android from the visual studio website
restart the project

and after that, it will fix


How do I record from a Casio keyboard with different sounds/instruments using multi-tracking?

Question: How do I record different from a Casio keyboard to Audacity, where different sounds (bass, drums, piano, etc.) make up multiple tracks?
Answer: Obviously any synth can be connected via a jack to a soundcard's audio input.
Your steps:

Connect your synth to your PC via audio cable, not USB or midi.
Run Audacity and set the audio params.
Add a new track and arm for recording. Set the appropriate audio channel.
Record the track using a sound of your choice.

For other tracks repeat p3-p4.
I would recommend using a DAW instead, Adobe Audition, Reaper, Pro Tools, Sony Acid, Fruity Loops, Cubase, or some other instead of Audacity.
Comment: I don't know if listing those counts as recommendations, but here is a more inclusive list of software that doesn't recommend any specifics. https://en.wikipedia.org/wiki/List_of_music_software
Comment: And it's Audacity, not Audiocity.


scaling GDI draw size to window size with Win32

Question: I'm writing a Win32 application, and am trying to get the sizes of windows to scale consistently with the things I draw in them. As a simplest possible case, I'm trying to create a window with a drawn rectangle in it that exactly fills the window.
The documentation for CreateWindow() says the width and height parameters are in device units, while the documentation for Rectangle() says the width and height parameters are in logical coordinates, which I assume means they're measured in logical units. I thought setting a POINT struct with the length and width I use to create a window, passing the POINT through DPtoLP(), then using the resulting x and y values as the width and height of my rectangle should work, but the rectangle ends up being bigger than the window. In fact, the discrepancy seems to be exactly the same as when I don't try to translate the window dimensions at all before I use them for the rectangle. Where am I going wrong? The full test program I'm using:
POINT logicalUnitSize;

LRESULT CALLBACK    WndProc(HWND, UINT, WPARAM, LPARAM);

int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
    _In_opt_ HINSTANCE hPrevInstance,
    _In_ LPWSTR    lpCmdLine,
    _In_ int       nCmdShow)
{
    WNDCLASS wc{};
    wc.lpfnWndProc = WndProc;
    wc.hInstance = hInstance;
    wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
    wc.lpszClassName = L"Main";
    RegisterClass(&wc);

    POINT deviceUnitSize{ 200,200 };//width and height of window in device units

    HWND hwnd = CreateWindow(wc.lpszClassName, L"Size Test", WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT, deviceUnitSize.x, deviceUnitSize.y, nullptr, nullptr, hInstance, nullptr);

    //get width and height of window in logical units
    HDC hdc{ GetDC(hwnd) };
    logicalUnitSize = deviceUnitSize;
    DPtoLP(hdc, &logicalUnitSize, 1);

    ShowWindow(hwnd, nCmdShow);
    UpdateWindow(hwnd);

    MSG msg;
    while (GetMessage(&msg, 0, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return (int)msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_PAINT:
    {
        PAINTSTRUCT ps;
        HDC hdc{ BeginPaint(hWnd, &ps) };
        Rectangle(hdc, 0, 0, logicalUnitSize.x, logicalUnitSize.y);
        EndPaint(hWnd, &ps);
        break;
    }
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}

Comment: DPtoLP() does not do anything interesting yet.  You specify the *outer* window size in CreateWindow().  But can only draw on the client area of the window, smaller by the borders and the caption.
Answer: I believe the main issue here is that the size parameters to CreateWindow are for the non-client area, that is, including decorations like the title bar and border.
Use GetClientRect after creating the window to get the client area, or use AdjustWindowRect[Ex].
Comment: You were right; using AdjustWindowRect to get the dimensions to use for creating the window worked. The one thing I still don't understand is that my drawn rectangle does indeed fit just the same whether or not I pass the coordinates through DPtoLP first. Does this suggest that under the conditions I'm working in, device units and logical units are coincidentally identical? If so, would the way to test whether I'm accounting for the difference correctly be to find another device to try my program on where they're different?
Comment: The default [mapping mode](https://msdn.microsoft.com/en-us/library/windows/desktop/dd145045(v=vs.85).aspx) is `MM_TEXT`. "When no translation is in effect (this is the default), page space in the MM_TEXT mapping mode is equivalent to physical device space." I think this means you only need to worry about conversion when you change the mapping mode or apply a translation.


Finding Roman Numeral Degree of Measure with Accidentals

Question: I'm working on a Roman numeral analysis of the Minuet in G Minor by Petzold. The piece is in the key of G minor. In measure 12, there is an accidental which changes the B flat to a B natural. I've determined a chord that matches the music, by sound, but I'm not sure how to label the triad. Do I label it as a triad in a different key or do I skip labeling it? The triad in question is a B natural, D, F triad. I've attached an image of the sheet in question below.
Thanks,

EDIT:
Sorry I didn't mention it and my original question, but you were all very attentive in pointing out that I did it in the wrong key. I am working on redoing my work so far... Thank you for all your answers!
Answer: (As Dekkadeci said, your analysis is actually in Bf major, instead of G minor, so you'll have to adjust your Roman numerals!)
To the actual answer, though: keep in mind that Roman-numeral analysis strives to show the function of each chord. As such, whenever you encounter a chromatic chord, you want to explain how this chord is functioning.
In most cases, a chromatic chord will be a major triad (or a major-minor seventh chord) where you don't expect it. Often these chords will resolve down a perfect fifth, showing that they are functioning as a dominant of the succeeding chord.
In your example, the Bn creates a G7 chord, and that major-minor seventh chord quality really lends it a dominant flavor. Assuming it resolves to C, this G7 is thus functioning as the dominant of C. We can then do a little "algebra":
 G7/C
 V7/C (because G is V of C)
 V7/iv (because C is iv in G minor)

Giving this chord the label of V7/iv. (I note that you don't use inversions in your analysis, but it will be a V65/iv if you consider the Bn as the bass pitch.)
As a final test: How would you label the chord A C# E in G minor?
Comment: It actually hangs on to G7 for the following bar, before resolving to C minor, probably more likely in a Gm piece. Attributed to JSB,  by the way.
Comment: As is the more famous "Menuet in G"; it was almost certainly Pezold, not Bach!
Comment: Maybe attributed is the wrong word. Blamed?!
Answer: My answer assumes that, instead of assuming your analysis is in B flat major (your use of vi to label the first chord gives that away), your analysis is in G minor (so vi is changed to i, I is changed to III, you likely should insert an extra chord in Bar 7 where the F# is so you can more easily explain how the last chord there is i, etc.).
For the last chord in Bar 12 alone (the one with the B natural), I'd call that vii°/iv, as it tonicizes C minor (the subdominant of G minor).
Answer: It looks like your analysis was done "by eye" only, not "by ear" (which in the end, is the only thing that matters about music). If you can't "hear" a simple piece like this by reading the score (i.e. not by actually playing it), that is a gap in your musical training that needs to be filled!
All your roman numerals are wrong, because (even if you analysed "by eye") you ignored the title of the piece, which says "G minor" - unless you assume Petzold made a mistake in the title, of course.
Considering the harmonic cadences of each phrase, your B flat chord in bar 4 doesn't make much sense in G minor, compared with a D (major or minor) chord. That would then suggest that the B flat in bar 4 is simply an (accented) passing note, and by analogy, the B natural in bar 12 is another one.
Your analysis of bars 5-7 doesn't look right either - though you did get bar 8 right, though you might not have noticed the similarity between bars 8, 4, and 12. But I'm not going to do the whole of the analysis for you!


Which hook to use when a date is going to be saved into the database

Question: I have a situation where I would like to know when a date (for an event) is going to be saved into the database so that I can modify the corresponding date in another module to match it. That is it in a nutshell. I need to do this because of the way this other module works. What is the best hook to use to accomplish this? Is it hook_node_update?
Thanks.
Comment: Are you using this [module](https://drupal.org/project/date) ?
Comment: No I am not using the download and extend module. I created an event node type that uses the date module.
Answer: If you are only using nodes then yes, implementing hook_node_update is a good approach. You also will need to implement hook_node_insert if you need to do logic when the nodes are first created.
Answer: If its node as it seems to be you can use hook_node_update which will act when an existing node is updated and hook_node_insert which will act when a new node is inserted so here you will be using two hook or you can use hook_node_presave which incorporate both events insert and update.


How to approach hurdle models with multiple covariates in R

Question: I have count data that I standardized into continuous data (density) because the area surveyed varied among sites.  I have several sites in which the count was zero. The probability of observing a non-zero was 0.21 so I wanted to use a hurdle model approach. I also recorded several potential explanatory variables for each site. I would like to test a suite of candidate models to address which variables best explains my response and I am unsure how to conduct this with a hurdle model.
1) Do I separate the two models and select for the best logistic model for observations of zeros and a linear model for density and then run a hurdle model with the two best models or can I run multiple hurdle models and just use the model with the best AIC (not sure how to do this step)?
2) Do I have to use count data for a hurdle model?
3) If I can use continuous data, how?
Thanks for the assistance!
MD
Comment: Standardizing a discrete variable doesn't make it continuous; it's a discrete mixture. You could account for the area by using an offset (with a log-link), or if you're not sure the count will be directly proportional to area, by including it as a predictor (whose supposed relationship you can check for reasonableness via diagnostics, for example).
Answer: A standard hurdle model is a mixture model consisting of a logistic regression model modelling the zeros and a poisson model modelling the counts. Therefore, you would have to use the count data in order to fit the model. Seeing that the sites differed in area, I would use the area of the site as an offset in your poisson model. This should solve your second and third question.
In order to select the best hurdle model, maybe you could try a backwards selection procedure after incorporating all relevant predictors in both models, unless you have sound knowledge of which predictors will be associated with which part of the mixture model.
Comment: +1. I believe that what model functions call an _offset_ is also known (outside of model functions) as the _exposure_? Just in case that clarifies anything.


how to select and count same data used in other colum using sql

Question: My database table 'user' have below details
 ---------------------------------------
 id |  username  |   ref   |   email
 ---------------------------------------
 1  |  name1     |   0     |    firstname.lastname@example.com
 2  | name2      |   1     |    firstname.lastname@example.com
 3  |  name3     |   0     |    firstname.lastname@example.com
 4  | name4      |   3     |    firstname.lastname@example.com
 5  | name5      |   3     |    email@example.com
 6  |  name5     |   0     |    email@example.com
 ---------------------------------------

this means id 3 is the referrer of 4,5 and id 1 is the referrer of id 2 because same id is showing in column ref.
My question is  how to select name of id 4&5 using id 3
And how to count id 3 have how many referrals?
example ans: Name3= 2 ref , Name1= 1 ref
Comment: Please show your expected output and also what you have tried?  Can the referral hierarchy be more than one level deep?
Answer: You can select the user whose ref is id 3 by below query :
SELECT * FROM data WHERE ref = 3

Output :
id  username    ref email
4   name4       3   email@example.com
5   name5       3   firstname.lastname@example.com

And you can count the number of user whose ref id is 3 :
SELECT count(id) FROM data WHERE ref = 3

Output :
count(id)
2

Answer: Use following procedure in mysql
CREATE PROCEDURE `get_tree`(IN `id` NUMBER)
    BEGIN
     DECLARE refid NUMBER;
     DECLARE userid NUMBER;
     SET userid = id;
     SET refid=0;
     SELECT `ref` into refid
     FROM `user` WHERE `id`=userid;
     create table IF NOT EXISTS temp_table select * from user;
     truncate table temp_table;
     insert into temp_table select * from user;
     WHILE (refid is not 0) DO
       insert into temp_table select * from user WHERE id=userid;
         SET userid = refid;
       SET refid=0;
       SELECT ref into refid
       FROM user WHERE id=userid;
     END WHILE;
     select * from temp_table;
    END

Answer: select (select u2.username from user u2 where u2.id = u1.ref), count(*) as refs from user u1 where u1.ref > 0 group by u1.ref

this is my test code:
drop table if exists `user`;

create table if not exists `user`(
    id int primary key auto_increment,
    name nvarchar(250),
    ref int
);

insert into `user`(id, name, ref) values (1, 'user1', 0);
insert into `user`(id, name, ref) values (2, 'user2', 1);
insert into `user`(id, name, ref) values (3, 'user3', 1);
insert into `user`(id, name, ref) values (4, 'user4', 2);
insert into `user`(id, name, ref) values (5, 'user5', 3);

select (select u2.name from `user` u2 where u2.id = u1.ref), count(*) as refs from `user` u1 where u1.ref > 0 group by u1.ref

and the out put is:
|name|refs|
|use1|2|
|use2|1|
|use3|1|


Set Date object in JSON request object to server using Postman

Question: I have a web service that I want to test.I am checking it with the help of Postman. I am facing issues when I have to set the date object in the JSON.
Here is my User class:
P.S: I am using Flask-sqlalchemy to create the database models.
class User(db.Model):
    id = db.Column('id', db.Integer, primary_key=True)
    name = db.Column('name', db.String(60), nullable=True, default=None)
    username = db.Column('user_name', db.String(100), nullable=False, unique=True)
    dob = db.Column('date_of_birth', db.Date, nullable=True, default=None)

And here is my JSON data that I am trying to post to the 'register' route - http://127.0.0.1:5000/register
{
    "name": "Catherin Francisco",
    "username": "c_francisco",
    "dob": new Date("1988-06-27")
}

I am getting 400 Bad Request: Failed to decode JSON object while setting the 'dob' key-value pair.
Can anyone please help me to set up the date object in JSON.
Comment: You're doing this in the pre-request script section? body? What's actually been sent out?
Comment: body=>raw data=>json
Comment: You have to write date as iso date string like `2020-02-04T10:58:49.024Z`. Because javascript date object won't work at body unless you write it at prescript.
Answer: What you want to do is set the date in the pre-request script section and set the value in a variable. For example:
var timestamp = moment().format("YYYY-MM-DDThh:mm:ss.SSSZ");
pm.environment.set("timestamp", timestamp);

Then in the body of your request you can use it simply with {{timestamp}}
{
  "name": "Catherin Francisco",
  "username": "c_francisco",
  "dob": "{{timestamp}}"
}

Comment: I have an error: There was an error in evaluating the Pre-request Script:ReferenceError: moment is not defined
Answer: You should also add it at the very top of the pre-request script to avoid errors with moment:
const moment = require('moment');

Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Problem playing things that I come up with

Question: So basically I come up with some really good and progressive stuff in my head, but when it comes to play those things I cannot find the right notes on the guitar. Mainly because those malodies are too fast, and I cannot slow them down in my head. Any suggestions how can I improve my inner ear ?
I have tried to listen to different songs and play along by ear and I can see the difference in a day or two, but if I stop doing that for another day or two I have to start over again training my ear.
Also I have a problem deciding if the note should be higher or lower, but I can definitely tell that this note is not the right one, and in 99% of cases I am right.
btw, just passed this test
http://tonedeaftest.com/results?r=P166FD79
and got 100%, but I still have trouble in hearing differences or deciding whether I should play play higher note or lower one, especially when listening to low pitch notes.
Comment: Can you sing or whistle what you are thinking of?
Comment: @topomorto, no, when I try to I cannot find the right notes, I can hear that I am singing it wrong though.
Answer: People who are tone deaf do know they are "singing it wrong".  But let's assume that since you passed the test that you are NOT in fact tone deaf.
Humans learn to intuitively replicate pitch with their voice just by hearing the pitch.  Musicians have to learn how to replicate a given pitch on their instrument.  This learning process takes intentional practice and a great deal of time.  Eventually a musician begins to develop a memory of what to do to play a given note - much the same way we memorized what to do with our vocal folds and mouth and throat to reproduce a given sound with our voice or by whistling.
But my thoughts are that before you can begin to learn how to translate a melody to your guitar, you would need to be able to translate the melody in your imagination - to a vocal representation.  In other words you should be able to sing or hum or whistle the melodies you hear in your head.
If you cannot do this at this time, you might benefit from ear training.  I would recommend seeking out the services of a professional teacher to at least evaluate your current abilities and prescribe or recommend a course of instruction or training regimen that will help you get from where you are now - to where you need to be to accomplish your goals.
Here is a link to the Wikipedia article on Ear Training - Wikipedia
While you are working on ear training, you can also start playing scales backwards and forwards on your guitar.  Focus primarily on the scales you are most likely to use for your melodies.  Practice playing the 7 note diatonic scale through multiple octaves backwards and forwards.  Also practice playing pentatonic (5 note scales) to help with recognizing larger intervals.
Playing scales will help you internalize in your brain which fret and string combination corresponds to a given note.
I wish you success as you develop the ability to translate the melodies in your head into something you are able to share with the rest of the world.  Good luck!


Creating domain name checker

Question: I wonder how to make a domain name checker (testing for availability) for top-level domains?
Eg. to check if the domain: stackoverflow.com or stackoverflow.dk is available or not.
Do I need to be subscribed to a service to do this, or is there some simple magic behind such test?
Thanks
Answer: You need to do a WHOIS lookup - see http://www.aspdev.org/articles/build-whois-lookup-asp.net/
Comment: WHOIS the correct answer, but You have to be online to check.
Comment: @ckuetbach how could you possibly check domain name availability without being online?
Comment: I can't. But I wanted to make this clear. But you are right, it is obvious, that you have to be online to check the domain.
Answer: It seems there is a protocol for this check "A Domain Availability Check". I am not sure if this is only for the german .de domains or for all domains. Maybe this will help you a  little bit.
Comment: The protocol is for all domains, but most TLDs do not have a server that is actually running this service, and the one server I found via google which offers it was only for .de and was very unreliable.
Answer: Your best bet would be to create a webRequest object to fire off a whois request.  You can then parse the results from the HTML using regex.  I've done this on a number of occasions and it works well (providing the underlying website doesn't change)
Answer: an helpfullweb service client
http://www.whoislookup.be/wswhois/wswhois.asmx
referance
http://www.whoislookup.be/using-an-webservice-to-access-whois-search.aspx

Creating domain name checker


How can I determine which reference I'm missing in this Outlook interop code (OlItemType.olMailItem)?

Question: I'm using my Interop Outlook code, which required me to add a reference to Microsoft.Office.Interop.Outlook ("Microsoft Outlook 12.0 Object Library"; Version = 18.104.22.168)
Adding that reference caused all the redded up Outlook classes to resolve to more subdued hues, but attempting to build the project still causes a compiler error, namely, "One or more types required to compile a dynamic expression cannot be found. Are you missing a reference?"
The code is this:
Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application();
MailItem mailItem = app.CreateItem(OlItemType.olMailItem);
mailItem.Subject = String.Format("Platypus file generated {0}", GetYYYYMMDDHHMM());
mailItem.To = emailAddr;

When I 2-click that err msg, this is highlighted:
app.CreateItem(OlItemType.olMailItem);

Here's an even odder one:
"*Predefined type 'Microsoft.CSharp.RuntimeBinder.Binder' is not defined or imported*"

2-clicking it leads nowhere; maybe it will go away once I appease the first beast.
What additional reference do I need to add to get this to compile?
Answer: Microsoft.CSharp must be referenced.  It should be one of the available framework assemblies.


Why is this bash script not working?

Question: I'm making a bash script which checks the available space on disk:
if [ check_space -gt "85" ]; then
echo "removing"
else
echo "not removing"
fi

check_space returns a number like 52 and the check_space function is:
check_space() {
df /dev/sda1 | tail -1 | awk '{print $5}' | sed 's/%//';
}

It's returning ./backup.sh: line 63: [: check_space: a full expression was expected (I translated it from spanish, so that maybe not exact translation). What could be wrong?
Comment: Please re-run the script with LANG=C so that we get the exact error message.
Answer: Your condition isn't actually calling check_space, you need something like:
if [ `check_space` -gt "85" ]; then

Comment: @Ryan, no, this example works perfectly well.
Comment: You're absolutely right. I'll remove my false doctrine.
Answer: Here's how you can do it...
#!/bin/bash

CHECK_SPACE=`df /dev/sda1 | tail -1 | awk '{print $5}' | sed 's/%//'`;

if [ $CHECK_SPACE -gt "85" ]; then
echo "removing"
else
echo "not removing"
fi

I had to pull out my bash cheat sheet. Functions in bash can't return a value, only an exit status.
Comment: Usually, you write the function to print information to stdout, and then capture the output when you invoke the function: `space=$(check_space)`
Answer: "85" with the quotes is a string, not a number... -gt will not work.
suggest:
CHECK_SPACE=$(df -P /dev/sda1 | awk '$1=="/dev/sda1"{sub("%","");print $5}')

if [ $CHECK_SPACE -gt 85 ]; then
  echo "removing"
else
  echo "not removing"
fi

Why is this bash script not working?


How to change menu item URL in menus for Drupal 7 multiiste

Question: I am using drupal 7 multisite (sharing the same database, same code base) i.e
1) one.example.com
2) two.example.com
Everything is working correctly and my site using the same menus for all the sites.
for primary domain, menus are working correctly like
there is one menu item named as test and published to both the sites
but
If I access the first site i.e one.example.com then my menu URL is
one.example.com/test
and same when I access the secondary domain i.e. two.example.com then my menu URL should be two.example.com/test instead of one.example.com/test
and currently, menu URL is one.example.com/test
Answer: Try to add menu links as "Relative Paths", then a domain name will be added automatically depends on sites.
E.g. use /test , not one.example.com/test.
Comment: ThankYou for your help menu item link is already with the relative path, the same as you mentioned above but not works
Answer: I got solution to my question
The node URL is not updated in the menu so its taking primary site URL after updating URL it is working fine.
Just edit all the nodes and save as it is all the URL of menus will automatically be updated.
And in menu items, it will automatically consider current working site URL


hook_menu() not available for ajax loaded links

Question: I'm loading a datatable and its data into a panel, through ajax. Below is the link which can add the row(entry) to favorites. When I click the link, the jquery animation is executed properly but the hook_menu and it's callback function is not being executed. It looks like the hook_menu is not 'available'
This is the link
$link = array(
    '#type' => 'link',
    '#title' => t('Favorite'),
    '#href' => 'favorite/' . $item->nid,
    '#attributes' => array(
    'class' => array('use-ajax', 'favorite_item_button'),
    ),
);

And this is the hook_menu
function favorite_item_menu() {
  $items = array();
  $items['favorite/%'] = array(
    'title' => 'favorite item',
    'page callback' => 'favorite_item',
    'page arguments' => array(1),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

Do you see any mistakes? Am I doing something wrong, forgetting something?
Advice is much appreciated.
Edit:
- no php error logs
- no js error logs
tried: sitename.com/favorite/501 - got the error 'access denied'
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/8688/discussion-between-aboodred1-and-maarten-hartman)
Comment: did you clear Drupal cache?
Comment: yes I did, caching is not the problem. Also the JS is attached properly because the jquery animation works. More suggestions ? : )
Comment: when you add the link in the address bar what do you get e.g. `http://domain.com/favorite/54`
Comment: hmm, access denied is what I get. Does this mean I should add access arguments?
Comment: yes try to add `'access callback' => TRUE,` and clear Drupal cache
Comment: it works when I use the url and press enter. However, when I click on the link the menu and function is still not being called.
Comment: so when click on the menu, the link should load the page or fire ajax callback?
Comment: fire the callback (so the php function is executed without page refresh)
Comment: can you add `drupal_set_message('test');` in `favorite_item` function add see if you'll get the message
Comment: the menu_hook and the function to be called are working perfectly, without ajax. As said, if I go to sitename.com/favorite/501, the function is being executed and is working properly. When I click on the link (code in question), the hook_menu is not executed (so neither is the favorite_item function)
Comment: i think you need to add class `use-ajax` to menu item
Comment: tried, doesn't work :(
Answer: You need to add 'access callback' => TRUE, to your menu item.
Your menu callback should look like the following:
function favorite_item_menu() {
  $items = array();

  $items['favorite/%'] = array(
    'title' => 'favorite item',
    'page callback' => 'favorite_item',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}


Why no orthogonality of residuals and predictions in neural networks?

Question: One fact about linear regression is that the predictions and residuals are orthogonal. In other words:
$$ \sum_{i=1}^N \hat{y}_i (y_i-\hat{y}_i)  = 0
$$
In nonlinear regression, this fails to be the case.$^{\dagger}$
That does not make sense to me. I've simulated what happens and confirmed that the nonlinear regression lacks orthogonal residuals and predictions, but it still is not intuitive, particularly for an approach with a neural network.

The neural network above does some feature engineering to find three features to feed into a linear regression, but the neural network is a nonlinear regression, since there would be a ReLU activation function in the hidden layer acting on the red, blue, and yellow parameters. However, if I got lucky and guessed the features in the hidden layer, then I could call my regression linear.
Those seem like the same model to me, yet one would be a linear regression with orthogonal residuals and predictions and one would be a nonlinear regression that lacks orthogonal residuals and predictions.
What gives?
A few links to threads that discuss this lack of orthogonality:
regression - does R2 only apply to measure linear regression performance?
Is R-squared truly an invalid metric for non-linear models?
$^{\dagger}$I am not sure if it can hold for a nonlinear regression, but it at least does not have to hold for a nonlinear regression.
Comment: orthogonality is a fundamentally linear notion: it's the inner product between the residuals and predictions (and inner products are the same thing as linear functions when both exist). I don't see any reason why a general nonlinear model would impose orthogonality necessarily, though if the set of linear models lies within the span of the nonlinear model, it is possible that it could if this leads to it achieving minimal MSE.
Answer: It appears this is due to the instability of the hidden features and the dynamics of gradient descent with these shifting features.
I did some experiments fitting with a small network with 3 hidden neurons, fitting one dimensional nonlinear data.
If you freeze the first layer, and only run gradient descent on the last layer, then the residuals go to zero:

Here I froze the first layer at 5000 epochs. The red line is plotting $\sum_{i=1}^N \hat{y}_i (y_i-\hat{y}_i)$ for the NN's predictions; the purple shows the same sum calculated with linear regression on the hidden features. The other lines show the activations of the hidden nodes and how they shift around until I freeze them.
If you just run forever, the residuals will go to zero if the hidden features stop shifting around:

Code here
Comment: do you think this might just be because when you fix all but the last hidden layer, we are simply doing linear regression with a different set of features?


Trying to use USB guitar cord in Windows 7

Question: I was given an Ibanez Acoustic/Electric for Christmas. I don't think it was brand new, but it looks and sounds great. I want to use this:

Which I got from Amazon for like $12.
When I plugged it into my usb port, the windows drivers installed themselves, and I can "see" it in my list of recording devices:

Trouble is, the level indicator shown in the above picture does not indicate activity.
I've gone into the properties of that device and checked/adjusted everything I can find to no avail. The computer is "listening to this device," The levels are at 100%, I've tried various combinations of "Exclusive Mode," If I plug the guitar directly into my amp (with a normal 1/4" plug), the amp picks up the guitar. I've tried various combos of disabling other sound devices, too.
The goal is to use FL Studio to record, but I'm pretty sure that the problem is in Windows as indicated by the indicator showing no activity. In FL Studio I'm using Asio4all and I see the USB cord listed on my mixer as an input option.
My computer is windows 7 64 bit, and I've tried FL Studio 11 in 64 bit mode and 32.
Ideas?
Edit: The red LED on the usb jack blinks steady about twice per second. Maybe someone knows what that means?
Answer: All guitar link type cables require the correct drivers to be installed and set up. They do not generally work straight out of the box, and ASIO4ALL doesn't generally identify them correctly.
Look in your documentation that came with the cable and identify the drivers and setup process you need (they are all a bit different)
The sound quality from these is not great, they don't compare to having a decent soundcard and normal guitar lead.
Comment: That's not a bad starter audio interface. Yes.
Comment: Thanks for the response. I've seen a few YouTube vids that show this cord working right out of the box, and due to the fact that I got no documentation (only the cord in a bag), I was really hoping that I didn't need anything additional. I'm now returning it and am strongly considering [this](https://www.amazon.com/BEHRINGER-Audio-Interface-1-Channel-UM2/dp/B00EK1OTZC/ref=pd_cp_267_2?pd_rd_w=qFSRo&pf_rd_p=ef4dc990-a9ca-4945-ae0b-f8d549198ed6&pf_rd_r=3631FMWX7J8769W4WNRQ&pd_rd_r=13829913-0e27-11e9-8165-45849ee12971&pd_rd_wg=7e8cd&pd_rd_i=B00EK1OTZC&psc=1&refRID=3631FMWX7J8769W4WNRQ). Better?


Trouble understanding on how to calculate all possible events of sample space S

Question: While doing some exercises I had following question:
How many possible events can be defined if the sample space S looks as follows:

$S = \{1,2,3\}  $
$S = \{1,2,3,4\}  $
$S = \{s_1, ..., s_n\}$

The solution is $8$, $16$, $2^n$.
Can someone explain me why the solution is $2^n$?
Comment: Any subset of the (finite) sample space is an event. You can look up or figure out how to see that the number of subsets of an $n$ element set is $2^n$,
Comment: How would you get the answers $8=2^3$ or $16=2^4$? This is not difficult to generalize.
Comment: @Arthur The thing is, I don't get how the solution is e.g. 8.
Comment: Then I suggest you start there. List all possible options. Try to be systematic. Then count them. Try to be clever about the counting, so that counting hundreds or thousands isn't much more work than counting the 8 you have this time.
Answer: I think it's because each number in the sample space is either part of the event or not, which is two possibilities. So with the three numbers 1, 2 and 3, there are 2 x 2 x 2 possibilities which is 2$^3$ This is then generalized with n numbers to 2$^n$
Answer: Hint: You can count the events. The sample space $S$ contains $n$ possible outcomes. What is the event space at the first case?
It is $\{\emptyset,1,2,3,12,13,23,123\}$. $\emptyset$ is the empty set (Never forget it!). It constains $2^3=8$ events. If you say that $k$ is the number of elements of a sequence then it can be written as a sum: $\sum\limits_{k=0}^n \binom{n}{k}=2^n$.
Answer: If the set has $n$ elements, then you are looking for the number $2^n$.
If you know some combinatorics, it follows from:
Let $S$ the sample space with $n$ elements
total events: all individual events + all combinations of 2 events + all combinatinations of 3 events + .. + all combination of $n-1$ events + all combinations of $n$ events (only 1 comb.)

all individual events: this is the combinatoric of $n$ in $1$
all combinations of 2 events: this is the combinatoric of $n$ in $2$
-all combinations of 3 events: this is the combinatoric of $n$ in $3$
...

So you need the number :
$${{n}\choose{0}}+{n\choose{1}}+{n\choose{2}}+{n\choose{3}}+\cdots+{n\choose{n-1}}+{n\choose{n}}=2^n$$


Original class name can be found after running proguard

Question: I am new in proguard and I use http://www.javadecompilers.com to verify my progurd setting.
The class name have been obfuscated. But the original class name can be found in javadecompiler.
Is there any setting to hide the original class name?
java decompiler output
File : proguard-project.txt
-optimizationpasses 5
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
#-dontskipnonpubliclibraryclassmembers
-dontpreverify
-verbose
-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*

#-keep public class * extends android.app.Activity

-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgentHelper
-keep public class * extends android.preference.Preference
-keep public class * extends android.util.Log

-keepclasseswithmembernames class * {
 native <methods>;
}

-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet);
}

-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet, int);
}

-keepclassmembers class * extends android.app.Activity {
public void *(android.view.View);
}

-keepclassmembers enum * {
public static **[] values();
public static ** valueOf(java.lang.String);
}

-keep class * implements android.os.Parcelable {
public static final android.os.Parcelable$Creator *;
}

-keep class android.support.v4.app.** { *; }
-keep interface android.support.v4.app.** { *; }
-keep class com.actionbarsherlock.** { *; }
-keep interface com.actionbarsherlock.** { *; }

-keepattributes *Annotation*,SourceFile,LineNumberTable

# goolge map
-keep class android.location.** { *; }

-keepnames class com.google.android.maps.** {*;}
-keep public class com.google.android.maps.** {*;}

-dontwarn com.google.android.maps.GeoPoint
-dontwarn com.google.android.maps.MapActivity
-dontwarn com.google.android.maps.MapView
-dontwarn com.google.android.maps.MapController
-dontwarn com.google.android.maps.Overlay
-dontwarn com.google.**

-keep class com.google.** { *; }
-keep interface com.google.** { *; }

Answer: The reason why you can determine the original file name is due to the SourceFile attribute in this line:
-keepattributes *Annotation*,SourceFile,LineNumberTable

You can change that behavior by removing it:
-keepattributes *Annotation*,LineNumberTable

or by forcing ProGuard to use a placeholder instead of the original file name:
-keepattributes *Annotation*,SourceFile,LineNumberTable
-renamesourcefileattribute SourceFile


Is it possible to filter an absolute path from Apache ErrorLog?

Question: Using Apache is it possible to edit the Virtual Host to exclude a certain absolute path (such as /var/www/html/blog/wp-content/plugins/my_plugin/) from log to the ErrorLog file?
I need to stop it from log warnings like this:
PHP Warning:  Illegal offset type in isset or empty in /var/www/html/blog/wp-content/plugins/my_plugin/tool.php

However I need to see other warnings, it's only about one file that's the reason why I would like to keep my php.ini unaltered.
Answer: That error message comes from php framework and mod_php, so the answer is no.
If you don't want to see them in httpd you will have to separate them (interpret php with php-fpm and proxy requests to it through mod_proxy_fcgi).
Apache httpd has no control over error messages generated by mod_php, so you do have to change php.ini or the above option, which I recommend (separation).


How to interpret a mosaic plot in R?

Question: The mosaic plot shown bellow is the product of this code
mosaicplot(table(survey$Air,survey$Satisfaction),
  main = "Satisfaction with Airconditioning and Overall Satisfaction")

Bear in mind that the satisfactions were coded as binary, where levels of satisfaction of 1,2,3 are coded as 0, and levels of satisfaction of 4,5 were coded as 1. I do not really know how to interpret the mosaic plot. Any help is appreciated!
Answer: A mosaic plot recursively partitions the area in the plot by the proportions of each margin conditional on all previous margins.

Thus, the widths of the cells in the two columns corresponds to the first margin Air and shows that there were many respondents that had lower satisfaction with air conditioning (0) and only few with high satisfaction (1).
The height of the cells correspond to the second margin Satisfaction and show the conditional proportion for overall satisfaction given satisfaction with air conditioning. This brings out clearly that those with low air conditioning satisfaction (left column) have a low overall satisfaction (lower left cell). In contrast, the proportion of high overall satisfaction (lower right cell) is much higher among those with high air conditioning satisfaction (right column).

The plot can be enhanced by using a shading for the "dependent" variable (second split) but with zero spacing. Such a version is produced by the default plot() method if both Air and Satisfaction are coded as factor variables. Possibly reversing the order of the levels on the y axis might help. Try:
plot(Satisfaction ~ Air, data = survey)
plot(Satisfaction ~ Air, data = survey, ylevels = 2:1)

(Had your example been reproducible, we could have shown you this in more detail.)
Comment: Faster and more general than my answer (+1).
Comment: Thank you very much for your answer, it was really helpful!
Answer: A mosaic plot helps to visualize the statistical association between two categorical variables, in your case between having AC (0, 1) and high satisfaction (0, 1).

The frequency distribution of the first variable (AC) is represented on the horizontal axis. The relative frequency of each factor level is proportional to the width of the corresponding segment on the x-axis. In your case, most observations are 0, so no AC was available. In pseudo-code, you would obtain the corresponding values by prop.table(table(AC))
The joint frequency distribution (the relative frequencies of each combination of the two factors) is represented by the areas of the corresponding rectangles. In your case, there are many dissatisfied persons without AC. You would get these relative frequencies by table(AC, satisfaction).
Within each level of the first variable, the frequency distribution of the second variable (satisfaction) is shown vertically. If these conditional distributions look similar, there is no or only a weak association between the two factors. If they look very different like in your case, you would speak of a clear association. In the no-AC group (the left vertical bar), a clear minority (about 10%) is satisfied. In the AC group (the right vertical bar), more than half of the persons were satisfied. In pseudo.code, you would get the corresponding proportions by prop.table(table(AC, satisfaction), margin = 1).

Typically, the third information is usually the reason to look at a mosaic plot. The order of the variables is essential.
Comment: Thank you for answering and explaining it in such a good manner!

How to interpret a mosaic plot in R?


How to get a index for a key I know to be unique in an array

Question: I have a list of items in a particular order so I've decided to store them in an array
$items = array(
   "apple",
   "banana",
   "pear"
);

If the program is called with the parameter "banana" I need to be able to say "apple" comes before and "pear" comes after. Currently I'm doing something like this:
foreach($items as $k=>$v) { if ($v == "banana") { $current_key = $k }

So now I know that $current_key -1 is previous and +1 is next. It works, it just FEELS ugly to iterate over the entire array. Is there a better way to do this?
UPDATE
In case anyone cares, I decided to do a few quick tests to see how fast the ways of getting the information were. Over 1000 iterations, on an array of 6000 items, microtime retunred:
My Posted Way:  4.567
Array_Search:  2.749
While I was thinking I also tried an approach that stored the data in a array of arrays like:
$items['banana']['next'] = 'pear';
$items['banana']['prev'] = 'apple';

which was, of course, the winner by miles ( 0.0005 ). None of this is really relevant, I was just curious and thought to share with anyone who reads this.
Comment: Sorry, but I do feel the need to nitpick your terminology: "apple", "banana" and "pear" are not keys in your example, they are values. They would be keys in the following example: array("apple" => "round", "banana" => "long", "pear" => "oblong").
What you call $current_key would be better described as a cursor or an index.
Comment: Yes, and im using the VALUE to find the KEY in the example ... you'll notice the value of $current_key is set to the array index, not the value. The title, however, is wrong, as I'm getting an index for a value i know to be unique :)
Answer: array_search() should save you the loop.
Comment: In addition, `array_keys()` may be of use if you need more than just the first one: http://php.net/manual/en/function.array-keys.php
Comment: The question says it's definitely unique, but neat. I never knew that array_keys took a second parameter.
Comment: Works like I charm. I even did some quick microtime() tests and it runs about twice as fast on a small array. No idea how it would fare on a large one. :)
Answer: You are looking for the array_search function: http://www.php.net/manual/en/function.array-search.php.
$key = array_search('banana', $items);

Answer: http://www.php.net/manual/en/function.array-search.php
$current_key=array_search('banana',$items);


How can the cycles be chosen so that they all have length 2 in case of permutation group?

Question: I am reading linear algebra book by Harvey E. Rose . There in permutation groups , he says ,

every permutation can be expressed as product of cycles

I understood this line.
. Then he said ,

A cycle of length n can be written in a number of ways as a product of
  2-cycles, one of which is given by
$ (1,2,3, ... ,n) = (1,2)(1,3)...(1,n) $
the reader should check this, noting we always read from left to right.

I can't understand the meaning of last two lines.
Comment: I can't understand what you find hard to understand about the quoted lines, which seem crystal clear to me. Do you understand the meaning of the identity $$(1,2,3,\dots n)=(1,2)(1,3)\dots(1,n)?$$ Are you able to verify that identity? Or is that your problem, that you don't see why it's true?
Answer: If $X = \{1,...,n\}$, the permutations being discussed are bijective functions from $X$ to $X$, and the multiplication is just composition of functions, in left-to-right evaluation order (i.e., the left-most function gets the actual the input). This is the opposite of the usual right-to-left evaluation order for composition notation, but some authors prefer this.

Thus, the permutation with cycle notation
$$(1,2,3,...,n)$$
is the function $f$ which maps
$$1 \to 2,\;\;2 \to 3,\;...\;,(n-1) \to n,\;\;n \to 1$$
and for $1 \le i < j \le n$, the transposition with cycle notation $(i,j)$ is the function $t_{i,j}$ which maps $i \to j,\;j \to i$, and leaves all other values fixed (unchanged).

Thus, the claim
$$(1,2,3, ... ,n) = (1,2)(1,3)...(1,n)$$
is equivalent to the claim (using standard right-to-left evaluation order)
$$f  = t_{1,n}\,\circ\,t_{1,{n-1}}\,\circ\cdots\circ\,t_{1,2}$$
To verify the claim, apply both sides to an arbitrary input $k$, and compare . . .

Thus, for example, we have $f(1)=2$, and also
\begin{align*}
&(t_{1,n}\,\circ\,t_{1,{n-1}}\,\circ\cdots\circ\,t_{1,2})(1)\\[4pt]
=\;&(t_{1,n}\,\circ\,t_{1,{n-1}}\,\circ\cdots\circ\,t_{1,3})(2)\\[4pt]
=\;&2\\[4pt]
\end{align*}
since the transposition $t_{1,2}$ maps $1 \to 2$, but the transpositions $t_{1,n},\;t_{1,{n-1}},...,t_{1,3}$ leave $2$ unchanged.

More generally, for $1 \le k < n$, we have $f(k)=k+1$, and also
\begin{align*}
&(t_{1,n}\,\circ\,t_{1,{n-1}}\,\circ\cdots\circ\,t_{1,2})(k)\\[4pt]
=\;&(t_{1,n}\,\circ\,t_{1,{n-1}}\,\circ\cdots\circ\,t_{1,k})(k)
&&\text{[since$\;t_{1,j}\;$fixes$\;k$, if$\;j < k$]}\\[4pt]
=\;&(t_{1,n}\,\circ\,t_{1,{n-1}}\,\circ\cdots\circ\,t_{1,k+1})(1)
&&\text{[since$\;t_{1,k}\;$maps$\;k \to 1$]}\\[4pt]
=\;&k+1
&&\text{[since$\;t_{1,k+1}\;$maps$\;1 \to k+1$}\\[-1pt]
&&&\;\text{and$\;t_{1,j}\;$fixes$\;k+1$, if$\;j>k+1$]}\\[4pt]
\end{align*}
Finally, we have $f(n)=1$, and also
\begin{align*}
&(t_{1,n}\,\circ\,t_{1,{n-1}}\,\circ\cdots\circ\,t_{1,2})(n)\\[4pt]
=\;&t_{1,n}(n)
&&\text{[since$\;t_{1,j}\;$fixes$\;n$, if$\;j < n$]}\\[4pt]
=\;&1\\[4pt]
\end{align*}
Thus, the claimed equality$\;(1,2,3, ... ,n) = (1,2)(1,3)...(1,n)\;$is verified.


Lmer model fails to converge

Question: My data is described here What can cause a "Error() model is singular error" in aov when fitting a repeated measures ANOVA?
I am trying to see the effect of an interaction using lmer so my base case is:
my_null.model <- lmer(value ~ Condition+Scenario+
                             (1|Player)+(1|Trial), data = my, REML=FALSE)

my.model <- lmer(value ~ Condition*Scenario+
                             (1|Player)+(1|Trial), data = my, REML=FALSE)

Running the anova gives me significant results, but when I try to account for random slope ((1+Scenario|Player)) the model fails with this error:
  Warning messages:
 1: In commonArgs(par, fn, control, environment()) :
   maxfun < 10 * length(par)^2 is not recommended.
 2: In optwrap(optimizer, devfun, getStart(start, rho$lower, rho$pp),  :
  convergence code 1 from bobyqa: bobyqa -- maximum number of function evaluations exceeded
 3: In commonArgs(par, fn, control, environment()) :
  maxfun < 10 * length(par)^2 is not recommended.
 4: In optwrap(optimizer, devfun, opt$par, lower = rho$lower, control = control,  :
   convergence code 1 from bobyqa: bobyqa -- maximum number of function evaluations exceeded
 5: In checkConv(attr(opt, "derivs"), opt$par, ctrl = control$checkConv,  :
   Model failed to converge with max|grad| = 36.9306 (tol = 0.002)
 6: In checkConv(attr(opt, "derivs"), opt$par, ctrl = control$checkConv,  :
   Model failed to converge: degenerate  Hessian with 1 negative eigenvalues

Alternatively if it fails to converge after a lot of iterations (I set it to 100 000) and I am getting the same results after 50k and 100k it means that it is very close to the actual value, just it does not reach it. So can I report my results like this?
Note that when I set the iterations so high I get only these warnings:
 Warning messages:
1: In checkConv(attr(opt, "derivs"), opt$par, ctrl = control$checkConv,  :
 Model failed to converge with max|grad| = 43.4951 (tol = 0.002)
2: In checkConv(attr(opt, "derivs"), opt$par, ctrl = control$checkConv,  :
 Model failed to converge: degenerate  Hessian with 1 negative eigenvalues

Answer: See this conversation for an alternative method of assessing convergence. Specifically, this comment from Ben Bolker:

thanks. An even simpler test would be to take a fitted example that gave you convergence warnings and take a look at the results of
relgrad <- with(fitted_model@optinfo$derivs,solve(Hessian,gradient))
max(abs(relgrad))
  and see if it's reasonably small (e.g. <0.001?)

Alternatively, you could try Bolker's advice here, which is to try a different optimizer.
Comment: what should one do if max(abs(relgrad)) gives you a value of 2.9239489e-05 ?
Comment: @Jens then that would be really, really small (e-05 means "write 5 zeros and then the numbers you see on the left", with a dot after the first zero). So one would be pretty happy with that value!

Lmer model fails to converge


Using Python, I want to print only positive integers on the list through recursion

Question: I'm studying recursion now, and my head is about to explode trying to use it.
If lst = [-1, -4, 0, 3, 6], my expecting output is result = [3, 6].
I tried this,
def positive(lst):
    result = []
    if not lst:
        return result
    else:
        if lst[0] > 0:
            result.append(lst[0])
        return positive(lst[1:])

But output is empty list. like result = [ ].
Answer: You are not passing your cache down through recursion
def positive(lst, result):
    if not lst:
        return result
    else:
        if lst[0] > 0:
            result.append(lst[0])
        return positive(lst[1:], result)

lst_in = [-1, -4, 0, 3, 6]
result = []
res = positive(lst_in, result)
print(res)

In your version, result's scope was limited to a single function execution. You need to have a common cache(in your case result list). You can do that by passing it down to each function, or defining it in global scope
Answer: In your recursive part, positve() always return a further call to itself. Therefore, you always get the result of the final call to positive(), i.e., an empty list.
A solution that does not change your interface is as below, but at the cost of moving list every time.
def positive(lst):
    result = []
    if lst:
        if lst[0] > 0:
            result.append(lst[0])
        result.extend(positive(lst[1:]))
    return result

lst = [-1, -4, 0, 3, 6]
print(positive(lst))
# [3, 6]

Edit: Because we add at most one value each time, we can use insert instead of extend to update result with lower cost.
def positive2(lst):
    if not lst:
        return []
    result = positive2(lst[1:])
    if lst[0] > 0:
            result.insert(0, lst[0])
    return result


SQL/PHP - Count results and show them according to HAVING clause

Question: I have this query:
$stmt = $dbh->prepare("SELECT DISTINCT country_code,country_name FROM users WHERE country_code!='NA' AND country_name!='NA'");
$stmt->execute();
$rows = $stmt->fetchAll();

Which distinctly select some information from my database.
I then later loop the data in a foreach loop:
foreach ($rows as $row){
 //Do something
}

Although, I wish to be able to only use the result/data, if the there is more than 5 results in the original query.
Example:
If country_code and country_name with values CA and canada is present more than 5 times.
Comment: Curious are you asking if you want the data if specific values are found more then five times or if you want the data if the overall returned amount is more then 5?
Comment: The specific values.
Comment: you have mention group by and having. could you do something like this `select country_code, country_name from user group by country_code having count(country_code) >=5` http://sqlfiddle.com/#!9/ceedf/1/0
Answer: You can use group by and having to get the specific result. You could use count() function to count the number of row group by the specific column. You also could add expression as well if you only want country_code='CA' as the example below.
select country_code, country_name from user
group by country_code
having country_code='CA' and count(country_code) >=5

here is the example http://sqlfiddle.com/#!9/b62530/1
Comment: What about the distinct?
Comment: group by giving you distinct in a way. With distinct you need to count the row after the query. With group by, it group the same country_code to return only 1 row of that country code. So, it's a distinct country_code in a way. Unless there are other columns that you need apart from country_code. Then, the query will be different.


Retornando NULL

Question: Estou utilizando esta query:
SELECT GROUP_CONCAT(coluna1) as valores FROM arquivos WHERE coluna2 IN (21, 22)

Ela retorna os valores da coluna1 das linhas cuja coluna2 possui um dos valores especificados.
O problema é que, neste caso, o valor 21 não é encontrado na tabela. Então preciso returnar um NULL. Mas a query está retornando somente o valor encontrado.
Comment: A query só vai retornar os valores encontrados , para retornar um null é preciso recorrer a artifícios como union etc
Answer: Não sei se é bem isso que você precisa, mas faça um teste:
select group_concat(ifnull(coluna1, 'x')) as valores
  from (select 21 coluna2
        union
        select 22
       ) tab_aux
  left join arquivos
    on arquivos.coluna2 = tab_aux.coluna2

Obs.: O 'x' representa o seu 'null'.
Comment: É exatamente isso que eu preciso. Mas tem um porém: os ids que uso vêm de um array dinâmico.
Comment: Deixa eu ver se entendi: o 21 e 22 não são valores fixos, são gerados dinamicamente, isso? E são sempre 2 valores apenas?
Comment: isso mesmo: não são gerados dinamicamente. E o número de valores pode variar.
Comment: Cara, então não tem jeito, você terá que montar essa query também de forma dinâmica, por linha de código. Se quiser mostrar seu programa como está hoje quem sabe eu ou outra pessoa possa te ajudar melhor.
Comment: Cara, então vou tentar reorganizar as tabelas. Mas muito obrigado pela ajuda.

Retornando NULL


How to find the Inverse CDF of a Skewed Normal Distribution

Question: The Wikipedia article on the distribution also doesn't seem to specify any formulae on right hand side. Also wolframalpha says there is no closed form solution.
Comment: I haven't worked it out, but perhaps there is something useful at http://www.apesimulator.org/help/models/rain/Skewed_normal_distribution.html , since it appears that the author is trying to use the inverse distribution method to generate random variates? Or alternatively, use a numerical nonlinear equation solver to numerically determine the inverse for a given argument.
Comment: I used wolfram alpha (also updated in the question), it couldn't find any closed form solution.
Answer: The inverse of the CDF is the quantile function. There is no closed form solution but it is already implemented in the R package sn. The way the package calculates the quantile of interest is by solving the non-linear equation $F(q) = p$ numerically.
https://cran.r-project.org/web/packages/sn/index.html

Description
Density function, distribution function, quantiles and random number
  generation for the skew-normal (SN) and the extended skew-normal (ESN)
  distribution.
Usage
dsn(x, xi=0, omega=1, alpha=0, tau=0, dp=NULL, log=FALSE) psn(x, xi=0,
  omega=1, alpha=0, tau=0, dp=NULL, engine, ...) qsn(p, xi=0, omega=1,
  alpha=0, tau=0, dp=NULL, tol=1e-8, solver="NR", ...)  rsn(n=1, xi=0,
  omega=1, alpha=0, tau=0,  dp=NULL)


Ajax slideshow for D7?

Question: I am looking for some kind of Ajax-based slideshow/banner module for D7 for a changeable front-page photo banner. Unfortunately neither Views Slideshow Ajax nor Ajax Slideshow have been ported to D7 yet. I have several megabytes of photo content and would like to load each image on demand, not load them all at once (which is, as I understand, how most of the slideshow modules work). Right now I am just using a view that returns a randomly-chosen image, but I'd rather have it cyclable by the user with arrows or by a timer.
Are there any existing D7 modules that do something like this? There are so many slideshow, banner, and gallery modules: I may have missed the one I need.
Comment: Sounds like you need to create a custom module to achieve this. I created a module with similar principle in this site - http://m.cnngo.com (More button)
Answer: The Views Slideshow module relies on the Cycle library, if I'm correct. It supports AJAX / progressive loading in it's current version as seen here:

http://malsup.com/jquery/cycle2/demo/progressive.php

In my experience, a lot of Drupal modules make the integration of library options unneccessarily complex:
So you could just generate the necessary code via views instead and load the lib yourself via template. Most current slideshow scripts support AJAX loading, so you can choose one that suits you.

Ajax slideshow for D7?


Submitting a Form with AJAX in a block

Question: So, I have a form that I wish to appear in a block. Now, I don't want the submission of this form to trigger an entire page reload, so I was hoping to use the built in AJAX framework.
I've tried several different things, but my current code is below. The data gets saved, but I can't figure out how to reset the form; anything I've tried has just left the data in the fields. Any help would be appreciated. Thanks.
/**
 * Implements hook_block_view()
 */
function test_contact_block_block_view($delta)  {
  switch ($delta) {
    case 'contact_block':
      $block['subject'] = t('Contact');
      $block['content'] = drupal_get_form('test_contact_block_form');
      break;
  }
  return $block;
}

function test_contact_block_form($form, &$form_state)   {
for_testing();

$form = array();
$form['form'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
);
$form['form']['access_id'] = array(
    '#type' => 'textfield',
    '#title' => t('Customer Access ID'),
    '#size' => 10,
    '#required' => true,
);
$form['form']['summary'] = array(
    '#type' => 'textfield',
    '#title' => t('Summary'),
    '#size' => 20,
    '#required' => true,
);
$platforms = explode(chr(13), variable_get('test_waiver_platforms', ''));
$form['form']['platform'] = array(
    '#type' => 'select',
    '#title' => t('Platform'),
    '#options' => array_combine($platforms, $platforms),
);
$contact_channels = explode(chr(13), variable_get('test_waiver_contact_channels', ''));
$form['form']['contact_channel'] = array(
    '#type' => 'select',
    '#title' => t('Contact Channel'),
    '#options' => array_combine($contact_channels, $contact_channels),
);
$form['form']['minutes'] = array(
    '#type' => 'textfield',
    '#title' => t('Minutes'),
    '#size' => 10,
    '#required' => true,
);
$form['form']['category'] = array(
    '#type' => 'select',
    '#multiple' => true,
    '#title' => t('Category'),
    '#description' => t('ctrl+click (Win)/cmd+click (Mac) to select more than one.'),
    '#options' => _get_services(),
    '#size' => 15,
    '#required' => true,
);
$form['form']['submit'] = array(
    '#type' => 'button',
    '#value' => t('Submit Contact'),
    '#attributes' => array('onclick' => 'return false;'),
    '#ajax' => array(
        'wrapper' => 'form-wrapper',
        'callback' => 'test_contact_block_form_callback',
    )
);
$form['form']['message'] = array(
    '#type' => 'item',
    '#markup' => t('Only for NON waivers.'),
);

return $form;
}

function test_contact_block_form_callback($form, &$form_state)  {
if(!ctype_digit($form_state['values']['minutes']))  {
    form_set_error('minutes', 'You must enter an integer for minutes');
}
else {// THE INCLUDE IS JUST FOR THE FUNCTION BELOW THAT'S COMMENTED OUT
    //module_load_include('inc', 'test_waiver', 'test_waiver.admin');
    // Gather all the variables
    global $user;
    $user_accessid          = $form_state['values']['access_id'];
    $summary                        = $form_state['values']['summary'];
    $platform                   = $form_state['values']['platform'];
    $contact_channel      = $form_state['values']['contact_channel'];
    $time_spent                 = $form_state['values']['minutes'] * 60;
    $categories                 =   $form_state['values']['category'];
    $comments                   = '';
    $last_con_accessid  = '';
    $close = true;
    // Submit to Jira
    // THIS IS EFFECTIVELY WHERE THE DATA IS SAVED/STORED IN THE DB; this already seems to work okay, so I commented it out
    //test_waiver_submit_jira_ticket($user_accessid, $summary, $platform, $contact_channel, $time_spent, $categories, $comments, $last_con_accessid, $close);
    // Reset values
    $form_state['input']['access_id'] = '';
    $form_state['input']['summary'] = '';
    $form_state['input']['platform'] = null;
    $form_state['input']['contact_channel'] = null;
    $form_state['input']['minutes'] = '';
    $form_state['input']['category'] = null;
}
$form_state['rebuild'] = TRUE;
return $form['form'];
}

// FUNCTIONS BELOW WERE ADDED FOR TESTING

function for_testing()  {
variable_set('test_waiver_platforms', 'Windows' . chr(13) . 'Mac');
variable_set('test_waiver_contact_channels', 'Walk-In' . chr(13) . 'Phone');
}

function _get_services()    {
return array('service 1' => 'service 1', 'service 2' => 'service 2');
}

(I've done my best to remove superfluous/too specific/dependent code, in the event that anyone wants to attempt to run it themselves.)
I can NOT get this to work. I have questions like:

Should I use '#type' 'button' or 'submit'? The docs aren't very clear on what the real difference between the two are, and I get slightly different behavior with each.
Should I use an onClick attribute to return false with the button?
Do I need and additional '#submit' callback to make the change? Or can/should it be done within the ajax callback? (I can't seem to change the $form_state, even when receiving it as a reference.)
Answer: You can use webform rather than custom code. Its very easy to use. No coding skill required.
Steps to do

Install webform and webform ajax module
Create a webform, add required fields.
In form setting, Go to Advance setting and enable "available as block".
Just below that, enable "ajax mode".

You can configure email also in email setting.
Answer: Try the below code snipped. It will try to rebuild the form
  $form_state = array('storage' => NULL, 'submitted' => FALSE);
  $form_build_id = $_POST['form_build_id'];
  $form = form_get_cache($form_build_id, $form_state);
  $args = $form['#parameters'];
  $form_id = array_shift($args);
  $form_state['post'] = $form['#post'] = $_POST;
  // Enable the submit/validate handlers to determine whether AHAH-submittted.
  $form_state['ahah_submission'] = TRUE;
  $form['#programmed'] = $form['#redirect'] = FALSE;
  drupal_process_form($form_id, $form, $form_state);
  $form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id);

Add this code on top of the test_contact_block_form_callback function.

Submitting a Form with AJAX in a block


Obtaining the expected value $E[X_{(1)} \mid\overline X = c]$

Question: Suppose we have $X_1,\dots, X_n \overset{\text{iid}}{\sim} N(\mu = 0, \sigma^2 = 1)$, for a known $n$. And we want to calculate $E[X_{(1)} \mid \overline X = c]$, where $c \in \mathbb{R}$ is known, $X_{(1)}$ is the first order statistic of the $X_i$'s and $\overline X$ is the sample mean of the data.
What I can see is that $X_{(1)}$ is an estimator of the data, because is an order statistic. Also, $X_{(1)}$ is a sufficient statistic of the data, for the same reason. Then, this expected value is really similar to the Rao-Blackwell Theorem to me, but how can I get/calculate this conditional expected value? Shouldn't one of the parameters ($\mu$, $\sigma^2$) need to be unknown to apply Rao-Blackwell?
Also, since $X_{(1)} = \min(X_1, \dots, X_n)$, the expected value would be $E[\min(X_1, \dots, X_n) \mid \overline X] = E[X_1 \leq x, \dots, X_n \leq x\mid \overline X]$?
Comment: The difference is that $X$$_($$_1$$_)$ is not a parameter of the population distribution it's a function of the sample and it's not a sufficient statistic for an unknown parameter of the population distribution.
Comment: Sufficiency has to do with a parameter or parameters. You have a known distribution so there is no parameter to estimate. I don't know what you mean by a sufficient statistic for the data. Since the sample mean equals c under the conditioning you already know that the minimum of the sequence is <= to c. I think you mean to condition on X bar = c We know that the minimum is <=x if & only if all the $X_i$ are <= x.. But you are using it in the expectation incorrectly..
Comment: I think that is where my misconception is, I'm seeing E[X_(1)} | X bar] as defined in the Rao-Blackwell Theorem (θ∗ =E (ˆθ | T), where ˆθ is an estimator and T is a sufficient statistic.)
Comment: Then, for example in this case, I could get $P(X_{(1)} \leq x)$, which if I didn't made a mistake should be $1 - (\frac{1}{\sqrt{2 \pi \sigma^2}}) e^{-\frac{1}{2 \sigma^2} \sum_{i=1}^{n} (x_i - \mu)^2}$. And then, I can get the $E[X_{(1)} | \bar{X}]$ from the definition of expectation?
Comment: In the formula you need to replace $\mu$ with 0 & $\sigma^2$ with 1. Also the normal density needs to be integrate from -$\infinity$ to $x$.
Comment: I tried to edit the previous comment to say "integrate from - infinity to $x$."  So the probability that the minimum of the $X_i$s is less than or equal to $x$ is F($x$)$^n$ where F($x$) is the cumulative standard normal distribution at $x$. This is not the formula you gave.
Comment: It is not clear to me how you go from that to get the conditional expectation you are trying to compute.
Comment: My idea was that once I have $P(X_{(1)}|\bar{X})$, I could use $\int X_{(1)} P(X_{(1)} | \bar{X}) dx$.
Comment: That is the right idea. But remember that you are conditioning on the sample mean being equal to c. So you have to figure out the appropriate region of integration. Remember that the minimum of the $X_i$ has to be <c when the sample mean=c.
Answer: Suppose $X_1,X_2,\ldots,X_n$ are i.i.d $N(\theta,1)$ where $\theta\in \mathbb R$.
Then $\overline X$ is a complete sufficient statistic for $\theta$.
Note that $X_{(1)}-\overline X=(X_{(1)}-\theta)-(\overline X-\theta)$, so that its distribution is free of $\theta$.
By Basu's theorem, the ancillary statistic $X_{(1)}-\overline X$ is independent of $\overline X$.
Therefore,
$$E\left[X_{(1)}-\overline X\right]=E\left[X_{(1)}-\overline X\mid \overline X\right]=E\left[X_{(1)}\mid \overline X\right]-\overline X$$
So for every $\theta$, we must have
$$E\left[X_{(1)}\mid \overline X\right]=E\left[X_{(1)}-\overline X\right]+ \overline X=E\left[X_{(1)}\right]-\theta+\overline X$$
In particular, the above holds for $\theta=0$.
Comment: Since $E[X_{(1)}]=c+\theta$ where $c$ is the expectation of the first order statistic from $N(0,1)$, the conditional expectation is always free of $\theta$.


How do you determine if a song should be played with a capo or which fret the capo should be if capo'd? When transcribing chord tabs for others

Question: I hope this makes sense because I'm always conflicted.
An example song is Taylor Swift - dorothea
I know that Taylor would use a capo but since this is a piano song with some arpeggios, I can't decide if it would be easier with chords for capo 2nd or capo 4th.. or which capo position she would actually use
@transcribers, how would you decide this?

An easy one to decide is if the song is in Ab, the obvious capo is 1st fret but it's tough to decide for piano songs
Comment: Reading the related questions and answers should provide adequate information. This is probably a dupe.
Answer: Given the key of Ab major, presumably chosen because it helps the singer sound her best, the capo at first fret allows you to play it like it was in G. Lots of easy chord shapes there.
If it had open-string licks, those might require you to play out of E shapes and capo at the fourth fret, or perhaps higher for C and D shapes. That would put the capo very high on the neck. It's done, but it isn't the most common.
A lot depends on what chords you need. Using G as your base would give you Em as an easy vi chord and Am as the ii, but you don't have a non-barre choice for your iii unless you use B7. Playing out of D would give you an easy iii with Em without any jazzy dominant sevenths getting in there.
Answer: Not sure how important it is that the song is in key E, but we'll use that as a basis.
Since it uses the three main major chords, and a couple of minors, we'll say that all six chords should be available. Let's check out the five positions.
Key E, open chords, E, A and B7 all straightforward. F♯m, C♯m and G♯m need barring.
Key E, capo 4th fret. Shapes are now C, F and G. Minors Am, Em, Dm. All 'open' shapes, barring (sic) F.
Key E, capo 2nd fret. Shapes now are D, G, A. Minors Bm, F♯m, C♯m. Majors 'open', all minors need barring.
Key E, capo 7th fret. Shapes are A, D and E. Minors F♯m, G♯m and C♯m. Majors simple, all minors need barring.
Key E, capo 9th fret. Getting unmanageable on some guitars! Shapes are G, C, D. Minors are Em, Am, Bm. All open except Bm.
Those are the options, they're based on CAGED system, simply speaking. Choice comes from voicings, playability, and reachability. Some players would stick to one position - with use of a capo, why not, others would go for the sound of the voicing, along with which strings work best for arpeggios, others would eschew the capo altogether, while yet others might opt for a capo on a low fret, but also use barre shapes higher.


Robust & Linear Control Systems

Question: The characteristic polynomial of a control system is the following uncertain polynomial:
$$s^3 + a_2 s^2 + a_1 s + 3.5 $$
Where $a_1 \in  [1.5,4.2],a_2 ∈ [1.2,4.25]$ and $ 4.2 ≤ a_1 + a_2 ≤ 6.3$
.
Is this uncertain polynomial stable?
How do I solve this problem, when I have got two values from $a_1$ and $a_2$.
Comment: Very interesting question.
Answer: The Hurwitz matrix of the polynomial is:
$$ \begin{bmatrix} a_2 & 3.5 & 0 \\ 1 & a_1 & 0 \\ 0 & a_2 & 3.5 \end{bmatrix}$$
To stability this matrix must be definite-positive, this is, all subdeterminants must be positive. The conditions are:
$$a_2 >0$$
$$a_2 a_1 >3.5 $$
If the second subdeterminant is positive, it follows that the third one also is (because $3.5 \gt 0$ ). You can check the polynomial will always be stable for the values you have.
Comment: Thank you for sharing your answer :). I would have solved it with more complicated methods.
Comment: Glad I could help
Answer: As @Villa proposed you can start with the Hurwitz criterion for a cubic polynomial.
$$a_1>0$$
$$a_2>0$$
$$a_1a_2>3.5.$$
The first two conditions are trivially fulfilled for the given intervals. Hence, we only need to care for $a_1a_2>3.5\implies a_2 > 3.5/a_1$. The given intervals for your coefficients will give you the feasible region for the inequalities (see below) without $a_1a_2>3.5$.

The only thing we need to do is to check if the corners of the lower diagonal edge given by $a_2=4.2-a_1$ are fulfilling the inequality $a_1a_2>3.5$.
Determining the corners:
$$a_1=1.5\implies a_2=4.2-1.5=2.7 \implies P_1=(1.50,2.70)$$
$$a_2=1.20 \implies a_1=3 \implies P_2=(3.00,1.20)$$
Now, check if $a_1a_2>3.5$ is true for both points:
$$P_1: a_1a_2=4.05>3.5$$
$$P_2: a_1a_2=3.6>3.5$$
We can conclude that the polynomials are asymptotically stable for the given conditions.
Comment: Thanks for the detailed explanation.
Answer: I would suggest checking the Kharitonov's theorem that gives a simple and practical answer for a similar question for polynomials of any degree.
Comment: Kharitonov's theorem is what I wanted to use in the first place. But the problem is the inequality $4.2 \leq a_1 + a_2 \leq 6.3$. How can you incorporate this into the theorem of Kharitonov? I think it is not possible as it is only using lower and upper bounds for your coefficients.

Robust & Linear Control Systems


Filter JSON string from String having json string and normal string in java

Question: I am stuck in a problem where I have to filter json data from a String which is a combination of json string and normal text.
sample: This message has all your required detail { "name" : "xyz","age": "21","place" :"sdf", "number": "7689"} check in this page you will get the details.
I need to extract the json object from given string.
Result expected is only : { "name" : "xyz","age": "21","place" :"sdf", "number": "7689"}.
Is there any clean way of doing this in Java.
One way to solve this is to remove non-json string and extract json object.
But that is a bad approach in my view.
Comment: Do you expect multiple json strings in a one java string?
Comment: No, There will be only one json string
Answer: If there are no other JSON-like parts, you can just extract the part between the first { and last }, including both ends:
int start=str.indexOf('{');
int end=str.lastIndexOf('}');
String json=str.substring(start,end+1);

Then of course you may want to check if both start and end are non-negative (so the characters are actually present), if there is a possibility that the string does not contain anything for you.
Also note that JSON can be an array too, so you can try checking if a pair of first [ and last ] lies outside of the {...}, but then at the end single values are valid JSON too (like true, false, 1, etc.). This is not really a happy task to write properly, thinking of everything.


Swift:Comparing Dictionary Keys

Question: i have a dictionary like this:
var dataDictionary : [String:String] = ["Result" : "result", "Date Added" : "dateAdded", "Entered By" : "enteredBy"]

to store this key and values i have made a array foe a key and values like this:
var selectedDictKeys :[String] = [String]()
var selectedDictValues :[String] = [String]()

and kept the keys and values into array like this:
self.selectedDictKeys = Array(self.dataDictionary.keys)
self.selectedDictValues = Array(self.dataDictionary.values)

This is my defaultName Model class:
class DefaultNameModel: EVObject {
    var key : String = ""
    var value : String = ""
}

Now how can i print set the value for values like..
self.selectedDictKeys = Array(self.dataDictionary.keys)
self.selectedDictValues = Array(self.dataDictionary.values)

var dataSet = [DefaultNameModel]()
for i in 0...(self.selectedDictKeys.count-1)
{
    let dataRow = DefaultNameModel()
    dataRow.key = String(self.selectedDictKeys)

    if dataRow.key == "Result"
    {
        dataRow.value == "Success"
        dataSet.append(dataRow)
        print("The data Row is\(dataRow)")
    }

    if dataRow.key == "Date Added"
    {
        dataRow.value == "2016-12-12"
        dataSet.append(dataRow)
        print("The data Row is\(dataRow)")
    }

    if dataRow.key == "Entered By"
    {
        dataRow.value == "Me"
        dataSet.append(dataRow)
        print("The data Row is\(dataRow)")
    }
}

Comment: If you know the key and value both then why are you creating dictionary simply create object of `DefaultNameModel` and object in array.
Comment: i have to append this in the table
Comment: so how can i do that..can you please suggest me..??
Comment: Your key is fixed value is fixed then what is the meaning of this, You are adding the same value for all object
Comment: Use loop like this.  for key in selectedDictKeys { .... } and assign the key to dataRow.
Comment: can you comment please @Rajesh73
Answer: for key in self.selectedDictKeys {
    let dataRow = DefaultNameModel()
    dataRow.key = key

    switch key {
    case "Result":
        dataRow.value == "Success"
    case "Date Added":
        dataRow.value == "2016-12-12"
    case "Entered By":
        dataRow.value == "Me"
    default:
        dataRow.value == ""
    }

    dataSet.append(dataRow)
    print("The data Row is\(dataRow)")
}

Answer:         var dataSet = [DefaultNameModel]()
        for i in self.selectedDictKeys
        {
            let dataRow = DefaultNameModel()
            dataRow.key = i

            if dataRow.key == "Result"
            {
                dataRow.value == "Success"
                dataSet.append(dataRow)
                print("The data Row is " + dataRow.Key + " " + dataRow.value)

            }

            if dataRow.key == "Date Added"
            {
                dataRow.value == "2016-12-12"
                dataSet.append(dataRow)
                print("The data Row is " + dataRow.Key + " " + dataRow.value)

            }
            if dataRow.key == "Entered By"
            {
                dataRow.value == "Me"
                dataSet.append(dataRow)
                print("The data Row is " + dataRow.Key + " " + dataRow.value)

            }
        }

Answer: I see that you are using EVReflection (EVObject is your base type). Then you could initiate your objects based on a dictionary. Why don't you put the values for the data in the dictionary? And even better, why don't you create an object with regular properties instead of a key and a value property. Here is some sample code that works:
func testxx() {
    // Why not setting the values in the dictionary?
    let dataDictionary: NSDictionary = ["Result" : "Success", "Date Added" : "2016-12-12", "Entered By" : "Me"]

    // Then you could just map it to the model using:
    let defaultNameModel: [DefaultNameModel] = dataDictionary.map { DefaultNameModel(dictionary: ["key": $0.key, "value": $0.value]) }
    print("defaultNameModelOld = \(defaultNameModel)")

    // But you could directly map it to a real model
    let defaultNameModelNew = DefaultNameModelNew(dictionary: dataDictionary)
    print("defaultNameModelNEw = \(defaultNameModelNew)")
}

class DefaultNameModel: EVObject {
    var key: String?
    var value: String?
}

class DefaultNameModelNew: EVObject {
    var Result: String?
    var Date_Added: String?
    var Entered_By: String?
}

Swift:Comparing Dictionary Keys


Kronecker product of $A$ and $B$ is similar to the Kronecker product of $B$ and $A$

Question: Given two matrices $A$ and $B$. How would one prove that the Kronecker product of $A$ and $B$ is similar to the Kronecker product of $B$ and $A$?
Answer: If $A$ and $B$ are square, then $A\otimes B = P^{-1}(B\otimes A)P$ where $P$ is a permutation matrix that you can write down explicitly; it depends only on the dimensions of $A$ and $B$.
If $A$ and $B$ are not square, then $A\otimes B$ and $B\otimes A$ are not necessarily similar even if they happen to be square. For example, if
$$ A=\begin{pmatrix}0\\1\end{pmatrix} \qquad
B = \begin{pmatrix}0&0&1&0\\0&0&0&1\end{pmatrix}$$
then $A\otimes B$ and $B\otimes A$ are not similar (they have different characteristic polynomials).
Answer: This is most easily seen in terms of coordinate-free linear algebra.
If $f : V \to W$ and $g : V' \to W'$ are linear maps and $S_{V,V'} : V \otimes V' \to V' \otimes V$ denotes the symmetry isomorphism, the diagram
$$\begin{array}{c} V \otimes V' & \xrightarrow{f \otimes g} & W \otimes W' \\ S_{V,V'} \downarrow ~ && ~ \downarrow S_{W,W'} \\ V' \otimes V & \xrightarrow{g \otimes f} & W' \otimes W \end{array}$$
commutes, since $v \otimes v'$ gets maped to $g(v') \otimes f(v) \in W' \otimes W$ by both compositions. If $W=V$ and $W'=V'$, it follows that $f \otimes g = S_{V,V'}^{-1} \circ (g \otimes f) \circ S_{V,V'}$, so that $f \otimes g,\,g \otimes f  \in \mathrm{End}(V \otimes V')$ are similar.


Practice before a gig - bored of material

Question: I'm doing a gig soon, together with a friend. We will play songs written by myself, at a small local venue.
The last couple of weeks, I've been practising a lot. I now know the songs flawlessly, technically speaking. But I have practised so much that I've grown somewhat weary of them.
Because of that, I'm now worried that I won't be able to convey the emotional content and message of the songs at the actual concert.
So, any thoughts on how to deal with this? Is there a way to practise songs to perfection (or close enough), without becoming bored with them? Or am I looking at this completely wrong..?
Answer: Playing live is very different to practicing. You will find you get an adrenaline rush, maybe nervousness, perhaps you will have astonishing vibrato (from your hands shaking - this happened to my at my first couple of gigs). You will feed off the audience's energy and responses.
So initially, I would say don't worry about knowing them too well - it will feel different once you are on that stage.
You could try thinking about choreography - I don't mean actual dancing, necessarily, but thinking about where/how each band member stands during each song. Should you jump about? Move between mic stands? Doing a bit of this could make your next couple of weeks practicing much more fun.
Do you have a song which picks you all up and gets things jumping? Play that as part of your warm up in practice sessions to help you feel more energetic. We have an established couple of songs we always start with in the practice studio - by the end of the second one we are all grinning and jumping about, no matter how we feel on entering the room.
Comment: First paragraph is the perfect answer. We had a rule "play it till you hate it" - but at performance time, you don't hate it!
Answer: I suspect that when you comne to do the gig, that latent boredom with the tunes will translate into confidence while playing them. I think this underlines the first part of Dr Mayhem's answer - that the adrenalin will carry you through, and it won't feel boring at the time because performing is different to practicing. You'll feed off the audience and there will; be nerves etc. Much more "woop wahay" involved in a gig than in a practice.
One thing you could do is leave the tunes alone, don't practice between now and maybe just before the gig to let it re-fresh itself in your mind a bit.
Answer: They're your songs, your babies. Babies grow and your songs could as well. If you regard a song as 'etched in stone' it never will be any different. For me at least, songs are the blank canvas. What else can happen in a particular song? Can the format be changed - a solo here, a bridge there, etc.? A key change makes a big difference sometimes. Can two songs be segued? What does this song sound like a lot slower? There is mileage in leaning stuff by rote, but, as you've discovered, it gets boring, just like practising pieces for an exam.A jazzer's approach may be 'I've got the bare bones of a well-known tune, what direction can I take it in for a change?'  There's always a tendency for a really well-rehearsed song to become bland to the performer, but never forget that the audience, bless it, is hearing it for the first time.So keep it as if that's how you are playing it - fresh. It's often a state of mind.
Comment: +1 for the 'etched in stone' comment. A piece should change each time its performed IMO, to reflect the performers mood
Comment: @CurlyPaul - absolutely. Otherwise music is going to atrophy.
Answer: Something a friend told me to do to help me just get pumped on stage is to plan some moves out for just your first song... jump here, guitar flip here (hehe), etc. This helps you get used to moving around for the show and builds a strange confidence in yourself to take care of the rest of the show yourself. It sounds silly, but it works.
For your case, since they're your songs I'm just going to assume you're singing and playing guitar, just maybe practice how they feel for you, or something along those lines, in front of a mirror so that when you get on stage you can just get into the feeling and get going.
This happens to every one, every band. Big name pop and rock acts will rehearse for hours every day months before a tour (for example, if you've seen Michael Jackson's This Is It). What you're feeling is totally normal. Take a little break from the songs before your gig and if you're bored of your songs, maybe take the time to use as inspiration to write something new!
Answer: When you are in front of the audience, 40% of your mental capacity go to the audience.  So you suddenly only have 60% left for your playing.  It's a big handicap.  You'll find that stuff that you have recently acquired and which works reasonably well is unusable on stage.  You just can't make it appear.
The other stuff you got beat into the 60%-of-your-mental-capacity range (too bad it's hard to check for that in advance, though recording can help with that) then gets 40% of audience interaction on top, making you give 140%.
Which feels great to you as well as the audience.
At any rate, try playing with your material.  Try playing it 20% faster.  More importantly, try playing it at half speed while still working to make it sound interesting, consistent, compelling.  Some of the figuring out of just what makes the stuff good even when played at "boring" speeds will rub off on the fast play eventually.  That's a slow and gradual process.  A few weeks are over rather fast...
Answer:
Practice starting:  Make sure you can always start tunes at the right tempo and sing the first part exactly right.  Do this the first thing when you start to practice, cold. Check your tempos with a metronome.  Then try playing slower than your starting tempo.  Then try changing your tempo.  When you play in front of an audience there's a definite tendency to speed up and try to sing too hard.  Don't do that. You may also overcompensate. So know how to gracefully change.  Also practice singing unaccompanied but on pitch, check your pitch against your instrument.
Heal the fractures:  Practice the hardest parts in your repetoire.  If you've got that down, try starting your songs at any point in the middle.  It's a good way to gracefully recover from errors and distractions.
Self-evaluate:  Record your entire set and then listen to it closely.  Believe me, this is a great motivator to practice.  Your recorder is your worst enemy and best critic.
Practice everywhere: When you're going somewhere or waiting for a bus, sing your songs and visualize your playing. Listen to that recording and sing along. Figure out harmony parts for the songs.  Try singing or playing them differently.  Play with them. Do this in little pieces, 1-10 minutes at a time, but do it a lot.

"Good luck and most importantly, have fun."
 -- "The Company" directed by Robert Altman


Angular material Style not loaded

Question: I have a fresh Angular-Cli project with angular/material
"dependencies": {
  "@angular/animations": "^4.4.6",
  "@angular/cdk": "^2.0.0-beta.12",
  "@angular/common": "^4.4.6",
  "@angular/compiler": "^4.4.6",
  "@angular/core": "^4.4.6",
  "@angular/forms": "^4.4.6",
  "@angular/http": "^4.4.6",
  "@angular/material": "^2.0.0-beta.12",
  "@angular/platform-browser": "^4.4.6",
  "@angular/platform-browser-dynamic": "^4.4.6",
  "@angular/router": "^4.4.6",

I have inclueded the needed Modules in the app.module.
Added node-sass for scss files.
Also added the theming in a theme.scss
@import '~@angular/material/theming';

@include mat-core();
$primary: mat-palette($mat-orange, 800);
$accent: mat-palette($mat-light-blue, 600, A100, A400);
$warn: mat-palette($mat-red, 600);
$theme: mat-light-theme($primary, $accent, $warn);

@include angular-material-theme($theme);

imported that file into app.module.ts
import './../theme.scss';

and added to angular-cli.json
"styles": [
    "styles.scss",
    "theme.scss"
],

It compiles and has no errors in the console.
But no style is loaded. I have also tried prebuild themes.
Also tried to load prebuild themes directly from the index.html.
What could be missing?
Answer: I forgot to replace some <md- elements with <mat-
sadly no error (missing component) is in the console even if the element no longer exists. or at least there are no styles available.
Comment: You can set this as the answer then, if your question is answered.

Angular material Style not loaded


Inverse Laplace Transform, I need help

Question: What is the ILT of $H(s)=\frac{7(3s+1)}{(s-3)(s^2+10s-13)}$
Also, if you kindly want to help with this another inverse transform, I'd really appreciate it: $H(s)=\frac{6(s+2)}{s^3(s-5)}$
Thanks!
Comment: Try partial fractions...
Answer: Here is a hint:
For the first:
$H(s) =  \frac{35}{13  ( s-3\ ) }-\frac{35 s+182}{13 ( {s}^{2}+10 s-13 ) }$, and you can write $\frac{35 s+182}{13 ( {s}^{2}+10 s-13 ) } = \frac{35 ( s+5 ) +7}{13 { ( s+5 ) }^{2}-494} $.
If you let $\hat{h}_3(s) = {35 \over 13} {s \over x^2-38}$, and
$\hat{h}_4(s) = {7 \over 13} {1 \over x^2-38}$, then the corresponding time functions are
$h_3(t) = {35 \over 13} \cosh(\sqrt{38}t)$, $h_4(t) = {35 \over 13} {1 \over \sqrt{38}} \sinh(\sqrt{38}t)$ (I am assuming $t>0$ here).
Note that the last term in $H(s)$ can be written as $-(\hat{h}_3(s+5)+\hat{h}_4(s+5))$, hence the corresponding time function is $-e^{-5t} (h_3(t)+h_4(t))$.
For the second: $H(s) = \frac{42}{125 ( s-5 ) } -\frac{42}{125 s}-\frac{42}{25 {s}^{2}}-\frac{12}{5 {s}^{3}} $.
Comment: That's for the first or the second one? Thank you very much1
Comment: Yes. I have edited the answer slightly.
Comment: I really really appreciate it! I'd try to investigate the next steps, the thing is that I just know how to do simple inverse transforms, but these ones are really difficult to me. Thanks!
Comment: Use tables. Look at multiplication by an exponential and power of $t$ in the time domain and the Laplace transform of $\sinh$. There is some pattern recognition involved.
Comment: Do you mean that just by those hints you gave me, I can use the tables to get h(t)? I have seen some close examples and they seem to be longer. Sorry for my ignorance, I just have 2 days studying laplace transforms and this homework is for today.
Comment: Yes. ${}{}{}{}{}$
Comment: I can see some of those related on the table, but I still have doubts :/ I'm not sure how to proceed.
Comment: Read my comments. For example, with ${\cal L} (t \mapsto e^{5t}) (s) = {1 \over s-5}$, so you can figure out the first terms of the above. Look at $\sinh$, powers of $t$ and multiplication by exponentials.
Comment: but what do I do with the fractions 42/125, 42/25 and 12/5? Do I put them on the left of the h(t) based of the table?
Comment: The Laplace transform is linear. If $c$ is a constant, then ${\cal L} (cf) = c {\cal L} (f)$.
Comment: Then it will be something like: 42/125e^(5t) - 42/125 - 42/25 t^(2) - 12/5t^(3)  Is this correct?
Comment: Close. The last two powers of $t$ should be $t,t^2$. The constant on the last term should be ${6 \over 5}$.
Comment: Thank you! just please throw me a last hint with the first one... I still don't know how to relate it with the table and choose the correct h(t).
Comment: Multiplying a function in the time domain by $e^{-5t}$ will result in the Laplace transform variable $s$ of the original function being replaced by $s+5$. So this reduces the last term to ${35 s+ 7 \over 13s^2-494}$. Split this into two terms and use the tables for $\sinh$ and $\cosh$.
Comment: The closest is e^(at)cos(wt)    w^(2) is 494? Edit: ok, let me try it.
Comment: Not $\cos$, you need hyperbolic functions since the constant in the denominator is negative.
Comment: 35s/13s^(2)-494 and 7/13s^(2)-494 = e^(-5t)(35cos(?t) + 7sen(?t)) I don't know what "w" is…  its sqr494, is it?
Comment: This is getting a little tedious and I need to sleep. Look for SINH/COSH not the trigonometric functions (this is my 4th time repeating this). The rest you need to work out.
Comment: I added some elaboration above, hope it helps.

Inverse Laplace Transform, I need help