text:
Q: ¿Cómo asignar a una variable el valor de una promesa? Quisiera saber como hacer una función que retorne lo que resuelve una promesa y luego eso asignarserlo a una variable, ejemplo:
let Get = async () =>{
  try{
    let res = await
    fetch('https://pokeapi.co/api/v2/pokemon/pikachu');
    let data = await res.json();
    let obj = {
      img : data.sprites.front_default,
      habilidad: data.abilities[0]
    }
    return obj;
  }
  catch(err){
    throw ("ha ocurrido un error" + err);
  }
}

var nueva = Get();
console.log(nueva);

A: Tienes 2 opciones:

*

*Usar .then en Get()

*Llamar a Get() desde una función async y usar await.
Opción 1:

let Get = async () =>{
  try{
    let res = await
    fetch('https://pokeapi.co/api/v2/pokemon/pikachu');
    let data = await res.json();
    let obj = {
      img : data.sprites.front_default,
      habilidad: data.abilities[0]
    }
    return obj;
  }
  catch(err){
    throw ("ha ocurrido un error" + err);
  }
}
Get().then(nueva => console.log(nueva));

Opción 2

let Get = async () =>{
  try{
    let res = await
    fetch('https://pokeapi.co/api/v2/pokemon/pikachu');
    let data = await res.json();
    let obj = {
      img : data.sprites.front_default,
      habilidad: data.abilities[0]
    }
    return obj;
  }
  catch(err){
    throw ("ha ocurrido un error" + err);
  }
}

async function foo() {
  let nueva = await Get();
  console.log(nueva);
}

foo();

Puedes leer más información sobre async y await.


text:
Q: Minecraft 1.16.5 how to summon a falling block(hopper) rotated in any direction? I'm trying to build a building in Minecraft 1.16.5 using commands, and I don't know how to summon a falling block rotated in any direction.
The command what I'm using now :
summon falling_block ~-1 ~50 ~12 {BlockState:{Name:"minecraft:hopper"},Time:1}

Edited:
Or summoning the top part of the rose bush, or summoning which stair in are rotated  to any direction, or summoning the top part of the door, and things like that.

A: I would recommend using a minecraft summon generator. Something like https://mcstacker.net/ should have what you need.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to manage elements with the same class in a Jquery method Hi I'm using a Jquery method to highlight a Keycaps on a keyboard when click. When you click on the individually you get a border on that keycap. All areas of the map has the class "key" and others have the class "alpha" and "control".
Now what I want to do is be able to click all alphanumeric keys at the same time which a button event "balpha".
The problem in the code is that after using the "balpha" button all the areas act as one, and when pressing one keycap in the keyboard all the keys with the class "alpha" get highlighted, when they should work individually.
Here is a sample of the code:
<!doctype html>

<meta charset="utf-8">
<title>Keyboard Designer</title>

        <map name="appleKeyboard">

        <area shape="rect" coords="61,58,98,95" href="#" alt="n1" class="key alpha" data-maphilight='{"strokeColor":"0000ff","strokeWidth":2,"fillColor":"ff0000","fillOpacity":0.0}'>
        <area shape="rect" coords="104,58,141,95" href="#" alt="n2" class="key alpha" data-maphilight='{"strokeColor":"0000ff","strokeWidth":2,"fillColor":"ff0000","fillOpacity":0.0}'>
        <area shape="rect" coords="147,58,184,95" href="#" alt="n3" class="key alpha" data-maphilight='{"strokeColor":"0000ff","strokeWidth":2,"fillColor":"ff0000","fillOpacity":0.0}'>
        <area shape="rect" coords="190,58,227,95" href="#" alt="n4" class="key alpha" data-maphilight='{"strokeColor":"0000ff","strokeWidth":2,"fillColor":"ff0000","fillOpacity":0.0}'>
    </map>
    <fieldset>
        <legend>keys group</legend>
            <button id="balpha" type="button" value="alpha" >Alphanumeric</button>

    </fieldset>

Thanks for any advice that you could give me!


text:
Q: Android: Detect another application has started playing audio My music application constantly plays music in the background, however I'd like to be able to detect when another application starts playing audio (such as the YouTube app) so I can pause/mute/stop the audio in my application.
This will allow a user to continue browsing the web whilst listening to music, but then if they wish to watch a video at any point, they can do so without audio conflict.
One solution might be to listen for a broadcast which states when an application begins using the AudioManager. Does such an Intent Action exist?

Edit: As in the answer provided below, there appears to be a method of detecting the loss of audio focus in 2.2 with AudioManager.OnAudioFocusChangeListener.
Great, but is there a solution for the more common versions of Android? Ideally 1.5+.

A: http://developer.android.com/reference/android/media/AudioManager.OnAudioFocusChangeListener.html
this thread also has additional information that might get you heading in the right direction.
http://groups.google.com/group/android-developers/browse_thread/thread/db6822d84feaac6/219d8cba07795c61?hl=en&lnk=gst&q=OnAudioFocusChangeListener#219d8cba07795c61


text:
Q: Custom macro for NSLocalizedString This question is regarding the localization from inside the app.
There are several blogs/tutorials that really helps and show the way to do it.
The ones which i referred to implement it are as below:
http://learning-ios.blogspot.in/2011/04/advance-localization-in-ios-apps.html
http://www.pastie.org/1976594
I am able to achieve it (with the help of such blogs.. thanks to them).
But i was trying one thing and i had a little doubt regarding the same as below
I am trying to create a same macro as the NSLocalizedString
[i.e. NSString *NSLocalizedString(String *key, String *value)]
but with a different macro name
something like
[NSString *getLocalizedString(String *key, String *value)] in my class and try to just replace NSLocalizedString method with my own macro using the same.
But a serious doubt/concern that i have is, is this technique/way approved by APPLE?
i mean.. can/will this violate the apple terms of non usage of Private API or kind of overriding the same??
Coz i have tried check the same in various blogs.. but was not able to find any specific answer to the same.
Can you please confirm if this can violate the T&C of APPLE or can i go ahead with the custom macro approach?
If possible can u also provide the link/blog/tutorial from which i can understand it better?
Thanks a lot in advance.

A: I don't see how this is using any kind of private APIs. -[NSBundle localizedStringForKey:] is a public API. You can write whatever macros or functions you want that call it. You can even #undef NSLocalizedString and replace it with your own definition if you want, it's just a C macro.

A: This won't violate Apple's terms.  In fact, they recommend you do this to test your app and make sure you translated all the strings. They demonstrated how to do this in the 2012 WWDC video, session 244 Internationalization Tips and Tricks at the 23:50 mark.


text:
Q: Function returns string when bool is expected What's wrong with this piece of code?
fun expd s:string = if size(s) > 0 then true else false;

The error I recieve:
- fun exnd s:string = if size(s) > a then true else false;
stdIn:657.1-837.8 Error: unbound variable or constructor: a
Error: right-hand-side of clause doesn't agree with function result type [tycon mismatch]
  expression:  bool
  result type: string

Why is this happening?

A: You need parentheses around s:string, because right now string is interpreted as the output type of the function and not the type of the parameter s:
fun expd (s:string) = if size(s) > 0 then true else false

By the way, the compiler can infer all the types here without any type annotations. Try the following:
fun expd s = if size(s) > 0 then true else false

And, of course, you can simplify this definition into:
fun expd s = size(s) > 0


text:
Q: Recommendations for in-memory object cache for .net I'm wondering what people's experiences are with in-memory cache solutions for .net.
We need an (ideally free) out-of-process caching solution that we can share between a number of different web sites (different app pools), and also some console apps that periodically run.
We've tried a few solutions so far, both of which are good but throwing up issues which make them less than ideal for production:
1) win32 Memcached with a .net client
Our first solution was to use a win32 port of memcached (http://jehiah.cz/projects/memcached-win32/), and a .net client library for it (http://sourceforge.net/projects/memcacheddotnet/).
It was fine and ran with no issues for a while, but then we started to see a lot of unexplained errors - the client library would fail to write to the cache. Not sure if this is an issue with the win32 port of memcached, or the client library, but I was uncomfortable with the lack of visibility of others using the same solution, and looked for a pure .net solution, which led me to...
2) SharedCache
Looks good, seems very well received in the community. Was very simple to set up and provides more features than our previous solution (e.g. the ability to get a list of all cached objects). This looked like a very good solution, but we recently started to see some issues creeping through:

*

*Memory consumption, there is an issue where it isn't releasing memory well, the service was using 700M even though we only held 30M of cached data

*Occasional CacheExceptions trying to retrieve objects from the cache (especially for larger cached objects)

So neither solutions are spot on. I'd love to know what solutions other people are employing. For information our server setup is currently only 32 bit windows box, so we don't have the option of a dedicated linux memcached server for example.

A: Microsoft has the artist formerly known as Velocity, now comes with Windows Server AppFabric

A: So in the end although appfabric looked promising, it seemed too much for what we need, and very tricky to work with, so we stuck with sharedcache, the memory consumption is manageable for us..
I suppose most people on the enterprise are all over NCache..


text:
Q: How to filter a table and have multiple results in jQuery I have a simple table with two dropdowns that sort the table by individual rows using jQuery. It will show one dropdown result or the other. I would like it to show multiple results like type and country. Right now it shows one at a time.
Type:
<select id="filter">
  <option value="all">All Steps</option>
  <option value="standard">Standards</option>
  <option value="review">Reviews</option>
  <option value="inspection">Inspections</option>
  <option value="payment">Payments</option>
  <option value="document">Documents</option>
</select>
Country:
<select id="country-filter">
  <option value="all">All Steps</option>
  <option value="usa">USA</option>
  <option value="fra">Frabce</option>
  <option value="bha">Bahamas</option>

</select>

    Standard

    USA

    Review

    France

    Inspections

    Bahamas

    Payments

    Documents

$("#filter").change(function() {
  console.clear();
  var filterValue = $(this).val();
  var row = $('.row');

  row.each(function(i, el) {
    if ($(el).attr('data-type') == filterValue) {
      row.hide()
      $(el).show();
    }
  });

// In Addition to Wlin's Answer (For "All" value)
  if ("all" == filterValue) {
    row.show();
  }

});

