text:
Q: consumer-producer pattern with MySql Hello and happy New Year to all of you! :)
I'm working on a software (Java, backend) that has 3 components each being independent Java application (you can even consider them as separate threads):
1) DB data importer 1.
2) DB data importer 2.
3) DB data exporter.
Now, all those apps are working with the same MySql database, using same 2 InnoDB tables - "Orders" and "Items". Each order may have 0 or many items. All DB operations (data query and data insert) are done using stored procedures. This is what my app does:
Application 1 or 2 (remember, they are independent) starts importing "an order" every few seconds. "Order" is being imported into "Orders" table and each "Item" is being imported into "Items" table.
a) Application takes and order, imports that order into "Orders" table and marks the order as "not ready for export".
b) Then application continues importing all items (if any) for that order.
c) In the end, when all items are imported, order is marked as "ready for export" (i have a dedicated column for that bit).
Application "3" every few seconds does this:
a) checks for "ready for export" orders.
b) selects 50 "ready for export" orders and marks them as "in export".
c) exports orders and theirs items into a file.
d) marks all orders that are "in export" to "exported".
Now, as you can tell, even with dedicated column which tells which order or item should be exporter and which is still being imported and shouldn't be exported yet, i'm getting some deadlocks and race conditions.
Do you know any simple and safe mechanism i can use to implement this "producer - consumer" system without locking entire tables "Orders" and "Items" (as they are actively used by other parts of the software)?
I guess using 3-state column is not a good idea taking into account each table may have millions of rows and index on such 3-state column is ineffective. There has to be something better :)

A: Your processing workflow procedure includes this step:

Application "3" every few seconds does this: a) checks for "ready for
  export" orders. b) selects 50 "ready for export" orders and marks them
  as "in export". c) exports orders and theirs items into a file. d)
  marks all orders that are "in export" to "exported".

It matters how you do this step.
If you do something like this procedure, it should run cleanly.
In my opinion, 50 is too big a batch to do at once. I'd start with doing them one by one, and then try to make the batches a little larger.
First, mark some orders as 'in export' in a single query. That way you won't have to worry about transactions.
UPDATE orders
   SET status = 'exporting'
 WHERE status = 'ready-for-export'
 ORDER BY id
 LIMIT 50

Then, in a loop do this to process all the orders in your match
 /* get an order to process */
 SELECT id, whatever, whatever
   FROM orders
   WHERE status = 'exporting'
   ORDER BY id
   LIMIT 1

 /* if no order came back from this query, you are done with your batch */

 /* process the order */

 /* mark the order done */
 UPDATE orders SET status = 'exported' WHERE id = ???id??? AND status='exporting'

This grabs a batch of orders (using LIMIT 50) and marks them "ready-for-export." It then chews through them one by one.
Now, to avoid deadlocks on the order table, queries in the rest of your software need to include WHERE status <> 'exporting' or the equivalent, so they'll ignore the rows being exported.
It's possible you're getting deadlocks on the Items table. You can avoid those by always doing single-query operations like this
 UPDATE items SET number_on_hand = number_on_hand - ???order_quantity???

You might also look into MySQL's version of UPSERT. It's called INSERT ... ON DUPLICATE KEY UPDATE.
But, the bottom line is this: If you have a busy system, you're going to have to use transactions. The classic way of avoiding deadlocks is to always lock resources in the same order. For example,

*

*Always lock the Order table row first, or the Item table row first, but never in the opposite order.

*If you have to lock several rows in one table, always lock them in the same order -- that is, use an ORDER BY id clause in the SELECT ... FOR UPDATE query.
Notice that an index on the orders table, on (status,id), will help optimize the queries to put orders into batches and release them from batches.


text:
Q: Lazily Transforming IReadOnlyList in C# I would like to be able to do something like this for setting up a
mesh data structure.
IReadOnlyList<Point> points;
IReadOnlyList<IReadOnlyList<int>> triangles;

where the triangles are indices into the points list. Given an index
of a triangle ''ti'' we can find the points easily
IEnumerable<Point> points = triangles[ti].Select(pi=>points[pi])

However I would like to be able to define a convienience structure
IReadOnlyList<IReadOnlyList<Point>> trianglesAsPoints;

so I can do
IEnumerable<Point> points = triangles[ti]

The obvious way to do this would be to create a linq like selector
IReadOnlyList<T> Select( this IReadOnlyList<U> This
                             , Func<U,T> selector)

which returns an instance whose class overrides the following method and
invokes the selector
public interface IReadOnlyList<out T> : IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable
{
    // Summary:
    //     Gets the element at the specified index in the read-only list.
    //
    // Parameters:
    //   index:
    //     The zero-based index of the element to get.
    //
    // Returns:
    //     The element at the specified index in the read-only list.
    T this[int index] { get; }
}

Does such a factory exist anywhere in the standard libs or nuget for this pattern?
Note I do not want IEnumerable as a result because I would lose the indexing ability
and the Count property, I just want to lazily transform the value which means not
copying all the values to a new list instance up front.

A: I don't believe there's anything which does this in the framework, no. It's obviously reasonably easy to implement yourself, but I believe you'll have to do it. It's entirely possible that there are 3rd party libraries which do it, but as IReadOnlyCollection was only in .NET 4.5 it's less likely than if the interface had existed for a while.
I'd suggest calling it something other than Select though - I'd use ProjectView or something similar. Of course that means it wouldn't work with LINQ query expressions, but it will be clearer to anyone reading the code that it's not just Enumerable.Select.

A: Here is a hand rolled solution to the problem
public static class CollectionMixins
{
    private class ReadOnlyListProjection<U,T> : IReadOnlyList<T>
    {

        public Func<U,T> Selector { get; private set; }
        public IList<U> List { get; private set; }

        public ReadOnlyListProjection(IList<U> list, Func<U, T> selector)
        {
            List = list;
            Selector = selector;
        }

        public T this[int index]
        {
            get { return Selector(List[index]);  }
        }

        public int Count
        {
            get { return List.Count; }
        }

        public IEnumerator<T> GetEnumerator()
        {
            return List.Select(Selector).GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return List.Select(Selector).GetEnumerator();
        }
    }

    public static IReadOnlyList<T> ProjectReadOnly<U, T>(this IList<U> This, Func<U, T> fn)
    {
        return new ReadOnlyListProjection<U, T>(This, fn);
    }
}

so I can now do
IList<int> foo = new List<int>{0,1,2};
IReadOnlyList<string> bar = foo.ProjectReadOnly( x=>x.ToString() );

redpajama_set_name: RedPajamaStackExchange


text:
Q: Click on each onclick where the onclick attribute changes randomly I need to scrap a web and click on multiple tabs on the web.
I'm checking the onclick's attribute value changes randomly and I can't find a way to select each tab. The onclick attribute are:
    onclick="clickDashboard('889113733777776')"
    onclick="clickDashboard('894967889413237')"
This is the html fragment I want to try to click on each tab. I get it with getHTML() casprjs function, if I try to copy from source code (crtl+U) I just can see javascript code. You can also see how li tag class is 'activetab' to indicate which tab is displayed. Here link to full html source file

+

                <input type="image" src="/Content/images/icons/excel.gif" value="Excel" title="Export default report">

                <input type="image" src="/Content/images/export-pdf-24x24.png" value="Excel" title="Export default report">

            Dashboard EUR

                <fieldset id="dbTabSettingsMenu_889113733777776" class="dashSettings-menu">

                             Añadir widgets

                              Borrar este dashboard

                </fieldset>

            Dashboard USD

                <fieldset id="dbTabSettingsMenu_894967889413237" class="dashSettings-menu">

                        ...

            </fieldset>

I'm trying select each tab and make a screenshot with this code:
//Wait to be redirected to the Home page, and then make a screenshot
casper.then(function(){
    casper.wait(5000, function(){
        this.capture('home.png');
        var tabs = document.querySelectorAll('[id^=dbTabLabel]');
        var i;
        console.log('Tabs found: ' + tabs.length);
        for(i = 0; i < tabs.length; i++) {
            tabs.click()
            var name = 'tab' + i + '.png'
            this.capture(name); //Make a screenshot for each tab
        }
    })
});

But it seems that it doesn't select any tab because output is Tabs found: 0

A: I recommend using
casper.each(tabs, function(self, tab){

};

Instead a for. Also, in the querySelectorAll use a more generic selector like ul#tabul li. I tried using a for loop inside a casperjs script and always got an error, using each and more generic selectors worked for me every time!


text:
Q: Creating HTML Table with PHP Array Is there a convention on how to create a table with a structure that resembles an iOS table view or Android ArrayList from a PHP array? Basically what I'm trying to do is implement a way to select a row and get the value from that row, something like a key from a database maybe.
When I write echo "
".$value."
" within a foreach loop, then use JavaScript to print something when it's pressed, it only prints the inner html of the first element in the array. But when I assign the id in the actual html body it works for all rows. I see PHP is really different. Any help would be appreciated!
Code:

<?php
         $subjects = array("IT","Programming","Networks");
        foreach($subjects as $key => $value) {
        echo ""."".$value.""."	";
        }
   ?>

A: Here is a way to do it.

<?php
    $subjects = array("IT","Programming","Networks");
    foreach($subjects as $key => $value) {
    echo ""."".$value.""."	";
    }
  ?>

Notice I added a column class to links, and I'm checking if users click on columns.
Edit: This is assuming I understood your question correctly. Otherwise if your actual code prints multiple rows, with multiple links, and you're trying to get the value of a row, then you shouldn't have multiple ids in your html. id is unique, class is for elements that repeat.

A: Use event.target to find out what element the user clicked on.

document.getElementById("subject").addEventListener("click", function(event) {
  console.log(event.target.textContent);
  event.preventDefault(); // prevent following the link
});

    Programming

    IT

    Networks


text:
Q: How to use popBackStackImmediate by allowing state loss commit I have a call of popBackStackImmediate in my Activity. I want to make a call to this method, but allowing stateloss commit as it is doing this method: commitAllowingStateLoss.
Is there a way for this?


text:
Q: Ajax returning blank response I'm working on a simple script where I just want to see request and response that is sent to server and then recieved at client via Ajax. The server is always returning Status 500. What am I doing wrong?
Below is my script.
Javascript:
<script>
function loginJs()
{

var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.open("GET","http://my-website.com/ajax_exp.php",true);

xmlhttp.onreadystatechange=function()
{

 alert("State "+xmlhttp.readyState+" Status "+xmlhttp.status);
 if (xmlhttp.readyState==4 && xmlhttp.status==200)
 {
    alert(xmlhttp.responseText);
 }
}
xmlhttp.send();
}
</script>

ajax_exp.php
<?php

header('Access-Control-Allow-Origin: http://my-website.com/ajax_exp.php');
add_action('wp_ajax_my_action',        'my_action');
add_action('wp_ajax_nopriv_my_action', 'my_action');

function my_action()
{
$username = 'username';
$password = 'password';

echo $username;
die();
}

?>

A: 1) try removing
 header('Access-Control-Allow-Origin: http://my-website.com/ajax_exp.php');
 add_action('wp_ajax_my_action',        'my_action');
 add_action('wp_ajax_nopriv_my_action', 'my_action');

