text:
Q: SL8051 UART Data is Garbled Every Few Attempts I have about 1500 samples stored in memory from an ADC on a SL8051 development board. When compiling these values into a CSV form to send over UART, the transmission is successful about 3/5 times. The other times it is completely garbled. The baud rate is the same on both sides, and we've checked that the UART sent is consistent with other receiving devices.
Acquisition code
 //Code to aqcuire from ADC
    void main (void)
    {
      // unsigned char delay_count;          // Used to implement a delay
      // bit duty_direction = 0;             // 0 = Decrease; 1 = Increase

       // Disable watchdog timer
       WDTCN = 0xde;
       WDTCN = 0xad;

       PORT_Init ();                       // Initialize crossbar and GPIO

        OSCILLATOR_Init ();
       PCA0_Init ();                       // Initialize PCA0
       EMIF_Init ();                        // Storing ADC samples in SRAM

       SFRPAGE = CONFIG_PAGE;

       RAM_CS = 0;                          // assert SRAM chip select

       UART0_Init ();                       // initialize UART0

       Timer3_Init (SYSCLK/SAMP_RATE);      // Init Timer3 for 100 ksps sample rate

       ADC0_Init ();                        // configure ADC0 and ADC1 for differential measurement

       EA = 1;                             // Globally enable interrupts

        while(1)
        {                           // loop this logic for multiple samples

           while(BB_GPIO_INPUT == 0);

           SFRPAGE = TIMER01_PAGE;
           TR0 = 1;
           DMA0_Init ();                        // configure DMA to move NUM_SAMP samples

           SFRPAGE = UART0_PAGE;
           //printf ("Data Acquisition in progress...\n");

           SFRPAGE = DMA0_PAGE;                 // Switch to DMA0 Page

           while (!(DMA0CN & 0x40));            // Wait for DMA to obtain and move ADC samples

           SFRPAGE = LEGACY_PAGE;
           //printf ("Data Acquisition complete.\n");
           SFRPAGE = TIMER01_PAGE;
           TR0 = 0;
           while(BB_GPIO_INPUT == 0);
           SendData();                          // Send data via the UART0

        }
    }

UART Code
//Code to print the data from DMA
 void SendData (void)
    {
        unsigned int i;
        char old_SFRPAGE = SFRPAGE;
        SFRPAGE = UART0_PAGE;

        read_ptr = XRAM_START_ADD;   //pointer at beginning of data

        for (i=0; i<NUM_SAMPLES; i++)
        {
            printf("%u",*read_ptr);     // send data as unsigned integers
            putchar(',');
            read_ptr++;
        }
        printf("\n");

        SFRPAGE = old_SFRPAGE;
    }

UART Init
void UART0_Init (void)
{
    char old_SFRPAGE = SFRPAGE;

    SFRPAGE = UART0_PAGE;           // Switch to UART0 page

    SCON0 = 0x50;                   // SCON: mode 1, 8-bit UART, enable RX
    SSTA0 = 0x10;                   // Timer 1 generates UART0 baud rate and
                                    // UART0 baud rate divided by two disabled

    SFRPAGE = TIMER01_PAGE;         // Switch to timer 0/1 page

//  TMOD = 0x20;                    // TMOD: timer 1, mode 2, 8-bit reload
    TMOD &= 0x0F;                   // clear all T0 control bits
    TMOD |= 0x20;                   // 8-bit auto-reload timer

    TH1 = -(SYSCLK/BAUDRATE/16);    // set timer 1 reload value for baudrate
    TR1 = 1;                        // start timer1;
    CKCON |= 0x10;                  // Timer1 uses SYSCLK as time base
    PCON |= 0x80;                   // SMOD = 1

    SFRPAGE = UART0_PAGE;           // Switch to UART0 page

    TI0 = 1;                        // indicate TX ready

    SFRPAGE = old_SFRPAGE;          // restore SFRPAGE

}

A: In cases like this, the problem is almost always due to the receiving system(s) not being able to keep up with the transmitter. Your transmitter is cranking out data at the full baud rate with no interbyte delay and it simply overruns the receiver.
One test you can do is to dramatically lower the baud rate. This gives the receiving system more time to process each received byte. It may not clear the problem completely but if the errors are reduced or occur less frequently you know where to look.
Another test is to place a decent delay between each transmitted character. If the problem goes away, you have found your culprit.

A: The code actually works. The issue was that the code was processing faster than the UART was being received.


text:
Q: UIFocusGuide doesn't work on UICollectionView in tvOS Basing on this post:
UICollectionViewCell to UIButton Focus in tvOS, I'm adding a UIFocusGuide so when the user are on the right of the collectionview, can select the button on left-buttom.
Using this code:
focusGuide = UIFocusGuide();
focusGuide.preferredFocusedView = btClick
view.addLayoutGuide(focusGuide)
focusGuide.topAnchor.constraintEqualToAnchor(collectionView.topAnchor).active = true
focusGuide.bottomAnchor.constraintEqualToAnchor(btClick.bottomAnchor).active = true
focusGuide.leadingAnchor.constraintEqualToAnchor(collectionView.leadingAnchor).active = true
focusGuide.widthAnchor.constraintEqualToAnchor(collectionView.widthAnchor).active = true

In my example I added a usefull code created by Jack Cox that shows the 'invisible' layout guides, and everything seems good because the layout begin on the top of the collectionView and ends on the bottom of the button.
But it doesn't works, the button only can be selected if the user are on the left of collectionView, on this image you can only going to button from item 1 and item 6.

I've made a little example on github here, I don't know what I'm doing wrong.

A: I have already figured out, the mistake was to create the focus with the entire size of the collectionView now I've created a focus guide just below the collectionView and set preferredFocusedViewto the button.
Using this code:
focusGuide = UIFocusGuide();
focusGuide.preferredFocusedView = btClick
view.addLayoutGuide(focusGuide)

//Modified the size of the UIFocusGuide
focusGuide.topAnchor.constraintEqualToAnchor(btClick.topAnchor).active = true
focusGuide.rightAnchor.constraintEqualToAnchor(collectionView.rightAnchor).active = true

focusGuide.widthAnchor.constraintEqualToAnchor(btClick.widthAnchor, multiplier: 8).active = true
focusGuide.heightAnchor.constraintEqualToAnchor(btClick.heightAnchor).active = true

Now the guide look like this:

I've just committ the changes to github maybe it helps anyone else.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Embedding Checkout I'm trying to embed the checkout of GiftUp on my angular site however not show when I run my HTML page.

Am I correct in just putting this inside my .html or should I split the script up from it.
Any help greatly appreciated.


text:
Q: Mech fighting anime where the good guys deliberately lose I watched this a few years ago. The storyline followed a young man who had a mech (built it himself?) and joined in an arena fight, where there were two sides: One side were the rulers of the city/country and had better equipment, and the other side were afraid to try too hard in case they managed to win because the rulers would get angry if they lost.
You see the characters' faces while they are inside the mechs quite often, and I think you see some electrical attack damage the suit from the inside, though I can't remember which side they were on.
The main character didn't want to deliberately lose though, and they won some fights for the first time in a long time. The show is about him improving his fighting skills, but I never finished it so I don't know what happens in the end.
The mechs were humanoid, and roughly Hulkbuster size.