$("#country-filter").change(function() {
  console.clear();
  var countryfilterValue = $(this).val();
  var row = $('.row');

  row.each(function(i, el) {
    if ($(el).attr('data-attr') == countryfilterValue) {
      row.hide()
      $(el).show();
    }
  });

Results should be what is selected in type: dropdown and what is selected in country: dropdown
Standard
USA

A: You can merge both event handler  .Then , inside this you can get value of both select-box and show required rows where data-attribute values matches.
Demo Code :

$("select").change(function() {
  var filterValue = $("#filter").val(); //get select values..
  var countryfilterValue = $("#country-filter").val();
  $('.row').hide()
  //if nobody has all option slected
  if (filterValue != "all" && countryfilterValue != "all") {
    $("tr[data-type=" + filterValue + "]").show() //show row. datattr match
    $("tr[data-attr=" + countryfilterValue + "]").show()
  } else {
    $('.row').show();
  }
});

Type:
<select id="filter">
  <option value="all">All Steps</option>
  <option value="standard">Standards</option>
  <option value="review">Reviews</option>
  <option value="inspection">Inspections</option>
  <option value="payment">Payments</option>
  <option value="document">Documents</option>
</select>
Country:
<select id="country-filter">
  <option value="all">All Steps</option>
  <option value="usa">USA</option>
  <option value="fra">Frabce</option>
  <option value="bha">Bahamas</option>

</select>

    Standard

    USA

    Review

    France

    Inspections

    Bahamas

    Payments

    Documents


text:
Q: Invertibility of sum and difference of matrices Assume that $X$ and $A$ are $n\times n$ real matrices, with $A$ invertible (in fact, the identity matrix up to a non-zero factor).
Can we derive conditions on $X$ such that both $X+A$ and $X-A$ are invertible?
Conversely, knowing that both $X+A$ and $X-A$ are invertible, does this provide some information on $X$?
I tried to decompose the inverses with known formulas (Henderson-Searle, Woodbury) but it seems that my attempts only lead to circular arguments.

A: Write $\,A= \lambda\cdot\mathbb{1}\,$ for the fixed matrix, with $\mathbb 1$ denoting the $n\times n$ identity matrix and $\lambda$ a scalar factor. The condition "$X+A$ and $X-A$ are invertible"
is then equivalent to both $\,-\lambda\,$ and $\,\lambda\,$ being not eigenvalues of $X$.
(And this does not depend on $\lambda\ne 0$ or not.)
Another equivalent formulation is, by definition:
$\{\lambda, -\lambda\}$ lies in the resolvent set of $X$. The latter is the complement within $\mathbb C$ of the spectrum $\sigma(X)$.
This is all that can be said due to the following facts:

Every non-empty set of at most $\,n\,$ complex numbers appears as spectrum of some $n\times n$ complex matrix.

You may consider a diagonal matrix containing all the numbers from the given set.

When dealing with real matrices then in addition we have that non-real numbers in the spectrum show up in complex-conjugate pairs.

Given such a set you may obtain a corresponding block-diagonal matrix by setting in the diagonal all the real elements and for each conjugate pair $\,a\pm ib\,$ a submatrix
$\left(\begin{smallmatrix}a&b\\ -b&a\end{smallmatrix}\right)$; note
that
$\,\begin{pmatrix} a&b\\ -b&a\end{pmatrix}
\begin{pmatrix} 1\\ \pm i\end{pmatrix} = (a\pm ib)
\begin{pmatrix} 1\\ \pm i\end{pmatrix}\,$.


text:
Q: To make div visible using jQuery In the below code I have a div I have set to false and I want to make visible true using jQuery. If I remove visible false in div I can make visible. Please help me to do this.

JavaScript:
$('#<%=divmaterialconsumption.ClientID %>').show();

A: visible="false" on a server control (e.g. runat="server") stops it being rendered at all!
Instead hide it with style="display:none" and get rid of the visible="false"
jQuery's show() method can then change the style to display: block

A: Do the program as follows:

jQuery:
$(document).ready(function(){
  $('#but1').click(function(){  //assuming event taking by click of a btn
   $('#divmaterialconsumption').css('display','block');
 });
});

OR
 $('#divmaterialconsumption').show();

I hope that solves your issue!


text:
Q: Count Min Sketch: How to handle counters overflow? So the whole point of Count-Min Sketch is to update certain counters depending on the results of the provided hash functions. But, these counters are limited in memory, and after running for quite some time, they might overflow, dropping from the MAX value to the MIN value (like Integers do). Assuming all I need is the N most frequent values in the sketch, is there a way to avoid this other than restarting the sketch every once in a while?

A: Use an appropriately sized integer if this worries you.
An 8-byte (long long) unsigned integer has a maximum value of 18,446,744,073,709,551,615. That should probably be enough.
Edit

Assuming all I need is the N most frequent values in the sketch, is there a way to avoid this other than restarting the sketch every once in a while?

Perhaps you could adapt reservoir sampling to your needs.


text:
Q: Pass C# Variables to Powershell Engine I am writing a WinForms application in C# that will ultimately migrate Exchange 2010 mailboxes to a file location (pstStore) in .pst format. The form consists of a collection of textboxes, combo boxes and radio buttons. The command that will do the work is New-MailboxExportRequest –Mailbox… -FilePath… after a button click.
I am accessing the Exchange Management shell and using a runspace to pass the cmdlet and  parameters. In the Parameters (-Mailbox and –FilePath) I want to pass the values of the textboxes and combo boxes. How do I do this in C#?
FYI… I'm using the same code to populate a combo box with all of the mailboxes from the exchange database. So the code works for that purpose so, I thought I could also use it to pass some variables into with the AddParameter method.
Here is the code from the click event:
 InitialSessionState iss = InitialSessionState.CreateDefault();
    PSSnapInException warning;          iss.ImportPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010",out warning);
    using (Runspace myrunspace = RunspaceFactory.CreateRunspace(iss))
    {
       myrunspace.Open();
       using (PowerShell powershell = PowerShell.Create())
        {              powershell.AddCommand("Microsoft.Exchange.Management.PowerShell.E2010\\New-MailboxExportRequest")
    powershell.AddParameter("Mailbox", "UserMailbox");
    powershell.AddParameter("FilePath", "ExchAdmin");
    powershell.AddParameter("","");
    powershell.Runspace = myrunspace;
    Collection<PSObject> results = null;
    try
    {
       results = powershell.Invoke(); //Runs the cmdlet synchronously
    }
    catch (RuntimeException ex)
     {
        foreach (PSObject thisResult in results)
        {
           lstBoxStatus.Items.Add(thisResult); //sending the result to a status window
        }
     }
     myrunspace.Close();
    }

A: When you call the AddParameter overload that takes two parameters, the second one is the value.  Just use the name of the C# variable there e.g.:
string mailbox = _mailBoxTextBox.Text;
...
powershell.AddParameter("Mailbox", mailbox);


text:
Q: get the number of shares done using my app alone I have a webpage where i can have customers share about multiple urls using below href
https://www.facebook.com/dialog/feed?app_id=12345&link=www.petsytest.com&...&...
So based on the user action, link changes, but the appid is always my facebook apps appid.
How can I find the number of shares happened through  my app id.? Is it possible anywhere in
developer.facebook.com. If not , is there any other way?


text:
Q: Is it possible to instantiate a new WC_Cart? I am trying to use a different plugin's functionality without letting it run normally. It has a function that uses a WC_Cart object, and I want to give it a cart that is completely spoofed. Absolutely not the standard WC()->cart.
I do not want to modify any plugins, and I want to keep my work inside the functions.php file.
Is it possible to make a new WC_Cart like this? How exactly can I do that?
Do I have to import the plugin file that contains the WC_Cart class? Or is it possible to access it without having to do that?

A: Turns out that I was in the incorrect namespace. A new woocommerce cart can be instantiated by
$cart = new WC_Cart();

assuming you're in the same namespace as the cart, but if you are in a different namespace and suffering the problem I had with my original question, you would change it to:
$cart = new /WC_Cart();

As the / means to check the standard namespace, the same namespace the WC_Cart was declared in.


text:
Q: How to use second rank pointer rightly? I have a 2D array called matrix, now I would like to add one to every element.
#include <stdio.h>
#include <stdlib.h>

int **add_one(int **matrix, int m, int n) {
    int i, j;
    int **new_mat;
    new_mat = (int **) malloc(m * n *sizeof(int));

    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            new_mat[i][j] = matrix[i][j] + 1;
        }
    }
    //return the 2nd rank pointer
    return new_mat;
}

int main() {
    int matrix[3][2] = {1, 2, 3, 4, 5, 6};
    int **new_mat;
    int i, j;
    new_mat = add_one(matrix, 3, 2);

    for (i = 0; i < 3; i++) {
        for (j = 0; j < 2; j++) {
            printf("%d  ", new_mat[i][j]);
        }
        printf("\n");
    }
    free(new_mat);
}

However, the compiler told me that

[Error] cannot convert 'int (*)[2]' to 'int**' for argument '1' to 'int** add_one(int**, int, int)'

A: It works a bit differently from what you thought
#include <stdio.h>
#include <stdlib.h>
// you can only pass what you have
int **add_one(int matrix[3][2], int m, int n)
{
  int i, j;
  int **new_mat;
  // allocate m pointers (the rows)
  new_mat = malloc(m * sizeof(*new_mat));

  for (i = 0; i < m; i++) {
    // allocate space for n ints
    new_mat[i] = malloc(n * sizeof(int));
    for (j = 0; j < n; j++) {
      new_mat[i][j] = matrix[i][j] + 1;
    }
  }
  //return the 2nd rank pointer
  return new_mat;
}

int main()
{
  // you forgot to encapsulate the rows, too
  int matrix[3][2] = { {1, 2}, {3, 4}, {5, 6} };
  int **new_mat;
  int i, j;
  new_mat = add_one(matrix, 3, 2);

  for (i = 0; i < 3; i++) {
    for (j = 0; j < 2; j++) {
      printf(" %d ", new_mat[i][j]);
    }
    printf("\n");
  }
  free(new_mat);
}

If you want to pass the two-star matrix as a two-star matrix you need to build it like the new_mat in the function add_one.


text:
Q: Is there a javascript/jquery event to where to detect text in an input element? I would want the function to detect whether there is text in a text field typed in by a user. Not necessarily keyup. I wouldn't want it to fire every time I type in the field. I would want it to detect whether there is text in the field or not.

A: html <input> tags including type='text' support the onchange event.  The onchange event occurs when the value of an element has been changed.

I wouldn't want it to fire every time I type in the field.

in this case, when exactly would you want it to be triggered? onblur event occurs when an object loses focus.

A: You have 2 another events like 'blur' or 'focus'


text:
Q: How find all beacons near you (android)? I need to find all beacons near.I try use code from this: https://altbeacon.github.io/android-beacon-library/samples.html
 But I have Collections with zero. I use nRF Connect (from market) and she shows me all beacons.
I don't understand how to set Beacon Layout and what is it?? Please help me
public class FragmentMain extends Fragment implements BeaconConsumer {
FloatingActionButton fabScan;
RecyclerView recyclerView;
BeaconListAdapter beaconListAdapter;
private BeaconManager beaconManager;
private static final int REQUEST_LOCATION = 1;
protected static final String TAG = "RangingActivity";

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_main, container, false);
    recyclerView = (RecyclerView) v.findViewById(R.id.rcvBeaconsList);
    fabScan = (FloatingActionButton) v.findViewById(R.id.fabScan);
    fabScan.setOnClickListener(onClickListenerScan);
    beaconListAdapter = new BeaconListAdapter(getActivity());
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    recyclerView.setAdapter(beaconListAdapter);
    setHasOptionsMenu(true);
    beaconManager = BeaconManager.getInstanceForApplication(getActivity());
    beaconManager.setForegroundScanPeriod(5000l);
    beaconManager.setBackgroundScanPeriod(5000l);
    beaconManager.setForegroundBetweenScanPeriod(1100l);
    beaconManager.setBackgroundBetweenScanPeriod(1100l);
    beaconManager.bind(this);
    return v;

}

View.OnClickListener onClickListenerScan =new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        onStartScan();
    }
};

private void onStartScan(){
    onBeaconServiceConnect();
}

private void checkPermis(){

    if (ActivityCompat.checkSelfPermission(getContext(),
            android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(getActivity(),
                new String[]{Manifest.permission.BLUETOOTH,
                        },
                REQUEST_LOCATION);
    } else {

       onBeaconServiceConnect();
    }
}

@Override
public void onBeaconServiceConnect() {
    beaconManager.setRangeNotifier(new RangeNotifier() {
        @Override
        public void didRangeBeaconsInRegion(final Collection<Beacon> collection, Region region) {
            if(collection.size() > 0){
              getActivity().runOnUiThread(new Runnable() {
                  @Override
                  public void run() {
                      beaconListAdapter.setNewData((List<Beacon>) collection);
                  }
              });
            Log.i(TAG, "The first beacon I see is about "+collection.iterator().next().getDistance()+" meters away.");}
        }
    });
    try {
        beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null));
    } catch (RemoteException e) {    }
}

@Override
public Context getApplicationContext() {
    return getActivity().getApplicationContext();
}

@Override
public void unbindService(ServiceConnection serviceConnection) {
    getActivity().unbindService(serviceConnection);
}

@Override
public boolean bindService(Intent intent, ServiceConnection serviceConnection, int i) {
    return getActivity().bindService(intent, serviceConnection, i);
}

@Override
public void onDestroy() {
    super.onDestroy();
    beaconManager.unbind(this);
}

}