replacing with
 my_action();

You can easily trace the error;
2) Check console log for any javascript errors.

A: Path is the problem provide your server path ajax/ajax_exp.php
<script>
function loginJs()
{

var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.open("GET","ajax/ajax_exp.php",true);

xmlhttp.onreadystatechange=function()
{

 alert("State "+xmlhttp.readyState+" Status "+xmlhttp.status);
 if (xmlhttp.readyState==4 && xmlhttp.status==200)
 {
    alert(xmlhttp.responseText);
 }
}
xmlhttp.send();
}
</script>

A: If anyone else is having the same issue, this is what I did and now it works!
Javascript
Replaced xmlhttp.send(); with xmlhttp.send(null);
PHP
<?php
$username = "user";
$password = "password";
print $username;
?>


text:
Q: Pass bundle from one tab fragment to another tab fragment Creating app in which i want to pass bundle data from one tab fragment to another.I have created two tab and getting list in one fragment but now i want to select item from Recyclerview list using checkbox and set this selected item to another tab fragment on swipe.Using viewpager for creating tab.In second tab fragment set bundle and in first tab fragment  get bundle but not working.
In second fragment i set bundle
    Bundle data = new Bundle();
    data.putString("name",contactArrayList.get(position).getContactName());
    data.putString("mobile",contactArrayList.get(position).getContactNumber());
    Fragment fragment = FragmentInfo.newInstance(1);
    fragment.setArguments(data);

In first fragment i get bundle
if (bundle != null) {
       String name = bundle.getString("name");
       String mobile = bundle.getString("mobile");
        // object of Model Class
        mydata.setName(name);
        mydata.setMobile(mobile);
        myDataArrayList.add(mydata);

    }

A: try this:
create a mechanism to access the tag across fragments via the main activity, . - Call getTag() in onCreateView() of FragmentB. Then pass it to the main activity. When FragmentA need to pass something to FragmentB, it retrieve it from MainActivity.
 public static class TabsAdapter extends FragmentPagerAdapter
  implements ActionBar.TabListener, ViewPager.OnPageChangeListener {

  private final Context mContext;
        private final ActionBar mActionBar;
        private final ViewPager mViewPager;
        private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();

        static final class TabInfo {
            private final Class<?> clss;
            private final Bundle args;

            TabInfo(Class<?> _class, Bundle _args) {
                clss = _class;
                args = _args;
            }
        }

  public TabsAdapter(FragmentActivity activity, ViewPager pager) {
   super(activity.getSupportFragmentManager());
            mContext = activity;
            mActionBar = activity.getActionBar();
            mViewPager = pager;
            mViewPager.setAdapter(this);
            mViewPager.setOnPageChangeListener(this);
        }

  public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
            TabInfo info = new TabInfo(clss, args);
            tab.setTag(info);
            tab.setTabListener(this);
            mTabs.add(info);
            mActionBar.addTab(tab);
            notifyDataSetChanged();
        }

  @Override
  public void onPageScrollStateChanged(int state) {
   // TODO Auto-generated method stub

  }

  @Override
  public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
   // TODO Auto-generated method stub

  }

  @Override
  public void onPageSelected(int position) {
   // TODO Auto-generated method stub
   mActionBar.setSelectedNavigationItem(position);
  }

  @Override
  public void onTabReselected(Tab tab, FragmentTransaction ft) {
   // TODO Auto-generated method stub

  }

  @Override
  public void onTabSelected(Tab tab, FragmentTransaction ft) {
   Object tag = tab.getTag();
            for (int i=0; i<mTabs.size(); i++) {
                if (mTabs.get(i) == tag) {
                    mViewPager.setCurrentItem(i);
                }
            }
  }

  @Override
  public void onTabUnselected(Tab tab, FragmentTransaction ft) {
   // TODO Auto-generated method stub

  }

  @Override
  public Fragment getItem(int position) {
   TabInfo info = mTabs.get(position);
            return Fragment.instantiate(mContext, info.clss.getName(), info.args);
  }

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

 }

For full implementation see this link:
http://android-er.blogspot.com/2012/06/communication-between-fragments-in.html


text:
Q: Returning future weekday excluding holidays I should preface by saying I know nothing about scripting. I found this script online that fit my needs, so I was able to re-purpose it for my project. Anyway, this script takes Google form submissions, populates a Google doc template, that template gets copied, converted to PDF, and placed in a specific folder on my Google Drive.
So my question is, I have a simple line that pulls the current date when the script gets run, but I also need some code that can calculate the current date plus 5 weekdays (which should exclude weekends), but I also need it to exclude defined holidays. Any help would be greatly appreciated.

// Work Order

// Get template from Google Docs and name it
var docTemplate = ""; // *** replace with your template ID ***
var docName = "Work Order";

// When Form Gets submitted
function onFormSubmit(e) {
  //Get information from form and set as variables
  var email_address = "";
  var job_name = e.values[1];
  var ship_to = e.values[11];
  var address = e.values[12];
  var order_count = e.values[7];
  var program = e.values[2];
  var workspace = e.values[3];
  var offer = e.values[4];
  var sort_1 = e.values[5];
  var sort_2 = e.values[6];
  var print_services = e.values[10];
  var priority = e.values[13];
  var notes = e.values[14];
  var formattedDate = Utilities.formatDate(new Date(), "EDT", "MM/dd/yyyy");

  // Get document template, copy it as a new temp doc, and save the Doc's id
  var copyId = DriveApp.getFileById(docTemplate)
    .makeCopy(docName + ' for ' + job_name)
    .getId();
  // Open the temporary document
  var copyDoc = DocumentApp.openById(copyId);
  // Get the document's body section
  var copyBody = copyDoc.getActiveSection();

  // Replace place holder keys,in our google doc template
  copyBody.replaceText('keyJobName', job_name);
  copyBody.replaceText('keyShipTo', ship_to);
  copyBody.replaceText('keyAddress', address);
  copyBody.replaceText('keyOrderCount', order_count);
  copyBody.replaceText('keyProgram', program);
  copyBody.replaceText('keyWorkspace', workspace);
  copyBody.replaceText('keyOffer', offer);
  copyBody.replaceText('keySort1', sort_1);
  copyBody.replaceText('keySort2', sort_2);
  copyBody.replaceText('keyPrintServices', print_services);
  copyBody.replaceText('keyPriority', priority);
  copyBody.replaceText('keyNotes', notes);
  copyBody.replaceText('keyDate', formattedDate);
  copyBody.replaceText('keyDue', expirationDate);

  // Save and close the temporary document
  copyDoc.saveAndClose();

  // Convert temporary document to PDF by using the getAs blob conversion
  var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");

  // Attach PDF and send the email
  var subject = "New Job Submission";
  var body = "Here is the work order for " + job_name + "";
  MailApp.sendEmail(email_address, subject, body, {
    htmlBody: body,
    attachments: pdf
  });

  // Move file to folder
  var file = DriveApp.getFileById(copyId);
  DriveApp.getFolderById("").addFile(file);
  file.getParents().next().removeFile(file);
}

A: You can use the below function to get future date which excludes weekends and if any holiday declared in the array.
function addDates() {
    var date = new Date(); // yor form date
    var hodiday = ["08/09/2017","08/15/2017"]; //Define holiday dates in MM/dd/yyyy
    var days = 5; //No of days you want to add
    date.setDate(date.getDate());
    var counter = 0;
        if(days > 0 ){
            while (counter < days) {
                date.setDate(date.getDate() + 1 );
                var check = date.getDay();
                var holidayCheck = hodiday.indexOf(Utilities.formatDate(date, "GMT", "MM/dd/yyyy"));
                  if (check != 0 && check != 6  && holidayCheck == -1) {
                         counter++;
                    }
            }
        }
        Logger.log(date) //for this example will give 08/16/2017
    return date;
}


text:
Q: Ajax call after 5 secs If I click on a button is it possible to call an ajax after 5 secs?
HTML :
<button>Click</button>

AJAX:
$('button').click(function() {
    $.ajax({
        type: 'post',
        url: 'save_student_db.php',
        data: 's_name=' + $('#s_name').val() +
            '&s_email=' + $('#s_email').val() +
            '&s_phone=' + $('#s_phone').val() +
            '&s_add=' + $('#s_add').val() +
            '&dept_select=' + $('#dept_select').val() +
            '&datepiker=' + $('#datepiker').val(),
        success: function(reply_data) {
            $('#output').html(reply_data);
        }
    });
});

Here I want when I click on the button then this ajax call will called after 5 secs. How can I do it? thank you.

A: Yes, like this:
$('button').click(function() {
    setTimeout(function () {
        $.ajax({
            type: 'post',
            url: 'save_student_db.php',
            data: 's_name='+ $('#s_name').val() +
                  '&s_email=' + $('#s_email').val() +
                  '&s_phone=' + $('#s_phone').val() +
                  '&s_add=' + $('#s_add').val() +
                  '&dept_select=' + $('#dept_select').val() +
                  '&datepiker=' + $('#datepiker').val(),
            success: function(reply_data) {
                $('#output').html(reply_data);
            },
        });
    }, 5000);
});

A: You can use setTimeout()
setTimeout(function(){ $(".selectSomething").yourAjaxFunctionHere() }, 5000);


text:
Q: How to mock getenv in pytest? In some of my test, I need to mock some function calls such as os.getenv, I tried to combine mock.patch but I guess pytest and patch don't go hand in hand, how can I do this?

A: Don't bother with mock.patch.  Since you are using pytest, you should use the fixture mentioned in the documentation:
def test_thing(monkeypatch):
    monkeypatch.setenv('VARNAME', 'var_value')


text:
Q: bash script led keyboard in crontab I use this simple bash script in order to power on my keyboard led in my linux VM .
If i don't use the script i can't power on led.
#!/bin/bash
sleep 1
xset led 3
xmodmap -e 'add mod3 = Scroll_Lock'

When i tried to launch it works , but if i insert in crontab doesn't.
@reboot /home/giacomo/Desktop/keyboard.sh

can you help me ?
i even tried to put in crontab the commands , doesn't work.
I tried insert it in root crontab, doesn't work.
@reboot xset led 3 ;  xmodmap -e 'add mod3 = Scroll_Lock'

i want  to automatically power on led of keyboard at reboot, without launch it myself.
thanks

A: Confused on your choice of approach for what you are trying to do.
Why are you not putting that code snippet in your ~/.bashrc-local, which will be left untouched by OS updates that modify ~/.bashrc ?


text:
Q: Neutrinos: how can they carry information about universe? I know that neutrinos are particles with a very small mass and no electric charge. They infrequently interact with matter and so they can give us information about the "old" universe. But how can they do it?

