text:
Q: How I can show zero ratio? I have a small problem, I don't know how to solve it
appreciate if anyone can help me
I'm calculating the Ratio for specific grades (Not All grades) as below
Select Term, GRADE,
       count (*) as "Total",
       case
       when GRADE IN ('A+','B+','C+','F') then
       round(100* RATIO_TO_Report(count(*))over (partition by Term),2)
else 0
       end as "Precentage "
  from RESULTS
 where Term = '2021'
       and GRADE IN('A+','B+','C+','F')
order by case
when GRADE IN('A+') then 1
when GRADE IN('B+') then 2
when GRADE IN('C+') then 3
when GRADE IN('F') then 4
else 5
end

I have tried to use the  below function but still I'm not getting the 0
COALESCE(count (GRADE),0)

my sql is working fine no issues, I only need to show if the count is 0 for one of the grades then the ratio is 0
The desired output as below, the C+ row is not showing because of the zero count. How can I show the zero?

I don't know how to do it
Thank you all

A: Oh, you mean your table doesn't have any C+ entries - well you can't count them then, because they aren't there to count
Let's simplify the query a bit:
select
  term,
  grade,
  round(100 * count(*) / sum(count(*)) over (partition by term),2) as Percentage
from results
where term = '2021' and grade IN ('A+','B+','C+','F')
group by term, grade

..which will just have rows for A, B and F
Then let's left join it to a query that definitely produces all the rows you want:
with res as (
 select
  term,
  grade,
  round(100 * count(*) / sum(count(*)) over (partition by term),2) as Percentage
 from results
 where term = '2021' --we can remove the grades from here because specifying them below will restrict to just those grades
 group by term, grade
)

select
  *
from
  (select 'A+' grade from dual union select 'B+' from dual union select 'C+' from dual union select 'F' from dual) grades
  LEFT JOIN res ON grades.grade = res.grade

Now you will have a null for C+ that you can coalesce ;)