A: Simply modify this line:
beaconManager = BeaconManager.getInstanceForApplication(getActivity());

To add the following lines afterward:
beaconManager = BeaconManager.getInstanceForApplication(getActivity());
beaconManager.getBeaconParsers().add(new BeaconParser().
            setBeaconLayout("x,s:0-1=feaa,m:2-2=20,d:3-3,d:4-5,d:6-7,d:8-11,d:12-15"));
beaconManager.getBeaconParsers().add(new BeaconParser().
            setBeaconLayout("s:0-1=feaa,m:2-2=00,p:3-3:-41,i:4-13,i:14-19"));

I've only shown you how to add two layouts (the one for EDDYSTONE-TLM and EDDYSTONE-UID).  You probably want to add others, too.  You can see a list of ones you can add here:
https://beaconlayout.wordpress.com/

A: You need to use a layout manager definitely. Are you using Eddystone, iBeacon or what kind of beacons?  I've written an example here, have a look at it: https://solidgeargroup.com/beacons-on-android


text:
Q: RuntimeError: The GPIO channel has not been set up as an OUTPUT My aim is to write a Ros node that publishes the data received from a Sonar installed on my robot car. I use a Raspberry Pi 4B as a microcontroller.Therefore i setted first the raspi pin as out/in for the sonar with the bash command:
$ echo 27 > /sys/class/gpio/export; $ echo out >/sys/class/gpio/gpio27/direction and finally i check if the pin 27 has been setted as output $ cat /sys/class/gpio/gpio27/direction  that outputs out. Now, when i run the following python code trying to access this pin, i get the following error: RuntimeError: The GPIO channel has not been set up as an OUTPUT.
It looks like the pin isn't setted. Please note:

*

*I didn't use the GPIO.setup() method cause the pin is already setted.

*I don't want to use the sudo command on the python script because this has to be runned with the rosrun command

*I setted as well the pin 22 as in

*I tried all conventions for pin numbering: BCM, WiringPi and BOARD

*Python code:

#!/usr/bin/env pyhton
import RPi.GPIO as GPIO
import time

class Sonar:
    def __init__(self):
        self.period = 0.00001
        self.trigger_pin = 27
        self.echo_pin = 22

        GPIO.setwarnings(False)
        GPIO.setmode(GPIO.BCM)
        #GPIO.setup(self.trigger_pin, GPIO.OUT)
        #GPIO.setup(self.echo_pin, GPIO.IN)

    def activateTrigger(self):
        GPIO.output(self.trigger_pin, 1)
        time.sleep(self.period)
        GPIO.output(self.trigger_pin, 0)

    def waitEcho(self, value):
        while GPIO.input(self.echo_pin) == value:
            pass

    def getDistance(self):
        measurements = []
        measurements_num = 3
        for i in range(measurements_num):
            # I activate the trigger
            self.activateTrigger()
            # I am waiting for the echo to turn 1 and i mesure the time ECHO=1
            self.waitEcho(0)
            start = time.time()
            self.waitEcho(1)
            stop = time.time()
            pulse_len = (stop - start)
            distance_cm = pulse_len*17000
            measurements.append(distance_cm)
        # return the average of the measurements
        return int(sum(measurements)/measurements_num)

if __name__=='__main__':
    s = Sonar()
    print('Getting distance...') ```


text:
Q: Put an extra cell in a table without an attached column I am trying to add an extra table cell to a table, that isn't attached to a column.  It just sticks out of the table like a 'bump'  I not entirely sure what kind of styling I would need to achieve this.
What I would like it to look like this:

My code:

    Firstname
    Lastname

    Peter
    Griffin

    Lois
    Griffin
    extra

I would think I need to add an empty  and remove the border from it and then add it to the last cells in the table?

A: I think you want to do like below:

    table{
      border-collapse: collapse;
      border-spacing: 0;
     }
    table tr td:last-child{
      border: none;
    }
    table td, table th{
      border: 1px #666 solid;
    }
    table tr:last-child td:last-child{
      border:  1px #666 solid;
    }

    Firstname
    Lastname

    Peter
    Griffin

    Lois
    Griffin
    extra

A: With javascript, you can do it like (of course you would change nth-child(3) to your target column):

var row = document.createElement('td')
row.innerHTML = 'teste'
document.querySelector('table tr:nth-child(3)').append(row)

    Firstname
    Lastname

    Peter
    Griffin

    Lois
    Griffin
    extra


text:
Q: Text show over Image Hover

PHP/HTML
<?php
    echo "
 See About Page for more info
";
    echo "
";
?>

When I place swap names in the css portion, imagetest for hoverText it works perfectly fine. The drawback with that method is that the div runs across the whole page and wherever the mouse cursor passes through the div the hover pops up. The hover is just not liking the class I stored on the image. I was wondering why this was.

A: Your CSS is trying to select a child element of ".imagetest" that has a class of "hover". Since the span.hover tag is not a child of .imagetest, css will not select it.
Try something like this

             See About Page for more info

This will help CSS find the inner span as a child element of .imagetest
Another option would be to use a CSS selector that selects siblings
.imagetest:hover + .hover {
    visibility: visible;
    display: inline-block;
}

See a list of CSS selectors at W3Schools


text:
Q: How to repeat every 2 cells in google sheets using api I need to repeat the formula in every 2 cells. For instance A1=formula, B1=blank, C1=formula, D1=blank.
Or fill blanks with 0. Is there any possibility to do this?

A: Try this:

 function myFunction() {

    var ss = SpreadsheetApp.getActive()

    for(x=0; x<10; x++){

    ss.getActiveSheet().getRange(1, (x*2)+1, 1, 1).setFormula('=yourFormula');
    ss.getActiveSheet().getRange(1, (x*2)+2, 1, 1).setValue("");

    }
    }

You will have to adjust the x<10 depending on how many times you want it to run. If you want that to be a variable please explain so we can help you with that.

A: You can use also arrayformula like this way :
=arrayformula(if(mod(row(A1:A);2);"my formula";""))

or according to your local parameters
=arrayformula(if(mod(row(A1:A),2),"my formula",""))


text:
Q: Pandas: Efficiently splitting entries I have a Pandas dataframe with columns as such:
event_id, obj_0_type, obj_0_foo, obj_0_bar, obj_1_type, obj_1_foo, obj_1_bar, obj_n_type, obj_n_foo, obj_n_bar, ....
For example:
col_idx = ['event_id']
[col_idx.extend(('obj_%d_id' %d, 'obj_%d_foo' %d, 'obj_%d_bar' %d)) for d in range(5)]
event_id = np.array(range(0,5))
data = np.random.rand(15,5)
data = np.vstack((event_id, data))
df = DataFrame(data.T, index = range(5), columns = col_idx)

I would like to split each individual row of the dataframe so that I'd have a single entry per object, as such:
event_id, obj_type, obj_foo, obj_bar
Where event_id would be shared among all the objects of a given event.
There are lots of very slow ways of doing it (iterating over the dataframe rows and creating new series objects) but those are atrociously slow and obviously unpythonic.  Is there a simpler way I am missing?

A: With some suggestions from some people in #pydata on freenode, this is what I came up with:
data = []
for d in range(5):
    temp = df.ix[:, ['event_id', 'obj_%d_id' % d, 'obj_%d_foo' % d, 'obj_%d_bar' % d]]
    temp.columns = ['event_id', 'obj_id', 'obj_foo', 'obj_bar']
    # Giving columns unique names.
    temp.index = temp['event_id']*10 + d
    # Creating a unique index.
    data.append(temp)

concat(data)

This works and is reasonably fast!


text:
Q: Laravel : How to using group By with sum and select multi field In my Laravel project ,I have users table contain id and username ...etc.
another table called predictors ,both of them related in user_id (one to many),now I want to create array contain username from users table and sum of point field in predictors table.
I tried many thing but don't work like this :
public function leader()
    {
    $predects = Predector::selectRaw(' user_id ,sum(point) as points')->groupBy('user_id')->get();
    foreach($predects as $predect){
        $predect->User->username;
    }
    return $predects;
    }

but it gave me this result
{
    "user_id": 1,
    "points": "3",
    "user": {
        "id": 1,
        "username": "sarmed",
        "nat_id": "123456",
        "email_verified_at": null,
        "created_at": "2020-11-30T17:10:27.000000Z",
        "updated_at": "2020-11-30T17:10:27.000000Z"
    }
},

and I want something like this :
 {
        "user_id": 1,
        "points": "3",
        "username": "sarmed",
    },

A: So if I understand correctly, goal is to get a sum of all points for a user and then provide a dataset of User's id, points and username
Assuming the relation on User model as
class User extends Model
{
    public function predects()
    {
        return $this->hasMany(Predector::class);
    }
}

Try the following snippet to achieve the desired output
public function leader()
{
    return User::query()
        ->with('predects:id,user_id,point')
        ->select('id', 'username')
        ->get()
        ->map(function($user){
            $predects = $user->predects;
            unset($user->predects);
            $user->points = $predects->sum('point');
            return $user;
        })
        ->sortByDesc('points')
        ->toArray();
}

For Laravel versions below 8.x have a look at Laravel Subquery package
https://github.com/Alexmg86/laravel-sub-query  to simplify things a bit more

A: I solved it by adding this line :
unset($predect->User);

now the correct code :
public function leader()
    {

        $predects = Predector::selectRaw(' user_id ,sum(point) as points')->groupBy('user_id')->orderBy('points','desc')->get();
        foreach($predects as $predect){
            $predect->username=$predect->User->username;
            unset($predect->User);
        }
        return $predects;
    }

and the result is :
[
    {
        "user_id": 2,
        "points": "7",
        "username": "sermedov"
    },
    {
        "user_id": 1,
        "points": "3",
        "username": "sarmed"
    }
]


text:
Q: How does Javascript Date print out a string when you console log it? When I create objects in Javascript, and log them out to the console, I nearly always see a Javascript object in the console. For example
var myObj = {
 bla: "foo"
}
console.log(myObj);

will output as
{
  bla: "foo"
}

However, Date acts differently.
When I create a Date, it somehow knows to print out a "String" representing the date of the Date object.
For example:
var myObj = {
     date: new Date()
    }
    console.log(myObj);

gets me
{
   date: Sun Oct 25 2020 18:36:19 GMT-0700 (GMT-04:00)
}

What is the underlying mechanism here?
How can I do the same with my own objects ?

A: This is a special exception the browser has made for Date objects, to make them easy to examine when logged. Otherwise, if the default behavior was followed, you'd get an empty object with no own-properties and no useful information about what the object actually contains:

However, you can observe somewhat similar behavior and display an arbitrary string when something is logged if the thing that's logged gets coerced to a string, by putting a toString method on the object:

const obj = {
  toString() {
    return 'foobar';
  }
};

console.log(String(obj));

To get something that actually logs like Date objects do without any coercion on your part, you'd have to change the browser's internal code. It's not something doable from JS.
There are a few other sorts of built-in objects that have special logging behavior, including:

*

*Arrays

*Functions

*Errors

A: It means that Date object has toString method implemented under the hood.
More reading: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString

A: Actually, the new Date() constructor function does not print a string in the console. It looks like a string but run the typeof operator against it and you'll see it's an object:

const date = new Date()
console.log(date)
console.log(typeof date)

Also, if you are a React developer and will try to use the above date variable between curly brackets in order to output the dynamic content, you'll get an error. If it was a string it would work flawlessly. It is so because objects in the JSX expressions are invalid while strings are perfectly valid.
Again, the result of calling new Date() is an object. It does not look like one but it definitely is an object.
It is also possible to call Date() constructor function without the new keyword in front of it. And guess what? The result of such a call is a normal string that can be used inside of the JSX expression.

const date = Date()
console.log(date)
console.log(typeof date)


text:
Q: JMS MQ binding problem I have this strange issue with a JMS binding on a MQ queue with a MDB

The Message-Driven EJB: CrbEventMessageAsynchronousService is unable to connect to the JMS destination: queue.contratto.crb.input.publicQueue. The Error was:
javax.jms.JMSException: MQJMS1017: non-local MQ queue not valid for receiving or browsing>

I checked on the QueueManager and the mq queue is defined as local and not as remote as said by the exception.

A: It may be that the top-most queue that the application is opening for reading is defined locally.  However, the queue that WMQ is resolving to is not.  For example, if you define a local alias over a remote clustered queue, the resolved queue is non-local.  Another possible cause is that a queue you intend to open for output is actually being opened for input as well.  This is actually quite common.
Finally, it is also somewhat common that the WMQ client is connected to a different queue manager than expected.  For example, the connection is to QMGRA and the queue object specifies a fully-qualified name like QUEUE@QMGRB.  Even though the queue lives on QMGRB and the JNDI object specifies that queue manager by name, the connection on QMGRA resolves it to a transmit queue and therefore sees it as non-local.
One of the best ways to nail this kind of error down in Dev is to use SupportPac MA0W.  This SupportPac runs as an API exit or as a channel exit and lists in human-readable language all of the API calls and all of the options selected for the call.  This will unequivocally show exactly what object name was opened, what it resolved to and the options used.
Alternatively, you can turn on trace using strmqtrc.  Don't forget to disable it with endmqtrc when you are done!  These traces are enabled and disabled on the QMgr server and trace WMQ API calls.  There are equivalent traces to run on the client side but these may not show the level of detail that you require.
Finally, it would be advisable to print any exceptions linked to the JMS exceptions.  The JMS Exception is a multi-level data structure where the linked exception holds provider-specific values.  For example, a JMS Security exception might be a WMQ authorization error.  But then again, it might be an error in the keystore or filesystem.  If the linked exception does not show a WMQ 2035 reason code, it's not a WMQ security error.  The Infocenter describes how to print the linked exception data in the section named Exceptions in WebSphere MQ classes for JMS.
Note that I've provided links to the v7.0 WMQ docs.  If you are coding in v6 these may not be completely accurate and you would want to look in the v6.0 Infocenter instead.  Since v6.0 of WMQ is end-of-life as of September 2011 it is highly recommended to do all new development on v7.0.  If you need the v7.0 client it is downloadable as SupportPac MQC7 and is backward compatible with v6.0 WMQ servers.


text:
Q: STL Map with custom compare function object I want to use the STL's Map container to lookup a pointer by using binary data as a key so I wrote this custom function object:
struct my_cmp
{
    bool operator() (unsigned char * const &a, unsigned char * const &b)
    {
        return (memcmp(a,b,4)<0) ? true : false;
    }
};

And using it like this:
map<unsigned char *, void *, my_cmp> mymap;

This compiles and seems to work, but I'm not sure what an "unsigned char * const &" type is and why it didn't work with just "unsigned char *"?

A: You need to provide a comparator that guarantees non-modifying of the passed values, hence the const (note that it applies to the pointer not the char). As for the reference operator (&), you don't need it -- it's optional. This will also compile:
struct my_cmp
{
    bool operator() (unsigned char * const a, unsigned char * const b)
    {
        return memcmp(a,b,4) < 0;
    }
};

A: It works for me with just unsigned char *.


text:
Q: Ignoring first n digits when importing data from .dat file into matlab I want to import data from .dat file into matlab workspace;however i don't want the first 5 digits.
34826
-82.7553 -18.7702 -2292.59,
-83.7271 -19.3224 -2291.53,

How can i do that? actually i came to the solution of removing those 5 digits from .dat file, but there must be an automatic way for that
my code is like this
fileID = fopen('temp.dat');
C = textscan(fileID,'%f %f %f','Delimiter',',');
fclose(fileID);

Thanks for your help

A: You can skip the first lines of the file you import using the 'HeaderLines' option of textscan, followed by the number of rows to skip.
nRowsToSkip = 1;
C = textscan(fileID, '%f %f %f','Delimiter',',', 'HeaderLines',nRowsToSkip);


text:
Q: Magento Hole puch With Varnish I recently installed the varnish 3.x in system (ubuntu) and configured it to 8080.
Now full page caching is enabled and its working fine. I just want to ignore some
specific dynamic blocks of the page. How can i do with magento. Also i am not
using Magentos default caching techniques so i disabled it. also tried module Terpentine
Thanks & Regard
Rajesh Ganjeer

A: I have done this using
Try this in local.xml  inside the app/design/frontend/XXX/XXX/layout/local.xml file:
<reference name="block name">
    <action method="setEsiOptions">
        <params>
            <access>private</access>
            <flush_events>
                <wishlist_item_save_after/>
                <wishlist_item_delete_after/>
                <sales_quote_save_after/>
                </flush_events>
        </params>
    </action>
</reference>`