A: Note: I am not an expert on neutrinos, so if I have missed anything, someone please let me know.
For one thing, the knowledge of the mere existence of neutrinos is important for a full understanding of our universe. Also you may have heard that for a long time neutrinos were thought to be massless, but the observation of neutrino flavor oscillation requires them to have mass. This is a bit of a problem as the standard model of particle physics doesn't account for non-zero neutrino masses, which is an indication of some new physics, beyond the standard model.
As you mentioned, neutrinos are very weakly interacting with other matter, making it hard to detect them, which is why neutrino detectors are built on such large scales (see http://icecube.wisc.edu and http://www-sk.icrr.u-tokyo.ac.jp/kam/kamiokande.html for example). But this can be useful in terms of things we may want to find out about our universe. This very weakly interacting behavior enables physicist to see the neutrino spectrum from a star, supernova, gamma ray bursts, etc. virtually unchanged on the way from the object to Earth. Meaning that information about objects very far from Earth (and therefore far back in time) can be found where conventional techniques using light are less successful (for example if there is dust or some other object in between Earth and the object of interest - the light would interact whereas the neutrinos pass through pretty much unchanged).

A: In the "old" universe there is interaction of matter by the the 4 fundamental forces. Neutrinos occur in the weak nuclear interactions. By studying the neutrinos one can study these weak interactions. They might not interact much, but they sure do carry energy.
So by a application of the conservation of energy one could determine the loss to neutrinos and try to link these to the interactions that they might think that occur. For example the nuclear fusion in the sun that converts hydrogen into deterium:
$p+p\rightarrow^2_1H+e^++\nu_e+0.42MeV$
gives an electron-neutrino. These neutrino's don't interact and the amount of energy of the neutrino is hence determined by the conservation of energy.
One could construct a model for the "old universe" and determine the energy of the neutrinos, as the missing energy. This could give some extra information I believe.


text:
Q: Can you explain Moment generation Function (MGF)? I am not from a Math field, but use statistics. I am having a tough time understanding the concept of a moment generating function.
I use PDF's mostly to characterize my data. What are the possible advantages of working with MGFs?

A: I just want to add some advantages of MGF that @BCLC does not mention.

*

*If two MGFs of two random variables coincide (maybe with some little more conditions), then the distributions of the two random variables are identical. This helps you to determine the distribution of some random variables with what you already know. It is also possible to recover the cumulative distribution by MGF.

*If $X_n$'s MGF $M_n$ converges to a  MGF $M
$( maybe with some little more condition), then we know the limit distribution of $X_n$ is the distribution corresponding to $M$. This really helps in statistics as the limit distribution is usually hard to compute but MGF is easy.

*MGF may not usually exists but they are easier to manipulate than the characteristic functions. Usually, people compare MGF, Cumulant and characteristic function. MGF is more practical than the other two since they only involve real numbers and already tells you a lot of the information of the random variables(all the moments and distribution to some extend).

A: PDFs as in Probability Distribution Functions? They don't always exist. They are taught to beginners to characterize data but really advanced studies use Cumulative Distribution Functions.
MGFs are close to characteristic functions which always exist. Not really sure.
I guess another advantage that MGFs give you moments from just differentiating and then plugging in zero while you need to do integration from PDFs to get moments. Take a look at these, and then tell me that you would rather integrate $x^n f(x)$ rather than just differentiate the MGF. :P
Not an expert. Wait for a better answer.

A: Can be very useful when you want to know the distribution of the sum of random variables, or even a random sum of random variables. (i.e. $\sum_1^N{x}$ where N is random as well as x.)

A: This is late, but I happened to stumble upon this question. I am not an expert, but wanted to add another insight:
To obtain a marginal mgf from a joint mgf (say of X and Y), you simply have to calculate $M_{X,Y}(t,0) = M_X(t)$, which may be easier to work with in the case that the marginal pdf ($f_X(x)=\int_{-\infty}^{\infty}f_{X,Y}(x,y)dy$) is difficult to calculate because of a complicated integral.
After calculating the mgf of X and Y, you could check for independence by testing whether $M_X(t)*M_Y(u)=M_{X,Y}(t,u)$, rather than checking whether $f_X(x)*f_Y(y)=f_{X,Y}(x,y)$.


text:
Q: Gradle error for java library module in Android Studio In my Android Studio project, there are 2 modules: an android app module and a java library module, they all worked. But after I upgraded the Android Studio and Gradle, the java library module doesn't work.
Error:Gradle: A problem occurred configuring root project 'demo'.
 > Could not resolve all dependencies for configuration ':classpath'.
 > Could not resolve com.android.tools.build:gradle:2.0.0.
 Required by:
     :demo:unspecified
  > No cached version of com.android.tools.build:gradle:2.0.0 available for  offline mode.

If there is no com.android.tools.build:gradle:2.0.0 in my Android Studio, why the android app module works normally?


text:
Q: Reactivesearch - search from any route I'm experimenting with ReactiveSearch and using the ReactiveList component.
I'm trying to figure out how I can navigate though my React app and still be able to search.
Say I'm on the home route '/', use DataSearch component for autocomplete and that takes me to the results page '/results but I don't get any results!!
In order to get results, I have to search and stay on the '/results' page. Is there a prop that I'm missing on my DataSearch component in the Header:
<DataSearch
  componentId="SearchSensor"
  dataField={["original_title"]}
  className="search-bar"
  showIcon={true}
  iconPosition="right"
  innerClass={{
    title: "text-title",
    input: "text-input",
    list: "text-item"
  }}
  />

Again, in order to get results, I have to search from the DataSearch component that I have on the results page. Search doesn't work when I have search from the DataSearch component that is in the Header.
So how can I set it to be able to perform a search from any route that I might be on (searching from the DataSearch component that is in the Header for instance)?

A: Here you would be only using the DataSearch for autocomplete and then redirecting to the results page for the actual results. For this you could use the onValueSelected prop on DataSearch docs:

onValueSelected is called with the value selected via user interaction. It works only with autosuggest and is called whenever a suggestion is selected or a search is performed by pressing enter key. It also passes the cause of action and the source object if the cause of action was 'SUGGESTION_SELECT'.

So you can get the selected value on the homepage, and then use it for doing a search on the results page. This value can be stored in your component's state for doing search or you can add a DataSearch in your results page too and use the URLParams prop to set its value from the url. For example:
Home Page
<DataSearch
  ...
  componentId="q"
  onValueSelected={(val) => Router.push(`?q=${val}`)}  // using nextjs router here for example
/>

Results Page
<DataSearch
  ...
  componentId="q"  // will set its value from the param 'q'
  URLParams
  className="hidden"  // adding some CSS to hide it if not needed
/>

<ReactiveList
  ...
  react={{
    and: ['q']
  }}
/>

Alternatively, you could use the onValueSelected on homepage to set the selected value in state (or store) and then query the ReactiveList on results page with defaultQuery prop docs.


text:
Q: React App - creating a "sub app" to only load a subsection of a large primary React application How can I deploy secondary "partial" React Apps using a subset of the same files?
A bit of background:
We have a fairly large React web app (around 75 primary pages/views, along with tons of modals, dynamic content, etc.) with about 5MB of JavaScript once it's been bundled for production.
It works well in normal browsers. But we also display certain views on TV screens, and have it cycling through several views - in a case like this, the "digital signage computer" - in some cases the onboard CPU/browser on a smart TV) is loading a "cycle screen", along with perhaps 4 pages contained in iFrames. (Complex setup, but we want the pages rotating in a few second interval, while only querying the database for updates every 10 minutes or so, and this achieves that.)
However, from my understanding, this means the Smart TV is having to load ~ 25MB of code (might be cached so not have to download it all 5 times, and very little of it is getting rendered, but still has to process it individually.) And occasionally, it appears that the TV gets overwhelmed while rendering and just displays a blank page.
I'm thinking perhaps there is a good a way to create lightweight secondary apps with just those pages (and associated provider contexts), so that these views could be trimmed down to < 1MB each.
But I don't want to maintain separate page/view files in different codebases, with different deployment processes, etc.
Is there a good method to do this? Where you can specify sub-apps which get separately bundled, and then where going to a certain route (e.g. server/subapp1) will only load that page's worth of code, while it's predominately the same code?


text:
Q: Excel split based on string I am having below type of values in xls column A
Row 1 - 3min 17s 463ms
Row 2 - 19s 364ms
Row 3 - 165ms
Row 4 - 364ms
Row 5 - 4min 1s 463ms

Form my calculation I need to convert above values into ms (milli seconds), I have tried doing this (with my limited VBScripting knowledge) using split functions but I couldn't make it work :(. Can you please help.
Thank You,
V2ri.

A: How about:
Sub millisec()
    Dim A As Range, r As Range, s As String
    Dim N As Long, milli As Long
    N = Cells(Rows.Count, "A").End(xlUp).Row
    Set A = Range("A1:A" & N)
    For Each r In A
        v = r.Text
        ary = Split(v, " ")
        milli = 0
        For Each ar In ary
            If Right(ar, 2) = "ms" Then
                milli = milli + CLng(Replace(ar, "ms", ""))
                GoTo qwerty
            End If
            If Right(ar, 1) = "s" Then
                milli = milli + 1000& * CLng(Replace(ar, "s", ""))
                GoTo qwerty
            End If
            milli = milli + 60& * 1000& * CLng(Replace(ar, "min", ""))
qwerty:
        Next ar
        r.Value = milli
    Next r
End Sub


text:
Q: Discrepancy calculating the distance between two opposite corners of a rectangle: infinite subdivisions vs hypotenuse I apologize in advance if this is a dumb question. I tried searching for duplicates but couldn't find any. Also, it is more of a curiosity, than a real question, so I hope it fits within the site guidelines.
Backstory
Yesterday, I was driving through California's Central Valley, thinking about how most of the roads there are orthogonal, directed north-south or east-west, creating some sort of square grid. Similar pattern to one found in many American cities and towns, with square grid layouts.
Here is a snapshot from Google Maps near Turlock, CA

I had driving directions on, and wondered for a bit about how an algorithm would calculate the shortest/fastest path when traveling "diagonally" (northeast -> southwest, for example). I didn't spend too much time on that, since some of these roads have different features, speed limits, etc.
Instead, I started thinking about different ways to calculate the distance between opposite corners of a square or rectangle (for simplification, I will focus on squares moving forward, but the math applies to both).
Pythagoras
We know that using Pythagoras, we can calculate the hypotenuse as the square root of the sum of the sides squared:
$ h = \sqrt{a^2 + b^2} $
Thus, for a 10 by 10 square, the hypotenuse will be the square root of 200: 14.1421...
Not Pythagoras
Ok, now, consider this. Given a 10 by 10 square (think of a city block, or orthogonal roads like the ones above), if we want to travel from one corner (A) to the opposite corner (B), first we need to visit one of the remaining two corners.

In this case, the distance traveled would be 10 + 10 = 20 (much longer than the 14.14 hypotenuse).
Now, if we divide this square into 4 equal squares, and we travel through the center, the distance traveled will remain the same: 5 + 5 + 5 + 5 = 20 units.