text:
Q: Android: Do in-app purchases from testphase (Alpha or beta) stay valid new APK for production is released? We released an app for testing in open Alpha on google Play.
All in-app purchases could be done, but they were fake (no real money was  transfered).
When we release the app for production, will these in-app purchases (from the alpha stage) keep working?
And also, moving from alpha to beta, will they stay valid?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make a text string into a bullet list I have a multi-select box (with a list of countries) on my BuddyPress registration page and would like to display the results on a member's page in a bullet list.
The code below shows a bullet but then still displays the text as a string. Please help.
<?php $countries = bp_member_profile_data( 'field=Countries' );
if ( ! empty( $countries ) ) {
    echo '
';
    foreach ( $countries as $country ) {
        printf( '
%s
', $country );
    }
    echo '
';
}
?>

Thank you,
John

A: If your string is delimited by a comma , you can explode the string at this point into pieces (an array of items). If your string is separated by something else, such as spaces or | then explode that instead.
<?php
//assuming your string might look like: "USA, Canada, Japan, Russia"
$countries = bp_member_profile_data( 'field=Countries' );

$array = explode(",", $countries);
//$array[0] = USA
//$array[1] = Canada
//$array[2] = Japan
//$array[3] = Russia

if ( ! empty( $countries ) ) {
    echo '
';
    foreach ( $array as $country ) {
        printf( '
%s
', $country );
    }
    echo '
';
}

/* Result

USA

Canada

Japan

Russia

*/
?>


text:
Q: Custom Github Shields How do you make custom GitHub shields that track status on your repository?
I am using shields.io and have figured out how to use a Jenkins plugin to expose the build status and create a shield, but wondering how others automate status for code coverage, documentation coverage, linting, unit tests, etc?

A: Code coverage, linting, etc. are provided by various services that you have to sign up with. For example, coveralls.io provides test coverage. Another popular service that provides many different types of code analysis and coverage tools is Code Climate. Most of those sites provide badges you can add to your GitHub repo, usually in the README.
For example, a repo I maintain has accounts with Travis, Gemnasium, and Code Climate, and I have badges for those services on my README: https://github.com/monfresh/ohana-sms


text:
Q: Office 365 REST API I am new to office 365 API. My requirement is i need to connect to office365 using REST API.
For authentication purpose i have only
Email
Password
As the fields , Can i generate a session with these? Or I need to collect the Client id , Secret and Return URL in authentication step it self?
I need to build a windows application not a web.
Also after authentication is successful i need to write code for Add Delegate , Update Delegates for Exchange server. Can i connect to these services by using RESt API?
Please help me to do these things.

A: You can use the user's email/password to retrieve an OAuth token. However you still need to register your application to obtain a client ID. Native applications (like a Windows app) don't use a client secret. Take a look at the ADAL library for .NET. One of the overloads for AcquireTokenAsync take a UserCredential object.
The REST APIs do not have any functionality to work with delegates. You can use Exchange Web Services to work with delegates.


text:
Q: Python:- Extracting the column headers from rows[0] enclosed in a  tag. Remove the unicode symbol and the link number after the planet name I am trying to iterate over all the column headers of row[0] then remove the unicode symbol
and the link number after the planet name. Right now my code looks like this:-
URL_solar_system = "https://en.wikipedia.org/wiki/List_of_gravitationally_rounded_objects_of_the_Solar_System"

from bs4 import BeautifulSoup

import requests

html_content = requests.get(URL_solar_system).text

soup_solar = BeautifulSoup(html_content, "lxml")

tables = soup_solar.find_all('table', attrs={'class': 'wikitable'})

planets = tables[2]

rows = planets.find_all('tr')

headers = [th.text.strip() for th in rows[0].find_all('th') if th.get_text().strip() != '' ]

print('headers: {}'.format(headers))

OUTPUT
headers: ['*Mercury[6][7]', '*Venus[8][9]', '*Earth[10][11]', '*Mars[12][13]', '°Jupiter[14][15]', '°Saturn[16][17]', '‡Uranus[18][19]', '‡Neptune[20][21]']

I am trying to achieve the output as shown below.
Desired Output:
headers: ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']

Hint for writing the code:-

*

*headers = []

*for loop that will loop through row[0] with a find all on 'th'

*first_variable = uses your iterator (let's say we call it i in the for loop definition) and uses the text method on it

*second_variable = find this value '[' from the first variable that has the text method
redefine the first variable by indexing the second element to the second variable element you defined.

*if statement for that label where is appends the first variable to the headers list you created.

A: Add
import re # in the begining of your module

then just add to the end of your code the following line
headers = re.findall(r'(\w+)\[\d+]',''.join(headers))

Your final code
import re

URL_solar_system = "https://en.wikipedia.org/wiki/List_of_gravitationally_rounded_objects_of_the_Solar_System"

from bs4 import BeautifulSoup

import requests

html_content = requests.get(URL_solar_system).text

soup_solar = BeautifulSoup(html_content, "lxml")

tables = soup_solar.find_all('table', attrs={'class': 'wikitable'})

planets = tables[2]

rows = planets.find_all('tr')

headers = [th.text.strip() for th in rows[0].find_all('th') if th.get_text().strip() != '' ]

headers = re.findall(r'(\w+)\[\d+]',''.join(headers))

print('headers: {}'.format(headers))

A: The header text are href's under the fourth table. Try using a CSS Selector that selects the fourth table: table:nth-of-type(4), and then use th > a which selects the a tags (the headers) under the th tags.
import requests
from bs4 import BeautifulSoup

URL = "https://en.wikipedia.org/wiki/List_of_gravitationally_rounded_objects_of_the_Solar_System"
soup = BeautifulSoup(requests.get(URL).content, "html.parser")

print([tag.text for tag in soup.select("table:nth-of-type(4) th > a")])

Output:
['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']


text:
Q: Get pages with specific custom field value not working I have created a custom field in some pages and I need to loop through these pages and print their info. The code I'm using isn't working (the foreach is not looping).
Here's the code:
<?php
        $args = array(
            'meta_key' => 'categoria-pagina',
            'meta_value' => 'programas'
          );

        $pages = get_pages($args);

        foreach ($pages as $page) {
          echo "
$page->post_title
";
        }

        wp_reset_postdata();
      ?>

And here's the page custom field config (wordpress in portuguese):

What's wrong with it?

A: Solved with this code:
<?php
        $args = array(
            'post_type' => 'page',
            'meta_key' => 'categoria-pagina',
            'meta_value' => 'programas'
          );

        $myPages = new WP_Query($args);
        while ($myPages->have_posts()) : $myPages->the_post();
          echo "$post->post_title";
        endwhile;

        wp_reset_postdata();
      ?>

A: <?php
$args = array(
        'meta_key' => 'categoria-pagina',
        'meta_value' => 'programas'
      );
$custom_query = new WP_Query( $args );
// The Loop
if ( $custom_query->have_posts() ) {
while ( $custom_query->have_posts() ) {
    $custom_query->the_post();
    echo '
' . get_the_title() . '
';
}
} else {
  // no posts found
}
/* Restore original Post Data */
wp_reset_postdata();

That should do the trick for you.


text:
Q: pushing items to object array - javascript Update: I'm trying to construct a table out of my data structure(ie section1) and then allow users to add rows to the table to insert more rows and save them to my datastructure.
I have an array newArr in the form of key value pairs. When somebody clicks a button, I want to be able to push the  newArray into the Groups.I dont seem to be able to push into the Groups array. Chrome dev tools shows Groups as Objects and i'm not certain how to loop through and append to each item of the Groups Object. Feel free to modify the $scope.section1 to a different datastructure that could make it easier to push new items to it.
$scope.section1 = [{
                "id":1, "Name": "Section 1: Inventory",
                 "Groups":[
                     {"cell" : "Number", "cellValue" : "value1"},
                     {"cell" : "Location", "cellValue" : "value2"},
                     {"cell" : "Severity", "cellValue" : "value3"}
                 ],
                 "FootNotes":[
                    {"templateurl" : "components/section/templates/notes/section1.notes.html"}
                 ]
            }]

        var newArr = {"cellValue" : "value4","cellValue" : "value5","cellValue" : "value6"}

So the output should look like
 $scope.section1 = [{
                    "id":1, "Name": "Section 1: Inventory",
                     "Groups":[
                         {"cell" : "Number", "cellValue" : "value1", "cellValue" : "value4"},
                         {"cell" : "Location", "cellValue" : "value2", "cellValue" : "value5"},
                         {"cell" : "Severity", "cellValue" : "value3", "cellValue" : "value6"}
                     ],
                     "FootNotes":[
                        {"templateurl" : "components/section/templates/notes/section1.notes.html"}
                     ]
                }]

A: You can't have two properties with the same name. You have cellValue two times for Object group. What are you trying to do?
You'd better like to change the structure itself:
...
"Groups": [
    {
        name: "group1",
        values: ['value 1', 'value 2', 'value 3']
    }
]

Then, adding one more value to group1:
$scope.section1[0].Groups.values.push('value 4')

Note than I'm trying to respect the whole structure that you already have, but I don't meaning this is the optimal way to solve your problem

A: $scope.section1[0].Groups.push({
  "cell" : "Number",
  "cellValue" : "value1",
  "anotherCellValue" : "value4"
});


text:
Q: Acrescentar uma Label em um Formulário HTML Olá, estava precisando de uma ajuda para acrescentar uma label em um "mini" formulário HTML. Preciso de uma label, como por exemplo : First Name e colocar junto desse form aqui, na mesma linha, e quando clicar no botão show selected disparar um alert com o valor do campo First Name, Country e State. O formulário é esse aqui :

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
var citiesByState = {
Australia: ["Sidney","Camberra"],
Canada: ["Toronto","Montreal"],
USA: ["Chicago","Miami"]
}
function makeSubmenu(value) {
if(value.length==0) document.getElementById("citySelect").innerHTML = "<option></option>";
else {
var citiesOptions = "";
for(cityId in citiesByState[value]) {
citiesOptions+="<option>"+citiesByState[value][cityId]+"</option>";
}
document.getElementById("citySelect").innerHTML = citiesOptions;
}
}
function displaySelected() { var country = document.getElementById("countrySelect").value;
var city = document.getElementById("citySelect").value;
alert(country+"\n"+city);
}
function resetSelection() {
document.getElementById("countrySelect").selectedIndex = 0;
document.getElementById("citySelect").selectedIndex = 0;
}
</script>
</head>
<body onload="resetSelection()">
<select id="countrySelect" size="1" onchange="makeSubmenu(this.value)">
<option value="" disabled selected>Choose State</option>
<option>Australia</option>
<option>Canada</option>
<option>USA</option>
</select>
<select id="citySelect" size="1" >
<option value="" disabled selected>Choose City</option>
<option></option>
</select>
<button onclick="displaySelected()">show selected</button>
</body>
</html>

Desde já agradeço

A: Em primeiro lugar coloque um campo no HTML, exemplo
<input type="text" id="firstName" placeholder="First Name">
Na function displaySelected() recupere o valor digitado
var firstName=document.getElementById("firstName").value;

Caso nada seja digitado pode colocar um valor default
if (firstName==""){
    firstName = "Nameless";
}

Ainda na function displaySelected() altere a forma de apresentar o alert, caso o State não seja selecionado o alerta irá lembrar de fazer isso
if (country){
   alert(firstName+ "\n"+country+"\n"+city);
}else{
   alert("Choose State");
}

A function resetSelection() também teve alterações bem óbvias
Modificado
document.getElementById("citySelect").innerHTML = '<option value="" disabled selected>Choose City</option>';

Incluído
document.getElementById("firstName").value="";

No HTML acrescentado botão para disparar a função resetSelection()

var citiesByState = {
Australia: ["Sidney","Camberra"],
Canada: ["Toronto","Montreal"],
USA: ["Chicago","Miami"]
}
function makeSubmenu(value) {
if(value.length==0) document.getElementById("citySelect").innerHTML = "<option></option>";
else {
var citiesOptions = "";
for(cityId in citiesByState[value]) {
citiesOptions+="<option>"+citiesByState[value][cityId]+"</option>";
}
document.getElementById("citySelect").innerHTML = citiesOptions;
}
}
function displaySelected() {
var firstName=document.getElementById("firstName").value;
if (firstName==""){
firstName = "Nameless";
}
var country = document.getElementById("countrySelect").value;
var city = document.getElementById("citySelect").value;
if (country){
alert(firstName+ "\n"+country+"\n"+city);
}else{
alert("Choose State");
}
}
function resetSelection() {
document.getElementById("countrySelect").selectedIndex = 0;
document.getElementById("citySelect").innerHTML = '<option value="" disabled selected>Choose City</option>';
document.getElementById("firstName").value="";
}
<body onload="resetSelection()">
<input type="text" id="firstName" placeholder="First Name">
<select id="countrySelect" size="1" onchange="makeSubmenu(this.value)">
<option value="" disabled selected>Choose State</option>
<option>Australia</option>
<option>Canada</option>
<option>USA</option>
</select>
<select id="citySelect" size="1" >
<option value="" disabled selected>Choose City</option>
<option></option>
</select>
<button onclick="displaySelected()">show selected</button>
<button onclick="resetSelection()">Reset selected</button>


text:
Q: When sending an email with smtp in python my \t are replaced with a single space. I need to be able to have tabs in the email i send so the content can be copy pasted into excel. Code:
SUBJECT = subj
TO = [whoto]
FROM = whofrom
BODY = string.join((
    "From: %s" % FROM,
    "To: %s" % ", ".join(TO),
    "Subject: %s" % SUBJECT ,
    "",
    text
    ), "\r\n")

server = smtplib.SMTP(host)
server.login(log,pass)
server.sendmail(FROM, TO, BODY)
server.quit()

My text has tabs in it but when the email is sent there are no tabs. How can i get the tabs to remain.

A: I suggest using the mime encoder libraries:
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import os
import smtplib
import datetime
import logging

class mailer:
    def __init__(self,SERVER="my.mail.server",FROM="email@mydomain.com"):
        self.server = SERVER
        self.send_from = FROM
        self.logger = logging.getLogger('mailer')

    def send_mail(self, send_to, subject, text, files=[]):
        assert type(send_to)==list
        assert type(files)==list
        if self.logger.isEnabledFor(logging.DEBUG):
            self.logger.debug(' '.join(("Sending email to:",' '.join(send_to))))
            self.logger.debug(' '.join(("Subject:",subject)))
            self.logger.debug(' '.join(("Text:",text)))
            self.logger.debug(' '.join(("Files:",' '.join(files))))
        msg = MIMEMultipart()
        msg['From'] = self.send_from
        msg['To'] = COMMASPACE.join(send_to)
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = subject
        msg.attach( MIMEText(text) )
        for f in files:
            part = MIMEBase('application', "octet-stream")
            part.set_payload( open(f,"rb").read() )
            Encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
            msg.attach(part)
        smtp = smtplib.SMTP(self.server)
        mydict = smtp.sendmail(self.send_from, send_to, msg.as_string())
        if self.logger.isEnabledFor(logging.DEBUG):
            self.logger.debug("Email Successfully Sent!")
        smtp.close()
        return mydict

Make sure to check the return dictionary, as it will let you know if only some people received the email.

A: You will need to switch your email to be HTML and use tables. In my case Gmail is converting the Email output from tabs to spaces to make it look correct.
To confirm this is your issue. Look at the raw email and try to copy and paste that in.


text:
Q: regular expression with javascript language I am working in Jquery
Is it possible to take a fragment from String variable? such as:
var text = "azerty uiop hello qsdf ghjklm wxcvbn";

I want take "hello" with 5 symboles before and after:
uiop Hello qsdf

A: This should work:
var text = "azerty uiop hello qsdf ghjklm wxcvbn";
console.log((text.match(/.{0,5}hello.{0,5}/) || [''])[0]); // uiop hello qsdf

A: You can also extract a fragment of a string using the substring function -
var text = "azerty uiop hello qsdf ghjklm wxcvbn";
var target = text.indexOf("hello");
print(text.substring(target-5,target+10));

A: Try using a regex in plain javascript:
/.{5}hello.{5}/.exec(text)

A: var text = "azerty uiop hello qsdf ghjklm wxcvbn";
text.match(/.{5}hello.{5}/)[0]; // uiop hello qsdf


text:
Q: Would "Constrained Types" be useful in VB/C#? Intro
This question prompted by Marc Gravell's suggestion that I post new language feature suggestions to this site to gather general opinion on them.
The idea is to gather if they might be helpful or maybe there is already another way to achieve what I am after.
Suggestion (Constrained Types)
A normal variable declaration in VB.Net is written thus:
Dim SomeVariable as SomeType

I suggest allowing the following form(s)
Dim SomeVariable1 as {SomeType, ISomeInterface}
Dim SomeVariable2 as {SomeType, ISomeInterface, ISomeOtherInterface}

This syntax is borrowed from Vb.Net's style of constraining Generics
Why allow this?...What is it good for?
Well the specific case I originally thought of was to define a particular subset of controls.
I wished to create an interface for a series of Control factories which would provide controls based on some business rules.
The consumer of these controls would require, through the interface, that all controls created, should also implement some series of interfaces (only one in my case) which gave all these controls additional facilities not found generally in normal controls.
It is worth noting that the following currently does not work.
Public Interface ISpecialControl
End Interface

Public Interface IControlProvider
    Function CreateControl(Of T As {Control, ISpecialControl})() As T
End Interface

Public Class SpecialTextBoxProvider
    Implements IControlProvider
    Public Function CreateControl(Of T As {Control, ISpecialControl})() As T Implements IControlProvider.CreateControl
        Return New SpecialTextBox
    End Function
End Class

Public Class SpecialTextBox
    Inherits TextBox
    Implements ISpecialControl
    Public Sub New()

    End Sub
End Class

I think this translates to C# as:
public interface ISpecialControl
{
}

public interface IControlProvider
{
    T CreateControl<T>()
        where T : Control, ISpecialControl;
}

public class SpecialTextBoxProvider : IControlProvider
{
    public T CreateControl<T>()
        where T : Control, ISpecialControl
    {
        return new SpecialTextBox();
    }
}

public class SpecialTextBox : TextBox, ISpecialControl
{
}

The attempt to return "New SpecialTextbox" fails due to an inability to cast SpecialTextbox to T.
"Value of type 'MyApp.SpecialTextBox' cannot be converted to 'T'"

I realize that my factories could be allowed to return simple controls and I could check at runtime if they implemented ISpecialControl, but this would yield runtime problems which I would rather check at compile time since it is a logical possibility even if not currently a practical one
Update: The idea is that these factories could sit in external (perhaps even third party) assemblies and could take a dependency on any control libraries they wanted, creating and returning derivatives of these controls which also implemented ISpecialControl.
These assemblies could be located through self-configuring-reflection (Reflection on first pass followed by configuration, which is then used on further runs) and used without any knowledge by the calling assembly on what dependancy these controls would have taken.
It does require that these factories are constructable without passing information about the control they are expected to call, since that would defeat the point.
So what do you think... Would this be useful?... Is there a better way to achieve this? Is there already a way to achieve this?

A: I think, whilst superficially useful this sort of thing is better handled by one of the two:

*

*Duck Typing via dynamic (coming in VS2010) for vastly more flexibility albeit removing type safety.

*Generic composition

Your original example requires neither and can be easily made to work like so:
public interface IControlProvider<T>
    where T : Control, ISpecialControl
{
    T CreateControl();
}

public class SpecialTextBoxProvider : IControlProvider<SpecialTextBox>
{
    public SpecialTextBox CreateControl()
    {
        return new SpecialTextBox();
    }
}

In fact given that most controls have a default public constructor you can make it even easier:
public class ControlProvider : IControlProvider<T>
    where T : Control, ISpecialControl, new()
{
    public T CreateControl()
    {
        return new T();
    }
}

var control = ControlProvider<SpecialTextBox>.CreateControl();

Given the additional restriction on calling code not taking a reference dependency on SpecialTextBox directly this won't work.

A: It is more "constrained variables" than "constrained types" - but definitely interesting. As with generic constraints, there are probably a few minor niggles with resolution if there are conflicting members, but the same workarounds would presumably apply as with generic constraints.
Of course, the pragmatic view is that you can already cast etc, but then you need to keep the two references up-to-date with each-other...
hmm... interesting.

A: How about using interface composition?
You have
interface IA;
class B;

if it exists use interface for class B and make a composite
interface IB;
interface IAB : IA, IB;

modify class
class C : B, IA

to implement composite interface (that should not present a problem)
class C : B, IAB

And you can use interface IAB as your constraint type.

A: I don't understand what you're proposing, I think that's my problem.
However, it sounds to me as you want to return a control that implements a specific interface.
Why can't you just say that the method returns that specific interface? It sounds to me as you're saying that "I want to return classes that descend from Control, and that also implements interface ISomeInterface".
Perhaps the solution is to extract the parts of Control you need into your own interface, and specify that you want to return objects that implement both?
Like this:
interface IControl { ... }
interface ISomeInterface { ... }

interface IControlInterface : IControl, ISomeInterface { ... }

This last interface would specify that you need an object that implements both the base interfaces, which is what it sounds like you want, except that you want one of the requirements to be a base class, instead of an interface.
I think you can solve this just by using interfaces.

A: Is this substantially different from extension methods? Why not just extend the controls?

A: edit: Oh wait I didn't read correctly, this is about constraining it to 2 types, not a choice 2 types. I think you could solve it similar to the class mentioned below though...
I've experimented with a class once to simulate this behavior:
public class Choice<T1, T2>
{
    private readonly T1 value1;
    private readonly T2 value2;

    public Choice(T1 value)
    {
        value1 = value;
    }

    public Choice(T2 value)
    {
        value2 = value;
    }

    public static implicit operator T1(Choice<T1, T2> choice)
    {
        return choice.value1;
    }

    public static implicit operator T2(Choice<T1, T2> choice)
    {
        return choice.value2;
    }

    public static implicit operator Choice<T1, T2>(T1 choice)
    {
        return new Choice<T1, T2>(choice);
    }

    public static implicit operator Choice<T1, T2>(T2 choice)
    {
        return new Choice<T1, T2>(choice);
    }

    public T1 Value1
    {
        get { return value1; }
    }

    public T2 Value2
    {
        get { return value2; }
    }
}

which allows you to create constructs like this:
[TestMethod]
public void TestChoice()
{
    TestChoice("Hello");
    TestChoice(new []{"Hello","World"});
}

private static void TestChoice(Choice<string[], string> choice)
{
    string value = choice;
    string[] values = choice;

    if (value != null)
        Console.WriteLine("Single value passed in: " + value);

    if (values != null) {
        Console.WriteLine("Multiple values passed in ");
        foreach (string s in values)
            Console.WriteLine(s + ",");
    }
}

Downside of the implicit operators is that it doesn't do implicit casting to an interface (it does work casting from an interface type), so passing in an IEnumerable<T> instead of a string[] wouldn't work when trying to cast the contained value back from Choice<IEnumerable<T>, T> to IEnumerable<T>.
Generally I would prefer just to use overloads/interfaces BTW, so don't get me wrong here :)
It would be more useful in cases where you use properties (and can't use overloading for that reason), something like a DataSource property that only allows list<string> or list<ListItem> for example.

A: It would seem a useful language feature.  It's possible to have method parameters whose type is unknown other than its compliance with multiple constraints, but there's no way to store such a parameter in a field in such a way that it can ever be passed to such a function, or even typecast to be passed.
There is another way, however, of achieving the basic result you're after, though it's a little clunky.  See my question Storing an object that implements multiple interfaces and derives from a certain base (.net) where offer up the best approach I've been able to formulate.


text:
Q: How to declare objects as constants in Objective-C? I found this question that explains very well how to declare a constant NSString or primitive type in Objective-C. The method worked perfectly.
I ran into a problem when, recently, I was writing an application using CoreBluetooth. There are several CBUUID's that I'd like to save as constants because I will be using them frequently. In this case the FOUNDATION_EXPORT technique fails.
When I put this in my header file
FOUNDATION_EXPORT CBUUID *const _Nonnull kTxPowerServiceUUID;

and this in my .m file
CBUUID *const kTxPowerServiceUUID = [CBUUID UUIDWithString:@"1804"];

I get this error

ERROR: Initializer element is not a compile-time constant.

To my surprise, I get this error even when the object I am trying to initialize is a compile time constant. For example, I have several calculations in my application that involve the speed of light in meters per second. I tried creating a constant NSNumber to represent it. When I tried this
NSNumber *const kTheSpeedOfLight = @(299792458);

I got the same error, and resorted to declaring kTheSpeedOfLight as an unsigned int.
So is there a way to create constants from objects in general? Or is it just for primitives and NSString's?


text:
Q: django: FileField model - 404 This is my first Django project and I have one problem. file1 is saved to media folder\files however when I try to download the file I'm getting 404. Any help is appreciated!
127.0.0.1:8000/about/files/2021/01/22/pyqt_tutorial_EB2ZapN.pdf
models.py
class Links(models.Model):
    file1 = models.FileField(upload_to = 'files/%Y/%m/%d/')
    is_published = models.BooleanField(default = True)
    publish_date = models.DateTimeField(default = datetime.now, blank = True)

html
        {% for link in links %}

Download Link

{{ link.publish_date }}

        {% endfor %}

urls.py>
urlpatterns = [
    path('admin/', admin.site.urls),
    path('about/', about, name = 'about')
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

settings.py>
# Media Folder Settings
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

Update: from the admin panel if I click on the link I can see it. Maybe In the {{ link.file1 }} url something need to be changed?

A: The href in your template should be {{ link.file1.url }} to properly construct the path to the file.


text:
Q: Проблема асинхронных бесконечных циклов Господа, я хотел бы узнать мнение опытных программистов, насколько правильное решение я применил. У меня есть сервер на вебсокетах, который ждет от клиентов сообщений. Реализована эта функция вот так:
async def start(self):
    while True:
        message = await self._connection.recv()
        LOGGER.info("%s: receive message %s", self.id, message)
        await self.route_message(message)

Однако, мне требовалось что бы у меня была возможность отправлять от сервера сообщения клиентам, для этого я сделал вот такую функцию с помощью такого же бесконечного цикла, который периодически проверяет состояние глобальной переменной h, которая может изменять свое состояние:
 async def remotestart():
    global h,N
    while True:
        if h==1:
            if cp.id==N:
                await cp.remote_start_transaction()
                h=0
            else:
                await asyncio.sleep(0.1)
        else:
            await asyncio.sleep(0.1)

Соответственно с помощью такой функции я собираю все в кучу.
    try:
        await asyncio.gather(cp.start(),remotestart())

Данное решение работает так как мне нужно, однако есть сомнение что это можно было решить иначе. Подскажите, адекватное ли решение ?


text:
Q: Highlight a WPF control when it gets focus I am working on a WPF application having lots of screens and every screen has lots of controls on it.
It becames very difficult to determine which control has focus.
So i want to highlight the control that currently have focus on it. It could be textbox, button, combobox, listbox or grid.
It'll be better if we could do this using styles and triggers.
Thanks

A: You should use a trigger for the right event. In your case it's IsFocused. Simple example:
<Trigger Property="IsFocused" Value="true">
    <Setter Property="BorderBrush" Value="Red" />
    <Setter Property="BorderThickness" Value="1" />
</Trigger>

You should use a Style tag, if you want to apply this style for a particular control type (use TargetType="{x:Type TextBox}", for example).
If you want to apply to all control types in your application, than you should consider using a base style with only such kind of trigger and than just inherit it in your custom styles with a help of BasedOn attribute:
<Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource BaseFocusStyle}">
Good example of how to do this is a SO question: "How to make Style.Triggers trigger a different named style to be applied".

A: I would suggest using visual states in custom styles for every control. All standard controls will suport this visual state. For example check out the MSDN style for button you will notice there is a visual state for Focused. This MSDN article might also help you.

A: You can also try and create an adorner for this behavior; in case you are open to use 3'rd party open source library then have a look at this implementation on codeplex, you can also go through the code to get idea about how to implement your own adorner -
http://uiannotations.codeplex.com/wikipage?title=Adorners&referringTitle=Documentation

Another similar question having details about other solutions - Reusable way to put a bright red box around whatever element currently has focus?


text:
Q: Screen Display in Ubuntu (with DisplayLink adapter) Since a while ago I wanted to use my laptop with 2 more screens (3 screens in total). I recently bought an USB to VGA adapter in order to set up the third one but apparently it only works on Windows.
Anyone knows how can I do this?

A: These links might help you out.
Have a look here:
http://www.displaylink.com/downloads
Some info on open source drivers (Libdlo)
https://libdlo.freedesktop.org/wiki/
Good luck!


text:
Q: How do I post and receive JSON via iOS notification center? I'm using swiftyJSON and "response" is a JSON object.
How do I pass it to a notification and then receive it on the other end?
self.center.postNotificationName(NotificationCenters.JSONObjectReceived, object: self, userInfo: response)  //how?

And then in another class:
func JSONObjectReceived(notification: NSNotification!){
    let response = notification.userInfo //response should be JSON type now
}

A: This happens because JSON is a struct. And to pass in notification you can use json.object value:
import UIKit
import Foundation
import SwiftyJSON

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Register for notification
        NSNotificationCenter.defaultCenter().addObserver(self, selector:"receiveNotification:", name: "my_notification", object: nil)

        // Create JSON object
        let jsonString: String = "{\"name\": \"John\"}"
        if let dataFromString = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
            let json = JSON(data: dataFromString)

            // Check that everything is ok with json object
            NSLog("%@", json.description)

            // Post notification
            let userInfo:[String:AnyObject] = ["my_key":json.object]
            NSNotificationCenter.defaultCenter().postNotificationName("my_notification", object: self, userInfo: userInfo)
        }
    }

    func receiveNotification(notification: NSNotification) {
        NSLog("name: %@", notification.name)

        // get json object
        if let userInfo = notification.userInfo {
            if let json = userInfo["my_key"] {

                // find value in json
                if let name = json["name"] as? String {
                    NSLog("name : %@", name)
                }
            }
        }
    }
}


text:
Q: How to Disable NTLM authentication over HTTP in IIS A recent security scan of our network reported the vulnerability "NTLM Authentication Host Information Disclosure" in our RemoteApps (Microsoft RemoteApp).
Here's an article that explains it: https://blog.gdssecurity.com/labs/2014/2/12/http-ntlm-information-disclosure.html
The only solution I have been told is to "Disable NTLM authentication over HTTP". I've seen this in several posts, but none really go into detail about what specifically that entails.
I thought it would be a setting in IIS, but I cannot locate anything that even looks remotely like that.
How would I go about disabling NTLM over HTTP?
Would this prevent RemoteApps from working?

A: I found it under
Authentication >> Windows Authentication >> Providers


text:
Q: Reading everything currently entered in stdin I want to read everything that is on stdin after 10 seconds and then break. The code I've been able to write so far is:
#include <stdio.h>
#include <stdlib.h>

int main() {
  sleep(10);
  char c;
  while (1) { // My goal is to modify this while statement to break after it has read everything.
    c = getchar();
    putchar(c);
  }
  printf("Everything has been read from stdin");
}

So when the letter "c" is entered before the 10 seconds have elapsed, it should print "c" (after sleep is done) and then "Everything has been read from stdin".
So far I have tried:

*

*Checking if c is EOF -> getchar and similar functions never return EOF for stdin

*Using a stat-type function on stdin -> stat-ing stdin always returns 0 for size (st_size).

A: You can use the select function to wait to see if there is something to read on stdin with a timeout that starts at 10 seconds.  When it detects something, you read a character and check for errors or EOF.  If all is good, then you call select again, reducing the timeout by the elapsed time so far.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/select.h>
#include <sys/time.h>
#include <time.h>

struct timeval tdiff(struct timeval t2, struct timeval t1)
{
    struct timeval result;

    result.tv_sec = t2.tv_sec - t1.tv_sec;
    result.tv_usec = t2.tv_usec - t1.tv_usec;
    while (result.tv_usec < 0) {
        result.tv_usec += 1000000;
        result.tv_sec--;
    }
    return result;
}

int cmptimestamp(struct timeval t1, struct timeval t2)
{
    if (t1.tv_sec > t2.tv_sec) {
        return 1;
    } else if (t1.tv_sec < t2.tv_sec) {
        return -1;
    } else if (t1.tv_usec > t2.tv_usec) {
        return 1;
    } else if (t1.tv_usec < t2.tv_usec) {
        return -1;
    } else {
        return 0;
    }
}

int main()
{
    struct timeval cur, end, delay;
    int rval, len = 0;
    fd_set fds;

    gettimeofday(&cur, NULL);
    end = cur;
    end.tv_sec += 10;
    FD_ZERO(&fds);
    FD_SET(0, &fds);

    if (fcntl(0, F_SETFL, O_NONBLOCK) == -1) {
        perror("fcntl failed");
        exit(1);
    }
    do {
        delay = tdiff(end, cur);
        rval = select(1, &fds, NULL, NULL, &delay);
        if (rval == -1) {
            perror("select failed");
        } else if (rval) {
            char c;
            len = read(0, &c, 1);
            if (len == -1) {
                perror("read failed");
            } else if (len > 0) {
                printf("c=%c (%d)\n", c, c);
            } else {
                printf("EOF\n");
            }
        } else {
            printf("timeout\n");
        }
        gettimeofday(&cur, NULL);
    } while (rval > 0 && len > 0 && cmptimestamp(end,cur) > 0);

    return 0;
}

Note that this doesn't detect the keys as you press them, only after you've either pressed RETURN or stdin is closed.

A: Here's an offering that meets my interpretation of your requirements:

*

*The program reads whatever data is typed (or otherwise entered) on standard input in a period of 10 seconds (stopping if you manage to enter 2047 characters — which would probably mean that the input is coming from a file or a pipe).

*After 10 seconds, it prints whatever it has collected.

*The alarm() call sets an alarm for an integral number of seconds hence, and the system generates a SIGALRM signal when the time is up.  The alarm signal interrupts the read() system call, even if no data has been read.

*The program stops without printing on receiving signals.

*If the signal is one of SIGINT, SIGQUIT, SIGHUP, SIGPIPE, or SIGTERM, it stops without printing anything.

*It fiddles with the terminal settings so that the input is unbuffered.  This avoids it hanging around.  It also ensures that system calls do not restart after a signal is received.  That may not matter on Linux; using signal() on macOS Big Sur 11.7.1, the input continued after the alarm signal, which was not helpful — using sigaction() gives you better control.

*It does its best to ensure that the terminal mode is restored on exit, but if you send an inappropriate signal (not one of those in the list above, or SIGALRM), you will have a terminal in non-canonical (raw) mode.  That leads to confusion, in general.

*It is easy to modify the program so that:

*

*input is not echoed by the terminal driver;

*characters are echoed by the program as they arrive (but beware of editing characters);

*signals are not generated by the keyboard;

*so it doesn't futz with standard input terminal attributes if it is not a terminal.

Code
/* SO 7450-7966 */
#include <ctype.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>

#undef sigemptyset      /* MacOS has a stupid macro that triggers -Wunused-value */

static struct termios sane;

static void stty_sane(void)
{
    tcsetattr(STDIN_FILENO, TCSANOW, &sane);
}

static void stty_raw(void)
{
    tcgetattr(STDIN_FILENO, &sane);
    struct termios copy = sane;
    copy.c_lflag &= ~ICANON;
    tcsetattr(STDIN_FILENO, TCSANOW, &copy);
}

static volatile sig_atomic_t alarm_recvd = 0;

static void alarm_handler(int signum)
{
    signal(signum, SIG_IGN);
    alarm_recvd = 1;
}

static void other_handler(int signum)
{
    signal(signum, SIG_IGN);
    stty_sane();
    exit(128 + signum);
}

static int getch(void)
{
    char c;
    if (read(STDIN_FILENO, &c, 1) == 1)
        return (unsigned char)c;
    return EOF;
}

static void set_handler(int signum, void (*handler)(int signum))
{
    struct sigaction sa = { 0 };
    sa.sa_handler = handler;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;    /* No SA_RESTART! */
    if (sigaction(signum, &sa, NULL) != 0)
    {
        perror("sigaction");
        exit(EXIT_FAILURE);
    }
}

static void dump_string(const char *tag, const char *buffer)
{
    printf("\n%s [", tag);
    int c;
    while ((c = (unsigned char)*buffer++) != '\0')
    {
        if (isprint(c) || isspace(c))
            putchar(c);
        else
            printf("\\x%.2X", c);
    }
    printf("]\n");
}

int main(void)
{
    char buffer[2048];

    stty_raw();
    atexit(stty_sane);
    set_handler(SIGALRM, alarm_handler);
    set_handler(SIGHUP, other_handler);
    set_handler(SIGINT, other_handler);
    set_handler(SIGQUIT, other_handler);
    set_handler(SIGPIPE, other_handler);
    set_handler(SIGTERM, other_handler);
    alarm(10);

    size_t i = 0;
    int c;
    while (i < sizeof(buffer) - 1 && !alarm_recvd && (c = getch()) != EOF)
    {
        if (c == sane.c_cc[VEOF])
            break;
        if (c == sane.c_cc[VERASE])
        {
            if (i > 0)
                i--;
        }
        else
            buffer[i++] = c;
    }
    buffer[i] = '\0';

    dump_string("Data", buffer);
    return 0;
}

Compilation:
gcc -O3 -g -std=c11 -Wall -Wextra -Werror -Wmissing-prototypes -Wstrict-prototypes -fno-common tensec53.c -o tensec53

No errors (or warnings, but warnings are converted to errors).
Analysis

*

*The #undef line removes any macro definition of sigemptyset() leaving the compiler calling an actual function.  The C standard requires this to work (§7.1.4 ¶1).  On macOS, the macro is #define sigemptyset(set) (*(set) = 0, 0) and GCC complains, not unreasonably, about the "right-hand operand of comma expression has no effect".  The alternative way of fixing that warning is to test the return value from sigemptyset(), but that's arguably sillier than the macro.  (Yes, I'm disgruntled about this!)

*The sane variable records the value of the terminal attributes when the program starts — it is set by calling tcgetattr() in stty_raw().  The code ensures that sane is set before activating any code that will call sttr_sane().

*The stty_sane() function resets the terminal attributes to the sane state that was in effect when the program started.  It is used by atexit() and also by the signal handlers.

*The stty_raw() function gets the original terminal attributes, makes a copy of them, modifies the copy to turn off canonical processing (see Canonical vs non-canonical terminal input for more details), and sets the revised terminal attributes.

*Standard C says you can't do much in a signal handler function than set a volatile sig_atomic_t variable, call signal() with the signal number, or call one of the exit functions.  POSIX is a lot more gracious — see How to avoid using printf() in a signal handler? for more details.

*There are two signal handlers, one for SIGALRM and one for the other signals that are trapped.

*The alarm_handler() ignores further alarm signals and records that it was invoked.

*The other_handler() ignores further signals of the same type, resets the terminal attributes to the sane state, and exits with a status used to report that a program was terminated by a signal (see POSIX shell Exit status for commands).

*The getch() function reads a single character from standard input, mapping failures to EOF.  The cast ensures that the return value is positive like getchar() does.

*The set_handler() function uses sigaction() to set the signal handling.  Using signal() in the signal handlers is a little lazy, but adequate.  It ensures that the SA_RESTART bit is not set, so that when a signal interrupts a system call, it returns with an error rather than continuing.

*The dump_string() function writes out a string with any non-printable characters other than space characters reported as a hex escape.

*The main() function sets up the terminal, ensures that the terminal state is reset on exit (atexit() and the calls to set_handler() with the other_handler argument), and sets an alarm for 10 seconds hence.

*The reading loop avoids buffer overflows and stops when the alarm is received or EOF (error) is detected.

*Because canonical processing is turned off, there is no line editing.  The body of the loop provides primitive line editing — it recognizes the erase (usually backspace '\b', sometimes delete '\177') character and the EOF character and handles them appropriately, otherwise adding the input to the buffer.

*When the loop exits, usually because the alarm went off, it null terminates the string and then calls dump_string() to print what was entered.

*If you wanted sub-second intervals, you would need to use the POSIX timer_create(), timer_delete(), timer_settime() (and maybe timer_gettime() and timer_getoverrun()) functions, which take struct timespec values for the time values.  If they're not available, you might use the obsolescent setitimer() and getitimer() functions instead.  The timer_create() step allows you to specify which signal will be sent when the timer expires — unlike alarm() and setitimer() which both send pre-determined signals.

POSIX functions and headers:

Functions
Functions
Headers

alarm()
sigaction()
<ctype.h>

atexit()
sigemptyset()
<signal.h>

exit()
signal()
<stdio.h>

getitimer()
tcgetattr()
<stdlib.h>

isprint()
tcsetattr()
<sys/time.h>

isspace()
timer_create()
<termios.h>

perror()
timer_delete()
<time.h>

printf()
timer_getoverrun()
<unistd.h>

putchar()
timer_gettime()

read()
timer_settime()

setitimer()


text:
Q: why my searchbar is moving with the spinner? I am using laravel 8, Laravel-livewire and tailwind css.
I made this spinner with tailwind animate-spin but when it appears the search bar gets shifted. How to fix this problem?
My code :

    <input wire:model="search" type="text" class="bg-gray-800 text-sm rounded-full w-64 px-4 pl-8 py-1 focus:outline-none focus:shadow-outline" placeholder="Search">

        <svg class="fill-current w-4 text-gray-500 mt-2 ml-2" viewBox="0 0 24 24"><path class="heroicon-ui" d="M16.32 14.9l5.39 5.4a1 1 0 01-1.42 1.4l-5.38-5.38a8 8 0 111.41-1.41zM10 16a6 6 0 100-12 6 6 0 000 12z"/></svg>

        <svg class="absolute animate-spin h-4 w-4 rounded-full bg-transparent border-2 border-transparent border-opacity-50 top-0 right-0 mr-2 mt-2" style="border-right-color: white; border-top-color: white;" viewBox="0 0 24 24"></svg>

    @if(strlen($search) > 2)

                @if ($searchResults->count() > 0)
                    @foreach ($searchResults as $result)

                                @if($result['poster_path'])

                                @else

                                @endif
                                {{ $result['title'] }}

                    @endforeach
                @else

No Result for {{ $search  }}

                @endif

    @endif

Here is a video of the problem
https://streamable.com/61l0ti

A: Try moving the aboslute and other positioning CSS rules to the parent div rather than the svg itself.

  <svg class="animate-spin h-4 w-4 rounded-full bg-transparent border-2 border-transparent border-opacity-50" style="border-right-color: white; border-top-color: white;" viewBox="0 0 24 24"></svg>


text:
Q: Usage of "walking out clean" Is the following sentence grammatically correct?
"I just hope he walks out clean from the probe"
If not, what is the correct form?
EDIT: The context of the above sentence is a situation where you wish someone comes out of an investigation (say, by the police) being acquitted.

A: For reasons I'm not sure I can fully articulate, I would suggest if you insist on using all of those words the following arrangement:

I just hope he walks out from the probe clean.

But I don't think that idiom is necessarily the best-suited expression to go with probe. There are two reasons. First, walks away from, at least to me, is two idioms:

*

*to end negotiations without a deal:

Speaker John Boehner walked away from the debt talks with President Barack Obama.

*

*to survive something:

Canadians walked away from a car crash.

Clearly, you're hoping to use the expression with the latter meaning. But in general, this meaning applies to one-time tragic events or things that you don't have to undergo for a long time.
I take a probe as google defines it as a an investigation into a crime or other matter to refer to something that might take weeks, i.e. an inquiry. Consequently, the image gets kind of mixed -- if you are hoping that he can abandon the probe if a little unclear, then this is fine. If you are hoping that he can survive the probe, the metaphor may not be adequate due to the ambiguity in its meaning. To put it another way,

The investigator walked away from the probe.

is a truly ambiguous sentence. It's caught between whether the investigator is the one pursuing the probe who has given up on its success and whether he is the one being probed in which case he escapes without harm. My sense is that the form possibility is much higher.
As such, I would recommend saying something else:

I hope he makes it through the probe.

Here, I'm assuming that what you want to emphasize is your hope that he survives the ordeal -- not that he can abandon it.


text:
Q: Chrome does not show network traffic of Silverlight RIA services messages after update to version 32.0.1700.76 m Couple days ago Google Chrome automatically updated from version 31.* to version 32.0.1700.76 m. After that happened it does not show in DevTools network traffic request/responses of "application/msbin1" type anymore. These requests are visible in all other browsers' dev tools (FireFox, IE) and in Fiddler, but not in Chrome. Also Chrome's popup menu in this version is very glitchy.
I don't see the way to downgrade Chrome to previous version. Please help I don't want to uninstall Chrome.
Network traffic does not even show resources (XAP file) a page loads.
Example:
http://www.microsoft.com/silverlight/pixel-shader/demo/
This page loads file SilverlightShaderApp.xap, however dev tools of new Chrome's version never shows it in network tab.
I posted the question here, because it's developers question, not just chrome users.
I reported this issue on google chrome forum as well: here.

A: Possibly related bugs:

*

*Issue 173844: Developer tools (Network section) don't show response of requests from flash applications

*Issue 335502:    XMLHttpRequests from Silverlight is not visible in devtools network tab
To avoid the bug, you could downgrade to Chrome 31. A fully offline installer can be downloaded from http://download.oldapps.com/Chrome/31.0.1650.39_chrome_installer.exe.
If you downgrade Chrome, don't forget to disable auto-update. Also, "star" the relevant issues on Chromium's issue tracker so you'll receive email notifications for progress updates. When the issue is fixed, enable auto-update again.
Often, starting a new version of Chrome renders a profile unusable for older Chrome versions ("Your profile can not be used because it is from a newer version of Google Chrome."). When you see such message on start-up, either delete your old profile (don't forget to make a back-up!) (you can also try to delete some files, according to various users, deleting "Web Data" and "Web Data-journal" is sufficient), or launch Chrome with a new profile directory (--user-data-dir=path\to\profile-dir).
For more information on user profiles, see http://www.chromium.org/user-experience/user-data-directory.


text:
Q: NDde loses OnAdvise event after random period I know there is already a question related to this, but still no answer.
NDde server stops getting OnAdvise callbacks after a while
I was study and debug for a long time but still can't find out the problem. It looks like there is no any exception raised from NDde, but it still lost of OnAdvice event for a Client, while some other Clients still still recieve it.

A: I just posted an comment to the link too. You might want to re-initialize the Client object each time it lost of the event.


text:
Q: Simple question on limit of the modulus I know that for real functions, if the limit at infinity of $f$ is a number $l$, then the limit of $|f|$ is $|l|$. Is this true for complex functions too? Thanks.
I'm thinking that if a function vanishes at infinity, then its modulus (distance from origin) also vanishes. And vice-versa. Correct?

A: Yes, and it is true for every function with values in a normed vector space. This follows from the reverse triangular inequality
$$
|\|f(x)\|-\|l\||\leq\|f(x)-l\|.
$$
In other words, the map $y\to \|y\|$ is $1$-Lipschitz, hence continuous.
In particular, if $\lim_{+\infty}f(x)$ exists, then $\lim_{+\infty}\|f(x)\|=\|\lim_{+\infty}f(x)\|$.
Note: in $\mathbb{C}$, replace $\|\cdot\|$ by $|\cdot|$.


text:
Q: ¿Se puede crear un xml en un archivo .xml y la ayuda de php? Buenas comunidad, tengo una duda, he creado una vista xml desde un archivo con extensión .php, pero me gustaría saber si, ¿Puedo replicar lo que he hecho pero desde un archivo .xml?. Muchas gracias de antemano.
    <?php
$html = "";
$url = "https://sports.yahoo.com/soccer/mls/rss.xml?shangrila=1";
$xml = simplexml_load_file($url);

header("content-type: text/xml");
echo('<?xml version="1.0" encoding="UTF-8" ?>');
// $html .= '  <rss version="2.0">'; // si descomentas se verá como un rss
$html .= '    <channel>';
foreach ($xml->channel as $object) {
  $html .='       <title> '.$object->title.' </title>'; // cabecera
  $html .='       <description> '.$object->description.' </description>';

}

  for($i=0; $i<10;$i++){ // cantidad de noticias
  $title = $object->item[$i]->title;
  $link =  $object->item[$i]->link;
  $description = $object->item[$i]->description;
  $pubDate = $object->item[$i]->pubDate;
  $guid = $object->item[$i]->guid;

  $html .='<item>';
  $html .='       <title> '.$title.' </title>';
  $html .='       <link> '.$link.' </link>';
  $html .='       <description>'.$description.' </description>';
  $html .='       <pubDate> '.$pubDate.' </pubDate>';
  $html .='       <guid> '.$guid.' </guid>';
  $html.='</item>';
}
    $html .= " </channel>";
  // $html .= "      </rss>";
//
  echo $html;
  file_put_contents("rss.xml",$html);
 ?>

PD: si quieren ver el código que he creado me hacen saber y lo coloco.


text:
Q: If $\mathcal{T}_1$ and $\mathcal{T}_2$ admit quantifier elimination, does $\mathcal{T}$ admit quantifier elimination? Let $\mathcal{T}_1$ and $\mathcal{T}_2$ be theories with disjoint signatures $\mathcal{L}_1, \mathcal{L}_2$.
Form a new language $\mathcal{L} = \mathcal{L}_1 \cup \mathcal{L}_2 \cup \{P_1, P_2\}$, with $P_1, P_2$ unary predicates. For each sentence $\phi_1 \in \mathcal{T}_1$, convert it to a new sentence $\phi$ over $\mathcal{L}$ by asserting that all of its quantified variables satisfy $P_1$; specifically, replace "$\exists x : \_\_\_$" with "$\exists x : P_1 x \land \_\_\_$" and replace "$\forall x : \_\_\_$" with "$\forall x : P_1 x \to \_\_\_$. Do the same for all sentences in $\mathcal{T}_2$, using the predicate $P_2$. Put all of these sentences into a new theory $\mathcal{T}$ over $\mathcal{L}$. Also add axioms:

*

*$\forall x : \lnot (P_1 x \land P_2 x)$

*$P_1 c$, for each constant symbol $c \in \mathcal{L}_1$, and likewise for $\mathcal{L}_2$;

*$\forall x_1 \ldots x_k : P_1 f(x_1, \ldots, x_k)$, for each $k$-ary function symbol $f \in \mathcal{L}_1$, and likewise for $\mathcal{L}_2$.
Together, all of this makes a theory $\mathcal{T}$ whose models--I think--behave sort of exactly like having a model of $\mathcal{T}_1$ and a model of $\mathcal{T}_2$ separately.
Anyway my concrete question is:

If $\mathcal{T}_1$ and $\mathcal{T}_2$ have quantifier elimination, does $\mathcal{T}$ have quantifier elimination?

which I am unable to prove. Maybe there is a counterexample.

A: Even if a model $M$ of $\mathcal{T}$ has to be a disjoint union of a model $M_1$ of $\mathcal{T}_1$ and a model $M_2$ of $\mathcal{T}_2$ (taking BrianO's comment into account), by definition of an $\mathcal{L}$-structure, it has to interpret the eventual function or relation symbols of both languages, and such symbol in $\mathcal{L}_i$ will range over $M_{3-i}$ as well. Corresponding formulas (without the specification of $P_i x$ at each instance of a quantifier symbol) may hardly be reduced to quantifier-free formulas modulo $\mathcal{T}$ since $\mathcal{T}$ says nothing about how for instance $f \in \mathcal{L}_1$ behaves for $\overline{x} \in M_2$.

For instance let $\mathcal{T}_1$ be the theory of algebraically closed fields of characteristic $0$ and $\mathcal{T}_2$ be the theory of dense linear orders without extrema. They have quantifier elimination in respectively $\left\langle +,.,-,\ ^{-1},0,1 \right\rangle$ and $\left\langle < \right\rangle$.
Now, $\mathbb{C} \uplus \mathbb{Q}$ * can be made into a model of $\mathcal{T}$ by seing $\mathbb{Q}$ as a subfield of $\mathbb{C}$ and defining the laws $+,.,-,\ ^{-1}$ accordingly, and stating that they range in $\mathbb{C}$ only. Now to interpret $<$, state:
-either that $\mathbb{C} < \mathbb{Q}$, no element of $\mathbb{Q}$ is inferior to an element of $\mathbb{C}$, $<$ behaves as usal on $\mathbb{Q}$ and is always verified in $\mathbb{C}$. This gives a model $M$.
-or that $\mathbb{Q} < \mathbb{C}$, no element of $\mathbb{C}$ is inferior to an element of $\mathbb{Q}$, $<$ behaves as usal on $\mathbb{Q}$ and is always verified in $\mathbb{C}$. This gives a model $M'$.
Mind that this definition of $<$ has nothing in common with the regular one (except when restricted to $\mathbb{Q}$), but that this is allowed by your conditions.

Let $\varphi$ be the sentence $\forall x (\exists y (P_2 y \wedge x.x < y))$.
$M \vDash \varphi$ since for $x \in \mathbb{Q} \uplus \mathbb{C}$, $x.x \in \mathbb{C}$ and $\mathbb{C} < \mathbb{Q}$, so take $y = 0 \in \mathbb{Q}$.
$M' \vDash \neg \varphi$ since for $x \in \mathbb{Q} \uplus \mathbb{C}$, $x.x \in \mathbb{C}$ and no element of $\mathbb{C}$ is inferior to an element of $\mathbb{Q}$.
Now let's assume $\varphi$ is equivalent to a quantifier-free $\mathcal{L}$-sentence molulo $\mathcal{T}$, that is (equivalent to) a disjonction of conjonctions of formulas of the type $q < 0$, or $\neg(q < 0)$ or $q = 0$ or $q \neq 0$ where $q$ is a rational number in $\mathbb{C}$.
Then it is equivalent in $M$ and $M'$ to just those of the form $q = 0$ or $\neg(q < 0)$ or $q \neq 0$ since two complex numbers (distinct or not) are inferior to one another in $M$ and $M'$, therefore $\varphi$ is true in $M$ iff there is no instance of a $\neg(q < 0)$ and all appearing in the form $q = 0$ $q$ are indeed zero while those appearing in the form $q \neq 0$ are non-zero. This is the same for $M'$, so $\varphi$ is true in $M'$ iff it's true in $M$ which contradicts the previous claim.
*$A \uplus B := (A \times \{0\}) \cup (B \times \{1\})$ so in my anwser and from the definition on, $\mathbb{C}$ means $\mathbb{C} \times \{0\}$ and $\mathbb{Q}$ means $\mathbb{Q} \times \{1\}$


text:
Q: Some problems with the confirmation of the urls in Django views My models:
Story:
categories = models.ManyToManyField(Category)

Category: name | slug
My urls:
(r'^(?P<cat_slug>.*)/$', 'news.views.archive_category'),

And in views, I use:
def archive_category(request, cat_slug):
    entry = News.objects.get( categories__slug=cat_slug )
    return render_to_response('news_archive_category.html', {'entry':entry, })

It has something wrong if I have a story of two or more category. Please help me. Many thanks!

A: What do you want to happen in this circumstance? Are you trying to show a list of all the entries in a category, or just one?
News.objects.get() will always get a single item, or raise an exception if there are more than one matching the criteria. Either you should use filter() instead, passing a QuerySet to the template, so you'll need to iterate through; or, add a criteria to your urlconf so that you get the specific entry slug as well, so you only get one object.

A: category = Category.objects.filter(slug=cat_slug)#get the category requested
#now get all the entries which have that category
entries = News.objects.filter(categories__in=category)#because of the many2many use __in

edited after comment


text:
Q: Base class overload I have a base class for application's entities:
public class LadderEntityBase : ICloneable
{
    public Guid PK { get; set; }
    public string Name { get; set; }
    public string Comment { get; set; }

    public object Clone()
    {
        return this.MemberwiseClone();
    }
}

Then two classes derive from it, with same functionality overload, which allows to create those classes with or without PK (Guid) parameter. If PK parameter omitted - new Guid will be created:
public class Order : LadderEntityBase
{
    public Order() : this(Guid.NewGuid())
    {
    }

    public Order(Guid guid)
    {
        this.PK = guid;
    }

    public string OrderFrom { get; set; }
}

and
public class Parcel : LadderEntityBase
{
    public Parcel() : this(Guid.NewGuid())
    {
    }

    public Parcel(Guid guid)
    {
        this.PK = guid;
    }

    public string SentTo { get; set; }
}

Is it possible to move Order's and Parcel's both constructors into the base class?

A: I believe its as far as you can go. Move all logic in base class and leave just base calls in inherited
public class LadderEntityBase : ICloneable
{
    public LadderEntityBase(Guid pk)
    {
        PK = pk;
    }

    public LadderEntityBase() : this(Guid.NewGuid())
    {
    }

    public Guid PK { get; set; }
    public string Name { get; set; }
    public string Comment { get; set; }

    public object Clone()
    {
        return this.MemberwiseClone();
    }
}

public class Order : LadderEntityBase
{
    public Order() : base()
    {
    }

    public Order(Guid guid) : base(guid)
    {
    }

    public string OrderFrom { get; set; }
}

public class Parcel : LadderEntityBase
{
    public Parcel() : base()
    {
    }

    public Parcel(Guid guid) : base(guid)
    {
    }

    public string SentTo { get; set; }
}

A: You can set the PK on Base class itself and then use base keyword to set the GUID(if you want different GUIDs for both derived classes).
public class LadderEntityBase : ICloneable
    {
        public Guid PK { get; set; }
        public string Name { get; set; }
        public string Comment { get; set; }
        public LadderEntityBase(Guid guid)
        {
            this.PK = guid;

        }

        public object Clone()
        {
            return this.MemberwiseClone();
        }
    }

    public class Order : LadderEntityBase
    {
        public Order() : this(Guid.NewGuid())
        {
        }

        public Order(Guid guid) : base(guid)
        {

        }

        public string OrderFrom { get; set; }
    }

    public class Parcel : LadderEntityBase
    {
        public Parcel() : this(Guid.NewGuid())
        {
        }

        public Parcel(Guid guid) :base( guid)
        {

        }

        public string SentTo { get; set; }
    }


text:
Q: Issues sorting by Date in a CRM report built using FetchXML I am creating a few custom reports in CRM using FetchXML for the data source.  All of the reports are to be sorted by the CreatedOn attribute:
<order attribute="createdon" descending="true" />

In the actual reports, I also have the both the Tablix (and Groups if applicable) sorted by CreatedOn Desc. This works but with one major drawback:  The dates are being sorted as if they were strings.
The dates are sorted starting with September them moving back to January:  9, 8, 7, 6, 5, 4, 3, 2, 12, 11, 10 and finally 1.  September 9, 2015 is displayed before September 8, 2016. (string 9/9 > 9/8)
I applied expressions to convert the values to dates but that didn't work either:
=CDate(Fields!createdon.Value)

Any suggestions on getting the report to sort by actual dates and not as the strings?

A: Sounds like your CDate is not able to convert the string.
As a test, try this:
=Format(CDate(Fields!createdon.Value),"yyyyMMdd")

If it looks the same, it is still being treated as a string.  You may have some invalid characters in the text that is preventing the conversion to date.  Is there any way you can classify the data type of the attribute in the XML?

A: Since it was bringing back the field as a string, I added a new Calculated Field (CreatedOnDATE) to the data set.
I set the calculated field with the CDate:
=CDate(Fields!createdon.Value)

Then I simply changed the sort order to use the new CreatedOnDATE field and it worked like a charm.  It just took a good night sleep and a fresh perspective.


text:
Q: How to position a car in image processing (computer vision)? I would like to locate a car (front center point x,y) using a high resolution single camera. The camera setup is fixed at 1-2m high, and tilted around 25 degrees. The camera can provide images in where the front side of the car is visible. The intrinsic and extrinsic parameters are known.
So far, I tried to detect the headlights and number plates. Issues... Headlights are not detected as blobs all the time. The shape of the headlights are changing depending on the distance. Also, the number plate is not visible in the dark.
Is there a robust algorithm to detect a car? or to detect headlights? or detect number plate?How could I proceed?
Thanks in advance,

A: Are you detecting the same car everytime? If yes, then presumably the appearance remains consistent. Rather than detect and recognise blobs and shapes, you may be better off using scale and rotation invariant features combined with a machine learning algorithm. Look into the SIFT and SURF feature descriptors. For easy experimentation, use OpenCV's implementation of feature description and matching. Take a look at this example.

A: This is not an easy problem because of the change in the scale and point of view. Ideally, you would need a collection of training images with the car seen from different points of view to match later some of them to your input image. Then, you need local features (SIFT, SURF) or some classifier to decide on the match.
On the other hand, if you are tracking the same car all the time, check out the MeanShift algorithm. The problem is you need an initial position to carry on with the tracking.


text:
Q: Popover image gallery not working in iPad iOS Swift Recently my app has rejected from App Review because I wasn't using Popover.
then I changed my coding into following. but still I'm not getting popup window in simulator.
Always getting normal iPhone photo choosing method and it makes app crash.
Also its not even printing "working".
 @IBAction func chooseGallery(sender: UIBarButtonItem) {

    imagePicker.sourceType = .PhotoLibrary

  //imagePicker.modalPresentationStyle = .Popover
  //presentViewController(imagePicker, animated: true, completion: nil)//4
  //imagePicker.popoverPresentationController?.barButtonItem = sender

    if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
        self.presentViewController(imagePicker, animated: true, completion: nil)
    }
    else {
        println("Working")// to test this part

        imagePicker.modalPresentationStyle = .Popover
        presentViewController(imagePicker, animated: true, completion: nil)//4
        imagePicker.popoverPresentationController?.barButtonItem = (sender)

        imagePicker.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.Up
        imagePicker.popoverPresentationController?.sourceRect = CGRect(x: 150, y: 150, width: 0, height: 0)
     }
}

A: Your code works fine for me with some modifications, In the following example I going to present a Popover only for iPad just like you.
@IBAction func showNextViewController(sender: UIBarButtonItem) {

    let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
    let nextViewController = storyBoard.instantiateViewControllerWithIdentifier("NextViewController") as! NexViewController

    if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
        self.presentViewController(nextViewController, animated: true, completion: nil)
    }
    else {
        nextViewController.modalPresentationStyle = .Popover
        presentViewController(nextViewController, animated: true, completion: nil)

        if let popover = nextViewController.popoverPresentationController {
            popover.barButtonItem = sender
            popover.permittedArrowDirections = UIPopoverArrowDirection.Up

            // to set it size
            nextViewController.preferredContentSize = CGSizeMake(200,500)
        }
    }
}

Because I don't know the class of UIViewController you're trying to present I just made one myself without nothing inside, and I instantiate it in the @IBAction to avoid keep references to it (is just for test purposes).
Just some observations:

*

*When you're going to present popovers you need to set only one of the two follwoing:

*

*barButtonItem

*sourceView, sourceRect
In the above example just like you set the barButtonItem you don't need anything more.
I hope this help you.

A: try this,
picker.modalPresentationStyle = .CurrentContext


text:
Q: WebDAV and Exchange Server - get contacts modified within the last X days? I have a PHP application which connects to Microsoft Exchange server to retrieve 'Contacts' via WebDAV.
Is there a WebDAV query I can issue to Microsoft Exchange to get only contacts that have been changed or added within the last X days?
It'd be a bit easier to deal with than querying for all 30 bajillion contacts every time and doing the check/update/insert thing for every record.

A: You might want to check out the excellent examples at this website. http://www.troywolf.com/articles/php/exchange_webdav_examples.php. They're great reference on how to access Exchange via WebDAV using PHP. He even has one on searching for contacts, http://www.troywolf.com/articles/php/exchange_webdav_examples.php#search_contacts, but doesn't mention the exact field that contains the field you're interested in constraining on, so I'll help you out.
Searching the Exchange store (http://msdn.microsoft.com/en-us/library/aa123573(EXCHG.65).aspx) is a great starting place. What you're looking for specifically is Specify a Date range http://msdn.microsoft.com/en-us/library/aa123600(EXCHG.65).aspx which spells out the syntax for using the dav:creationdate field.
There's more information on the DAV namespace here http://msdn.microsoft.com/en-us/library/aa565717.aspx as well.
Good luck!


text:
Q: Java Serialization without external dependency? Is there a way to serialize Java object in any common formats like JSON, XML, YAML, etc. Without external dependency?
Or, with minimal single-file code that could be easily copy-pasted as a dependency?
The serialisation could be very simple, just walking on simple object/array tree and saving it into any text-based representation, without any configs or custom options.
P.S.
It should be automatic, not writing JSON manually or with XMLBuilder etc.


text:
Q: Stack overflows although there is enough memory available In my class our teacher wanted us to write a quicksort algorithm in C which will work on an array of 10000 int. My friends and I have written the code as seen on pseudocode.
It works okay when sorting a random valued array but when sorting sorted array code crashes as seen.
Unhandled exception at 0x00FF2509 in ConsoleApplication1.exe: 0xC0000005: Access violation writing location 0x00330F58.

Now I've searched for it a bit and found out that linker gives 1MB of stack for recursive functions (I might have gotten it wrong though). So with 4-byte integer variables (will be 4x10k of them when sorted array is being sorted again) and a 10k int referenced array, it all should take about 200KB of the stack.
So I couldn't find out why I get this error. Teacher told us that it was (of course) possible to write that code as the pseudocode. So either I'm doing something wrong on code, else I have no idea.
Can anyone please help explain what's wrong?
void quicksort_last(int *A,int p,int r){

if(p<r){
    int q=partition(A,p,r);
    quicksort_last(A,p,q-1);
    quicksort_last(A,q+1,r);
}
}

int partition(int *A,int p, int r){
const int x=A[r];
int i=p-1;
int j=p;
int temp;

while(j<r){
    if(A[j]<=x){
        i++;
        temp=A[i];
        A[i]=A[j];
        A[j]=temp;
    }
    j++;
}
temp=A[i+1];
A[i+1]=A[r];
A[r]=temp;
return i+1;
}

Edit:
This is the error debug gives. Debug stops about 4000th recursion at the beginning of partition function. Remainder of the code is here.

Unhandled exception at 0x00BF2509 in ConsoleApplication1.exe: 0xC00000FD: Stack overflow (parameters: 0x00000001, 0x002B2FA8).

A: Why do you think of stack limitation if your exception states access violation? There surely is a bug in your code which results in that you write to forbidden memory, which doesn't belong to your application. Did you run in a debugger? It should tell you at least in which iteration the error occurs.

A: Synopsis
Your transcription and implementation of the algorithm seems to be OK; it works for me without problems.
You need to scrutinize you driver code to make sure you aren't overstepping the bounds of any of your arrays.  The chances are that you will find a problem in that driver code.
Analysis
Having worked a bit with the sort and partition code you show, I don't think there's a major problem with it.  I used the following test case, but was testing on Mac OS X 10.9 with GCC 4.8.2.  It was compiled with -std=c11 (amongst other options stringent options), and uses two features — the 'declare variables in for loops feature and the 'declare variables when needed' feature — that were added to C99.  You can fix those straight-forwardly if you don't use a C99-capable compiler.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

static void dump_partition(char const *tag, int *array, int lo, int hi)
{
    if (lo < hi)
    {
        int i;
        printf("%s: %d..%d\n", tag, lo, hi);
        for (i = lo; i <= hi; i++)
        {
            printf(" %4d", array[i]);
            if ((i - lo) % 10 == 9)
                putchar('\n');
        }
        if ((i - lo) % 10 != 0)
            putchar('\n');
    }
}

static int partition(int *A, int p, int r)
{
    const int x=A[r];
    int i=p-1;
    int j=p;
    int temp;

    while (j < r)
    {
        if (A[j] <= x)
        {
            i++;
            temp=A[i];
            A[i]=A[j];
            A[j]=temp;
        }
        j++;
    }
    temp=A[i+1];
    A[i+1]=A[r];
    A[r]=temp;
    return i+1;
}

static void quicksort_last(int *A, int p, int r)
{
    if (p < r)
    {
        int q=partition(A, p, r);
        printf("quicksort: %p (%d..%d)\n", (void *)&q, p, r);
        //dump_partition("L-part", A, p, q-1);
        //dump_partition("R-part", A, q+1, r);
        quicksort_last(A, p, q-1);
        quicksort_last(A, q+1, r);
    }
}

int main(void)
{
    int data[] =
    {
        31, 14, 53, 45, 88,  0, 79, 59, 84,  5,
        83, 42, 61, 38, 24, 47, 86, 69,  8, 36,
    };
    enum { N_DATA = sizeof(data) / sizeof(data[0]) };

    dump_partition("Random", data, 0, N_DATA-1);
    quicksort_last(data, 0, N_DATA-1);
    dump_partition("Sorted", data, 0, N_DATA-1);

    enum { BIG_SIZE = 10000 };
    int data2[BIG_SIZE];
    srand(time(0));
    for (int i = 0; i < BIG_SIZE; i++)
        data2[i] = rand() % BIG_SIZE;

    dump_partition("Random", data2, 0, BIG_SIZE-1);
    quicksort_last(data2, 0, BIG_SIZE-1);
    dump_partition("Sorted", data2, 0, BIG_SIZE-1);

    return 0;
}

The dump_partition() function allows me to monitor what's in the partitions.  When the commented out ones in quicksort_last() were active, it allowed me to see that the partitioning was working correctly.  The printf() that prints the address of q gives a measure of stack depth.  On my machine, the output from running:
qs | grep quicksort: | sort -u -k2,2

was:
quicksort: 0x7fff555f66f0 (3962..3963)
quicksort: 0x7fff555f6730 (3961..3963)
quicksort: 0x7fff555f6770 (3961..3965)
quicksort: 0x7fff555f67b0 (1214..1215)
quicksort: 0x7fff555f67f0 (1197..1198)
quicksort: 0x7fff555f6830 (1151..1152)
quicksort: 0x7fff555f6870 (1150..1152)
quicksort: 0x7fff555f68b0 (865..867)
quicksort: 0x7fff555f68f0 (435..436)
quicksort: 0x7fff555f6930 (433..436)
quicksort: 0x7fff555f6970 (20..21)
quicksort: 0x7fff555f69b0 (20..22)
quicksort: 0x7fff555f69f0 (20..23)
quicksort: 0x7fff555f6a30 (20..28)
quicksort: 0x7fff555f6a70 (20..29)
quicksort: 0x7fff555f6ab0 (20..30)
quicksort: 0x7fff555f6af0 (1..2)
quicksort: 0x7fff555f6b30 (1..4)
quicksort: 0x7fff555f6b70 (0..4)
quicksort: 0x7fff555f6bb0 (0..6)
quicksort: 0x7fff555f6bf0 (0..11)
quicksort: 0x7fff555f6c30 (0..18)
quicksort: 0x7fff555f6c70 (0..93)
quicksort: 0x7fff555f6cb0 (0..138)
quicksort: 0x7fff555f6cf0 (8..9)
quicksort: 0x7fff555f6d30 (7..9)
quicksort: 0x7fff555f6d70 (3..4)
quicksort: 0x7fff555f6db0 (0..1)
quicksort: 0x7fff555f6df0 (0..5)
quicksort: 0x7fff555f6e30 (0..19)

The maximum stack depth was:
  0x7fff555f6e30
- 0x7fff555f66f0
  --------------
  0x000000000740

which is less than 2 KiB.  There are 28 levels on the stack.  That's with the random data (the code shown).  When I revised the code to sort the already sorted data, then the stack used was a lot greater — as I noted in a comment, that leads to very bad behaviour in the partitioning.

If your input data is already sorted, choosing the first element of the sub-array as the pivot value leads to quadratic sorting and very deep recursion. It is better to choose a pivot at random, or use Median of Three, or related techniques.

There were 9999 levels on the stack, and difference in the stack positions was:
  0x7fff5d0bde30
- 0x7fff5d021ab0
  --------------
  0x000000013074

However, that's still less than 80 KiB of stack space used (in the sorting code; the space for the arrays is extra, but that's a known quantity, and roughly 40 KiB).  None of these sizes should stress an ordinary machine.
Consequently, I have to diagnose that the problem is not the code you showed in the question.  This surprisingly often turns out to be the case.
You can verify this by taking my driver code (main() and maybe the dump_partition() function) and running that with your quicksort_last().  You should find similar results to what I got.  If that's the case, you can start working on your driver code.  I took a look at it and decided I didn't want to scrutinize it — indeed, the code originally posted does not compile at all for me.  It also seems to have large swathes of repeated code, which is always a bad sign.  When I did enough work to get it to compile warning-free (which meant printing out the carefully calculated times, in large part, but there were other problems too), then the output I got was:
 0.000787
 0.156366
 0.000001
 0.031464
 0.000001
 0.040427
 0.001198
 0.597619
 0.000001
 0.121826
 0.000000
 0.159727
 0.001914
 1.335059
 0.000001
 0.275667
 0.000002
 0.358740
 0.002504
 2.381662
 0.000000
 0.487816
 0.000000
 0.645867

This was printing the time using %13.6f as the format string.  Again, it did not crash on Mac OS X 10.9.  I did not measure stack usage in this code.

A: Well, the last thing i did was the first thing i should've done(as usual)
void plusplus(int a){
    printf("%d\n",a);
    plusplus(a+1);
}

int main(){
    plusplus(0);
    return 0;
}

When i run this code, it cracks around 4700th recursion. So i am getting that, either the 1 mb stack is filled in 4700th depth or there is a limitation(which i doubt).
Thanks for your time and help everyone ;)