A: This could be Full Metal Panic! Invisible Victory, the fourth series in the Full Metal Panic! anime franchise. It first aired in April 2018, so you could have seen it no sooner than two years ago.
Episoded 5 to 8 follow Sousuke Sagara trying to infiltrate the world of illegal fights between Arm Slaves (the series' term for mechas).
He helps a small team win a minor (and legal) championship and find a sponsor; while a corrupted officer contacts them to fix the result of a match, Sousuke refuses, instead volunteering to fight in illegal matches where real weapons are used and pilots risk their lives.
The anime opening has a few images relating to this story arc, in particular from 0:34 to 0:40:

A: It's VOTOMS: the Big Fight, or first arc of VOTOMS.


text:
Q: How to print a GoogleMap (or any div) I would like to print the google map (not the rest of the page) of my website, It shall include markers, polyline, infoWindows.
The common way is to use window.print() but this prints the entire page, is there any way to only print a specific map or div?
I've seen people hiding the entire page except the rendered div but that seems overkill.

A: I have found a way to do this using a combination of html2canvas and popout :
First, I use html2canvas to render the GoogleMap (or the div to be rendered).
Then I open a new window with the size of the map or the div, I add an img tag inside the window and I give the canvas URI (rendered in the first step) as the image data .
Finally, I print the popup with window.print() and then close the popout.
Here is my js function(including html2canvas lib):
function printDiv(divId){
    // For GoogleMaps I ignore the helps messages (.gm-style-pbc) displayed over the GoogleMap
    $(".gm-style-pbc").each(function(){this.setAttribute("data-html2canvas-ignore","true");});
    html2canvas($('#'+divId),
    {
    useCORS: true, // useCORS for GoogleMap or divs that use resources from outside the website
      onrendered: function (canvas) {
            // Can be tweaked to avoid popout being blocked
            var myWindow=window.open("about:blank","popup"," width="+canvas.width+", height="+ canvas.height + "resizable=0,scrollbar=0");
            if (myWindow == null){
                //If popout has been blocked display a error message here
            }else{
                //Creating empty window with rendred div image URI
                var content = "<!DOCTYPE html>";
                content += "<title>Map</title>"
                content += ""
                content += ""
                myWindow.document.open()
                myWindow.document.write(content);
                myWindow.document.close();
                myWindow.focus();
                //Added a 500 ms timer before printing and closing as GoogleChrome sometimes didnt had time to render the image and printed a blank screen
                setTimeout(function(){myWindow.print();myWindow.close();},500);
            }
      }
    });
  }

A few notes:

*

*The render of the GoogleMap isn't perfect as html2canvas doesn't support webkit transformation.

*Even with useCORS on, if connection to map API is slow, googlemap background may be incomplete (use html2canvas proxy if you encounter this issue)

*Popout can be blocked and have to be allowed manually by the user (especially on Firefox from my experience)

A screenshot of my french app for the sake of it:


text:
Q: C# 8 default interface implementation and inheritance I want to use C# 8 default interface implementation to face a performance issue in my code.
Actually, I have this intefaces :
public interface IDataAdapter {}
public interface IDataAdapter<T> : IDataAdapter
{
   void Insert(T value);
}

I actually have to do reflection across all IDataAdapter, check generic type and call Insert by reflection for a specific T instance. What I wish to do is :
public interface IDataAdapter
{
   void InsertValue(object value);
}
public interface IDataAdapter<T> : IDataAdapter
{
   void Insert(T value);
   public void InsertValue(object value) => Insert(value as T);
}

The compiler says to use the keyword new to mask the inherited method. However, the only thing I'm trying to accomplish is to have a non-generic method already implemented to make all IDataAdapter<T> implementations to only have to implement the generic version.
Is this something I can accomplish or it's still impossible ? I already know that using an abstract class is a way to solve this issue, but I want to allow a developper to have a class that implements many IDataAdapter...
This is my current reflection code :
public IEnumerable<IDataAdapter> DataAdapters { get; }

    public Repository(IEnumerable<IDataAdapter> dataAdapters)
    {
        DataAdapters = dataAdapters;
    }

    public async Task SaveAsync()
    {
        foreach (var item in aggregates)
        {
            foreach (var dataAdapter in DataAdapters)
            {
                if (dataAdapter.GetType().GetInterfaces().Any(i => i.IsGenericType && i.GetGenericArguments()[0] == item.GetType()))
                {
                    dataAdapter.GetType().GetMethod("Insert", new[] { item.GetType() }).Invoke(dataAdapter, new[] { item });
                }
            }

        }
    }

A: I recognize this problem where you need to look up the IDataAdapter implementation which knows how to handle a certain type of item. I've done something similar for a "view plugin" system, where I would look for the view plugin that knows how to render a certain type. This is useful if you can't know in advance what type of objects you'll need to render.
As far as I know, trying to shoehorn more compile-time type safety into this pattern won't really work, or if it does then it won't actually provide any benefits. I would just declare IDataAdapter like this:
public interface IDataAdapter
{
   void InsertValue(object value);
   Type SupportedType { get; }
}

If a data adapter supports multiple types, you can make it IEnumerable<Type> SupportedTypes instead, or maybe replace the property by a bool SupportsType(Type) method.

A: From an object oriented point of view, what you are trying to do can't be done.
Suppose you create the following class hierarchy:
public interface  IFoo{}
public interface  IBar{}
public class A: IFoo{}
public class B: IFoo{}
public class C:IFoo,IBar {}

And then the following adapters:
public class TestA : IDataAdapter<A>{}
public class TestB : IDataAdapter<B>{}
public class TestC : IDataAdapter<C>{}
public class TestIFoo : IDataAdapter<IFoo>{}
public class TestIBar : IDataAdapter<IBar>{}
public class TestIBoth : IDataAdapter<IFoo>,IDataAdapter<IBar>{}

What should happen if TestA receive an instance of A is quite easy. But what about TestIFoo receive a C? Currently your reflection code won't work because you test type equality (does C equals IFoo? No! Even if C as IFoo is ok).
This breaks Liskov substitution principle. If something works with a class then it should also work with any of its subclasses.
Let's suppose you fix above point. Now what about TestIBoth receiving a C? Is there two different implementation of Insert in it? Of course, this is required by inheritence! But then... do you have to insert C twice? Or do you have to insert it just once in the first fitting method?
The reason why you have to go through reflection is because all those questions needs an algorithmic answer. Your compiler won't be able to answer (which makes the language prevent it by the way)
In the end I would strongly recommend to use a very different solution (like the one proposed by Wim Coenen)


text:
Q: How can I define multiple identifier classes and styles in listings? I'm trying to add different styles (color, etc.) to different groups of words in the listings package. Note that my question is different from How can I use multiple declarations (\textbf, \emph) in listings' emphstyle?.
Let me show you some code:
\documentclass{article}
\usepackage{listings}
\begin{document}
...
\begin{lstlisting}
    {
        "id": {integer},
        "login": {string},
        "password": {string},
        "name": {string},
        "picture": {
            File Resource
        }
    }
    ...
    PUT /files/{file_id}
\end{lstlisting}
\end{document}

I use the \lstset command to define the following:
...
    emph={  % HTTP Request
        GET,POST,PUT,DELETE
    },
    emphstyle={\color{green}},
...

but I would like to add more words with a different style (color, etc.), like so
...
    emph2={  % Variable Types
        integer,string,blob,datetime
    },
    emphstyle2={\color{darkBlue}},
...

How can I do that?

A: You're halfway there. The listings manual (p.31 in v1.5b) tells you that multiple classes of identifiers and associated styles can be defined by using
\emph=[<number>]{<identifier list>}
\emphstyle=[<number>]{<identifier style>}

where <number> is some integer of your choice that gets associated with the class of identifiers in question.

\documentclass{article}

\usepackage{xcolor}
\usepackage{listings}

\lstset%
{%
    emph=[1]%
    {%
        DELETE,
        GET,
        POST,
        PUT,
    },
    emphstyle=[1]{\color{green}},
    %
    emph=[2]% Variable Types
    {%
        blob,
        datetime,
        integer,
        string,
    },
  emphstyle=[2]{\color{blue}},
}

\begin{document}
...
\begin{lstlisting}
    {
        "id": {integer},
        "login": {string},
        "password": {string},
        "name": {string},
        "picture": {
            File Resource
        }
    }
    ...
    PUT /files/{file_id}
\end{lstlisting}
\end{document}

A: A supplement to @Jubobs's answer as a reminder for users of listings v1.6 (maybe also for versions later on, I haven't checked yet).
In listings v1.6, the valid syntax for specifying group in emph and keywords has been changed into
emph={[2]...}, emphstyle={[2]...}
keywords={[1]...}, keywordstyle={[1]...}

These can be found in the listings manual (v1.6, p22).


text:
Q: CSS inheritance broken? i have nested lists with links inside the li tags. On nesting level x I want to change the appearance of the links. Just some sample code:
CSS:
.blue a { color: blue; }
.red a { color: red; }

HTML:

blue-1

red-1

blue-2

                blue-3

                        red-2

red-3

red-4

blue-4

blue-5

red-5

red-6

red-7

In that way it is working as expected. Links with text red-* are in red. But when I change the order of the CSS classes, it is not longer working:
.red a { color: red; }
.blue a { color: blue; }

Why this behavior? Shouldn't it be the same?
I have to use more colors than red and blue, so it is impossible to give a correct order in CSS.

A: Css selector precedence is set according to how specific it is:

*

*every tag is counted as 1 point

*every class as 10 points

*event id as 100 points

Both selectors you got have the same precedence, so that one which is set further in code overrides previous ones.

A: The reason for this is that in your css you're telling every a tags that are child, grandchild, etc. elements of a class named blue. And that's getting overidden when you're telling that every a tags that are child, grandchild, etc. elements of a class named red should be red.
So instead of doing this (affecting all link tags)
.blue a { color: blue; }
.red a { color: red; }