The number of horizontal segments is equal to the number of columns (2 in this case).
The length of each horizontal segment is equal to the width divided the number of columns:
$ s_h = \frac{width}{columns} $
Thus, the distance traveled horizontally $ d_h $ would be $ s_h * columns $, or in other words, equal to the total width.
The same applies to the distance traveled vertically $ d_v $, where the total distance will be equal to the total height.
$ d_h = columns * \frac{width}{columns} = width $
$ d_v = rows * \frac{height}{rows} = height $
It seems to be the case that the number of columns and rows does not matter, as the distance traveled will always be the sum of the width (horizontal distance) and height (vertical distance).
We could divide the square infinitely, so we have infinite columns and infinite rows, and the distance will still be the same (20 units in this example).
Wait a minute...
My Conjectures

*

*According to the above, the distance traveled through infinite segments will be 20.

*Why is the value so different from the hypotenuse (almost 50% higher), given than the path from A to B would pretty much represent a diagonal line at that point?
It's been long since I studied integrals and Calculus, so I'm looking for someone that would not mind spending some time explaining this.
Thank you!
PS: I looked at this question, which has a nice diagram similar to mine, but the Manthatan Distance (aka Taxicab Geometry) is not what I'm looking for, as it does not mention any relation with hypotenuse distance when the number of segments approaches infinity.

A: What you say about dividing it into line segments is true, so long as you restrict it to finitely many line segments.  the mistake you are making, and it is a very common one, is to assume that what is true of finitely many segments remains true when we somehow jump to infinitely many many segments.
In the first place, it isn't clear at all what you mean by infinitely many segments.  How exactly is the distance to be divided into infinitely many segments.  In the finite examples you give, all the segments are the same size, but if we have infinitely many segments of the same size, their total length will be infinite.
Leaving that problem aside for the moment, there is no reason to believe that because the lengths of the staircase curves is constant, the limit of these curves will have the same length.    If you think about how arc length was defined in calculus, as the supremum of the lengths of all possible inscribed polygonal paths, you'll see it has nothing to do with these staircase curves, which are not inscribed in the diagonal.  Furthermore, it is not true that familiar properties are preserved by passage to the limit.  On the contrary, a great deal of effort has been spent in discovering conditions under which the limit of a sum is the sum of the limits, the limit of an integral is the integral of the limits, and so on.
As to your final point, "The path from A to B would pretty much represent the hypotenuse at that point," no it wouldn't.  As you yourself have pointed out, it's almost $50\%$ longer.