OR
<reference name="block name">
    <action method="setEsiOptions">
        <params>
            <access>private</access>
            <ttl>0</ttl>
        </params>
    </action>
</reference>`

OR
<reference name="block name">
<action method="setEsiOptions">
    <params>
        <access>private</access>
        <method>ajax</method>
    </params>
</action>
</reference>`

OR
Whole page will ignore cached eg. one page module checkout_onepage_index
<checkout_onepage_index>
    <turpentine_cache_flag value="0"/>
</checkout_onepage_index>

I tried this using module Nexcessnet Turpentine. and it works
For your reference after Turpentine installation :
app/design/frontend/base/default/layout/turpentine_esi.xml
Thanks a lot for your feedbacks.
Reference Sites :
http://www.magentocommerce.com/magento-connect/turpentine-varnish-cache.html
https://github.com/nexcess/magento-turpentine
Thanks & Regards
Rajesh Ganjeer

A: Follow this to start to end solutions for varnish
http://rajeshganjeer.wordpress.com/2014/05/28/varnish-with-magento-terpentine/

A: Try this in layout.xml file:
 <reference name="block name">
      <action method="setCacheLifetime"><s>null</s></action>
  </reference>

if you want to disable in phtml file then use false after block name like this:
<?php echo $this->getChildHtml('topLinks',false) ?>

and if you want to disable from php file then use this code in specific Block class:
public function getCacheLifetime() { return null; }

Hope this helps. All the best!

A: Using Turpentine will be the way to go.
The specific link you are looking for is to:
https://github.com/nexcess/magento-turpentine/wiki/ESI_Cache_Policy
With the detail being:

The default ttl if not specified is a little complex: If access is
  private, then if method is ajax the default ttl is 0 (not cached)
  otherwise the default cookie expiration time is used. If access is
  global then the default page TTL is used (regardless of method).

Implemented like:
<reference name="block name">
    <action method="setEsiOptions">
        <params>
            <access>private</access>
            <ttl>0</ttl>
        </params>
    </action>
</reference>


text:
Q: Efficient way of serializing/deserializing JSON for ASP.net MVC I have thousands of JSON objects in my ASP.NET MVC project. I want to quickly save and load them to/from the file system and parse to JSON.
My current implementation is just save all the data into text file (file content is in json format). But sometimes this save takes around a few minutes. Is there a way of optimizing this?


text:
Q: Is it ok to use BCrypt's generate_salt method to create a token for password resetting in ruby on rails? I'm creating a password_reset feature in rails the same way I did it when I used codeigniter.
For a user to reset their password, they type in their email address and click a button. The token is generated and stored in the database, and an email is sent to their email address with a URL containing that token.
When user clicks the link in the email, a method is called that checks that the token in their email matches the token stored in the db.
Now my question is: is it ok to use BCrypt's generate_salt method to generate this token, or is there some other way I should be doing this?

A: SecureRandom.hex is more suitable in that case.

A: since the modern encrption mechanism like shai doesnt allow decryption of the currrent passwords it is mandatory one to generate a new password. bcrypt should be fine doing this


text:
Q: How to show aonce and then hide my socialproof popup on mobile? I have two social proof pop-ups (one page visit, the other bought products).
Everything works fine because the popup appears and disappears, but I would like the popup to appear only once on the mobile and then hide it.

(function($) {
  //VARS
  let productsBuy = parseInt("{% socialproof %} debc5b96-be0e-495d-938f-5a1fb5af9101 {% endsocialproof %}");
  let count = 'sztuk';
  let num = parseInt("{% socialproof %} 012a023f-e69a-4e61-9690-adcdf19e082b {% endsocialproof %}");

  //IFS

  //productsBUY
  if (productsBuy < 1) {
    productsBuy = 4;
  } else if (productsBuy > 2 & productsBuy < 3) {
    productsBuy = 7 * 2;
  } else {
    productsBuy = productsBuy * 4;
  }
  //sztuki
  if (productsBuy < 5) {
    count = 'sztuki';
  } else {
    count;
  }
  //productsWatch
  if (num < 1) {
    num = 11;
  } else {
    num = num * 9;
  }

  function langVariations(num) {
    const smallList = [2, 3, 4];
    const bigList = [0, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21];
    let persons = "osoba ogląda";
    const lenght = Math.ceil(Math.log(num + 1) / Math.LN10);
    let value = num.toString().slice(lenght - 2);
    if (num < 1) {
      return `Jeszcze nikt nie kupił tego produktu, bądź pierwszy`;
    } else if (value == 1) {
      return `${num} ${persons} osoba ogląda`;
    } else if (value > 21) {
      const last = value.toString().slice(-1);
      if (smallList.includes(Number(last))) {
        persons = "osoby oglądają "
      } else {
        persons = "osób ogląda"
      }
    } else {
      if (bigList.includes(Number(value))) {
        persons = "osób ogląda"
      } else if (smallList.includes(Number(value))) {
        persons = "osoby oglądają"
      }
    }
    return `<b>${num}</b> ${persons} ten produkt`;
  };

  //FUNCTIONS
  (() => {
    const outOfStockBadge = document.querySelector('.out-of-stock-badge');
    outOfStockBadge ? null : init();

    function init() {
      insertBanner();
    }
  })();

  // functions
  function insertBanner() {
    const insertPlace = document.querySelector('.woocommerce-product-gallery');
    const html = `

                W ciągu 24h zakupiono ${productsBuy} ${count}

                 ${langVariations(num)}

`;

    insertPlace.insertAdjacentHTML('beforebegin', html);
  }

  // (function($){
  //     setInterval(function() {
  //         $('.custom-social-proof').toggleClass('active');
  //     }, 4000);
  // })(jQuery);
  // (function($){
  //     setInterval(function() {
  //         $('.custom-social-proof2').toggleClass('active');
  //     }, 5000);
  // })(jQuery);

  (function($) {
    function customNotificationToggleClass() {
      $('.custom-social-proof').toggleClass('active');
    }

    customNotificationToggleClass();

    if (window.innerWidth > 768) {
      setInterval(function() {
        customNotificationToggleClass();
      }, 5000);
    }
  })(jQuery);

  (function($) {
    function customNotificationToggleClass() {
      $('.custom-social-proof2').toggleClass('active');
    }

    customNotificationToggleClass();

    if (window.innerWidth > 768) {
      setInterval(function() {
        customNotificationToggleClass();
      }, 6000);
    }
  })(jQuery);
})(jQuery);
.custom-social-proof {
  position: relative;
  bottom: -460px;
  left: 60px;
  font-family: 'Open Sans', sans-serif;
  -webkit-transform: translateY(20%);
  -ms-transform: translateY(20%);
  transform: translateY(20%);
  -webkit-transition: opacity 1s ease, -webkit-transform 1s ease;
  transition: opacity 1s ease, -webkit-transform 1s ease;
  -o-transition: transform 1s ease, opacity 1s ease;
  transition: transform 1s ease, opacity 1s ease;
  transition: transform 1s ease, opacity 1s ease, -webkit-transform 1s ease;
  opacity: 0;
  z-index: 3;
}