You could do this (affects only the first child if it's a link tag):
.red > a,
.red > ul > li > a{ color: red; }
.blue > a,
.blue > ul > li > a { color: blue; }

What that second line does is it finds all elements that has a class name red. Then it finds all direct child ul elements. And under those matching elements it finds all direct child li elements that has direct child a elements. Matching these, it finally adds styles.
JSFiddle:
http://jsfiddle.net/Y9jFr/


text:
Q: Calculating the week number for a date, when your year starts on a non 1st January day I need to calculate the week number for a given date, when my year begins on the 1st of May.
My hope was to use Calendar.GetWeekOfYear(), which applies the rules I need, but by overriding the first day of year in a Calendar that derives from say, GregorianCalendar.
Unfortunately I can't find a way of doing this. Adding an arbitrary 122 / 123 days to the date in question will break the GetWeekOfYear() CalendarWeekRule.FirstFourDayWeek rule I wish to use.
Short of writing a custom and I suspect messy algorithm to determine this, is there a way of calculating the week number for a given date, when my year begins on the 1st of May?

A: Maybe you could use this approach which simply subtracts the 121 days from  January 1st to May 1st from a given DateTime and then uses Calendar.GetWeekOfYear on that date:
static readonly int DayOffset = (new DateTime(DateTime.Today.Year, 5, 1)
                               - new DateTime(DateTime.Today.Year, 1, 1)).Days; // 121

// ... somewhere else:
DateTime date = DateTime.Today;
DateTime offsetDate = date.AddDays(-DayOffset);
int weekNum = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(offsetDate, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
Console.WriteLine("Year:{0} Week:{1}", offsetDate.Year, weekNum); // Year:2016 Week:19

A: I ended up with this, which works but doesn't handle the week 53 scenario:
    private int calculateBizWeekNumber(DateTime date, DateTime yearStart, CalendarWeekRule cwr, DayOfWeek firstDoW)
    {
        var cal = DateTimeFormatInfo.CurrentInfo.Calendar;

        var dateWoY = cal.GetWeekOfYear(date, cwr, firstDoW);
        var firstWoY = cal.GetWeekOfYear(yearStart, cwr, firstDoW);

        var bizWeek = dateWoY - firstWoY + 1;

        return bizWeek <= 0 ? 52 + bizWeek : bizWeek;
    }


text:
Q: Unable to access AJAX JSON response, despite setting content type and datatype, parseJSON returns error however still 'valid' JSON I am using Laravel 4 as a backend (though I don't think it is necessarily causing an issue here), and am trying to do some AJAX validation (to preserve dynamically populated dropdowns).
First of all, the code I am using to call the AJAX request:
$('#add_character_submit').click(function(e) {
    e.preventDefault();
    $.ajax({
        url: '{{ URL::route("addcharactercheck") }}',
        type: 'POST',
        dataType: 'json',
        data: {
            'name': $('#name').val().replace('/[^a-zA-Z0-9\s\-\(\)\.\,]+/', ''),
            'gender': $('#gender').val().replace('/[^0-9]+/', ''),
            'server': $('#server').val().replace('/[^0-9]+/', ''),
            'faction': $('#faction').val().replace('/[^0-9]+/', ''),
            'race': $('#race').val().replace('/[^0-9]+/', ''),
            'class': $('#class').val().replace('/[^0-9]+/', ''),
            'path': $('#path').val().replace('/[^0-9]+/', '')
        }
    }).done(function(response) {
        console.log(response);
    }).fail(function(response) {
        console.log(response.errors);
    });
});

And then this is the response I am getting:
{"success":false,"errors":{"name":["Please pick a name"],"server":["Please pick a server"],"faction":["Please pick a faction"],"race":["Please pick a race"],"class":["Please pick a class"],"path":["Please pick a path"]}}

If I put that into a JSON validator, it says it passes.
I am returning the response as Content-Type: application/json and I have dataType: 'json' in the AJAX request as above, however trying to console.log(response.errors) results in undefined.
I have also tried using $.parseJSON on the response, however that gives an unexpected character type error (note this is just to double check).
If I type the following in the console:
var x = {"success":false,"errors":{"name":["That name is not available"],"faction":["Please pick a faction"],"race":["Please pick a race"],"class":["Please pick a class"],"path":["Please pick a path"]}}
console.log(x.errors);

Then it correctly outputs the errors in the console.
Despite searching a good dozen or so similar questions here on SO, they all seem to suggest an accepted answer of one or both of the above - I can't find anything different to try.

A: The right answer was established in the comments:
On .fail, jQuery returns a jqXHR object, instead of data. The data you're looking for is in the responseText property of this object.
.fail(function(jqXHR) {
    var json = $.parseJSON(jqXHR.responseText);
    console.log(json);
});


text:
Q: Access a list of dictionaries inside of a dictionary in Django templates I'm trying to access a list inside of my Django Html template, but I can't seem to grab the first element of the list the normal way by grabbing it via its index. In my views, I have a function edamam that calls the API endpoint and returns a JSON dictionary named ingredients.
Here's the function:
@login_required
def edamam(request):
    ingredients = {}
    if 'ingr' in request.GET:
        ingr = request.GET['ingr']
        app_key = APP_KEY
        app_id = APP_ID
        url = f'https://api.edamam.com/api/food-database/v2/parser?ingr={ingr}&app_id={app_id}&app_key={app_key}'
        response = requests.get(url)
        ingredients = response.json()
        print(f'Type: {type(ingredients)}')
        return render(request, 'todo/edamam.html', {'ingredients': ingredients})
    else:
        return render(request, 'todo/edamam.html', {'error': 'That item does not exist in the database.'})

I printed typeof(ingredients) to be certain I'm returning a dictionary and the printout does verify that in the console:
Type: <class 'dict'>

In my views edamam.html, I'm grabbing ingredients.parsed (ingredients is just a massive dictionary) because I'm trying to get the list named parsed in order to grab elements from that.

   {% if ingredients %}

{{ ingredients.parsed }}

   {% endif %} {% endblock %}

which returns:
[{'food':

    {'foodId': 'food_bnxr4n3b1ld7i6ace2hkqbwm89du', 'label': 'cheeseburger', 'nutrients': {'ENERC_KCAL': 263.0, 'PROCNT': 12.97, 'FAT': 11.79, 'CHOCDF': 27.81, 'FIBTG': 1.1}
    , 'category': 'Generic foods', 'categoryLabel': 'food'}

}]

My question is, how do I get to the 'food' dictionary inside of list? I tried ingredients.parsed.food (nothing returns) and also tried ingredients.parsed['food'] and get a template syntax error
Could not parse the remainder: '['food']' from 'ingredients.parsed['food']' and lastly ingredients.parsed[0] since it is the first element in the parsed list, but I get another template syntax error Could not parse the remainder: '[0]' from 'ingredients.parsed[0]'. So ultimately I'm just trying to grab the nutrients dictionary items inside of the food dictionary which seems to be the first element of the parsed dictionary. I'm just not certain how to get to food yet.

A: This should work,
ingredients.parsed.0

try it!


text:
Q: I have forced my IP address to go to a different page with htaccess I have made a code in the htaccess below:
# TO MAKE A DIFFERENT PAGE FOR A SPECIFIED IP-ADRES
    RewriteEngine On
    #DENY THIS SPECIFIED IP-ADRES OR REDIRECT IT TO ANOTHER PAGE (=something like iframe)
        #RewriteCond %{REMOTE_ADDR} !^1\.2\.3\.4$
        #RewriteRule index\.html$ index2\.html [L]

Let's just say my IP address is 1.2.3.4. How can I delete this code and that I go back to the normal index.html instead of being redirect to index2.html?


text:
Q: How to actually "present a template chooser before calling the importHandler"? The sample code for UIDocumentBrowserViewController has a comment in documentBrowser:didRequestDocumentCreationWithHandler: that says Optionally, you can present a template chooser before calling the importHandler.
But how? If I instantiate a view and its controller to use for selecting a template, and call presentViewController:animated:completion: on it, the code doesn't wait for the presented view to be dismissed, but continues happily on. So how can I wait for the the user to select a template in the presented view?

A: I figured it out. The trick was to realize that there is no need to call the importHandler block already in the documentBrowser:didRequestDocumentCreationWithHandler method. You can store the block in an instance variable of the object you use to select a template (in my case, an instance of a class derived from UICollectionViewController), present that dialog, return, and then call the stored importHandler block much later in the suitable method of that template selection class, in my case the collectionView:shouldSelectItemAtIndexPath.
See code here


text:
Q: Proving a relation on Z×(Z-{0}) is an equivalence relation Question:Let $X=\mathbb{Z}\times(\mathbb{Z}\setminus\{0\})$. Define a relation $\sim$ on $X$ by declaring that $(a, b)\sim(c, d)$ if and only if $ad = bc$
Prove that the relation $\sim$ is an equivalence relation.
My attempt
$ab = ba \Leftrightarrow (a, b) \sim (a, b)$. When I focus on left side of the biconditional, the relation $\sim$ is symmetric, but when I see the right side, the relation is reflexive. I can't clearly say the relation.
$ab= ab \Leftrightarrow (a, a) \sim (b, b)$. I don't know how to define this relation when I look at the right side. But when I look at the left side, it's reflexive relation.
For a transitive relation, I'm not clearly sure if I have to write "$ab=bd=cd$".  But what should follow after "$ab=bd=cd$"?
Can you complete the proof?
[Edit] Now I know how to prove it.
(i) $ab = ba \Leftrightarrow (a, b) \sim (a, b)$
Therefore,~ is reflexive
(ii) $[ad = bc \Leftrightarrow (a, b) \sim (c, d)]$
$\implies$ [cb=da $\Leftrightarrow$ (c, d) $\sim$ (a, d)]
Therefore, ~ is symmetric
(iii) $[ad = bc \Leftrightarrow (a, b) \sim (c, d)]$
$\land$ [cf=de $\Leftrightarrow$ (c, d) $\sim$ (e, f)]
$\implies$ [ $\dfrac {ad} {de}$= $\dfrac {bc}{cf}$ $\Leftrightarrow$ af=be $\Leftrightarrow$ (a, b) $\sim$ (e, f)]
Therefore ~ is transitive
By (i), (ii), (iii), the relation ~ is an equivalence relation.
[FYI]
A relation $R$ from $A$ to $B$ is a subset of the Cartesian product $A\times B$. It is customary to write $aRb$ for $(a, b)\in R$. The symbol $aRb$ is read "$a$ is $R$-related to $b$.
$A$ relation on a set $A$ is a relation from $A$ to $A$.
$R$ is reflexive if and only if $\forall x\in X, xRx$
$R$ is symmetric if and only if $xRy\Rightarrow yRx$
$R$ is transitive if and only if $xRy\land yRz\Rightarrow xRz$.
$R$ is an equivalence relation if and only if R is reflexive, symmetric, and transitive.

A: Since multiplication is commutative in $\Bbb Z,$ then $ab=ba.$ Hence, as you noted, the relation is reflexive.
To prove symmetry, start by supposing that $(a,b)\sim(c,d),$ meaning that $a,b,c,d$ are integers with $b,d\ne0,$ and $ad=bc.$ You must then prove that $(c,d)\sim(a,b),$ which you will do by showing that $cb=da.$
To prove transitivity, start by assuming that $(a,b)\sim(c,d)$ and $(c,d)\sim(x,y).$ This means that $a,b,c,d,x,y$ are integers with $b,d,y\neq0,$ such that $ad=bc$ and $cy=dx.$ You must use these assumptions to prove that $(a,b)\sim(x,y),$ which you will do by proving that $ay=bx.$
Added: As a side note, your second paragraph--the one about $(a,a)\sim(b,b)$--isn't in any way pertinent to the proof.

A: (You don't need biconditionals for these)
Reflexive: Take any $(a,b)$ in the set. Then clearly $(a,b)\sim(a,b)$ since $ab=ba$.
Symmetric: Take another $(c,d)$ in the set. We want to show that $(a,b)\sim(c,d)\implies(c,d)\sim(a,b)$. The left side means that $ad=bc$. This means of course that $cb=da$, so the right side is also true.
Transitive. Take another $(e,f)$ in the set. Suppose that $(a,b)\sim(c,d)$ AND $(c,d)\sim(e,f)$. We have $ad=bc$ and $cf=ed$. Then we have $adf=bcf=bed$, so $af=be$. This means that $(a,b)\sim(e,f)$.
Note that, in the last step, we must divide by $d$, so $d$ can't be zero. This is why we can't define the same equivalence relation on $\Bbb{Z}\times\Bbb{Z}$.

A: It seems like you are on the right track, but let me write the proofs as I would have done it to clear up any confusion.
I want to prove that the relation is reflexive, so take $(a,b)\in X$. We need to show that $(a,b)\sim (a,b)$. By definition of $\sim$, this is equivalent to $ab = ba$, which is true, because the order of multiplication doesn't matter.
To show that it is symmetric, suppose that $(a,b)\sim (c,d)$. We have to prove that then also $(c,d)\sim (a,b)$. By definition, our hypothesis is equivalent to $ad = bc$. I can rewrite this as $cb = da$, which is equivalent to $(c,d)\sim (a,b)$, which proves that the relation is symmetric.
As for transitivity, take $(a,b),(c,d),(e,f)\in X$, such that $(a,b)\sim (c,d)$ and $(c,d)\sim (e,f)$. We need to show that $(a,b)\sim (e,f)$. By our hypothesis, we have that $ad = bc$ and $cf = de$. We are trying to prove that $af = be$. Take $ad = bc$ and multiply it by $f$ (which is non-zero), and take $cf = de$ and multiply it by $b$ (which is non-zero). This gives you
$$adf = bcf,$$
and
$$bcf = bde.$$
Combining these two equations, we see that
$$adf = bde,$$
which you can divide by $d$ (which is non-zero) to obtain $af = be$, which is what we set out to prove. The relation is thus transitive.
As a side note, what relation does this resemble? You have $X=\mathbb{Z}\times(\mathbb{Z}\setminus\{0\})$, and $(a,b)\sim (c,d)$, iff $ad = bc$. This is very similar to equality of fractions, i.e. $\frac{a}{b} = \frac{c}{d}$, iff $ad = bc$.

A: $(a,b)\sim(c,d) : ad=bc$
then
$(a,b)\sim(a,b) : ab=ba$
$(a,b)\sim(c,d) : ad=bc$, since$ad=da,bc=cb$, then $bc = ad :(c,d)\sim(a,b)$
$(a,b)\sim(c,d) , (c,d)~(e,f): ad=bc, cf=de$ then since $b,d,f \neq 0$ we have $adf=bcf=bde$, since $ab=ba$, we have $daf=dbe$. Again, since $d \neq 0$, we have $af=be$ which means $(a,b)\sim(e,f)$. Thus, it is an equivalence relation.

A: 1.) $(a,b) ∼ (a,b)$ since $ab = ba$
2.) $(a,b) ∼ (c,d) \Rightarrow ad = bc \Rightarrow cb = da \Rightarrow (c,d) ∼ (a,b)$
3.)$(a,b) ∼ (c,d)$ and $(c,d) ∼ (x,y) \Rightarrow ad = bc,cy =dx \Rightarrow adcy = bcdx \Rightarrow ay = bx \Rightarrow (a,b) ∼ (x,y) $


text:
Q: How do you do a System State Restore on a Windows 2016 server located in a datacenter where you only have RDP and serial console access? I am attempting to do a system state restore on a Windows Server 2016 box, however the server is in a data center (1&1) and I only have RDP and serial console access to it.  I have the WindowsBackupImage folder on my d drive which should not be involved in the system changes as they are all on C.  I have hit two major snags.
The first is that I am having trouble getting Microsoft Backup to accept the path to the image.  Some reading online seems to indicate it should be possible to run from the D drive, but I can't figure out the proper way to do so.
The second issue is that some accounts seem to indicate that there may be sections of the process that require interaction where I'm unsure if the serial console or RDP will be available and I'm not sure if there is a way to make them run unattended.

A: It turns out that if you move the WindowsBackupImage folder to the root of the non-system drive (in my case d:\WindowsBackupImage), it will detect just fine in Windows Backup and allow you to do a restore of it.  Unfortunately, in my case, something went horribly wrong and after an initial reboot that worked and had services running, my next reboot after bluescreened with a system corruption error and required wiping my system and starting the restore over again from scratch.


text:
Q: Checking in code without deploying on Heroku I've been successfully running an app on Heroku, but now would like to work with a collaborator on it.  Is there a way with can check in (and pull) code without deploying it live?  Right now a git push deploys to code the live site.

A: Create a new branch and use that.
git checkout -b BRANCH_NAME
git push heroku BRANCH_NAME

A: One of the advantages of git is that it is distributed and decentralized. You can have multiple remote repositories configured.
I suggest you use github for collaboration with others. This allows you to determine what changes you actually push to heroku.
Set up a github repository and push the project. Then grant your collaborators access to the github repository. Change your workflow to use github as the primary repository and only push to heroku those changes that are production ready.

A: You can also have a look at a service like GitHub* for actual git hosting. As git is entirely distributed, you can have multiple repositories. Use one for remote storage/project coordination and Heroku just for deployment.

*

*I use GitHub for my open source stuff and a commercial Unfuddle account for projects (Unfuddle gives you unlimited git repos and issue tracking).


text:
Q: asp.net pass value from javascript to control on a modal popup Ok, I changed the title because I can't get anywhere with previous approach, so I'm returning to the original question: how can I pass a variable obtained through javascript to a textbox on a modal popup?
I already tried to place a hidden field and even a textbox on the parent page, inside or outside an update panel, but when I click on the linkbutton that opens the modal popup their values are resetted to default.
I already searched and tried many different ways but I can't succeed.
I have a table in a repeater and I need to know the cells selected by the user: start and ending cell of the selection. I accomplish that with this javascript:
$(function () {
            var mouse_down = false;
            var row, col;    // starting row and column
            var $tr;

            $("#tblPersonale td")
                .mousedown(function () {
                    $("#col_to").html('?');
                    mouse_down = true;

                    // clear last selection for a fresh start
                    $(".highlighted").removeClass("highlighted");
                    $(this).addClass("highlighted");

                    $tr = $(this).parent();
                    row = $tr.parent().find("tr").index($(this).parent());
                    col = $tr.find("td").index($(this));

                    $("#row").html(row);
                    $("#col_fr").html(col - 1);

                    return false; // prevent text selection
                })

                .mouseover(function () {
                    if (mouse_down) {
                        $("#col_to").html('?');
                        if ($tr[0] === $(this).parent()[0]) {
                            var col2 = $(this).parent().find("td").index($(this)); // current column
                            var col1 = col;
                            if (col > col2) { col1 = col2; col2 = col; }

                            $("#col_fr").html(col1-1);
                            $("#col_to").html(col2 - 1);

                            // clear all selection to avoid extra cells selected
                            $(".highlighted").removeClass("highlighted");

                            // then select cells from col to col2
                            for (var i = col1; i <= col2; i++) {
                                if (col1>1){
                                    $tr[0].cells[i].className = "highlighted";}
                            }
                        }

                    }
                })
                .bind("selectstart", function () {
                    return false; // prevent text selction in IE
                })

            $(document)
                .mouseup(function () {
                    mouse_down = false;
                });
        });

So, when user selects one or more cells I have the start/end value in here:
?
?

Then, when user click a linkbutton I want to use these values to write a text in a textbox on the modal popup that shows. As I said, I can't make it work, anything I tried the result is that the values are lost when popup shows, even if I assign values to global variables before showing the popup.
This is my linkbutton:
<asp:LinkButton runat="server" ID="lnkAddDip"  OnClick="lnkAddDip_Click">

The idea behind the old question was to pass the values to the url as parameters and then in the page load use them, but then the table selection doesn't work anymore because at every selection the page refresh because of the url change.
Please anyone, I'm totally lost and not for lack of trying!
OLD QUESTION
asp.net pass a control value as parameter in onclientclick
I found similar questions but no one answer to my problem (or at least, I can't make anything working).
I want to concatenate to the url of the active page some parameters like Home.aspx?col_fr=2 where instead of the fixed "2" I want to pass the value of a hidden field. How can I achive that?
This is my current code:
<asp:hiddenfield runat="server" id="hdnColonnaDa" EnableViewState="true"  />
<asp:LinkButton runat="server" ID="lnkAddDip"  OnClick="lnkAddDip_Click" OnClientClick="window.location='Home.aspx?col_fr=2';return false;">

Thanks

A: It just have to move the parameter code o a javascript function like
function getURL(){
   var param1 = someField.value/*get field value*/;
   var url= "Home.aspx?col_fr="+ param1;
   window.location= url;
  return false;
}

Html
<asp:LinkButton runat="server" ID="lnkAddDip"  OnClick="lnkAddDip_Click" OnClientClick="getURL()">

A: Don't use UpdatePanel or Modal popup server side. You can use a Thickbox or similar jquery plugin to open the popoup.
Popup can be an inpage div or another page. In case of page, you can easily pass parameters in the url, in case of inpage div, you can get hidden field values.
You can find jquery overlay as Thickbox: just add css and js to your site, the right class on the link and fix the url to open.
Solution using another page
Imagine to use Colorbox (http://www.jacklmoore.com/colorbox/):
PRE
Suppose you have your variable values in some hidden field in your page
TODO

*

*include jquery in your page

*Download and include css and js for colorbox

*In your page add a html tag with on click event

*Add a script section in your page
function openLink()
{
    var hiddenValue= $("#col_fr").text(); // or .html()
    var urlToOpen = "yourpage.aspx?ids=" + hiddenValue;
    $.colorbox({
            iframe: true,
            width: "75%",
            height: "75%",
            href: urlToOpen
   });
}

Then in Yourpage.aspx you can use url parameter "ids".
Code is not tested!

A: Finally I did what I want by tuning the original javascript function.
I added 3 hiddenfield on the page and then I add this bit
var hdncol_fr = document.getElementById("hdncol_fr").value;
var hdncol_to = document.getElementById("hdncol_to").value;
var hdnrow = document.getElementById("hdnrow").value;
if (hdncol_fr = '?'){
   document.getElementById("hdncol_fr").value = col - 1;
   document.getElementById("hdncol_to").value = col2 - 1;
   document.getElementById("hdnrow").value = row;
}

This way the hidden fields values are set only when user actively select some cells, when there is a postback event the javascript function returns '?' for the 3 values, so with the added code the hidden field maintains the previous values until user select something else.


text:
Q: SerialVersionUID JavaDoc? When adding documentation to my Java program, I realize that most classes require a serialVersionUID constant property to be declared. How exactly should I document this property? And do I document it differently if I used a default vs. generated serial version UID?
/**
 * What goes here? "A unique serial version identifier"
 */
private static final long serialVersionUID = -8922096951749901688L;

A: First of all, the serialVersionUID comment you provided seems right but unnecessary.
The serialVersionUID is required as part of a  Serializable object (not all java classes) and is used during the serialization / deserialization of this objects.
As a general rule. ALWAYS CHECK THE API
in this case, Serializable API, at the bottom!!

The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named "serialVersionUID" that must be static, final, and of type long:
ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;

So you're saying that it should actually not be documented whatsoever because there is javadoc for it already? When I omit the javadoc and mouseover it, it does not show anything :/

It's part of Serializable interface, so IMHO is not necessary... anyway, you can use your own comment + @see annotation. Something like this (not sure if will work, cannot create javadoc now...)
/**
 * A unique serial version identifier
 * @see Serializable#serialVersionUID
 */


text:
Q: C#: How do I create an instance with a generic while it has been declared as object I am facing a problem where I want to create an instance of a SomeClass<T> where T is giving by the method, but SomeClass<T> is added to a dictionary that is declared like ConcurrentDictionary<OtherClass, SomeClass<object>>. What I want to do does not compile because Type 'T' doesn't match expected type object
private readonly SemaphoreSlim semaphoreSlim;
private readonly ConcurrentDictionary<StatisticType, StatisticsList<object>> statisticsDictionary;

public StatisticsDictionary()
{
    semaphoreSlim = new SemaphoreSlim(1);
    statisticsDictionary = new ConcurrentDictionary<StatisticType, StatisticsList<object>>();
}

(...)

public bool TryAdd<T>(StatisticType key, DateTime dateTime, T value)
{
    if (!statisticsDictionary.ContainsKey(key))
    {
        semaphoreSlim.Wait();
        statisticsDictionary.TryAdd(key, new StatisticsList<T>());
        semaphoreSlim.Release();
    }

    if (!statisticsDictionary.TryGetValue(key, out var statistics))
        return false;

    statistics.Add(dateTime, value);
    return true;
}

The concurrentDictionary is wrapped in a class that needs to support different types of 'T' (like long, DateTime, TimeSpan and possibly other types)
I've tried to just initialize SomeClass<T> as SomeClass<object> so that it matches the declaration. And then on retrieval cast object to T that is given by the method. But this leads to casting exceptions because it seems to be impossible to (explicitly) cast an object to, for example, long even when the object is in fact a long during run time.
public bool TryGetFrom<T>(StatisticType key, DateTime from, out IEnumerable<(DateTime, T)> value)
{
    if (statisticsDictionary.TryGetValue(key, out var statistics))
    {
        var list = statistics.TryGetFrom(from);
        value = (IEnumerable<(DateTime, T)>) list;

        return value != null;
    }

    value = null;
    return false;
}

Is it even possible what I try to accomplish?

Edit Source code of StatisticsList as requested in the comments
public class StatisticsList<T>
{
    private readonly SemaphoreSlim semaphoreSlim;
    private readonly SortedList<DateTime, (DateTime, T)> sortedList;
    public DateTime StartedAt { get; }
    public int Count => sortedList.Count;

    public StatisticsList()
    {
        try
        {
            semaphoreSlim.Wait();
            sortedList.Add(key, (key, value));
        }
        finally
        {
            semaphoreSlim.Release();
        }
    }

    public void Add(DateTime key, T value)
    {
        semaphoreSlim.Wait();
        sortedList.Add(key, (key, value));
        semaphoreSlim.Release();
    }

    public bool TryGetFrom(DateTime from, out IEnumerable<(DateTime, T)> value)
    {
        try
        {
            semaphoreSlim.Wait();
            value = sortedList.Where(s => s.Key > from).Select(s => s.Value).ToList();
            return true;
        }
        catch (ArgumentNullException) { }
        finally
        {
            semaphoreSlim.Release();
        }

        value = null;
        return false;
    }

    public bool TryGetLast(out (DateTime, T) value)
    {
        try
        {
            semaphoreSlim.Wait();
            var dateTime = sortedList.Max(s => s.Key);
            return sortedList.TryGetValue(dateTime, out value);
        }
        catch (ArgumentNullException)
        {
            value = (default, default);
        }
        finally
        {
            semaphoreSlim.Release();
        }

        return false;
    }

    public IEnumerable<(DateTime, T)> ToList()
    {
        try
        {
            semaphoreSlim.Wait();
            return sortedList.Values.ToList();
        }
        finally
        {
            semaphoreSlim.Release();
        }
    }
}

A: Generics are effective when you know the type during design-time. In your case, your collection can store items of any different types.
You can utilize a pretty popular trick of declaring non-generic and inherited generic version of a collection item.
As a side effect, you can get rid of a not-very-readable value tuple :)
Declare item class like this:
public abstract class StatisticsListItem
{
    public DateTime Time { get; protected set; }
}

public class StatisticsListItem<T> : StatisticsListItem
{
    public StatisticsListItem(DateTime time, T value)
    {
        Time = time;
        Value = value;
    }

    public T Value { get; }
}

And then you can store them as StatisticsListItem and perform operations depending on their specific sub-type. It is also type-safe, because you cannot access the value of a generic list item, like in case if you declare it as non-generic StatisticsListItem with object Value { get; } property.
The simplest usage scenario can look like this:
public class StatisticsList
{
    public List<StatisticsListItem> Values { get; set; } = new List<StatisticsListItem>();

    public void TryAdd<T>(DateTime dateTime, T value)
    {
        // Adding an item of generic type to non-generic list:
        Values.Add(new StatisticsListItem<T>(dateTime, value));
    }

    public IEnumerable<StatisticsListItem<T>> TryGetFrom<T>(DateTime dateTime)
    {
        // Dynamically filtering only items of specific generic type
        return Values
            .OfType<StatisticsListItem<T>>() // computationally ineffective, subject to improvement ;)
            .Where(t => t.Time >= dateTime); // same, just an example
    }
}

It is just an example. You still need to implement it in a way it supports keys, fits into your dictionary and makes filtering of items by type much more effective. Good luck!
Some minor comments: you still might have some problems with handling multi-threading, but this is out of the scope of this question :)


text:
Q: Create a validation for a managed lightning button on Salesforce Opportunity 0
Hi I am struggling to build this in SF.
I have tried to create a validation for a managed lightning button (I cannot edit its functionality), on the opportunity level.
The scenario is:
If the user should click the button, while a specific text field on the opportunity level is empty, it should not allow the button to work.
I read here that I need to create a VF page, and an Apex class controller, but didn't really succeed doing this.
I tried building the controller as following:
public class ButtonValidationController {
if(String.isBlank(Opportunity.Billing_Street__c))
}
Can you give an actual example of the syntax I need to build?
Thank you.


text:
Q: How to get actual MIME type of file loaded with html  I am trying to determine the actual MIME type of a file loaded in a web page using <input type="file" accept="image/* onchange="handler()"/>
I want to support the user browsing for any image file, but I need to know the actual MIME type for uploading it to a REST API.
I suppose I could load a file extension mapping table and have a Javascript function to determine the MIME type from the file's file extension.  I was just hoping maybe the browser already knows that, and it is somehow available in the DOM.

A: function getMimeType(file) {
  const reader = new FileReader();
  reader.onloadend = function() {
    const arr = (new Uint8Array(reader.result)).subarray(0, 4);
    let header = "";
    for(let i = 0; i < arr.length; i++) {
      header += arr[i].toString(16);
    }
    switch (header) {
      case "89504e47":
        return "image/png";
      case "47494638":
        return "image/gif";
      case "25504446":
        return "application/pdf";
      case "ffd8ffe0":
      case "ffd8ffe1":
      case "ffd8ffe2":
        return "image/jpeg";
      default:
        return "unknown";
    }
  };
  reader.readAsArrayBuffer(file);
}

This function takes a file object as an argument and returns the actual MIME type of the file. It uses a FileReader object to read the content of the file and then checks the first few bytes of the file to determine its actual MIME type. Different file formats have different "magic numbers" at the beginning of the file, which can be used to identify the file format.
In the example code, we have included some common file formats and their corresponding magic numbers. You can add more formats and magic numbers to this function as needed.


text:
Q: Is it better to use System.arraycopy(...) than a for loop for copying arrays? I want to create a new array of objects putting together two smaller arrays.
They can't be null, but size may be 0.
I can't chose between these two ways: are they equivalent or is one more efficient (for example system.arraycopy() copies whole chunks)?
MyObject[] things = new MyObject[publicThings.length+privateThings.length];
System.arraycopy(publicThings, 0, things, 0, publicThings.length);
System.arraycopy(privateThings, 0, things,  publicThings.length, privateThings.length);

or
MyObject[] things = new MyObject[publicThings.length+privateThings.length];
for (int i = 0; i < things.length; i++) {
    if (i<publicThings.length){
        things[i] = publicThings[i]
    } else {
        things[i] = privateThings[i-publicThings.length]
    }
}

Is the only difference the look of the code?
EDIT: thanks for linked question, but they seem to have an unsolved discussion:
Is it truly faster if it is not for native types: byte[], Object[], char[]? in all other cases, a type check is executed, which would be my case and so would be equivalent... no?
On another linked question, they say that the size matters a lot, for size >24 system.arraycopy() wins, for smaller than 10, manual for loop is better...
Now I'm really confused.

A: public void testHardCopyBytes()
{
    byte[] bytes = new byte[0x5000000]; /*~83mb buffer*/
    byte[] out = new byte[bytes.length];
    for(int i = 0; i < out.length; i++)
    {
        out[i] = bytes[i];
    }
}

public void testArrayCopyBytes()
{
    byte[] bytes = new byte[0x5000000]; /*~83mb buffer*/
    byte[] out = new byte[bytes.length];
    System.arraycopy(bytes, 0, out, 0, out.length);
}

I know JUnit tests aren't really the best for benchmarking, but
testHardCopyBytes took 0.157s to complete
and
testArrayCopyBytes took 0.086s to complete.

I think it depends on the virtual machine, but it looks as if it copies blocks of memory instead of copying single array elements. This would absolutely increase performance.

EDIT:
It looks like System.arraycopy 's performance is all over the place.
When Strings are used instead of bytes, and arrays are small (size 10),
I get these results:
    String HC:  60306 ns
    String AC:  4812 ns
    byte HC:    4490 ns
    byte AC:    9945 ns

Here is what it looks like when arrays are at size 0x1000000. It looks like System.arraycopy definitely wins with larger arrays.
    Strs HC:  51730575 ns
    Strs AC:  24033154 ns
    Bytes HC: 28521827 ns
    Bytes AC: 5264961 ns

How peculiar!
Thanks, Daren, for pointing out that references copy differently. It made this a much more interesting problem!

A: It is not possible that Arrays.copyOf is faster than System.arraycopy since this is the implementation of copyOf:
public static int[] copyOf(int[] original, int newLength) {
    int[] copy = new int[newLength];
    System.arraycopy(original, 0, copy, 0,
                     Math.min(original.length, newLength));
    return copy;
}

A: Executing native methods like Arrays.copyOf(T[], int) does have some overhead  but it doesnot mean that it is not fast as you are executing it using JNI.
The easiest way is to write a benchmark and test.
You can check that Arrays.copyOf(T[], int) is faster than your normal for loop.
The benchmark code from here:-
public void test(int copySize, int copyCount, int testRep) {
    System.out.println("Copy size = " + copySize);
    System.out.println("Copy count = " + copyCount);
    System.out.println();
    for (int i = testRep; i > 0; --i) {
        copy(copySize, copyCount);
        loop(copySize, copyCount);
    }
    System.out.println();
}

public void copy(int copySize, int copyCount) {
    int[] src = newSrc(copySize + 1);
    int[] dst = new int[copySize + 1];
    long begin = System.nanoTime();
    for (int count = copyCount; count > 0; --count) {
        System.arraycopy(src, 1, dst, 0, copySize);
        dst[copySize] = src[copySize] + 1;
        System.arraycopy(dst, 0, src, 0, copySize);
        src[copySize] = dst[copySize];
    }
    long end = System.nanoTime();
    System.out.println("Arraycopy: " + (end - begin) / 1e9 + " s");
}

public void loop(int copySize, int copyCount) {
    int[] src = newSrc(copySize + 1);
    int[] dst = new int[copySize + 1];
    long begin = System.nanoTime();
    for (int count = copyCount; count > 0; --count) {
        for (int i = copySize - 1; i >= 0; --i) {
            dst[i] = src[i + 1];
        }
        dst[copySize] = src[copySize] + 1;
        for (int i = copySize - 1; i >= 0; --i) {
            src[i] = dst[i];
        }
        src[copySize] = dst[copySize];
    }
    long end = System.nanoTime();
    System.out.println("Man. loop: " + (end - begin) / 1e9 + " s");
}

public int[] newSrc(int arraySize) {
    int[] src = new int[arraySize];
    for (int i = arraySize - 1; i >= 0; --i) {
        src[i] = i;
    }
    return src;
}

System.arraycopy() uses JNI (Java Native Interface) to copy an array (or parts of it), so it is blazingly fast, as you can confirm  here

A: System.arraycopy() is a native call which does copy operation directly at memory. Single memory copy would be always faster than your for loop

A: Arrays.copyOf(T[], int) is easier to read.
Internaly it uses System.arraycopy() which is a native call.
You can't get it faster!

A: It depends on the virtual machine, but System.arraycopy should give you the closest you can get to native performance.
I've worked for 2 years as a java developer for embedded systems (where performance is a huge priority) and everywhere System.arraycopy could be used, I've mostly used it / seen it used in existing code. It's always preferred over loops when performance is an issue.
If performance isn't a big issue, I'd go with the loop, though. Much easier to read.

A: Instead of relying on speculation and possibly outdated information, I ran some benchmarks using caliper.  In fact, Caliper comes with some examples, including a CopyArrayBenchmark that measures exactly this question!  All you have to do is run
mvn exec:java -Dexec.mainClass=com.google.caliper.runner.CaliperMain -Dexec.args=examples.CopyArrayBenchmark

My results are based on Oracle's Java HotSpot(TM) 64-Bit Server VM, 1.8.0_31-b13, running on a mid-2010 MacBook Pro (macOS 10.11.6 with an Intel Arrandale i7, 8 GiB RAM).  I don't believe that it's useful to post the raw timing data.  Rather, I'll summarize the conclusions with the supporting visualizations.
In summary:

*

*Writing a manual for loop to copy each element into a newly instantiated array is never advantageous, whether for short arrays or long arrays.

*Arrays.copyOf(array, array.length) and array.clone() are both consistently fast.  These two techniques are nearly identical in performance; which one you choose is a matter of taste.

*System.arraycopy(src, 0, dest, 0, src.length) is almost as fast as Arrays.copyOf(array, array.length) and array.clone(), but not quite consistently so.  (See the case for 50000 ints.)  Because of that, and the verbosity of the call, I would recommend System.arraycopy() if you need fine control over which elements get copied where.

Here are the timing plots:


text:
Q: Is there any way to dynamically allocate constant memory? CUDA I'm confused about copying arrays to constant memory.
According to programming guide there's at least one way to allocate constant memory and use it in order to store an array of values. And this is called static memory allocation:
__constant__ float constData[256];
float data[256];
cudaMemcpyToSymbol(constData, data, sizeof(data));
cudaMemcpyFromSymbol(data, constData, sizeof(data));

According to programming guide again we can use:
__device__ float* devPointer;
float* ptr;
cudaMalloc(&ptr, 256 * sizeof(float));
cudaMemcpyToSymbol(devPointer, &ptr, sizeof(ptr));

It looks like dynamic constant memory allocation is used, but I'm not sure about it. And also no qualifier __constant__ is used here.
So here are some questions:

*

*Is this pointer stored in constant memory?

*Is assigned (by this pointer) memory stored in constant memory too?

*Is this pointer constant? And it's not allowed to change that pointer using device or host function. But is changing values of array prohibited or not? If changing values of array is allowed, then does it mean that constant memory is not used to store this values?

A: The developer can declare up to 64K of constant memory at file scope. In SM 1.0, the constant memory used by the toolchain (e.g. to hold compile-time constants) was separate and distinct from the constant memory available to developers, and I don't think this has changed since.  The driver dynamically manages switching between different views of constant memory as it launches kernels that reside in different compilation units.  Although you cannot allocate constant memory dynamically, this pattern suffices because the 64K limit is not system-wide, it only applies to compilation units.
Use the first pattern cited in your question: statically declare the constant data and update it with cudaMemcpyToSymbol before launching kernels that reference it.  In the second pattern, only reads of the pointer itself will go through constant memory.  Reads using the pointer will be serviced by the normal L1/L2 cache hierarchy.


text:
Q: How can I fix my custom keyboard to work properly? Every time I press the check button the keyboard understands that i've pressed it!
It makes no sense to give a user the wrong answer if s/he hasn't even typed anything in to the text field
So how can i block my check button to not recognise it if its the first thing pressed by the user....?
- (IBAction)btncheck:(id)sender {

NSString *answer = [_textbox.text stringByReplacingOccurrencesOfString:@" " withString:@""];

if ([answer isEqualToString:@"q"]) {
    // String is correct, resign keyboard
    _keyboard.hidden = YES;
    _textXclear.hidden = YES;
    //Perfect button
    [_closeone setHidden:NO];
    [_wrongone setHidden:YES];

}
else {
    // Was not correct.  Notify user, or just don't do anything
    [_wrongone setHidden:NO];

    // animation that shakes the image (qimage)

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.03];
    [UIView setAnimationDelay:0.15];
    [UIView setAnimationRepeatCount:0];
    [UIView setAnimationRepeatAutoreverses:YES]

    qimage.transform = CGAffineTransformMake(1.08, 0, 0, 1, 0, 1.);
    qimage.transform = CGAffineTransformMakeTranslation(0,0);

}

And finally the else veritable is a animation that needs fixing, so what is the right way to animate a UIImage to buzz/vibrate/earthquake effect or shake from left to right when the user gets a wrong answer?

A: Why don't you check for an empty string first?
 if([answer isEqualToString:@""]) {
    //do nothing
} else {
    //do your stuff
    if ([answer isEqualToString:@"q"]) {
        // String is correct, resign keyboard
        _keyboard.hidden = YES;
        _textXclear.hidden = YES;
        //Perfect button
        [_closeone setHidden:NO];
        [_wrongone setHidden:YES];

    }
    else {
        // Was not correct.  Notify user, or just don't do anything
        [_wrongone setHidden:NO];

        // animation that shakes the image (qimage)

        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.03];
        [UIView setAnimationDelay:0.15];
        [UIView setAnimationRepeatCount:0];
        [UIView setAnimationRepeatAutoreverses:YES]

        qimage.transform = CGAffineTransformMake(1.08, 0, 0, 1, 0, 1.);
        qimage.transform = CGAffineTransformMakeTranslation(0,0);

    }
}


