text:
Q: O365 API return all meetings for specific date including recurring meetings Is there an API query that will return all meetings for a specific date including recurring meetings from O365?

A: ../EWS/OData/Me/Events?$top=100&$filter=End ge 2014-06-06T22:30:00Z and Start le 2020-12-14T22:30:00Z
All times are in UTC.


text:
Q: Updating views within a single row of a ListView when clicked I was wondering how to update views/UI (say, making a TextView invisible) within a single row of a ListView when clicking on the row because every other rows' views would be affected as well. A good example would be playing a song in Google Play Music, and the equalizer animation would be displayed accordingly. Here are my snippets:
MainActivity's onCreate():
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main); // Renders only a ListView

    ListView songListView = (ListView) findViewById(R.id.list);
    List<Song> songList = new ArrayList<>();
    for (int i = 1; i <= 200; i++) songList.add(new Song("Song" + i, "Artist" + i));
    SongAdapter songAdapter = new SongAdapter(this, songList);
    songListView.setAdapter(songAdapter);
    songListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
            if (position == view.getId()) {
                TextView titleText = (TextView) view.findViewById(R.id.song_title);
                titleText.setVisibility(View.INVISIBLE);
            }
        }
    });
}

... and my ArrayAdapter's getView method and ViewHolder class:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;

    if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent,
                false);

        holder = new ViewHolder();
        holder.song = (TextView) convertView.findViewById(R.id.song_title);
        holder.artist = (TextView) convertView.findViewById(R.id.song_artist);

        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    convertView.setId(position);

    Song currentSong = getItem(position);

    if (currentSong != null) {
        holder.song.setText(currentSong.getTitle());
        holder.artist.setText(currentSong.getArtist());
    }

    return convertView;
}

private static class ViewHolder {
    TextView song;
    TextView artist;
}

A: Add one more variable in your song model class to make visibility for each row, please try this below code :
class Song{
    private boolean isShowing =false;

    public boolean isShowing() {
        return isShowing;
    }

    public void setShowing(boolean showing) {
        isShowing = showing;
    }
}

SongsAdapter.class
class SongAdapter extends BaseAdapter {
           private Context mContext;
           private List<Song> mSongList;

           public SongAdapter(Context context, List<Song> songs) {
               mContext = context;
               mSongList = songs;
           }

           @Override
           public int getCount() {
               return mSongList.size();
           }

           @Override
           public Object getItem(int i) {
               return null;
           }

           @Override
           public long getItemId(int i) {
               return 0;
           }

           @Override
           public View getView(final int position, View convertView, ViewGroup parent) {
               ViewHolder holder;

               if (convertView == null) {
                   convertView = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent,
                           false);
                   holder = new ViewHolder(convertView);

                   convertView.setTag(holder);
               } else {
                   holder = (ViewHolder) convertView.getTag();
               }

               final Song songModel = mSongList.get(position);
               holder.song.setText(songModel.getSongTitle());
               holder.artist.setText(songModel.getSongArtist());

               if(songModel.isShowing()){
                   holder.song.setVisibility(View.VISIBLE);
               }else{
                   holder.song.setVisibility(View.GONE);
               }
               convertView.setOnClickListener(new View.OnClickListener() {
                   @Override
                   public void onClick(View view) {
                       if(songModel.isShowing()){
                           songModel.setShowing(false);
                       }else{
                           songModel.setShowing(true);
                       }

                       notifyDataSetChanged();

                   }
               });
               return convertView;
           }

           public class ViewHolder{
               TextView song;
               TextView artist;

               public ViewHolder(View itemView) {
                   song = (TextView)itemView.findViewById(R.id.song_title);
                   artist = (TextView)itemView.findViewById(R.id.artist);

               }

           }
       }

A: Hope this helps:
holder.song.setId(position);

Then your code looks like this:
mSongView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
    Log.d(LOG_TAG, "Song item clicked");
    TextView titleText = (TextView) view.findViewById(position);
    titleText.setVisibility(View.INVISIBLE);

}
});

A: Add the below code in your adapter class
public interface OnItemClickListener {
void onClick(View view);}
private final OnItemClickListener listener;
public YourAdapter(Context mContext, OnItemClickListener listener) {
this.mContext = mContext;
this.listener = listener;}

Modify your viewholder class
class ViewHolder implements View.OnClickListener {

TextView song;
TextView artist;

ViewHolder(View itemView) {
    super(itemView);
    song = (TextView)itemView.findViewById(R.id.txt1);
    artist = (TextView)itemView.findViewById(R.id.txt2);
    itemView.setOnClickListener(this);

}

 @ Override
public void onClick(View v) {
    listener.onClick(v);
}

And lastly implement the interface in your Activity class
class MainActivity extends AppCompatActivity implements YourAdapter.OnItemClickListener{
 @Override
public void onClick(View view) {
   TextView titleText = (TextView) view.findViewById(R.id.song_title);
        titleText.setVisibility(View.INVISIBLE);
}

}

A: I finally figured this out after getting help from my mentor. Initializing an int field in the adapter to keep record of previous positions in the list did the trick as follows:
MainActivity:
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ListView songListView = (ListView) findViewById(R.id.list);
        List<Song> songList = new ArrayList<>();
        for (int i = 1; i <= 200; i++) songList.add(new Song("Song" + i, "Artist" + i));
        final SongAdapter songAdapter = new SongAdapter(this, songList);
        songListView.setAdapter(songAdapter);
        songListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
                songAdapter.setSongPosition(position);
                songAdapter.notifyDataSetChanged();
            }
        });
    }
}

Custom Song class:
public class Song {
    private String mSongTitle, mSongArtist;

    public Song(String songTitle, String songArtist) {
        mSongTitle = songTitle;
        mSongArtist = songArtist;
    }

    public String getSongTitle() {
        return mSongTitle;
    }

    public String getSongArtist() {
        return mSongArtist;
    }
}

Custom adapter:
public class SongAdapter extends ArrayAdapter<Song> {
    private int currentlyPlaying = -1;

    public SongAdapter(Context context, List<Song> songList) {
        super(context, 0, songList);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent,
                    false);

            holder = new ViewHolder(convertView);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        Song song = getItem(position);
        holder.song.setText(song.getSongTitle());
        holder.artist.setText(song.getSongArtist());

        // Hides the row, so both TextViews. Otherwise, sets each row visible.
        if (position == currentlyPlaying) convertView.setVisibility(View.INVISIBLE);
        else convertView.setVisibility(View.VISIBLE);