.custom-social-proof.active {
  -webkit-transform: translateY(0);
  -ms-transform: translateY(0);
  transform: translateY(0);
  opacity: 1;
}

.custom-social-proof2 {
  position: relative;
  bottom: -420px;
  left: 60px;
  font-family: 'Open Sans', sans-serif;
  -webkit-transform: translateY(20%);
  -ms-transform: translateY(20%);
  transform: translateY(20%);
  -webkit-transition: opacity 1s ease, -webkit-transform 1s ease;
  transition: opacity 1s ease, -webkit-transform 1s ease;
  -o-transition: transform 1s ease, opacity 1s ease;
  transition: transform 1s ease, opacity 1s ease;
  transition: transform 1s ease, opacity 1s ease, -webkit-transform 1s ease;
  opacity: 0;
  z-index: 3;
}

.custom-social-proof2.active {
  -webkit-transform: translateY(0);
  -ms-transform: translateY(0);
  transform: translateY(0);
  opacity: 1;
}

.custom-notification {
  width: 240px;
  border: 0;
  text-align: left;
  z-index: 3;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  font-weight: 400;
  border-radius: 6px;
  -webkit-box-shadow: 2px 2px 10px 2px hsla(0, 4%, 4%, 0.2);
  box-shadow: 2px 2px 10px 2px hsla(0, 4%, 4%, 0.2);
  background-color: #fff;
  cursor: pointer;
  position: absolute;
}

.custom-notification2 {
  width: 240px;
  border: 0;
  text-align: left;
  z-index: 3;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  font-weight: 400;
  border-radius: 6px;
  -webkit-box-shadow: 2px 2px 10px 2px hsla(0, 4%, 4%, 0.2);
  box-shadow: 2px 2px 10px 2px hsla(0, 4%, 4%, 0.2);
  background-color: #fff;
  cursor: pointer;
  position: absolute;
}

.custom-notification-container {
  display: -webkit-box !important;
  display: -ms-flexbox !important;
  display: flex !important;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  height: 30px;
}

.custom-notification-image-wrapper img {
  max-height: 12.5px;
  width: 12.5px;
  overflow: hidden;
  border-radius: 6px 0 0 6px;
  -o-object-fit: cover;
  object-fit: cover;
  margin-left: 10px;
}

.custom-notification-content-wrapper {
  margin: 0;
  height: 100%;
  color: #000000;
  padding-left: 8px;
  padding-right: 20px;
  border-radius: 0 6px 6px 0;
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
  display: -webkit-box !important;
  display: -ms-flexbox !important;
  display: flex !important;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -ms-flex-direction: column;
  flex-direction: column;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
}

.custom-notification-content {
  font-family: inherit !important;
  /* margin: 0 !important; */
  padding: 0 !important;
  font-size: 12px;
  top: 50%;
  -webkit-transform: translateY(20%);
  -ms-transform: translateY(20%);
  transform: translateY(20%);
}

img {
  vertical-align: baseline;
}

@media screen and (max-width: 700px) {
  .custom-social-proof {
    bottom: -300px;
    left: 30px;
  }
  .custom-social-proof2 {
    bottom: -260px;
    left: 30px;
  }
}


text:
Q: Python - keeping counter inside list comprehension Is it possible to write a list comprehension for the following loop?
m = []
counter = 0
for i, x in enumerate(l):
    if x.field == 'something':
        counter += 1
        m.append(counter / i)

I do not know how to increment the counter inside the list comprehension.

A: You could use an itertools.count:
import itertools as IT
counter = IT.count(1)
[next(counter)/i for i, x in enumerate(l) if x.field == 'something']

To avoid the possible ZeroDivisionError pointed out by tobias_k, you could make enumerate start counting from 1 by using enumerate(l, start=1):
[next(counter)/i for i, x in enumerate(l, start=1)
 if x.field == 'something']


text:
Q: How can I have a full or in Ruby regular expression? I want to check if a non letter/number or \W is at the beginning or the end of a variable, just a true or false. The usual code that I would use would be:
str.match( /^\W) || str.match( /\W$/ )

Of course, one could accomplish that using mutltiple ways, such as:
[ /^\W/, /\W$/ ].index{ | regy | str.match( regy ) }

however, I would like to know if there is a way to this in one regular expression. I.e.
str.match( regy ) # the single regexp handles the or part on it's own.

Thanks

A: Yes. Use the | in regex:
/^\W|\W$/


text:
Q: javascript only work in 1 data I'm trying to get button hidden using javascript.
here the javascript code:

<script>
    var btn = document.getElementById("view1");
    var a="<?php echo $data[0]->status==1;?>";
    if(!a==0){
        btn.style.display = 'none';
    }
</script>
<script>
    var btn = document.getElementById("view2");
    var a="<?php echo $data[0]->status;?>";
    if(!a==0){
        btn.style.display = 'none';
    }
</script>

but actually only 1 data javascript worked

A: You can't have multiple elements with the same ID in one HTML document. IDs (identifiers) are supposed to be unique. Look into name or class and selecting multiple elements using document.getElementsByName or document.getElementsByClassName.
Alternatively, if your HTML is generated from PHP as well, display / hide the buttons in the HTML directly.


text:
Q: input changes getting previous value I'm getting the previous value in console when i write in the input, how can i get the actual value?

const input1 = document.querySelector('#a')

input1.addEventListener('keypress', (e) => {
    console.log(e.target.value)
})
<input type="text" id="a" />

A: Try eventListener input. Keydown is fired before the character is added to the field, which is why you don't see the 4 after typing 1234. (An if you prevent the default action of keydown, the character is never added.) keyup is also fired after the character is added.

const input1 = document.querySelector('#a')

input1.addEventListener('input', (e) => {
    console.log(e.target.value)
})
<input type="text" id="a" />

A: The easiest way is just to change keydown to keyup event listener. It will work for your case.
input1.addEventListener('keyup', (e) => {
   console.log(e.target.value)
})

A better way will be if you use event listener "input".
input1.addEventListener('input', (e) => {
   console.log(e.target.value)
})

A: hello freind i want provide you how to listen input event
if this case have many method:
1)
<input name="name" id="a"/>
document.querySelector("input#a").addEventListener("input",function(event){
console.log(event.target.value);})


text:
Q: newenvironment behaving differently inside another environment Friends,
Please have a look at the code below.
The problem is the environment hlcard is behaving differently when it is inside card environment, or directly under frame. I have picked the card environment directly from net, and doesn't have much clue what those long optional argument is doing. Kindly help.
The behaivour directly inside frame is the expected behaviour
\documentclass[12pt]{beamer}
\usepackage[customcolors,shade]{hf-tikz}
\usetikzlibrary{arrows,shadows,petri,decorations.markings,shapes}
\RequirePackage[many]{tcolorbox}
\definecolor{dcol}{HTML}{3F51B5}
\definecolor{BGgrey03}{RGB}{190,190,190}
\definecolor{BGgrey04}{RGB}{230,230,230}
\usecolortheme[named=dcol]{structure}
\usepackage{biblatex}

\tcbset{%
colback=BGgrey04, colbacktitle=dcol, coltitle=white, coltext=dcol,%
enhanced, sharpish corners=all,%
fuzzy shadow={0mm}{0.9mm}{0.6mm}{0.2mm}{black!20!BGgrey03}, % top
fuzzy shadow={0mm}{-0.6mm}{-0.1mm}{0.2mm}{black!40!BGgrey03}, % bottomSmall
fuzzy shadow={0mm}{-0.2mm}{-0.2mm}{0.2mm}{black!20!BGgrey03}, % bottomBig
left=6mm, right=6mm, top=6mm, bottom=6mm, middle=4mm,%
title filled, boxrule=0mm, %
segmentation code={\path[draw=BGgrey01](segmentation.west) -- (segmentation.east);}%
}