text:
Q: "I look for a place where I be free" — subjunctive or just bad English? I'd like to know whether the phrase "where I be" is grammatically incorrect or whether it is correct if in the subjunctive mood. If it is in the subjunctive mood, what exactly would it mean?
The entire example sentence is:

I look for a place where I be free.

A: "Where I be" can be used in conjunction with an auxiliary verb. I would suggest never using the phrase on its lonesome as "be" should be replaced with "am." Instead, inserting "would," "should," or "could" into the phrase can be used in a wide variety of situations.

Hawaii is where I would/should/could be right now.

"Would" expresses a wish or a desire. "Should" expresses a sense of longing. Finally, "could" expresses a sense of possibility.


text:
Q: Real time multi user interaction The program I am making requires the use of real time cross computer interactions via the internet.
The issue I'm coming across is that while I wish for the clients to connect to a host client rather then going for a client server model there are a lot of problems in terms of getting the host client able to actually host (accept an incoming connection, etc.)
I'm trying to make the process of hosting a session as simple as possible, so that a user with no networking knowledge can accept incoming connections without having to configure their router or any other such thing. I was wondering how I could achieve this?

A: Sounds like you want to programatically update firewall rules, given the variation in network set ups, it's not possible to have a one size fits all approach. I think you have three choices, the last probably being the better:
1) http://en.wikipedia.org/wiki/Internet_Gateway_Device_Protocol
2) http://en.wikipedia.org/wiki/Tunneling_protocol
3) instructions for users to configure their routers (will be needed as a back-up for users who the first two fail for)