A: As @saulspatz points out, this paradox illustrates an issue with our intuition, not an issue with our definition of length.
If I have a sequence of paths $\gamma_n: [0, 1] \to \Bbb{R}^2$ connecting two points $P$, $Q$ (i.e. $\gamma_n(0) = P$, $\gamma_n(1) = Q$ for all $n$), and this sequence of paths converges pointwise to another path $\gamma: [0, 1] \to \Bbb{R}^2$ connecting $P$ and $Q$ (i.e. $\gamma(0) = P$, $\gamma(1) = Q$), then the arclengths $L_n$ of the paths $\gamma_n$ need not converge to the arclength $L$ of the limiting path $\gamma$.
We would need additional assumptions, such as that the paths $\gamma_n$ and $\gamma$ are smooth (i.e. continuously differentiable) curves for which $\gamma_n'(t) \to \gamma'(t)$ pointwise (in addition to $\gamma_n(t) \to \gamma(t)$ pointwise), to conclude that $\lim_{n \to \infty} L_n = L$.
(Although Fatou's lemma does guarantee that $\liminf L_n \geq L$--that is, if the $L_n$ converge but not to $L$, they have to converge to something bigger, not smaller, than $L$. We couldn't make up an example like this where the lengths of the diagonal approximations converged to a limit smaller than the diagonal, in other words. Informally, we interpret this as saying the extra bumpiness/jaggedness in cases of non-convergence always increases the sequence of arclengths, compared to the limiting curve's arclength.)
In the OP example, the "street grid" paths $\gamma_n$ have corners (in fact, more and more corners as I make the gridlines closer and closer together) while the "crow-flight" diagonal path itself is smooth, and that jaggedness is what keeps those lengths from settling down to the diagonal length.
It may interest you to know that this isn't even the most pathological example out there. We could use the fractal Koch curve, which is infinitely long (and infinitely jagged), to build a sequence $\gamma_n$ of approximations to the diagonal of the square, each of which has infinite length:

But as explained previously, this picture should not be interpreted as saying that the diagonal of the square is infinitely long!

A: The length of the hypoteneuse on a right triangle with sides $a,b$ is $\sqrt{a^2+b^2}$.
In this case, we have $a=b$, and the limit of the ratio tends:
$$\lim_{a\to0} \frac{2a}{\sqrt{2a^2}}=\sqrt{2}$$


text:
Q: How to remove duplicate entries in PHP's mysqli_query return value? I'm using the following code to retrieve data from my MySQL DB
function mySqlQueryToArray($sql){
    $con = mysqli_connect(host, user, pw, db); //I've ommitted the access details for security

    // Check connection
    if (mysqli_connect_errno()) {
      exit("ERROR: Failed to connect to MySQL: " . mysqli_connect_error());
    }
    // Process SQL query
    $result = mysqli_query($con, $sql);

    // Put result  into 2D array
    $output = array();
    while($row = mysqli_fetch_array($result)) {
        array_push($output, $row);
    }

//Finish
    mysqli_close($con);
    return $output;
}

The return value of this function looks something like this:
Array
(
    [0] => Array
        (
            [0] => 1
            [TopicID] => 1
            [1] => test
            [name] => test
        )

)

I'd like to make it so that the output instead looks like:
Array
(
    [0] => Array
        (
            [TopicID] => 1
            [name] => test
        )

)

I'm wondering A) Why the function creates these duplicates and B) How to remove them, either as part of the call to mysqli_query or as some array manipulation magic.


text:
Q: pstats print_stats() throws error TypeError: descriptor 'write' requires a '_io.StringIO' object but received a 'str' I want to write profiler decorator as in the example of official documentation of cProfiler. But I get TypeError.
I have debugged and in pstats module this line throws the exception:
print(indent, self.total_calls, "function calls",
end='',file=self.stream).

Here self.stream comes as IoString object.
import cProfile, pstats, io
def profile(fnc):
    def inner(*args, **kwargs):
        pr = cProfile.Profile()
        pr.enable()
        ret_val = fnc(*args, **kwargs)
        pr.disable()
        s = io.StringIO
        sort_by = 'cumulative'
        ps = pstats.Stats(pr, stream=s).sort_stats(sort_by)
        ps.print_stats()
        # ps.dump_stats('results')
        print(s.getvalue())
        return ret_val
    return inner

File "/usr/lib/python3.5/pstats.py", line 336, in print_stats
      print(indent, self.total_calls, "function calls", end=' ',
      file=self.stream) TypeError: descriptor 'write' requires a '_io.StringIO' object but received a 'str'


text:
Q: Run 2 applications on same port and same ip adress with iis I'm trying (as the title explains) to run two applications both on the same port and same ip adress as i have one server with only one ip adress and one hostname.
And for security reasons i only have one open port.
So i'm using iis and i want to know what's the best way to do so.
Thanks in advance.


text:
Q: bash: ./mybashfile.sh: Permission denied I created a bash file mybashfile.sh containing below commands, but running it in the terminal giving me a Permission Denied Error I tried running the file from su but same Permission Denied Error for su.
I am running the command like this -

$: ./mybashfile.sh

It is in a directory containing mybashfile.sh
My mybashfile.sh file -
#!/usr/bin/env bash
redis-server --save "" &
sleep 1
redis-cli flushall
cd ~/Documents/class-prj/class-prj
npm run app.js

Let me know what I am doing wrong here.

A: Set the mode to executable:
chmod +x mybashfile.sh


text:
Q: NServicebus / CQRS: How to handle things in the userinterface? I've been reading Udi Dahan's text on [Command Query separation and SOA][1]. Thinking about how I would use this in practice in a system I'm currently working on raised some questions...

1.
Consider the following situation where I have a WPF client application that allows the user to edit a list of entries:
The client application is started. At startup, it subscribes to the command service that will handle and publish changes to the entries and it queries a WCF service for the complete list of entries. After receiving the list of entries, any changes (by other clients) that may have been published to the clients queue while it was busy waiting for a reply from WCF are merged into the list.
Now to me there seems to be a (probably very small) chance that the client subscribes just after a command responsible for a change was handled and that the WCS service's query is started just before the same change has been committed to the database. In this situation I'll end up with incorrect data in my client that is not (and will never get into) sync with the database (unless the client application is restarted). Does this problem really exist and if it does, how should it be handled?

2.
My second question is about how to design/implement the user interface:
The user now wants to change an entry in the list; a windows pops up, data is changed and the ok button is pressed: we send a message to our command handler to handle this change.
The user expects to see either a confirmation (the entry in the list changes) or an error
message.
Now I can try to handle things in the user interface in a 'synchronous' way (let the user do one thing at a time, and let him wait for success or failure before he's allowed to do anything else) the following way:

*

*After the user presses ok, disable all controls so no further editing is possible.

*Create a Saga with a timeout that waits for ...? The response message? The published notification from the command service? Both?

*When a response message is received the data in the list is changed, controls are enabled and we're done -- or:

*A timeout occurs. The command message has been queued, so the change will eventually be performed, so what to do? Show a message to the user ("this is taking longer than expected..."), enable all controls and change the data in the client once the notification is received from the command service? But what if an error is returned? The user may have started doing something else (maybe editing another entry) and popping up an error message from a previous edit attempt doesn't seem like a good idea.

Another approach would probably be to just send the command and let the user continue with whatever he likes to do next. Maybe show all outstanding commands in a list in the user interface somewhere, with an indicator of success or failure and the possibility for the user to display the error message in case of a failure. Given that timeouts are hopefully exceptional and that responses should normally be received within a few seconds would mean that this list should normally have at most 1 outstanding command in it.. That and the fact that I can't remember that I've ever seen a user interface doing things this way means that it's probably not a good idea.
And your question is ? ;)
Well, I'm just wondering about how other people are solving this in their user interfaces. Likely there are better ways of handling things in the UI than the two maybe not-so-clever ways that I came up with?
Apologies for the long text and thanks in advance for your replies.
[1]: http://www.udidahan.com/2008/08/11/command-query-separation-and-soa/"Command Query separation and SOA"

A: To question number 1, the standard solution for querying is to create a server-side persistent query store that the client RPC-request/responses against.
To question number 2, the answer is very much dependent on the domain - the kinds of commands, the nature of inter-user collaboration. As an overarching rule, think of ways you can change the UI and/or the data/handling of the commands such that commands will hardly ever fail (unless we're talking about malicious users).
Hope that helps.


text:
Q: Leak in CGBitmapContextCreate Trying to find the leak in my code I removed all the thing that did not matter, leaving the following code:
static int last_memory = 0;

void report_memory(NSString *name) {
    struct task_basic_info info;
    mach_msg_type_number_t size = sizeof(info);
    kern_return_t kerr = task_info(mach_task_self(),
                                   TASK_BASIC_INFO,
                                   (task_info_t)&info,
                                   &size);
    if( kerr == KERN_SUCCESS ) {
        int change = (int)info.resident_size - last_memory;
        NSLog(@"%@ >>> Memory in use: %u (change: %d Kb)", name, info.resident_size, change/1024 );
        last_memory = info.resident_size;
    } else {
        NSLog(@"Error with task_info(): %s", mach_error_string(kerr));
    }
}

- (CGContextRef) createBitmapContextOfSize:(CGSize) size {
    CGContextRef    context = NULL;
    CGColorSpaceRef colorSpace;
    void *          bitmapData;
    int             bitmapByteCount;
    int             bitmapBytesPerRow;

    bitmapBytesPerRow   = (size.width * 4);
    bitmapByteCount     = (bitmapBytesPerRow * size.height);

    colorSpace = CGColorSpaceCreateDeviceRGB();
    bitmapData = malloc( bitmapByteCount );
    if (bitmapData == NULL) {
        NSLog(@"Memory not allocated!");
        CGColorSpaceRelease( colorSpace );
        return NULL;
    }
    context = CGBitmapContextCreate (bitmapData,
                                     size.width,
                                     size.height,
                                     8,      // bits per component
                                     bitmapBytesPerRow,
                                     colorSpace,
                                     kCGImageAlphaPremultipliedLast);
    CGContextSetAllowsAntialiasing (context,NO);
    if (context== NULL) {
        free (bitmapData);
        CGColorSpaceRelease( colorSpace );
        NSLog (@"Context not created!");
        return NULL;
    }
    CGColorSpaceRelease( colorSpace );
    return context;
}

- (IBAction) clickButton:(UIButton *)sender {
    report_memory(@"begin");
    NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"test"];
    UIImage *image = [UIImage imageWithContentsOfFile:path];

    report_memory(@"image_created");

    CGContextRef myBitmapContext = [self createBitmapContextOfSize:CGSizeMake(256, 256)];
    if (!myBitmapContext){
        return;
    }
    report_memory(@"bitmap_context_created");
    CGContextDrawImage(myBitmapContext, CGRectMake(0, 0, 256, 256), image.CGImage);
    report_memory(@"draw_image");
    CGImageRef ref = CGBitmapContextCreateImage(myBitmapContext);
    report_memory(@"image_context_created");
    CGContextRelease(myBitmapContext);
    report_memory(@"bitmap_context_released");
    UIImage *result = [UIImage imageWithCGImage:ref];
    report_memory(@"image_created");
    CGImageRelease(ref);
    report_memory(@"image_context_released");
    imageView.image = result;
    report_memory(@"image_assigned");
}

("test" is 256x256 JPEG image).
The console showed the following after a few clicks:
begin >>> Memory in use: 18866176 (change: -12 Kb)
image_created >>> Memory in use: 18870272 (change: 4 Kb)
bitmap_context_created >>> Memory in use: 18870272 (change: 0 Kb)
draw_image >>> Memory in use: 19140608 (change: 264 Kb)
image_context_created >>> Memory in use: 19140608 (change: 0 Kb)
bitmap_context_released >>> Memory in use: 19140608 (change: 0 Kb)
image_created >>> Memory in use: 19140608 (change: 0 Kb)
image_context_released >>> Memory in use: 19140608 (change: 0 Kb)
image_assigned >>> Memory in use: 19140608 (change: 0 Kb)

A net loss of 256Kb per click (equal to 256x256x4). The same trend could be seen in the allocations performance tool. Everything pointing to the CGBitmapContext not being released. I just don't see what I am doing wrong...

A: Let the CGBitmapContextCreate allocate the memory itself by providing NULL as the first argument (bitmapData). That frees you from managing your memory allocation - which you're not freeing at the moment.


text:
Q: Display current folder name on Document Library web part I am displaying a Document Libray Web Part (which contains folders) on a subsite homepage.

When I click on a folder to show its contents, the Document library header still says "Documents". It gives no indication of what folder is being shown. This is confusing, especially when the folder is empty.

This is in contrast to how the Documents Library shows when it is opened in its own page:

How can I make the Document Library Web Part on a Site Page display the current folder name as is done when the Document Library is opened on its own page?

A: There isn't an OOB way, but you can inject a script that create a breadcrumb to enable you to navigate the folder structure.
You can find the code here: https://github.com/RiccardoGDev/sp-breadcrumb

A: Ok, so you are using a Modern Document Library, and then you have a Classic List View web part on a classic page.
The classic list view web part does not support breadcrumbs for folder navigation, but the JavaScript snippet at the following link will provide this functionality
https://code.msdn.microsoft.com/office/SharePoint-2013-Folder-661709eb


text:
Q: UNIX / Linux / Mac OSX get permission of file as number This must be really simple to do but have completely drawn a blank.  I can see the permission of files by using ls -la which can give something like:
-rwxr-xr-x   1 james  staff   68  8 Feb 13:33 basic.sh*
-rw-r--r--   1 james  staff   68  8 Feb 13:33 otherFile.sh*

How do I translate that into a number for use with chmod like chmod 755 otherFile.sh (with out doing the manual conversion).

A: stat -f "%Lp" [filename] works for me in OS X 10.8.

A: You should be able to use the stat command instead of ls.  From looking at the manpage, this should work to get the file permissions:
for f in dir/*
do
    perms=$(stat -f '0%Hp%Mp%Lp' $f)
    echo "$f has permissions $perms"
done

(although I am not at my Mac at the moment and therefore cannot test it).


text:
Q: What is default system font name? Ubuntu 14.04: what is default system font name?

EDIT: This font is not Ubuntu. Ubuntu font look different:

See the difference?

A: The default system font name is also Ubuntu.


text:
Q: At login screen, a progress bar logs me in without asking for password first time here for asking a question :)
Everything is in the title : the issue happens when I'm at the login screen after booting my laptop, at the screen where I have to choose the account I want to log in ( I just have a single one actually). If I touch nothing, a little progress bar at the bottom of the selection box of the account starts and when it reaches the end of the box my session opens automatically without asking for the password. I looked for an option to avoid this issue ( because I don't really want ubuntu to open my session without asking the password) but I didn't find it.
May I ask for help on this matter ? I'm on Ubuntu 19.10 and the option for automatic login on user settings is unchecked, in case.


text:
Q: Chart.js Radar Chart how to add custom tooltip a non-point location I have a pretty basic radar chart and its working as it should.
Now I'm wondering if there is a way to add tooltips that use the default styling but for non-point coordinates, such as the centre position.
I would like to re-use the built in tooltips to benefit from styling and transitions without having to built a custom onHover overwrite.
So I would like to specify x and y coordinates in which the tooltip should show up and then the text that should be displayed. Some kind of callback would work I assume.
I suppose I could add a dataset which has all 0 values and add a custom tooltip to that, but that's not quite exactly what I am trying to achieve here.
Does Chart.js support this? I couldn't find it in the specs nor on stack overflow.
Thanks in advance!


text:
Q: 404 when trying to upload different file types I have a form and a controller. On form submit, the controller method is called, and being hit.
[HttpPost]
public ActionResult PostDocument(
    IEnumerable<HttpPostedFileBase> files,
    IEnumerable<string> classifications,
    string loanAppId,
    string loanNumber)
{
    List<UploadedDocument> uploadedDocuments = new List<UploadedDocument>();
...

When I select .txt files in my form to upload, the method gets called, and happiness ensues. When I try to upload a .pdf, I get a 404 error.
Any thoughts why I might be getting a 404 error when I upload different file types? Is there some config setting somewhere preventing this? If so, why would a 404 error be the result?

A: If you are using IIS you should ensure that the file extension PDF (and any others that you wish to allow) have been configured. Out of the box certain file types will be blocked.
Check at the site level and individual subweb (for any override) under "Request Filtering->File Name Extensions" tab in IIS 7.5.


text:
Q: Cannot change column 'role_id':used in a foreign key constraint 'users_role_id_foreign'(SQL:ALTER TABLE users CHANGE role_id role_id INT DEFAULT NULL)
SQLSTATE[HY000]:General error:1832 Cannot change column 'role_id':
  used i n a foreign key constraint 'users_role_id_foreign' (SQL: ALTER
  TABLE users CHANGE role_id role_id INT DEFAULT NULL)

voyager version : v1.1
laravel : v5.7
I made changes in seeders and re-seed the database
run this command
php artisan migrate:refresh --seed
I was phasing this error
Screenshot

2017_11_26_013051_add_user_role_relationship_fix.php. this file is there in migration everything in commented in run() and down() method.
how to solve this please anyone can help me

A: just run php artisan migrate:fresh --seed instead


text:
Q: How to destroy root Preact node? I want to destroy the root Preact DOM node. I initially render my component as follows:
import { h, render } from 'preact';
import App from "./components/App";

render(<App />, document.querySelector("#app");

How do I destroy App? Do I simply unmount the #app DOM node, or does Preact offer a method similar to React's unmountComponentAtNode() method?

A: Disclaimer: I work on preact.
Any rendered preact app can be easily destroyed by passing null to render:
render(null, document.querySelector("#app"));

We don't need any special functions to do that and have chosen to keep a small API surface area. The implementation for unmountComponentAtNode in preact-compat does literally just call render with null:
// Excerpt from compat for Preact X
function unmountComponentAtNode(container) {
    if (container._prevVNode!=null) {
        render(null, container);
        return true;
    }
    return false;
}

A: There is no method like unmountComponentAtNode() without preact-compat.
A workaround is to use the third argument of the render() method to replace the component you want to unnmount by '' or null like suggested here :
https://github.com/developit/preact/issues/53#issuecomment-184868295


text:
Q: How can I rotate texture inside a plane? have pb with rotate texture, i read this question
Three.js Rotate Texture and there guys propose rotate in canvas, and it work good if you have rectangle, but i have pb with polygon, so after rotating i will have black area in some corner, so that solution is not for me, so maybe who know how i can rotate texture by threejs???

A: //Here's some code showing texture rotation/repeat/offset/center/etc.

var renderer = new THREE.WebGLRenderer();
var w = 600;
var h = 200;
renderer.setSize(w, h);
document.body.appendChild(renderer.domElement);

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(
  45, // Field of view
  w / h, // Aspect ratio
  0.1, // Near
  10000 // Far
);
camera.position.set(15, 10, 15);
camera.lookAt(scene.position);
controls = new THREE.OrbitControls(camera, renderer.domElement);

var light = new THREE.PointLight(0xFFFF00);
light.position.set(20, 20, 20);
scene.add(light);
var light1 = new THREE.AmbientLight(0x808080);
light1.position.set(20, 20, 20);
scene.add(light1);
var light2 = new THREE.PointLight(0x00FFFF);
light2.position.set(-20, 20, -20);
scene.add(light2);
var light3 = new THREE.PointLight(0xFF00FF);
light3.position.set(-20, -20, -20);
scene.add(light3);

var planeGeom = new THREE.PlaneGeometry(40, 40);
var canvas = document.createElement('canvas');
canvas.width = canvas.height = 64;
var ctx = canvas.getContext('2d');

ctx.fillStyle = 'rgba(256,0,0,0.95)'
ctx.fillRect(0, 0, 32, 32);
ctx.fillRect(32, 32, 32, 32);
var srnd = (rng) => (Math.random() - 0.5) * 2 * rng
for (var i = 0; i < 300; i++) {
  ctx.fillStyle = `rgba(${srnd(256)|0}, ${srnd(256)|0}, ${srnd(256)|0}, ${srnd(1)})`
  ctx.fillRect(srnd(60) | 0, srnd(60) | 0, 5, 5);
}
ctx.fillStyle = 'rgba(256,256,0,0.95)'
ctx.fillText("TEST", 2, 10);
ctx.fillText("WOOO", 32, 45);

var tex = new THREE.Texture(canvas)
tex.magFilter = THREE.NearestFilter;
tex.wrapS = tex.wrapT = THREE.RepeatWrapping;
tex.magFilter = tex.minFilter = THREE.NearestFilter;
tex.needsUpdate = true;
var material = new THREE.MeshLambertMaterial({
  color: 0x808080,
  map: tex,
  transparent: true,
  side: THREE.DoubleSide
});
var mesh = new THREE.Mesh(planeGeom, material);
scene.add(mesh);
renderer.setClearColor(0xdddddd, 1);

tex.repeat.x = tex.repeat.y = 2;

//fun effect
for (var i = 1; i < 10; i++) {
  var m;
  scene.add(m = mesh.clone());
  m.position.z += i * 1.1;
}

(function animate() {
  var tm = performance.now() * 0.0001
  tex.rotation = Math.sin(tm) * Math.PI
  //tex.offset.x = tex.offset.y = -2;
  //tex.offset.x = Math.sin(tex.rotation) * -0.5;
  //tex.offset.y = Math.cos(tex.rotation) * -0.5;
  tex.repeat.x = tex.repeat.y = Math.sin(tex.rotation * 1.5) * 3;
  tex.center.x = 0.5;
  tex.center.y = 0.5;

  requestAnimationFrame(animate);
  controls.update();
  renderer.render(scene, camera);
})();
<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://cdn.rawgit.com/mrdoob/three.js/master/examples/js/controls/OrbitControls.js"></script>


text:
Q: Batch Self-Altering Script I have a batch script that in essence is an infinite loop which resets after pause>nul. However, I need a way to replace every set /p to a set in order to remove the prompting while still showing the input that was given in the previous loop. Can I implement something into this script to self-edit all of the set /p's to set's?
@echo off
title
setlocal enabledelayedexpansion
:a
cls
set /p a=Hello, world
echo %a%
pause>nul
goto a

The output that I desire after the first loop is:
@echo off
title
setlocal enabledelayedexpansion
:a
cls
set a=Hello, world
echo %a%
echo %a%
pause>nul
goto a

Can somebody please explain to me Aacini's answser because it seems to work perfectly.

A: This solve your original request of replace every set /p ... commands by set ... ones:
@echo off
title
setlocal enabledelayedexpansion
set pSwitch=/p
:a
cls
set %pSwitch% a=Hello, world
echo %a%
pause>nul
set "pSwitch="
goto a

Just use the set %pSwitch% ... format in all commands you want to change.
EDIT: Reply to the comments
In your example you changed a set /p var=Prompt command by set var=Prompt, that is, after the first loop you assign the Prompt to the variable! Just after read your last comment I realized that you want "to store variables that are inputted by the user permanenetly". You may do that this way:

*

*At beginning of your program, insert: call :initVars.

*Change each set /p var=Prompt command by call :mySet var="Prompt".

*At end of your program, insert:

.
:mySet var="Prompt"
if not defined %1 (
   set /P "%1=%~2"
   echo set "%1=!%1!" >> "%~F0"
)
exit /B

:initVars

For example:
@echo off
title
setlocal enabledelayedexpansion
call :initVars

:a
cls
call :mySet a="Hello, world"
echo %a%
pause>nul
goto a

:mySet var="Prompt"
if not defined %1 (
   set /P "%1=%~2"
   echo set "%1=!%1!" >> "%~F0"
)
exit /B

:initVars

A: idk what you have tried, or what your script looks like, but try something like this.
set p=/p var=prompt
:a
set %p%
pause>nul
set p=var=prompt
goto a

if this doesnt help, please describe your issue further.
ps, not at a windows comp right now, so cant test this.

A: This will ask for a value the very first time and use "Hello, world" in all other runs in the loop (that is what your example suggests):
@echo off
set "a="
    :a
if not defined a ( set /p "a=Hello, world:" ) else ( set a=Hello, world )
echo %a%
pause>nul
goto :a

This is, what I think you want: asking for a value the first time and use this value in all other runs:
@echo off
set "a="
    :a
if not defined a (set /p "a=Hello, world:") else (echo %a%)
pause>nul
goto :a


text:
Q: Script to fill a web form using a set of data I am currently configuring software, however, the fields I am configuring requires a very simple set of data (3 variable fileds) to be entered into a form. However, this operation needs to be done approximately 2,500 times to cover all cases. I can easily genrate a csv containing all the fields for all the entries of this tabel.
I am looking for high level information as to how this can best be accomplished using a script. Could somebody provide a crash course on how to incorperate a custom script to load and submit this information using an external file. Things such as: what fields should I look for using the inspect element or how to load and iterate through a file using JS or python, etc.  Or provide any resources that would be helpful on how to accomplish this. Thanks in advance!

A: In this case I suggest using python rather than javascript, which can be executed conveniently in local.
At the beginning, you need a I/O. In case you are not familiar, take a look on this.
Next, you need a way to send http request. The library for this is urllib, which is inbuilt. Then you need a way to make everything in json, which is well-accepted type for data transferring through http.
You can find the sample of using urllib here.
Please remember that you are 'passing the data', use 'POST' method instead of 'GET' method.
Your data should be encoded in
from json import dumps
data= dumps({
    //data dictionary
})
...
urllib.urlencode({'login' : 'MyLogin', 'password' : 'MyPassword', 'data': data})

You can ignore login and password just in case your backend doesn't require verification.
Welcome to ask me if you have any problem about this.


text:
Q: Adb was accidentally removed. How to restore it on Mac? I have installed Android Studio 2.2 on my mac. While playing with "ln" command, i removed "adb" through incorrect arguments usage.
 How can i restore the "adb"?
If i try to install SDK tools, it tries to stop adb, which can't be found.

A: Download platform-tools_rXX...zip for your operations system ad extract ad
https://stackoverflow.com/tags/adb/info


text:
Q: How to add an element in this XML file using DOM parser? I want to know how can I modify this XML file,
<?xml version="1.0"?>
<nombre>
    <id>12345</id>
</nombre>

into a XML file like this using DOM parser in Java,
<?xml version="1.0" encoding="UTF-8" ?>
    <heat>2013-09-09</heat>
    <nombre>
      <id>12345</id>
    </nombre>

I have tried this but doesn't work,
public class Test {

public static final String xmlFilePath = "src/vnx.xml";
public static final String xml2FilePath = "src/input2.xml";

public static void main(String argv[]) {

    try {

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(xmlFilePath);

        Element version = document.createElement("heat");
        version.appendChild(document.createTextNode("2013-09-09"));
        document.appendChild(version);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();

        Transformer transformer = transformerFactory.newTransformer();
        DOMSource domSource = new DOMSource(document);

        StreamResult streamResult = new StreamResult(new File(xml2FilePath));
        transformer.transform(domSource, streamResult);

    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    } catch (TransformerException tfe) {
        tfe.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } catch (SAXException sae) {
        sae.printStackTrace();
    }
}

}
It returns a parsing error. Any suggestion would be really helpful. Thanks a lot!

A: Try This Code,I have used Xpath to navigate XML and created the new Node and Appended to XML.
Or Without XPATH you can Do it.
Following Code is without Xpath.Xpath Code is in Comment
 try {
    File inputFile = new File("src/vnx.xml");
    DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    // creating input stream
    Document doc = builder.parse(inputFile );

    //Xpath compiler
    //XPathFactory xpf = XPathFactory.newInstance();
    // XPath xpath = xpf.newXPath();

    //XPath Query
   // XPathExpression expr = xpath.compile("/");
    //Node attributeElement = (Node) expr.evaluate(doc, XPathConstants.NODE);

    //New Node
    Node childnode=doc.createElement("heat");
    doc .appendChild(childnode);
    childnode.setTextContent("12-34-56");

    // writing xml file
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
     File outputFile = new File("src/input2.xml");
    StreamResult result = new StreamResult(outputFile );
    // creating output stream
    transformer.transform(source, result);
    } catch (Exception e) {
        e.printStackTrace();
    }

In case file not found,please check the path of your XML files
Thank you

A: Before reading your code, I found problems in your XML file.
A xml file should contains only one root, in your case, the correct file may be something like this:
<?xml version="1.0" encoding="UTF-8" ?>
<root>
    <heat>2013-09-09</heat>
    <nombre>
      <id>12345</id>
    </nombre>
</root>

A: Try This one:
try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory
                .newInstance();

        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        /* create root elements */
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("root");
        doc.appendChild(rootElement);

        /* create elements */
        Element heat= doc.createElement("Heat");
        heat.setAttribute("heat", "2013-09-09");
        rootElement.appendChild(heat);

        Element number= doc.createElement("number");
        rootElement.appendChild(number);

        /* create child node and add id elements */
        Element id= doc.createElement("ID");
        id.setAttribute("id", "12345");
        number.appendChild(id);

        /* write the content into xml file */
        TransformerFactory transformerFactory = TransformerFactory
                .newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        /* set source and result */
        DOMSource source = new DOMSource(doc);

        StreamResult result = new StreamResult(new File("input2.xml"));

        transformer.transform(source, result);
        return true;
    } catch (ParserConfigurationException pce) {
        LOGGER.error("exception while creating Xml File", pce);
        return false;
    } catch (TransformerException tfe) {
        LOGGER.error("exception while creating Xml File", tfe);
        return false;
    } catch (Exception e) {
        LOGGER.error("exception while creating Xml File", e);
        return false;
    }