\newenvironment{card}[1][pR23s2OTKY]{%
    \ifthenelse{\equal{#1}{pR23s2OTKY}}{%
      \begin{tcolorbox}%
    }{%
      \begin{tcolorbox}[colbacktitle=dcol, coltitle=white, title=#1, left=1mm, right=6mm, top=1mm,
        bottom=1mm, middle=4mm, toptitle=1mm, bottomtitle=1mm, ]%
    }%
}{%
  \end{tcolorbox}%
}

\newenvironment{hlcard}[1][pR23s2OTKY]{%
      \begin{tcolorbox}[noparskip, breakable, colback=dcol,%
          coltitle=black,coltext=white, fonttitle={\bfseries \scshape}, left=1mm, right=6mm, top=1mm,
        bottom=1mm, middle=4mm, toptitle=1mm, bottomtitle=1mm,]%
}{%
  \end{tcolorbox}%
}

\begin{document}
\begin{frame}
\begin{card}[Problem]
  \begin{hlcard}
    Foo
  \end{hlcard}
\end{card}
  \begin{hlcard}
    Bar
  \end{hlcard}
\end{frame}
\end{document}

A: The \tcbset macro provides for .style options, i.e. collections of specific tcolorbox (or tikz/pgfkeys), otherwise any option that is not 'wrapped' in a .style is used globally and has a side effect on tcolorbox 'layers'
Nested boxes are reset, using a default setting and the global values from tcbset.
I suggest to use an outerlayer style and an innerlayer style which calls outerlayer first, then applies its own settings.
Also the environments should be defined with \newtcolorbox instead of wrapping them in \newenvironment macros.
\documentclass[12pt]{beamer}
\usepackage[customcolors,shade]{hf-tikz}
\usetikzlibrary{arrows,shadows,petri,decorations.markings,shapes}
\RequirePackage[many]{tcolorbox}
\definecolor{dcol}{HTML}{3F51B5}
\definecolor{BGgrey03}{RGB}{190,190,190}
\definecolor{BGgrey04}{RGB}{230,230,230}
\usecolortheme[named=dcol]{structure}
\usepackage{biblatex}

% Common options
\tcbset{%
  left=6mm, right=6mm, top=6mm, bottom=6mm, middle=4mm,
}

\tcbset{
  outerlayer/.style={
    enhanced,
    sharpish corners=all,
    colbacktitle=dcol,
    coltitle=white,
    left=1mm,
    right=6mm,
    top=1mm,
    bottom=1mm,
    middle=4mm,
    toptitle=1mm,
    bottomtitle=1mm,
    fuzzy shadow={0mm}{0.9mm}{0.6mm}{0.2mm}{black!20!BGgrey03}, % top
    fuzzy shadow={0mm}{-0.6mm}{-0.1mm}{0.2mm}{black!40!BGgrey03}, % bottomSmall
    fuzzy shadow={0mm}{-0.2mm}{-0.2mm}{0.2mm}{black!20!BGgrey03}, % bottomBig
    title filled, boxrule=0mm, %
    segmentation code={\path[draw=BGgrey01](segmentation.west) -- (segmentation.east);}
},
  innerlayer/.style={outerlayer,
    noparskip,
    breakable,
    colback=dcol,%
    coltitle=black,
    coltext=white,
    fonttitle={\bfseries \scshape},
    bottomtitle=1mm}
}

\newtcolorbox{card}[1][]{%
  outerlayer,
  title=#1,
}

\newtcolorbox{hlcard}[1][]{%
  innerlayer,
  #1
}

\begin{document}
\begin{frame}
\begin{card}[Problem]
  \begin{hlcard}
    Foo
  \end{hlcard}
\end{card}
\begin{hlcard}
  Bar
\end{hlcard}
\end{frame}
\end{document}


text:
Q: How to delete a specific line when it equals a certain text? I have the following code which is put into the Index Worksheet I have in my workbook.  It creates a hyperlink to each worksheet on my "Index" tab and should create a hyperlink in Cell "A1" called Back to Index.  It's working perfectly fine however if I ever add a new worksheet I have to go through tab by tab and delete the first line, I've looked into the issue and haven't been able to come up with anything to resolve the issue.
In short I want to delete Row 1 on each worksheet that contains the text "Back to Index" in cell "A1".  Would anyone have any suggestions on this?  Thank you very much for anyone who can offer advice on the issue.
Sub TCIndex()
Dim wSheet As Worksheet
Dim l As Long
Dim lastRow As Long

l = 1

With Me
    .Columns(1).ClearContents
    .Cells(1, 1) = "INDEX"
    .Cells(1, 1).Name = "Index"
    .Rows(1).HorizontalAlignment = xlCenter
    .Rows(1).Font.Size = 14
    .Rows(1).RowHeight = 18
    .Columns(1).ColumnWidth = 60
    .Range("A1").Interior.Color = RGB(0, 0, 0)
    .Range("A1").Font.Color = RGB(255, 255, 255)
    .Range("A1").Font.Bold = True
    .Range("A1:A1").Borders.LineStyle = xlContinuous
    .Range("A2:A70").RowHeight = 15
    .Range("A2:A70").VerticalAlignment = xlCenter
End With

lastRow = Range("A1").End(xlDown).Row

For Each Cell In Range("A2:A" & lastRow)
    If Cell.Row Mod 2 = 1 Then
        Cell.Interior.Color = RGB(200, 200, 200)
    Else
        Cell.Interior.ColorIndex = xlNone
    End If
Next Cell

For Each wSheet In Worksheets
    If wSheet.Name <> Me.Name Then
        l = l + 1
        With wSheet
            .Range("A1").Name = "Start_" & wSheet.Index
            .Range("A1").EntireRow.Insert
            .Hyperlinks.Add Anchor:=.Range("A1"), Address:="", _
            SubAddress:="Index", TextToDisplay:="Back to Index"
        End With
        Me.Hyperlinks.Add Anchor:=Me.Cells(l, 1), Address:="", _
    SubAddress:="Start_" & wSheet.Index, TextToDisplay:=wSheet.Name
    End If
Next wSheet
End Sub

A: To answer your question
I want to delete Row 1 on each worksheet that contains the text "Back to Index" in cell "A1".
for each wrkSht in worksheets
    if wrkSht.[A1] = "Back to Index" then
        wrkSht.rows(1).delete
    endif
next wrkSht


text:
Q: Google drive API : How to find all files I shared with others I am using drive api v3 to look for files I hare shared with others (anyone),to list them & potentially cancel sharing them.
I know that in the search box you can do a 'to:' and it will retrieve these files, but I could not use such thing on the API.
my current tri ;
query="'me' in owners and trashed=false and not mimeType = 'application/vnd.google-apps.folder' and visibility != 'limited'"

Thanks in advance

A: As tanaike said, a workaround that solves the problem is by looping through the files using files.list() function, and including id, owners, permissions in the fields. This is going to return a list of objects, and from there we can check if type is anyone.
From there, we can also check for attributes like shared:true & ownedByMe:true.
This is just a workaround, and surely not the best solution, since with Drive search, we can do all this by typing to:, which lists all owr shared files. I hope we get an API for this.
Thanks again tanaike


text:
Q: Using OR operator in React js conditional rendering I want to conditionally render a button based on two conditions.
Am not really sure if am doing it the right way.
But i get this error This condition will always return 'true' since the types '"started"' and '"cancelled"' have no overlap.ts(2367) where the red underline is.
Am using React js with typescript

A: When you are checking for multiple values, you can simplify with includes method
{ !["started", "cancelled"].includes(journey) && <Button> Cancel Journey </Button> }

Alternatively
{ journey === "stopped" && <Button> Cancel Journey </Button> }

or
{ ["stopped"].includes(journey) && <Button> Cancel Journey </Button> }

A: You have a logical error. A variable can not have two values at the same time which means that journey !== "started" || journey !== "cancelled" will always be true.
You probably want to use journey === "started" in order to display the Cancel Button

A: If there are only two options in your condition like "stared" and "cancelled" you can add ternary operator.
{journey === "stared" ? <Button>Journey Started</Button> : <Button>Journey Cancelled </Button>}

But if more options like ("stared","cancelled","completed","any other")
  {journey === "stared" && <Button>Journey Started</Button> }
  {journey === "cancelled" && <Button>Journey cancelled</Button> }
  {journey === "completed" && <Button>Journey completed</Button> }

This is an optional thing, It's a best practice not to use strings directly in conditions. Better you define them as type, or enum,(If using typescript with React) or just costs;
const STARTED = "started"
const COMPLETED = "completed"
const CANCELED = "canceld"

const journey = STARTED // Or anything the matches with the requirement.

{journey === STARTED ? <Button>Journey Started</Button> : <Button>Journey Cancelled </Button>}


text:
Q: Error partitioning and formatting USB flash drive in C++ I'm stuck attempting to re-partition and format a USB flash drive using C++, any help would be great!
The goal is to re-partition any arbitrary flash drive with a single partition taking the entire space and formatted FAT32 (later options NTFS and EXFAT).  This will be done in batch, hopefully with 50+ devices at once, so drive letter access is not an option.  I'm able to create a partition, but when I try IOCTL_DISK_SET_PARTITION_INFO_EX to set the format type, it is failing with 0x32, ERROR_NOT_SUPPORTED.  But it's not clear what exactly is not supported.  I can manually partition the device using utilities such as diskpart, so I know the partition and file system types are supported by the device.  Can anyone help?  My full source code is below, it's failing on the DeviceIoControl() call with IOCTL_DISK_SET_PARTITION_INFO_EX.
#include "stdafx.h"
#include <random>
#include <Windows.h>
#include <atlstr.h>
#include <iostream>
#include <assert.h>

using namespace std;

#define THROW_CSTRING(a, b) { CString csE; csE.Format(a, b); throw csE; }
#define RANDOM_DWORD {DWORD(rand()) | DWORD(rand() << 8) | DWORD(rand() << 16) | DWORD(rand() << 24)}

int main()
{
  DRIVE_LAYOUT_INFORMATION_EX* pdg = NULL;
  HANDLE hDevice = INVALID_HANDLE_VALUE;

  try
  {

    hDevice = CreateFile(L"\\\\.\\PhysicalDrive2",
                          GENERIC_READ | GENERIC_WRITE,
                          0,              // Only we can access
                          NULL,           // Default security
                          OPEN_EXISTING,  // For hardware, open existing
                          0,              // File attributes
                          NULL);          //Do not copy attributes
    if (hDevice == INVALID_HANDLE_VALUE)
    {
      THROW_CSTRING(L"ERROR: CreateFile() failed: 0x%x", GetLastError());
    }

    CREATE_DISK dsk;
    memset(&dsk, 0, sizeof(dsk));
    CREATE_DISK_MBR dskmbr = { 0 };
    dskmbr.Signature = 1;
    dsk.PartitionStyle = PARTITION_STYLE_MBR;
    dsk.Mbr = dskmbr;

    // DRIVE_LAYOUT_INFORMAITON_EX has an array of partition info at the end, need enough for 4 partitions minimum
    int iDriveLayoutBytesRequired = sizeof(DRIVE_LAYOUT_INFORMATION_EX) + sizeof(PARTITION_INFORMATION_EX) * 3;
    pdg = (DRIVE_LAYOUT_INFORMATION_EX*)new BYTE[iDriveLayoutBytesRequired];
    memset(pdg, 0, iDriveLayoutBytesRequired);

    DRIVE_LAYOUT_INFORMATION_MBR mbrlayout = { 0 };
    mbrlayout.Signature = RANDOM_DWORD;
    pdg->PartitionStyle = PARTITION_STYLE_MBR;
    pdg->Mbr = mbrlayout;
    pdg->PartitionCount = 1;

    DWORD dwBytesReturned = 0;

    if (!DeviceIoControl(hDevice, IOCTL_DISK_CREATE_DISK, &dsk, sizeof(dsk), NULL, 0, &dwBytesReturned, NULL))
    {
      THROW_CSTRING(L"ERROR: IOCTL_DISK_CREATE_DISK failed: 0x%x", GetLastError());
    }

    // Get the drive dimensions, then use that info to create a new partition

    // Drive length
    GET_LENGTH_INFORMATION sLenInfo = { 0 };
    if (!DeviceIoControl(hDevice, IOCTL_DISK_GET_LENGTH_INFO, NULL, 0, &sLenInfo, sizeof(sLenInfo), &dwBytesReturned, NULL))
    {
      THROW_CSTRING(L"ERROR: IOCTL_DISK_GET_LENGTH_INFO failed: 0x%x", GetLastError());
    }
    assert(sizeof(sLenInfo.Length.QuadPart) == sizeof(__int64));
    __int64 iDiskLengthBytes = sLenInfo.Length.QuadPart;

    pdg->PartitionStyle = PARTITION_STYLE_MBR;
    pdg->PartitionCount = 4;
    pdg->Mbr.Signature = 1;

    pdg->PartitionEntry[0].PartitionStyle = PARTITION_STYLE_MBR;
    pdg->PartitionEntry[0].StartingOffset.QuadPart = 0;
    pdg->PartitionEntry[0].PartitionLength.QuadPart = iDiskLengthBytes;
    pdg->PartitionEntry[0].PartitionNumber = 1;
    pdg->PartitionEntry[0].RewritePartition = TRUE;

    //pdg->PartitionEntry[0].Mbr.PartitionType = PARTITION_IFS; // NTFS
    pdg->PartitionEntry[0].Mbr.PartitionType = PARTITION_FAT32;
    pdg->PartitionEntry[0].Mbr.BootIndicator = TRUE;
    pdg->PartitionEntry[0].Mbr.RecognizedPartition = 1;
    pdg->PartitionEntry[0].Mbr.HiddenSectors = 0;

    // Partition device
    if (!DeviceIoControl(hDevice, IOCTL_DISK_SET_DRIVE_LAYOUT_EX, pdg, iDriveLayoutBytesRequired, NULL, 0, &dwBytesReturned, NULL))
    {
      THROW_CSTRING(L"ERROR: IOCTL_DISK_SEt_DRIVE_LAYOUT_EX failed: 0x%x", GetLastError());
    }

    // Tell the driver to flush its cache
    if (!DeviceIoControl(hDevice, IOCTL_DISK_UPDATE_PROPERTIES, NULL, 0, NULL, 0, &dwBytesReturned, NULL))
    {
      THROW_CSTRING(L"ERROR: IOCTL_DISK_UPDATE_PROPERTIES failed: 0x%x", GetLastError());
    }

    SET_PARTITION_INFORMATION_EX dskinfo;
    memset(&dskinfo, 0, sizeof(dskinfo));
    dskinfo.PartitionStyle = PARTITION_STYLE_MBR;
    dskinfo.Mbr.PartitionType = PARTITION_FAT32;

    if (!DeviceIoControl(hDevice, IOCTL_DISK_SET_PARTITION_INFO_EX, &dskinfo, sizeof(dskinfo), NULL, 0, &dwBytesReturned, NULL))
    {
      THROW_CSTRING(L"ERROR: IOCTL_DISK_SET_PARTITION_INFO_EX failed: 0x%x", GetLastError());
    }

  }

  catch (CString csErr)
  {
    // Error lookup: https://msdn.microsoft.com/en-us/library/w indows/desktop/ms681382(v=vs.85).aspx
    // 0x7a - ERROR_INSUFFICIENT_BUFFER
    // 0x57 - ERROR_INVALID_PARAMETER
    // 0x32 - ERROR_NOT_SUPPORTED
    // 0x18 - ERROR_BAD_LENGTH
    // 0x05 - ERROR_ACCESS_DENIED
    wcout << csErr.GetString();
  }

  CloseHandle(hDevice);
  delete pdg;
  return 0;
}

A: I have a solution, but it's a bit convoluted.  I'm using DeviceIoControl() as above to partition the disk.  Then I use VDS and the IID_IVdsVolumeMF interface to create the file system, but getting there is a bit of work.  The goal is to partition and format all flash drives (USB sticks) on the system.  VDS will perform the format via the IID_IVdsVolumeMF interface, BUT it will not tell you (at least I haven't figured out how) which devices are removable.  But WMI will tell you which devices are removable, but doesn't have a format function.  So...
First use WMI to get a list of all removable volume paths on the system, for example:
CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *)&pLoc)
pLoc->ConnectServer(CComBSTR(L"ROOT\\CIMV2"), nullptr, nullptr, nullptr, 0, nullptr, nullptr, pWbemSvc)
CoSetProxyBlanket(
                                      *pWbemSvc,                        // Indicates the proxy to set
                                      RPC_C_AUTHN_WINNT,           // RPC_C_AUTHN_xxx
                                      RPC_C_AUTHZ_NONE,            // RPC_C_AUTHZ_xxx
                                      NULL,                        // Server principal name
                                      RPC_C_AUTHN_LEVEL_CALL,      // RPC_C_AUTHN_LEVEL_xxx
                                      RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
                                      NULL,                        // client identity
                                      EOAC_NONE                    // proxy capabilities

pWbemSvc->ExecQuery(CComBSTR(L"WQL"), CComBSTR(L"SELECT * FROM Win32_Volume WHERE DriveType=2"), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator)

Gives you paths such as:
 L"\\\\?\\Volume{3899cb7b-7c3f-11e6-bf82-005056c00008}\\"

Then use VDS to get a list of all VDS volumes on the machine.  Basically you load VDS, then get all software providers.  This source is missing parts for brevity, but I think I left enough to explain what's happening:
pSvc->QueryProviders(VDS_QUERY_SOFTWARE_PROVIDERS, &pEnumProviders)

Now iterate through the list of providers getting the packs from each provider:
pEnumProviders->Next(1, &pUnk, &cFetched)
pProv = pUnk;
pProv->QueryPacks(&pEnumpacks)
vPacks.push_back(pEnumpacks);

Now iterate through the packs and get all of the volumes in each pack:
iterator iPacks = vPacks.begin();
(*iPacks)->Next(1, &pUnk, &cFetched)
pPack = pUnk;
pPack->QueryVolumes(&pEnumvolumes)
pvpEnumvolumes->push_back(pEnumvolumes)

Now you have a list of paths to removable devices, and you have a list of all volumes on the system.  Time to compare them and figure out which volumes are removable.
iVolEnum = pvpEnumOfVDSVolumes->begin()
(*iVolEnum)->Next(1, &pUnk, &cFetched)
pVMF3 = pUnk;
CComHeapPtr<LPWSTR> pVDSVolumePaths;
pVMF3->QueryVolumeGuidPathnames(&pVDSVolumePaths, &nPaths)
iterator iWMIVolPath = pvWMIRemovableVols->begin();
loop..
if (wcscmp(iWMIVolPath->data(), pVDSVolumePaths[i]) == 0)
{  // VDS Vol is removable! }

Now use this VDS volume object to format the volume:
foreach( vol in vRemovableVDSVols )
{
CComQIPtr<IVdsVolume> pVolume = *(vol);
IVdsVolumeMF *pVolumeMF;
pVolume->QueryInterface(IID_IVdsVolumeMF, (void **)&pVolumeMF);
pVolumeMF->Format(  VDS_FST_FAT32,
                              L"MyFob",
                              512, // alloc size
                              true, // force
                              false, // quick
                              false, // compression
                              &pAsync); // async
}

And presto your USB stick is formatted!  Whew.. but it seems to be working.
Could Microsoft really not have made this any easier?


text:
Q: How can I add Actions to the tool-bar in the Dashboard of Jupyter Notebook? I'm creating a custom front-end extension for Jupyter Notebook. The actions will be triggered via buttons in the Notebook Dashboard and the Notebook Editor.
The extension will affect single or multiple files (like the already existing "Move", "Duplicate", etc -Buttons do). So the resulting button might look like this:

I can already place buttons in the tool-bar of the Notebook Editor, thanks to this tutorial, but I'm still unable to add actions to the toolbar in the Dashboard.
How can I add Actions to the tool-bar in the Dashboard of jupyter?

A: You can use a bit of jQuery to get this effect. For instance, if you want your button to appear before the Delete button, you can add something like
$('<button/>')
    .addClass('my-new-button btn btn-default btn-xs')
    .attr('title', 'My New Button')
    .attr('aria-label', 'My New Button')
    .text('My New Button')
    .insertBefore('.delete-button')
    .on('click', function () {...});

This is a little fragile, because it relies on the '.delete-button' being in that location, but the docs note that the front-end API is not very stable anyways. In addition, the button will probably always be shown, since I haven't found a way to get access to the selected list and check whether the button should be displayed. Finally, this probably won't work with JupyterLab which is the future™
This could go in an nbextension (see frontend extensions and distributing extensions) to make it easier to install.


text:
Q: How can I tell SuperCSV NOT to map empty string to null I am using ICsvListReader and ICsvListWriter to read and write csv file.
I found that the empty string in csv file is converted to null and then output.
How can I avoid this happen. I've tried create a new CellProcessor:
private CellProcessor[] getProcessors(int columnNumber){

        CellProcessor[] processors = new CellProcessor[columnNumber];
        for (int i=0; i< columnNumber; i++){
            processors[i] = new ConvertNullTo("");
        }
        return processors;
    }

But it still not working.
Is there any way to change this setting?

A: Empty columns don't require escaping in CSV (so by default Super CSV won't apply quotes around empty strings), but if you want quotes to always be applied then you can change the QuoteMode in Super CSV.
Here's a recent example on SO that demonstrates this.
Update: If you only want to quote empty strings, then make sure the values you're writing are empty String (i.e. you may need to use ConvertNullTo("")), then use the following quote mode:
public class QuoteEmptyString implements QuoteMode {

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean quotesRequired(String csvColumn, CsvContext context,
        CsvPreference preference) {
        return "".equals(csvColumn);
    }

}


text:
Q: How to get a date in this form? I need to get a date in this form:
"12/31/2020 5:00 AM"

I wrote this code:
var ExpireI = new Date ();
ExpireI.setTime(ExpireI.getTime() + (24 * 3600 * 1000));
alert(ExpireI.toGMTString());

but it display something like this:
Tue, 26 Jun 2012 10:26:35 GMT

so, how can I get a date in that form ?

A: Try this
Instead of doing this way:
getDate()     // Returns the date
getMonth()    // Returns the month
getFullYear() // Returns the year

And for your case, you can use this way:
alert(ExpireI.getFullYear() + "-" + ExpireI.getMonth() + "-" + ExpireI.getDate());

Fiddle here... :)