text:
Q: Programmatically switch to navigation view on TableViewCell click in Swift I was able to create an iOS application in which you could switch between views with buttons. These views had a navigation controller so you could go back.
However I want to adapt this slightly.
Instead I want to have a single view start with no navigation controller.
Then when a cell in my table view is clicked, I want to navigate to the next view which has a navigation controller.
I can make this happen using segue in the interface builder but I don't want to manage it through the builder. This is because I only want to go to the next view when I have done some checking on the cell clicked in the table view.
So basically I need to programmatically change views.
Here is what I have done so far:

*

*I have an ordinary View Controller.

*I then have next to it a Navigation Controller which is linked to a new View Controller after that.

*I gave this View a storyboard ID of presetController.

I then have the below code in my table cell onclick function:
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

let nextViewController = storyBoard.instantiateViewController(withIdentifier: "presetController") as! PresetNavigationController
        self.present(nextViewController, animated:true, completion:nil)

Now this code takes me to the next view, but no navigation controller is loaded.
How can I make the navigation controller link to this view? It already is embedded to it via the editor tab link.
Photo to explain story board:
StoryBoard

A: If your link Navigation controller from New controller and Your are opening presntview controller than you will be make as this
  let nextViewController = storyBoard.instantiateViewController(withIdentifier: "presetController") as! PresetNavigationController

  let navController = UINavigationController(rootViewController: nextViewController)

  self.present(navController, animated:true, completion: nil)

