text:
Q: AWS Mobile Push Notification by Example I'm trying to wrap my head around how AWS Mobile Push Notification works. Specifically I'm building out a web service that will be capable of sending notifications to my mobile app running on my users' devices. After reading all of their docs, it sounds like the high level flow is:

*

*Configuration

*

*I need to go into my respective Push Notification Services (GCM for Android and APNS for iOS) and configure them to get credentials that I configure my backend service to use for connecting to them at runtime

*I need to log in to the AWS SNS console and generated a platform application ARN (PlatformApplicationARN) that I also configure my backend to use

*Code Flow (Runtime)

*

*When a new user signs up for the first time, or anytime an existing user signs in on a new device, I have the app send my service their device info. One critical piece of this device info is their device token (also referred to as a "registration ID" in the AWS docs). This token is generated by their OS and uniquely identifies their device within their respective Push Notification Services (again either GCM or APNS for me)

*When my service receives this new device info, I save it, and I also use the device token to hit the AWS SNS API (along with my configured PlatformApplicationARN) to generate a unique EndpointARN for that particular device

*Now, whenever my backend decides it needs to send a notification to that user, I can look up all the devices associated with that user (that I previously stored in my DB), and fetch each device's EndpointARN. Then its just a matter of hitting the AWS SNS API to send my notification message to that EndpointARN, and it sounds like AWS SNS will take care of everything else (and delivering the actual message to the device)

So before I go any further, I'm just looking for someone to help sanity check my understanding and provide any course correction if I've misunderstood anything or am missing any important pieces of the config/flow! Assuming I'm more or less on track...
I'm still not seeing how SNS will be able to connect to GCM and APNS once I send a notification message to an EndpointARN. Do they maintain their own integration/connection with these services? Or do I somehow inject my own GCM/APNS credentials into the AWS SNS API call somehow?
Also, I know push notifications can be fairly configurable, allowing you to do things like:

*

*Determine what sound the device should play when it receives a notification

*Determine what color LED to blink on/off when it receives a notification (on my Android phone, different apps cause green, blue even purple LEDs to blink!)