text:
Q: temporal rule engine for alarm management I am looking for a rule based system (forward chaining) like CLIPS  than can do temporal reasoning, i.e. phrases of the form:
If condition active for more than 10s...
If condition1 becomes active less than 10s after condition2 becomes active...
If more than n events during 10s...
If first condition1 then condition2 and then condition3 not more than 2 s apart...
This is for an alarm system, I would prefer a c or python library or something that can be easily interfaced to python.
I've found this discussion, but it did not help much:
Rules engine for spatial and temporal reasoning?

A: It's not been modified for several years, but there is a Python library for CLIPS on sourceforge called PyCLIPS.  They have a rather complete manual too.


text:
Q: PHP rename image based on HTML form input file ID I was wondering whether it is possible to rename an image base on the form input file ID.
<form action="upload_file.php" enctype="multipart/form-data" method="post">
    <input id="picture_01"  type="file">
    <input id="picture_02"  type="file">
    <input id="picture_03"  type="file">
    <input id="picture_04"  type="file">
<input name="submit" type="submit" value="Submit">
</form>

I want that if the image is uploaded from input 4 it will be renamed to 'picture_04', if it is from input form 2 it will be renamed to 'picture_02'. Not sequencially but according to the input form box.
I haven't managed to do this despite the various trial and errors.