A: You need to swap View Controller with Navigation Controller and then do this code:
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

let nextViewController = storyBoard.instantiateViewController(withIdentifier: "presetController") as! PresetNavigationController
        self.present(nextViewController, animated:true, completion:nil)

this will make your navigationbar back button appear

A: Using the suggestions from ppinho I put the navigation controller as the entry point.
As I did not want the navigation controller on the first view I hid it with the below code:
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    // Hide the navigation bar on the this view controller
    self.navigationController?.setNavigationBarHidden(true, animated: animated)
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    // Show the navigation bar on other view controllers
    self.navigationController?.setNavigationBarHidden(false, animated: animated)
}

I then added the new view to the navigation like so:
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

let nextViewController = storyBoard.instantiateViewController(withIdentifier: "presetController") as! PresetViewController

self.navigationController?.pushViewController(nextViewController, animated: true)

A: Here it is
let nextScreen = storyboard?.instantiateViewController(withIdentifier: "nextScreenIdentifier") as! NextScreenControllerName
self.navigationController?.pushViewController(nextScreen, animated: true)

write this inside any function of the viewcontroller.


text:
Q: Returned string that looks like an array from database - PHP The database returns me a string like so :
"date_approved"=>"2015-01-01T10:19:44+00:00", "date_realized"=>"2015-01-01T10:31:11+00:00", "date_tn_approved"=>"2015-01-01T10:09:40+00:00"

What's the best to convert this into an array so I can use this data easily?

A: It seems that this is the output of the var_export function. The opposite of it is eval but it is considered a bad practice in terms of security so you can try:
$data = '"date_approved"=>"2015-01-01T10:19:44+00:00", "date_realized"=>"2015-01-01T10:31:11+00:00", "date_tn_approved"=>"2015-01-01T10:09:40+00:00"';
$result = array();
$items = explode(',', $data);

foreach($items as $item) {
    $item_data = explode('=>', $item);
    $result[trim($item_data[0], '"')] = trim($item_data[1], '"');
}

Finally in $result you will have an array with the parsed data for this specific data row.

A: I think a nice way is to make that string into a JSON format string, by replacing '=>' with ':', then apply json_decode().
$str = '"date_approved"=>"2015-01-01T10:19:44+00:00", "date_realized"=>"2015-01-01T10:31:11+00:00", "date_tn_approved"=>"2015-01-01T10:09:40+00:00"';
$str = '{'. str_replace('=>', ':', $str). '}';
$arr = json_decode($str, true);

// Test
var_export($arr);
//array ('date_approved'=>'2015-01-01T10:19:44+00:00', 'date_realized'=>'2015-01-01T10:31:11+00:00', 'date_tn_approved'=>'2015-01-01T10:09:40+00:00')

A: It's untrusted data coming from the database but this should do it:
eval("\$array = array($string);");
print_r($array);

You could also try this but just like the other answers, it won't work with all data (if it contains the >," in the data):
$string = str_replace(array(',','"','>'), array('&','',''), $string);
parse_str($string, $array);
print_r($array);


text:
Q: Java connection String ORA-12650: No common encryption or data integrity algorithm I have problem connecting Oracle cloud database from my connection string, the error says:

ORA-12650: No common encryption or data integrity algorithm

I tried my connection string with other oracle databases, all works, except for this cloud db.
I also tried solution like this the following, but not works (changed parameters in sqlnet.ora)
https://doganay.wordpress.com/2012/06/28/ora-12650-no-common-encryption-or-data-integrity-algorithm/
String dbURL = "jdbc:oracle:thin:@<hostname>:1521:<SID>";
try {
   Class.forName("oracle.jdbc.driver.OracleDriver");
   Connection conn = DriverManager.getConnection(dbURL, "username", "password");
} catch (Exception e) {
   System.out.println("Database access failed " + e);
}

A: Please make sure correct version of Driver jar being used, to avoid this kind of issues


text:
Q: Gradle sonarqube plugin - how to set memory for findbugs? I have a project module with 30K classes.
After migrating sonar analysis from ant script to gradle plugin I have OOM error with output like this:

13:10:36 Out of memory
13:10:36 Total memory: 954M
13:10:36  free memory: 119M
13:10:52 Caused by: java.util.concurrent.ExecutionException: java.lang.OutOfMemoryError: GC overhead limit exceeded
13:10:52  at org.sonar.plugins.findbugs.FindbugsExecutor.execute(FindbugsExecutor.java:163)
13:10:52  ... 109 more
13:10:52 Caused by: java.lang.OutOfMemoryError: GC overhead limit exceeded
13:10:52  at

We've run ant script with the following parameters "-Xmx3800m -XX:ReservedCodeCacheSize=128m"
How can I set the same parameters for sonarqube gradle plugin?
I've tried setting the following env variable before calling gradle

GRADLE_OPTS=-Xmx3800m -XX:ReservedCodeCacheSize=128m

It's applied correctly, but findbugs still failing and prints "Total memory: 954M"
Also I've tried adding the following properties to reduce memory consumption, but without any luck
property 'sonar.skipPackageDesign', 'true'
property 'sonar.skipDesign', 'true'

Gradle version is 3.5
Sonarqube plugin version is 2.5
jdk version is 8u131

A: I realized what was the problem.
Setting GRADLE_OPTS was correct solution, however I also used gradle daemon, so those options were ignored for daemon.
I ended up disabling daemon by adding -Dorg.gradle.daemon=false to GRADLE_OPTS and it worked.

A: Check build.gradle file and set maxHeapSize as given below,
 tasks.withType(FindBugs) {
            maxHeapSize = "1000m"
        }

You can change heap size.