text: Q: Как быстрее обходить список (ArrayList) и вставлять в него элементы? Через ListIterator или созданием нового списка? Есть следующая задача: имеется цикл по спискам элементов (ArrayList), содержащим в среднем около 15 элементов. Каждый раз мы вставляем в этот список примерно 1-2 элемента, причём в неопределенное место списка (т.е. может быть и начало, и конец, и середина). И в итоге нужно создавать копии этих списков и сохранять отдельно. Вижу 2 основных подхода: использование ListIterator - создание в цикле копии списка и вставка прямо по ходу цикла. И второй - создание нового списка и добавление в него по очереди всех элементов, в том числе и новых. С одной стороны, вставка в новый список будет занимать константное время, но возможны затраты на расширение массива, а ListIterator двигает элементы в массиве, которые находятся правее вставляемого. Но при этом часто слышу мнение, что нужно использовать Iterator. Как всё таки быстрее?


text:
Q: Deleting documents from PouchDB vs keeping them when the user logs out or closes the app I am developing an single page application that relies on PouchDB for storing state when a user logs in with the app. My application state consists in user data such as email address, first name, etc.
I am new to PouchDB and the concept of storing data in the browser. I am wondering what the best practices are when dealing with issues such as deleting/purging data from PouchDB for a given user...
What are the pros and cons of keeping data/documents in PouchDB/IndexedDB (versus deleting it) when the user signs out or closes and leaves the SPA?
In other words, what would be example use cases of keeping the data and use cases for deleting it upon user log out?