A: You need to name your inputs:
<input id="picture_01" name="picture_01" type="file">

etc.
Then in PHP you retrieve the image with the $_FILES array, like $_FILES['picture_01'] or by simply looping through $_FILES.
foreach( $_FILES as $input_name=>$file)
{
  // $input_name is the name used as the form input name
  // $file is an array with the following keys: name, type, tmp_name, error, size.
}

Of course the manual is always a good read http://www.php.net/manual/en/features.file-upload.post-method.php

A: I would use separate forms for each input. This way you could use a hidden input like:
<form action="upload_file.php" enctype="multipart/form-data" method="post">
   <input type='hidden' name='picture_03_file' value="picture_03" />
   <input type='file'   name='picture_03_name' />
</form>
<form action="upload_file.php" enctype="multipart/form-data" method="post">
   <input type='hidden' name='picture_04_file' />
   <input type='file'   name='picture_04_name' value="picture_04" />
</form>

This way your PHP code would look like:
$imgName = $_POST['picture_04_name'];
// Do file upload here


text:
Q: Prove $b^{2} (\cot A + \cot B) = c^{2}(\cot A + \cot C)$ In any triangle  $ABC $ prove that  $$b^{2} (\cot A + \cot B) = c^{2}(\cot A + \cot C)$$
How we can prove this trigonometric identity.  I tried many ways and use the other well known identity but it wasn't work. My question is how we can prove this trigonometric identity?. Any hint will help  Thanks.

A: We have
$$\cot A+\cot B=\frac{\cos A}{\sin A}+\frac{\cos B}{\sin B}
=\frac{\cos A\sin B+\sin A\cos B}{\sin A\sin B}$$
Now, by using the formula $\sin (A+B)=\sin A\cos B+\cos A\sin B\,\,\,\,$ and $\,\,\,\,\sin C=\sin (\pi-C)$ we get
$$b^2(\cot A+\cot B)=\frac{b^2\sin (A+B)}{\sin A\sin B}=\frac{b^2\sin C}{\sin A\sin B}...(1)$$
In a similar way we get
$$c^2(\cot A+\cot C)=\frac{c^2\sin B}{\sin A\sin C}...(2)$$
In order to prove that $(1)$ and $(2)$ are equal it will be sufficient to prove:
$$\frac{b^2\sin C}{\sin B}=\frac{c^2\sin B}{\sin C}$$
Which is equivalent to
$$\frac{b^2}{\sin^2 B}=\frac{c^2}{\sin^2 C}$$
And the last equality holds due to Sine Law.

A: There is a nice proof of this trig identity.
Notice, in right $\triangle ABC$  $(A+B+C=180^\circ)$ we know from sine rule $$\frac{a}{\sin A}=\frac{b}{\sin B}=\frac{c}{\sin C}=k$$
$$\implies \ a=k\sin A, \  b=k\sin B, \ c=k\sin C, $$
Now, we have $$LHS=b^2(\cot A+\cot B)$$
$$=(k\sin B)^2\left(\frac{\cos A}{\sin A}+\frac{\cos B}{\sin B}\right)$$
$$=k^2\sin^2B \left(\frac{\sin A\cos B+\cos A\sin B}{\sin A\sin B}\right)$$
$$=k^2 \frac{\sin B\sin (A+B)}{\sin A}$$
 $$=k^2 \frac{\sin (180^\circ-(A+C))\sin (180^\circ-C)}{\sin A}$$
 $$=k^2 \frac{\sin (A+C)\sin C}{\sin A}$$
$$=k^2\sin^2 C \left(\frac{\sin A\cos C+\cos A\sin C}{\sin A\sin C}\right)$$
 $$=(k\sin C)^2 \left(\frac{\cos C}{\sin C}+\frac{\cos A}{\sin A}\right)$$
setting the value $k\sin C=c$ from (1) $$=\color{}{(c)^2(\cot C+\cot A)}$$
$$LHS=\color{red}{c^2(\cot A+\cot C)}=RHS$$

A: Here's a trigonograph for non-obtuse $B$ and $C$:

$$|\overline{AB}||\overline{ED}| = |\square AEDF| = |\overline{AC}||\overline{FD}| \quad\to\quad c^2\,\left(\, \cot A + \cot C \,\right) = b^2\,\left(\,\cot A + \cot B\,\right)$$


text:
Q: ASP.NET Identity VS Самописная система авторизации Может показаться что это очень "холиварный" вопрос, но я всё же задам его.
Начинал писать свою систему ещё тогда, когда был в моде ASP.NET Membership. Ну естественно, гибкости мне далеко не хватало и я решил писать свою систему авторизации, не опираясь на какие-то устоявшиеся в те времена принципы разработки авторизационных/аутентификационных систем. Что примерно из себя напоминает система сейчас:

*

*Отдельный контекст (мало ли что в жизни бывает);

*CodeFirst - реализация;

*Хранение токена сессии в кукисах и сравнение его с токеном в отдельной таблице в БД.

*Авторизационные фильтры типа ([IdentityFilter("admin", "user", "manager")]) и типа ([IdentityFilter(RolesEnum.Manager)]). На выбор ;)

*Репозиторий.