text:
Q: Independent scrolling panels with no body scroll I'm using bootstrap in my template also its having two or more main panels. i want to set independent scrolling of this panels. panel contents are loaded dynamically and also with no body scroll working with any resolution.
I'm tried this link,but cannot achieve this.
here is my sample code :
    <!DOCTYPE html>

      <title> Example</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce nec lorem mauris. Nulla fermentum tincidunt nulla et dignissim. In porttitor sem id velit lobortis aliquam. Duis et purus ac orci porttitor luctus at quis leo. Mauris vulputate pellentesque est, sit amet egestas tellus facilisis sit amet. Cras sodales bibendum tellus, a gravida tortor hendrerit sed. Pellentesque blandit posuere nisl

 tristique nibh venenatis. In id eros sed libero iaculis commodo quis vitae neque. Nulla gravida neque in tortor congue id mattis massa auctor. Cras auctor tincidunt ipsum, in suscipit risus iaculis sed. Nulla at eros nec urna auctor tincidunt eu ac diam. Aenean nulla metus, accumsan eu dignissim vitae, congue sed nisl. Pellentesque ut nunc eget metus malesuada vulputate  interdum libero faucibus ac lacinia sapien bibendum. Quisque sed odio et metus molestie

 tristique nibh venenatis. In id eros sed libero iaculis commodo quis vitae neque. Nulla gravida neque in tortor congue id mattis massa auctor. Cras auctor tincidunt ipsum, in suscipit rSuspendisse congue fringilla urna vitae dapibus. Phasellus iaculis, velit at ornare feugiat, nunc dolor scelerisque dolor, sed placerat enim magna sit amet magna. Quisque gravida arcu eu neque porttitor rutrum. Donec tempus urna interdum libero faucibus ac lacinia sapien bibendum. Quisque sed odio et metus molestie

 commodo enim. Curabitur eu justo non felis tempus fermentum ut vitae augue. Ut cursus ultrices metus eu vehicula. Praesent sem nulla, eleifend eget adipiscing a, tempor sit amet lectus. Suspendisse congue fringilla urna vitae dapibus. Phasellus iaculis, velit at ornare feugiat, nunc dolor scelerisque dolor, sed placerat enim magna sit amet magna. Quisque gravida arcu eu neque porttitor rutrum. Donec tempus urna interdum libero faucibus ac lacinia sapien bibendum. Quisque sed odio et metus molestie

 Pellentesque felis erat, tristique nec semper vel, dignissim ut nisl. Donec ac dui purus. Nunc in ligula lacus. In vehicula scelerisque convallis. Ut in ornare ante. Vestibulum ante fringilla urna vitae dapibus. Phasellus iaculis, velit at ornare feugiat, nunc dolor scelerisque dolor, sed placerat enim magna sit amet magna. Quisque gravida arcu eu neque porttitor rutrum. Donec tempus urna interdum libero faucibus ac lacinia sapien bibendum. Quisque sed odio et metus molestie

 Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Etiam et libero a nibh venenatis tristique vitae vitae ligula. Phasellus vitae tempor ante. Proin  neque porttitor rutrum. Donec tempus urna interdum libero faucibus ac lacinia sapien bibendum. Quisque sed odio et metus molestie

haridass

tae tempor ante. Proin egestas commodo enim. Curabitur eu justo non felis tempus fermentum ut vitae augue. Ut cursus ultrices metus eu vehicula. Praesent sem nulla, eleifend eget adipiscinggravida arcu eu neque porttitor rutrum. Donec tempus urna interdum libero faucibus ac lacinia sapien bibendum. Quisque sed odio et metus molestie

 eget adipiscing a, tempor sit amet lectus. Suspendisse congue fringilla urna vitae dapibus. Phasellus iaculis, velit at ornare feugiat, nunc dolor scelerisque dolor, sed placerat enim magna sit amet magna. Quisque gravida arcu eu neque porttitor rutrum. Donec tempus urna interdum libero faucibus ac lacinia sapien bibendum. Quisque sed odio et metus molestie

Ut in ornare ante. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Etiam et libero a nibh venenatis tristique vitae vitae ligula. Phasellus vitae te Quisque gravida arcu eu neque porttitor rutrum. Donec tempus urna interdum libero faucibus ac lacinia sapien bibendum. Quisque sed odio et metus molestie

Suspendisse congue fringilla urna vitae dapibus. Phasellus iaculis, velit at ornare feugiat, nunc dolor scelerisque dolor, sed placerat enim magna sit amet magna. Quisque gravida arcu eu neque porttitor rutrum. Donec tempus urna interdum libero faucibus ac lacinia sapien bibendum. Quisque sed odio et metus molestie

haridass


text:
Q: Discretize value that is in range [0,1] in 10 bins data = pd.read_csv('C:\\User\\Desktop\\20_p_n1.csv',sep=',')
#print(data)
list = data['F'].tolist()
#print(list)
pd.qcut(list,10, labels=None, retbins=False, precision=1, duplicates='drop')

Here I have converted dataframe to list so that I can pass it to pd.qcut().
This is what I got as output. My data contains value between [0,1] with values as 0.1,0.2,0.5, etc. But I am only able to generate one category.
[(-0.1, 1.0], (-0.1, 1.0], (-0.1, 1.0], (-0.1, 1.0], (-0.1, 1.0], ..., (-0.1, 1.0], (-0.1, 1.0], (-0.1, 1.0], (-0.1, 1.0], (-0.1, 1.0]]
Length: 25192
Categories (1, interval[float64]): [(-0.1, 1.0]]

data.head()
    F
0   0
1   0
2   0
3   0

pd.qcut output
data.head()

A: Try using pd.cut.
[In] 1: pd.cut(np.random.rand(100), 10)

[Out]1: [(0.348, 0.38], (0.156, 0.188], (0.316, 0.348], (0.348, 0.38], (0.156, 0.188], (0.059, 0.0914], (0.348, 0.38], (0.156, 0.188], (0.348, 0.38], (0.284, 0.316]]
Categories (10, object): [(0.059, 0.0914] < (0.0914, 0.124] < (0.124, 0.156] < (0.156, 0.188] ... (0.252, 0.284] < (0.284, 0.316] < (0.316, 0.348] < (0.348, 0.38]]


text:
Q: sed command to change names for few files in different directories at once
I have few folders as S1S, S2S ,S3S ... , In each of these folders there is a file1 .
This file1 in each folder consistent of

1990.A.BHT_S1S.dat
1994.I.BHT_S1S.dat
1995.K.BHT_S1S.dat
likewise S1S extension change according to the folder.

I'm trying to change these names into 1990.A.BHT type for all folders using this command
for dir in S*
do
cd $dir
sed -i 's/_${dir}\.dat//g' file1 > file2
cd ../
done

but i get an empty file for file2
Can someone help me to figure out my mistake please?

A: This might work for you (GNU sed and parallel):
parallel sed 's/_{}\.dat//' {}/file1 \> {}/file2 ::: S*S

Create a new file file2 in each directory S1S S2S S3S ... from file1 with the string _SnS.dat removed (where SnS represents the current directory).

A: There are several problems here. First, as konsolebox said in a comment, sed -i modifies the original file rather than producing output that can be redirected with >, so you need to remove that option.
Second, variables don't expand in single-quoted strings, so 's/_${dir}\.dat//g' doesn't use the dir variable, it just treats that whole thing as a literal string.
The third is probably ok, but using cd in a script is dangerous, because if it fails for some reason the rest of the script will run in unexpected places, with possibly very bad results. It's generally better to use explicit paths, like sed ... "$dir/file1" instead of cding to $dir and then using sed ... file1.
Finally (again probably ok here) is that you should almost always put double-quotes around variable references, to avoid weird parsing of some characters.
So here's how I'd rewrite the script snippet:
for dir in S*
do
    sed "s/_${dir}\.dat//g" "$dir/file1" > "$dir/file2"
done

p.s. shellcheck.net is good at spotting common mistakes in shell scripts; it spots three of the four problems I saw (all but the sed -i problem). I recommend running your scripts through it as a check.


text:
Q: Pandas Python 3.11 Pivot FutureWarning: default value of of numeric_only in DataFrameGroupBy.sum is depricated Have a large mixed table of text and numbers and am pivoting a smaller set from the larger table.  It appears that when I updated to Python 3.11 I'm receiving an FutureWarning on my pivots now.
df = df.pivot_table(df2,index=['My_text_Column'], aggfunc='sum').reset_index()

The code runs fine but results in

FutureWarning: The default value of numeric_only in
DataFrameGroupBy.sum is deprecated. In a future version, numeric_only
will default to False. Either specify numeric_only or select only
columns which should be valid for the function.

What is the updated code I should use?

A: I hit this exact same problem with the code here https://www.geeksforgeeks.org/pivot-tables-in-pandas/
Adding
'values = "Marks" to
# pivot_table() method
display(pd.pivot_table(df, index = ["ID", "Name"]))

so that I had:-
display(pd.pivot_table(df, values="Marks", index = ["ID", "Name"]))

Removed the warning.
I tried using:-
display(pd.pivot_table(df, numeric_only = None, index = ["ID", "Name"]))

But got the warning
TypeError: pivot_table() got an unexpected keyword argument 'numeric_only'.
So specifying 'numeric_only = True' doesn't actually seem to be a thing in pivot_table().
The pandas documentation at https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot_table.html didn't make it any clearer either.


text:
Q: Adding a multiline comment within listing I'm creating a short document commenting on some C++ code. Part of what I'm trying to do is create blocks of text to the right of the code as in Numerical Recipes:

If it was just a bit of text, I would just have escapechar=@ and add my single line of text in my environment. The nice thing about NR that I'm trying to emulate is a) multiline blocks of text (hopefully not broken up manually) and b) have multiple comments be aligned (when possible, depending on the code):

How would I go about doing this?


text:
Q: Matplotlib: Simplest possible example for 2 x 1 - grid of plots fails with "cannot create weak reference to bool" I'm trying to do the simplest possible 1-row, 2-column multi-ax-plot with matplotlib, actually taken from the examples in the documentation:
from matplotlib import pyplot as plt
fig, (ax1, ax2) = plt.subplot(nrows=1, ncols=2, sharey=True)

    ---------------------------------------------------------------------------

    TypeError                                 Traceback (most recent call last)

    <ipython-input-9-4bc4f1ccd8e8> in <module>
          1 from matplotlib import pyplot as plt
    ----> 2 fig, (ax1, ax2) = plt.subplot(nrows=1, ncols=2, sharey=True)

    ~/.virtualenvs/tcpsp/lib/python3.7/site-packages/matplotlib/pyplot.py in subplot(*args, **kwargs)
       1082
       1083     fig = gcf()
    -> 1084     a = fig.add_subplot(*args, **kwargs)
       1085     bbox = a.bbox
       1086     byebye = []

    ~/.virtualenvs/tcpsp/lib/python3.7/site-packages/matplotlib/figure.py in add_subplot(self, *args, **kwargs)
       1365                     self._axstack.remove(ax)
       1366
    -> 1367             a = subplot_class_factory(projection_class)(self, *args, **kwargs)
       1368         self._axstack.add(key, a)
       1369         self.sca(a)

    ~/.virtualenvs/tcpsp/lib/python3.7/site-packages/matplotlib/axes/_subplots.py in __init__(self, fig, *args, **kwargs)
         68
         69         # _axes_class is set in the subplot_class_factory
    ---> 70         self._axes_class.__init__(self, fig, self.figbox, **kwargs)
         71         # add a layout box to this, for both the full axis, and the poss
         72         # of the axis.  We need both because the axes may become smaller

    ~/.virtualenvs/tcpsp/lib/python3.7/site-packages/matplotlib/axes/_base.py in __init__(self, fig, rect, facecolor, frameon, sharex, sharey, label, xscale, yscale, **kwargs)
        471             self._shared_x_axes.join(self, sharex)
        472         if sharey is not None:
    --> 473             self._shared_y_axes.join(self, sharey)
        474         self.set_label(label)
        475         self.set_figure(fig)

    ~/.virtualenvs/tcpsp/lib/python3.7/site-packages/matplotlib/cbook/__init__.py in join(self, a, *args)
        923
        924         for arg in args:
    --> 925             set_b = mapping.get(weakref.ref(arg), [weakref.ref(arg)])
        926             if set_b is not set_a:
        927                 if len(set_b) > len(set_a):

    TypeError: cannot create weak reference to 'bool' object

    <Figure size 432x288 with 0 Axes>