*Determine whether the notification is received by the Android/iOS OS itself (in which case if I come back to my phone after being away from it for a few minutes, I can press any button and see a high-level listed summary of any new notifications I've received); or whether the notification is purely an "in-app" notification in which case I'll only see that I received it if I actually open up my app.

I'm wondering where all this configuration takes place? Any ideas?

A: I can confirm that the high level flow is:

*

*Log into AWS SNS and create 2 different Platform Applications, 1 for Android (FCM -- Firebase Cloud Messaging) and the other for iOS (APNS -- Apple Push Notification Services)

*For each Platform Application you'll get a PlatformApplicationArn and you will be asked for credentials so that SNS can connect to your respective FCM/APNS accounts

*

*For FCM you will just need your Server API Key (this can be obtained from Firebase Cloud Manager)

*For APNS you will need to go through a really labor-intensive process of creating certificates through the Key Chain Access tool on your Mac, this was not fun...

*Add these 2 PlaformApplicationArns to your code's config

*When a user registers a new device with your app, they will send you a device token (provisioned by FCM or APNS) that uniquely identifies them to FCM/APNS

*Take this device token, combined with your PlatformApplicationArn for FCM or APNS and use the AWS SNS SDK to create an EndpointArn for the device. Store this EndpointArn however you like.

*Now you can use the AWS SNS SDK to push messages to your EndpointArn (specific device) anytime you want to.


text:
Q: How can I setup my .git/config to be able to push to / pull from multiple remote repositories? Ok, I have three different computers that I work from and right now their configurations are all different so I have to push/pull a certain on each and its very bothersome. What I want to do is have ONE config file that I can use for all three that will allow me to do the following:
git push unfuddle
git pull heroku
git push unfuddle
git pull heroku

And I'm new to git, so I know that maybe I need heroku master or 'heroku origin` or somethign?
Here is what my config file looks like right now:
[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
[remote "origin"]
    fetch = +refs/heads/*:refs/remotes/origin/*
    url = git@heroku.com:HEROKU-APP.git
[branch "master"]
    remote = origin
    merge = refs/heads/master
[remote "unfuddle"]
    fetch = +refs/heads/*:refs/remotes/origin/*
    url = git@UNFUDDLE-APP.unfuddle.com:UNFUDDLE-APP/UNFUDDLE-APP.git

Obviously the git urls were changed to protect the innocent. What should I change so that I can easily push and pull to/from both of these repos?

A: First of all, there are three levels of config files:

*

*config local to your current repo

*config local to your current user (home directory)

*config local to your system

You can define as many remote repo addresses you want, and you can do it at the user level, provided you synchronize that config file from destop to destop
git remote add origin1 git+ssh://remote.location/git/repository1.git
git remote add origin2 git+ssh://remote.location/git/repository2.git
git remote add origin3 git+ssh://remote.location/git/repository3.git

If those commands add the remote addresses only in your current repo config file, you can manually move those to your current user config file.
But on each repo, you need to define your remote tracking branch for the right repo:
git branch --set-upstream master origin1/master

(from Git1.7.0, quicker than the two git config branch you had to do before)
So if you have the right synchronization mechanism (like dropbox for instance) for your user config file, you are all set.

redpajama_set_name: RedPajamaStackExchange


text:
Q: WooCommerce authorization issue so, recently i was tryin to integrate my WooCommerce with DSers dropshipping platform... but with no success.
I always have this not found error on woocommerce auth webpath.
screenshot
here is my nginx vhost conf
server {
root /srv;
index index.php index.html index.htm index.nginx-debian.html;

server_name example.com;
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.4-fpm.sock;
}
location ~ /\.ht {
deny all;
}
location ~ ^/wp-json {
rewrite ^/wp-json(.*?)$ /?rest_route=/$1 last;
}

}
perhaps its the rewrite rule?


text:
Q: Python + MySQL: Search function returning all entries I'm putting together an inventory program using Python and MySQL. I want to implement a search function that returns entries based on user input (programmed in a separate GUI file). In the code below, I expected that the search function would return entries with the brand "UGreen". Instead, it returns all of the entries in the table.
I'm not sure what I'm doing wrong here. I have used a similar structure in another program with a sqlite database instead and the search worked fine.
Any and all help/suggestions would be greatly appreciated :)
import mysql.connector

equipdb = mysql.connector.connect(
    host = "localhost",
    user = "root",
    password = "REDACTED",
    database = "tel_inventory"
)

def view():
    cur = equipdb.cursor()
    cur.execute("SELECT * FROM equipment")
    result = cur.fetchall()
    return result

def search(name="", brand="", model="", consumables="", storage="", room="", photo=""):
    cur = equipdb.cursor()
    cur.execute("SELECT * FROM equipment WHERE name=%s OR brand=%s OR model=%s OR consumables=%s OR storage=%s OR room=%s OR photo=%s", (name, brand, model, consumables, storage, room, photo))
    result = cur.fetchall()
    return result

#print(view())
print(search(brand="UGreen"))

A: Try using keyword argument directly
def search(**kwargs):
    cur = equipdb.cursor()
    key = str(list(kwargs.keys())[0])
    value = str(kwargs[key])
    cur.execute('SELECT * FROM equipment WHERE {} = "{}"'.format(key,value))
    result = cur.fetchall()
    return result


text:
Q: how to disable wildcard subdomain in ubuntu 18.04 for localhost Hello and thank you your time, I have Xampp 7.2.29 installed and it's working fine
but i don't know why i can access any wildcard subdomain in localhost even i don't have created any in host file.
when i go to
new.localhost it returns xampp dashboard and same goes for any subdomain *.localhost
host file
#127.0.0.1 localhost

# The following lines are desirable for IPv6 capable hosts
#::1     ip6-localhost ip6-loopback
#fe00::0 ip6-localnet
#ff00::0 ip6-mcastprefix
#ff02::1 ip6-allnodes
#ff02::2 ip6-allrouters

A: .localhost is a Top-level domain - reserved domain, so foo.localhost or bar.localhost, etc. always resolve to the same ip, 127.0.0.1, which in this case is used for Xampp.


text:
Q: using if-else statements in React JSX I'm trying to display react component based on what the pair name is, but I am not sure how to get that to happen. This is the code I have so far, any suggestions?
class App extends React.Component {
  state = {
    bases: ['EUR', 'AUD', 'CAD', 'JPY', 'NZD'],
    selectedBase: 'USD',
  };

  displayGraph = () => {
    if(document.getElementById('pairName').innerText === 'USD/EUR'){
      <Graph defaultBase={"EUR"} />
    } else if (document.getElementById('pairName').innerText === 'USD/CAD'){
      <Graph defaultBase={"CAD"} />
    } else if(document.getElementById('pairName').innerText === 'USD/AUD'){
      <Graph defaultBase={"NZD"}/>
    } else if(document.getElementById('pairName').innerText === 'USD/NZD'){
      <Graph defaultBase={"AUD"}/>
    } else if (document.getElementById('pairName').innerText === 'USD/JPY') {
      <Graph defaultBase={"JPY"}/>
    }
  }

  render(){
    return (

USD/EUR

          {/* GOAL: show graphs when correct pairs are selected */}

          {this.displayGraph}

  }
}

export default App;

A: In your code I think you are missing return before the <Graph... />.
However another way you could do this could also be like this:
class App extends React.Component {
  state = {
    bases: ['EUR', 'AUD', 'CAD', 'JPY', 'NZD'],
    selectedBase: 'USD',
  };

  displayGraph = () => {
    switch(document.getElementById('pairName').innerText) {
    case 'USD/EUR':
        return <Graph defaultBase={"EUR"} />;
    case 'USD/CAD':
        return <Graph defaultBase={"CAD"} />;
    case 'USD/AUD':
        return <Graph defaultBase={"NZD"}/>;
    case 'USD/NZD':
        return <Graph defaultBase={"AUD"}/>;
    case 'USD/JPY':
        return <Graph defaultBase={"JPY"}/>;
  }

  render(){
    return (

USD/EUR

          {this.displayGraph}

  }
}

export default App;

P.s. As a side note, I would look at converting the React class to a function and using the useState hook as it is the newer way of writing react code. You can read more about it here.


text:
Q: Create new columns containing the rows of an existing column based on values in those rows I am working in Python with Pandas and have the following problem. I have a dataframe with a large number of rows depicting cryptocurrency data per date. After reaching the last date, a new time series is started for another cryptocurrency, all in the same columns. I am looking for a way to manipulate the dataframe so that for every token_date, all cryptocurrency data is shown in a single row, so that the total number of rows would equal the total number of token_date 's
Currently the df looks as follows:
token_id    token_caption   token_date  token_price_usd token_marketcap_usd
64          WAN Wanchain    2019-06-24  0.3817          40414601.0
64          WAN Wanchain    2019-07-01  0.3644          38683920.0
64          WAN Wanchain    2019-07-08  0.3557          37759781.0
64          WAN Wanchain    2019-07-15  0.2625          27824362.0
64          WAN Wanchain    2019-07-22  0.2545          27036722.0
...
57          MAID            2017-07-24  0.3775          170824959.0
57          MAID            2017-07-31  0.2917          132012254.0
57          MAID            2017-08-07  0.3589          162410652.0
57          MAID            2017-08-14  0.3763          170283706.0
57          MAID            2017-08-21  0.4615          208873303.0
...

I am looking for code to achieve something like this.: (The column split will be performed roughly 100 times, ending up with ca. 201 columns)
token_date   WAN Wanchain - Price   WAN Wanchain - Marketcap  ...  MAID - Price   MAID - Marketcap...
2019-06-24   0.3817                 40414601.0                     xxx            xxx
2019-07-01   0.3644                 38683920.0                     xxx            xxx
2019-07-08   0.3557                 37759781.0                     xxx            xxx
...

I would be thankful for any help. I am a total beginner regarding Python and have no concept on how to achieve this.
Thank you!

A: If you set the index to ['token_date', 'token_caption'] and unstack the caption to make it a column instead, you get a pretty clean MultiIndex column with what you're looking for:
In [144]: df
Out[144]:
   token_id token_caption  token_date  token_price_usd  token_marketcap_usd
0        64  WAN Wanchain  2019-06-24           0.3817           40414601.0
1        64  WAN Wanchain  2019-07-01           0.3644           38683920.0
2        64  WAN Wanchain  2019-07-08           0.3557           37759781.0
3        64  WAN Wanchain  2019-07-15           0.2625           27824362.0
4        64  WAN Wanchain  2019-07-22           0.2545           27036722.0
5        57          MAID  2019-06-24           0.3775          170824959.0
6        57          MAID  2019-07-01           0.2917          132012254.0
7        57          MAID  2019-07-08           0.3589          162410652.0
8        57          MAID  2019-07-15           0.3763          170283706.0
9        57          MAID  2019-07-22           0.4615          208873303.0

In [145]: df.set_index(["token_date", "token_caption"])[["token_price_usd", "token_marketcap_usd"]].unstack().swaplevel(axis=1)
Out[145]:
token_caption            MAID    WAN Wanchain                MAID        WAN Wanchain
              token_price_usd token_price_usd token_marketcap_usd token_marketcap_usd
token_date
2019-06-24             0.3775          0.3817         170824959.0          40414601.0
2019-07-01             0.2917          0.3644         132012254.0          38683920.0
2019-07-08             0.3589          0.3557         162410652.0          37759781.0
2019-07-15             0.3763          0.2625         170283706.0          27824362.0
2019-07-22             0.4615          0.2545         208873303.0          27036722.0

A: Why not use pivot:
Given data
token_id    token_caption   token_date  token_price_usd token_marketcap_usd
64          WAN_Wanchain    2019-06-24  0.3817          40414601.0
64          WAN_Wanchain    2019-07-01  0.3644          38683920.0
64          WAN_Wanchain    2019-07-08  0.3557          37759781.0
64          WAN_Wanchain    2019-07-15  0.2625          27824362.0
64          WAN_Wanchain    2019-07-22  0.2545          27036722.0
57          MAID            2019-06-24  0.3775          170824959.0
57          MAID            2019-07-01  0.2917          132012254.0
57          MAID            2019-07-08  0.3589          162410652.0
57          MAID            2019-07-15  0.3763          170283706.0
57          MAID            2019-07-22  0.4615          208873303.0

note I repeated the dates so there was something to match on
df.pivot("token_date", "token_caption", ["token_price_usd", "token_marketcap_usd"])

gives
              token_price_usd              token_marketcap_usd
token_caption            MAID WAN_Wanchain                MAID WAN_Wanchain
token_date
2019-06-24             0.3775       0.3817         170824959.0   40414601.0
2019-07-01             0.2917       0.3644         132012254.0   38683920.0
2019-07-08             0.3589       0.3557         162410652.0   37759781.0
2019-07-15             0.3763       0.2625         170283706.0   27824362.0
2019-07-22             0.4615       0.2545         208873303.0   27036722.0

A: I use pivot_table and construct the new column names:
df=df.pivot_table(index="token_date",columns="token_caption",values=["token_price_usd","token_marketcap_usd"])

token_marketcap_usd              token_price_usd
token_caption                MAID WAN Wanchain            MAID WAN Wanchain
token_date
2017-07-24            170824959.0          NaN          0.3775          NaN
2017-07-31            132012254.0          NaN          0.2917          NaN
2017-08-07            162410652.0          NaN          0.3589          NaN
2017-08-14            170283706.0          NaN          0.3763          NaN
2017-08-21            208873303.0          NaN          0.4615          NaN
2019-06-24                    NaN   40414601.0             NaN       0.3817
2019-07-01                    NaN   38683920.0             NaN       0.3644
2019-07-08                    NaN   37759781.0             NaN       0.3557
2019-07-15                    NaN   27824362.0             NaN       0.2625
2019-07-22                    NaN   27036722.0             NaN       0.2545

df.columns=[ lev2+" - "+lev1.split("_")[1].title() for lev1,lev2 in df.columns]
df.reindex(sorted(df.columns.values,reverse=True) ,axis=1)

            WAN Wanchain - Price  WAN Wanchain - Marketcap  MAID - Price  MAID - Marketcap
token_date
2017-07-24                   NaN                       NaN        0.3775       170824959.0
2017-07-31                   NaN                       NaN        0.2917       132012254.0
2017-08-07                   NaN                       NaN        0.3589       162410652.0
2017-08-14                   NaN                       NaN        0.3763       170283706.0
2017-08-21                   NaN                       NaN        0.4615       208873303.0
2019-06-24                0.3817                40414601.0           NaN               NaN
2019-07-01                0.3644                38683920.0           NaN               NaN
2019-07-08                0.3557                37759781.0           NaN               NaN
2019-07-15                0.2625                27824362.0           NaN               NaN
2019-07-22                0.2545                27036722.0           NaN               NaN

Finally you can apply 'reset_index'.


text:
Q: Accessing and updating Keyword in the Document Object I've a got a strange question, (at least I assume it's strange, I can't find anything like it online)
Essentially I'm looking to access the Keywords section of the Document object, I have a trigger that is started by a document being uploaded.
I read the content of the file to programmatically calculate the highest occurring words in the file (checked against a list of common words that are exempt).
So I used to the DocumentContentLink to let me read the body. Is there a means for me to insert the word(s) that I have gleaned into the Keyword?
The developer console only allows Select and Find so I can't figure out how to reach this value to insert anything.
I can see from the document docs that the keyword is selectable from here.
select name,body,authorID, keywords
from Document where id = '01541000001mo73'

If this is not reachable is there a way I can create a relationship between the calculated keywords and the file at least?
Anything at all would be a great help! I've been wracking my brains for this for a while. Thank you so much!

A: Works out for me
Id docId = '01563000000Dv9G'; // hardcoded doc ID
Document doc = [select name,body,authorID, keywords from Document where id=:docId];

System.debug(doc.keywords); // null
System.debug(doc.id); // 01563000000Dv9G

doc.keywords ='salesforce';
update doc;

Document updatedDoc = [select name,body,authorID, keywords from Document where id = :docId];

System.debug(updatedDoc.keywords); // output is "salesforce"


text:
Q: Relación uno a muchos Entity Framework c# estoy comenzando a utilizar este Framework. Tengo dos clases:
public class Pedido
    {
        public int PedidoId { get; set; }
        public int Estado { get; set; };
        public virtual ICollection<Producto> Productos { get; set; }
}

public class Producto
    {
        public int ProductoId { get; set; }
        public string Nombre { get; set; }
        public string Descripcion { get; set; }
        public string Tipo { get; set; }
        public float Precio { get; set; }
        public bool Cocina { get; set; }
        public byte[] Imagen { get; set; }

        public int PedidoId { get; set; }
        public virtual Pedido Pedido { get; set; }

    }

Lo que no entiendo muy bien es como manejarme a la hora de de almacenar Productos que no hagan referencia a ningun pedido, es decir, cuando son creados. Debo crear otra clase Productoque no este enlazada con Pedido?
Espero haberme explicado bien. Gracias


text:
Q: Property 'onDidDismiss' does not exist on type ionic 4 and Angular I am developing an app and I have the next class in TypeScript.
I want to try to get the data in a method of type callback in ´ModalController´ when it dismiss the modal:
import { Component, OnInit } from '@angular/core';
import {NavController, ModalController} from '@ionic/angular';
import { Router } from '@angular/router';
import { HomePage } from '../home/home.page';
import {AddItemPage} from '../add-item/add-item.page';

@Component({
  selector: 'app-todo',
  templateUrl: './todo.component.html',
  styleUrls: ['./todo.component.scss']
})

export class TodoComponent implements OnInit {

  public items;

  constructor(public navCtrl: NavController, public modalCtrl: ModalController) {
    this.ionViewDidLoad();
  }

  ngOnInit() {}

  async addItem()  {
    // Create a modal using MyModalComponent with some initial data
     const modal = await this.modalCtrl.create({
        component: AddItemPage,  componentProps: {
           'prop1': "cadena!!!!!!!"
        }
     }).then(function(modal) {
        return modal.present();
     });

     modal.onDidDismiss(() => {
        // Call the method to do whatever in your home.ts
        console.log('Modal closed');
    });
  }
}

I got this error:

core.js:15724 ERROR Error: Uncaught (in promise): TypeError: Cannot
  read property 'onDidDismiss' of undefinedTypeError: Cannot read
  property 'onDidDismiss' of undefine

A: How is related in this post:https://medium.com/@david.dalbusco/how-to-declare-and-use-modals-in-ionic-v4-4d3f42ac30a3
My error was just How I was creating the modal. I have followed this code to create my modal property.
async openModal() {
    const modal: HTMLIonModalElement =
       await this.modalController.create({
          component: DatePickerModal,
          componentProps: {
             aParameter: true,
             otherParameter: new Date()
          }
    });

    modal.onDidDismiss().then((detail: OverlayEventDetail) => {
       if (detail !== null) {
         console.log('The result:', detail.data);
       }
    });

    await modal.present();
}

A: Since you're using await to create the modal, you don't need to use the then like that.
Please try the following:
async addItem()  {

  // Create the modal
  const modal = await this.modalCtrl.create({
    component: AddItemPage,
    componentProps: {
      'prop1': "cadena!!!!!!!"
    }
  });

  // Present the modal
  return await modal.present();

  // Wait for the modal to be dismissed before continuing...
  const eventDetails = await modal.onDidDismiss();

  if (eventDetails) {
    console.log(eventDetails.data);
  }

  // ...

}

The code above assumes you're returning something when dismissing the modal, like this:
// Dismiss the modal returning some data object
modalController.dismiss({
  'result': 'This is the result returned by the modal!'
});

A: Try :
const modal = await modalController.create({...});
const { data } = await modal.onDidDismiss();
console.log(data);

As per official documentation .


text:
Q: I have vs I have one Suppose someone asks me "Do you have any sister? Which answer would be more appropriate?

Yes. I have.

Or

Yes. I have one.

If both one is correct then what is the difference between them?
Is the sentence "Yes, I have a sister "
uncommon?

A:
"Do you have any sisters?"

The question must use the plural. If it uses the singular it is a mistake which I would politely overlook and assume the question used the plural.
Then "Yes" means "I have at least one sister", and "Yes, I have a sister" means "I have one sister".
I won't say "I have one sister", when I also have two sisters, even if it is technically true.
So the difference is that the second answer includes the number of sisters. THe first answer does not.


text:
Q: how to install gems without sudo On all my gem installs I have to do sudo ? So

sudo gem install rails

will work, while only

gem install rails

will not work. How do I remedy it ?
I have rvm installed -
murtaza@murtaza-dev:~$ which rvm
/home/murtaza/.rvm/bin/rvm

murtaza@murtaza-dev:~$ which gem
/home/murtaza/.rvm/rubies/ruby-1.9.3-p194/bin/gem

However I am also getting this warning when I do any operations with gem -
murtaza@murtaza-dev:~$ gem
/home/murtaza/.rvm/rubies/ruby-1.9.3-p194/bin/gem:4: warning: Insecure world writable dir /opt in PATH, mode 040777

EDIT
I have reinstalled rvm using curl -L get.rvm.io | bash -s stable --auto (without sudo).
However still when I try installing gem it gives me the following error -
murtaza@murtaza-dev:~$ gem install rails
/home/murtaza/.rvm/rubies/ruby-1.9.3-p194/bin/gem:4: warning: Insecure world writable dir /opt in PATH, mode 040777
ERROR:  While executing gem ... (Errno::EACCES)
    Permission denied - /home/murtaza/.gem/specs

EDIT
I did chown on the whole thing but still getting the error -
murtaza@murtaza-dev:~$ sudo chown murtaza.murtaza -R ~/.rvm/*

 murtaza@murtaza-dev:~$ gem install rails
    /home/murtaza/.rvm/rubies/ruby-1.9.3-p194/bin/gem:4: warning: Insecure world writable dir /opt in PATH, mode 040777
    ERROR:  While executing gem ... (Errno::EACCES)
        Permission denied - /home/murtaza/.gem/specs

A: You should install Ruby Version Manager. It stores installed rubies and gems in your home dir, so now you don't have to use sudo to install gems. It has a lot more features besides this. :)

A: Use chown on the whole .rvm and .gem directories back to your user. You probably used sudo before and it screwed up permissions.
sudo chown -R username:group ~/.rvm
sudo chown -R username:group ~/.gem

Of course, change username to your username and group to your group

A: I resolved my issue in the following way: (I have ubuntu 17.10)
Open terminal and type:
echo "gem: --user-install" >> ~/.gemrc

Then add ruby's bin path in .bashrc file
export PATH="$PATH:$HOME/.gem/ruby/x.x.x/bin"

A: MacOS
brew install ruby

edit   ~/.zshrc  for  zsh (for Bash could be something like ~/.bash_aliases)
# By default, binaries installed by gem will be placed into:
# /usr/local/lib/ruby/gems/2.6.0/bin
export GEM_HOME="/usr/local/lib/ruby/gems/"
export PATH="$GEM_HOME/bin:$PATH"

A: When you install them without sudo, Ruby doesn't know where they get installed to. I can't remember where it installs them by default, probably somewhere like ~/.gems or something. Anyway, you can tell Ruby that's where they're installed by setting the GEM_HOME environment variable.
$ # assuming your gems are stored in ~/.gems
$ GEM_HOME="$HOME/.gems" ruby my_program.rb

If that works, then you might put it in your ~/.bashrc (there are a number of possible files this could go in, depending on your system)

A: For Mac users, this works for me...

*

*Add GEM_HOME to your .bash_profile
For example, nano ~/.bash_profile and add export GEM_HOME=$HOME/.gem where the path is to your own Home folder

*Add the gem executables to your system path

Also in .bash_profile, add export PATH="$GEM_HOME/bin:$PATH"
Source: http://michaelehead.com/2016/02/06/installing-gems-without-sudo.html

A: try gem install package --install-dir $HOME/.gem.
Don't forget setting the path as it was mentioned before export PATH="$PATH:$HOME/.gem/bin".
Something you have to consider is changing the PATH order like export PATH="$HOME/.gem/bin:$PATH". It might happen for example if you are trying to install rails into your local directory on a OS X system but there is an executable alredy built in. In this case if you don't change the path order you will also receive the following output:

Rails is not currently installed on this system. To get the latest version, simply type:
$ sudo gem install rails
You can then rerun your "rails" command.

And setting the variable GEM_HOME like export GEM_HOME="$HOME/.gems"


text:
Q: Copying files in ADB shell with run-as Is there a way to write a script that will copy files from an ADB shell using run-as?
The only way I know of to copy in the adb shell is using cat source > dest (edit: modern android versions have the cp command, which makes this question unnecessary), but I am only able to quote the greater-than sign one level deep - so my script can pass it to adb shell, but not to adb shell run-as.
For example, this works:
adb shell "cat source > dest"
But this does not:
adb shell run-as "cat source > dest"
Nor this:
adb shell "run-as cat source \> dest"
I even tried created a small script and uploading it to the device, but I can't seem to run the script from the adb shell - it tells me "permission denied". I can't chmod the script, either.
The reason I want to do this is to copy a file into an app's private storage area - specifically, I am using a script to modify shared preferences and put the modified preferences back. Only the app itself or root can write to the file I want, however.
The use case in this scenario is coping a file to a protected location on the device, not retrieving it; for retrieving, there are already good answers in this question.

A: you could just change the permission of the directory and then pull all the files out. but for me i was looking for just one shared preference file and i was able to get the data like this:
PACKAGE='com.mypackage.cool'
SHAREDPREF_FILE="${PACKAGE}_preferences.xml"

    adb shell "run-as $PACKAGE cat /data/data/$PACKAGE/shared_prefs/$SHAREDPREF_FILE">$SHAREDPREF_FILE

now we have the data of the sharedpreference file stored in a file of the same name.

A: The OP tried to combine the following 3 commands (that he had no problem executing one after another in the interactive shell session) into a single non-interactive command:
adb shell
run-as com.example.app
cat /sdcard/temp_prefs.xml > shared_prefs/com.example.app_preferences.xml

For simplicity let's start from within an interactive adb shell session. If we just try to combine the last two commands into a single line:
run-as com.example.app cat /sdcard/temp_prefs.xml > shared_prefs/com.example.app_preferences.xml

This would not work because of how shell redirection works - only the cat /sdcard/temp_prefs.xml part of the command would be run with com.example.app UID
Many people "know" to put the part of the command around redirection into quotes:
run-as com.example.app "cat /sdcard/temp_prefs.xml > shared_prefs/com.example.app_preferences.xml"

This does not work because the run-as command is not smart enough to parse the whole command. It expects an executable as the next parameter. The proper way to do it would be to use sh instead:
run-as com.example.app sh -c "cat /sdcard/temp_prefs.xml > shared_prefs/com.example.app_preferences.xml"

So can we just prepend adb shell to the command and be done with it? Not necessarily. By running the command from your PC you also add another local shell and its parser. Specific escape requirements would depend on your OS. In Linux or OSX (if your command does not already contain any ') it is easy to single-quote the whole command like so:
adb shell 'run-as com.example.app sh -c "cat /sdcard/temp_prefs.xml > shared_prefs/com.example.app_preferences.xml"'

But sometimes it is just easier to use an alternative solutions with (-out or less) quotes:
adb shell run-as com.example.app cp /sdcard/temp_prefs.xml shared_prefs/com.example.app_preferences.xml

Or if your device does not have the cp command:
adb shell run-as com.example.app dd if=/sdcard/temp_prefs.xml of=shared_prefs/com.example.app_preferences.xml

Also notice how I used shared_prefs/com.example.app_preferences.xml instead of full /data/data/com.example.app/shared_prefs/com.example.app_preferences.xml - normally inside of run-as command your current directory is the HOME dir of your package.

A: Following Chris Stratton's advice, the way I eventually got this to work was as follows (for copying shared preferences back to the device):
adb push shared_prefs.xml /sdcard/temp_prefs.xml
cat <<EOF | adb shell
run-as com.example.app
cat /sdcard/temp_prefs.xml > /data/data/com.example.app/shared_prefs/com.example.app_preferences.xml
exit
exit
EOF

Piping directly to adb shell run-as did not work, and I do not know why, but piping to adb shell does. The trick is to then call run-as from the interactive shell, and it continues to accept input from the pipe.
The HERE doc lets me easily embed the newlines to separate commands and in general just makes it readable; I did not have much luck with semicolons, but that might have been because of the way I was doing things. I believe it might work with other methods of piping multiple commands/newlines; I stopped the experiment once I finally got it to work.
The two exits are necessary to prevent a hanging shell (killable with CTRL-C); one for run-as, and the other for adb shell itself. Adb's shell doesn't respond to end-of-file very nicely, it seems.

A: Using the latest adb (ADB v1.0.41 / Version 33.0.3) and a Play Store emulator image I experienced adb root not being granted. I also could not copy from /data/local/ or /storage/emulated/0/ due to not having permissions when run-as com.myapp.app
new_prefs_path="my_machine.xml"
config="$(cat $new_prefs_path)"
my_app_uri="com.myapp.app"
adb shell "run-as $my_app_uri sh -c 'echo \"$config\" > shared_prefs/on_android.xml'"

This fixes it for me as a bash script. It's made slightly more complicated by needing to be configurable for different apps and complex payloads.
We take a file (could be generated earlier in this script) and read it to a variable.
We then start shell, do run-as my app and run echo expanding the read file to a file in shared_prefs.


text:
Q: Add select with javascript in Symfony 2 I want to raise an issue that arose me and do not know how to fix it .
Suppose I want to create a dynamic select , ie , if a select product , if I add or remove a product, select automatically updated. for example, could make the query in the controller like this:
$products = $em->getRepository('MyBundle:Entity')->findAll();

Then render it in this way:
return $this->render('MyBundle:myfolder:mytwig.html.twig', array("products" => $products));

And finally in my template , create my select like this:
<select>
{% for product in products %}
<option value="{{ product.name }}">{{ product.name }}</option>
{% endfor %}
</select>

my problem is I have a select where the user chooses to buy a product , and if you want to add another , by a button labeled "Add" enable a javascript , and so another select where you can choose another product is generated.
I've already made the javascript file, but if I use a twig for in the product not recognize me , ie , I can not add this with javascript:
<select>
    {% for product in products %}
    <option value="{{ product.name }}">{{ product.name }}</option>
    {% endfor %}
</select>

long time since I am with this, please , if you can help me do . thanks

A: You could do this with JavaScript alone, if you change your template to generate a "base" copy of your <SELECT> like this (assuming jQuery for brevity):
<div id='products_list'>
    <select>
    {% for product in products %}
      <option value="{{ product.name }}">{{ product.name }}</option>
    {% endfor %}
    </select>
</div>
<button id='AddProduct'>Add</button>
<script>
  $('#AddProduct').on('click', function () {
    var base = $('#products_list select:first');
    base.parent().append(base.clone());
  });
</script>

(demo)

A: I think that including your Javascript in your Twig file, and not in a separate file, enables you to use {{ }}, resolving your problem.
Hope this helps.


text:
Q: AJAX load in same page causes divs to repeat I'm performing the ajax call to the same page which works perfectly however it reload existing divs. I was wondering if there was a way to suppress it? Here's more details:
My project setup
index.php - Open records Controller
/**app logic**/

view('open',$data); //require '../views/layout.php';

layout.php
/*all the js scripts and stylesheets loaded here*/

include($path); //loads the open.view.php file

open.view.php
/*AJAX call to self*/

function getViaAjax(chosenGroup){
    $.post('index.php',{group:chosenGroup},
                function(data)
                {
                    $("#default").remove();
                    $('#group-tickets').html(data);
                });
}

As you might be able to tell, this causes the #logo and #nav div to duplicate on the page. I understand that I can do a AJAX post to a different file and I will get around the issue altogether but I was wondering if there's a way to do this?

A: Try this Link. Documentation Explains : The .load() method, unlike $.get(), allows us to specify a portion of the remote document to be inserted.
$('#result').load('ajax/test.html #container');


text:
Q: How to run npm variables during run time (process.env.SERVER) on a windows machine using Cmder? I have created a NodeJs, Selenium and webdriverio framework, but struggling to run npm variables during rune time (The same setup works on a mac).
My wdio file:
if(process.env.SERVER == "prod") {
    baseUrl = 'http://www.google.com';
}

exports.config = {

Running the following command in Cmder:
SERVER=prod npm test

However I get the following message:
'SERVER' is not recognized as an internal or external command,
operable program or batch file.

Operating system: Window 10 pro
Bash console: Cmder.
Any ideas ?

A: The closest behavior seems to be SET SERVER=prod && npm test. SET /? claims that it:

Displays, sets, or removes cmd.exe environment variable

I guess that should be accessible through Node.
However, contrary to usual shells, setting a variable seems to be a command in itself, hence requiring an explicit separator before the next command: here && to one-line it, you could also just hit Enter before calling npm - and ; doesn't seem to work.


text:
Q: jquery mobile loadpage problem I am trying to use loadPage with jquery mobile and the function doesn't seem to return data to the desired page container.
My javasript is like so
  $('.numMobi a').live("click", function() {
        var dataurl = $(this).attr("data-url");
        if (dataurl != null)
            $.mobile.loadPage("lib/loadMobis.php",{
                pageContainer:$("#MobiDirSites"),
                data:dataurl,
                transition: "slideup"
            });
    });

I get the databack in firebug but it is not inserting it in the page.
Here is my html

Any ides why it isn't inserting it?

A: In my test, your code successfully fetched the URL and loaded it into #MobiDirSites. I suspect this is what you want, since you're specifying a target element on the existing page. What I think Phill is picking up on is the fact that you specified a transition in your loadPage() call. transition only applies to changePage().


text:
Q: Why memory of spark executor keep growing? I submit my code to a standalone cluster running on one node. The node have 16GB memory and 8 core CPU.
I noticed that the executor memory keeps growing. Very slow but really growing. Eventually the memory of executor will exceed the setting I specified and cause the program hang there.  With some error like :
16/05/09 19:32:32 ERROR ContextCleaner: Error cleaning broadcast 12242
org.apache.spark.rpc.RpcTimeoutException: Futures timed out after [120 seconds]. This timeout is controlled by spark.rpc.askTimeout
    at org.apache.spark.rpc.RpcTimeout.org$apache$spark$rpc$RpcTimeout$$createRpcTimeoutException(RpcTimeout.scala:48)
    at org.apache.spark.rpc.RpcTimeout$$anonfun$addMessageIfTimeout$1.applyOrElse(RpcTimeout.scala:63)
    at org.apache.spark.rpc.RpcTime

The submit command I use is here:
./bin/spark-submit   --master spark://ES01:7077 --executor-memory 4G --num-executors 1 --total-executor-cores 1 --conf "spark.storage.memoryFraction=0.2" ./mycode.py   1>a.log 2>b.log

The workload is not heavy. A few kb data will be calculated during each batch interval. And my executor memory is setting to 4GB.
The code is very simple so I will post here also in case there might be anything inappropriate.
from pyspark import SparkContext
from pyspark.streaming import StreamingContext
from pyspark import SparkContext, SparkConf
from pyspark.sql import SQLContext, Row, HiveContext
import pyspark.sql.functions as func
from pyspark.sql.window import Window

def getSqlContextInstance(sparkContext):
    if ('sqlContextSingletonInstance' not in globals()):
        globals()['sqlContextSingletonInstance'] = HiveContext(sparkContext)
    return globals()['sqlContextSingletonInstance']

def top_n(df, groupby_column, agg_column, ):
    df_agg = df. \
        groupBy(['tag', 'interface', groupby_column]). \
        agg(func.sum('pkts').alias('pkts'), func.sum('bits').alias('bits'))

    windowSpec = Window. \
        partitionBy(df_agg['tag'], df_agg['interface']). \
        orderBy(df_agg[agg_column].desc())

    rank = func.dense_rank().over(windowSpec)

    top_n_agg = df_agg. \
        select(df_agg['tag'], df_agg['interface'], df_agg[groupby_column], df_agg['pkts'], rank.alias('rank')). \
        filter("rank<=2")
    top_n_agg.show()

def process(time, rdd):
    if rdd.isEmpty():
        return sc.emptyRDD()

    sqlContext = getSqlContextInstance(rdd.context)

    # Convert RDD[String] to RDD[Row] to DataFrame
    parts = rdd.map(lambda l: l.split(","))
    rowRdd = parts.map(lambda p: Row(
        tag=p[0], in_iface=int(p[1]), out_iface=int(p[2]), src_ip=p[3], dst_ip=p[4], src_port=int(p[5]),
        dst_port=int(p[6]), protocol=p[7], ip_dscp=p[8], flow_direction=p[9], pkts=int(p[10]), bits=int(p[11])))

    df = sqlContext.createDataFrame(rowRdd)

    dataframe_ingress = \
        df.filter(df['flow_direction'] == 0). \
            select(df['tag'], df['in_iface'].alias('interface'), df['src_ip'], df['dst_ip'], df['src_port'],
                   df['dst_port'], df['protocol'], df['flow_direction'], df['pkts'], df['bits'])
    dataframe_ingress.cache()

    #########################################
    # top N
    #########################################
    top_n(df=dataframe_ingress, groupby_column='protocol', agg_column='pkts')
    top_n(df=dataframe_ingress, groupby_column='protocol', agg_column='bits')
    top_n(df=dataframe_ingress, groupby_column='src_ip', agg_column='pkts')
    top_n(df=dataframe_ingress, groupby_column='src_ip', agg_column='bits')
    top_n(df=dataframe_ingress, groupby_column='dst_ip', agg_column='pkts')
    top_n(df=dataframe_ingress, groupby_column='dst_ip', agg_column='bits')

    dataframe_ingress.unpersist()

if __name__ == "__main__":
    dataDirectory = '/stream/raw'

    sc = SparkContext(appName="Netflow")
    ssc = StreamingContext(sc, 15)

    lines = ssc.textFileStream(dataDirectory)
    lines.foreachRDD(process)

    ssc.start()
    ssc.awaitTermination()


text:
Q: Pass a variable to a function from another function in JavaScript (winJs) Hi I'am working with Windows 8 app using  Java Script
function fetchFromLiveProvider(currentList, globalList,value) {
    feedburnerUrl = currentList.url,
    feedUrl = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&output=json&num=999&q=" + encodeURIComponent(feedburnerUrl);
        WinJS.xhr({url: feedUrl, responseType: "rss/json"
        }).done(function complete(result) {
                 var jsonData = JSON.parse(result.response);
                    //console.log(JSON.stringify(jsonData));
                 var entries = jsonData.responseData.feed;
               });
    }
function setOther(entries){
       //some code here
    }

I want to do is pass the  entries in the fetchFromLiveProvider function to another function called setOther(entries){}. Thank you for any help...

A: Since WinJS.xhr returns a promise, you can do the following:
var entriesPromise = function fetchFromLiveProvider(currentList, globalList, value) {
    feedburnerUrl = currentList.url,
    feedUrl = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&output=json&num=999&q=" + encodeURIComponent(feedburnerUrl);
    return WinJS.xhr({
        url: feedUrl,
        responseType: "rss/json"
    });
}

function setOther(entries) {
    entries.done(function complete(result) {
        var jsonData = JSON.parse(result.response);
        //console.log(JSON.stringify(jsonData));
        var entries = jsonData.responseData.feed;

        //some code here
    })
}

setOther(entriesPromise);


text:
Q: Java codes giving error after proper allocation of memory I'm trying to print the value of each pixel, but it gives error when p = 300.
Before p = 300, all pixels are printed.
orignal.getHeight() = 344; and orignal.getWidth() = 300;.
BufferedImage binarized = new BufferedImage(original.getWidth(), original.getHeight(), original.getType());
int p, q;

System.out.println(original.getHeight() + "," + original.getWidth());

for(p=0;p<original.getHeight();p++)
{
    for(q = 0; q < original.getWidth(); q++)
    {
        //System.out.println("goint to get pixel"+"("+p+","+q+")");
        int Pixel = binarized.getRGB(p, q);
    }
}

Error message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Coordinate out of bounds!
    at sun.awt.image.ByteInterleavedRaster.getDataElements(ByteInterleavedRaster.java:318)
    at java.awt.image.BufferedImage.getRGB(BufferedImage.java:888)
    at Binarization.binarize(Binarization.java:137)
        at Binarization.main(Binarization.java:20)

Is this some kind of memory allocation problem?

A: No, this means that you have an error in your logic.
You try to access an array element by index, which is greater than array size
Try changing the logic of the array retrieval:
 int Pixel=binarized.getRGB(q,p);

This works because the method expects: getRGB(int width,int height), but you provide height, width to it

A: Look at the documentation for BufferedImage.getRGB
public int getRGB(int x, int y)

Note that the x value is the first parameter - that's the one which should be in the range [0, width). The y value is the second parameter - that's the one which should be in the range [0, height). You've got them the wrong way round. I'm slightly disappointed that the exception isn't friendlier, admittedly.
It would be much clearer if you'd use x and y variables in your loop, too:
for (int y = 0; y < original.getHeight(); y++)
{
    for (int x = 0; x < original.getWidth(); x++)
    {
        int pixel = binarized.getRGB(x, y);
        // Use pixel
    }
}

(Also note how I've declared x and y in the loops themselves; there's no point in declaring them beforehand. I've also added whitespace for readability.)


text:
Q: Razor RenderPartial generates wrong HTML I have a page Item Edit with multiple partial rendered forms for images delete. Item Edit page:
@model EditModel
<form method="post" enctype="multipart/form-data">
    <input asp-for="ItemModel.Id" type="hidden" />
    <input asp-for="ItemModel.AllOtherFields" type="hidden" />
</form>
@if (Model.ItemModel.ImageViewModels != null && Model.ItemModel.ImageViewModels.Any())
{
    foreach(var imageViewModel in Model.ItemModel.ImageViewModels)
    {
       Html.RenderPartial("ItemImage/_itemImageEdit", imageViewModel);
    }
}

ItemImage/_itemImageEdit
@model ViewModels.ItemImageViewModel

<form asp-controller="Images" asp-action="Delete" method="post">
    <input type="hidden" asp-for="@Model.Id" />

    <input type="submit" value="Delete" />
</form>

and here is my strange final html
<form method="post" action="/Images/Delete/5" novalidate="novalidate">
     <input type="hidden" data-val="true" data-val-required="The Id field is required." id="Id" name="Id" value="5">

    <input type="submit" value="Delete">
</form>

Where 5- Item id and 10 - image Id. So this is expected and correct

while this is not. Item Id used instead of id (ItemImageViewModel.id)
action="/Images/Delete/5"

I have no idea why does @Model.Idgenerate different ids on the same subview.
Edit1:
public class ItemImageViewModel
{
    [BindProperty]
    public int Id { get; set; }
    public string Title { get; set; }
    public int ItemId { get; set; }

}

public class ItemViewModel
{
    public ItemViewModel()
    {
    }
    public ItemViewModel(ItemViewModel vm)
    {
        Id = vm.Id;
        Title = vm.Title;
        ImageViewModels = vm.ImageViewModels;
    }
    public int Id { get; set; }
    public string Title { get; set; }
    public IEnumerable<ItemImageViewModel> ImageViewModels { get; set; }
}

I have removed unrelated fields.
Debugger shows alright

A: Now this weird piece of code generates what it supposed to generate
<form action="@Url.Action("Delete", "Images", new { id = Model.Id })" method="post">
    <input type="hidden" id="Id" name="Id" value="@Html.DisplayFor(m => Model.Id)" />
    @Html.HiddenFor(m => Model.ItemId)"

    <input type="text" asp-for="@Model.Title" />
    <input type="submit" value="Delete" />
</form>

<form action="/Images/Delete/10" method="post" novalidate="novalidate">
    <input type="hidden" id="Id" name="Id" value="10">
    <input data-val="true" data-val-required="The ItemId field is required." id="ItemId" name="ItemId" type="hidden" value="5">"

    <input type="text" id="Title" name="Title" value="Jacket">
    <input type="submit" value="Delete">
</form>


text:
Q: Function in LISP replacing every non-number in a list/sublist with NIL I am trying to self-learn LISP programming. I'm having difficulty writing a LISP function that replaces every non-number in a list or sublist with NIL.
For example, if I input (REPLACE '(4 0 4)) it should return (4 0 4).
If I input (REPLACE '(1 2 SHOE (3 4 DOOR))) it should return (1 2 NIL (3 4 NIL))
I'm a bit stuck... how would this be done? Any help would be greatly appreciated!
EDIT: I don't have much, unfortunately, but so far, I have:
(defun REPLACE (L)
    (cond ( (NUMBERP L)

I know I'd need to check to see if each element in the list is a number using NUMBERP. If anyone could help explain to me how to go from here so I can progress that'd be so helpful.

A: You need to split the problem up in steps:
A function that replaces non numbers with nil:
(defun (nil-non-number v)
  ...)

(nil-non-number 3) ; ==> 3
(nil-non-number 'q) ; ==> nil
(nil-non-number "test") ; ==> nil

A function that iterates a list and uses nil-non-number for each element:
(defun replace-non-nums (lst)
  ...)

(replace-non-nums '())                    ; ==> nil
(replace-non-nums '(4 0 4))               ; ==> (4 0 4)
(replace-non-nums '(4 a 4))               ; ==> (4 nil 4)
(replace-non-nums '(1 2 shoe (3 4 door))) ; ==> (1 2 nil nil)

As a last step you need at add a test for cons before testing for non numbers and if it is you should also call replace-non-nums for that list and use the return there as the element. Then you can test the last one again:
(replace-non-nums '(1 2 shoe (3 4 door))) ; ==> (1 2 nil (3 4 nil))

All the other tests should yield the same as before as well.


text:
Q: How to Decode a CSR in .net,php,cgi,etc How to Decode a CSR in .net,php,cgi,etc
wth a output like
CN
OU
O
L
S
C

A: Easy in PHP:
$csr=$_POST['txtcsr'];  // Copy CSR to a variable
$data=openssl_csr_get_subject($csr);  // Get the subject of the CSR
print_r($data); // Print the output as an array:

Output: Array ( [C] => US [ST] => Minnesota [L] => Shakopee [O] => Test Organization [OU] => IT Arhitecture [CN] => your.domain [emailAddress] => your@email.com)
Tip: To get the function work, the server must have the OPENSSL_CNF environment variable correctly set.

A: Look at OpenSSL modules for php and python for example.
Php OpenSSL
Python OpenSSL
You can check php openssl_x509_parse() function or use something like proc_open, os.popen to call openssl tool to do all the job and get results.


text:
Q: How to get the -fpermissive flag to take effect? I'm building a library in c++ with the NDK (Android). The output tells me that some code is flagged as an error but could be suppressed by using the -fpermissive flag.  At least that's how it looks to me.  The output is:
MyClass.cpp:412:1: error: jump to label 'extractUp' [-fpermissive]
 extractUp:
 ^
jni/../../../../SharedSrc/MyClass.cpp:469:10: error:   from here [-fpermissive]
     goto extractUp;
          ^
jni/../../../../SharedSrc/MyClass.cpp:402:31: error:   skips initialization of 'Foo* ISC'
      Foo *ISC = new Foo;

The code that's causing the error isn't relevant here as the question I'm asking is what might be preventing the -fpermissive flag from taking effect.  The makefile (Android.mk) seems to be correct in how it is setting the flag but I don't know much about make files:
add_definitions(-DFPERMISSIVE=1)

I've also tried -Dfpermissive in case all caps were not allowed, and have tried adding it to LOCAL_CFLAGS with:
LOCAL_CFLAGS += -Dfpermissive

and
LOCAL_CFLAGS += -DFPERMISSIVE

A: Actually that's not a flag definition so you shouldn't use -Dflagname but just -fpermissive, which is a flag to the compiler.
-Dflagname has the effect of #define flagname which is not what you need to do.
By the way the -fpermissive doesn't suppress errors, it just downgrades them to warning.

A: You can add APP_CFLAGS += or APP_CPPFLAGS += in your Application.mk file.
For C++ code you need to use APP_CPPFLAGS += -fpermissive
Where as for C code you use APP_CFLAGS += -fpermissive
It is also possible to use both of them in your Application.mk file if your project contains both codes.


text:
Q: use of other functions alongside analog input function I have an analog input object (winsound) taking samples and performing a task on audio in MATLAB.
set(AI, 'SamplesAcquiredFcnCount',num_samples)
set(AI, 'SamplesAcquiredFcn',{@function1,AI,num_samples})

My understanding is that the analog input object just keeps taking samples, and hence function1 keeps being called when samples reach the set number. So it has 'priority'.
Now I have another function (function2), that I want to continuously process the (global) variables that the function1 updates. My problem is that in my current implementation function2 won't "come back" and look at the updated variables from the analog input.
I want to call function2 continuously up to a certain duration or condition, but how do I make it see the updated variables from the analog input function1? (they are already global, but once function2 has begun it doesn't get the updated variables, only as they were when it started).
I've tried to look into stuff in parallel computing toolbox to help me here, but haven't found anything. I really appreciate any help! This will really piece my project together

A: In the end the best way to ensure good side-by-side operation is just to call function2 inside function1. Since function1 is nicely controlled as a callback in the analog input object, this is the safest way to go about it.


text:
Q: Can't update RecyclerView through AsyncTask I'm trying to view list of IP address in the local network, but I'm doing something wrong because I couldn't update the RecyclerView after the list of IP's is ready.
Here is my Main Activity:
public class MainActivity extends AppCompatActivity {

RecyclerView recyclerView;
String light_names[];
int icon[] = {R.drawable.light_icon};
IPListAdapter ipListAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    recyclerView = findViewById(R.id.recyclerView);
    light_names = new String[]{"Detecting.."};
    ipListAdapter = new IPListAdapter(this, light_names, icon);
    recyclerView.setAdapter(ipListAdapter);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    new getIps().execute();
    ipListAdapter.notifyDataSetChanged();
}

private class getIps extends AsyncTask<Void, Void, Void>{

    String[] all_ips;
    int counter;
    int onsetCounter;

    @Override
    protected Void doInBackground(Void... params) {

        //count
        counter = 0;

        try {
            Enumeration nis = NetworkInterface.getNetworkInterfaces();
            while(nis.hasMoreElements())
            {
                NetworkInterface ni = (NetworkInterface) nis.nextElement();
                Enumeration ias = ni.getInetAddresses();
                while (ias.hasMoreElements())
                {
                    InetAddress ia = (InetAddress) ias.nextElement();
                    counter++;
                }
            }
        } catch (SocketException ex) {

        }

        all_ips = new String[counter+1];

        // getting count
         onsetCounter = 0;

        try {
            Enumeration nis = NetworkInterface.getNetworkInterfaces();
            while(nis.hasMoreElements())
            {
                NetworkInterface ni = (NetworkInterface) nis.nextElement();
                Enumeration ias = ni.getInetAddresses();
                while (ias.hasMoreElements())
                {
                    InetAddress ia = (InetAddress) ias.nextElement();
                    String s = ia.getHostAddress();
                    if(s!=null){
                        all_ips[onsetCounter] = s;
                    }else{
                        all_ips[onsetCounter] = "s";
                    }

                    onsetCounter++;
                }
            }
        } catch (SocketException e) {
          e.printStackTrace();

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        light_names = all_ips;

        ipListAdapter.notifyDataSetChanged();

        super.onPostExecute(result);

    }
}

Here is the IPListAdapter class:
public class IPListAdapter extends RecyclerView.Adapter<IPListAdapter.MyViewHolder> {

String data1[];
int images[];
Context context;

public IPListAdapter(Context ct, String s1[], int img[] ){
    context= ct;
    data1 = s1;

    images = img;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(context);
    View view = inflater.inflate(R.layout.my_row, parent, false);
    return new MyViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
    holder.myText1.setText((data1[position]));
    holder.myImage.setImageResource(images[0]);
}

@Override
public int getItemCount() {
    return data1.length;
}

public class MyViewHolder extends RecyclerView.ViewHolder {
    TextView myText1;
    ImageView myImage;

    public MyViewHolder(@NonNull View itemView) {
        super(itemView);
        myText1 = itemView.findViewById(R.id.light_name);
        myImage = itemView.findViewById(R.id.myImageView);
    }
}
}

I feel like the problem is mainly from the way I update the adapter in onPostExecute. I tried adding a textview and setting its value inside onPostExecute and it worked well, but the recycler view wouldn't update.

A: like @blackapps mentioned in the comment you are giving a copy of your IP-list to the Adapter-class when you instantiate the adatper. In your onPostExecute you only update the list of the activity, but the adapters data field is not changed.


text:
Q: how do i redirect a specific path to another path in nginx? I need to redirect a specific path:
mydomain.com/old-path/

to a new path, permanently:
mydomain.com/new-path/

i am using elgg software (elgg.org) and presently when someone navigates to the /old-path/ folder they view a page (rather than a folder listing) - thus no specific page name is used.
i tried the various methods of redirecting that can be found via google for nginx and so far none have had any effect. they mostly are either for a specific page or a directory, yet what i am doing, is, i suppose, technically neither a specific page or a directory..
anyone know how to achieve this?
thanks

A: You can use nginx HttpRewriteModule to do this.
rewrite ^/old-directory/(.*)$ /new-directory/$1 last;


text:
Q: Simple Button to Magento 1.9 sales order view Im trying to add a simple button to the Magento Order. I tried the solution from stackoverflow but it is not working. This is my code, would be great if you can tell me what Im doing wrong. Thank you.
app/local/FirstGood/PrintCard/Block/Adminhtml/Sales/Order/View.php

<?
class FirstGood_PrintCard_Block_Adminhtml_Sales_Order_View extends Mage_Adminhtml_Block_Sales_Order_View {
    public function  __construct() {

  parent::__construct();
        $this->addButton('button_id', array(
            'label'     => Mage::helper('xxx')->__('Some action'),
            'onclick'   => 'jsfunction(this.id)',
            'class'     => 'go'
        ), 0, 100, 'header', 'header');
    }
}

app/local/FirstGood/PrintCard/etc/config.xml

<?xml version="1.0"?>
<config>
<modules>
        <FirstGood_PrintCard>
            <version>0.0.1</version>
        </FirstGood_PrintCard>
    </modules>
<global>
    <blocks>
         <adminhtml>
            <rewrite>
                <sales_order_view>FirstGood_PrintCard_Block_Adminhtml_Sales_Order_View</sales_order_view>
            </rewrite>
   <events>
        <adminhtml_widget_container_html_before>
            <observers>
                <firstgood_printcard>
                    <class>firstgood_printcard/observer</class>
                    <type>singleton</type>
                    <method>adminhtmlWidgetContainerHtmlBefore</method>
                </firstgood_printcard>
            </observers>
        </adminhtml_widget_container_html_before>
    </events>
        </adminhtml>
    </blocks>
 </global>
 </config>

app/local/FirstGood/PrintCard/Model/Observer.php

<?php
class FirstGood_PrintCard_Model_Observer {
    public function adminhtmlWidgetContainerHtmlBefore($event)
{
    $block = $event->getBlock();

    if ($block instanceof Mage_Adminhtml_Block_Sales_Order_View) {
        $message = Mage::helper('your_module')->__('Are you sure you want to do this?');
        $block->addButton('do_something_crazy', array(
            'label'     => Mage::helper('your_module')->__('Export Order'),
            'onclick'   => "confirmSetLocation('{$message}', '{$block->getUrl('*/yourmodule/crazy')}')",
            'class'     => 'go'
        ));
    }
}
}

app/etc/modules/FirstGood_PrintCard.xml

<?xml version="1.0"?>
<config>
  <modules>
    <FirstGood_PrintCard>
      <active>true</active>
      <codePool>local</codePool>
      <version>0.1.0</version>
    </FirstGood_PrintCard>
  </modules>
</config>

A: You just need to use "sales" helper, instead of "xxx". Use below code, it will help to fix this out.
app/local/FirstGood/PrintCard/Block/Adminhtml/Sales/Order/View.php
<?
class FirstGood_PrintCard_Block_Adminhtml_Sales_Order_View extends Mage_Adminhtml_Block_Sales_Order_View {
    public function  __construct() {

       parent::__construct();
       $this->addButton('button_id', array(
        'label'     => Mage::helper('sales')->__('Some action'),
        'onclick'   => 'jsfunction(this.id)',
        'class'     => 'go'
       ), 0, 100, 'header', 'header');
    }
}


text:
Q: Highlight text in SharePoint document preview This SO question shows a programmatic way for highlighting text in a word document. I am looking to do the same thing but for a document opened inside Sharepoint 2010.
From this link I understand that a document can be opened inside sharepoint itself using the office webapp (a bit of a hack in 2010, better in 2013) or in the local user instance of word/excel/...
I would need programmatic, read-only control over that preview. Mainly to highlight particular text fragments. I would think it should be possible to do this for the webapp instance but not for the locally started instance. Though I have't found any example code or pointers how to approach this. Commercial solutions are not an option.
Edit:

*

*Related question

*There seems to be some kind of an api
for the Excel web app but not for word

A: As far as I can see this is not possible, but happy to be proven wrong. The only solution I see is to do the highlighting on the server side up front (e.g., using com or openxml libs) in a separate copy of the document or on the fly (e.g., like here). Then serve the processed document to the client.


text:
Q: I need create custom order tracking functionality in woo commerce Hello I have a woo commerce website and I  am selling some books every thing is cleared but I need create custom order tracking functionality in woo commerce code to add order tracking functionality for end user is it possible if possible how can I do this please help me.
I create a custom page name as woocommerce-custom-order-tracking.php
and code is given below
<?php

// Register a custom endpoint to handle order tracking
function wc_register_order_tracking_endpoint() {
    add_rewrite_endpoint( 'order-tracking', EP_PAGES );
}
add_action( 'init', 'wc_register_order_tracking_endpoint' );

// Display the order tracking form
function wc_display_order_tracking_form() {
    if ( ! is_wc_endpoint_url( 'order-tracking' ) ) {
        return;
    }

    // Get the order id from the query string
    $order_id = absint( $_GET['order_id'] );

    // Get the order
    $order = wc_get_order( $order_id );

    if ( $order ) {
        // Display the order tracking information
        echo '
Order Number: ' . $order->get_order_number() . '
';
        echo '
Order Status: ' . wc_get_order_status_name( $order->get_status() ) . '
';
        echo '
Tracking Number: ' . get_post_meta( $order_id, '_tracking_number', true ) . '
';
    } else {
        echo '
Invalid order ID.
';
    }
}
add_action( 'woocommerce_before_single_product', 'wc_display_order_tracking_form' );


text:
Q: how do i compare the value of an object in this code i want to put integers in a double list
and then to check if the list is sorted or not
so in a method i try to compare the value the first
object of the list with the second, then the second with the third etc.
what i dont remember/know is how you compare them
public class Ergasthrio6 {

    public static boolean isSorted(DoubleLinkedList dl) throws ListEmptyException{
        DoubleLinkedList selectedItem = (DoubleLinkedList) dl.removeFirst();
        dl.insertLast(selectedItem);
        DoubleLinkedList tmp;
        for (int i=1; i < dl.size(); i++){
            tmp = (DoubleLinkedList) dl.removeFirst();
            dl.insertLast(tmp);
            if (selectedItem < tmp)) <-----here
               return false;
            else
               selectedItem = tmp;
            tmp = tmp.removeFirst();
        }
    }

    public static void main(String[] args) throws ListEmptyException {
        // TODO code application logic here
        DoubleLinkedList dl = new DoubleLinkedList();
        for (int i=0; i < 10; i++)
            dl.insertFirst(UserInput.getInteger());
        isSorted(dl);
    }
}

A: an easy approach would be to create a method in which each variable of the two objects will be compared. returning a boolean or a -1, 1 kind of value would suffice in case of less than or not scenarios.


text:
Q: Detecting NULL dates and showing empty string in SSRS I'm trying to format some cells in a Reporting Services report that will contain DateTime? values - or not.
If the underlying data has a NULL for that DateTime?, I'd like to show nothing (empty cell) - and if that data source contains a value, I'd like to show the date in short date format (dd.MM.yyyy in my locale).
So I tried to put this formula into the relevant SSRS cells
=FormatDateTime(Fields!DatumBSE.Value, 2)

but now I'm getting 01.01.0001 for all NULL dates....
I can't seem to wrap my head around how to do this in a SSRS (VB) formula.... I tried using IsNothing() but that doesn't seems to really help - I can detect a NULL, but how to I tell the cell to show an empty string in that case?
Solution:
I ended up using this function:
=IIF(IsNothing(Fields!DatumBSE.Value), "", FormatDateTime(Fields!DatumBSE.Value, 2))

Seems to work just fine for me now.

A: I just tested the following expression and it replaced the null date with an empty string:
=IIF(Fields!DatumBSE.Value is nothing, nothing, FormatDateTime(Fields!DatumBSE.Value, 2))

The other suggestion that I would make is that you could format the date to the correct format in the report dataset by placing a CASE expression around the date value.

A: use a code like this:
If(isNull([date field]),Null, elsequote)


text:
Q: How can I use variables that are declared in another class? I am automating an email to be sent nightly. The "Send email" class contains the variables  mailFrom and mailTo. ExcelReader is a prerequisite class that reads the cells of an Excel worksheet that will contain the email addresses . I need my "Send email" (SendCf) class to get it's mailFrom and mailTo variables from the ExcelReader class (which gets it's variables from the Excel sheet's cells).
The purpose is so other people can modify an Excel sheet with different To/From email addresses, and my email sent nightly will reflect that. So I need to pull from the Excel sheet every time I send an email (not sure how to make that method run as a prerequisite to the email either).
First, my ExcelReader. It declares the values of variables a1Val and b1Val (the cells that contain the needed email adresses).
package com.test.Email;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelReader {

    public static void main(String[] args) {
        try {
            FileInputStream fileInputStream = new  FileInputStream("C:/Users/TEST.xlsx");
            XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
            XSSFSheet worksheet = workbook.getSheetAt(0);

            XSSFRow row1 = worksheet.getRow(0);
            XSSFCell cellA1 = row1.getCell((int) 0);
            String a1Val = cellA1.getStringCellValue();
            XSSFCell cellB1 = row1.getCell((int) 1);
            String b1Val = cellB1.getStringCellValue();

So now we have variables set from excel. The mailTo and mailFrom are in cells A1 and B1. Now, i need my Send Email class to grab A1 and B1 from the ExcelReader class and assign their values to the sender and recipient. I know what I have below is very incorrect.
package com.test.Email;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

     public class SendCF {

        //Not sure about this, I think I need to declare a local ExcelReader here?
        ExcelReader cfExcel = new ExcelReader();

     public static void main(String[] args)

            String host = "smtp.gmail.com";
            String port = "587";
//These two variables, I need to get from the excel sheet via the ExcelReader class.
            String mailFrom = cfExcel.a1Val;
            String mailTo = "cfExcel.b1Val;
            String password = "QAtesting";

            // after this I compose the email and send it.

edit: I now declare variables outside of the main method, but it won't allow me to make them public. I get "Illegal modifier for the variable a2Val; only final is permitted"
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelReader {
                {
    try {
        FileInputStream fileInputStream = new     FileInputStream("C:/Users/test.xlsx");
        XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
        XSSFSheet worksheet = workbook.getSheetAt(0);

        XSSFRow row1 = worksheet.getRow(0);
        XSSFCell cellA1 = row1.getCell((int) 0);
        String a1Val = cellA1.getStringCellValue();
        XSSFCell cellB1 = row1.getCell((int) 1);
        String b1Val = cellB1.getStringCellValue();
        XSSFCell cellC1 = row1.getCell((int) 2);
        String c1Val = cellC1.getStringCellValue();
        XSSFCell cellD1 = row1.getCell((int) 3);
        String d1Val = cellD1.getStringCellValue();
        XSSFCell cellE1 = row1.getCell((int) 4);
        String e1Val = cellE1.getStringCellValue();
        XSSFCell cellF1 = row1.getCell((int) 5);
        String f1Val = cellF1.getStringCellValue();

      } catch (FileNotFoundException e) {
        e.printStackTrace();
        } catch (IOException e) {
        e.printStackTrace();
        }
}

public static void main(String[] args) {
    //dont think I need anything here?

    }
}

A: You have a1Val and b1Val defined in your main method these variables will only be accessible in that scope. If you want to access them outside the class you need to make them global variables. If you want to directly access them they need to have the public modifier or you can use private and create getters and setters second option is recommended.
Method 1:
public class ExcelReader {
    public String a1Val;
    public String b1Val;

    public static void main(String[] args) {

Access like this:
    cfExcel.a1Val;

Method 2:
public class ExcelReader {
    private String a1Val;
    private String b1Val;

    public String geta1Val()
    {
        return this.a1Val;
    }

    public String getb1Val()
    {
        return this.b1Val;
    }

    public void seta1Val(String a1Val)
    {
        this.a1Val = a1Val;
    }

    public void setb1Val(String b1Val)
    {
        this.b1Val = b1Val;
    }

    public static void main(String[] args) {

Access like this:
cfExcel.geta1Val();
cfExcel.seta1Val("test");

********************************************************UPDATE**********************************************************
This is how it should look:
public class ExcelReader {
    public String a1Val;
    public String b1Val;

    public static void main(String[] args) {
        try {
            FileInputStream fileInputStream = new  FileInputStream("C:/Users/TEST.xlsx");
            XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
            XSSFSheet worksheet = workbook.getSheetAt(0);
            XSSFRow row1 = worksheet.getRow(0);
            XSSFCell cellA1 = row1.getCell((int) 0);
            a1Val = cellA1.getStringCellValue();
            XSSFCell cellB1 = row1.getCell((int) 1);
            b1Val = cellB1.getStringCellValue();


text:
Q: C# SOAP Client using WebForm and listing results I'm very new to SOAP and C# but I trying to learn by building a simple SOAP web client. I've create a web form with a single button and listbox. Clicking the button sends a SOAP call to the web services, returns a simple result and displays in the list box. That method (getCountRegisteredSubscribers) doesn't require input and returns an int. Next I want to return information about subscribers using another method called getSubscriber. This method does require input (subscriber name) and will return several results. I'm struggling with how to make the call by passing the subscriber name and listing the results in my listbox, would really appreciate any suggestions!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

namespace WebApplication2
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            WebApplication2.WebReference.SMFAdmin ws = new WebApplication2.WebReference.SMFAdmin();

            ListBox1.Items.Add("Request Submitted");
            ListBox1.Items.Add(""+ ws.getCountRegisteredSubscribers());
            //ListBox1.Items.Add("" + ws.getSubscribers("subname"));
        }
    }
}

Update
I've added a variable to store the subscriber name, however, it's returning 'WebApplicaiton2.WebReference.Subscriber' in my listbox. Any ideas how to fix this? There are several items associated with each subscriber, how do I get them to list inside my listbox? Thanks in advance.
namespace WebApplication2
{
public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {

        var subName = "subscriber 1";

        WebApplication2.WebReference.SMFAdmin ws = new WebApplication2.WebReference.SMFAdmin();

        ListBox1.Items.Add("Request Submitted");
        ListBox1.Items.Add(""+ ws.getCountRegisteredSubscribers());
        ListBox1.Items.Add("" + ws.getSubscriber(subName));

    }

}
}

A: You just need to loop through the result and insert them to list box.
protected void Button1_Click(object sender, EventArgs e)
{
    WebApplication2.WebReference.SMFAdmin ws = new WebApplication2.WebReference.SMFAdmin();

    ListBox1.Items.Add("Request Submitted");
    ListBox1.Items.Add("" + ws.getCountRegisteredSubscribers());
    ListBox1.Items.Add("" + ws.getSubscribers("subname"));

    List<string> lstOutput = new List<string>();
    lstOutput = ws.getSubscribers("subname");
    lstOutput.ForEach(eachItem => ListBox1.Items.Add(eachItem));
}

A: From your Exception message, its seems getSubscribers doesn't take String value as parameter. So what you have to do this something like this.
ws.getSubscribers(new SubscriberNameInfo
{
  *** value goes here **
});

I don't know the Detail of SubscriberNameInfo class, so I can't specified the properties.
Note: The second comment from the above answer is similar, I just added some code snippets.
I hope, this will help.


text:
Q: How do you find the "main" picture of a website, given the URL? Let's say you're given http://nytimes.com
How would you pull out the "main" image?
The reason I'm asking is because Flipboard is able to grab the main image from a website, just using the URL.
You could parse out all the image tags. But then what?

A: There really isn't anything that is considered the "main" image in a web page--nothing in HTML or otherwise to distinguish this. Not to mention you'd probably have to read all the images in CSS (or rather the background images etc). But if I had to do this, here is what I would do:

*

*First I would decide a suitable image size, lets say a 400x400 minimum. (I don't want to pick any old image, something really small would likely scale horribly)

*I would then iterate through each image on the page.2.

*For each image I encountered I would check the size of it3.
If it was 400x400 (my predefined size) or larger I would use this image.
If it wasn't, I would check that its the largest image I've found so far and if so keep its information stored off to the side.

*Once I had reached a predefined number of images I've checked
(for argument lets say 10, but surely you'd probably go much higher) I'd use the largest image I've found (stored off to the side) because I wouldn't want to scan the page indefinitely looking for images!

A: I don't believe there's a standard method. You could start by looking for an Open Graph Protocol image tag. Facebook uses these to select images for urls posted in status updates and comments.
<meta property="og:image" content="http://ia.media-imdb.com/rock.jpg"/>

If you're prepared to use a third party, Embedly offer this as a chargeable service.

Embedly provides a powerful API to convert standard URLs into embedded
  videos, images, and rich article previews from 218 leading providers.

A: There are many strategies to determine what is the "main" image of an URL:

*

*many websites now declare what the main image is (for Facebook OpenGraph or Twitter Cards)

*sometimes, the image can be guessed from the URL or by doing an API call (especially true for image hosting websites such as Instagram)

*the main image can also be determined with by analyzing the webpage with content extraction techniques (Readability). You might want to filter out "noise" to get rid of tracking pixels or ads.

*if all these techniques fail, you can download all the images and assume that the largest images are the most interesting.

I've created a JavaScript library that uses most of these techniques to determine the "main" picture of an URL : ImageResolver.

A: Facebook allows the user to pick one of several images that it has deemed to be a "main" image. As far as automatically determining a "main" image, I would judge it based on page position, size, relation to text, and (if you wanted to be more sophisticated) its visual content.
For example, you could use a simple face detection program, or look at color breakdowns to determine if the picture was "interesting" to you or not.
EDIT: In the case of www.nytimes.com, I would probably just look at the page structure, because a large carousel of images is located right underneath an H1 tag.


text:
Q: Xbox360 Universal Media Remote - out of sync? I have the Universal Media Remote from Microsoft, which was included with my HD-DVD package. I've been using it for over a year to watch videos/DVDs on my Xbox360 and it saved me the hassle of navigating with the game controller (which turns itself off every 5 minutes).All of a sudden (it didn't fall or suffer any severe trauma), it does not communicate with the Xbox anymore: it is on, I replaced batteries several times, but the Xbox does not respond to commands. The TV does - volume, channels, etc. - but I need the Xbox functionality.As far as I can see, there's no way to sync the remote with the Xbox - it lacks that small sync button that the game controllers have.I called Microsoft Support and spoke for an hour to someone who, I guess didn't know what to do at all. Bottom line - since it's been over a year, they won't fix/replace it - I have to get a new one.Before I do (if I do), I need to know if there's anything I can do with the existing remote, and will I have the same problem with a new one (i.e. the problem is with the Xbox itself)?
Thanks!

A: The Universal Media Remote relies on transmitting InfraRed (IR) signals to control devices, including your Xbox360.
Now, given that your remote still can control your TV, there might be a possibility that the IR receiver on your Xbox360 is kaput. Be ready for that...
I strongly suggest before running out to buy another remote, try removing any faceplates on the XBox360, or aiming the remote really near, or getting another remote to test first.
Good luck!

A: I found this post describing similar issues. Press the Xbox 360 Guide button, go to Settings. Select System Settings, Console Settings, then Remote Control. I think those names should be correct (or close), and the last thing should be to select Xbox 360 Media Remote.
I'm not at home so I'm not able to verify this right now, but it's worth a shot.

A: Mine just did the same thing and I just realized that it was upside down (hadn't turned it on in a very long time and just hooked it up how I had sat it on the shelf last).  When I turned it right side up, the remotes started working again. Try using the remote with the xbox in the upright and flat down positions.  The sensors may have a problem augmenting based on the way that the xbox it sitting.  It worked for me.

A: I just had a similar problem with my new Xbox 360 Slim and after some time, I figured out that the answer was in the console settings.  I documented to whole process http://www.urtech.ca/index.php/2010/12/how-to-sync-media-center-remote-to-xbox-360-slim-or-any-xbox-360-with-nov-2010-software-update/
I hope this helps!


text:
Q: AirConsole Game develoment - Control with Sprites? Im working on building my own game for AirConsole. I am using Unity, have imported all relevant assets and have begun my project.
So basically what I want is two different sprites to show up on the users controller depending on if they have not touched the screen, or have swiped up on the screen and are holding. So far all my research has showed very basic controllers with just buttons. Is this even possible?

A: Yes that's absolutely possible.
The controllers are written in HTML. Javascript and CSS are supported. So anything you can do in a mobile browser can be done in an AirConsole controller.


text:
Q: Library installation issues- rlang I have a new laptop that was working with R and R studio and then after updating packages I have run into continual issues loading or installing R packages in R studio.

*

*I have tried to uninstall R and R studio deleted all folders associated and then re-installed.

*removing and re-installing rlang however it keeps coming up as not properly installed.

*Checked my .libPath ()

My question is how do you make sure you have closed everything so you do not have any .dll file open and then therefore so that the installer can overwrite .dll? will this solve my issue?
Restarting R session...
> .libPaths()
[1] "C:/R-4.0.4/library"

> install.packages("rlang")
trying URL 'https://cran.rstudio.com/bin/windows/contrib/4.0/rlang_0.4.10.zip'
Content type 'application/zip' length 1181510 bytes (1.1 MB)
downloaded 1.1 MB

package 'rlang' successfully unpacked and MD5 sums checked

The downloaded binary packages are in
    C:\Users\dhiam\AppData\Local\Temp\RtmpuiHNNP\downloaded_packages
> tools::checkMD5sums("rlang")
[1] TRUE

> library(rlang)
Error: package or namespace load failed for 'rlang':
 .onLoad failed in loadNamespace() for 'rlang', details:
  call: NULL
  error: The rlang package is not properly installed.
The DLL version does not correspond to the package version.
Please update rlang to the latest version.
Updating packages on Windows requires precautions:
  <https://github.com/jennybc/what-they-forgot/issues/62>

> sessionInfo()
R version 4.0.4 (2021-02-15)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18363)

Matrix products: default

locale:
[1] LC_COLLATE=English_xx.1252  LC_CTYPE=English_xx.1252    LC_MONETARY=English_xx.1252
[4] LC_NUMERIC=C                       LC_TIME=English_xx.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
[1] compiler_4.0.4 tools_4.0.4    gtable_0.3.0   grid_4.0.4

Please also note, I do not have admin rights to this computer (as it is work laptop).


text:
Q: Is $\int |x\rangle \langle x|dx$ Mathematical? I am enrolling in a Quantum Mechanics class. As we all know, the formulation of the basic ideas from QM relies heavily on the notion of Hilbert Space. I decide to take the course since it might help me understand the motivation underlying the theory of unbounded operators.
However, things started to get confusing when the teacher introduced the inner product of the quantum states. Suppose there are two vectors $|\phi \rangle$,$|\psi \rangle$ represented by two column vectors $v$,$u$ respectively, he then defined their inner product to be
$$
\langle \psi  |\phi \rangle = \bar u^t v
$$
which makes perfect sense to me. He then went on to explain the continuous case by first introducing the thing called "completeness relation"
$$
1=\sum |i\rangle\langle i|
$$
where $|i\rangle$'s are the normalized eigenvectors of an Hermitian Operator. I, as the only math major in the class, recognize the term on the RHS as the projector into the subspace spanned by the orthonormal sequence $(|i\rangle)_{i=1}^\infty$, which is equal to identity since the sequence is complete.
He then went on to find a way to calculate $\langle \psi  |\phi \rangle$ in the case where $|\phi \rangle$,$|\psi \rangle\in L^2[-a,a]$, the so-called infinite square well. He said that since the state is continuous (whatever that means) the above summation approach an integration, so we have
$$
1=\int |x\rangle \langle x|dx
$$
instead. Then he demonstrated
$$\begin{align}
\langle \psi|\phi \rangle &= \langle \psi|1|\phi \rangle \\
&= \langle \psi|(\int |x\rangle \langle x|dx)|\phi \rangle \\
&= \int \langle \psi|x\rangle \langle x|\phi \rangle dx \\
&= \int \overline{\langle x|\psi\rangle} \langle x|\phi \rangle dx \\
&= \int \bar\psi(x)\phi(x) dx
\end{align}$$
, which makes very little sense to me. I had always seen the relation as THE definition of inner product in $L^2$ space, not something to be derived. When I asked him questions about the derivation he tried to justify it by saying something about Dirac's delta being an element of the Hilbert space (the irony) and the family of shifted Dirac's delta constitutes a basis (in some vague sense) of $L^2[-a,a]$.
While knowing that my teacher's statement makes little sense in the theory of Hilbert space, which is not untypical of a physicist by the way (This is not meant to be an accusation by any mean, I really respect him and he's a good physicist. However the word "physicist" and "rigor" are usually mutually exclusive), I've learned about existence of Rigged Hilbert space and heard that it partially resolve some foundational issues with using Dirac's delta in QM.
Here's my questions:
1.) I wonder if the notation $\int |x\rangle\langle x|dx$
has definite meaning in the Rigged Hilbert space?
2.) Could anyone please explain to me if the derivation is sound in ANY mathematical theory?
Note that I'm an undergraduate so I'd really appreciate some not-to-advanced answers :) Thank you in advance.
Edit: What does $\langle x|\phi \rangle = \phi(x)$ means anyway? At first I think it looks like the evaluation map but now I'm not quite sure.

A: Yes, this does make sense in the context of "rigged Hilbert spaces", e.g., something like what is occasionally called a Gelfand triple $H^{+1}\subset L^2\subset H^{-1}$ of Sobolev spaces on an interval in $\mathbb R$. Somehow Dirac had a wonderful intuition in this direction already prior to 1930. Also, the possibility of writing "integral kernels" for all mappings was eventually systematized into L. Schwartz' Kernel Theorem, and A. Grothendieck's nuclear spaces. Perhaps the most direct way to make things completely precise is as follows.
Let $L^2=L^2[a,b]$ be the usual space of square-integrable functions, which we know is also the completion of the space of test functions on $[a,b]$ with respect to the $L^2$ norm. Let $H^1=H^1[a,b]$ be the completion of test functions with respect to the (Sobolev) norm $|f|^2_{H^1}=\langle f-f'',f\rangle$. The injection $j:H^{-1}\to L^2$ has an adjoint $j^*$, and we identify $L^2$ with its own dual (but not the others!), obtaining $j^*:L^2\to H^{-1}$ where $H^{-1}=(H^1)^*$.
Dirac delta at a point $x_o$ in $[a,b]$ is provably in $H^{-1}$.
As a small part of some version of Schwartz' Kernel Theorem in this setting, with some vector-valued integral justification, the computation you quote is exactly the verification that the kernel for the identity map is "Dirac delta on the diagonal" in $[a,b]\times[a,b]$.
(The bra-ket notation can be rewritten in terms of tensors and tensor products if one desires, making it look less physics-y.)

A: Here is my understanding. But I know very little about QM, so this explanation may be incorrect.

Consider the multiplication operator $A$ defined on $L^2[-a, a]$ by
$$A\varphi(x) = x\varphi(x). $$
(In quantum mechanics, $A$ corresponds to the position operator.) Since this operator is bounded with the spectrum $\sigma(A) = [-a, a]$, by the spectral theorem there corresponds a projection-valued measure $E$ on $\sigma(A)$ such that
$$ A = \int_{[-a, a]} \lambda \, dE_{\lambda}. $$
This measure admits the resolution of the identity:
$$ 1 = \int_{[-a, a]} dE_{\lambda}. $$
Now heuristically, Dirac delta $\delta_{\lambda}$ is an eigenfunction of $A$ corresponding to the eigenvalue $\lambda$. Since we know that $E_{\lambda} = \mathbf{1}_{(-\infty, \lambda]}(A)$, we can think that $dE_{\lambda} \approx \mathbf{1}_{\{\lambda\}}(A)$ is a projection to the eigenspace corresponding to $\lambda$, which should be spanned by $\delta_{\lambda}$. Thus it is not unreasonable to carelessly write
$$ dE_{\lambda} \approx | \delta_{\lambda} \rangle\langle \delta_{\lambda} | \, d\lambda, $$
where $d\lambda$ comes from the normalization.


text:
Q: How to use jQuery in dynamically loaded elements? I have loaded 12
 elements first to web page and it has a description inside a . Other
 elements load when scrolling the page. I have used following jQuery to limit description text on div.
$(document).ready(function () {
        $("span.fine-print").html(function(index, currentHTML) {
            if (currentHTML.length > 200) {
                var str= currentHTML.substr(0, 200)+ '...
Read more
';
                return str;

            }
        });
    });

This jQuery works correctly for first 12
 elements, but it's not working after 12 elements. How to fix this issue. Is there any possibility to do this?

A: Check this :
Html

   hello hello hello hello hello hello hello hello hello

  hello hello hello hello hello hello hello hello hello

  hello hello hello hello hello hello hello hello hello

  hello hello hello hello hello hello hello hello hello

  hello hello hello hello hello hello hello hello hello

Jquery
$(document).ready(function () {
      $(".sp").html(function(index, currentHTML) {
       return changeContent(currentHTML);
    });
});

$(document).scroll(function() {
  var htmlStrng = "
hello hello hello hello hello hello hello hello hello
";
    var $contentStr = $(htmlStrng);
    var contentString = $contentStr.find('span').text();
    contentString = changeContent(contentString);
    $contentStr.find('span').html(contentString);
    $("#wrapper").append($contentStr);
    });

function changeContent(htmlStr){
    if (htmlStr.length > 20) {
            var str= htmlStr.substr(0, 20)+ '...
Read more
';
            return str;
        }
}

Demo Link
Check this :- https://jsfiddle.net/o3ntvbex/3/
Note : just for demo purpose. Not optimised code.

A: Just created a quick demo to demonstrate the fact that you need to do it each time your ajax call returns with more content.

function abridgeFinePrint(){
  $("span.fine-print").html(function(index, currentHTML) {
            if (currentHTML.length > 200) {
                var str= currentHTML.substr(0, 200)+ '...
Read more
';
                return str;

            }
        });
}

$(document).ready(function () {
    abridgeFinePrint();
    $('button').on('click', function(){
      $('#loading-indicator').show();
      //simulate ajax latency
      setTimeout(function(){
        $('#loading-indicator').hide();
        $('#template').clone().css({display: "block"}).appendTo('section');
        $('section div:last span').addClass('fine-print');
        abridgeFinePrint()
        }, 800);
      });
});
div {
  border: 1px solid #555;
  border-radius: 5px;
  padding: 15px;
  margin: 3px;
}

div:hover {
  background: #ddd;
}

#template,
#loading-indicator {
  display: none;
}

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

Loading...

<button>Load more divs</button>

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.