A: This mostly comes down to user experience versus freshness of data.
PouchDB is meant to allow an app to keep data locally and sync it with a backend system. (CouchDB and Couchbase are both currently supported, as examples of backend servers.)  It's also designed to allow multiple clients to make changes.
Most databases expect high-availability of a central system.  They are designed to resolve conflicts immediately.  With PouchDB you expect conflicts that may not be resolved at client write time.
The core idea is that your app will be used with poor or no network connectivity at times.  Keeping information locally means your application can continue to work, even in these situations.
The main tradeoffs:
Keep

*

*App may still provide useful functionality w/o network connectivity

*Faster response times

*Reduce data transfers across network (avoid resending all data for each invocation)

*May need to pay attention to conflict resolution

*May store excessive amounts of data locally

Delete/Purge

*

*App can't meaningfully function offline

*App needs to guarantee users only sees updated data

*App uses unacceptable amount of storage

Note PouchDB is a NoSQL database.  NoSQL databases can't enforce "ACID" compliance.  This means if your app needs data changes to be atomic (transactional), this is the wrong solution.
There are plenty of use cases where eventually consistent data is fine.  This can be as simple as having a single client and the backend system "agree" on what's correct.  Or it can be a complex system with multiple writers making changes that eventually propagate and get integrated.
There's also security to consider.  Will you give the user a way to remove sensitive data in case they're on a shared machine, that sort of thing.
As a final note, you might want to search for 'offline first' as an approach to app development.