A: This should work,
var d = new Date ();
var date = d.getDate();
var month = d.getMonth() + 1;  // because january is 0 in javascript
var year = d.getFullYear();
var hour = d.getHours();
var min = d.getMinutes();
var m;
if(hour > 12 ){
  hour-=12;
  m = 'PM';
}
else{
 m = 'AM';
}

console.log(month + '/' + date + '/' + year + ' ' + hour + ':' + min + ' ' + m);


text:
Q: Why make is locking up? I've defined below function inside makefile.
# check debug xdc
define check_debug_xdc
    if [ -f ${DEBUG_XDC} ]; then \
        ...
    fi
endef

make runs fine, if directly call it.
# Optimize
${OUTPUTS1}: ${INPUTS1}
    @echo ""
    @echo "Optimization"
    @date '+%Y_%m%d_%H%M'
    @$(call check_debug_xdc)

But if I commented out DEBUG_XDC and put $(call check_debug_xdc) inside if-fi to check whether DEBUG_XDC is defined or not, make stops responding, nothing is printing out, even the date.
# DEBUG_XDC     = ./fpga_ila/fpga_ila.srcs/constrs_1/new/${TOP}.xdc
...
# Optimize
${OUTPUTS1}: ${INPUTS1}
    @echo ""
    @echo "Optimization"
    @date '+%Y_%m%d_%H%M'
    @if [ ! -z "${DEBUG_XDC}" ]; then $(call check_debug_xdc); fi

Tried make -dn, it prints below message then stop responding.
GNU Make 3.81
Copyright (C) 2006  Free Software Foundation, Inc.
This is free software; see the source for copying conditions.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.

This program built for i686-pc-linux-gnu
Reading makefiles...
Reading makefile `makefile'...
Updating makefiles....
 Considering target file `makefile'.
    ...
         Finished prerequisites of target file `fpga/fpga_opt.dcp'.
        Must remake target `fpga/fpga_opt.dcp'.

How to fix it?


text:
Q: AWS API credentials with OneLogin SAML and MFA We want to allow our users to retrieve a set of temporary CLI credentials for a given AWS role by signing in to OneLogin with password and MFA. We have a working solution, but it requires the user to fully re-authenticate to OneLogin (including MFA) every 60 minutes as the AWS temporary credentials expire. I think that won't fly - our users are accustomed to permanent API credentials tied to a real IAM user.
Ideally, we'd like to allow users to authenticate once a day, securely cache the resulting SAML assertion, and use that to transparently refresh the AWS API credentials as needed. I'm thinking of something like aws-keychain that would use the local OS credential store to remember the SAML assertion, and only prompt the user for input when their OneLogin session has timed out.
This almost works as-is. The catch is that the SAML assertion returned by OneLogin's saml_assertion and verify_factor endpoints sets a three-minute deadline on the Subject and Conditions fields.
Is there a way to do what we want, or are we trying to route around a core SAML principle?

A: We're in the process of officially adding an option to in our official CLI tool to re-use the user credentials similarly to what you're describing.
Essentially our CLI tool has an option to reuse the user/pass in the background to continuously refresh the access info in a user profile so while the user will provide credentials once, the access info will get updated before it expires.
But unfortunately, at least at this time, there's no way to get around the MFA part if the application policy requires MFA. It'll need that MFA to refresh the credentials.
If you have to have MFA, you can always use the OneLogin MFA APIs to bake in an MFA flow into the tool...
Check it out here: https://github.com/onelogin/onelogin-aws-cli-assume-role/pull/5

A: The accepted answer here is no longer true. It is now possible to authenticate the user and verify MFA once at the start of a session and then have the session refreshed on an hourly basis without having to enter further MFA tokens.
To do this you must use the --loop parameter of the CLI tool and have a corresponding App Policy in OneLogin that enables the "Skip if OTP received within last X minutes" setting.
https://developers.onelogin.com/api-docs/1/samples/aws-cli


text:
Q: How to pass data from current fragment to previous fragment I am having 2 Fragments A and B. I am starting Fragment B from Fragment A. I need to pass data from Fragment B to Fragment A before Fragment B is closed. Its like startActivityForResult() idea.
Here in Fragment A I am calling Fragment B:
 FragmentB calendarDialog = new FragmentB();
                calendarDialog.setTargetFragment(CurrentPanchangDialog.this, 1);
                FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
                transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                transaction.setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left);
                transaction.add(android.R.id.content, calendarDialog).addToBackStack(null).commit();

Now in Fragment B I am calling something like this while closing:
getTargetFragment().onActivityResult(
                    getTargetRequestCode(),
                    Activity.RESULT_OK,
                    new Intent().putExtra("data", "datafrom C")
            );
            getActivity().getSupportFragmentManager().popBackStackImmediate();