        return convertView;
    }

    private class ViewHolder {
        private TextView song;
        private TextView artist;

        private ViewHolder(View itemView) {
            song = (TextView) itemView.findViewById(R.id.song_title);
            artist = (TextView) itemView.findViewById(R.id.artist);
        }
    }

    public void setSongPosition(int position) {
        currentlyPlaying = position;
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: pass the address to a function and assign it to another variable    if ((pos < n) && (key == ptr->keys[pos].value))
        function(&ptr->keys[pos]);

here i need to pass the address of ptr->keys[pos] to function, and i have done it as shown above, i am calling this "function" inside another function
    inline struct return_values *function(struct classifier *fun_ptr)
    {
        struct return_values *r;
        r = malloc(sizeof(struct return_values));
        r->value1 = Duplicate;
        r->value2 = (void *)get;
        return r;
    }

the definition of function is as shown above i have to assign the address of ptr->keys[pos] to  r->value2
the structure return_values is as shown below
    struct return_values
    {
        KeyStatus_t value1;
        void* value2;
    }

how to assign the address of &ptr->keys[pos] to r->value2, i am able to pass the address to function form there how to assign that address to r->value2 and i dont want to change  structure return_value in any case as it will have effect my entire code please help.

A: Passing the address to fields of a struct can cause trouble depending on your runtime (and is bad style, but that's an opinion).
Instead of:
function(&ptr->keys[pos]);

*

*You should either pass the pointer to the struct:
function(ptr);
and let the function de-reference it (not encapsulated but flexible).

*or just call the function with the value stored inside that field, and assign to that field when the function returned like so:
ptr->keys[pos] = function(ptr->keys[pos]);


text:
Q: Create matrix with entries unique to row and column R I need to find all possible 5x5 matrix of integers 1-5 unique to each row and column (imagine a Sudoku) in R.
Is there any efficient way of doing this without creating all 120C5 matrices and then finding the fitting ones?
Thank you!

A: As I said in my comment above, matrices of this type are called Latin squares.
For a start, we already know that there are 56 so-called reduced Latin squares and 161280 all Latin squares of size 5. The reduced Latin squares are such that both the first column and the first row are just 1, 2, 3, 4, 5 (in this order). Given those reduced Latin squares, one may easily (as long as the size is not greater than 5) generate all Latin squares: permute all the rows except the first one and permute all the columns. Hence, as expected, 161280=5!*4!*56.
By restricting the first row and column one could generate 4!*3!*2!=288 matrices and check which 56 are Latin squares. However, I'm going to skip that and take their list from here.
First we read and rearrange the data
reduced <- read.table("http://users.cecs.anu.edu.au/~bdm/data/reduced5.txt", head = FALSE, colClasses = "character")
reduced <- lapply(1:nrow(reduced), function(r) matrix(as.numeric(unlist(strsplit(unlist(reduced[r, ]), ""))) + 1, 5))
length(reduced)
# [1] 56

Now let's generate all 5! and 4! permutations of 1, 2, 3, 4, 5 and 1, 2, 3, 4, respectively.
library(combinat)
perms5 <- permn(1:5)
perms4 <- permn(1:4)

Lastly, we go over all the reduced Latin squares and permute them in all possible ways
allLS <- sapply(reduced, function(m) {
  LS <- vector("list", gamma(6) * gamma(5))
  for(i in 1:gamma(5))
    for(j in 1:gamma(6))
      LS[[(i - 1) * gamma(6) + j]] <- m[perms4[[i]] + 1, perms5[[j]]]
  LS
})

Takes just a couple of seconds and we have the result
length(allLS)
# [1] 161280

It is easy to verify that they all are different
table(table(sapply(allLS, paste0, collapse = "")))
#      1
# 161280

and you could also check if they all are Latin squares.


text:
Q: How to detect hoveron button? c# devexpress I have 3 simple buttons from DevExpress. And I need no effects on hover. I was try to off it by ApperanceHovered but it's don't work.

I need to remove this blue hover effect.

A: Hi you simply can apply these changes to your button easily using these two lines of codes.
Set the button's FlatStyle to Flat
this.btnClose.FlatStyle = FlatStyle.Flat;

Set the button's MouseOverBackColor to Transparent
this.btnClose.FlatAppearance.MouseOverBackColor = Color.Transparent;

Hope this will help. Thanks


text:
Q: What are the reflection and transmission coefficients for two EM waves incident on a dielectric interface from opposite sides? I am aware of the derivation of the Fresnel reflection and transmission coefficients for a single plane wave incident on a planar interface between two dielectrics.
So I wondered what happens if there are two plane waves of the same frequency incident on a planar interface from opposite sides, with different angles of incidence, but in the same plane of incidence. I was not sure whether reflection and transmission of each wave can be treated independently, given by the same Fresnel coefficients as for a single incident wave. If this is indeed the case, can someone give a rigorous explanation/derivation?
Since I was not sure about this, I tried to derive the resulting electric fields from first principles, taking into account the usual interface conditions. Assume an EM wave 1 is incident with frequency $\omega$ in medium with refractive index $n_1$ from the left on the interface and wave 2 with frequency $\omega$ in medium with refractive index $n_2$from the right onto the interface. The angle of incidence for wave 1 is $\theta_{i1}$ and for wave 2 it is $\theta_{i2}$. I thought it would be natural to assume that there will be six waves propagating overall in this situation: The two incident waves, two waves propagating in the -z direction on the left side arising from reflection of wave 1 and transmission of wave 2 and two waves propagating in the +z direction on the right side arising from transmission of wave 1 and reflection of wave 2.
The coordinate system is set up such that the +z axis extends from left to right normal to the interface, the +y axis is "up" in the plane of incidence and the +x axis points into the page. For the wavevectors of these waves I get:
$$
\mathbf{k}_{i1} = k_{i1} (\sin\theta_{i1} \,\mathbf{\hat{y}}+ \cos\theta_{i1} \,\mathbf{\hat{z}})\\
\mathbf{k}_{r1} = k_{r1} (\sin\theta_{r1} \,\mathbf{\hat{y}}- \cos\theta_{r1} \,\mathbf{\hat{z}})\\
\mathbf{k}_{t1} = k_{t1} (\sin\theta_{t1} \,\mathbf{\hat{y}}+ \cos\theta_{t1} \,\mathbf{\hat{z}})
$$
and
$$
\mathbf{k}_{i2} = k_{i2} (\sin\theta_{i2} \,\mathbf{\hat{y}}- \cos\theta_{i2} \,\mathbf{\hat{z}})\\
\mathbf{k}_{r2} = k_{r2} (\sin\theta_{r2} \,\mathbf{\hat{y}}+ \cos\theta_{r2} \,\mathbf{\hat{z}})\\
\mathbf{k}_{t1} = k_{t2} (\sin\theta_{t2} \,\mathbf{\hat{y}}- \cos\theta_{t2} \,\mathbf{\hat{z}})
$$
If I then resolve the electric fields of the incident waves into a p-component (in the plane of incidence) and s-component (normal to the plane of incidence) and require that the parallel component of the electric field (so x- and y-components in my coordinate system) is continuous across the boundary where z=0, I arrive at the following equation:
$$
[E_{i1}^p \cos\theta_{i1} \,\mathbf{\hat{y}} + E_{i1}^s \,\mathbf{\hat{x}}]
\,e^{i(k_{i1}y\sin\theta_{i1} - \omega t)} +
[E_{r1}^p \cos\theta_{r1} \,\mathbf{\hat{y}} + E_{r1}^s \,\mathbf{\hat{x}}] \,e^{i(k_{r1}y\sin\theta_{r1} - \omega_{r1} t)} +
[E_{t2}^p \cos\theta_{t2} \,\mathbf{\hat{y}} + E_{t2}^s \,\mathbf{\hat{x}}] \,e^{i(k_{t2}y\sin\theta_{t2} - \omega_{t2} t)} = \\
[E_{i2}^p \cos\theta_{i2} \,\mathbf{\hat{y}} + E_{i2}^s \,\mathbf{\hat{x}}] \,e^{i(k_{i2}y\sin\theta_{i2} - \omega t)} +
[E_{r2}^p \cos\theta_{r2} \,\mathbf{\hat{y}} + E_{r2}^s \,\mathbf{\hat{x}}] \,e^{i(k_{r2}y\sin\theta_{r2} - \omega_{r2} t)} +
[E_{t1}^p \cos\theta_{t1} \,\mathbf{\hat{y}} + E_{t1}^s \,\mathbf{\hat{x}}] \,e^{i(k_{t1}y\sin\theta_{t1} - \omega_{t1} t)}
$$
This has to be fulfilled at all times and at all points on the interface, so for all y. I assumed this requires that all the exponentials are equal, in which case it follows that
$$
\omega_{r1} = \omega_{t1} = \omega_{r2} = \omega_{t2} = \omega
$$
as one might expect. However, it also leads to
$$
k_{i1}\sin\theta_{i1} = k_{i2}\sin\theta_{i2}
$$
which cannot be satisfied in general because I do not require the angles of incidence for the two waves to be the same and the k are fixed since $k_{1, 2} =\frac{n_{1, 2} \omega}{c}$. So the boundary conditions would impose a constraint that cannot be satisfied in general. How can this discrepancy be resolved?

A: The problem is linear so it reduces to two independent problems, each which can be solved using Fresnel's equations.


text:
Q: Do I need to configure the binding at both client and server? I am using NetNamedPipeBding to communicate with a service in local machine. I understand I need to define the configuration settings for client like maxstringcontentlength, sendtimeout, maxbyteperread etc.
Do I need to define the same things at server side as well? What is the relationship between these two? If the client doesn't have configuration settings while connecting to it, will it use its default binding settings? Are they totally independent?
For ex: I defined the below settings for client
    <netNamedPipeBinding>
            <binding name="NetNamedPipeBinding_IService" closeTimeout="00:01:00"
               openTimeout="00:03:00" receiveTimeout="00:10:00" sendTimeout="00:10:00"
               transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions"
               hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="2147483647"
               maxBufferSize="2147483647" maxConnections="10" maxReceivedMessageSize="2147483647">
              <readerQuotas maxDepth="32" maxStringContentLength="2147483647"
                  maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
              <security mode="None">
                <!--<transport protectionLevel="EncryptAndSign" />-->
              </security>
            </binding>
          </netNamedPipeBinding>

And I also defined at server side similar settings:
  <services>
      <service behaviorConfiguration="ServiceBehavior" name="Namespace.Service" />
    </services>

    <bindings>
      <netNamedPipeBinding>
        <binding name="NetNamedPipeBinding_Service" closeTimeout="00:01:00"
           openTimeout="00:03:00" receiveTimeout="00:10:00" sendTimeout="00:10:00"
           transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions"
           hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="2147483647"
           maxBufferSize="2147483647" maxConnections="10" maxReceivedMessageSize="2147483647">
          <readerQuotas maxDepth="32" maxStringContentLength="2147483647"
              maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
          <security mode="None">
            <!--<transport protectionLevel="EncryptAndSign" />-->
          </security>
        </binding>
      </netNamedPipeBinding>
    </bindings>

A: Some settings are relevant on both ends and some are relevant only on the server while some on client. Generally most settings should have same value and yes you need to configure the binding at both ends. One will not use the settings of other after connection is established.


text:
Q: How to calculate the total price after discount Now the price after discount is shown but I want to calculate the total price after the discount for 5 items at the end. I have used a for loop in this case
#include <stdio.h>
int main()
{
float price1,disc,total;
int i;
for (i=0;i<5;i++){

printf("\nEnter price of item : "); //to enter price of item
scanf("%f",&price1);
if(price1<50)
{
    disc=(price1*10)/100;
    total=price1-disc; //price after discount
    printf("$Item after discount is: %.2f\n",total);
}
else if(price1>=50 && price1<200)
{
        disc=(price1*20)/100; //to cal discount
        total=price1-disc; //price after discount
    printf("$Item after discount is: %.2f\n",total);

}
else if(price1>=200 && price1<=500)
{
        disc=(price1*25)/100; //to cal discount
        total=price1-disc; //price after discount
    printf("$Item after discount is: %.2f\n",total);
}
else if(price1>500)
{
        disc=(price1*30)/100; //to cal discount
        total=price1-disc; //price after discount
    printf("$Item after discount is: %.2f\n",total);
}

}

}

enter image description here

A: You can define an another float variable as total_price. And you can add a sum operation (total_price +=total;) to last line of the for loop. With this, At the end of each loop, you will have added the value to the total price. And finally, you can print the value after loop is finished.
Here:
#include <stdio.h>
int main()
{
float price1,disc,total;
int i;

float total_price=0;

for (i=0;i<5;i++){

printf("\nEnter price of item : "); //to enter price of item
scanf("%f",&price1);
if(price1<50)
{
    disc=(price1*10)/100;
    total=price1-disc; //price after discount
    printf("$Item after discount is: %.2f\n",total);

}
else if(price1>=50 && price1<200)
{
        disc=(price1*20)/100; //to cal discount
        total=price1-disc; //price after discount
    printf("$Item after discount is: %.2f\n",total);

}
else if(price1>=200 && price1<=500)
{
        disc=(price1*25)/100; //to cal discount
        total=price1-disc; //price after discount
    printf("$Item after discount is: %.2f\n",total);
}
else if(price1>500)
{
        disc=(price1*30)/100; //to cal discount
        total=price1-disc; //price after discount
    printf("$Item after discount is: %.2f\n",total);
}

total_price +=total;

}
printf("Your total price is: %.2f",total_price);

}


text:
Q: Unaligned subscripts in latex formula I am trying to write the below formula in latex, but as you can see the subscript for sigma is not aligned with the one for mu. This is caused by the square in alpha. How can I align them?

UPDATE: the formula is in inline mode, like this
$q_{\phi}(z|x_i) \sim \mathcal{N}(\mathbf{\mu}_{z|x_i}, \mathbf{\sigma}_{z|x_i}^2\mathbf{I})$

UPDATE2: thanks to the link sent by @AndrewSwann, the vphantom command makes the trick!
$q_{\phi}(z|x_i) \sim \mathcal{N}(\mathbf{\mu}_{z|x_i}^{\vphantom{2}}, \mathbf{\sigma}_{z|x_i}^2\mathbf{I})$

Thanks

A: If you want a boldface mu, the command \mathbf is useless (and you get a normal weight mu, as you see).
A boldface mu can be obtained with \bm{\mu}. As said in the comments, sigma should not be boldface.
For aligning the subscripts, add an empty superscript.
\documentclass{article}
\usepackage{amsmath}
\usepackage{bm}

\begin{document}

$q_{\phi}(z\mid x_i) \sim
\mathcal{N}(\bm{\mu}^{}_{z\mid x_i}, \sigma_{z\mid x_i}^2\mathbf{I})$

\end{document}

A: Just for completeness, here's a solution that employs LuaLaTeX and the unicode-math package.
Note that with unicode-math loaded, it's not necessary to load the bm package as well. The \symbf macro can be applied to both \mu and I.

% !TEX TS-program = lualatex
\documentclass{article}
\usepackage{unicode-math}
\begin{document}
\[
q_{\phi}(z\mid x_i) \sim \mathcal{N}
(\symbf{\mu}^{}_{z\mid x_i},
\sigma_{z\mid x_i}^2\symbf{I})
\]
\end{document}


text:
Q: Does a phrase "by itself" have to be gramatically correct We can have sentences which are not correct in posters and we forgive them.
I made a poster and was criticized for it.
It was (and this is the full sentence)
Including ghost hunting after hours.

I was told it should be
Including ghost hunt after hours.

Both read (sound) OK to me.
Is this actually correct or are both accepted?

A:
Including ghost hunting after hours.

As a phrase, this is grammatically correct (although some people, of a poetic bent, might find the repeated gerund "including...hunting" less than euphonious).

Including ghost hunt after hours.

Hunt (unlike hunting) is a countable noun, and as such, takes an article when appearing in the singular: "Including a ghost hunt after hours".  Without it, the phrase comes off as headlinese.
If this is just an advertisement, have you considered simply "Ghost hunting after hours!"?  (Arguably, even "after hours" is superfluous: no one goes ghost-hunting in the light of day.)

A: Regarding your NEW QUESTION dude ..
Does a phrase "by itself," such as an advertising headline, have to be grammatically correct?
the only meaningful answer is: it is incredibly well established, with literally millions of examples, that the headlines on advertising (whether 'billboards', 'magazine ads', etc) are -- observably -- usually (indeed "almost always"), simply sentence fragments rather than entire sentences.
So, your question "have to be" -- as in "SHOULD Saatchi & Saatchi ONLY USE full sentences (indeed, grammatically correct ones) for advert headlines...."
It's kind of a meaningless question.  I mean, I'm all for completely banning outdoor advertising, as in Sao Paolo.
Observably it is incredibly common - essentially, "the norm" - that poster headlines are in fact "sentence fragments".  Note too they are often very simply "labels".
(For example, the sign on a door "Exit" or "Toilet" is not a sentence - it's a label.)

A: Both are perfectly correct as the headlines on posters.
I think the second one sounds a little better - also it's shorter - but the person was totally wrong to tell you it is "grammatically incorrect".


text:
Q: Is there a way to make "holes" for parameters in bash commands that can then be "filled" at the end? eg "cp [hole] dir < [arg]" so arg comes at end? I'm not sure that the above makes sense, but a pattern I've noticed a lot in my shell usage is the following
I have a command which might be rather long, and due to the design of the CLI, there is a required order. I need to run the command multiple times, often varying a particular argument. of course if I know all the arguments up front I can use xargs or something, but sometimes that isn't the case... so I might have a command like
cli -flag -flag X arg arg arg arg
and rerunning it is annoying because I have to hop back to X. so what would be cool is to somehow do the following:
cli -flag -flag HOLE arg arg arg arg < X
that way if I want to alter the argument, I can press up and easily replace X
is this possible?

A:
if I know all the arguments up front I can use xargs or something, but sometimes that isn't the case

If you know all the arguments except the one that changes, make a function of it:
myfunc () { cli -flag -flag "$1" arg arg arg arg ; }

Then call that function with the changing argument.
Or you can use history expansion:
$ cli -flag -flag X arg arg arg arg    # Run the first time
$ ^X^Y            # will replace the first occurrence of X anywhere in the previous command with Y and run it
$ ^Y^Y2           # now replace Y with Y2 in the command that resulted from the above

Note that the history expansion doesn't discriminate - if you had my-command asterisk period comma colon and wanted to run my-command asterisk period apostrophe colon, you can't use ^comma^apostrophe because that will produce my-apostrophend asterisk period comma colon. A function would be better in this case.


text:
Q: Taking element that is not in given set I am reading a solution to a problem, where set $J$ is given and it is said that

Let us extend $J$ by one element $x∉J$ , $J′=J∪\{x\}$.

I can't understand where did we get this $x$ from? After thinking a bit I think there is Russel's Paradox (or perhaps its non-existence) is involved, I mean since $J$ is (perhaps) not set of all the sets, we can take an element from some set of all sets$-J$, but this argument seems silly.
I vaguely remember I read somewhere that we can go with assuming $x=J$ in this situation and $J'=J\ \cup\{J\}$ will do. Is this approach true?

A: Provided that your background theory includes

*

*The Axiom of Extensionality and

*The Axiom of Regularity
you can indeed take $x := J$ as a new element, i.e. we have $J \not \in J$ for all sets $J$. This is true for all commonly used set theories.
However, I'd also like to add that you're posing a valid question here. There are set theories in which such a choice for $x$ may not be possible. For example, in NF, the set of all sets, call it $V$, does exist and hence for $V$ there is no possible choice of $x$ with $x \not \in V$. Note that, while it has extensionality, NF does not and cannot have the axiom of regularity for the reasons outlined above.


text:
Q: What CMS would you use to recreate slashdot's distributed moderation system? Total, embarassing noob here, so here goes nothing: if you wanted to create a karma-based reputation system that treated user comments pretty much the way Slashdot does, but slashcode had never been invented, how would you go about it? Is there an OpenSource CMS that comes close to doing this?

A: Why not use the real deal?
Edit:
Somehow I missed the comment in the middle about Slashcode.  Sorry.
I'm still curious why you wouldn't use Slashcode, but what I'd probably do is give moderation to all logged-in users but give their moderation weighted values depending on their involvement and something akin to meta-moderation.
Thinking about it, SO and /. aren't that dissimilar in their community ranking strategies.  Karma and involvement having a lot to do with how often you receive moderation points....
Extracted from comments:
Vanilla with the Community Moderation add-on may be a good place to start.

A: Coming from the perspective of a software engineer, I would likely pick up PHP, MySQL, and a good development framework, and have at it.
It usually doesn't take to long to get a system to a working state if you know exactly what you need it to do. And the plus is that you get exactly what you want.
With open source tools like PHP and MySQL available, you are already so much of the way there that it may be easier to hand-code what you need rather than learning how to make X framework do it for you.


text:
Q: Get follower count on Twitter API search results What I'm trying to do is pull some search results, and sort them by users.
Right now I'm using
$to->OAuthRequest('http://search.twitter.com/search.json', array('q' => 'search-term'), 'GET');
to get the results, but I can't actually get information about the user like follower_count, etc. so I though I'd take each result's user_id, and run it through http://twitter.com/users/show.xml to get the rest of the information.
The problem is, if I get 50 results that way, that's 50 API calls, which is 1/3 of the hourly limit...
Is there a better way to do this?

A: Update:
I have requested whitelisting, and the guys at Twitter told me I should instead use the new Streaming API.
This kinda sucks since it's in Alpha testing, and the documentation is unclear, but the concept looks cool, and the limits are different than the regular API. Gonna dive into it later.

A: Only reliable user information you can get from twitter search results are username (from_user) and profile image url. If you want more information, you will have to call the users/show method for each user. There is no workaround or better way(that I'm aware of).
You will have to Cache user information and request whitelisting.


text:
Q: Avoiding a big data redirect in MVC without using TempData Problem:

*

*You have a custom controller action, which modifies a large amount of data (around 5MB).

*You need to pass this data to another controller action, which you are NOT allowed to modify.

What's the best way to do this?
A normal RedirectToAction would result in a huge data post.
TempData can't be used as a workaround as you cannot modify the other controller to read the tempdata.
[HttpPost, ActionName("Import")]
    public ActionResult ImportPost(int id)
    {
    var bigData = GetBigData(id);
    bigData = ManipulateBigDataIntoFormatOtherControllerUnderstands(bigData);

    // TODO: redirect to other controller (which has HttpPost attribute), somehow??
}

A: Nevermind, came up with an answer right after posting:
var c = new Namespace.Controllers.OtherController();
c.ControllerContext = ControllerContext;
return c.Action(bigData);


text:
Q: Adobe AIR Security Error loading .swf with RSS I'm trying to load an swf file using SWFLoader in Adobe AIR app. The problem is that after the swf loads, Adobe AIR shows me the following error. I know that this swf tries to download an RSS file from the web.

SecurityError: Error #2028: Local-with-filesystem SWF file file:///xfile.swf cannot access Internet

How can i fix it? Does anyone have any idea?
Thanks,

A: In AIR SWFs that are loaded from outside of the contents of the AIR file get put into a sandbox.  You need to include the SWF file you are loading in your AIR file.  If that is not possible then you will need to make sure that the loaded SWF doesn't try to get outside the sandbox.  Read more about the AIR sandbox:

*

*Introducing the Adobe AIR security model

*AIR Security - Sandboxes


text:
Q: how do I get the post method for a website that doesn't provide posts in python? I want to get data in the form of a list on the website https://gmail.inputekno.com/ by scraping
but when I check, the website doesn't provide post requests, is there a way to work around this? thx u

I have tried like this but failed
import requests

cookies = {
    '_ga': 'GA1.1.1869494453.1672283765',
    '__gads': 'ID=e350f661fb3c1b6a-22c8b78c11d900b8:T=1672283764:RT=1672283764:S=ALNI_MYcfleQdj417a3BQakIyzzrp83MdQ',
    '__gpi': 'UID=00000b9a196b924e:T=1672283764:RT=1672283764:S=ALNI_MZ4UaRvjE4GzR-k0Na5Jj-HBksD4w',
    '_ga_R3D1879B9V': 'GS1.1.1672283764.1.1.1672284364.0.0.0',
}

headers = {
    'authority': 'gmail.inputekno.com',
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'accept-language': 'en-US,en;q=0.9',
    'cache-control': 'no-cache',
    # 'cookie': '_ga=GA1.1.1869494453.1672283765; __gads=ID=e350f661fb3c1b6a-22c8b78c11d900b8:T=1672283764:RT=1672283764:S=ALNI_MYcfleQdj417a3BQakIyzzrp83MdQ; __gpi=UID=00000b9a196b924e:T=1672283764:RT=1672283764:S=ALNI_MZ4UaRvjE4GzR-k0Na5Jj-HBksD4w; _ga_R3D1879B9V=GS1.1.1672283764.1.1.1672284364.0.0.0',
    'pragma': 'no-cache',
    'sec-ch-ua': '"Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"',
    'sec-ch-ua-arch': '""',
    'sec-ch-ua-bitness': '"64"',
    'sec-ch-ua-full-version-list': '"Not?A_Brand";v="8.0.0.0", "Chromium";v="108.0.5359.125", "Google Chrome";v="108.0.5359.125"',
    'sec-ch-ua-mobile': '?1',
    'sec-ch-ua-model': '"Nexus 5"',
    'sec-ch-ua-platform': '"Android"',
    'sec-ch-ua-platform-version': '"6.0"',
    'sec-ch-ua-wow64': '?0',
    'sec-fetch-dest': 'document',
    'sec-fetch-mode': 'navigate',
    'sec-fetch-site': 'none',
    'sec-fetch-user': '?1',
    'upgrade-insecure-requests': '1',
    'user-agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Mobile Safari/537.36',
}

payload : { 'username':'danielmantha'}
response = requests.post('https://gmail.inputekno.com/', cookies=cookies, headers=headers,data=payload)

A: As CharlesHan commented,

There is no POST because the emails are generated by their Javascript code. https://cdn.jsdelivr.net/gh/rulnoveid/CodeBlog@main/gmail%20trick/trick.js

So, there's no way to scrape this particular data with requests-based methods.

If you really wanted to, there's selenium [and other web-automation tools]. You could use scrapeGmailDotTrix [short version below] - e.g., calling scrapeGmailDotTrix('somename') will scrape and return a list of the generated emails from the site after entering somename in the input.
### full version at https://pastebin.com/tgC4EpGZ
## YOU MUST DOWNLOAD CHROMEDRIVER.EXE FOR THIS ##
## https://chromedriver.chromium.org/downloads ##

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def scrapeGmailDotTrix(username: str, wait_start=10, wait_op=200):
    driver = webdriver.Chrome()
    driver.get('https://gmail.inputekno.com/')

    WebDriverWait(driver, wait_start).until(
        EC.visibility_of_element_located((
            By.XPATH, '//input[@id="username"][@type="text"]')))

    driver.find_element(
        By.XPATH, '//input[@id="username"][@type="text"]'
    ).send_keys(str(username))

    WebDriverWait(driver, wait_op).until(
        EC.text_to_be_present_in_element_value(
            (By.XPATH, '//textarea[@id="emails"]'),
            '.'.join(str(username))))

    return [em.strip() for em in driver.find_element(
        By.XPATH, '//textarea[@id="emails"]'
    ).get_attribute('value').splitlines()]

[The full version has error-handling and precautionary waits to load input, etc.]
However, if you just want to generate emails the same way, this method is unnecessarily convoluted.

In contrast, the main JavaScript logic is fairly simple to replicate with python:
def gmailTrix_gen(uname:str):
    if len(uname) > 1:
        head, tail = uname[0], uname[1:]
        for item in gmailTrix_gen(tail):
            yield head + item
            yield head + '.' + item
    else: yield uname

def gmailTrix_list(username:str):
    return [f'{gu}@gmail.com' for gu in gmailTrix_gen(username)]

For example, gmailTrix_list('rand') will return (just like the site):

['rand@gmail.com', 'r.and@gmail.com', 'ra.nd@gmail.com', 'r.a.nd@gmail.com',
 'ran.d@gmail.com', 'r.an.d@gmail.com', 'ra.n.d@gmail.com', 'r.a.n.d@gmail.com']


text:
Q: SQL Server show distinct values from one column and count number of entries for each distinct I'm trying to show each unique value from column A with a count of how often each value appears ignoring where it has a value of null in column B
I.e
Column A     Column B
1              56
1              null
1              78
2              null
3              54

I would want a return that looked something like
1    2
3    1

A: You should make use of GROUP BY on ColumnA, and selecting those records for which ColumnB is not NULL. The following script accomplish your request, i've included some explanations after it
CREATE TABLE Test(ColumnA INT, ColumnB INT)

INSERT INTO Test(ColumnA, ColumnB) VALUES (1, 56),
                                          (1, null),
                                          (1, 78),
                                          (2, null),
                                          (3, 54)

SELECT ColumnA, COUNT(*)
FROM TEST WHERE ColumnB IS NOT NULL
GROUP BY ColumnA

DROP TABLE Test

The part of interest is the SELECT instruction. The rest of the script is only for the creation and population of a simple table, like the one you're talking about.
Please note the SELECT is made on ColumnA, and that column is also used in the GROUP BY clause. That means we want to extract single values from ColumnA, in order to select other columns, aggregating them in some way.
That specific aggregation , i.e. the occurence of the values of ColumnB, is made by the aggregate function COUNT(), which tells to extract the number of those records that matches the grouped column. In our case, COUNT() counts the amount of record for each value of ColumnA.
But since you want to exclude those records that have a NULL value for ColumnB, we simply exclude them from the selection through the WHERE clause: as you can see, i'm asking for those records where ColumnB IS NOT NULL.
That way, and using the sample data you've posted, we'll obtain exactly what you expected:
1    2
3    1


text:
Q: Spring Web Mvc jQuery AJAX call with post not bidinding from with @ModelAttribute I am trying to send an AJAX call with jquery to a spring web mvc application. I have a modal which contains a form:

    <form id="frmEditTileModal" modelAttribute="editTile" class="floating-labels " action="/DESSOApplicationPortalAdmin/rest/tile/002" method="POST">

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Edit Tile

                            <input type="text" class="form-control" id="editTileId" name="id" required>
                            Id

                            <input type="text" class="form-control" id="editTileDescription" name="description" required>
                            Description

                            <input type="text" class="form-control" id="editTileRole" name="role" required>
                            Role

                            <input type="text" class="form-control" id="editTileTarget" name="target" required>
                            Target

                            <input type="text" class="form-control" id="editTileIndex" name="index" required>
                            Index

                            <input type="text" class="form-control" id="editTileTileimagename" name="tileImageName" required>
                            Tile Image Name

                            <input type="text" class="form-control" id="editTileUrl" name="url" required>
                            Url

                                <input type="checkbox" class="custom-control-input">

                                Disable Tile

">

Tile Image Normal

                                You can add a default value
                                <input type="file" id="img-tile-normal" class="dropify" data-default-file="resources/vendor/plugins/bower_components/dropify/src/images/test-image-1.jpg" />

Tile Image on Hover

                                You can add a default value
                                <input type="file" id="img-tile-on-hover" class="dropify" data-default-file="resources/vendor/plugins/bower_components/dropify/src/images/test-image-1.jpg" />

            <button type="button" class="btn btn-default waves-effect" data-dismiss="modal">Close</button>
            <button id="btnSaveEditTile" type="submit" class="btn btn-danger waves-effect waves-light">Save changes</button>

    </form>

This is the jQuery
       $('#frmEditTileModal').submit(function (e) {
        e.preventDefault();
        alert("save edit start!");

        var editSuccesFunc = function () {
            alert('Success Edit!');
        };
        var editErrorFunc = function () {
            alert('Error Edit!');
        };

        var tileId = $('#editTileId').val();
        alert("data to send: " + $('#editTileId').val());

        var formData = new FormData();
        formData.append("id", $('#editTileId').val());
        formData.append("description", $('#editTileDescription').val());
        formData.append("role", $('#editTileRole').val());

        $.ajax({
            type: "POST",
            url: "/DESSOApplicationPortalAdmin/rest/tile/" + tileId,
            data: $('#frmEditTileModal').serialize(),
            contentType: "application/json",
            dataType: "json",
            success: editSuccesFunc,
            error: editErrorFunc
        });
    });

and this is the java controller:
    @RestController
    @RequestMapping(value = "rest/tile")
public class TileRestController {

    @Autowired
     TileService tileService;

    @RequestMapping(value = "/{tileId}", method = RequestMethod.GET)
       public Tile getProductById(@PathVariable(value = "tileId") String tileId) {
        System.out.println("------------->" + this.getClass().getSimpleName() + ": getProductById called. Searching for Tile Id " + tileId);
        return tileService.getTileById(tileId);
    }

    @RequestMapping(value = "/{tileId}", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public  Tile update( @ModelAttribute("editTile") Tile tile, @PathVariable(value = "tileId") String tileId) {
        Tile updatedTile = new Tile();
        //updatedTile.setId("099");
        //updatedTile.setDescription("ExampleTile");

        System.out.println("------------->" + this.getClass().getSimpleName() + " update method: print object fields: "+tile.toString());
        return updatedTile;
       //return tileService.updateTile(tile);

    }
}

When I try a doing a normal submit (no ajax or jquery) the controller correctly reads the field to the object.
However when, I try doing the same as an ajax call, it correctly sends the data but the controllers does not map it to an object via modelAttribute("editTile"). Here is a print of the class:

------------->TileRestController update method: print object fields: Tile{ tileImageName=null, description=null, role=null, url=null, target=null, index=0, id=null, disabled=false}

Am I missing something?
EDIT:
I tried a suggestion made in the answers, but it did not seem to work. Here is what I did:
I change the code of the update method in order to use the @RequestBody annotation
@RequestMapping(value = "/{tileId}", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public  Tile update( @RequestBody Tile tile, @PathVariable(value = "tileId") String tileId) {
    Tile updatedTile = new Tile();
    //updatedTile.setId("099");
    //updatedTile.setDescription("ExampleTile");

    System.out.println("------------->" + this.getClass().getSimpleName() + " update method: print object fields: "+tile.toString());
    return updatedTile;
   //return tileService.updateTile(tile);

}

plus, I changed my content type as well for the ajax call:
$.ajax({
            type: "POST",
            url: "/DESSOApplicationPortalAdmin/rest/tile/" + tileId,
            data: $('#frmEditTileModal').serialize(),
            contentType: "application/www-form-url-encoded",
            dataType: "json",
            success: editSuccesFunc,
            error: editErrorFunc
        });

however, now I get an ajax error, it it does not even make the call:

A: You seem to be Posting a JSON (content-type: application/json) from ajax.
Try using @RequestBody instead of @ModelAttribute for the Tile.
A FORM post normally gets post'ed as content-type: application/www-form-url-encoded.


text:
Q: Accessing the length of a variable in a dataset Is it possible to find the length of a variable in a dataset ? My dataset name is 'usairports' and I want to find the length of the 'ownership' variable.
length(usairports("ownership")

I tried this but it gave me the wrong output.
Thank you!

A: Please try
length(usairports$ownership)

or

length(usairports[['ownership']])


text:
Q: QT C++ Connect signals from derived classes I am working on a class that has two parent classes:
GetSetInterface which derives QObject and
QSpinBox(which derives QObject aswell)
And I Call it SpinBoxInterface
class GetSetInterface : public QObject
class SpinBoxInterface : public QSpinBox, public GetSetInterface

In the constructor of SpinBoxInterface I am trying to connect signal QSpinBox::valueChanged(int) to the signal GetSetInterface::sendInfo(int, QVariant), and here comes a problem:
When I write (of course in SpinBoxInterface class)
connect(this, QOverload<int>::of(&SpinBoxInterface::valueChanged), this, [=](int value){
        emit sendInfo(TYPE_ANYCHANGE, value);
    });

I Get an error non-static member 'connect' found in multiple base-class subobjects of type 'QObject',
However, when I write
GetSetInterface::connect(this, QOverload<int>::of(&SpinBoxInterface::valueChanged), this, [=](int value){
        emit sendInfo(TYPE_ANYCHANGE, value);
    });

I get an error
ambigious conversion from derived class 'AxisSpinBox' to base class 'const QObject'. As long as I understand the first error ('connect found in multiple base-classes'), the second one feels weird, as GetSetInterface::connect has only one parent class, from where to get definition of connect - and it is only one QObject.
#define TYPE_ANYCHANGE 0 is used in a methods above


text:
Q: pandas.Series.drop_duplicates for picking a single value from a subpart of a column I have a DataFrame df filled with rows and columns where there are duplicate Id's:
Index   A   B
0   0.00    0.00
1   0.00    0.00
29  0.50    105.00
36  0.80    167.00
37  0.80    167.00
42  1.00    209.00
44  0.50    105.00
45  0.50    105.00
46  0.50    105.00
50  0.00    0.00
51  0.00    0.00
52  0.00    0.00
53  0.00    0.00

When I use:
    df.drop_duplicates(subset=['A'], keep='last')

I get:
Index   A   B
37  0.80    167.00
42  1.00    209.00
46  0.50    105.00
53  0.00    0.00

Which makes sense, that's what the function does. However, what I actually would like to achieve is something like:
Index   A   B
1   0.00    0.00
29  0.50    105.00
37  0.80    167.00
42  1.00    209.00
46  0.50    105.00
53  0.00    0.00

Basically from each subpart of column A (0,0), (0.80, 0.80), etc. To pick the last value.
It is also important the values in column A stay in this order 0; 0.5; 0.8; 1; 0.5;0 and they do not get mixed.

A: Compare by not equal Series.ne with Series.shift and filter by boolean indexing:
df1 = df[df['A'].ne(df['A'].shift(-1))]
print (df1)
         A      B
Index
1      0.0    0.0
29     0.5  105.0
37     0.8  167.0
42     1.0  209.0
46     0.5  105.0
53     0.0    0.0

Details:
print (df['A'].ne(df['A'].shift(-1)))
Index
0     False
1      True
29     True
36    False
37     True
42     True
44    False
45    False
46     True
50    False
51    False
52    False
53     True
Name: A, dtype: bool


text:
Q: Find location of pair of elements in two arrays in numpy I have two numpy arrays x and y
Suppose x = [0, 1, 1, 1, 3, 4, 5, 5, 5] and y = [0, 2, 3, 4, 2, 1, 3, 4, 5]
The length of both arrays is the same and the coordinate pair I am looking for definitely exists in the array.
How can I find the index of (a, b) in these arrays, where a is an element in x and b is the corresponding element in y. For example, the index of (1, 4) would be 3: the elements at index 3 of x and y are 1 and 4 respectively.

A: You could use numpy.where combined with numpy.logical_and if you want a purely numpy solution:
In [16]: import numpy as np

In [17]: x = np.array([0, 1, 1, 1, 3, 4, 5, 5, 5])

In [18]: y = np.array([0, 2, 3, 4, 2, 1, 3, 4, 5])

In [19]: np.where(np.logical_and(x == 1, y == 4))[0]
Out[19]: array([3], dtype=int64)

numpy.logical_and allows you to element-wise perform a logical AND operation between two numpy arrays.  What we're doing here is determining which locations contain both the x values being 1 and the y values being 4 in the same corresponding locations.  Those locations that satisfy this are True.  numpy.where determines the locations in the array where this condition is satisfied.  numpy.where actually returns both row and column locations of where the condition is True separately as a tuple of two elements, but as we are only considered with one dimension, only the first tuple is valid which is why we immediately index the first element of the tuple.
The output is a numpy array of locations where the condition is valid.  You can even go further and coerce the output to be a list of indices to make things neater and/or if it is required (thanks @EddoHintoso):
In [20]: list(np.where(np.logical_and(x == 1, y == 4))[0])
Out[20]: [3]

A: You could compare your first array with the first value, second array with the second value and then find where both True. Then you could get that True with argmax which will give you first index of the first True occurence:
x = np.array([0, 1, 1, 1, 3, 4, 5, 5, 5])
y = np.array([0, 2, 3, 4, 2, 1, 3, 4, 5])
idx = ((x == 1) & (y == 4)).argmax()

In [35]: idx
Out[35]: 3

In [36]: x == 1
Out[36]: array([False,  True,  True,  True, False, False, False, False, False], dtype=bool)

In [37]: y == 4
Out[37]: array([False, False, False,  True, False, False, False,  True, False], dtype=bool)

If you could have multiple occurence you could use following using nonzero:
idx_list = ((x == 1) & (y == 4))
idx = idx_list.nonzero()[0]

In [51]: idx
Out[51]: array([3], dtype=int64)

Or if you need list of indices:
In [57]: idx_list.nonzero()[0].tolist()
Out[57]: [3]

You could do that in one line with:
idx = ((x == 1) & (y == 4)).nonzero()[0]

A: x = [0, 1, 1, 1, 3, 4, 5, 5, 5]
y = [0, 2, 3, 4, 2, 1, 3, 4, 5]
w=zip(x,y)
w.index((1,4))


text:
Q: Double integral of product of Bessel functions in Python I would like to perform a numerical integral (in Python) of the form
$$\displaystyle F_\nu(k) = \int_0^\infty dk' \ k' \int_0^\infty dr\ r \ f(k', r) \ J_\nu(k' r) \ J_\nu(k r),$$
where $J_\nu$ is the $\nu$-th order Bessel function of the first kind.
Moreover, note that the Bessel functions form an orthogonal basis with respect to the weighting factor $r$, i.e.
$$ \int_0^\infty dr \ r \ J_\nu(k'r) \ J_\nu(kr) = \frac{\delta(k' - k)}{k}, \quad k,\ k'>0,$$
where $\delta$ is the Dirac delta.
Although this is not impossible by naively performing this integral in Python, it takes a long time to evaluate. However, given the fact that the Bessel functions form an orthogonal basis, and since since this form somewhat resembles a Hankel transform (for which packages are available that perform an order of magnitude better than their naive counterparts) I was hoping there might be faster way to evaluate this integral.
Any ideas on how to tackle this integral?

A: $$
\int_0^\infty k' dk' \int_0^\infty r dr f(k',r) J_\nu (k' r) J_\nu (kr)\\
f(k',r) = \int_0^\infty k'' dk'' F_\mu (k',k'') J_\mu (k'' r)\\
\int_0^\infty k' dk' \int_0^\infty r dr \int_0^\infty k'' dk'' F_\mu (k',k'') J_\mu (k'' r) J_\nu (k' r) J_\nu (kr)\\
$$
Where we have substituted $F_\mu(k',k'')$ which is a Hankel transformation of $f(k',r)$
The integral
$$
D((m,\gamma),(m',\gamma'),(m'',\gamma'')) \equiv \int_0^\infty r dr J_m (\gamma r) J_{m'} (\gamma' r) J_{m''} (\gamma '' r)
$$
was studied in Auluck for integer orders.
So assuming I can Fubini the $r$ and $k''$ integrals
$$
\int_0^\infty k' dk' \int_0^\infty k'' dk'' F_\mu (k',k'') \int_0^\infty r dr J_\mu (k'' r) J_\nu (k' r) J_\nu (kr)\\
$$
I'm assuming $\nu$ is an integer now.
$$
\int_0^\infty k' dk' \int_0^\infty k'' dk'' F_\mu (k',k'') D((\mu ,k''),(\nu,k'),(\nu,k))\\
$$
Some examples of $D$ have exact solutions. For example,
$$
D((0,\gamma),(m',\gamma'),(m',\gamma''))
$$
is at the bottom of page 6. But that gets you some expression in Legendre functions and $\frac{k^2+k'^2-k''^2}{2kk'}$, so I don't know how useful that will be.
You could use the approximation on page 24 which gives you an approximation to $D$ as a distribution on $k''$ for smooth weight functions which would hopefully include $F_\mu (k',k'')$. Note however, that formula is not proven there.


text:
Q: ExtJS: wrapping pre-existing div into Extjs container I wonder if there's a method of creating an Extjs container or a panel with the contents taken from a pre-existing element in the page DOM. The page already contains the needed markup in a div, but i'd like to wrap it inside an extjs container and place it into Extjs managed layout.
If you ask why: I'm using ASP.Net MVC templating for creating page markup and would like to keep it this way instead of building the DOM client-side in Javascript or using XTemplates. I'd like to build the html in traditional way and then use client-side Extjs code to set up few containers and layout manager for them.

A: You can use contentEl config property. In this config you can specify an existing HTML element, or the id of an existing HTML element to use as the content for component.
HTML inside body:
<div id="panelContent">
    Content inside panelContent div
</div>

ExtJS panel with div used as its content:
Ext.create('Ext.panel.Panel', {
    title: 'Test Panel',
    width: 200,
    contentEl: 'panelContent',
    renderTo: Ext.getBody()
});

Fiddle with live example: https://fiddle.sencha.com/#fiddle/2ji


text:
Q: Promise not working in React useEffect in combination with Firebase I want to get data from firebase inside a useEffect function like this:
  useEffect(() => {
   /** nope */
   async function fetchData() {
     let dataObject = {};
     let dataArray = [];
     setAttendees({});

     // You can await here
     if (newData[listRedux]) {
       const request = await Object.keys(newData[listRedux] .
       [1].attendees).map(
         user => {
           usersRef.child(user).on('value', snap => {
             dataObject[snap.key] = snap.val();
             setAttendees(dataObject);
             console.log(dataObject);
             let comp = (
               <Avatar
                 key={snap.key}
                 size="small"
                 source={snap.val().avatar}
                 alt={snap.val().name}
               />
             );
             dataArray.push(comp);
             setAttendeesComp(dataArray);
           });
         }
       );

       // Wait for all requests, and then setState
       await Promise.all(request).then(() => {
         console.log('done');
       });
     }
   }
   fetchData();
 }, [newData, listRedux]);

Now the second console.log inside the promise all will first show then the first console.log, meaning the request was not done yet.
How can i improve my code so the request and the states are first being set and then continue with the rest?

A: export default function Example() {
    const [data, dataSet] = useState(false)
    const [attendees, setAttendees] = useState(false)

    async function fetchMyAPI() {
      let response = await fetch('api/data')
      response = await res.json()
      console.log(response);
      dataSet(response)
    }

 useEffect(() => {
      if (!attendees) return
      fetchMyAPI();
    }, [attendees, newData, listRedux]);

useEffect(() => {
     setAttendees({})
  }, [])

More examples here:


text:
Q: What is gssapi-with-mic? Debugging a Nagios warning on ssh, I've discovered that gssapi-with-mic is causing long lags in authentication. I've turned it off, but what exactly am I missing? I gather that GSSAPI is a tool for authentication, but what about the -with-mic part?

A: The fix is simple: disable attempts to use GSS-API by adding the following to ~/.ssh/config:
GSSAPIAuthentication no

A: Message Integrity Code.
This is also called a Message Authentication Code, but that acronym gets used for other things, so MIC is less ambiguous.  From that Wikipedia page:

The term message integrity code (MIC) is frequently substituted for the term MAC, especially in communications, where the acronym MAC traditionally stands for Media Access Control.

A: GSSAPI Authentication is typically used with Kerberos.  Kerberos must be configured on both the server and client.  If you are not using Kerberos, then you probably do not need it.  If you are just using password or SSH keys to log in to your server you likely do not need GSSAPI, and you can disable it in the sshd_config file.
Set in the /etc/ssh/sshd_config
GSSAPIAuthentication no
As for the "with-mic" part, there are two authentication methods for GSSAPI; with-mic and -keyex.  The MIC stands for message integrity code.  And from what I gather from reading the RFC-4462 it is generated by the client using many of the agreed upon connection parameters and is hashed several times.  Read more


text:
Q: FInd in array and output whole array? Array ( [feature class] => L
        [feature code] => RGN
        [country code] => ES
        [admin1code] => 00
        [admin2code] => CO
        [geonameid] => 2521750 )

Array ( [feature class] => A
        [feature code] => ADM1
        [country code] => ES
        [admin1code] => 51
        [admin2code] => [geonameid] => 2593109 )

Array ( [feature class] => S
        [feature code] => GDN
        [country code] => ES
        [admin1code] => 60
        [admin2code] => A
        [geonameid] => 10290879 )

Here are my 3 print_r arrays. How hot check which one has this: [feature code] => ADM1 and then from that array output this : [country code] => ES [admin1code] => 51
P.S
Here is my array.
Array ( [0] => Array ( [feature class] => L [feature code] => RGN [country code] => ES [admin1code] => 00 [admin2code] => CO [geonameid] => 2521750 ) [1] => Array ( [feature class] => A [feature code] => ADM1 [country code] => ES [admin1code] => 51 [admin2code] => [geonameid] => 2593109 ) [2] => Array ( [feature class] => S [feature code] => GDN [country code] => ES [admin1code] => 60 [admin2code] => A [geonameid] => 10290879 ) )

I did: foreach ($array as $key => $value)
Now how do I find which array has in it this: [feature code] => ADM1 and output it's all data?

A: Let's say the 3 arrays are named as follows: $arr1, $arr2, and $arr3. Put them all into 1 array and loop through to check:
$all = [$arr1, $arr2, $arr3];
foreach ($all as $a) {
    if ($a['feature code'] === "ADM1") $result = $a;
}
print_r($result);


text:
Q: Determining conditions on two circles inscribed in square so that a tangent rectangle has integer area In the accompanying figure, all seven contact points are tangential. It can be verified that if the areas of the major and minor circles, noted $A$ and $a$, are respectively equal to $8\pi$ and $2\pi$ then the area of the blue rectangle is equal to $7$.

Can you find without much work necessary and sufficient conditions between the areas $A$ and $a$ so that the area of the blue rectangle is an integer? Or would it be too difficult?

A: If the radii of the circles are $r$ and $R$, then the side of the big square is $s=(r+R)(1+\frac{\sqrt{2}}{2})$ and so the sides of the rectangle are $s-2r=R(1+\frac{\sqrt{2}}{2})+r(-1+\frac{\sqrt{2}}{2})$ and $s-2R=R(-1+\frac{\sqrt{2}}{2})+r(1+\frac{\sqrt{2}}{2})$, so (after the calculation) the area of the rectangle is:
$$-\frac{1}{2}R^2-\frac{1}{2}r^2+3Rr=\frac{-A-a+6\sqrt{Aa}}{2\pi}$$
Now, I presume you want $A=u\pi, a=v\pi$, so this area then becomes:
$$-\frac{u+v}{2}+3\sqrt{uv}$$
which gives you necessary and sufficient conditions: (a) $u,v$ are of the same parity; (b) $uv$ is a square.

A: After observing that the centers of the two circles are on the diagonal involved, everything comes out easy with the $45º$ angles in play. Thus we arrive at the relationship between the radii $R$ and $r$ which expresses the integer area $n$ of the blue rectangle.
$$\frac12(6rR-R^2-r^2)=n$$
Moving then to areas $A$ and $a$ of the problem we have the equation
$$6\sqrt{aA}-A-a=2n\pi$$ from this an easy partial solution is given by the mentioned conditions in Stinking Bishop's answer above.
However the solution is much more general. Expressing the areas as a function of the radii, the transcendent $\pi$ disappears and we return to the original expression, so we can do
$$R=3r\pm\sqrt{8r^2-2n}$$ This suggests that for each natural integer $n$ there exists an infinity of real pairs $(r, R)$ such that the corresponding blue rectangle has an area equal to $n$.
We end with an example for area $n=1$ (there is an infinity possible).
Example.-$(n,r,R)=(1,\sqrt3,\space 3\sqrt3+\sqrt{22})$.
In fact $$6\sqrt3(3\sqrt3+\sqrt{22})-(\sqrt3)^2-(3\sqrt3+\sqrt{22})^2=2\cdot1$$


text:
Q: Generic function accepting &str or moving String without copying I want to write a generic function that accepts any kind of string (&str/String) for convenience of the caller.
The function internally needs a String, so I'd also like to avoid needless re-allocation if the caller calls the function with String.
foo("borrowed");
foo(format!("owned"));

For accepting references I know I can use foo<S: AsRef<str>>(s: S), but what about the other way?
I think generic argument based on ToOwned might work (works for &str, and I'm assuming it's a no-op on String), but I can't figure out the exact syntax.

A: I think what you are after can be achieved with the Into trait, like this:
fn foo<S: Into<String>>(s: S) -> String {
    return s.into();
}

fn main () {
    foo("borrowed");
    foo(format!("owned"));
}


text:
Q: Python: Check if any list element is a key in a dictionary Given the following code
all_options = { "1": "/test/1", "2": "/test/2", "3": "/test/3" }
selected_options = [ "1", "3" ]

How do I get the entries from all_options where the key matches an entry in selected_options?
I started down the path of using a List Comprehension, but I'm stuck on the last clause:
final = ()
[ final.append(option) for option in all_options if ... ]

Thank you

A: Just like this?
>>> dict((option, all_options[option]) for option in selected_options if option in all_options)
{'1': '/test/1', '3': '/test/3'}

From Python 2.7 and 3 onwards, you can use the dict comprehension syntax:
{option : all_options[option] for option in selected_options if option in all_options}

Or if you just want the values:
>>> [all_options[option] for option in selected_options if option in all_options]
['/test/1', '/test/3']

A: [option for option in all_options if option in selected_options]

You may want to make a set of selected_options and use that instead if there are many.

A: Use set() instead, and take advantage of the intersection operation:
>>> final = set(all_options.keys()) & set(selected_options)
>>> print(final)
{'1', '3'}

The above only returns the keys, but NullUserException notes that the question may want the value as well, using a dict comprehention:
>>> {x: all_options[x] for x in set(all_options.keys()) & set(selected_options)}
{'1': '/test/1', '3': '/test/3'}

For completeness, here's just the value:
>>> [all_options[x] for x in set(all_options.keys()) & set(select_options)]
['/test/1', '/test/3']

The below is wrong. Using set() iterates over both lists, instead of just one.

Using sets is better assuming the options become large. The conditional list comprehensions check every item in one of the containers, but a set intersection takes advantage of Python's excellent hashing. Even the list comprehension here only looks up the desired keys in all_options.

A:
How do I get the entries from all_options where the key matches an entry in selected_options?

With a comprehension. We have two kinds: list comprehensions and generator comprehensions.
Note that this depends on what you mean by "entries". If you want a dict with the key/value pairs that match, then you'll need a comprehension that creates the key/value pairs, and then use that to create a dict by feeding it to the dict constructor.
There is a special syntax rule that says that if we call something callable (like, say, a class constructor) with just one argument, and that argument is a generator comprehension, then we only need one pair of parentheses (instead of two: one to call the function and another to mark the comprehension as a comprehension). This lets us write very natural-looking things.
On the other hand, if you just want a list of keys, then you can just use a list comprehension. (You could pass a generator comprehension to the list constructor, too.)

I started down the path of using a List Comprehension...

You have the wrong idea, fundamentally, about how they work. You don't use them to perform an action repeatedly; you use them to calculate a result repeatedly. You wouldn't make an append call in the first part of the statement because (a) the comprehension is already building the sequence for you, so there's no reason to create another empty sequence to append to; (b) the append call returns None after doing the appending, so you end up with a list of None values that you subsequently throw away.
A list comprehension creates a value. A generator comprehension also creates a value, but it's a generator (so you have to extract its values to use them).
So, how do we write the code?
A list of keys looks like this: for each key in the dict (iterating over a dict iterates over its keys), we want that key (with no modification), only if the key is in our other list. That is, we want [key for key in all_options if key in selected_options]. And that's exactly how you write it in Python. A language could hardly read any more naturally while still being unambiguous.
A dict of key-value pairs looks like this: for each key-value pair in the key-value pairs of the dict, we want that pair, only if the key is in our other list. We want to make a dict using those key-value pairs, so we wrap the comprehension in the dict constructor. To get key-value pairs from a dict, we iterate over its .items(). So, we want a dict constructed from a key and value, for each key and value in the items of the original dict, where the key is in the other list. And again, that's exactly what we write: dict((key, value) for (key, value) in all_options if key in selected_options).
In more recent versions of Python, we can also use a "dict comprehension", which is basically syntactic sugar so that we can write something that looks more like the list comprehension.

A: I'm not sure which exact contents you're trying to return, so I'm giving a couple of choices:
if your trying to return: ['1', '3']
[option for option in all_options if option in selected_options]

OR
if you're trying to return: ['/test/1', '/test/3']
[all_options[option] for option in all_options if option in selected_options]


text:
Q: In JS web apps, how is it ensured that a malicious user with the access token will not be able to refresh it? I find ensuring safety for OAuth with JS apps a̶ ̶p̶a̶i̶n̶ ̶i̶n̶ ̶t̶h̶e̶ ̶a̶.̶.̶.̶  very annoying :(

Let's imagine I am Alice, a legal user, using a JS single page app client of an OAuth server. I have logged in and received my tokens (access and refresh).
At some point, unfortunately, my still valid access token and the refresh token are retrieved by a malicious user, Bob (note that there is no reason only the refresh token could be retrieved since both are sent back by the OAuth server the same way).
Ok, so what I'm understanding from this question is that, well, that does not matter that much because evil Bob will only have a limited amount of time to do bad stuff, since the token has a short life.
Now let's assume the token has expired. In theory, all should be over for Bob.
But I do not understand what now prevents Bob to request a new token. What does Alice has that Bob does not so that only Alice can get a new access token?

Let's now think of slightly different client configuration: there is still a JS web app, but this time the actual OAuth client is a PHP backend the JS client makes requests to. This PHP back-end acts as a sort of proxy and, as any OAuth client, makes/forwards requests to the OAuth server.
In this case, the refresh token could have been kept secret by the back-end, and Bob would have only retrieved the access token. But in this case, again, except from the this now expired access token, that Bob do know, what data can Alice give the back-end so that it differentiates between her and Bob so that the refreshing process is only done for Alice?

A: For JavaScript applications (SPAs), you are supposed to use the implicit grant, which does not support refresh tokens. Basically, your users are redirected to the auth server, log in and get the access token. When the access token expires, they need to re-authenticate with the auth server.
Since you can't keep secrets in a JavaScript application, there's no client ID or secret:

The implicit grant type does not include client authentication, and
relies on the presence of the resource owner and the registration of
the redirection URI.


text:
Q: PHPStan throws undefined static method when using custom rules in Respect/Validation I'm using Respect/Validation class and I have custom rule CustomRule() which works fine:
use Respect\Validation\Validator as v;

// ...

'email' => v::CustomRule()->email()->setName('email');

But this causes PHPStan to throw an error:
Call to an undefined static method Respect\Validation\Validator::CustomRule().
But if I move it after a built-in rule (e.g., email()), PHPStan works fine, no errors:
'email' => v::email()->CustomRule()->setName('email');
To be clear, both code works but PHPStan thinks the first code is invalid.
Any workaround so that PHPStan will accept it even if CustomRule() was set first?
Update:
I've found that if I edit the doc block of Respect\Validation\Validator class and append my custom rule to the list of its built-in rules, it works!
/**
* ...
* @method static Validator CustomRule()
*/
class Validator extends AllOf
...

Of course it's a bad idea to directly modify the doc block from the main class. That said, my question still remains the same. Or, maybe is there a way for PHPStan to honor my own doc block from my CustomRule class?

A: Ran into the same issue. What I did was just to add the custom Validators to phpstan config file (phpstan.neon).
It can be done with regex eg:
parameters:
    ignoreErrors:
        - '#Call to an undefined method Respect\\Validation\\Validator::[a-zA-Z0-9\\_]()#'

Docs: https://github.com/phpstan/phpstan#ignore-error-messages-with-regular-expressions
More of a workaround I guess though.


text:
Q: Should I say "It's better for me to talk BY / ON / IN English" What's better for you as a native English speakers?
If for example you see someone who knows 2 languages, but you understand English only. Then you want to talk the language that's considered understandable for you. Here are the options:

"It's better for me to talk by / on / in English"

or to say simply

"It's better for me to talk English" (without any prepositions)

A: In this context -  the correct sentence is: "It's better to talk in English".
You can talk on English - but that means you are talking about the English language
You can also talk by English - but that would indicate you are talking next to a person called English.
The reason why you can't say "talk by English" to mean talk using English is because English is not a physical tool you use to do the physical action of talking, unlike a pickaxe for mining (mine by pickaxe) or an telephone for talking over long distances (talk by telephone).
However, you can "Communicate by English" - because communication is not a physical action, and English is a tool for Communication.


text:
Q: Reflecting over assemblies causes Unity to require Microsoft.Practices.ServiceLocation We typically only reference Microsoft.Practices.Unity.dll in our applications. We're only using basic capabilities, and this works fine. In one application, the act of using reflection is causing Unity to require another DLL.
For example, create a console app and reference only Microsoft.Practices.Unity (file version 2.0.414.0). Enter the following code and run it:
class Program
{
    static void Main()
    {
        using (var container = new UnityContainer())
        {
            container.RegisterType<IDoSomething, ConcreteDoSomething>();

            var thing = container.Resolve<IDoSomething>();

            thing.DoSomething();
            Console.WriteLine();

            LoadSchemaLoaders();
        }
    }

    public static void LoadSchemaLoaders()
    {
        var type = typeof(ISchemaLoader);

        try
        {
            // Get all loaded assemblies, including Unity.
            // Get all of the types.
            // Filter for types that ISchemaLoader (custom type) can be assigned from.

            var types = AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(s => s.GetTypes())
                .Where(c => type.IsAssignableFrom(c) && c.IsClass && !c.IsAbstract && !c.IsGenericParameter);

            Console.WriteLine("Got here...");

            types.FirstOrDefault();
        }
        catch (ReflectionTypeLoadException ex)
        {
            Console.WriteLine(ex.Message);

            foreach (Exception exSub in ex.LoaderExceptions)
            {
                Console.WriteLine(exSub.Message);
            }
        }
    }
}

public interface IDoSomething
{
    void DoSomething();
}

public class ConcreteDoSomething : IDoSomething
{
    public void DoSomething()
    {
        Console.WriteLine("Something!");
    }
}

public interface ISchemaLoader {}

On my machine, the output is:
Something!

Got here...
Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
Could not load file or assembly 'Microsoft.Practices.ServiceLocation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.
Now comment out the line
LoadSchemaLoaders();

Run it again and it works.
This is a simplified version of production code. The production code is actually dynamically loading custom types that implement an interface. As soon as we introduced Unity, the code threw an exception. But Unity types can't implement our interface!
I don't understand how simply reflecting over the assembly is causing the core Unity assembly to require another dependency.

A: A type in the Unity assembly from an interface defined in Microsoft.Practices.ServiceLocation (probably IServiceLocator).
The compiler doesn't require your application to reference that dll directly...but reflecting over the System.Type object will try to load the dll referenced by Unity.
The reason this only happens when you reflect over the assembly is because Unity probably doesn't load the type that references Microsoft.Practices.ServiceLocation under normal circumstances.
As a work-around, you could enclose your Assembly.GetTypes() call in a try/catch block.
Alternatively, if you put the Microsoft.Practices.ServiceLocation dll in a location where your application can find it, that should resolve the issue as well.


text:
Q: Set color properties of citep and citet I hope you're doing great. I want to set the color properties (for example blue) of the cite command in Beamer (citep and citet) but I don't know how. How can I do it? That is my code.
\documentclass[xcolor=dvipsnames,t]{beamer}
\definecolor{mikadoyellow}{rgb}{1.0, 0.77, 0.05}
\definecolor{yaleblue}{rgb}{0.06, 0.3, 0.57}
\usetheme{warsaw}
\usefonttheme{serif}
\setbeamerfont{section in head/foot}{family=\sffamily}
\setbeamerfont{subsection in head/foot}{family=\sffamily}
\setbeamerfont{author in head/foot}{family=\sffamily}
\setbeamerfont{title in head/foot}{family=\sffamily}
\setbeamercolor*{palette primary}{use=structure,fg=black,bg=red}
\setbeamercolor*{palette quaternary}{fg=white,bg=black}
%\usepackage[spanish]{babel}
\usepackage{multirow}
\usepackage{ragged2e}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{gensymb}
\usepackage{xcolor}
\usepackage{hyperref}
\justifying
\usefonttheme{professionalfonts}
\usepackage[none]{hyphenat}
\usepackage{cancel}
\usepackage{tikz}
\usepackage[round]{natbib}
\usepackage{color}
\usepackage{colortbl}
%\let\oldcite=\citet
%\let\oldcite=\citep
%\renewcommand{\citet}[1]{\textcolor[rgb]{0,0,1}{\oldcite{#1}}}
%\renewcommand{\citep}[1]{\textcolor[rgb]{0,0,1}{\oldcite{#1}}}

%\def\@citet#1#2{{\hypersetup{linkcolor=blue!black}[{#1\if@tempswa , #2\fi}]}}

\newcommand{\textunderscript}[1]{$_{\text{#1}}$}
\setbeamersize{text margin left=20pt,text margin right=20pt}

\title[Title 2]{Title}
\author{Author}
\date{\today}

\begin{document}
\sloppy
{
\addtobeamertemplate{headline}{%
\setbeamercolor{section in head/foot}{use=palette quaternary, fg=palette     quaternary.bg}
}{}
\begin{frame}
\titlepage
\end{frame}
}
%-------------------------START----------------------------

\section{Problem definition}
\subsection{Introduction}
\frame{
\citep{Ansari2014} and \citet{Ansari2014}
}

\begin{frame}[allowframebreaks]
\bibliographystyle{apalike}
\bibliography{ref_qualify}
\end{frame}
\end{document}

Thanks in advance

A: You nearly have the answer in the comments to your code, try with this slight modification:
\let\oldcitet=\citet
\let\oldcitep=\citep
\renewcommand{\citet}[1]{\textcolor[rgb]{0,0,1}{\oldcitet{#1}}}
\renewcommand{\citep}[1]{\textcolor[rgb]{0,0,1}{\oldcitep{#1}}}

Full MWE:
\documentclass[xcolor=dvipsnames,t]{beamer}

\definecolor{mikadoyellow}{rgb}{1.0, 0.77, 0.05}
\definecolor{yaleblue}{rgb}{0.06, 0.3, 0.57}

\usetheme{Warsaw}
\usefonttheme{serif}
\setbeamerfont{section in head/foot}{family=\sffamily}
\setbeamerfont{subsection in head/foot}{family=\sffamily}
\setbeamerfont{author in head/foot}{family=\sffamily}
\setbeamerfont{title in head/foot}{family=\sffamily}
\setbeamercolor*{palette primary}{use=structure,fg=black,bg=red}
\setbeamercolor*{palette quaternary}{fg=white,bg=black}

\usepackage{multirow}
\usepackage{ragged2e}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{gensymb}
\justifying
\usefonttheme{professionalfonts}
\usepackage[none]{hyphenat}
\usepackage{cancel}
\usepackage{tikz}
\usepackage[round]{natbib}
\usepackage{colortbl}

\let\oldcitet=\citet
\let\oldcitep=\citep
\renewcommand{\citet}[1]{\textcolor[rgb]{0,0,1}{\oldcitet{#1}}}
\renewcommand{\citep}[1]{\textcolor[rgb]{0,0,1}{\oldcitep{#1}}}

\newcommand{\textunderscript}[1]{$_{\text{#1}}$}
\setbeamersize{text margin left=20pt,text margin right=20pt}

\begin{document}
\frame{
\citep{moore:related} and \citet{moore:related}
}

\begin{frame}[allowframebreaks]
\bibliographystyle{apalike}
\bibliography{biblatex-examples}
\end{frame}
\end{document}

Offtopic:
You don't need
\usepackage{xcolor}
\usepackage{hyperref}
\usepackage{color}

as beamer already provides these functionalities.


text:
Q: Calculate $\lim{a_{n}}$ for $a_{n}=((1+\frac{1}{n^{2}})^{n^{2}}(1-\frac{1}{n})^{n}(1+\frac{1}{n}))^{n}$ $$a_{n}=((1+\frac{1}{n^{2}})^{n^{2}}(1-\frac{1}{n})^{n}(1+\frac{1}{n}))^{n}=(e^{\ln((1+\frac{1}{n^{2}})^{n^{2}})+\ln((1-\frac{1}{n})^{n})+\ln((1+\frac{1}{n})^{n})})^{n}$$Then I can use Taylor's theorem - because function $f(x)=e^{x}$ is monotonic I can examine $\ln((1+\frac{1}{n^{2}})^{n^{2}})+\ln((1-\frac{1}{n})^{n})+\ln((1+\frac{1}{n})^{n})$. However I think it is too time-consuming and there is probably a faster way.Have you some ideas?

A: You know $$\left(1 + \frac{1}{n}\right)^n \to e$$ as $n \to \infty$. As for
$$\left(1 + \frac{1}{n^2}\right)^{n^3} \left(1 - \frac{1}{n}\right)^{n^2}$$
take logarithms and use $\log(1 + x) = x - x^2/2 + \dots$ as $x \to 0$ to get
$$ n^3 \log\left(1+\frac{1}{n^2}\right) + n^2 \log\left(1 - \frac{1}{n}\right)= n - \dots - n - \frac{1}{2} - \dots \to -\frac{1}{2}$$ as $n \to \infty$.
Thus the limit is $$e^{-1/2} e = \sqrt{e}.$$


text:
Q: For SharePoint Online, can I change a site's search to look within the entire Hub? We have a collection of sites that all live under a Hub Site. The sites within it are not subsites, just normal sites within the Hub's collection.
For the Hub site itself, when I run a search on the front-end it searches across all sites for results. The placeholder text of that search says "search across sites." For the internal sites, the initial search query only looks within its specific site contents and that placeholder text says "search this site."
One other note about the internal site search. The results from that search look like the screenshot attached. If I click on the "Hub Site" label, it does change the scope of the search to be across all sites.
I'm wondering if I can change the settings of the internal sites to behave as the Hub site does and search across all sites by default? And if I can, is it possible to configure this setting on a site-by-site basis?

Any and all help is appreciated, thank you!

A: There is not yet an option through the settings user interface, but it is an option you can set on each site via PnP PowerShell.  If you have not already configured your machine to execute PnP PowerShell, follow these instructions first for installing and getting started, then:
Connect-PnPOnline -Url https://<<yourFullsiteurl>> -UseWebLogin

$web = Get-PnPWeb
$web.SearchScope = 2 # see below for possible SearchScope values
$web.Update()
Invoke-PnPQuery

0 = default, let SharePoint decide
1 = All sites in the organization
2 = All sites in this Hub
3 = Just this site

A: willman's script is correct and it is a quite new feature. It is more discussed here and have a check on it if you need more information:https://techcommunity.microsoft.com/t5/sharepoint/configure-modern-search-results-to-search-all-of-your/m-p/447334


text:
Q: SINGLE LINE of JAVA neuroph code is not working I made a program that tries to use neuroph made neural network consisting of one line of code (beside imports, main etc.)
NeuralNetwork nnet = NeuralNetwork.createFromFile('path here');

The first error I got was:

Exception in thread "main" java.lang.NoClassDefFoundError: Lorg/slf4j/Logger;

After adding slf4j-api-1.7.25.jar I get:

Exception in thread "main" org.neuroph.core.exceptions.NeurophException: Class not found while trying to read neural network from file!

I also tried with other versions of slf4j I could get. Sounds good, does not work. I have no idea how to begin fixing it.

A: Seems like the second error is not related to slf4j , but to NeuralNetwork not finding it's own classes.
Code that throws the error:
https://github.com/neuroph/neuroph/blob/master/neuroph-2.9/Core/src/main/java/org/neuroph/core/NeuralNetwork.java line 683.
See How do I resolve ClassNotFoundException? for some pointers


text:
Q: valueChanges() to only return affected items of a list change Working on an Angular5 app using angularfire2.
I have a List with a big number of items.
When I subscribe to it using:
this.db.list("/list").valueChanges().subscribe(data => { .. });

I get all children of the list in data as expected.
When I now change one single item in the Firebase backend, the callback then receives the entire list of all children again.
How can I subscribe to only receive the affected items of a list in data?
Or is it irrelevant because angularfire2 handels the state of the list internally and only transfers the affected items from the server to the app? My target is to minimize connection traffic.
Thanks in advance :)

A: AngularFire2 valueChanges() always gives you the entire list. If you want just the state changes, use stateChanges.
There are use-case for any of the observable types in AngularFire. Check the documentation to see which one matches your use-case best.


text:
Q: Simulate a Click on an Image with usemap I know how to simulate a click event on a button using webbrowser control. However, I am not able to simulate the click event on an image with usemap with mouseup and mousedown events associated.
how can I do it?
Bellow is the html associated to the image and to the usemap:
<img src="http://www.temp.com/zoom_off.gif" id="photo_zoom" style="width: 39px; height: 23px; border: 0" alt="" usemap="#btnZCMap">

 <area shape="rect" coords="2,2,19,25" href="#" onmouseover="doBtn('photo_zoom','in'); return false;" onmouseout="ZM=0; doBtn('photoe_zoom','off'); return false;" onmousedown="ZM=1; doZC(-1); return false;" onmouseup="ZM=0; return false;" onclick="return false;">

A: First, you need to get the element, and then invoke the correct member, for example:
For Each elem As HtmlElement In webBrowser1.Document.GetElementsByTagName("img")
    If elem.GetAttribute("alt") = "MyImage" Then
        elem.InvokeMember("click")
    End If
Next

If this didn't work you could try the RaiseEvent:
WebBrowser1.document.GetElementById("ImgID").RaiseEvent("onclick")


text:
Q: Кодировка в SMTP-сообщениях Я получаю от Exchange-сервера письмо с кириллицей. Текст сообщения при отправлении - "Hello, мир!". Есть проблема при обработке это сообщения потому что:

*

*кириллица ("мир") - передается в формате Quoted Printables, т.е. вид имеет примерно такой - "=F1=E2=E3"

*При перекодировке из Quoted Printables в 1251  (чтобы рус. яз. отобразился нормально) теряется латинница.

Так я получаю русский язык из Quoted Printables:
public static string DecodeQuotedPrintables(string input, Encoding encoding)
    {
        var regex = new Regex(@"\=(?<Symbol>[0-9A-Z]{2})", RegexOptions.Multiline);
        var matches = regex.Matches(input);
        var bytes = new byte[matches.Count];

        for (var i = 0; i < matches.Count; i++)
        {
            bytes[i] = Convert.ToByte(matches[i].Groups["Symbol"].Value, 16);
        }

        return encoding.GetString(bytes);
    }

Подскажите пожалуйста алгоритм, как, имея в строке латинницу и крилиицу конвертировать сообщение, чтобы сохранить оба языка?

A: Идешь по строке, от символа к символу. Рассматриваешь каждый символ. Если код символа имеет значение: с 33 по 60; или с 62 по 126; или 32 или 9, то кладешь этот код в байтовый буфер. Если это символ "равно" ("="), то после него может идти либо перевод строки (то есть "\r\n"), либо двузначное шестнадцатеричное число. Если после "=" идет перевод строки, то пропускаешь этот перевод строки. Если после "=" идет шестнадцатеричное число, то кладешь его значение в байтовый буфер. В конце, переводишь полученный байтовый буфер в строку в соответствие с кодировкой. Примерно так:
static string FromQuotePrintable(string s, Encoding e) {
      using (var ms = new MemoryStream(s.Length)) {
        for (int i = 0; i < s.Length; ++i) {
          byte c = (byte)s[i];
          if (c >= 33 && c <= 60 || c >= 62 && c <= 126 || c==' ' || c=='\t') {
            ms.WriteByte(c);
            continue;
          }
          if (c == '=') {
            i += 2;
            if (s[i - 1] == '\r' && s[i] == '\n') {
              continue;
            }
            ms.WriteByte(byte.Parse(s.Substring(i - 1, 2), System.Globalization.NumberStyles.HexNumber));
          }
        }
        return e.GetString(ms.GetBuffer(), 0, (int)ms.Length);
      }
    }

В этом коде нет проверки на несоответствие кодировке Quote Printable. Так что если входная строка будет ей не соответствовать, то могут происходить разные ошибки: выход за пределы строки, ошибка при переводе из шестнадцатеричной строки в байт и другие.
Описание кодировки здесь: http://kunegin.com/ref2/email/mime03.htm
В принципе по скорости и памяти было бы эффективнее самому переводить из 2-х шестнадцатеричных символов в байт, без "выгрызания" подстроки. Это чуть сложнее.


text:
Q: Recursive functions and pattern matching in ocaml The following code snippet comes from the official OCaml website:
# let rec compress = function
| a :: (b :: _ as t) -> if a = b then compress t else a :: compress t
| smaller -> smaller;;
val compress : 'a list -> 'a list = <fun>

The above function 'compresses' a list with consecutive, duplicative elements, e.g. :
# compress ["a";"a";"a";"a";"b";"c";"c";"a";"a";"d";"e";"e";"e";"e"];;

- : string list = ["a"; "b"; "c"; "a"; "d"; "e"]

I'm having a devil of a time understanding the logic of the above code. I'm used to coding imperatively, so this recursive, functional approach, combined with OCamls laconic - but obscure - syntax is causing me to struggle.
For example, where is the base case? Is it smaller -> smaller? I know smaller is a variable, or an identifier, but what is it returning (is returning even the right term in OCaml for what's happening here)?
I know that lists in OCaml are singly linked, so I'm also wondering if a new list is being generated, or if elements of the existed list are being cut? Since OCaml is functional, I'm inclined to think that lists are not mutable - is that correct? If you want to change a list, you essentially need to generate a new list with the elements you're seeking to add (or with the elements you're seeking to excise absent). Is this a correct understanding?

A: Yes, the base case is this:
| smaller -> smaller

The first pattern of the match expression matches any list of length 2 or greater. (It would be good to make sure you see why this is the case.)
Since OCaml matches patterns in order, the base case matches lists of lengths 0 and 1. That's why the programmer chose the name smaller. They were thinking "this is some smaller list".
The parts of a match statement look like this in general:
| pattern -> result

Any names in the pattern are bound to parts of the value matched against the pattern (as you say). So smaller is bound to the whole list. So in sum, the second part of the match says that if the list is of length 0 or 1, the result should just be the list itself.
Lists in OCaml are immutable, so it's not possible for the result of the function to be a modified version of the list. The result is a new list, unless the list is already a short list (of length 0 or 1).
So, what you say about the immutability of OCaml lists is exactly correct.


text:
Q: How to validate date format in spring form without using Annotation? addEmployee.jsp

<form:form id="bookForm" modelAttribute="employee" method="post" action="${baseURL}employee/saveemployee" class="form-horizontal" enctype="multipart/form-data">

    Birth Date

      <form:input path="personalInformation.dateOfBirth" placeholder="yyyy-MM-dd" class="datepicker form-control" />
      <form:errors path="personalInformation.dateOfBirth"></form:errors>

    Date Of Joining

      <form:input path="dateOfJoining" placeholder="dateOfJoining" class="form-control" />
      <form:errors path="dateOfJoining"></form:errors>

</form:form>

This is jsp form in which i have to validate date feilds
whenever i click on save button it gives null pointer exception.

2)EmployeeAddController.java
@RequestMapping(value="/saveemployee",method = RequestMethod.POST)
public String saveEmployee(@ModelAttribute("employee")Employee employee,BindingResult result,Errors e,ModelMap map){

        employeeValidatorobj.validate(employee,e);
        if(e.hasErrors())
        {
            map.addAttribute("employee",employee);
            return "addEmployee";
        }

        else{
    System.out.println("inside save");
      System.out.println(employee.getPersonalInformation().getFirstName());
         map.addAttribute("employee",new Employee());

       iEmployeeService.saveEmployee(employee);
        map.addAttribute("message", "EmployeeAdded sucessfully");
       return "employeeList";
    }
    }

This is controller here i am checking if form has errors or not.`
3)emolyeeValidator.java
public class EmployeeValidator implements Validator {

private Pattern pattern;
private Matcher matcher;

private static final String DATE_PATTERN="((?:19|20)\\d\\d)/(0?[1-9]|1[012])/([12][0-9]|3[01]|0?[1-9])";
@Override
public boolean supports(Class<?> arg0) {

    return Employee.class.equals(arg0);
}

@Override
public void validate(Object obj, Errors errors) {

        // Employee employee=new Employee();
    Employee employee = (Employee) obj;

       String date=employee.getDateOfJoining().toString();
       if (!date.matches(DATE_PATTERN)) {

           pattern=pattern.compile(DATE_PATTERN);
           matcher=pattern.matcher(date);
           if(matcher.matches()){
               errors.rejectValue("dateOfJoining", "dateOfJoining.incorrect","enter correct dateOfJoining");
           }

    }

This is employeeValidator class for custome validation of date but when i am try to save record it gives null pointer exception.i have also mapped employeevalidator in bean.and whenever iam trying to validate with .equals() string  method then it gives exception on jsp page string cannot convert into java.util.Date.please check code and suggest me how to check condition in employeeValidator for date format (YYYY-MM-DD)


text:
Q: MySQL procedures comma delimited string compare with triger i have a mysql column which hold comma delimited value, and external program intert/update data to that column, how can  i make trigger to compare which value added to comma delimited string or which data remove?
lets say column1 has data a,b,c,d and external program add e or remove d from column1, how to detect which value was added or removed?


text:
Q: Ethernet switch timeout after 3min ~50seconds using Micrel KSZ8895MQXC evaluation board I am trying to test throughput and ping delay on a chain of Micrel KSZ8895 chips. Unfortunately I am running into the issue that they stop sending data 3 minutes and ~50 seconds after boot. I have tried to access the registers through SPI but when I set the evaluation board to SPI mode it fails to send any packets at all. Any ideas as to why the switch would fail every time after a set amount of time?

A: you need to set bit 0 in SPI register 0 or 1. In SPI or I2C mode the chip only starts after setting this bit


text:
Q: Is the any sort of repository for OS/system dSYM files for every version of iOS, macOS, etc.? To fully symbolicate Apple crash files it would be nice to have all the dSYM files for all the modules (binary images) mentioned in the crash stack traces. Where do people normally get dSYM files for OS/system components of iOS, macOS, etc.? Is there any centralized repo for getting those?

A: The list and download links can be found on GitHub - https://github.com/Zuikyo/iOS-System-Symbols/blob/master/collected-symbol-files.md
Unfortunately there are only iOS 13 and earlier versions.


text:
Q: Regex for splitting into sentences, ignoring decimal numbers as part of the split? In javascript, I'm interested in splitting a body of text into an array sentences, where it ignores decimal numbers (and ideally web sites) for the split.  I've found how to do it for sentences - e.g., str.split(/[\.\!]+\s*|\n+\s*/) - but not sure how to add the extra bit to ignore decimal numbers in the split
For example, if
str = "Hello there, the ice cream is $2.00.Toppings are extra."

Would result in
["Hello there, the ice cream is $2.00", "Toppings are extra"]

Is this possible?
thanks!

A: str = "Hello there, the ice cream is $2.00.Toppings are extra.";
str.split(/[\.\!]+(?!\d)\s*|\n+\s*/); //[ 'Hello there, the ice cream is $2.00', 'Toppings are extra',]

*

*(?!\d) Zero-width negative lookahead to match digit.

If the lookahead matches, The regex is not matched and the string is not splitted.

A: Scala :
    import java.util.regex.Pattern;
    var regPattern = "(?<!\\d)\\.(?!\\d)|(?<=\\d)\\.(?!\\d)|(?<!\\d)\\.(?=\\d)";
    val pt = regPattern.compile(pattern);
    var strList: List[String]= pt.split(input).map(_.trim)(breakOut)