A: Typical use cases of deleting data once the user logs out might be:

*

*Deleting authentication tokens: Once the user logs out, any authentication token will become invalid. No need to store them anymore.

*Deleting personal or sensitive data: PouchDB stores it's data in IndexedDB or WebSQL, depending on the browser you're using. As you already found out, data stored there is available "across sessions and browser tabs/windows, within a particular device." Source
Therefore you want to keep personal or sensitive data as short as possible.

Note: At best you do not need to store data like mentioned above in PouchDB but this is beside the point.
Use cases for keeping data after log out:

*

*Keep anything else: Well it depends on your application but if your data is not sensitive, why not store it? Building a offline first app is all about not having to fetch all your data from a remote database so...
Only limitation is the storage of the device you're running on and the user's goodwill. Of course this again depends on your application, but you might want to make sure, you're not using up Megabytes of storage for a simple app.


text:
Q: RealSense R200 crashes with high color resolution and low depth resolution I'm currently working on a program that uses both color and depth streams of the Intel RealSense R200. I want to use the lowest depth resolution 240p, since it has less noise than higher resolutions. However, when using it in combination with a 1080p resolution for the color stream, the sensor suddenly stops acquiring frames for some reason.
In detail, the method PXCSenseManager::AcquireFrame() at some points blocks for about 10 seconds before returning with error code -301 (i.e. "Execution aborted due to errors in upstream components").
Higher depth resolutions or lower color resolutions seem to work fine, but resulting either in more noise for the depth data or less quality for the color data. This problem occurs not only within my code, but also in the official RSSDK, namely DF_RawStreams and DF_CameraViewer.
Has anyone of you experienced the same problem and if yes, do you know a way to solve it? Unfortunately I haven't yet been able to find anything dealing with this kind of problem.
My PC has following specs:

*

*Motherboard:

*

*Mouse Computer Ltd. H110M-S01

*CPU:

*

*Intel® Core™ i7-6700 CPU @ 3.40GHz

*Memory:

*

*16GB RAM DDR3

*Graphics card:

*

*NVIDIA GeForce GTX 980 4GB GDDR5

Thank you very much in advance
PS: It's my first question to ask on StackOverflow, so I'd appreciate any feedback :) Thank you!

A: I got a reply in the Intel forum that says:

Are you using Windows 10 Anniversary Update? It may be because of a bug in that causing some cameras to crash. Try running your app on a PC which hasn't updated in the last few weeks. Unfortunately, I'm not aware of any current fixes. Apparently, Microsoft are planning on pushing another update which fixes this issue (amongst others) sometime in September.

When checking other PCs that haven't been applied the Anniversary update, the software worked well without any crash. I guess I should wait for Microsoft to provide a patch that fixes the camera crash issue.
However, please feel free to reply, if you have got anything to comment regarding this problem :)


text:
Q: displaying multiple lines of a file, never repeating i need to, for every ten lines, echo them in a div.
example:

line 1
line 2
...
line 9
line 10

line 11
line 12
...
line 19
line 20

does anyone know a way to do this?
array is from file(), so its lines from a file.

A: This should work:
$blocks = array_chunk(file('path/to/file'), 10);
foreach($blocks as $number => $block) {
    printf('
%s
',
            $number+1,
            implode('
', $block));
}

References:

*

*array_chunk()

*printf()

A: echo '
';
$lineNum = 0;
foreach ($lines as $line) {
    if ($lineNum && !($lineNum % 10)) {
        echo '

';
    }
    echo $line."
";
    $lineNum++;
}
echo "
";

A: With a quick google search:
http://www.w3schools.com/php/php_file.asp
Reading a File Line by Line
The fgets() function is used to read a single line from a file.
Note: After a call to this function the file pointer has moved to the next line.
Example from W3 Schools:
The example below
reads a file line by line, until the end of file is reached:
<?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
  {
  echo fgets($file). "
";
  }
fclose($file);
?>

All you need to do is have your counting variable that counts up to 10 within that while loop. once it hits 10, do what you need to do.

A: Assuming your lines are in an array that you're echoing, something like this would work:
$count = 0;
$div = 1;
foreach($lines as $line){ //or a for loop, whatever you're using
  if(0 == $count){
    echo "
";
  }

  $count++;
  echo $line;

  if(10 == $count){
    echo "
";
    $count = 0;
  }
}


text:
Q: resignFirstResponder() didn't work for Date Picker I have a very simple CustomIDatePicker class written in Swift 5, which has a toolbar on top that contains a 'Done' button. The issue is, the keyboard never retracted when this button was pressed. I have tried 4 different methods, please see details below:
import UIKit

class CustomDatePicker: UIDatePicker {

    var zTextField: UITextField!

    let toolbar = UIToolbar()

    convenience init(textField: UITextField) {
        self.init()

        // bar buttons
        let doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(donePressed(sender:)))

        toolbar.sizeToFit()
        toolbar.setItems([doneBtn], animated: true)

        self.datePickerMode = .date

        // link up the Text Field
        zTextField = textField
        zTextField.inputAccessoryView = toolbar
        zTextField.inputView = self
    }

    @objc func donePressed (sender: UIBarButtonItem) {
        print("done pressed") // this line appeared in the debugger

        //self.resignFirstResponder()
        //self.inputView?.resignFirstResponder()
        //self.endEditing(true)
        self.inputView?.endEditing(true) // tried all of these 4, but keyboard always remained in view
    }
}

A very simple ViewController to test this class:
class ViewController: UIViewController {

    @IBOutlet weak var theTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        let datePicker = CustomDatePicker(textField: theTextField)
    }
}