Now in the Base Activity I am overriding onActivityForResult():
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Fragment pFragment = getSupportFragmentManager().findFragmentById(R.id.content);
        if (pFragment instanceof CurrentPanchangDialog) {
            if (pFragment != null) {
                pFragment.onActivityResult(requestCode, resultCode, data);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

I am not getting the data back to Fragment A from Fragment B.

A: This method is also called the Delegate Pattern
• Create an interface with one method like this one:
public interface FragmentCallback {
    void onDataSent(String yourData);
}

• Implement this interface in your FragmentA and implement onDataSent() method:
public class FragmentA implements FragmentCallback {

    @Override
    void onDataSent(String yourData){
        //Do something with your data
    }
}

• Declare this interface variable in Fragment B and create a public setter method:
public class FragmentB {

private FragmentCallback fragmentCallback;

    public void setFragmentCallback(FragmentCallback callback) {
        this.fragmentCallback = callback;
    }
}

• Somewhere withing FragmentA set it as a callback on FragmentB instance:
fragmentB.setFragmentCallback(this);

• Path data from FragmentB to FragmentA (you can do it from one of fragment's lifecycle method if data should be sent when FragmentB is about to be closed):
public class FragmentB {

    public void onDestroy() {
        if(fragmentCallback != null){
            fragmentCallback.onDataSent("Some data from FragmentB");
        }
        super.onDestroy();
    }
}

A: You could alternatively just use a variable in the Activity, and then access it from the Fragment, maybe something like this:
Activity:
private String data;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

public String getData() {
    return this.data;
}

Fragment:
String dataFromActivity = ((YourActivity)getActivity).getData();


text:
Q: Is there anything to prove in this corollary? Show that if  $B$ is not finite and $B\subset A$, then A is not finite.
I mean the statement is very trivial, but I'm having an issue actually writing what I would deem a good proof of this. The only idea I have is of letting $x\in B$ and  then show it is in $A$, but even that is trivial because I'm given that in my assumption.

A: As $B$ is not finite, there is an injective function $f:\mathbb{N}\to B$ (by definition).  Define $g:\mathbb{N}\to A:x\mapsto f(x)$.  Now $$g(x)=g(y)\iff f(x)=f(y)\iff x=y$$ by injectivity of $f$.  Hence $g$ is an injection to $A$.  Hence $A$ is not finite by definition.

A: Suppose there's an injective map $A\stackrel{\phi}{\hookrightarrow} n\in\mathbb{N}$
Since $B$ is infinite, there's an injective map $n\stackrel{\theta}{\hookrightarrow} B$ (I think this is the only point where one has to be careful not to use the axiom of choice)
But the inclusion $B\subseteq A$ gives us an injective map $B\stackrel{id_B}{\hookrightarrow}A$
But then we have a chain of injective maps
$$n\stackrel{\theta}{\hookrightarrow}B\stackrel{id_B}{\hookrightarrow}A\stackrel{\phi}{\hookrightarrow}n$$
But then, by Cantor-Bernstein's theorem, there exists a bijection $B\stackrel{\gamma}{\longleftrightarrow}n$. Absurd.

A: Think of the inclusion map, $\iota: B \to A, \iota(b) \mapsto b$. This is definitely an injection. Therefore $\operatorname{card} B \leq \operatorname{card} A$.


text:
Q: Cannot start windows phone emulator in visual studio 2015 My machine is HP EliteBook 8540w which supports Hyper-V as far as I know and I have enabled it in BIOS. However, I am receiving the following error when trying to start emulator for Windows Phone apps in Visual Studio 2015:

Windows Phone Emulator is unable to start because the hypervisor is not running.

The more detailed screen shot follows:

According to my i7-720QmCPU specs, it supports VT-d

So what is the reason for it being unable to start the emulator on my machine?
Update:
I also checked using the BIOS settings using coreinfo tool with the results as in the following picture:

Update:
Following stijnvangaal's comment, I ran the following command as administrator and rebooted.

'bcdedit /set hypervisorlaunchtype auto'

But, in the wake of next run I faced the following Window ("Virtual machine service not running")

Then, I started this (by clicking the link on the message box):

Under, action menu, I clicked "start service" and then ran the application again in visual studio. Success? Not yet unfortunately, ending up in this (feeling desperate):

A: I had the same issue :
1 - I disable the Hyper V mode in the Windows Feature :

*

*Go to 'Programs and Features'.

*Select Turn Windows Features on or off.

*Deselect Hyper-V and click OK.

2 - Restart the computer
3 - Enable Hyper V again in the Windows Feature.
And it works !
Hope it help :)

A: Just disable Hyper-V on "Programs and Features" (if it is enabled). Then restart computer and turn it on again. Problem solved for me


text:
Q: Can I make `sudo` follow my path via CLI? You can edit sudoers file and set secure_path to match your path. This is documented in Unix & Linux.
Is there a command line switch I can pass to sudo such that it uses the path I have set? For example:
rick@alien:~$ sudo echo $PATH
/home/rick/bin:/home/rick/.local/bin:/mnt/e/bin:/mnt/e/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
───────────────────────────────────────────────────────────────────────────────
rick@alien:~$ echo $PATH
/home/rick/bin:/home/rick/.local/bin:/mnt/e/bin:/mnt/e/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
───────────────────────────────────────────────────────────────────────────────
rick@alien:~$ sudo which auto-brightness-config
/usr/local/bin/auto-brightness-config
───────────────────────────────────────────────────────────────────────────────
rick@alien:~$ which auto-brightness-config
/mnt/e/usr/local/bin/auto-brightness-config
───────────────────────────────────────────────────────────────────────────────
rick@alien:~$ sudo locate auto-brightness-config
/Desktop/Link to auto-brightness-config
/home/rick/Pictures/display-auto-brightness-config 1.png
/mnt/e/Desktop/Link to auto-brightness-config
/mnt/e/usr/local/bin/.auto-brightness-config
/mnt/e/usr/local/bin/Link to auto-brightness-config
/mnt/e/usr/local/bin/auto-brightness-config
/usr/local/bin/.auto-brightness-config
/usr/local/bin/Link to auto-brightness-config
/usr/local/bin/auto-brightness-config

When I run using sudo it is finding the wrong copy of the script in /usr/local/bin when I really want the version in /mnt/e/usr/local/bin .
If I don't want to maintain the path in sudoers file, is there a switch I can pass to sudo to use my path to find the right command?

A: Ubuntu by default already has secure_path set:
~ sudo -l
Matching Defaults entries for muru on muru-1604:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin
User muru may run the following commands on muru-1604:
    (ALL : ALL) ALL

There is no command-line option that can override secure_path set in sudoers.
From man sudoers:
 secure_path   Path used for every command run from sudo.  If you don't
               trust the people running sudo to have a sane PATH
               environment variable you may want to use this.  Another use
               is if you want to have the "root path" be separate from the
               "user path".  Users in the group specified by the
               exempt_group option are not affected by secure_path.  This
               option is not set by default.

So either set exempt_group in sudoers and add yourself to that group, or exempt yourself from sudoers:
Defaults:rick !secure_path

(rick presumably being your username.)


text:
Q: How to use external images in PDF using wicked_pdf I want to embed some external images to pdf i am using  tag for doing this but image is not display in pdf. How to show external images inside pdf

A: Try using this version of wkhtmltopdf.
This may solve your problem.


text:
Q: Grub starts in command line after BIOS update and can't boot any OS my problem is very similar to this question asked by Antoine Aubry.
I have an ASUS laptop with Windows 10 and Ubuntu 20.04.2 LTS installed in dual boot. After a recent BIOS update, when I start my computer I am met with the GRUB 2 Command Shell instead of the usual GRUB 2 menu. I tried getting out of the shell by typing exit which prompts me to the normal GRUB 2 menu. The problem is that when I select either Windows or Ubuntu, it goes to a black screen and refuses to boot. At this point, I just press the power button to stop my computer. When I turn my computer back on, the normal GRUB 2 menu directly appears and when I try booting into any OS, it works normally.
I have only had this problem for a week and while it still allows me to use both my Ubuntu and Windows, it is not practical to restart my computer each time. I tried executing these steps but upon entering ls I can't seem to find my Linux partition. I should mention that my Windows partition is installed on my SSD while my Linux partition is installed on my HDD. Grub seems to only be able to list the partitions of my SSD. That is why I wanted to know how I could access my HDD partitions in the Grub Command Shell. I must say that I am not familiar with the Grub boot loader and I apologize for any necessary information that I have failed to share here. Thanks in advance.

A: Okay so I managed to fix my problem in the end by using boot-repair as requested by @psusi. Once I did that my laptop could only boot into Ubuntu and I did not have the choice to select any other OS because the Grub menu did not even show. I decided to open up grub-customizer to see the current configuration and it retrieved my previous configuration. I decided to update the grub with the saved configuration and now everything seems to work as normal. When I boot my computer, I don't see the Grub Shell anymore and it directly goes to the Grub menu from which I can boot to either Ubuntu or Windows. Thank you for providing your help so quick. I'll mark this question as solved.


text:
Q: JS anonymous function and parentNode to delete a table row I have an HTML table that has a delete button in the last column of every row. I am attempting to make each complete row deletable using the JS code below. I am able to get a console readout of what seems to be the correct tr to delete with console.log but am unable to figure out the code for actually deleting it:
var bns = document.getElementsByTagName("button");
  for (var i = 0; i < bns.length; i++) {
    bns[i].addEventListener("click", function()
     {
      console.log(this.parentNode.parentNode);
     });
 }


text:
Q: PairedTTest - how to extract 95% confidence intervals for difference between paired means? data1 = {19.4, 21.2, 17.1, 21.1, 19.1, 18.2, 19.6};
data2 = {19.6, 21.1, 18.2, 21.8, 19.5, 18.3, 19.1};
PairedTTest[{data1, data2}]

How do I extract the 95% confidence intervals for the difference between the means from the PairedTTest?

A: Yes it is surprising that such a common task is not available in the latest Statistics framework. PairedTTest[{data1,data2},"ConfidenceInterval"] really ought to return what you're after (i.e. the object from PairedTTest[{data1,data2},0,"HypothesisTestData"] ought to contain "ConfidenceInterval" as a property).
Confidence Intervals existed in V 5.2's package "Statistics`ConfidenceIntervals`" which was upgraded to the package HypothesisTesting`. This, in turn, was superseded by the new (kernel) framework of which PairedTTest is a member. To generate such a confidence interval then, go back to HypothesisTesting`.
Needs["HypothesisTesting`"]
data1 = {19.4, 21.2, 17.1, 21.1, 19.1, 18.2, 19.6};
data2 = {19.6, 21.1, 18.2, 21.8, 19.5, 18.3, 19.1};
MeanCI[data1 - data2]

(* {-0.757051, 0.214194} *)

MeanCI's default assumptions match that for a PairedTTest confidence interval. To explicitly apply a "T-test confidence interval" the package's StudentTCI can instead be used to define "My" expected syntax:
MyPairedTTest[{data1_, data2_}, 0, "ConfidenceInterval"] := Let[
diff = data1 - data2,
n = Length@diff,
m = Mean@diff,
se = StandardDeviation@diff/Sqrt@n,

StudentTCI[m, se, n - 1]]

(* {-0.757051, 0.214194} *)

N.b, the package's MeanDifferenceCI will not do here since one of its assumptions is that both samples are independent (unlike the paired or matched case where individual effects are accounted for meaning that smaller differences can define significance; or equivalently,  matched-pairs' confidence intervals are tighter)
 MeanDifferenceCI[data1, data2]

 (* {-1.91857, 1.37571} *)

A: I don't think you can.  While I like the options with LinearModelFit and NonlinearModelFit, whoever wrote PairedTTest and TTest (and a few others) seemed to think that all one needs are P-values.
Here's how to get the confidence intervals in a brute-force way:
data1 = {19.4, 21.2, 17.1, 21.1, 19.1, 18.2, 19.6};
data2 = {19.6, 21.1, 18.2, 21.8, 19.5, 18.3, 19.1};

confidenceLevel = 0.95;
diff = data1 - data2;
n = Length[diff];
meanDiff = Mean[diff]
(* -0.271429 *)
se = StandardDeviation[diff]/Sqrt[n];
t = InverseCDF[StudentTDistribution[n - 1], 1 - (1 - confidenceLevel)/2];
{lower, upper} = meanDiff + {-1, 1} t se
(* {-0.757051, 0.214194} *)