text:
Q: What can I do to stop the Play / Pause button from opening iTunes? In Snow Leopard the Play / Pause media button (on the F8 key) opens up iTunes. How can I disable that? Preferably keeping the old Leopard behaviour, so I can use it to control other media applications (e.g. Spotify).

A: Renaming iTunes only works until OS X finds it again. I deleted it from Applications and a couple of minutes later it was found on my backup disk and the problem returned. Deleted it from there to, no more problems. Don't forget to emty the Trash, or it will probably be found there...
So, deleting all copies works fine for me. My music is flac so I have no use for it anyway.

A: I have a 'workaround':

*

*Quit iTunes

*Locate iTunes.app in Finder (In Finder: Menu › Go › Applications...)

*Ctrl-click on the iTunes.app-file and select 'Compress "iTunes.app"' (for backup)

*Ctrl-click on the iTunes.app-file and select 'Show Package Contents'

*Locate the file 'Info.plist' inside the folder 'Contents'

*Ctrl-click 'Info-plist' and select 'Open with..' and select 'TextEdit' (or your favourite text-editor. Not Word tho.)

*Near the bottom of the file locate the following segment:
<key>CFBundleIdentifier</key>
<string>com.apple.iTunes</string>

*Change the last 's' in the word 'iTunes' to 'z', like so:
<key>CFBundleIdentifier</key>
<string>com.apple.iTunez</string>

*Save the file

*IMPORTANT: Drag the file 'iTunes.app' out of the Applications-folder and on to the Desktop

*Drag the file 'iTunes.app' back into the Applications folder

*(You should probably disable the iTunesHelper. This can be done by going to System Preferences › Accounts › (Your account) › Login Items and remove the 'iTunesHelper'.)

*Log out and log in

I hope this works. It works for me!

A: For controlling Spotify, use Shift + Option + Play button. iTunes does not react to this combination, but Spotify does.

A: For Snow leopard users:
Ok i didnt find an answer for this problem, but i tried to work my way around(for people who wants to watch videos on VLC and pause it with the apple remote/keyboard and itunes keep opening)
option 1:
open itunes and let it run but click on itunes store and hide itunes or minimize it. continue with watching videos on VLC and music won't play.
option 2:
Use Front Row to watch all your videos. To do so install PERIAN for quicktime(which allows you to play all formats in quicktime) and put all your movies in your "movies" folder. Enjoy watching movies through front row.
option 3:(this one worked partially. )
Rename itunes in applications folder to "itunes_off". In order to do this you might need to make your user privileges to" read and write". right click on itunes and click on "get info" then go in privileges and click on little lock icon, enter your password and then change your user setting to "read and write". After this rename itunes to something else. But this solution didnt work correctly for me. it stopped opening itunes for a while but when i restarted my mac it started opening it again.
Try if this works for anybody.
And keep me posted.

A: a better temporary fix is to start quicktime and just have it running(not playing a movie) in the background. It uses less ram/cpu than iTunes.

A: I only used iTunes and Spotify.
I've found the following low-tech solution works:
1. Open iTunes and select one of the folders under "library" that has no content - I never have any "ringtones" for instance; You can also create an empty playlist and select this.
2. Leave iTunes open, but select "Hide iTunes" in the "Itunes" menu.
The results is although iTunes is open it doesn't have any content to play and so when I hit the 'play' button all I hear is music from Spotify.

A: Not sure how many other applications this will work with, but it certainly works with Spotify: if it's already open, pressing option while using the media keys will not open iTunes, and will control Spotify in the background.

A: Quick fix that I think is better than these... download functionflip at http://kevingessner.com/software/functionflip/ and check two boxes: "F8: Play/pause" and "Start FunctionFlip at Login."  Then go to Ecoute or Spotify or whatever you're using, and set the keyboard shortcut for play/pause to F8 by pressing the play/pause key.  Now it'll work just as you want it to, and you will still be able to use it with itunes if you hold down the function (fn) key while you press it.
Works great for me!

A: andrew px and dmonner wrote an excellent workaround here: http://discussions.apple.com/thread.jspa?threadID=2122639&start=30&tstart=0
It uses a python script and some renaming to prevent iTunes from opening when applications of your choice are already open:
Open a Terminal and type the following
cd /Applications/iTunes.app/Contents/MacOS
sudo mv iTunes iTunesX
sudo curl https://web.archive.org/web/20130327115441if_/http://www.cs.umd.edu/~dmonner/iTunes -O
sudo chmod uog+x iTunes

From https://web.archive.org/web/20130327115441if_/http://www.cs.umd.edu/~dmonner/iTunes
#!/usr/bin/env python

import sys, os, subprocess

launch = True
blocker = ""

apps = ["Spotify", "Songbird"]

ps = subprocess.Popen("/bin/ps -x", shell=True, stdout=subprocess.PIPE)

for line in ps.stdout.read().split("\n"):
    for app in apps:
        if app in line:
            launch = False
            blocker = app

ps.stdout.close()

if launch :
    os.spawnvp(os.P_WAIT, '/Applications/iTunes.app/Contents/MacOS/iTunesX', sys.argv)
else :
    print "Not launching iTunes while %s is running." % blocker

Add whatever application you need to the list apps = ["Spotify", "Songbird", "your app here"]

A: Update: There is a GUI available that performs the below steps, at the official website.
Fixing this is very simple. While the installation process does involve using Mac Terminal, you do not need any knowledge of it. I have included images to make it easier! Just follow 6 simple instructions below and you are done!

*

*Download this zip file

*Unzip the file

*Run the Patch.command file (Double Click It)

*It will open mac terminal. It will most likely prompt you to enter your password. Type your password and press enter. It should look similar to the image below:

*At the bottom it will say "Everything is ready. Would you like to create a backup and apply the patch (y/N)". Type y, then press Enter. It should look similar to the image below:

*You are done! It should output some text and say [Process Complete] at the bottom. You can then close the mac terminal window. The process completing successfully should look similar to the image below:

Uninstall
If you want to remove this patch, simply run the Patch.command script again.
Here is the github repository Thanks to thebitguru for this script.

A: The real solution: Open Terminal, paste in the following line, and hit enter. You're done. To undo, change unload to load in the same line.
launchctl unload -w /System/Library/LaunchAgents/com.apple.rcd.plist

A: Instead of changing the name of iTunes.app, try changing the name of
/Applications/iTunes.app/Contents/MacOS/iTunes

to, for example
iTunes_

This prevents the iTunes.app from working when you double click on it, but at least it saves you from the respawning of iTunes when you press play/pause. If you want to use iTunes.app just rename the file back to "iTunes"

A: I have found a solution, though slightly hacky. Basically run iTunes, but select 'Applications' or 'Radio' from the side menu.
That way, when you press the play buttons, there is nothing to play in iTunes so it doesn't do anything, but it works in the application you want to control.

A: There is a patch available at http://www.thebitguru.com/projects/iTunesPatch that will disable opening iTunes when pressing the Play/Pause multimedia key. You have to unzip the file you download from the 'Play Button iTunes Patch 0.7' and run the 'Patch.command' program in the PlayButtonItunesPatch directory.
I have tested it on Snow Leopard (Mac OSX 10.6) and it works flawlessly. Play/Pause continues to work on open programs but will no longer open up iTunes. If you test it please leave feedback in the comments, whether it works or not.

A: The patches provided here generally don't work on more recent versions of Mac OS X like Mountain Lion.  Drawing more attention to @trisweb's answer in a comment:

Latest Mountain Lion patch here: thebitguru.com/projects/iTunesPatch /
  github: github.com/thebitguru/play-button-itunes-patch

A: This is a work-in-progress solution.. I mainly use XMBC and Hulu so can live without iTunes until there is a real solution:

*

*Delete iTunes from Applications

*Delete Front Row from Applications

*Empty your trash can

After these steps Hulu and XMBC are usable via the remote again! The only issue is that the Menu Key on the Remote still opens Front Row
=====
Personally I am considering using Win7 on my HTPC Mac Mini. Every app I use on the Mac has a Windows counterpart. It looks like this open source software will let the IR work in Boot Camp: http://www.eventghost.org/

A: In System Preferences, under the Keyboard pane, on the Keyboard tab, enable "Use all F1, F2, etc. keys as standard function keys".  Be sure to read the note about getting that functionality back by holding the Fn key.
Assign your Function-keys to various functions either in the Keyboard Shortcuts tab of the Keyboard pane, given application, or other preference pane (Exposé, etc).
Use an application like Quicksilver or Butler to assign actions, applications, and/or AppleScripts to various key shortcuts of your choosing.