Any help would be greatly appreciated!

A: Implement UITextField delegate function
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
  return false
}
@objc func donePressed (sender: UIBarButtonItem) {
        print("done pressed")

        self.zTextField.resignFirstResponder() // new line
    }


text:
Q: how to stop time in pygame to wait for input? here's what I want to do: I want to stop the time in pygame so that the player of my game can press 'enter' when they are done reading the dialog, and then the time can start running again.
however, when I try to do that, the program does nothing when I press the enter button. moreover, it crashes my program when I try to close it. I have been trying out everything I know, and when I couldn't figure it out I decided to come here to ask for help. here's my code for the first cutscene:
# time setup
    realtime = int(pygame.time.get_ticks() / 1000)

    # animations start here
    # cutscene 1
    if draw_scene_1:
        screen.blit(frame_0, (0, 0))
        pygame.draw.rect(screen, (0, 0, 0), (0, 0, 320, 480), 15)
        if realtime >= 1:
            loading(337, 99)
        fadein()
        if realtime <= 9 and realtime >= 3:
            channel1.play(pygame.mixer.Sound('missions\call.ogg'))
            time.sleep(9)
        elif realtime >= 9:
            screen.blit(frameE_0, (320, 0))
            pygame.draw.rect(screen, (0, 0, 0), (320, 0, 320, 480), 15)
        if realtime >= 12.5:
            screen.blit(dialE, (45, 300))
            textbox("hello?", 65, 340)
        if realtime >= 14:
            textbox("who is this?", 125, 340)
        if realtime >= 14:
            textbox("press enter to continue...", 330, 420)
        if realtime .= 15:
            pause(True)
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN and realtime >= 13:
                if event.key == pygame.K_RETURN:
                    pause(False)
                    draw_scene_2 = True

and here's the def code for the pause function:
    def pause(bool):
    while bool == True:
        pygame.time.wait(1000)

Any help would be appreciated.