*Авторизационная информация получается в фильтре и далее гуляет в HttpContext`e.

*Ну и много других мелочей.

Так вот, как бы работает быстро, но что то подсказывает мне, что можно ещё быстрее.
Собственно хотелось узнать, какие преимущества может нести для меня Identity и целесообразно ли его использование в "реальном продакшне", или же это интерфейс для новичков, и для тех, кто не хочет парится.
Ведь в моём коде для меня нет никаких ограничений, а вот в Identity ограничения всё таки есть, хотя бы то же самое именование таблиц и полей по умолчанию.
P.S. Прошу очень развёрнутый, и тем более аргументированный ответ. Заранее спасибо!

A: Membership забыл как страшный сон, перешел на Identity:

*

*Нужна простая авторизация без лишней возни? - пожалуйста. Добавил подсистему и забыл.

*Нужно использовать Claims? - пожалуйста. Не нужно? - можно добавить в любой момент, а до тех пор хранить все основной таблице. А Claims так и будет ждать своего часа.

*Нужно добавить авторизацию через соцсети? - пожалуйста.

*Не нравятся именование полей или самой таблицы? - можно все переименовать.

*Нужно добавить новое поле? - пожалуйста. Автоматическая миграция, ничего не нужно удалять или бэкапить.

*Необходима двухфакторная аутентификация с подтверждением по смс или электронной почте? - Всё есть, просто добавить необходимые службы.

*Дополнительные требования к логинам и паролям? - орудия пыток на выбор:
AllowOnlyAlphanumericUserNames,
RequireUniqueEmail
// -------------------
RequiredLength = 6,
RequireNonLetterOrDigit = false,
RequireDigit = false,
RequireLowercase = false,
RequireUppercase = false

и т.д. и т.п.
Проще в студии загрузить готовый шаблон и поковырять его пару вечерков, чтобы точно убедиться подходит ли Identity для своих нужд.
Для загрузки рабочего примера с комментариями в консоли пишем «Install-Package Microsoft.AspNet.Identity.Samples -Pre»
Update

*

*Если нужно простое, гибкое, функциональное и готовое решение - Asp.net Identity подойдет. Все в коробке.

*Если необходимо реализовывать сложные сценарии: глубокие политики безопасности, одновременная аутентификация по Active Directory, сертификатам, токенам, онлайн формам (как на всех сайтах), то советую обратить внимание на Windows Identity Foundation. Придется несколько попотеть.

A: Холивар полнейшей -)
Добавлю к ответу от товарища @Ice2burn - авторизация по клеймам возможна и достаточно проста в написании. Я написал подобное и уже года полтора в продакшне использую с большим успехом. Прототип можно поковырять здесь.
Identity состоит на самом деле из нескольких пакетов:

*

*Microsoft.AspNet.Identity.Core - в основном интерфейсы и базовые имплементации классов которые не относятся к хранению данных

*Microsoft.AspNet.Identity.EntityFramework - имплементации классов которые относятся к хранению данных. Здесь все заточенно под EF, но все имплементации могут быть замененны на кастомное хранилище. Я видел пакеты которые позволяют хранить информацю о юзерах использую NHibernate или в RavenDb или Azure Tables. Так что хранилище может быть замененно без проблем.

*Microsoft.AspNet.Identity.Owin - адаптер для использования OWIN и создания кукисов через OWIN. В принципе тоже можно заменить, но не могу придумать зачем это менять.

Claims - весьма удобная вещь. Все клеймы которые добавленны в запись юзера попадают в authentication куки и их оттуда можно достать без проблем. Их можно не использовать, но потратить полчаса на понимание как они работают и отказаться будет невозможно -). Когда создается печенка для входа на сайт, все пользователькие роли на самом деле записываются в куку как клеймы. Система потом достает из куки все клеймы с названием Role. То есть хочешь-не хочешь а клеймы используются по дефолту. Можно даже сказать что роли это по сути отдельный класс клеймов.
Еще одна очень удобная вещь в Identity это SecurityStamp - GUID на записи пользователя. Если это поле меняется в базе, то сбрасываются все пользователькие куки и надо логиниться по-новой. Так можно легко предотвращать двух людей которые логинятся с разных компов под одним аккаунтом - полезно когда бизнес модель предполагает оплату по количеству аккаунтов.


text:
Q: Problems while selecting data from the table? I have a table like the one given below.
View        :    Cat    :    Name
abcView
abcView      abcCategory2
abcView      abcCategory2    abcFilter
abcView2
abcView2     abcCategory
abcView2
abcView3

View is the parent of Cat and Cat is the parent of Name. View can never be empty if Cat exists. Similarly, Cat can never be empty if Name exists. I want to fetch data in such a way that I dont want any empty spaces or replications in my result. If there are two entries, one with a child and one without a child then I only want to show the entry with the child. But if there is no child then I just want to return the parent(s) name.
View      :   Cat      :    Name
abcView    abcCateogry2  abcFilter
abcView2   abcCategory
abcView3

A: Try this:
SELECT a.View, MAX(a.Cat) Cat, MAX(a.Name) AS `name`
FROM tableA a
GROUP BY a.View

A: Try following query and check whether it is working or not. It is working in sample data but may create problem in data which you have in table. I am combining three column and checking same combination is not exist in table so you will get one row with max level possible:
DECLARE @TABLE TABLE
(
[View] VARCHAR(100),
Cat VARCHAR(100),
Name VARCHAR(100)
)

INSERT INTO @TABLE VALUES
('abcView','',''),
('abcView','abcCategory1',''),
('abcView','abcCategory2',''),
('abcView','abcCategory2','abcFilter'),
('abcView2','',''),
('abcView2','abcCategory',''),
('abcView2','',''),
('abcView3','','')

    SELECT
    t1.[View],
    t1.Cat,
    t1.Name
FROM
    @TABLE AS t1
WHERE
    (
        SELECT
            COUNT(*)
        FROM
            @TABLE
        WHERE
            ([View]+'-'+Cat+'-'+Name) LIKE '%'+ REPLACE((t1.[View]+'-'+t1.Cat+'-'+t1.Name),'--','-') + '%'
    ) = 1

A: you could select all entries, where a name exists by
SELECT View, Cat, Name
FROM yourTable
WHERE Name NOT NULL

then union it with all entries, where just a cat exists (and no name)
SELECT View, Cat, Name
FROM yourTable
WHERE Name IS NOT NULL
UNION
SELECT View, Cat, NULL
FROM yourTable
WHERE Cat IS NOT NULL AND
      Name IS NULL AND
      Cat NOT IN (SELECT Cat FROM yourTable WHERE Name IS NOT NULL)

and finally union it with all entries, where just a view (and no name and cat exists)
SELECT View, Cat, Name
FROM yourTable
WHERE Name IS NOT NULL
UNION
SELECT View, Cat, NULL
FROM yourTable
WHERE Cat IS NOT NULL AND
      Name IS NULL AND
      Cat NOT IN (SELECT Cat FROM yourTable WHERE Name IS NOT NULL)
UNION
SELECT View, NULL, NULL
FROM yourTable
WHERE View IS NOT NULL AND
      Cat IS NULL AND
      View NOT IN (SELECT View FROM yourTable WHERE Cat IS NOT NULL)


text:
Q: Python, program that multiplies number by 2 til it's greater than 1000, having issue with syntax When I put oursum outside of the loop it infinitely multiplies it by 2
usernum=float(input('Enter a number: '))
if usernum<=0 or usernum>1000:
    print('Your number is '+str(usernum))
else:
     oursum=usernum*2
     while oursum<=1000:
          print('Multiplied by 2 equals '+str(oursum))

When inside, it's not defined.
usernum=float(input('Enter a number: '))
if usernum<=0 or usernum>1000:
   print('Your number is '+str(usernum))
else:

     while oursum<=1000:
          oursum=usernum*2
          print('Multiplied by 2 equals '+str(oursum))

I understand the problems I'm making but I don't know how to rectify this without making it unnecessarily long and complicated. Thanks in advance.

A: The issue is that you're saving the result of the multiplication inside oursum but you're not using oursum later to continue multiplicating.
The following should work and it doesn't add complexity to the code:
usernum=float(input('Enter a number: '))
if usernum<=0 or usernum>1000:
    print('Your number is '+str(usernum))
else:
    oursum = usernum  # oursum starts from usernum and it will get bigger through each iteration
    while oursum<=1000:
        oursum=oursum*2
        print('Multiplied by 2 equals '+str(oursum))

A: In your second code, You are using oursum in the condition of the while statement before defining it. So, define oursum before the while loop and assign a value like 0
usernum=float(input('Enter a number: '))
if usernum<=0 or usernum>1000:
   print('Your number is '+str(usernum))
else:
     oursum = 0 #like this
     while oursum<=1000:
          oursum=usernum*2
          print('Multiplied by 2 equals '+str(oursum))

A: The condition in the if and while being pretty similar, you can combine both in a single test. It can also be a good idea to define a function in order to be able to reuse and test it more easily:
def transform(number):
    while 0 < number <= 1000:
        number *= 2
    return number

if __name__ == '__main__':
    user_num = float(input('Enter a number: '))
    print('After transformation, your number is', transform(user_num))


text:
Q: Variation output hall effect sensor I'm using the hall effect sensor A1301EUA-T, I'm feeding it with 5V. At the VOUT output when there is no magnetic field there is 2.5V. When approaching the NORTH POLE of the magnet VOUT ranges from 2.5 up to 5v. When it approaches the SOUTH POLE of the VOUT magnet it varies from 2.5 up to 0v. To have a variation in VOUT from 0v to 5v I need 2 magnets, move one away and bring the other closer. My question is: how do I have a variation in VOUT from 0v to 5v approaching just one magnet, that is, I want it when I have no magnetic field close to the sensor I have 0v in VOUT?
Here is my circuit:

A: Subtract 2.5 volts and apply a gain factor of two. This can be done quite easily with an opamp but it's likely you'll need a negative supply to reach precisely 0 volts and a positive supply greater than 5 volts to reach an output of 5 volts.


text:
Q: Respond CSS Not Working Properly I am using https://github.com/scottjehl/Respond to help with my browser compatibility for responsive media queries but it doesn't seem to be working properly for I.E.
I have the respond.src.js file in the same folder as index.html / style.css.
<head>
<meta charset="utf-8" />
<link href="style.css" rel="stylesheet"/>
<script src="respond.src.js"></script>
</head>

Any ideas if I am doing anything wrong here?
I am then simply just adding an iFrame.
<body>

    <iframe src="http://instagram.com/p/cR5BORA8Ij/embed/" width="300" height="400" frameborder="0" scrolling="no" allowtransparency="true" id="myFrame"></iframe>

</body>

The iFrame doesn't seem to load in IE 8.

A: Refer to this link:
https://github.com/scottjehl/Respond
It quotes:
Reportedly, if CSS files are encoded in UTF-8 with Byte-Order-Mark (BOM), they will not work with Respond.js in IE7 or IE8. Noted in issue #97


text:
Q: AWS Chime: Serverless Endpoint Security I am trying to setup AWS Chime for iOS application using iOS SDK using this as a reference. One of the steps is to setup a serverless meeting in AWS. All the above steps are successful. But upon creating the serverless meeting in AWS< the endpoint that I received looks like below:
The issue that I am facing is that the endpoint is publicily accessible and anyone can start a meeting with this link. How do I control the host access in this endpoint?


text:
Q: LSTM not learning, no MSE Hi I am having trouble with finding the correct inputshape for my LTSM model. I have been trying to find a shape that fits but have trouble understanding what is required.
I think the problem is in the ytest and ytrain shape. Why is it not the same shape as xtrain and xtest?
xtrain (80304, 37)
xtest (39538, 37)
ytrain (80304,)
ytest (39538,)
Epoch 1/3
2510/2510 [==============================] - 34s 13ms/step - loss: nan
Epoch 2/3
2510/2510 [==============================] - 32s 13ms/step - loss: nan
Epoch 3/3
2510/2510 [==============================] - 33s 13ms/step - loss: nan
Model: "sequential_9"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
lstm_10 (LSTM)               (None, 4)                 96
_________________________________________________________________
dense_9 (Dense)              (None, 1)                 5
=================================================================
Total params: 101
Trainable params: 101
Non-trainable params: 0

The model isnt training based on MSE:
When I try to fit this model:
print('tf version', tf.version.VERSION)

train_size = int(len(oral_ds) * 0.67)
print(train_size)
test_size = len(oral_ds) - train_size
print(test_size)
train = oral_ds[:train_size]
test = oral_ds[80319:119881]

print(len(train), len(test))

X_train = train.drop(columns=['PRICE','WEEK_END_DATE','Optimized rev','Original rev'])
y_train = train.PRICE

X_test = test.drop(columns=['PRICE','WEEK_END_DATE','Optimized rev','Original rev'])
y_test = test.PRICE

print('xtrain',np.shape(X_train))
print('xtest',np.shape(X_test))
print('ytrain',np.shape(y_train))
print('ytest',np.shape(y_test))

X_train=X_train.values.reshape(X_train.shape[0],X_train.shape[1],1)
#y_train=y_train.values.reshape(y_train.shape[0],y_train.shape[1],1)
X_test=X_test.values.reshape(X_test.shape[0],X_test.shape[1],1)
#y_test=y_test.values.reshape(y_test.shape[0],y_test.shape[1],1)

#print('reshaped xtrain',np.shape(X_train))
#print('reshaped xtest',np.shape(X_test))
#print('reshaped ytrain',np.shape(y_train))
#print('reshaped ytest',np.shape(y_test))

single_step_model = tf.keras.models.Sequential()
single_step_model.add(tf.keras.layers.LSTM(4,
                                            input_shape=(37,1)))
single_step_model.add(tf.keras.layers.Dense(units = 1))
single_step_model.compile(optimizer = 'adam', loss = 'mean_squared_error')

BATCH_SIZE=32
train_data = tf.data.Dataset.from_tensor_slices((X_train, y_train))
train_data = train_data.cache().shuffle(10000).batch(BATCH_SIZE)
valid_data = tf.data.Dataset.from_tensor_slices((X_test, y_test))

history = single_step_model.fit(train_data, epochs=3)
single_step_model.summary()

I have tried to implement solutions from other posts such as:

*

*https://datascience.stackexchange.com/questions/39334/recurrent-neural-network-lstm-dimensions-error

*ValueError: Input 0 of layer cu_dnnlstm is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: [None, 175]
But neither of these are working.
Anyway any guidance?

A: So in general LSTM expects 3 dimensonal inputs:
 (#batch_size, #number_of_features, #timesteps)

for which the feature and timesteps indices change depending on the platform. I guess you have 37 timesteps and 1 feature, so just change your input to:
 (#batch_size,37,1) or (#batch_size,1,37)

So see the following dummy example:
import tensorflow as tf
inputs = tf.random.normal([100, 37, 1])
lstm = tf.keras.layers.LSTM(units =50 ,input_shape=(37,1))
output = lstm(inputs)
>>print(output.shape)
(100, 50)

The code in the following works end-to-end:
X_train = np.random.rand(80319,37,1)
y_train = np.random.randint(0,1,80319)
BATCH_SIZE=32
train_data = tf.data.Dataset.from_tensor_slices((X_train, y_train))
train_data = train_data.cache().shuffle(10000).batch(BATCH_SIZE)

single_step_model = tf.keras.models.Sequential()
single_step_model.add(tf.keras.layers.LSTM(4,
                                            input_shape=(37,1)))
single_step_model.add(tf.keras.layers.Dense(units = 1))

single_step_model.compile(optimizer = 'adam', loss = 'mean_squared_error')
single_step_model.fit(train_data, epochs=10)

and if you remove the batch size selection it throws the exactly same error.


text:
Q: Calling open in Terminal in MacOS brings another program to the foreground I have two application bundles (called ProgramA and ProgramB) that I have written for MacOS. If I use open in Terminal to launch one of them it will launch just fine. But if I try to use open to launch the other one while the first one is open, it will instead bring to the foreground the already launched app. For instance, if ProgramA is already open and I use open -a ProgramB, Program A will instead come to the foreground.
I know I can use open -n -a ProgramB to ensure a new app is launched, but I would like to keep the behavior of bringing the app to the foreground if it already running. If I double-click the icon in Finder the apps will open as expected. The apps are being launched by another app so just using Finder isn't an option.
I thought maybe the issue was a duplicate key in the Info.plist that is used by the system, but that doesn't seem to be an issue. The values for the following keys are unique between the two apps:

*

*CFBundleIdentifier

*CFBundleExecutable

*CFBundleName

Is there a way I can get open to launch the correct app if other app is already running?