I honestly have no clue why it tries to create a weak reference to a bool.
I'm using fairly recent versions of matplotlib and Python:
import sys
print(sys.version)

    3.7.0 (default, Sep 12 2018, 18:30:08)
    [GCC 8.0.1 20180414 (experimental) [trunk revision 259383]]

import matplotlib
matplotlib.__version__

    '3.0.2'

Am I right to assume that the example from the documentation should work? Is this a Matplotlib bug or have I done something wrong?

A: First off, use plt.subplots()
It might be easier to not unpack your ax subplots variable until you want to customize each plot individually.
Usually how i'll do it is:

fig, ax = plt.subplots(1, 2, dpi=175)

quadrants = 0, 1

so if I need to apply anything globally I can do:
for quad in quadrants:
    ax[quad]. (whatever)

and then individually:
ax[0].plot(...)

This also scales pretty well, such that if I was working with instead a 2x2 matrix of plots (like I am now), the difference is simply:
fig, ax = plt.subplots(2, 2, dpi=175)

quadrants = (0,0),(0,1),(1,0),(1,1)


text:
Q: Delete 0s that occur only at the beginning of a list I have a list which has 0s at the beginning I want to delete. 0s do occur elsewhere in the data but I want to keep these.
l=[0, 0, 0, 0, 151, 199, 149, 147, 281, 133, 166, 162, 0, 353, 867, 1060, 525, 1031, 420, 0, 832, 1114, 869, 531, 546, 555, 520, 679, 715, 669, 555, 888, 605, 809, 0, 514]

needs to become:
l=[151, 199, 149, 147, 281, 133, 166, 162, 0, 353, 867, 1060, 525, 1031, 420, 0, 832, 1114, 869, 531, 546, 555, 520, 679, 715, 669, 555, 888, 605, 809, 0, 514]

A: Use itertools.dropwhile() to drop those zeros:
from itertools import dropwhile
import operator

l = list(dropwhile(operator.not_, l))

This will drop just the initial 0 values; or rather, all false-y values, using operator.not_().
Demo:
>>> from itertools import dropwhile
>>> import operator
>>> l=[0, 0, 0, 0, 151, 199, 149, 147, 281, 133, 166, 162, 0, 353, 867, 1060, 525, 1031, 420, 0, 832, 1114, 869, 531, 546, 555, 520, 679, 715, 669, 555, 888, 605, 809, 0, 514]
>>> list(dropwhile(operator.not_, l))
[151, 199, 149, 147, 281, 133, 166, 162, 0, 353, 867, 1060, 525, 1031, 420, 0, 832, 1114, 869, 531, 546, 555, 520, 679, 715, 669, 555, 888, 605, 809, 0, 514]

A: You could use the methods list.index() and next():
L=[0, 0, 1, 2, 'a', 3, 0, 0, 9]

noLeadingZeros = L[L.index(next(i for i in L if i!=0)):]


text:
Q: UITableViewController wont display the cells im creating first off I'm new to iOS development so this may be a simple issue,
I've got the following code
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;

    cell.textLabel.text = @"Hello!";
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    NSLog(@"Creating cell for %i:%i", indexPath.section, indexPath.row );

    return cell;
}

Now the table shows, but all the rows are blank. And the cells are being created. Not sure if it matters but im not using xib's or story boards so i dont know if its a styling issue.
I'm really in the dark here about what im doing. I've tried to follow a few tutorials and every time i end up at the same place with a blank table.
Thank you for all help! I'm open to ideas and possible tutorials etc.

A: (This is more of a comment, but it's too big for the comment field.)
I've copied your methods exactly into my .m file, and it works. The rest of the file looks like this:
@interface MYViewController ()

@end

@implementation MYViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    UITableView *table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 640) style:UITableViewStylePlain];
    [table setDataSource:self];
    [table setDelegate:self];
    [self.view addSubview:table];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

I'm assuming you set the data source, since you're getting the NSLogs to print.

A: Are you sure that the UITableView is not hidden, does not have a 0 alpha, and is above all other views?

A: If the data you display has the possibility of changing when you go out and back into the view, I'd advice use of
[self.yourTableViewObject reloadData];

This will call all the delegate methods (getting the sections, individual cells) and repopulate your table view.


text:
Q: Issue binding Gridview itemsource to viewmodel property I'm having some issues binding my collection property in my viewmodel to a GridView. I'm using MVVM light and i believe i have the ViewModelLocator setup correctly and have the DataContext setup in the page's xaml.
Model
public class Base
{
    public ObservableCollection<Downloads> results { get; set; }
}
public class Downloads
{
    public int id { get; set; }
    public string name { get; set; }
    public int trackNumber { get; set; }
    public string mixName { get; set; }
    public string title { get; set; }
    public string slug { get; set; }
    public string releaseDate { get; set; }
    public string publishDate { get; set; }
    public List<Artist> artists { get; set; }
    public string artistNames
    {
        get
        {
            return (artists == null)
                ? string.Empty
                : string.Join(", ", artists.Select(a => a.name));
        }
    }
    public string artistNamesSlug
    {
        get
        {
            return (artists == null)
                ? string.Empty
                : string.Join("_", artists.Select(a => a.name));
        }
    }

    public Release release { get; set; }
    public Label label { get; set; }
    public Image images { get; set; }
    public int downloadId { get; set; }
    public string audioFormat { get; set; }
    public string downloadUrl { get; set; }
}
public class Release
{
    public int id { get; set; }
    public string name { get; set; }
    public string type { get; set; }
    public string slug { get; set; }
}
public class Label
{
    public int id { get; set; }
    public string name { get; set; }
    public string type { get; set; }
    public string slug { get; set; }
    public bool status { get; set; }
}
public class Image
{
    public LargeImage large { get; set; }
}
public class LargeImage
{
    public int id { get; set; }
    public int width { get; set; }
    public int height { get; set; }
    public string url { get; set; }
    public string secureUrl { get; set; }
}

ViewModel
public class AvailableViewModel : ViewModelBase
{

    public AvailableViewModel()
    {

    }

    private Base availableDownloads;
    public Base AvailableDownloads
    {
        get
        {
            if(availableDownloads == null)
            {
                GetData();
            }
            return availableDownloads;
        }
        set
        {
            availableDownloads = value;
            RaisePropertyChanged(() => AvailableDownloads);
        }
    }

    private async void GetData()
    {
        OAuth oauth = new OAuth();

        string httpMethod = "GET";
        string parameters = "status=available";
        string response = await oauth.GetData(OAuth.availDownloadsUrl, httpMethod, parameters);

        Base availableDownloads = JsonConvert.DeserializeObject<Base>(response);
    }
}

XAML
DataContext="{Binding Available, Source={StaticResource Locator}}">

<Page.Resources>
    <DataTemplate x:Key="AvailableGridView">
        <Grid Margin="0,10,0,0">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="2*"/>
            </Grid.ColumnDefinitions>
            <Image Source="{Binding AvailableDownloads.images.large.url}" Grid.Column="0" />
            <StackPanel Grid.Column="1" VerticalAlignment="Top" Margin="20,0,0,0">
                <TextBlock Text="{Binding AvailableDownloads.title}" Style="{StaticResource BaseTextBlockStyle}" TextWrapping="Wrap"/>
                <TextBlock Text="{Binding AvailableDownloads.release.name}" Style="{StaticResource BaseTextBlockStyle}"/>
                <TextBlock Text="{Binding AvailableDownloads.artistNames}" Style="{StaticResource SubtitleTextBlockStyle}"/>
            </StackPanel>
        </Grid>
    </DataTemplate>
</Page.Resources>

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <GridView ItemsSource="{Binding AvailableDownloads.results}" SelectionMode="Multiple" ItemTemplate="{StaticResource AvailableGridView}"/>
</Grid>

This might be part of the problem, but when i set the DataContext in the xaml the layout displays an Object Reference error. I don't know why that happens, but application will compile and run. I'm new to MVVM and i can't seem to figure out why my bindings aren't working here.

A:
This might be part of the problem, but when i set the DataContext in the xaml the layout displays an Object Reference error.

Is this "Object Reference error" NullReferenceException error? Since your code it not comprehensive, I can reproduce this problem in several places, but I don't know which exactly causes your problem.
First I changed your XAML code for test here, and I used x:Bind in the DataTemplate of GridView:
  ...
  DataContext="{Binding Available, Source={StaticResource Locator}}"
  xmlns:model="using:[Namespace of your app].Model">
<Page.Resources>
    <DataTemplate x:Key="AvailableGridView" x:DataType="model:Downloads">
        <Grid Margin="0,10,0,0">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="2*" />
            </Grid.ColumnDefinitions>
            <!--<Image Source="{x:Bind downloadUrl}" Grid.Column="0" />-->
            <StackPanel Grid.Column="1" VerticalAlignment="Top" Margin="20,0,0,0">
                <TextBlock Text="{x:Bind title}" Style="{StaticResource BaseTextBlockStyle}" TextWrapping="Wrap" />
                <TextBlock Text="{x:Bind release.name}" Style="{StaticResource BaseTextBlockStyle}" />
                <TextBlock Text="{x:Bind artistNames}" Style="{StaticResource SubtitleTextBlockStyle}" />
            </StackPanel>
        </Grid>
    </DataTemplate>
</Page.Resources>

<Grid>
    <GridView ItemsSource="{Binding AvailableDownloads.results}" SelectionMode="Multiple" ItemTemplate="{StaticResource AvailableGridView}" />
</Grid>

And I changed your Base class like this:
public class Base
{
    public ObservableCollection<Downloads> results { get; set; }

    public Base()
    {
        results = new ObservableCollection<Downloads>();
    }
}

This could be a possible reason if you don't create a new instance of ObservableCollection<Downloads> when you add data.
And I changed your AvailableViewModel() like this, the data added into the result are fake, just for testing:
public AvailableViewModel()
{
    availableDownloads = new Base();
    availableDownloads.results.Add(new Downloads { title = "11111", artistNames = "222", release = new Release(0, "333", "", "") });
    availableDownloads.results.Add(new Downloads { title = "11111" });
    availableDownloads.results.Add(new Downloads { title = "11111" });
    availableDownloads.results.Add(new Downloads { title = "11111" });
    availableDownloads.results.Add(new Downloads { title = "11111" });
}

As you can see, I created a new instance of Base class here.
I noticed that in your xaml code you used release.name, for this, I think you need to modify your Release class like this:
public class Release
{
    public Release()
    {
    }

    public Release(int Id, string Name, string Type, string Slug)
    {
        this.id = Id;
        this.name = Name;
        this.type = Type;
        this.slug = Slug;
    }

    public int id { get; set; }
    public string name { get; set; }
    public string type { get; set; }
    public string slug { get; set; }
}

And you can create the instance of Release class like this:
release = new Release(0, "333", "", "");

I commented the Image control in your DataTemplate, to do this work, you need modify your LargeImage and Image like the Release class.