A: I got around this problem (I only use spotify and iTunes so it probably wasn't as difficult) using an applescript that play/pauses spotify and Quicksilver. It won't work with a remote but If you just want to be able to quickly play/pause spotify without making itunes open and play etc it works like a treat.
This is the applescript if you're interested:
tell application "Spotify" to activate
tell application "System Events"
    tell process "Spotify"
        click menu item 1 of menu 1 of menu bar item 5 of menu bar 1
    end tell
end tell

A: I did a sort of low tech thingy that at least prevents iTunes to auto start. I renamed the iTunes.app using:
sudo mv /Applications/iTunes.app /Applications/iTunesX.app

This stops iTunes from autostarting but if you have it started you're still able to use media controls for it.

A: There was a recent Lifehacker article that pointed how to disable it:

*

*Free Your Mac's Media Keys from iTunes, No Manual Hacking Required

A: this solution is permanent and fool-proof. Go to your login items and take the iTunes Helper out of the login items, then go to Activity monitor (found in the Utilities folder under Applications) and quit out of iTunes Helper. The keys keep working, but iTunes Helper does not reopen and hitting play no longer opens iTunes.

A: This has been fixed now with iTunes 10.2 (released the same day the iPad 2 was presented). Now I can use Spotify without having to open an idle instance of Quicktime!

A: WORKING FIX, simplest and most effective solution (per mritunjai at https://discussions.apple.com/thread/2570254?start=75&tstart=0):

*

*Open Terminal

*Enter (these are two separate commands)
launchctl stop com.apple.rcd
launchctl unload /System/Library/LaunchAgents/com.apple.rcd.plist

A: I realize the OP originally asked about Snow Leopard, but it seems that at least for Spotify, this problem no longer exists on High Sierra -- the remote control buttons work just fine with Spotify and iTunes is no longer started as a side-effect.

A: a solution that worked for me for Mojave was to remove the execution bit from iTunes:
sudo chmod -x /Applications/iTunes.app/Contents/MacOS/iTunes
and optionally add the media player in question under
Preferences -> Security & privacy -> Accessibility

A: The software Mac Media Key Forwarder provides a user-friendly approach to prioritizing Spotify for your media keys. It runs in the background and gives you a few simple settings in the Mac menu bar. It just works.

Download and installation
It can be downloaded and installed directly from the homepage, or by using e.g. Homebrew:
brew cask install macmediakeyforwarder

Notes

*

*It is compatible with macOS Catalina.

*The software was previously known as High Sierra Media Key Enabler.

*Ensure the application is given sufficient privileges in Security & Privacy in the System Preferences.

*I am not affiliated with the developer(s), I am just a satisfied user.

A: Easiest solution: rename itunes.app!

*

*Get read/write permissions on itunes
select the app and press ctrl+i
click the small lock icon in the bottom left corner
enter your password
now set "everyone" to read write
close the info window

*Now you can rename the itunes.app

No more itunes popup open all the time!


text:
Q: Meaning of "nonexistent" in "Because his delivery was halting, the effect of his speech on the voters was nonexistent." I know that nonexistent means not exist or not real. But in this context what does nonexistent mean. Is it meaning his speech is not real or effective.

Because his delivery was halting, the effect of his speech on the voters was nonexistent.

A: His speech was not effective. Since delivery is mentioned, we know that the speech itself took place ("to deliver a speech" is a common collocation), but it's effect was negligible.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Property Get via Lambda Expression I have gotten quite use to being able to use lambda throughout my c# projects and in Visual Studio 2015 preview I can now use my properties as so:
public ObservableCollection<WorkspaceViewModel> Workspaces => workspaces ?? (workspaces = new ObservableCollection<WorkspaceViewModel>());

or
public string Something => something;

However when switching between Visual Studio 2015 and 2013... 2013 doesn't like them :(
Is there a way I can force 2013 to read these expressions and compile them properly, I understand MSbuild is open source now, do I have to tell 2013 to use a new version of MSbuild?
Cheers.

A: This is a c# 6 feature, you can get it working in VS 2013 but it seems that is no longer updated and was just used for previews.
How can I add C# 6.0 to Visual Studio 2013?
From the Roslyn site it says

You can also try April's End User Preview, which installs on top of
  Visual Studio 2013. (note: this VS 2013 preview is quite out of date,
  and is no longer updated)

Who knows if it will come out in VS2013 again...


text:
Q: How to do class type inside class type? do you know how to do a class-type inside another class-type?
Let's say I have a LinkedList class, and I want to do a Node class inside.
class LinkedList
{

class Node
{
 int val;
 Node *next;
 Node *prev;

};

};

And now I want to write methods in a .cpp file for the Node class. Can I write them in the .cpp file of the LinkedList, or do I have to make a new .cpp file for the node?
And how do I do that?

A: It's been a while since I was doing c++, but if I remember correctly you would put them in the same .cpp file. The trick is to define them including the containing class name:
Node* LinkedList::Node::getNext() {
    return next;
}

A: You should take a look at this : Nested Class
This is an example which shows how to declare nested class.


text:
Q: work in progress animation when background work is not complete in android In my app, I want to show user some animation when background work is in progress(e.g. like FIle downloading/getting surrent location etc).
How I can do that?

A: Use a asyncTask like below.
class MyTask extends AsyncTask<Void, Void, Void> {
ProgressDialog pd;
@Override
protected void onPreExecute() {
  super.onPreExecute();
   pd = new ProgressDialog(MainActivity.this);
   pd.setMessage("loading");
   pd.show();
}

@Override
protected Void doInBackground(Void... params) {
  // Do your request , eg: file download etc
}

@Override
protected void onPostExecute(Void result) {
  super.onPostExecute(result);
  if (pd != null)
  {
     pd.dismiss();
  }
}
}

call this class like below when you need it like below,
new MyTask().execute();

A: You can use progress bar for this purpose. You can create a progress bar and place in a custom dialog box. Or you can use a library for that purpose. I can suggest you some library. Here is some progress bar by Awesome Android UI -
https://github.com/wasabeef/awesome-android-ui#progress


text:
Q: How to bold one output text in Bash? I'm writing a Bash script that prints some text to the screen:
echo "Some Text"

Can I format the text? I would like to make it bold.

A: The most compatible way of doing this is using tput to discover the right sequences to send to the terminal:
bold=$(tput bold)
normal=$(tput sgr0)

then you can use the variables $bold and $normal to format things:
echo "this is ${bold}bold${normal} but this isn't"

gives

this is bold but this isn't

A: I assume bash is running on a vt100-compatible terminal in which the user did not explicitly turn off the support for formatting.
First, turn on support for special characters in echo, using -e option. Later, use ansi escape sequence ESC[1m, like:
echo -e "\033[1mSome Text"

More on ansi escape sequences for example here: ascii-table.com/ansi-escape-sequences-vt-100.php

A: In theory like so:
# BOLD
$ echo -e "\033[1mThis is a BOLD line\033[0m"
This is a BOLD line

# Using tput
tput bold
echo "This" #BOLD
tput sgr0 #Reset text attributes to normal without clear.
echo "This" #NORMAL

# UNDERLINE
$ echo -e "\033[4mThis is a underlined line.\033[0m"
This is a underlined line.

But in practice it may be interpreted as "high intensity" color instead.
(source: http://unstableme.blogspot.com/2008/01/ansi-escape-sequences-for-writing-text.html)

A: In order to apply a style on your string, you can use a command like:
echo -e '\033[1mYOUR_STRING\033[0m'

Explanation:

*

*echo -e - The -e option means that escaped (backslashed) strings will be interpreted

*\033 - escaped sequence represents beginning/ending of the style

*lowercase m - indicates the end of the sequence

*1 - Bold attribute (see below for more)

*[0m - resets all attributes, colors, formatting, etc.

The possible integers are:

*

*0 - Normal Style

*1 - Bold

*2 - Dim

*3 - Italic

*4 - Underlined

*5 - Blinking

*7 - Reverse

*8 - Invisible


text:
Q: Get nested custom fields JSON Objective C Im having a bit of a problem with a JSON I get in Objective C
this is the JSON:
 {
        "id": 264,
        "type": "products",
        "slug": "dali",
        "url": "http://localhost/?products=dali",
        "status": "publish",
        "title": "Dali",
        "title_plain": "Dali",
        "content": "",
        "excerpt": "",
        "date": "2014-03-25 15:47:16",
        "modified": "2014-04-04 15:52:52",
        "categories": [
            {
                "id": 26,
                "slug": "juices-2",
                "title": "Juices",
                "description": "",
                "parent": 0,
                "post_count": 1
            }
        ],
        "tags": [],
        "author": {
            "id": 1,
            "slug": "arturocalvo",
            "name": "arturocalvo",
            "first_name": "",
            "last_name": "",
            "nickname": "arturocalvo",
            "url": "",
            "description": ""
        },
        "comments": [],
        "attachments": [],
        "comment_count": 0,
        "comment_status": "closed",
        "custom_fields": {
            "tipo_de_producto": [
                "bebida"
            ],
            "tipo_de_bebida": [
                "jugo"
            ],
            "product_0_sucursal": [
                "2"
            ],
            "product": [
                "1"
            ],
            "product_0_sizes_0_size": [
                "s"
            ],
            "product_0_sizes_1_size": [
                "m"
            ],
            "product_0_sizes_2_size": [
                "l"
            ],
            "product_0_sizes": [
                "3"
            ],
            "product_0_prices_0_price": [
                "20"
            ],
            "product_0_prices_1_price": [
                "25"
            ],
            "product_0_prices_2_price": [
                "30"
            ],
            "product_0_prices": [
                "3"
            ]
        }
    }

when Im mapping it with ResKit, I want to store the 3 different sizes in an array I have in the class Below:
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#import "ProductPrice.h"

@class Categories, ProductPrice;

@interface AllProducts : NSObject

@property (nonatomic, copy) NSString * name;
@property (nonatomic, copy) NSSet * productType;
@property (nonatomic, copy) NSSet * locationId;
@property (nonatomic, copy) NSArray * sizes;
@property (nonatomic, copy) NSSet * productCategoryId;

@end

this is the Object mapping code:
//Products Mapping
RKObjectMapping *productsMapping = [RKObjectMapping mappingForClass:[AllProducts class]];
[productsMapping addAttributeMappingsFromDictionary:@{
                                                      @"title": @"name",
                                                      @"custom_fields.product_0_sucursal": @"locationId",
                                                      @"custom_fields.tipo_de_producto": @"productType",
                                                      @"categories.id": @"productCategoryId"
                                                      }];

the problem Im having is that the keys of the JSON came with 3 different numbers, product_0_sizes_0_size and then in goes from 0 to 2, I don't know what to put in the mapping code, can anyone help me?, thanks in advance

A: Well, your situation is a bit rubbish (due to the unpleasant JSON). If you had the option you should change that.
As you can't, I think the best option is to create a dynamic mapping that you use as the mapping of the response descriptor. That mapping returns a mapping created from what you currently have with additions made in a loop based on the content of product_0_sizes to generate the source key paths.
Now, things get more unpleasant as you can only have one mapping to each destination key, and you obviously have multiple source keys that you want to merge to a single destination key.
I'd try abuse setValue:forUndefinedKey: to work around that. If you create your destination keys as appendSize0, appendSize1, ... without creating those properties on the class then setValue:forUndefinedKey: should be called on your destination class for each source key that is mapped. In your implementation of setValue:forUndefinedKey: you can extract the supplied values and append them to your true sizes array.
(Note: I haven't directly tried this but it should work. There is a risk of issues with type introspection for data type mutation...)
(Note: Your implementation of setValue:forUndefinedKey: should call super if you receive a key that doesn't start with appendSize)
Abusing setValue:forUndefinedKey: is certainly minimal code. Alternative would be to add a whole heap of properties that you can map into, but that's not very nice or flexible.


text:
Q: How to display Typescript Runtime errors/exceptions in .ts instead of .js Im new to typescript. Im using a serverless solution from google (google cloud functions) that in the background is running Node.js with typescript.  When I get an "runtime error" in the logs I see an error in a .js file, this makes sense since .ts code is compiled to .js but it makes debugging a lot harder as I write typescript code and not javascript code. In general I would like to see the line that produced the error in .ts and not in .js. Is this possible?

A: You will need a "source map" to map the JavaScript line numbers to TypeScript line numbers.
You can do this with the source-map-support node module.  First install it in your project:
npm install source-map-support

Then add this to your TypeScript file (index.ts):
require('source-map-support').install()

Then, if you function crashes, the line numbers should show TypeScript source lines.


text:
Q: How to validate cascading dropdown in MVC I am developing a MVC application and I am using Cascading dropdown in one of my dropdown. The problem is I need to validate both drop downs if user has not selected any value. Currently its validating both drop downs when you clicks on save after immediate opening of pop up, but when you selects value from master drop down(Company) and selects value from Child drop down(Customer) and again change value of master drop down the child drop down is not validating.
Here I am providing code of my Model, View and Controller file.
Model-
public class CustomerComment : BaseModel
    {

        [Required(ErrorMessage = "Please select Customer name")]
        public int InvoiceCustomerId { get; set; }

        public string OldCustomerId { get; set; }

        [Display(Name = "Invoice Customer")]
        public string  InvoiceCustomerName { get; set; }

        [Display(Name = "Invoice Customer")]
        public string InvoiceCustomer { get; set; }

        [Required(ErrorMessage = "Please select Company name")]
        public int CompanyId { get; set; }

        [Display(Name = "Company Name")]
        [Required(ErrorMessage = "Please enter Company name")]
        public string CompanyName { get; set; }

        public string  Company { get; set; }

        [Display(Name = " Comment")]
        [StringLength(220, ErrorMessage = "Customer comment must be maximum length of 220")]
        public string Comment { get; set; }

        [Display(Name = "Group")]
        public bool Group { get; set; }

        public List<InvoiceCustomer> InvoiceCustomerList { get; set; }

        public CustomerComment()
        {
            InvoiceCustomerList = new List<InvoiceCustomer>();
        }
}

View:
@model ACS.MDB.Net.App.Models.CustomerComment

@{
    ViewBag.Title = "MDB::Customer Comment";
}

    @using (Html.BeginForm())
    {
        @Html.ValidationSummary(true)

        //hidden field
        @Html.HiddenFor(m => m.ID)
        @Html.HiddenFor(m => m.InvoiceCustomerId, new { @id = "txtCustomerId" })
        @Html.HiddenFor(m => m.CompanyId, new { @id = "txtCompanyId" })
        @Html.HiddenFor(m => m.InvoiceCustomerName, new { @id = "txtCustomerName" })
        @Html.HiddenFor(m => m.CompanyName, new { @id = "txtCompanyName" })

            @if (Model.ID != 0)
            {

                        @Html.LabelFor(m => m.CompanyName)

                        @Html.DisplayFor(m => m.CompanyName, new { style = "width:300px" })

            }
            else
            {

                        @Html.LabelFor(m => m.CompanyName, new { @class = "mandatoryLabel" })

                        @Html.DropDownListFor(x => x.CompanyId, new SelectList(Model.OAcompanyList, "ID", "Name", Model.CompanyId), "Select Company", new { @id = "ddlCompany", style = "width:300px;height:25px" })

                        @Html.ValidationMessageFor(model => model.CompanyId)

            }

            @if (Model.ID != 0)
            {

                        @Html.LabelFor(m => m.InvoiceCustomerName)

                        @Html.DisplayFor(m => m.InvoiceCustomerName, new { style = "width:300px" })

            }
            else
            {

                        @Html.LabelFor(model => model.InvoiceCustomerName, new { @class = "mandatoryLabel" })

                        @Html.DropDownListFor(x => x.InvoiceCustomerId, new SelectList(Model.InvoiceCustomerList, "ID", "CustomerandOACustomerId", Model.InvoiceCustomerId), "Select Customer", new { @id = "ddlInvCustomer", style = "width:300px;height:25px" })

                    @Html.ValidationMessageFor(m => m.InvoiceCustomerId)

            }

                    @Html.LabelFor(m => m.Comment)

                    @Html.TextAreaFor(m => m.Comment, 4, 1, new { @id = "txtCustomerComment", @maxlength = "220", style = "width:290px; resize: none" })

                    @Html.ValidationMessageFor(model => model.Comment)

                    @Html.LabelFor(m => m.Group, new { style = "width:200px" })

                    @Html.CheckBoxFor(m => m.Group)

    }

Controller:
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using ACS.MDB.Net.App.Common;
using ACS.MDB.Net.App.Models;
using ACS.MDB.Net.App.Services;
using ACS.MDB.Net.App.ValueObjects;
using MODEL = ACS.MDB.Net.App.Models;

namespace ACS.MDB.Net.App.Controllers
{
    public partial class ContractController
    {
        ///
        /// Returns CustomerComment index view
        ///
        /// <returns>CustomerComment index view</returns>
        /// GET: /ContractController/CustomerComment/
        public ActionResult CustomerCommentIndex()
        {
            return IndexView();
        }

        ///
        /// Gets the customer comment list
        ///
        /// <param name="param"></param>
        /// <returns>Customer comment List</returns>
        public ActionResult CustomerCommentList(MODEL.jQueryDataTableParamModel param)
        {
            try
            {
                List<Company> companyList = Session.GetUserAssociatedCompanyList();
                List<CompanyVO> companyVOList = new List<CompanyVO>();
                foreach (var item in companyList)
                {
                    companyVOList.Add(new CompanyVO(item));
                }

                CustomerCommentService customerCommentService = new CustomerCommentService();
                List<MODEL.CustomerComment> customerCommentList = new List<CustomerComment>();

                List<CustomerCommentVO> customerCommentVOList = customerCommentService.GetCustomerCommentList(companyVOList);

                foreach (var item in customerCommentVOList)
                {
                    customerCommentList.Add(new MODEL.CustomerComment(item));
                }

                //get the field on with sorting needs to happen and set the
                //ordering function/delegate accordingly.
                int sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
                var orderingFunction = GetCustomerCommentOrderingFunction(sortColumnIndex);

                var result = GetFilteredObjects(param, customerCommentList, orderingFunction);
                return result;
            }
            catch (Exception e)
            {
                return new HttpStatusCodeAndErrorResult(500, e.Message);
            }
        }

        ///
        /// Create new customer comment
        ///
        /// <returns>The Customer comment details view</returns>
        public ActionResult CustomerCommentCreate()
        {
            try
            {
                MODEL.CustomerComment customerComment = new MODEL.CustomerComment();

                customerComment.OAcompanyList = Session.GetUserAssociatedCompanyList();
                return PartialView("CustomerCommentDetails", customerComment);
            }
            catch (Exception e)
            {
                return new HttpStatusCodeAndErrorResult(500, e.Message);
            }
        }

        ///
        /// Edit customer comment
        ///
        /// <param name="id">The customer comment id</param>
        /// <returns>Customer comment details</returns>
        public ActionResult CustomerCommentEdit(int id)
        {
            MODEL.CustomerComment customercomment = new CustomerComment();
            try
            {
                CustomerCommentService customerCommentService = new CustomerCommentService();

                //Get Customercomment details
                CustomerCommentVO customerCommentVO = customerCommentService.GetCustomerCommentById(id);
                if (customerCommentVO == null)
                {
                    ModelState.AddModelError("", String.Format(Constants.ITEM_NOT_FOUND, Constants.CUSTOMERCOMMENT));
                }
                else
                {
                    customercomment = new CustomerComment(customerCommentVO);
                }
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", e.Message);
            }
            return PartialView("CustomerCommentDetails", customercomment);
        }

        ///
        /// Save the customer comment
        ///
        /// <param name="model">model object</param>
        /// <returns></returns>
        public ActionResult CustomerCommentSave(MODEL.CustomerComment model)
        {
                try
                {
                    if (model.InvoiceCustomerId == 0)
                    {
                        throw new ApplicationException("Please select Customer name");
                    }

                    else
                    {
                        CustomerCommentService customerCommentService = new CustomerCommentService();

                        if (ModelState.IsValid)
                        {
                            //Get user id
                            int? userId = Session.GetUserId();
                            if (userId.HasValue)
                            {
                                CustomerCommentVO customerCommentVO = new CustomerCommentVO(model, userId);
                                customerCommentService.SaveCustomerComment(customerCommentVO);
                            }
                            return new HttpStatusCodeResult(200);
                        }
                        else
                        {
                            throw new ApplicationException(String.Format(Constants.CANNOT_SAVE, Constants.CUSTOMERCOMMENT));
                        }
                    }
                }
                catch (ApplicationException e)
                {
                    return new HttpStatusCodeAndErrorResult(500, e.Message);
                }
        }

        ///
        /// Delete the Customer comment(s)
        ///
        /// <param name="Ids">Ids of customerComment to be deleted</param>
        public ActionResult CustomerCommentDelete(List<int> ids)
        {
            try
            {
                CustomerCommentService customerCommentService = new CustomerCommentService();
                customerCommentService.DeleteCustomerComment(ids);
                return new HttpStatusCodeResult(200);
            }
            catch (Exception e)
            {
                return new HttpStatusCodeAndErrorResult(500, e.Message);
            }
        }

        ///////
        /////// Gets the Customer List
        ///////
        /////// <returns>Invoice Customer List</returns>
        //public List<MODEL.InvoiceCustomer> GetCustomerList()
        //{
        //    MODEL.CustomerComment customerComment = new CustomerComment();
        //    InvoiceCustomerService invoiceCustomerService = new InvoiceCustomerService();
        //    List<InvoiceCustomerVO> invoiceCustomerVOList = invoiceCustomerService.GetAllCustomerList();

        //    foreach (InvoiceCustomerVO item in invoiceCustomerVOList)
        //    {
        //        customerComment.InvoiceCustomerList.Add(new MODEL.InvoiceCustomer(item));
        //    }

        //    return customerComment.InvoiceCustomerList;
        //}

        /////
        ///// Gets invoice customer list based on customer name
        /////
        ///// <param name="customerName">customer name</param>
        ///// <returns>Invoice customer List</returns>
        //public JsonResult GetCompanyByCustomerName(string customerName)
        //{
        //    try
        //    {
        //        InvoiceCustomerService invoiceCustomerService = new InvoiceCustomerService();
        //        List<CompanyVO> companyVOList = invoiceCustomerService.GetCompanyListByCustomerName(customerName);
        //        //List<InvoiceCustomerVO> invoiceCustomerVOList = invoiceCustomerService.GetCompanyByCustomerName(customerName);

        //        return Json(companyVOList);
        //    }
        //    catch (Exception e)
        //    {
        //        return Json(new ApplicationException());

        //    }
        //}

        ///
        /// Get InvoiceCustomer List based on companyId
        ///
        /// <param name="companyId">company Id</param>
        /// <returns>Invoice customer List based on company Id</returns>
        public JsonResult GetInvoiceCustomerListByCompany(int companyId)
        {
            try
            {
                InvoiceCustomerService invoiceCustomerService = new InvoiceCustomerService();
                List<InvoiceCustomerVO> invoiceCustomerVOList = invoiceCustomerService.GetInvoiceCustomerList(companyId);

                return Json(invoiceCustomerVOList);
            }
            catch (Exception e)
            {
                return Json(new ApplicationException());

            }
        }

        /// The function used to return field used for sorting
        ///
        /// <param name="sortCol">The column number on which sorting needs to happen</param>
        /// <returns></returns>
        public Func<BaseModel, object> GetCustomerCommentOrderingFunction(int sortCol)
        {
            Func<BaseModel, object> sortFunction = null;
            switch (sortCol)
            {
                case 2:
                    sortFunction = obj => ((MODEL.CustomerComment)obj).InvoiceCustomer;
                    break;
                case 3:
                    sortFunction = obj => ((MODEL.CustomerComment)obj).Company;
                    break;
                case 4:
                    sortFunction = obj => ((MODEL.CustomerComment)obj).Comment;
                    break;
                default:
                    sortFunction = obj => ((MODEL.CustomerComment)obj).ID;
                    break;
            }

            return sortFunction;
        }
    }
}


text:
Q: Failure to build pyarrow numpy when pip installing streamlit, python 3.9.4 I get the following error when I pip install streamlit:
Failed to build pyarrow numpy
ERROR: Could not build wheels for pyarrow, numpy which use PEP 517 and cannot be installed directly


text:
Q: How to implement Service inherit from generic repository? I work on asp.net core mvc blazor application , I have issue I can't implement service inherit from generic repository .
meaning how to inherit from IRepository to get functions below on class server names service :
Insert
Update
GetById
GetList
GetListAsync
Interface generic repository
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

public interface IRepository<TEntity> where TEntity : class
{

    Task<int> Count(Expression<Func<TEntity, bool>> where);
    TEntity GetByID(object id);
    TEntity Insert(TEntity entity);
    void Update(TEntity entityToUpdate);
    Task<ICollection<TType>> Get<TType>(Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, TType>> select) where TType : class;
    Task<bool> Any(Expression<Func<TEntity, bool>> where);
    TEntity GetFirst(Expression<Func<TEntity, bool>> where);
    TEntity Single(Expression<Func<TEntity, bool>> where);
    Task<List<TEntity>> GetListAsync(Expression<Func<TEntity, bool>> where);
    List<TEntity> GetList(Expression<Func<TEntity, bool>> where);
    Task<bool> UpdateBasedOnCondition(Expression<Func<TEntity, bool>> where, Action<TEntity> select);
    void Save();

}

class that implement interface as below :
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;

using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using UC.AppRepository.Core;

public class BaseRepository<TEntity> : IRepository<TEntity> where TEntity : class
{
    internal AppsRepositoryDBContext _context;
    internal DbSet<TEntity> dbSet;

    public BaseRepository(AppsRepositoryDBContext context)
    {
        _context = context;
        this.dbSet = _context.Set<TEntity>();
    }

    public virtual TEntity GetByID(object id)
    {
        return dbSet.Find(id);
    }

    public virtual TEntity Insert(TEntity entity)
    {
        var result = dbSet.AddAsync(entity).Result.Entity;
        Save();
        return result;
    }

    public virtual void Update(TEntity entityToUpdate)
    {
        dbSet.Attach(entityToUpdate);
        _context.Entry(entityToUpdate).State = EntityState.Modified;
    }

    public virtual async Task<bool> UpdateBasedOnCondition(Expression<Func<TEntity, bool>> where, Action<TEntity> select)
    {
        try
        {
            var ListOfRecord = await dbSet.Where(where).ToListAsync();
            if (null != ListOfRecord && ListOfRecord.Count > 0)
            {
                ListOfRecord.ForEach(select);
                //  Save();
                await _context.SaveChangesAsync();
                return true;
            }
            return false;
        }
        catch (Exception ex)
        {
            return false;
            throw;
        }

    }

    public async Task<ICollection<TType>> Get<TType>(Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, TType>> select) where TType : class
    {
        if(where == null)
        {
            return await dbSet.Select(select).ToListAsync();
        }
        return await dbSet.Where(where).Select(select).ToListAsync();
    }

    public async Task<int> Count(Expression<Func<TEntity, bool>> where)
    {
        return await dbSet.Where(where).CountAsync();
    }

    public async virtual Task<List<TEntity>> GetListAsync(Expression<Func<TEntity, bool>> where)
    {

        //  var test = dbSet.Where(where).ToList();
        return await dbSet.Where(where).ToListAsync();

    }

    public virtual List<TEntity> GetList(Expression<Func<TEntity, bool>> where)
    {
        return dbSet.Where(where).ToList();

    }

    public async Task<bool> Any(Expression<Func<TEntity, bool>> where)
    {
        return await dbSet.AnyAsync(where);
    }

    public TEntity GetFirst(Expression<Func<TEntity, bool>> where)
    {
        return dbSet.FirstOrDefault(where);
    }

    public TEntity Single(Expression<Func<TEntity, bool>> where)
    {
        return dbSet.Single(where);
    }

    public void Save()
    {
        try
        {
            _context.SaveChanges();
        }
        catch (Exception ex)
        {

            throw;
        }

    }
}

so I have class ServerNameService and class interface IserverNamesService
I need to implement insert,update,selectById,selectall functions for server name models
from base repository
 public class ServerNameService:IRepository
    {
// what i write here
    }

 public interface IserverNamesService:IRepository
    {
// what i write here
    }

public class ServerNames
    {
        [Key]
        public int ServerID { get; set; }
        public string Server_Name{ get; set; }
        public string Server_Type { get; set; }
        public string Operating_System { get; set; }
        public string Version { get; set; }
        public bool IsActive { get; set; }

    }

A:
I have issue I can't implement service inherit from generic repository.I have class ServerNameService and class interface IserverNamesService I need to implement insert,update,selectById,selectall functions for server name models from base repository

Well, to directly answer your question, to implement your ServerNameService which derived from IRepository that would would be as following:
IserverNamesService:
public interface IserverNamesService : IRepository<ServerNames>
    {

    }

Note: Keep it empty because we will use of IRepository and BaseRepository in ServerNamesService class to implement its members.
ServerNamesService:
public class ServerNamesService : BaseRepository<ServerNames>, IserverNamesService
    {
        public ServerNamesService(ApplicationDbContext context) : base(context)
        {
        }

        public override ServerNames GetByID(object id)
        {
            return _context.ServerNames.Where(sn => sn.ServerID == (int)id).FirstOrDefault();

        }
    }

Controller:
[Route("api/[controller]")]
[ApiController]
public class ServerNamesServiceController : ControllerBase
{

    private readonly IserverNamesService _serverNamesService;

    public ServerNamesServiceController(IserverNamesService namesService)
    {
        _serverNamesService = namesService;
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetById(object id)
    {
        var item = _serverNamesService.GetByID(id);

        if (item == null)
            return NotFound();

        return Ok(item);
    }

}

Program.cs:
builder.Services.AddScoped<IserverNamesService, ServerNamesService>();

Note: Register your ServerNamesService class in your program.cs
UnitOfWork Pattern Implementation:
As long your application would continue evolving and there would be ton of service class, in that scenario, you have to introduce lot of service in your controller. But if you would like to handle those smoothly, you could use UnitOfWork pattern which would contain all of your service together.
Interface:
 public interface IUnitOfWork
    {
        IserverNamesService ServerNamesService { get; }
        Task CompleteAsync();
    }

Implementation:
public class UnitOfWork : IUnitOfWork, IDisposable
    {
        private readonly ApplicationDbContext _context;

        public IserverNamesService ServerNamesService { get; private set; }

        public UnitOfWork(ApplicationDbContext context)
        {
            _context = context;
            ServerNamesService = new ServerNamesService(context);
        }

        public async Task CompleteAsync()
        {
            await _context.SaveChangesAsync();
        }

        public void Dispose()
        {
            _context.Dispose();
        }
    }

Controller:
    [Route("api/[controller]")]
    [ApiController]
    public class ServerNamesServiceController : ControllerBase
    {

        private readonly IUnitOfWork _unitOfWork;
        public ServerNamesServiceController(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        [HttpGet("{id}")]
        public async Task<IActionResult> GetById(object id)
        {
            var item = _unitOfWork.ServerNamesService.GetByID(id);

            if (item == null)
                return NotFound();

            return Ok(item);
        }

    }

Output:

Note: If you would like to know more details on repository pattern you could check our official document here and working sample here.

A: You should pass your Entity as generic type to IRepository in IServerNamesService, and then inheritance  ServerNameService from IServerNamesService.
public interface IServerNamesService:IRepository<ServerNames>
{
    // your methods interface
}

  public class ServerNameService:IServerNamesService{
         private readonly IRepository<ServerNames> _repository;

         public class ServerNameService(IRepository<ServerNames> repository)
         {
             _repository = repository;
         }
         //body of your methods
   }


text:
Q: Complex pagination with AJAX POST and $.getJSON I have multiple checkboxes group whose value, if checked, is passed to a php page in an object with jquery, i get the results all good. Now I want to paginate the results. I am not sure how to go about this. As using pagination is not returning any value passed by AJAXPOST. My JS :
$(":checkbox").on('change', function() {
    var mygroup = {};
    $(':checkbox:checked').each(function(i) {
        var val = this.value;
        var name = this.name;
        mygroup[name] = (mygroup[name] || []).concat([val]);
    });

    var itemsPerPage = 5;

    if(typeof url == 'undefined' ){
    url = "finalprocess1.php?page=1&items_per_page="+itemsPerPage;
}
     $.ajax({
        type: "POST",
        url: 'finalprocess.php',
        data: mygroup,
        success: function(data) {

        $.getJSON(url, function(data){       //NOT SURE IF I CAN DO THIS
        var result = userTemplate({users : data.users})  //UNDERSCORE TEMPLATING
        $("#theresult").html(result);
            });
        }
    });

});

A: You should add a LIMIT and OFFSET clause to your query on the php side, to take certain ranges according to your page limit: (example using plain sql, php and PDO)
$limit = $_GET['items_per_page'];  //Page limit

//Get request page, if not set to 1
!null == $_GET['page'] ? $page = $_GET['page'] : $page = 1;

//Get total rows count
$totalRows = $this->db->query('SELECT FOUND_ROWS from items')->fetchColumn();

//Calculate number of pages
$totalPages = ceil($totalRows / $limit);

//Show next or previous button only when needed validation
$hasPrevPage = $page > 1 ? true : false;
$hasNextPage = $page < $totalPages ? true : false;

//Calculate offset
$offset = ($page - 1) * $limit;

$sql = "SELECT * from items
        LIMIT :pageLimit OFFSET :offset"; //The standard pagination clause

$query = $this->db->prepare($sql);
$query->bindValue(':pageLimit', $limit);
$query->bindValue(':offset', $offset);
$query->execute();
return $query->fetchAll();

Then on your view you should create two links, previous and next, mantaining your request URI and modifing the page parameter, +1 to page on next and -1 on previous so you can navigate the results
just as you did here:
url = "finalprocess1.php?page=1&items_per_page="+itemsPerPage;

but modifying the page parameter:
prevUrl = "finalprocess1.php?page=" + (page-1) + "&items_per_page=" + itemsPerPage;
nextUrl = "finalprocess1.php?page=" + (page+1) + "&items_per_page=" + itemsPerPage;

Make sure you pass these validations to your js to show the buttons only when needed, and prevent an offset error.
$hasPrevPage = $page > 1 ? true : false;
$hasNextPage = $page < $totalPages ? true : false;


text:
Q: Namespace constant in C# Is there any way to define a constant for an entire namespace, rather than just within a class?  For example:
namespace MyNamespace
{
    public const string MY_CONST = "Test";

    static class Program
    {
    }
}

Gives a compile error as follows:
Expected class, delegate, enum, interface, or struct

A: You can use the constants in your other classes if you add the "Using Static" too:
using static MyNameSpace.MyGlobals;

namespace MyNameSpace {
    public static class MyGlobals{
        public const bool SAVE_LOGSPACE = true;
        public static readonly DateTime BACKTEST_START_DATE = new DateTime(2019,03,01);
    }
}

A: No, there is not. Put it in a static class or enum.

A: This is not possible
From MSDN:

The const keyword is used to modify a declaration of a field or local variable.

Since you can only have a field or local variable within a class, this means you cannot have a global const. (i.e namespace const)

A: I believe it's not possible. But you can create a Class with only constants.
public static class GlobalVar
{
    public const string MY_CONST = "Test";
}

and then use it like
class Program
{
    static void Main()
    {
        Console.WriteLine(GlobalVar.MY_CONST);
    }
}

A: I would define a public static class with constants:
namespace Constants
{
    public static class Const
    {
        public const int ConstInt = 420;
    }
}

Inside my Program.cs, i would add the following using:
using static Constants.Const;
using static System.Console;

Now you can freely use the defined constants (which are static by default) and static Console-Methods, e. g.
class Program
{
    static void Main(string[] args)
    {
        WriteLine(ConstInt);
    }
}


text:
Q: How do astronomers determine the distance of a luminuos body from Earth and the direction of its velocity? As it is explain here, we can determine the speed a luminous body along the direction of the line of sight in the sky; moreover, with enough long observation, we can observe how much the body change its position in the sky, but how can we actually determine how far is this body from Earth, and what is it's velocity ?
I mean without knowing how far the body is, we cannot say anything about its speed along perpendicular to the line of sight from its proper motion in the sky.

A: If we known the intrinsic luminosity of the star, then we can determine its luminosity distance from the fact that the apparent luminosity of the object will diminish with the square of the distance. The intrinsic luminosity can sometimes be inferred from other observable qualities such as the temperature or variability (depending on the type of object).
For stars that are not too distant we can also use stellar parallax to measure their distance. As the Earth (and we with it) move around the Sun, the position of nearby stars shifts compared to distant stars (see diagrams on Wikipedia page). The size of this shift is (approximately) inversely proportional to the distance. This type of measurement is the fundamental basis for most distance measurements in astronomy. In fact the most common distance unit in astronomy, the parsec, was originally defined as the distance of an object with a parallax of 1 arcsecond.


text:
Q: Laravel listen socket.io client emit I have chat application using Laravel + laravel-echo-server + Redis.
currently i am using http api request from client to send message.
But its slow if i have large client number.
Is there a way to send message from client to server through socket and listen in laravel?
Probably something like this
    public function onMessage($client, $data)
    {
        .....
    }

i already tried laravel-websocket, but if i set APP_DEBUG=false in .env CustomSocketHandler unable to work anymore.
Thank you.


text:
Q: Design for 110 V brownout detector I suspect that a power circuit in my home has an intermittent connection somewhere, and I'd like to test this to be sure (because if I'm wrong, then the equipment running on that circuit needs to be sent back for warranty repair).
I have the idea that if I can take either an isolating step-down transformer, or perhaps just a voltage divider, from the power rail, then feed it into an ADC on a micro-controller (probably ESP8266). I should be able to monitor continuously and trigger an alert, or record some data in a file in an SD card, if it detects that the rail has not reached a proper peak voltage within the last 1/60th of a second.
Obviously, I'm dealing with high enough voltage that it'll bite me if I mess up, and for that matter, if I divide carelessly, I could easily let the smoke escape from the ESP, but in principle I can get those things right. But, are there other concerns (or specifics about the above concerns) that might have eluded me?
It's also possible that there's a device cheaply available on the market that would do this, but if so, I've failed to find it. I'm happy enough to buy something if it's not too expensive, so if such a thing has a name, I'd be pleased to hear what that name is.

A: Easiest (and very safe) approach is to find an old non-switching (linear) wall wart and divide the DC output down to some acceptable voltage for the ADC with a simple voltage divider.
The divider resistance can help determine how fast the voltage drops when there is an interruption.
Response will be fractions of a second not cycle-by-cycle. If you need the latter, you can use a (more rare) AC output wall wart and a bridge rectifier/voltage divider.

A: A really cheap and simple way to determine if there are glitches or brownouts on an AC line would be an AC relay that latches on by means of a NO contact. When the disturbance occurs, the relay will drop out until manually reset. You could also connect an old style electric clock across the coil, and it will stop at the instant power drops out.
If you want to know how many times a disturbance occurs, you could connect an electromechanical counter to the relay contacts.

A: Using DC gets tricky because of the capacitor(s) and the associated time constant. You can transformer the AC down then use an optocoupler (resistor needed for led value dependent on transformer output voltage) to look for missing cycles and leve. This gives you double isolation from the mains and low voltages to work with. The ADC will give you amplitude for brownout and you can use the digital input on your microcontroller to do the monitoring for you and trigger the ADC.  You can if you want use a count totalizer and a RTC and log the readings and time every maybe 15 seconds (or whatever you want) minutes to see if there is a pattern. For a single instance you can use a retriggerable one shot with the optocoupler or implement it in software.


text:
Q: How to set the app always login until user click the logout button on ionic3 I created a new mobile app in ionic3
If an user closes the app without clicking the logout button, the user should be logged in if he or she re-opens the app. However, if an user closes the app and re-opens it, login page appears.
How do I set up the app so the users stay logged in until they click the logout button?

A: Well, the way I think they do that, is tracking the ip.  If the user enters from the same ip, and user has not log out (you have to save that info in a tb) the the script logs him/her in with user info ( that user info also in the former tb along with the ip)
YOu should have guessed that

A: In my case, I use JWT (https://jwt.io/) for authentication.
So, when users login, the jwt info would be stored in localStorage as well.
Of course, when user logout, JWT info in localStorage will be deleted.
When application is launched, I check localStorage and if there is a valid JWT info (JWT has valid time info as well), I use the JWT info.
I hope it would be helpful :)

A: You can recover it by using localstorage
I will provide an example for you.As usal app.component.ts is load first so i need to work on it for which page are showing.
import { Component, ViewChild } from '@angular/core';
import { Platform, Nav  } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import {ProfilePage} from "../pages/profile/profile";
import {LoginPage} from "../pages/login/login";

@Component({
  templateUrl: 'app.html'
})

export class MyApp {

  @ViewChild(Nav) nav: Nav;
  rootPage: any;

  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {

    platform.ready().then(() => {
      this.initializeApp(statusBar, splashScreen);
    });

  }

  initializeApp(statusBar: StatusBar,
                splashScreen: SplashScreen) {

    let username = window.localStorage.getItem('username') ? window.localStorage.getItem('username') : '';
    let password = window.localStorage.getItem('password') ? window.localStorage.getItem('password') : '';

    if(username == 'user' && password == 'user') {
      this.nav.setRoot(ProfilePage);
    }else{
      this.nav.setRoot(LoginPage);
    }
    statusBar.styleDefault();
    splashScreen.hide();
  }
}

Here username and pasword are taken from localstorage if they have no value then its load LoginPage.In LoginPage you need to setup for storing username and password in localstorage.
  signIn(){

    if (this.loginForm.value.username=="user" && this.loginForm.value.password=="user") {
          window.localStorage.setItem('username', this.loginForm.value.username);
        window.localStorage.setItem('password', this.loginForm.value.password);
          this.navCtrl.setRoot(ProfilePage);
    }
  }

And also when you logout then destroy username and password localstorage value.
 window.localForage.removeItem('username')
 window.localForage.removeItem('password')


text:
Q: Keyboard shortcut to an action in SWT How to define a keyboard shortcut (accelerator) to an action associated with a context menu item of TreeViewer or TableViewer (or any control in general).
I have trees and tables of different kind of objects and I have generic actions like "move up", "move down", "expand" or "collapse". I created context menus for table or tree controls, but I want the user to be able to call actions without necessity of right clicking on selection (or without necessity of using mouse in general). For example "Move up" action should be called when the viewer is focused and user presses Alt+↑.
Setting accelerator to that actions does not work. I do not also want to add the actions to main menu bar (like Edit menu etc.).

A: I take it you are using Action for your actions.
Call
setActionDefinitionId("command id");

in your Action constructor to specify a command that this action handles.
Declare the command in your plugin.xml using the org.eclipse.ui.commands extension point.
Use the org.eclipse.ui.bindings extension point to bind a key sequence to the command.

A: Just for future generations:
I followed Greg's advice and added KeyListsner to the viewer control. This is a snippet of my class that wraps StructuredViewer:
private class ViewerWrapper{

    private StructuredViewer fViewer;

    [...]

    private class ViewerKeyAdapter implements KeyAdapter{
        private int fKeyCode;
        private Action fAction;
        private int fStateMask;

        public ViewerKeyAdapter(int keyCode, int stateMask, Action action){
            fKeyCode = keyCode;
            fStateMask = stateMask;
            fAction = action;
        }

        @Override
        public void keyReleased(KeyEvent e) {
            if((e.stateMask & fStateMask) != 0 || fStateMask == SWT.NONE){
                if(e.keyCode == fKeyCode){
                    fAction.run();
                }
            }
        }
    }

    [...]

    public void addKeyListener(int keyCode, int stateMask, Action action){
        fViewer.getControl().addKeyListener(new ViewerKeyAdapter(keyCode, modifier, action));
    }
}

Most of the time I spent on this was to realize that SWT.UP and SWT.ARROW_UP is not the same...


text:
Q: Does the spin of an atom affect the velocity of it? Does the spin of an atom affect the velocity of it?
If so, in layman terms, can someone explain to me why/how the spin of an atom can effect velocity.

A: In case of an isolated atom - or molecule for that matter - the answer is no, since there is no force acting on the spin. However, if you introduce an external force, for instance inhomogeneous electric or magnetic fields, one can change the velocity of an atom or molecule flying through such a field. The best known example is the Stern-Gerlach experiment in which silver atoms were deflected (the orthogonal velocity component changes) by inhomogeneous magnetic fields.
In general, the force acting on a particle is given by
$$ F=-\frac{dW}{dr}$$
where $W$ is the internal energy of the particle (in some field) and $r$ is the coordinate vector.
If you have a particle that has an internal energy that depends on (the orientation of) its spin, such as the Zeeman effect we can rewrite the above equation as follows (in case of a magnetic field $B$)
$$ F =-\frac{dW}{dB}\frac{dB}{dr}$$
Implying that the field has to be inhomogeneous ($dB/dr\neq0$) to change the velocity of the particle.

A: Please allow me a little leeway here. An atom is made up of different parts: electrons, neutrons and protons, as you know, so let me describe one of those parts first and then come back to the atom in a later question, as it is too complicated to describe the spin of an atom unless you follow the way the parts of the atom works first.
I would take the electron first.
In layman terms, this is the basic idea. The spin of an electron does not affect it's speed  in any way, but it can affect its direction of travel, if we put it in a magnetic field,  because an electron itself  is a tiny magnet.
I will stick to the intrinsic spin of an electron, the spin around its own axis, rather than the revolution of the electron around the atom, as I think it is the former point you are interested in.
Now comes the hard part, (as you have to give up every bit of common sense you might have, I am sorry about that).
You are asking about the quantum world, which has a different set of rules  from the classical world that we live in, so do not expect any of your assumptions to be applicable. Trying to apply common sense and classical rules to the quantum world, is like trying to play American football using baseball rules, it won't make sense most of the time.
One example of this is to ask you to forget everything I said about revolution and the axis in the paragraph above.
An electron does not spin as a soccer ball, it might be dimensionless, (that is a point particle), it does not have an axis and it takes two "revolutions" to get back to its orginal position, not like a soccer ball which takes 1 360 degree  revolution.
Because of that, the word spin will always make you think of a tiny ball, so I will call it spinlike from now on.
So why do we use the word spin? Because in the 1920s, we discovered that the electron had a bit more energy that we could explain, so we totally imagined that it was a tiny ball, and the extra energy came from its spinning around this axis.
An electron  only has two directions of spinlike.  In the 3 D world that we live in, this makes no sense, but the electron is a quantum particle,  it does not play by classical rules.
We say it has spinlike up, or it has spinlike down, again forget the ball idea, the words up and down are just used to distinguish the state it is in, either spinlike up or spinlike down. The amount of spinlike an electon has always stays the same, we can change its spinlike direction by magnetic fields,  but we cannot make it spinlike any faster or slower than the amount of spinlike it has.
We don't know exactly what an electron "is", we only know it's properties,  what it can do and what it can't do.
We don't even know where the electron will be at a given time, we can only say it will probably be in a certain position, so ideas like velocity are not really applicable, but they are so handy that we use them.


text:
Q: Trying to write a foreach argument for a drupal7 cck field I am using Drupal 7 and the jQuery and the Cycle2 feature. I followed the example code on this page.
http://jquery.malsup.com/cycle2/demo/basic.php
The code looks like this:

I created a Drupal cck multiple photo upload field called 'field_slider_photo'. And in my node template I wrote this.

<?php print render($content['field_slider_photo']); ?>

But this will display all photos all at once. I want them to play in the slideshow one at a time. Do I need to use an array or a foreach argument ?
I want to end up with something like this as an example:

<?php print render($content['field_slider_photo']); ?>Array1
<?php print render($content['field_slider_photo']); ?>Array2
<?php print render($content['field_slider_photo']); ?>Array3

I got it working but is there a better way to write this?

<?php print render($content['field_slider_photo'][0]); ?>
<?php print render($content['field_slider_photo'][1]); ?>
<?php print render($content['field_slider_photo'][2]); ?>
<?php print render($content['field_slider_photo'][3]); ?>

A: You're close, give this a whirl.

  <?php foreach($content['field_slider_photo']['#items'] as $img): ?>
    <img src="<?php print file_create_url($img['uri']);?>">
  <?php endforeach; ?>


text:
Q: How the standard input output operation done in C++ I have this code.
int main() {

int x;
cin>>x;
cout<<x<<endl;
char ch;
cin>>ch;
cout<<ch<<endl;
cin>>x;
cout<<x<<endl;
return 0;

}

if I give input R495 at first time then the output shows
0
0
Can anyone explain me why happened this. And why the console does not wait for me to enter other input.

A: After the wrong input, state of i/o stream is changed to a failed state.
Without clearing it, you will get the wrong input.
You can check if it is in a failed state with cin.fail().
...
cin>>x;
cout<<x<<endl;
-----------------
if (cin.fail())
{
  cout<<"Failed state"<<endl;
}else{
  cout<<"Good state"<<endl;
}
...

More info here std::ios::fail

A: int x;
cin>>x;

This is the first part. Here you said, that user will input x, but x will be Integer. Integer is whole number. So you need to enter a number.
char ch;
cin>>ch;

Here you said that user will input ch, but type of ch is Character. This means that you need to enter character for this to work (you can also enter integer here, which then will be mapped to ASCII value etc).


text:
Q: Motivation for definition of essentially bounded A function $f:(X,S,\mu)$ is said to be essentially bounded if $\Vert f\Vert_\infty$ is finite where, $$\Vert f\Vert_\infty:=\inf\{M:\mu(x:|f(x)|>M)=0\}$$
I would like to know why $\Vert f\Vert_\infty$ is defined the way it is?
My understanding is the following:
To say a function is essentially bounded means to say it is almost equal to a bounded function. So the set where the function is unbounded is a set of measure zero. The goal now would ideally be to find a bound for the function at the remaining points. So if $A$ is the set where $f$ is unbounded then ideally, $$\Vert f\Vert_\infty=\sup\{|f(x)|: x\in A\}=\inf\{M:|f(x)|\leq M, \forall x\in A\}.$$
To me this seems like a more natural way to define $\Vert f\Vert_\infty$. Is this equivalent to the actual definition?

A: It's not clear to me how you are defining $A$.
The definition of essentially bounded I prefer requires that $f$ is equal to some bounded function off a set of measure zero. This happens to be equivalent to finiteness of $||f||_{\infty}.$ This is because $||f||_{\infty}$ is finite if and only if $$\{M:\mu(x:|f(x)|>M)=0\}$$ is nonempty, if and only if there is some $M$ such that $$\mu(x:|f(x)|>M)=0,$$
if and only if $f$ is equal to some bounded function almost everywhere.

A: In estimating integrals, we often want to make the estimate $|f(x)| \leq M$ for a.e. $x$. The inf of constants $M$ that work is called $\|f\|_{\infty}$. You can show that this inf is actually attained.


text:
Q: Group and average array values based on index I have a two-dimensional array that contains strings and integers.
In GAS I want to create a new array that averages the integers of arrays that have common strings.
I've looked for solutions, but the majority of what I found was on ES6 which is not supported in GAS, and the rest I couldn't adapt to my case.
I tried to use map, reduce and filter but I couldn't find a proper solution.
Below is an example of the array and the desired output.
function myfunction(){

var array = [
["House1", 1.0, 2.0, 5.0, 1.0],
["House1", 1.0, 4.0, 2.0, 3.0],
["House2", 2.0, 3.0, 3.0, 4.0],
["House2", 5.0, 4.0, 3.0, 4.0],
["House2", 4.0, 5.0, 2.0, 2.0],
["House3", 2.0, 1.0, 4.0, 5.0]]
}

//Desired output

var newArray = [
["House1", 1.0, 3.0, 3.5, 2.0],
["House2", 3.6, 4.0, 2.6, 3.3],
["House3", 2.0, 1.0, 4.0, 5.0]
]

A:

let array = [
  ["House1", 1.0, 2.0, 5.0, 1.0],
  ["House1", 1.0, 4.0, 2.0, 3.0],
  ["House2", 2.0, 3.0, 3.0, 4.0],
  ["House2", 5.0, 4.0, 3.0, 4.0],
  ["House2", 4.0, 5.0, 2.0, 2.0],
  ["House3", 2.0, 1.0, 4.0, 5.0]];

let averageArrays = arrays =>
    arrays.reduce((sum, a) => {
      a.forEach((v, i) => sum[i] = (sum[i] || 0) + v / arrays.length);
      return sum;
    }, []);

let grouped = array.reduce((acc, a) => {
  acc[a[0]] = acc[a[0]] || [];
  acc[a[0]].push(a.slice(1));
  return acc;
}, {});

let averages = Object.entries(grouped).map(([name, arrays]) => [name, ...averageArrays(arrays)]);

console.log(averages);

A: You could take a hash table for same groups and get the averages by storing the sums and the count.
The result is an array of averages for every group.

function buildAverages(array) {
    var hash = {},
        result = [],
        i, j, item, key;

    for (i = 0; i < array.length; i++) {
        item = array[i];
        key = item[0];
        if (!hash[key]) {
            hash[key] = { avg: array[i].slice(), sums: array[i].slice(), count: 1 };
            result.push(hash[key].avg);
            continue;
        }
        hash[key].count++;
        for (j = 1; j < item.length; j++) {
            hash[key].sums[j] += item[j];
            hash[key].avg[j] = (hash[key].sums[j] / hash[key].count);
        }
    }
    return result;
}

var array = [["House1", 1.0, 2.0, 5.0, 1.0], ["House1", 1.0, 4.0, 2.0, 3.0], ["House2", 2.0, 3.0, 3.0, 4.0], ["House2", 5.0, 4.0, 3.0, 4.0], ["House2", 4.0, 5.0, 2.0, 2.0], ["House3", 2.0, 1.0, 4.0, 5.0]]

console.log(buildAverages(array));
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: The code below was tested in GAS environment.
function myFunction() {
  var array = [
    ["House1", 1.0, 2.0, 5.0, 1.0],
    ["House1", 1.0, 4.0, 2.0, 3.0],
    ["House2", 2.0, 3.0, 3.0, 4.0],
    ["House2", 5.0, 4.0, 3.0, 4.0],
    ["House2", 4.0, 5.0, 2.0, 2.0],
    ["House3", 2.0, 1.0, 4.0, 5.0]
  ];

  var avg = {}, count = {};
  array.forEach(function(a) {
    var key = a.shift();
    if (avg[key]) {
      for (var i = 0; i < 4; i++) {
        avg[key][i] += a[i];
      }
      count[key]++;
    } else {
      avg[key] = a;
      count[key] = 1;
    }
  });

  var result = [];
  for (var key in avg) {
    for (var i = 0; i < 4; i++) {
      avg[key][i] /= count[key];
    }
    avg[key].unshift(key);
    result.push(avg[key]);
  }

  Logger.log(result);
}

May be, it is long, but each step is clear. We accumulate intermediate results in avg and count objects, which are converted to the result array as desired.

A: Create a grouped object of arrays for each house. Take each group object and Sum them and then average them individually for each object.

function groupByAndAvg(array) {
  var out = {};
  array.forEach(function(row) {
    var house = row[0];
    out[house] = out[house] || [];
    out[house].push(row);
  });
  return Object.keys(out).map(function(thisHouse) {
    var house = out[thisHouse];
    var l = house.length;
    var sumHouse = house.reduce(function(acc, row) {
      return acc.map(function(e, i) {
        return typeof e === 'number' ? e + row[i] : e;
      });
    }, house.pop());
    return sumHouse.map(function(e) {
      return typeof e === 'number' ? e / l : e;
    });
  });
}
var array = [
  ['House1', 1.0, 2.0, 5.0, 1.0],
  ['House1', 1.0, 4.0, 2.0, 3.0],
  ['House2', 2.0, 3.0, 3.0, 4.0],
  ['House2', 5.0, 4.0, 3.0, 4.0],
  ['House2', 4.0, 5.0, 2.0, 2.0],
  ['House3', 2.0, 1.0, 4.0, 5.0],
];
console.info(groupByAndAvg(array));


text:
Q: Plotting a data set I have data set like this (x , y , n) n is the number from 0 to 12 I want to plot this data set but I want to the color of each point be base on the third column. For example if I have 0 in third column get red point on my graph and for 2  get blue and so far.

A: I assume your data consist of triplets: {x,y,color}. For an example, we create some data:
SeedRandom[10];
dat = RandomInteger[{0, 12}, {20, 3}];

We use ListPlot to display the data and color the points using ColorFunction. As ColorFunction only receive {x,y}, we need to look up the third element of the triple:
SeedRandom[10];
dat = RandomInteger[{0, 12}, {20, 3}];
ListPlot[dat[[All, 1 ;; 2]],
 ColorFunction -> (Hue[Cases[N@dat, {#1, #2, _}][[1, 3]]/12] &),
 ColorFunctionScaling -> False]

A: The data points in the x- and y-axes.
x = {1, 2, 3, 4};
y = {1, 2, 3, 4};

Create the list to be plotted
z = Thread[{x, y}]

One way:
ListPlot[{#} & /@ z, PlotStyle -> list2]

A second way:
ListPlot[{{Style[z[[1]], Green]}, {Style[z[[2]], Purple]}, {Style[
    z[[3]], Red]}}, PlotStyle -> PointSize[0.02]]

A third way:
Graphics[Prepend[Riffle[list2, Point /@ list1], PointSize[0.03]],
 Frame -> True]


text:
Q: Stop worker role instance from Windows Azure Management Portal There is probably an easy solution to this, but my searching has been unable to find it.
In my Azure solution, I have a worker role with two instances that are pulling messages off a queue for processing. For debugging purposes, I want to temporarily stop those instances.
If I click on Cloud Services, and then click Instances, I see my two instances which are running, but there doesn't appear to be any way to pause/stop/turn them off. Any ideas as to how I can?

A:
there doesn't appear to be any way to pause/stop/turn them off

You're correct in your observation because you can't pause/stop/turn off a specific instance. You could stop or turn off an entire cloud service but not an individual instance. You could however delete a particular instance but that's not something you have in mind if I understand correctly.

Any ideas as to how I can?

Do take a look at this blog post: http://alexandrebrisebois.wordpress.com/2013/09/29/temporarily-taking-a-cloud-service-role-instances-off-of-the-load-balancer/. Basically the trick is to make an instance Busy so that Azure load balancer does not send request to that instance.


text:
Q: Spring boot WebLogic 12c Jndi Datasource I'm deploying a Spring boot application on WebLogic 12c.
Without Jndi datasource all works fine.
I tried to configure on WebLogic a datasource with name "jdbc/MyDataSource" and on my application I setted the propertie like that:
spring.datasource.jndi-name=jdbc/MyDataSource

But, when I deploy my web app I receive the following error:

weblogic.application.ModuleException:
  javax.naming.NameNotFoundException: While trying to lookup
  'jdbc.MyDataSource' didn't find subcontext 'jdbc'. Resolved '';
  remaining name 'jdbc/MyDataSource'

I tried also the following properties configuration without success:
spring.datasource.jndi-name=java:comp/env/jdbc/MyDataSource

spring.datasource.jndi-name=java:/jdbc/MyDataSource

spring.datasource.jndi-name=java:jdbc/MyDataSource

My maven configuration:
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.2.RELEASE</version>
    <relativePath />
</parent>

My Spring App Configuration:
@EnableSwagger2

@ComponentScan({ "com.ws.repository", "com.ws.service", "com.ws.controller" })

@EntityScan("com.ws.entity")

@EnableJpaRepositories(basePackages = "com.ws.repository")

public class MyServiceApplication {
...
}

Expected:
I want to use the same jndi datasource because I want to deploy many services that use just one datasource

A: I solved modifying the servers destination (all, including AdminServer) of the datasource and saving the configuration

A: Try the default DataSource, and set the lookup name(java:comp/DefaultDataSource), and check if it works.
I have an example using Spring with Wildfly, all JNDI names(Datasource, JMS, Java Mail, EntityManagerFactory, etc) are working well.


text:
Q: MODX Revo считать и сохранить значение из базы MODX только начал изучать, не ругайтесь. Нужно увеличить счетчик на 1. Сделал числовое доп. поле countOfShow, читаю данные в чанке так: [[+tv.countOfShow]], пятёрочка видится. Я так понимаю, нужно вызвать сниппет
[[!IncCountOfShow? &docid=`[[+id]]`]]

Нужно просто увеличить значение на 1 и сохранить.
Так не получается
<?php
if(isset($_GET['docid'])){
    $user = $modx->getObject('modTemplateVarResource',['contentid'=>$_GET['docid']]);
    $count = $user->get('countOfShow');
    $count++;
    $user->save();
}

A: Вы не задали новое значение перед сохранением: $user->set();
Прочитайте курс по работе с xPDO, многие вопросы отойдут - https://ilyaut.ru/xpdo/

A: Вот так правильно:
<?php
if ($tv=$modx->getObject('modTemplateVarResource', array('tmplvarid' => 16, 'contentid' => $docid))) {
$count = $tv->get('value');
$count++;
$tv->set('value', $count);
$tv->save();
}


text:
Q: Is there any way to switch off the display and switch it back on explicitly? I turn off my display using nircommand which uses Window's default switch off monitor function. The problem with this is that, the display turns on when I move my mouse or type something in the keyboard(like controlling spotify).
I need to shut down the monitor and not have it turn itself on on an event, is there any way to do that?

A: Since you are using Windows 7, you could try switching the display with Win+P to a position in which it would redirect all to the external display.
More directly, you could make a shortcut to the program which is called by this shortcut:
Switch to External (and black out the main screen)
%windir%\System32\DisplaySwitch.exe /external

Switch back to the main screen
%windir%\System32\DisplaySwitch.exe /internal

Of course, this would work only if you don't actually have an external display plugged.

A: Of course, if anything else fails on the software side, there's always the "hardware" solution:

One button, switch on and off the display, and it's not out of reach.

A: You can do this with C#. Personally if I were doing this, I would write a small executable in C# that simply takes an argument for which action it will perform and then write a wrapper in autoit that monitors for whatever criteria it needs to take any action using that executable.


text:
Q: Concept and meaning of immersion Who can explain concept and meaning of "Immersion" maps, very easy and useful? thanks for advanced.

A: Let $ M $ and $ N $ be two manifolds and suppose $ \dim M \leq \dim N $. An immersion of $ M $ into $ N $ is a smooth map $ f: M \rightarrow N $ such that its differential map $ df_p: T_p(M)\rightarrow T_f(p)(N) $ is injective for every point $ p \in M $. Note that $ f $ is not injective in general. If an immersion $ f $ is also an homeomorphism onto its image, then it is called embedding. On the other hand you can find this answer in any basic book of differential geometry, so i don't know if this answer is what you are looking for.


text:
Q: How can stop mediaPlayer which is already running ,and create new mediaPlayer? I am working in android. I am creating a mediaPlayer which is running audio files. i have 10 buttons. i have assigned different url to each button. So when i  press button1 then song of url with respect to button 1 is playing. and then i click on 2nd button then song of button 2 is also playing with song 1. but i want to stop song of button 1 when i press button 2.
this is the code i am using for this functionality:-
  public void onClick(View v)
 {

        MediaPlayer mediaPlayer=new MediaPlayer();

        if (mediaPlayer.isPlaying())
        {
            mediaPlayer.stop();
            mediaPlayer.release();

        }

        int i = Integer.parseInt((v.getTag()).toString());
        String str=urls[i];
        try {

                mediaPlayer.setDataSource(str);
        mediaPlayer.prepare();
        mediaPlayer.start();

         } catch (Exception e)
               {
                e.printStackTrace();
        }

    }

please check my code and let me know what is mistake done by me.

A: you have construct a  new MediaPlayer object each time the user click you view
how could it be in the running state  !!!
calling release() method on a MediaPlayer object it is in thre End state
Once the MediaPlayer object is in the End state, it can no longer be used and there is no way to bring it back to any other state.
but in case you want to reuse a MediaPlayer object you should call the
call the following method in the same order
reset()
make the mediaPlayer enter the Idle state
setDataSource()
 set your data source note : the mediaplayer shoud be in the idle state
prepare()
start()


text:
Q: Interpretation of interaction variable when base variable is insignificant I am investigating the effect of Indian service imports on U.S. service employment, using a balanced panel data set. The employment data are state-level for 5 different business service sectors. In this research the dependent variable is U.S. business service employment. The independent variables are: Indian service imports, Skill intensity within business service sectors(measured in average years of education), Real GDP and an interaction variable IMPORT*Skill. The purpose of this interaction variable is to measure whether the effect of Indian business services is larger in sectors that are more skill intensive. Logs are used to ease the interpretation of results. Furthermore, not all variables were found to be stationary, which is why the first difference is taken of each variable. A dummy for each year has been used to add a time effect.
The results show that there is no significant relationship between Indian service Imports and U.S. business service employment and that there is a significant positive relationship between Skill and business service employment. Furthermore, the interaction variable is found to be significantly negatively related with employment.
The regression I used is:
xtreg DIFvalue DIFimp DIFskill DIFgdp DIFimpXskill dummy1 dummy2 dummy3 dummy4 dummy5 dummy6 dummy7 dummy8 dummy9 dummy10 dummy11 dummy12 dummy13 dummy14 dummy15 dummy16, fe vce (cluster cn_ind)

The output is as following:
R-sq:               Obs per group:
within  =   0.2501  min =         14
between =   0.5817  avg =       14.0
overall =   0.2011  max =         14
F(15,249)         =          .
corr(u_i, Xb)   = 0.0045    Prob > F          =          .

(Std. Err. adjusted for 250 clusters in cn_ind)

DIFvalue         Coef.     Std. Err.   t       P>t     [95% Conf. Interval]

DIFimp         .045624    .0393354     1.16   0.247    -.0318485    .1230965
DIFskill       8.36e-10   3.32e-10     2.51   0.013     1.81e-10    1.49e-09
DIFgdp        -.0016054   .0273678     -0.06  0.953    -.0555073    .0522965
DIFimpXskill  -.0003645   .0001315     -2.77  0.006    -.0006236   -.0001055

My question is, How do I interpret the interaction variable? Indian imports(DIFimp) are not significantly related with U.S. employment(DIFvalue) and Skill(DIFskill) is positively related with U.S. employment. The interaction variable is negatively related with employment. So does this still mean that as the skill within a sector is higher, that the effect of Indian imports on employment is lower? Or is this impossible as the effect of Indian imports on employment is insignificant?
Could anyone help me with this interpretation?

A: You should use Stata's factor notation and margins command to interpret the interaction. Assuming your two variables (DIFimp and DIFskill) are continuous  you could rewrite your model as:
xtreg DIFvalue c.DIFimp##c.DIFskill c.DIFgdp i.year, fe vce (cluster cn_ind)

Then, you can use the margins command to compute predicted values for various values of the two independent variables. Let us assume both variables have a range from 1 to 10, you can use this code:
margins, at(DIFimp=(1 5 10) DIFskill=(1(1)10))
marginsplot

This will create a plot with three lines showing you the expected value of DIFvalue for each value of DIFskill. The three lines show you how the predicted values differ between the three levels of DIFimp.
You should refrain from interpreting the interaction by looking at each coefficient in isolation. The coefficients of DIFimp and DIFskill only display the effect of these variable when the other variable equals zero. This might not be a plausible value. Even if it is, it is only one part of the interaction.
Hope this helps.


text:
Q: Scrape 'deep' audio features using Spotipy python library For the past few days, I've been using the excellent Spotipy python library for the Spotify Web API. Having navigated my way to accessing the basic information, however (track/artist/album names, urls, uris, etc), I'm now trying to find some deeper track features (BPM, tempo, etc).
I know that Spotify makes this information publicly available because some enterprising services have already integrated these into their offerings. My question is, is there any way to access this sort of information through the spotipy.Spotify() object or is it simply not attainable as of the latest spotipy release (v2.3.8)?
Any assistance would be greatly appreciated!

A: That link is not an enterprising service, it is part of the examples for the Echo nest parts of the Spotify Web API.
https://developer.spotify.com/web-api/code-examples/#echo-nest-example-apps
https://github.com/plamere/SortYourMusic
What might be confusing is that the attributes are not available on the track object, but you need to call a new method called audio_features.
https://developer.spotify.com/web-api/get-several-audio-features/
http://spotipy.readthedocs.io/en/latest/#spotipy.client.Spotify.audio_features
This worked for me:
import spotipy
import spotipy.oauth2

credentials = spotipy.oauth2.SpotifyClientCredentials()
spotify = spotipy.Spotify(client_credentials_manager=credentials)
print spotify.audio_features(['4uLU6hMCjMI75M1A2tKUQC'])


text:
Q: Multiple Conditional statements in LINQ Is this possible to do in LINQ, this wouldn;t compile however this is the result am trying to achieve.
I know I can filter this prior to union statement, curious to know if this is supported or not.
var _tickers = (from _position in positions_
                      where _position.Ticker_PositionQuote.PropertyValue != string.Empty
                      select _position.Ticker_PositionQuote.PropertyValue)
        .Union(
          from _position in positions_
          where _position.AssetClassLevel2.PropertyValue.ToUpper() == "EQUITY OPTIONS"
          and _position.Ticker_PositionUnderlyerQuote.PropertyValue != string.Empty
          select _position.Ticker_PositionUnderlyerQuote.PropertyValue);

Thanks,
Raul Dsouza

A: If I understand your question correctly, you are looking for a way to implement this "and" statement. Please correct me if I am wrong.
To get the result of
from item in collection
where condition1 "and" condition2

you can use either
from item in collection
where condition1 && condition2

or
from item in collection
where condition1
where condition2

The first method will probably be faster.