text:
Q: Making HTTP Get call upon button press in android I am totally new to android and trying to develop a basic application. I have used the default Navigation Drawer Activity from android while creating the project.
Basically, I am getting an exception when I am making an HTTP get req upon a button click. I have created a button that is all working fine. The button is created inside the HomeFragment.java.
Here is the code -
   final Button button = root.findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
           // new ApiCall("637", "22-05-2021", textView).start();
            try {
               // String finalUrl = address+"district_id="+this.district_id+"&date="+this.date;
                URL url = new URL("https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/findByDistrict/?district_id=637&date=22-05-2021");
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("GET");
                con.setRequestProperty("User-Agent", "PostmanRuntime/7.26.10");
                con.setRequestProperty("Accept-Language", "en_US");
                con.setRequestProperty("Content-Type", "application/json");
                con.setRequestProperty("Accept", "application/json");

               //Exception
                BufferedReader in = new BufferedReader(new InputStreamReader( con.getInputStream())); // here exception coming////////////////////

                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    System.out.println(inputLine);
                }
                in.close();
            } catch(MalformedURLException e) {
                System.out.println("Malformed URL: " + e.getMessage());
                textView.setText("Malformed");

            } catch(IOException e) {
                System.out.println("IOException: " + e.getMessage());
                textView.setText("Exception");

            }
            catch (Exception e){
                textView.setText("Exception");
                e.printStackTrace();
            }

        }
    });

This code of calling HTTP get req is all working fine when I do it purely in java in IntelliJ Idea.
I don't know why am I getting exceptions here.
Let me know
Thanks,
Akhi

A: As @Bhardwaj suggested, you can't make network calls in the main thread in Android. Create a background thread like this:
class RetrieveRemoteData extends AsyncTask<String, Void, YourResponseModelClass> {

    private Exception exception;

    protected YourResponseModelClass doInBackground(String... urls) {
        // new ApiCall("637", "22-05-2021", textView).start();
            try {
               // String finalUrl = address+"district_id="+this.district_id+"&date="+this.date;
                URL url = new URL("https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/findByDistrict/?district_id=637&date=22-05-2021");
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("GET");
                con.setRequestProperty("User-Agent", "PostmanRuntime/7.26.10");
                con.setRequestProperty("Accept-Language", "en_US");
                con.setRequestProperty("Content-Type", "application/json");
                con.setRequestProperty("Accept", "application/json");

               //Exception
                BufferedReader in = new BufferedReader(new InputStreamReader( con.getInputStream())); // here exception coming////////////////////

                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    System.out.println(inputLine);
                }
                in.close();
            } catch(MalformedURLException e) {
                System.out.println("Malformed URL: " + e.getMessage());
                textView.setText("Malformed");

            } catch(IOException e) {
                System.out.println("IOException: " + e.getMessage());
                textView.setText("Exception");

            }
            catch (Exception e){
                textView.setText("Exception");
                e.printStackTrace();
            }

        }
    }

    protected void onPostExecute(YourResponseModelClass responseObject) {
        // write your code here what happens after getting response or exception
    }
}

You can refer to this, this has a lot of detailed steps for your use case.
Additionally, try to include more details to your question like what exceptions are you getting to be more descriptive about your issues so that the contributors understand your question better and suggest you accurate solutions.


text:
Q: React-Native-Popup-Menu with FloatingActionButton Component cannot trigger with MenuTrigger I would like to use react-native-popup-menu and react-native-floating-action-button components together. I've tried :
<MenuTrigger>
    <FloatingActionButton
        size={56}
        textDisable
        iconName="directions"
        iconType="material-icons"
        shadowColor="#000"
        iconColor="white"
        backgroundColor="#405914"
    />
</MenuTrigger>

This code does not trigger the MenuTrigger because FloatingActionButton's onPress is triggered.

I also tried this kinds of stuff :
<MenuTrigger customStyles={{ TriggerTouchableComponent: FloatingActionButton }} />

This one's trigger is working with MenuTrigger but I cannot customize the FAB button's styling.
Can you provide me a solution ?  :)
Thank you

A: According to doc you could use triggerTouchable.
      <MenuTrigger
        customStyles={{
          TriggerTouchableComponent: Button,
          triggerTouchable: { title: 'Select (Custom Touchables)' },
        }}
      />

A: Using react-native-popup-menu version 0.15.12 I am able now to achieve this with
<MenuTrigger>
  <MyCustomButtonComponent>
    <Icon ...>
  </MyCustomButtonComponent>
</MenuTrigger>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Adding Hyperlinks in a richtextbox that activate a method instead of a webpage Specifically, im looking for a way to add links to all the words in my (rich)textbox that start with #. so, if my richTextBox1.Text property equaled "This is an #example of what i want" i would want "#example" to be highlighted. and if its clicked, id want to add a context menu for right click, and just on left click id want it to trigger a void in my program, with the text that was clicked.

A: Have a look at the following CodeProject article:
Links with arbitrary text in a RichTextBox
http://www.codeproject.com/KB/edit/RichTextBoxLinks.aspx
The code in this article will allow you to insert arbitrary text links into your RichTextBox.  When the text link is clicked, the LinkClicked event will fire, and the LinkLabelLinkClickedEventArgs will contain the text of the link you clicked.


text:
Q: Installing the Express Application Generator using npm unable to install these package using npm: npm install eslint --save-dev  , npm install -g express-generator
Both time give same error :**
npm ERR! Unexpected end of JSON input while parsing near '...0.2.13":{"name":"mini'

npm ERR! A complete log of this run can be found in:
npm ERR! /home/user/.npm/_logs/2020-06-04T15_20_40_810Z-debug.log
but while installing another package npm install express  it successfully installed

A: try to clean npm cache and then reinstall the packages
npm cache clean --force
npm install eslint --save-dev
npm install -g express-generator


text:
Q: How do I filter out NaN FLOAT values in Teradata SQL? With the Teradata database, it is possible to load values of NaN, -Inf, and +Inf into FLOAT columns through Java.  Unfortunately, once those values get into the tables, they make life difficult when writing SQL that needs to filter them out.  There is no IsNaN() function, nor can you "CAST ('NaN' as FLOAT)" and use an equality comparison.
What I would like to do is,
SELECT
  SUM(VAL**2)
FROM
  DTM
WHERE
  NOT ABS(VAL) > 1e+21 AND
  NOT VAL = CAST ('NaN' AS FLOAT)

but that fails with error 2620, "The format or data contains a bad character.", specifically on the CAST.  I've tried simply "... AND NOT VAL = 'NaN'", which also fails for a similar reason (3535, "A character string failed conversion to a numeric value.").  I cannot seem to figure out how to represent NaN within the SQL statement.  Even if I could represent NaN successfully in an SQL statement, I would be concerned that the comparison would fail.  According to the IEEE 754 spec, NaN = NaN should evaluate to false. What I really seem to need is an IsNaN() function.  Yet that function does not seem to exist.

A: I have figured out a work-around, and I'll share that with those of you searching for a solution.  But first, it's obvious to me that Teradata's handling of NaN floating point values is incomplete and any behavior I've stumbled into figuring out is likely unintentional and inconsistent across different versions.  So I offer the following free advice, with no guarantees, promises, or liabilities of any kind.  Caveat emptor.
After drilling down into the data, I find that if I CAST the FLOAT value to a VARCHAR(50), the NaN values come out as a string of 22 asterisks (**********************).  I can cast to a VARCHAR(1) instead, and the NaN comes out as a single asterisk (*).  That comparison isn't that bad.
SELECT
  SUM(VAL**2)
FROM
  DTM
WHERE
  NOT CAST (VAL AS VARCHAR(1)) = '*' AND
  ABS(VAL) < 1.0e+21

I'll note two things.
First, my original desire of "NOT ABS(VAL) > 1.0e+21" on my version of Teradata seems to get converted to "ABS(VAL) <= 1.0e+21" under the covers.  This (sometimes) fails because of the equality potion of the comparison -- error [2651], "Operation Error computing expression involving VAL."  I'm assuming that the conversion from "NOT >" to "<=" is happening, because "NOT ABS(VAL) >= 1.0e+21" works fine (but looks ugly).  Using "ABS(VAL) < 1.0e+21" works just fine and captures the need.
Second, while I can't reproduce it consistently, I have examples in my history where "ABS(VAL) <= 1.0e+21" does effectively screen out NaN, some where it doesn't, and some where it fails with [2651] (see above), yet the SQL and the data in the tables were identical.  The only conclusion I can come to is that Teradata is inconsistent in how it evaluates the comparison when NaN is involved (or it thinks it might be).  It's possible that different amps are handling it differently, but I don't know for sure.  That said, the above two comparisons in the where clause consistently and effectively screen out the Inf and NaN values.


text:
Q: ajax request after -load I have some problems with Ajax and .load;
I want to fire the ajax request under three circumstances.
When a facility is chosen and when the preMonth/nextMonth was chosen.
My problem is that Ajax doesn't send the dates of the new month but the last active Month.
jQuery('main').on('click', '#terminstandorte select option, .nextMonth, .prevMonth', function(){

    //Some Code

    if (jQuery(this).get(0) == jQuery('.nextMonth').get(0)) {
        jQuery('#kalender').load('?' + jQuery(this).attr('value') + ' #thisMonth',function () {
            getFreeDates();
        });
    } else if (jQuery(this).get(0) == jQuery('.prevMonth').get(0)) {
        jQuery('#kalender').load('?' + jQuery(this).attr('value') + ' #thisMonth',function () {
            getFreeDates();
        });
    }

    var werk = parseInt(jQuery('#terminstandorte select option:selected').attr('value'));
    var firstDay = jQuery('.calDates .noDate:first').attr('id');
    var lastDay = jQuery('.calDates .noDate:last').attr('id');

    //Some Code again

    function getFreeDates() {
        //Hier werden alle freien Termine für den aktuellen Monat angezeigt
        jQuery.ajax({
            url: CENSORED,
            type: "GET",
            data: {
                request: request,
                werk: werk,
                firstDay: firstDay,
                lastDay: lastDay
            },
            contentType: 'application/json; charset=utf-8',
            beforeSend: function () {
                // console.log(firstDay, lastDay);
                today = new Date(firstDay);
                console.log(today.getMonth()+1);
            },
            success: function (data) {
                freeDates = JSON.parse(data);
                freeDates.forEach(function (date) {
                });
            },
            error: function () {
                alert('Etwas lief schief');
            }
        })
    }
});

I tried to put the Ajax in a function, so that Ajax is called after the load, but the result is still the same.
What I am doing wrong?


text:
Q: Using a HTML button to call and pass information to a PHP function I have the following code in which I am trying to display some information from an SQL Database, print it and have a button next to this information which would allow me to call a PHP Function. I am aware that you can not simply call a PHP function from HTML as PHP is server side. However all of the other answers seem to assume a knowledge of AJAX/ javascript which I do not have. My code is as follows:
while ($row = $results->fetchArray()){

            /* return the results */
            $links .= 'Website Name: '. $row['title'].'
';
            $links .= "Link        :  " . $row['link'] ."
";
            $links .= "Recommendations: " . $row['recommendations'] . "

";
            }

        return $links;

I add each bit of information, pre formatted, to the $links variable and then return this to be accessed in a different file. Originally, I thought I would be able to do something similar to this
$links .= 'Website Name: '. $row['title'].'<button onClick="recommend($row[id])" />
';

However this requires a Javascript function recommend to be called and I do not have any knowledge of Javascript. For this reason, I can think of no other way of solving this problem. I am sorry if I have not explained my issue well enough and will be happy to provide any extra information you may want. Thank you in advance for your help.

A: To do this you need to change the content of the page dynamically, which is only possible with Javascript or something similar.
The only other way to achieve something similar is to have an iframe in the page. A link could then be loaded in that iframe and request a page from the server without affection the parent page.

Execute Script

Still, this is a rather dirty workaround. I would suggest you to look at JavaScript and AJAX, even if it takes some time to get into.
Best wishes!

A: Here's a non-ajax answer for you.
while ($row = $results->fetchArray()){

        /* return the results */
        $links .= 'Website Name: '. $row['title'].'
';
        $links .= "Link        :  " . $row['link'] ."
";
        $links .= "Recommendations: " . $row['recommendations'] . "

";
        $links .= " Recommend ";
        }

    return $links;

Then on update.php add the code to process the id from the $_GET array and redirect back to the original page.
That way you can stick to php and not worry about AJAX/Javascript

A: Try using a form instead of a button.
Replace
<button onClick="recommend($row[id])">

with
<form action="some_php_page"><input type="hidden" value="$row[id]" name="PICK_A_NAME"><input type="submit" value="WHATERVER_U_WANT_THE_BUTTON_TO_SAY"></form>

So when the button is clicked the page will post the hidden field value on a php page where you can save it in the database and after that return the user to the page where you list the websites for recommendation.
Not sure how good of a solution this will be because anyone can recommend a website multiple times. I guess you have to adjust it so that it will reflect the website logic.


text:
Q: Bayes' rule and change of measure I wonder about how to explain best why the following formula (1) is called "Bayes' formula".
Given a probability space $(\Omega,\mathfrak A,P)$, a sub-$\sigma$-algebra $\mathfrak B\subset \mathfrak A$, a strictly positive random variable $Z\in L^1(\mathbb P)$ with $E[Z] =1$, we can define the equivalent probability measure $Q$ via $Q(A) = E[Z \textbf 1_A]$. Then, for any $Y\in L^1(\Omega,\mathfrak A,Q)$, we have
\begin{equation}
(1) \qquad E^Q[Y \mid \mathfrak B] = \frac{E[YZ\mid \mathfrak B]}{E[Z \mid \mathfrak B]}.
\end{equation}
Note that, if $A \in \mathfrak A$ with $P(A) > 0$, then we can put $Z = \textbf 1_A / P(A)$ in order to get $Q = P(\cdot\mid A)$.
But what is the precise relation to the elementary formula due to Bayes/Laplace, i.e. for $A,B \in \mathfrak A$ with $P(A)P(B) >0$ we have
\begin{equation*}
P(B\mid A) =  \frac{P(B)P(A\mid B)}{P(A)},
\end{equation*}
how do we have to choose $\mathfrak A, \mathfrak B, Z,Y$ above in order to derive this formula (without using the elementary argument which shows the elementary rule)?
Otherwise, there would – in my humble opinion – be no reason to call it "Bayes' formula".

A: Let $\mathfrak B$ be trivial, and set $Y = 1_B$, $Z = 1_A / P(A)$. Then:
$$
P(B \mid A) = E^Q[Y \mid \mathfrak B] = \frac{E[YZ \mid \mathfrak B]}{E[Z \mid \mathfrak B]} = \frac{P(A \cap B)}{P(A)},$$
which isn't exactly Bayes' rule, but it's pretty close; you can of course derive Bayes' rule by applying this result twice.


text:
Q: list index out of range syntax error pygame I am creating a 2D fighting game via pygame. At the moment i am implementing jumping to player1 using a velocity list. However player1 jumps and lands just how i want the object to but when it lands back on the platform an error message occurs:
self.y +=velocity[self.velocity_index], list index out of range.
This is the velocity list in my main code:
    velocity = list([-10, -9.5, -9, -8.5, -8, -7.5, -7, -6.5, -6, -5.5, -5, -4.5, -4, -3.5, -3, -2.5, -2, -1.5, -1, 0.5, 1, 1.5, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6, 6.5, 7, 7.5, 8, 8.5, 9, 9.5, 10])

This is in the def_init subroutine in my player1 class:
     self.velocity_index = 0

This piece of code is in the player1 class aswell and is where the error is occuring:
def do_jump(self):
    global velocity
    if self.jumping :
        self.y += velocity[self.velocity_index]
        self.velocity_index += 1
        if self.velocity_index >=len(velocity) - 1:
            self.velocity_index
        if self.y - self.rect.h == 362: #self.rect is the surface that the player should land on.
            self.pos=0
        elif self.y == 362-self.rect.h:
            self.jumping = False


text:
Q: How to implement Rate limit in Asp.net Framework API I am trying to limit the rate of api calls to avoid DDos attack. What i am trying to achieve is to limit how many calls can be made in one mins to 60 only, or 1 call per second.
I have found the implementation for .net core api, but for .net framwork api, I cannot find anything. Please help.
with ASP.net core api, it looks like this(as gotten from an elmah blog).
in the program.cs or startup.cs
services.AddMemoryCache();
services.AddSingleton<IClientPolicyStore, MemoryCacheClientPolicyStore>();
services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();

and then add
services.Configure<ClientRateLimitOptions>(options =>
{
 options.GeneralRules = new List<RateLimitRule>
 {
    new RateLimitRule
    {
        Endpoint = "*",
        Period = "1m",
        Limit = 500,
    },
    new RateLimitRule
    {
        Endpoint = "*",
        Period = "1h",
        Limit = 3600,
    }
  };
});

Anyone know how to do one for ASP.net framework API?

A: If you are here, please note. As of the time i am writing this code, I have not seen solution i could use, so I created mine.
I created a task/Service  that is called in the controller. this task is as thus:
 public bool IsWithinRangeLimit()
    {
        var dbEntities = new DbEntities();
        var isWithinRangeLimit = true;
        int rangeLimitNumber = int.Parse( ConfigurationManager.AppSettings["RateLimitNumber"].ToString() );
        int timeSpanInMins = int.Parse(ConfigurationManager.AppSettings["RateLimitTimeInMins"].ToString() );

        try
        {

            var requestList = dbEntities.RequestTrackers.ToList();
            Random rd = new Random();
            int rand_num = rd.Next(100000, 30000000);
            var newTracker = new RequestTracker()
            {
                id = rand_num,
                requestDate = DateTime.Now
            };

            if (!requestList.Any())
            {
                dbEntities.RequestTrackers.Add(newTracker);
                dbEntities.SaveChanges();
            }
            else
            {
                var reqListOrganised = requestList.OrderByDescending(m => m.requestDate).Take(rangeLimitNumber);
                var endTime = DateTime.Now;
                var starttime = endTime.AddMinutes(-timeSpanInMins);
                var tenthDate = reqListOrganised.LastOrDefault().requestDate;

                if (starttime <= tenthDate && tenthDate <= endTime)
                {
                    isWithinRangeLimit = false;

                }
                else
                {
                    dbEntities.RequestTrackers.Add(newTracker);
                    dbEntities.SaveChanges();
                }

            }

        }
        catch
        {
        }

        foreach (var item in dbEntities.RequestTrackers)
        {
            var isSAmeDay = this.IsSameDay(DateTime.Now, item.requestDate);
            if (!isSAmeDay)
            {
                dbEntities.RequestTrackers.Remove(item);

            }

        }
        dbEntities.SaveChanges();
        return isWithinRangeLimit;

    }

The isSameDay class i added can be found here.
the data comes in from web.config. It looks as thus:
  <add key="RateLimitTimeInMins" value="1" />
  <add key="RateLimitNumber" value="2" />

'Idealy' you will want to create an autoincrement able Primary Key, and want to dispose not needed date from the database using time dependent services.
Please add answer if you have a better solution


text:
Q: How do i install Libreoffice 3.4? I read that it has better GTK+ integration,is faster and java has been minimized . so i wanted to try it .
How do i install it ?
A PPA would be preferable.

A: LibreOffice 3.4.3 for Natty was released 7 Oct 2011.
The standard LibreOffice ppa should be used to update - see linked question on how to install.
For those that like to live on the bleeding edge, there are .deb files you can download directly from the LibreOffice website here.  Obviously, these will be vanilla LibreOffice and therefore probably will not include any stuff the ubuntu packagers also add.

Linked Question:

*

*Will LibreOffice 3.4 be included in an update?

A: Visit the PPA's overview page in Launchpad. click this link https://launchpad.net/~libreoffice/+archive/ppa
Step 2: Use the Display sources.list entries drop-down box to select the version of Ubuntu you're using.
Step 3: You'll see that the text-box directly below reads something like this:
deb http://ppa.launchpad.net/libreoffice/ppa/ubuntu YOUR_UBUNTU_VERSION_HERE main
deb-src http://ppa.launchpad.net/libreoffice/ppa/ubuntu YOUR_UBUNTU_VERSION_HERE main
Copy those lines.
Step 4: Open a terminal and type:
sudo nano /etc/apt/sources.list
This will open a text editor containing the list of archives that your system is currently using. Scroll to the bottom of the file and paste the lines you copied in the step above.
Save the file and exit the text editor.
Step 5: Back on the PPA's overview page, look for the Signing key heading. You'll see something like:
1024R/72D340A3
Copy the portion after the slash but not including the help link; e.g. just 72D340A3.
Step 6: Now you need to add that key to your system so Ubuntu can verify the packages from the PPA. In your terminal, enter:
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 72D340A3
Replace 72D340A3 with whatever you copied in the step 5.
This will now pull down the PPA's key and add it to your system.
Step 7: Now, as a one-off, you should tell your system to pull down the latest list of software from each archive it knows about, including the PPA you just added:
sudo aptitude update
sudo aptitude install libreoffice
Now you're ready to start libreoffice

A: Follow this instructions --you have to download DEB packages until they update the official PPA.
http://www.unixmen.com/software/1755-libreoffice-340-is-released-installation-instructions-for-ubuntu-fedora-debian


text:
Q: I have imported a project into Xcode. It is giving an error I have imported a project into Xcode. It is giving an error that is unexpected identifier (.
File name is SignIn.h
and code that is written in this file is
../../../../Google/Headers/SignIn.h

A: Add this line in your bridging Header file and import Google in AppDelegate
import <GoogleSignIn/GoogleSignIn.h>

import <Google/Core.h>

Hope this would help you.


text:
Q: OnManualSubmit как определить index Таблица.
  setEditStrategy(QSqlRelationalTableModel::OnManualSubmit);
  ui->tableView->setModel(model);

model->submitAll(); по нажатию на кнопку(QPushButton). Как перед сабмитом  проверить, если в комбобоксе было выбрано значение "cancel", то выполнить определенное действие...

A: А где у вас комбобокс?
QComboBox* ComboBox = new QComboBox();

Вообще узнать текущий индекс можно так:
ComboBox->currentIndex(); // вернет int

Можно у комбобокса спросить, какой он отображает текст:
ComboBox->currentText(); // вернет QString с тем текстом, который выбран


text:
Q: How do I set a C# checkbox property to "unchecked" for the purpose of saving a setting? How do I set a C# checkbox property to "unchecked" for the purpose of saving a setting? I'm using the .NET settings feature to store the state of a checkbox. When the form loads it grabs that setting and checks or un-checks that checkbox accordingly. The code below works to set the setting to true. But there is no definition for unchecked in this context.

Can anyone help?
Thanks.
PS. This is using VS2010, C# and .NET 3.5

A: chkBackup.Checked will contain false if the box is unchecked, so you can just always use chkBackup.Checked to get what you need. The following code should be all that you ever need -
private void chkBackup_CheckChanged(object sender, EventArgs e)
{
    Properties.Settings.Default.Backup = chkBackup.Checked;
    Properties.Settings.Default.Save();
}

A: Use (chkBackup.Checked == true) as the value:
Properties.Settings.Default.Backup = (chkBackup.Checked == true);
Properties.Settings.Default.Save();

This also gets rid of your enclosing if statement, and will work with properties that are nullable bools (bool?)


text:
Q: Java Call Array from another Class I need help with this question, can anyone teach me how can I print out the array of Actor[] from the class ActorAll[] at the main method? I am able to print from the Actor() class but unable to do so from ActorAll() due to reasons I do not know, it is greatly appreciated if someone can help me.
public class Actor {
private String fName;
private String lName;

public Actor(String f,String l){
    setfName(f);
    setlName(l);
}

public String getfName() {
    return fName;
}

public void setfName(String fName) {
    this.fName = fName;
}

public String getlName() {
    return lName;
}

public void setlName(String lName) {
    this.lName = lName;
}
public String displayMessage(){
    return String.format("%s %s", getfName(),getlName());
}

}
public class ActorAll extends Actor{
private Actor[]actor;

public ActorAll(Actor[] actor){
    setActor(actor);
}

public Actor[] getActor() {
    return actor;
}

public void setActor(Actor[] actor) {
    this.actor = actor;
}

public String displayMessage(){
    return String.format("%s ", getActor());
}

}
public class ActorAllTest {

static Scanner sc= new Scanner(System.in);
public static void main(String[] args) {
    Actor actor;

    actor=addContact();
    System.out.println(actor.displayMessage());
}
public static Actor addContact(){
    String fName=sc.next();
    String lName=sc.next();
    Actor actor = new Actor(fName,lName);
    return actor;
}

}

A: If you want to print the actor[] from ActorAll, you need to create an ActorAll dynamic type object and call displayMessage on that object.
public static void main(String[] args) {
    Actor actor = new ActorAll();

    actor=addContact();
    System.out.println(actor.displayMessage());
}


text:
Q: MVC Resolving a url in a .JS file So I've got some Javascript in a seperare js file (jquerySliderMenu.js)
to resolve the url of an image i do this:
var imgUrl = $Url.resolve("~/Assets/Javascript/Img");
works find in dev, (iis 6)
but on prod(iis 7.5) , it resolves to
https://XXXX.org/Home.mvc.aspx/~/Assets/Javascript/Img/right.gif
instead of
https://XXXX.org/Assets/Javascript/Img/right.gif
Which causes an error.
I remember the IT guys had to add the .MVC. stuff but i can't rememebr why or how they did it.
Is there a better way to resolve the issue that will work with the settings that add the .mvc.aspx to everything? (And please, what is that setting?)
Thansk,
Eric-

A: You should not be trying to resolve any urls in ytour javascript files. You should use url helpers to generate them in the HTML. Javascript will then unobtrusively read and use them.
You could use HTML5 data-* attributes, the same way unobtrusive AJAX and client side validation works. So for example let's suppose that you have the following element in your DOM

some contents

and then in your javascript:
var imgUrl = $('#foo').data('url');

or in the case you are for example unobtrusively AJAXifying an anchor or a form, you could directly fetch the href or action attributes on the corresponding DOM elements which would of course have been generated with Url/Html helpers and thus ensuring proper urls respecting routes.


text:
Q: Binding in ViewHolder This will be theoretical question.
As everyone we use RecyclerView in many parts of the app. Sometimes RecyclerView contains different items, not only image for example, but ads, hints etc. And that's why we can use getViewType() method in Adapter.
But problem occurs when we have many viewTypes and binding this in Adapter is not elegant. So here is the question, is it nice and good pattern to bind data in ViewHolder?
Let's say we have list of apps.
Every app has name for simplicity. Our ViewHolder looks like this:
class AppViewHolder extends RecyclerView.ViewHolder {

     public TextView nameText;

     AppViewHolder(View itemView) {
          super(itemView)
          nameText = (TextView) itemView.findViewById(R.id.text_name);
     }
}

Now we could add bind method:
public void bind(App app) {
     nameText.setText(app.getName());
}

Is it good pattern?
Another solution would be using ViewModel. Because we have different items in RecyclerView, our Adapter could contain list of class which is base class for every ViewModel.
So basic class is:
class RecyclerViewItem {}

Now class which is ViewModel for App.
class AppRecyclerViewItem extends RecyclerViewItem {

     App app;

     ...
}

and our Adapter just has list of RecyclerViewItems:
class Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    List<RecyclerViewItem> items;

    ...
}

So with this approach (I mean using ViewModel) is it better to add bind method in ViewHolder, or in ViewModel?

A: I would say that none of your solutions is good.
First one is good only for items, that appear only once in adapter. Creating a method to fill row inside ViewHolder is not a good solution as different type of ViewHolders would grow and your RecyclerView.Adapter would gain more and more lines.
Second method is also not good. Model is the model, should only contain data and not business logic of application.
I would suggest a solution to keep RecyclerView.Adapter clean and pass logic of creating ViewHolder and filling them with data to delegates, that would be registered in ie. RecyclerView.Adapter constructor.
This technique is explained more here
This way, registering even over a doven of different ViewHolder does not expecially add boilerplate to RecyclerView.Adapter, but delegates the logic of creating and filling RecyclerView.Adapter rows to those delegates.
But that is just a suggestion.

A: For my apps I've been using something like this:
public abstract class BindableViewHolder<T> extends RecyclerView.ViewHolder {
  public BindableViewHolder(View itemView) {
      super(itemView);
  }

  public abstract void bind(T thing);
}

The idea is to delegate the implementation of binding to the ViewHolder. This solution is meant for cases when you want to bind the same kind of object to different viewholders, but I think it's easily expandable to more general cases.
Here's an example of a really simple adapter. I think it explains itself, hope it helps!
public class ShowsAdapter extends RecyclerView.Adapter<BindableViewHolder<Show>> {

  private final DataProvider<Show> showsProvider;

  public ShowsAdapter(DataProvider<Show> showsProvider) {
      this.showsProvider = showsProvider;
  }

  @Override
  public BindableViewHolder<Show> onCreateViewHolder(ViewGroup parent, int viewType) {
      return ShowViewHolder.create(parent);
  }

  @Override
  public void onBindViewHolder(BindableViewHolder<Show> holder, int position) {
      holder.bind(showsProvider.get(position));
  }

  @Override
  public int getItemCount() {
      return showsProvider.size();
  }
}

Here, ShowViewHolder is a concrete subclass of BindableViewHolder,

A: There is great solution using delegates - http://hannesdorfmann.com/android/adapter-delegates and it can be even used for DataBinding (with simple changes, https://github.com/drstranges/DataBinding_For_RecyclerView). In this way data binded not in ViewHolder and not in RecyclerView Adapter but ItemDelegate do this, so your code remains clear and readable.
Following this approach all work with view-types delegated to the DelegateManager:
public abstract class AbsDelegationAdapter<T> extends RecyclerView.Adapter {

protected AdapterDelegatesManager<T> delegatesManager;
protected T items;
//...

    @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return delegatesManager.onCreateViewHolder(parent, viewType);
    }

    @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        delegatesManager.onBindViewHolder(items, position, holder);
    }

    @Override public int getItemViewType(int position) {
        return delegatesManager.getItemViewType(items, position);
    }
}

And your code will look like this:
mAdapter = new BindableAdapter<>(
        new UserDelegate(actionHandler), // you can create custom delegate
        //new ModelActionItemDelegate<BaseModel>(actionHandler, User.class, R.layout.item_user, BR.user), // or use generic
        new AnotherItemDelegate());

Where ItemDelegate can look like this:
public class UserDelegate extends BaseAdapterDelegate<BaseModel, ItemUserBinding> {

    @Override
    public boolean isForViewType(@NonNull final List<BaseModel> items, final int position) {
        return items.get(position) instanceof User;
    }

    @NonNull
    @Override
    public BindingHolder<ItemUserBinding> onCreateViewHolder(final ViewGroup parent) {
        // create ViewHolder
        return BindingHolder.newInstance(R.layout.item_user, LayoutInflater.from(parent.getContext()), parent, false);
    }

    @Override
    public void onBindViewHolder(@NonNull final List<BaseModel> items, final int position, @NonNull final BindingHolder<ItemUserBinding> holder) {
        // Just bind data
        final User user = (User) items.get(position);
        holder.getBinding().setUser(user);
    }

}


text:
Q: Simple Products are not showing as associated in configurable products in Magento 1.9 Hope you are doing well.
I need to ask about how to set up a simple product to be able to show it to my configurable associated products.
I think I already configure all the attributes like,
visibility = not show individually
stock = in stock
price = also set
status = enable

anything I missed? Because when go to my configurable product there is nothing as Associated Products.
Any help appreciated.

A: Hello Quan,

To associate them
not needed:

visibilty = not show inidividually
stock = in stock
price = also set
status = enable

needed:
attribute set = the same as configurable product (check configurable product attribute in admin section)

to create a config
Beside this you need to make sure, that the attributes you want to be configurable are NOT system, "Global", input type "Dropdown" and "allowed for configurables"

to show them in frontend
Only the simple ones which are in stock and enabled are shown in frontend, might be an indexing issue?

Thanks!


text:
Q: View logcat whilst not debuggin I'm developing an application that communicates with another device over usb, the problem is this makes it quote difficult to debug because I can't connect it to my PC at the same time. Is there a way of getting at the logcat out at a later date. That is, I have a bunch of log.d statements, I'm hoping I can run my app, and then afterwards connect it to my PC to download the resulting log statements?
Regards
Dan

A: the trick to have adb debugging while doing USB communication is to use adb tcpip


text:
Q: Chrome extension switch tabs queue Is it possible to queue tab switching and let the background script know when it is ok to process the next tab switch?
For example in content.js
chrome.runtime.sendMessage("Do something", function(resp) {
   doSomethingFor3Seocnds().then(function(resp) {
    // now it's OK to go to the next tab
 })
}

background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
  chrome.tabs.update(sender.tab.id, {"active": true}, function(tab){
    // only run if OK to go to next tab
    return sendResponse(tab)
  });
});


text:
Q: Java Tower Of Hanoi convert number to String Java Tower Of Hanoi convert numbers looping result to String result
How to make print statement into letters instead of numbers, the print is like this
1  |     |
2  |     |
3  |     |
i want to change to letters like this
a  |     |
b  |     |
c  |     |
I try using if-else for every time I print d1, d2, and d3, but d1,d2, and d3, don't have have of 1,2, and 3 so I cant use conditional statement to change di value into a string
can you help me with this problem
     import java.util.*;

     /* Class TowerOfHanoiUsingStacks */
     public class HelloWorld
     {
         public static int N;
         /* Creating Stack array  */
         public static Stack<Integer>[] tower = new Stack[4];

         public static void main(String[] args)
         {
             Scanner scan = new Scanner(System.in);
             tower[1] = new Stack<Integer>();
             tower[2] = new Stack<Integer>();
             tower[3] = new Stack<Integer>();
             /* Accepting number of disks */
             System.out.println("Enter number of disks");
             int num = scan.nextInt();
             N = num;
             toh(num);
         }
         /* Function to push disks into stack */
         public static void toh(int n)
         {
             for (int d = n; d > 0; d--)
                 tower[1].push(d);
             display();
             move(n, 1, 2, 3);
         }
         /* Recursive Function to move disks */
         public static void move(int n, int a, int b, int c)
         {
             if (n > 0)
             {
                 move(n-1, a, c, b);
                 int d = tower[a].pop();
                 tower[c].push(d);
                 display();
                 move(n-1, b, a, c);
             }
         }
         /*  Function to display */
         public static void display()
         {
             System.out.println("  A  |  B  |  C");
             System.out.println("---------------");
             for(int i = N - 1; i >= 0; i--)
             {
                 String d1 = " ", d2 = " ", d3 = " ";
                 try
                 {
                     d1 = String.valueOf(tower[1].get(i));
                 }
                 catch (Exception e){
                 }
                 try
                 {
                     d2 = String.valueOf(tower[2].get(i));
                 }
                 catch(Exception e){
                 }
                 try
                 {
                     d3 = String.valueOf(tower[3].get(i));
                 }
                 catch (Exception e){
                 }
                 System.out.println("  "+d1+"  |  "+d2+"  |  "+d3);
             }
             System.out.println("\n");
         }
     }

A: If you just want to print letters instead of numbers, cast your value to char
String.valueOf((char)(tower[1].get(i) + 97))
You might want to use 96 instead, since I believe you are using 1 as the first index.


text:
Q: 403 Forbidden: Able to open uri in browser but not in JavaScript code I'm trying to open a (cross domain) uri in my JavaScript code. I'm able to open it if I copy it to my browser and directly open it. However, if I open it in my JavaScript code, I get 403 Forbidden error. Here is my code:
var xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.withCredentias = true;
xhr.open('get', uri, 'true');
xhr.onload = function() {
    console.log(xhr.response);
}
xhr.send();

It doesn't seem like a CORS error, because in the response header I can see my origin host in the Access-Control-Allow-Origin part. I didn't get any CORS error either.
Does anyone have any idea why this happens? Really appreciate your help!
Thanks!
====UPDATE====
Directly from browser (Chrome)
Request:
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Host:host.com
Pragma:no-cache
Upgrade-Insecure-Requests:1
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36

Response:
Cache-Control:max-age=60
Connection:Keep-Alive
Content-Encoding:gzip
Content-Type:application/json; charset=utf-8
Date:Mon, 01 Aug 2016 17:58:20 GMT
Expires:Mon, 01 Aug 2016 17:59:20 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.4.6
Transfer-Encoding:chunked
Vary:Accept-Encoding

From code
Request:
Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Host:host.com
Origin:myhost.com
Pragma:no-cache
Referer:myhost.com/login
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36

Response:
Access-Control-Allow-Credentials:true
Access-Control-Allow-Methods:GET, HEAD, OPTIONS
Access-Control-Allow-Origin:myhost.com
Cache-Control:max-age=60
Connection:Keep-Alive
Content-Length:0
Content-Type:application/json; charset=utf-8
Date:Mon, 01 Aug 2016 18:20:54 GMT
Expires:Mon, 01 Aug 2016 18:21:54 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.4.6

A: I came across a similar issue where I can submit a GET request just fine from my browser to the URL, but using JavaScript (electron, node.js, net.request) was giving me a 403 error with certain data to that same URL.
I ended looking at the Headers sent by my browser and then just added those same Headers to the Javascript request and then the issue went away.
So this answer is not a pure Javascript answer, but it worked for Electron javascript. I added this in my main.js:
const electron = require('electron');
 const { net, session } = electron;

  session.defaultSession.webRequest.onBeforeSendHeaders((details, callback) => {
    details.requestHeaders['Upgrade-Insecure-Requests'] = '1';
    details.requestHeaders['Dnt'] = '1';
    details.requestHeaders['Accept-Encoding'] = 'gzip, deflate, br';
    details.requestHeaders['Accept-Language'] = 'en-US,en;q=0.5';
    details.requestHeaders['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
    details.requestHeaders['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0';
    details.requestHeaders['Connection'] = 'close';
    details.requestHeaders['X-Forwarded-Proto'] = 'http';
    callback({ cancel: false, requestHeaders: details.requestHeaders });
  });

  const request = net.request({
      method: 'GET',
      protocol: 'https:',
      url: 'http s://mydomain.com/somefile.php?data=something&moredata=somethingelse'
   });

  request.on("error", (err) => {
    console.log("NetError::: " +err.message);
   });

     request.on('response', (_response) => {
    _response.on('end', () => {
      console.log('NetEnd::: END response (no more data).');
    });
    _response.on('data', (_chunk) => {
        console.log("NetStatus::: " + _response.statusCode);
        console.log("NetHeaders::: " + JSON.stringify(_response.headers) );
        console.log("NetBody::: " + _chunk);
    });

 });

 request.end();

A: I was able to solve the same problem when I changed User-Agent request header to chrome's standard one.


text:
Q: How do you iterate over float excel columns in python? Say I have an imported excel sheet that looks like this:
    A         B        C          D
4.296178, 0.434362, 0.033033, 2.758968
0.296178, 0.434362, 0.033033, 0.758968
3.396178, 0.434362, 0.033033, 1.758968

And I want to iterate through it in a way that returns the sum of each column, how would I do this?
I have tried this:
import openpyxl

    templist = []
    Col_one_total = []
    Col_two_total = []
    Col_three_total = []

    for row in sheet.rows:
        Col_one_total += row[0].value
        Col_two_total += row[1].value
        Col_three_total += row[2].value
        templist.append(Col_one_total)
        templist.append(Col_two_total)
        templist.append(Col_three_total)
        return max(templist)

but I keep getting an error saying TypeError: 'float' object is not iterable.
Does anyone know how to resolve this?

A: I recommend using Pandas to do this. The following code reads in the Excel file using the read_excel method and the sums each column using the sum dataframe method.
import pandas as pd

df = pd.read_excel('test.xlsx')

column_sums = df.sum()

print(column_sums)

Output:
A    7.988534
B    1.303086
C    0.099099
D    5.276904
dtype: float64

Note: You need to have openpyxl installed for this to work. Else you'll run into the following error: ImportError: Missing optional dependency 'openpyxl'.  Use pip or conda to install openpyxl.


text:
Q: WPF datagridcomboboxcolumn not binding I'm trying to get a DataGridComboBoxColumn to bind to an enum, but all I get is a Empty dropdown.
I tried a number of things with DisplayMemberPath and other things, but no avail.
The binding on the SkillName works, but not the SkillLevel
XAML:
<Window x:Class="EveCommon.Skills.EveSkillEditWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Common.Skills"
    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    mc:Ignorable="d"
    Title="Skills Window" Height="600" Width="600"
    DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Window.Resources>
    <ObjectDataProvider x:Key="SkillEnum" MethodName="GetValues" ObjectInstance="{x:Type sys:Enum}">
        <ObjectDataProvider.MethodParameters>
            <x:Type TypeName="local:SkillLevels"/>
        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
</Window.Resources>

        <DataGrid Grid.Row="1" ItemsSource="{Binding Skills}" AutoGenerateColumns="False" CanUserAddRows="False">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name" IsReadOnly="True" Binding="{Binding SkillName}"/>
            <DataGridComboBoxColumn Header="Skill Level" DisplayMemberPath="SkillLevel"
                                    SelectedValueBinding="{Binding Path=SkillLevel}"
                                    ItemsSource="{Binding Source={StaticResource SkillEnum}}"/>
        </DataGrid.Columns>
    </DataGrid>

Enum:
public enum SkillLevels
{
    Zero = 0,
    I,
    II,
    III,
    IV,
    V
}

Skill class:
public class Skill : ImplementPropertyChanged
{
    private string _skillName;
    private SkillLevels _skillLevel;

    public string SkillName
    {
        get => this._skillName;
        set => this.SetField(ref this._skillName, value);
    }

    public SkillLevels SkillLevel
    {
        get => this._skillLevel;
        set => this.SetField(ref this._skillLevel, value);
    }

}

And the collection:
    public ObservableCollection<Skill> Skills
    {
        get => this._skills;
        set
        {
            this._skills = value;
            this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Skills"));
        }
    }

A: There are two issues in your XAML code. First at your ObjectDataProvider; it should be ObjectType instead of ObjectInstance. Second one is, you should not specify DisplayMemberPath for this as your are displaying the Enum values.
Try this
<ObjectDataProvider x:Key="SkillEnum" MethodName="GetValues" ObjectType="{x:Type sys:Enum}">
    <ObjectDataProvider.MethodParameters>
        <x:Type TypeName="local:SkillLevels"/>
    </ObjectDataProvider.MethodParameters>
</ObjectDataProvider>

Your DataGridComboBoxColumn will be,
<DataGridComboBoxColumn Header="Skill Level"
         SelectedValueBinding="{Binding Path=SkillLevels, UpdateSourceTrigger=PropertyChanged}"
         ItemsSource="{Binding Source={StaticResource SkillEnum}}"/>


text:
Q: Cannot send httponly cookie to express server from react js I am working on a react app which receives httponly cookie from third party website.
I am able to see the cookie in Chrome developer console.
I am trying to send this cookie to backend of my app, built in expressjs, so that I can read the cookie. I am using fetch to send a GET request to the app while including the prop below:
Credentials: 'include'

In the express server, am allowing my front-end inside CORS and also
set credentials equal to true.
Issue:
In request header of my express server, I can't see the httponly cookie.
Can anyone guide me how can I send httponly and get it inside express server?

A: On client you must enable credentials as well. There is axios module to make requests with credentials. Example of usage:
import axios from 'axios'

const instance = axios.create({
  withCredentials: true,
  baseURL: API_SERVER
})

instance.get('todos')

In other way, you could provide cookie with XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/', true);
xhr.withCredentials = true;
xhr.send(null);

XMLHttpRequest

A: The first thing is allow our Express application to be able to receive requests from the host on which the Fetch API makes the calls in our situation it makes them from https://localhost:8080
const express = require('express');
const cors = require('cors');

app.use(cors({
origin: 'http://localhost:8080',
credentials: true
}));

The last thing is to create a fetch request via the Fetch API from [https://localhost:8080] to [http://localhost:9090/example]:
fetch('http://localhost:9090/example',{
method: 'GET',
credentials: 'include'
});

And now no matter that we made the request from another host ,we receive the cookies


text:
Q: getting empty value in viewWillAppear( ) but getting valid value in viewDidLoad( ) When print(mess) is called from the viewDidLoad function, it prints what is expected, but when called from the viewWillAppear function, it gives empty output.  label also not getting updated after doing the assignment in viewDidLoad .Why is this?
main ViewController:
if segue.identifier == "temp"
{
let tovc = segue.destination as ! ADDviewcontroller1
tovc.mess = self.var1
}

In ADDviewcontroller1:
var mess: String = ""
override func viewWillAppear(animated: Bool)
{
super.viewWillAppear(animated)
self.infoLabel.text = mess
print(mess) //giving empty output in console
}

override func viewDidLoad()
{
super.viewDidLoad()
self.infoLabel.text = mess //label not getting updated

print(mess) //printing the required output in console
}

A: I have reproduced your code and found several mistakes, I have a working example below and think I have found your issue.
First viewcontroller (ViewController)
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "show" {
        let tovc = segue.destination as? AddViewController
        tovc?.mess = "test"
    }
}

Note: I have renamed the identifier to show, rename it back to whatever it is at your code. Also I used the string "test" as a replacement for your var1
In your first viewcontroller you will have to overwrite  the prepare(for:sender:) func with the code you provided. Note that the ! was one space away from the as statement. I concatenated them and changed it into a conditional cast with ?. This way it's more safe.
Second viewcontroller (AddViewController)
@IBOutlet weak var infoLabel: UILabel!

var mess: String = ""
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.infoLabel.text = mess
    print(mess) //this is now printing 'test'
}

override func viewDidLoad() {
    super.viewDidLoad()
    self.infoLabel.text = mess //label is now being set

    print(mess) //this is now printing 'test'
}

Note the extra _ you were missing in the viewWillAppear(animated:) func signature. Not cohering to the signature makes it possible to not have it fired like you expect (because the system won't recognize the viewWillAppear as a valid override).
Running this code in the latest Xcode (9.2) using Swift 4 I have no problems and can't reproduce your issue (if it ain't the missed signature of the viewWillAppear). I'm guessing this issue is to locale if you still run into troubles.

A: It's impossible for a non-optional value to produce 'nil', but it may be a bug in Xcode try:
1- Clear derived data folder: https://stackoverflow.com/a/18933382/3882414
2- Restart Xcode
3- Clean and rebuild


text:
Q: Color Excel cell based on COUNTIF function I'm trying to color excel cell based on my COUNTIF-function. There are many examples to count cell based on color but i need to fill cell with color based on COUNTIF-function. I have 30 names in a column. At the end i have COUNTIF-function to count total number of names with last name Malik. This works and i get number 8 from this function. Now I would like to highlight these 8 cells, so they are easy to find. If colorfill can be combined with COUNTIF-function, it would be the best.

A: conditional formatting -> formula -> =isnumber(search("Malik",a1;0)) should work. delete dollar signs for the search cell. Adapt the celladdress to your needs.
You could also use =COUNTIF(A1,"*Malik*") or even use =COUNTIFS(A1,"*Malik*",B1,"<"&today())


text:
Q: Visual Studio Online and Local Build Host We have visual studio online  professional license and MSDN, we need a local build server as we require third party controls.  Can anyone tell me the licensing on this? Do we need to purchase a local TFS license as well?

A: No additional software needs to be purchased to setup a build environment with VSO.
If you want to setup a Xaml build controller the easiest way to get that is to download and install but not configure TFS Express which is free and does grant you a license to use the software.  Once that is done you can simply launch the admin console and configure the build controller against your VSO account.
With the new build system you simply download the agent software directly from VSO in your account control panel.  You can find documentation here https://msdn.microsoft.com/Library/vs/alm/Build/agents/windows#ManuallydeployabuildagentDownloadandconfiguretheagent
Each account allows you to connect 1 Xaml controller or 1 agent for free.  To connect additional agents you need to purchase more Private Agents you can see details on pricing here https://www.visualstudio.com/features/continuous-integration-vs and here https://www.visualstudio.com/en-us/get-started/setup/get-more-build-or-load-testing-vs

A: If the MSDN subscription account you have is one of the followings, you can download and deploy one instance of Team Foundation Server 2015 from MSDN subscriber download site, and you get one CAL(Client Access License) as well.

*

*Visual Studio Enterprise with MSDN

*Visual Studio Professional with MSDN

*Visual Studio Test Professional with MSDN

*MSDN Platforms

However, for example, if you want to have 2 build servers to associate with VSO, you have to buy another one license for TFS (TFS license includes build service); similarly, if you want to allow 10 users to use the build server, you may need to buy CAL license based on the TFS license you have (for example, Team Foundation Server 2015 purchased in retail channels contains up to five CALs)
Please check the license white paper for the details: http://www.microsoft.com/en-us/download/details.aspx?id=13350


text:
Q: Windows 8 to Windows 7: downgrading vs. clean install? I'm looking to buy a new laptop soon. However, it seems most of them are running Windows 8, and I prefer to work with Windows 7.
From what I've heard, only the Professional Edition of Windows 8 has downgrade rights. If I want to "upgrade" to Windows 7 from a non-Professional edition of Windows 8, is there anything to prevent me from wiping the OS and doing a clean install?

A: No there isn't. As long as you own a full retail copy of W7 and have the appropriate installation media (DVD or USB) and the corresponding license key to boot you are cleared to go. The first part of doing a "clean" installation of an operating system is wiping the hard drive.
Be ware though that your warranty for the computer, at least the software part will most likely be void if you do this. Or more likely, if you get any problems and want them to fix it, they will probably wipe tha hard drive and do a "factory reset", reverting it back to W8.


text:
Q: Prevent $scope from overriding I am using a controller to set the icon image for each list in my ng-repeat directive. Right now the $scope.icon_level overrides all the other values with the last value given to the scope. How can I make sure each list gets it's own $scope.icon_level value and it is not replaced with the next value?
HTML:

{{exemplifier.exemplifier}}

How I set the scope value:
angular.module('ciscoImaDashboardApp').controller('keyCtrl', function ($scope, dummyData) {

var exemplifiers = dummyData.exemplifier_data;

for (var i = 0; i < exemplifiers.length; i++) {
        if(exemplifiers[i].average_score < 3) {
            $scope.icon_level = "images/acorn-icon@2x.png";
        }
        else if(exemplifiers[i].average_score < 6) {
            $scope.icon_level = "images/seedling-icon@2x.png";
        }
        else if(exemplifiers[i].average_score < 9) {
            $scope.icon_level = "images/tree-icon@2x.png";
        }
}
});

A: Because of the complexity of the 3 conditions - ng-src is probably not best. so I gave you an easier, ng-if based solution. the non-applicable images will not render in the DOM. I am making the assumption that ringToHighlight is an property of exemplifier
HTML

<img ng-if="exemplifier.ringToHighlight <3" src="images/acorn-icon@2x.png" width="30" class="{{exemplifier.section}}"/>
= 3 && exemplifier.ringToHighlight < 6" src="images/seedling-icon@2x.png" width="30" class="{{exemplifier.section}}"/>
= 6 && exemplifier.ringToHighlight < 9" src="images/tree-icon@2x.png" width="30" class="{{exemplifier.section}}"/>
{{exemplifier.exemplifier}}

JS
angular.module('ciscoImaDashboardApp').controller('keyCtrl', function ($scope, dummyData) {

var exemplifier_data = dummyData.exemplifier_data;
$scope.exemplifiers = exemplifier_data;

});

A: I would use the 'ng-class' and assign the style to the tag as you iterate.

angular.module("app", [])
.controller("main",["$scope",function($scope){

  $scope.ids =[{"id":"bob", "value": 3},{ "id": "fred","value": 1},{"id":"mark", "value": 5},{"id":"sally", "value": 3}];

  $scope.exemplifiers = $scope.ids.map(function(e){
    if( e.value > 3) {e.section = "red"; }
    else if( e.value > 1 ){ e.section = "blue";}
    else {e.section = "green";}
    return e;
  });

  }]);
.green {
  background-color:green;
  /* replace with your imgs */
  }
.red {
  background-color:red;
  /* replace with your imgs */
  }
.blue{
  background-color:blue;
 }
img.green{
  content:url("images/acorn-icon@2x.png");
        }

img.red{
content:url(images/seedling-icon@2x.png";
        }

img.blue{
content:url("images/tree-icon@2x.png"
  }

{{exemplifier.id}}

A: There are multiple ways to solve the problem you are describing here.  The root of the problem boils down to the fact that you want to represent multiple values in your HTML but you have only allocated a single variable.
Angular's two way binding is going to ensure that this value always stays up to date, meaning that your iteration is essentially looping through the whole array and resetting the same variable to a new value over and over, and your result will always be the last item in the loop.
There are two common ways to approach this problem.  One way would be to create a property on each exemplifier and attach the value to this object property.  If augmenting your objects is not possible or causes other issues, an alternative would be to change the icon_level into a function that can be run repeatedly and return different results each time.
Option 1:
Here we loop through the exemplifiers and add an additional icon_level property to each.  Note, I also am illustrating the use of angular.foreach() here.
var exemplifiers = dummyData.exemplifier_data;

angular.foreach(exemplifiers, function(exemplifier) {
  if (exemplifier.average_score < 3) {
    exemplifier.icon_level = "images/acorn-icon@2x.png";
  } else if (exemplifier.average_score < 6) {
    exemplifier.icon_level = "images/seedling-icon@2x.png";
  } else if (exemplifier.average_score < 9) {
    exemplifier.icon_level = "images/tree-icon@2x.png";
  }
});

    {{exemplifier.exemplifier}}

Option 2:
Here, we convert $scope.icon_level into a function, and call it for each ng-repeat iteration, passing in the value that we want to check.
$scope.icon_level = function(level) {
  if (level < 3) {
    return "images/acorn-icon@2x.png";
  } else if (level < 6) {
    return "images/seedling-icon@2x.png";
  } else if (level < 9) {
    return "images/tree-icon@2x.png";
  }
}

    {{exemplifier.exemplifier}}

A: I figured it out by doing using ng-style and setting the scope variable in each view controller:
JS:

HTML:
$rootScope.backgroundImg = "url('../images/background-bark@2x.jpg')";


text:
Q: Generic properties of families of algebras over an infinite dimensional base space Let $\mathbb{k}$ be an algebraically closed field and let $A$ be a $\mathbb{k}$-algebra which is a free module of rank $r$ over some central subalgebra $Z_0$. If $Z_0$ is affine and $r$ is a finite number then the maximal ideals of $Z_0$ all have $\mathbb{k}$-codimension 1 and so the quotients $$\{A / \mathbb{m} A \mid \mathbb{m} \in \operatorname{Max}(Z_0)\}$$
all have dimension $r$ over $\mathbb{k}$. One could say that an algebraic property is generic for this family of algebras if there is a non-empty Zariski open subset $\mathcal{U}$ of the algebraic variety $\operatorname{Max}(Z_0)$ such that for all $\mathfrak{m} \in \mathcal{U}$ the algebra $A/ \mathfrak{m} A$ possesses this property. There are many results which state that certain properties are generic for certain families of algebras. For example, it is not hard to prove that the centre of $A/\mathfrak{m} A$ attains its minimal value on a Zariski open subset of $\operatorname{Max}(Z_0)$. I believe that if $A/\mathfrak{m}A$ is a simple algebra for some $\mathfrak{m}$ then the same is true generically, although I don't know a proof, perhaps other hypotheses are needed. As a side question, does anyone know a proof for this claim?
I want to understand some examples where $A$ has countable rank as a free $Z_0$-module, and $Z_0$ is a countably generated central subalgebra of $A$. Provided the cardinality of the field is uncountable or greater the maximal ideals of $Z_0$ have codimension 1 over $\mathbb{k}$ and so we have a  reasonable description of $\operatorname{Max}(Z_0)$. What can be said about generic properties of such families? Is there an obvious replacement for the Zariski topology on $\operatorname{Max}(Z_0)$? This is the first obvious question if you want to claim that some property is generic in this case. Are there any known results about generic properties for such families of algebras?
I'd be especially interested in ideas which work over fields of characteristic $p > 0$ but obviously I'm interested to hear comments which only apply to $\mathbb{C}$, for example.
My interest in this question came from considering representations of countable dimensional restricted Lie algebras: the enveloping algebra of such a Lie algebra $\mathfrak{g}$ in characteristic $p > 0$ is a free module over the $p$-centre, and the latter is a countably generated polynomial ring.


text:
Q: This may be because the user has not allowed the application to access location information Pick Place error The operation couldn't be completed. The Places API could not find the user's location. This may be because the user has not allowed the application to access location information. How to solve it?

A: So what I understand from your question, you are trying to fetch the users current location, but you are getting the above mentioned error.
In iOS it is mandatory to request permission from user to access the user's current location. You can request the permission by creating an instance of the CLLocationManager & then calling the appropriate method. The appropriate method can be based on your requirement whether you want to use the location services while the app is running or always. So here is how you do it:
let locationManager = CLLocationManager()
// For getting the user permission to use location service when the app is running
locationManager.requestWhenInUseAuthorization()
// For getting the user permission to use location service always
locationManager.requestAlwaysAuthorization()

After that make sure to add an appropriate key to the Info.plist file as follows:
<key>NSLocationWhenInUseUsageDescription</key>
<string>Your location is required to show suggestions</string>

OR
<key>NSLocationAlwaysUsageDescription</key>
<string>Your location is required to show suggestions</string>

The string for the key is optional. But it recommended to include a proper string which describes why your app wants to access user's location.


text:
Q: Azure AD using token from client application in Web API I have the following setup:
2 Client applications (Xamarin Forms and WPF) and a single Web API (.NET Core 2.0).
The client applications use the MSAL library to authenticate against Azure AD (Single Tenant application).
After the client applications are authenticated they can call the Web API using their authentication token.
The Web API should authenticate this token ([Authorize] in the controllers) if it is valid and to know what user is calling the API.
Authenticating the clients is no problem, using the AcquireTokenInteractive and AcquireTokenSilent methods this was made very easy.
When calling the Web API (using HttpClient we add the token in the headers: client.DefaultRequestHeaders.Add("Bearer", token);.
The Web API is (removed all test code) configured like this (and I know this is not enough) in the Startup.cs class:
services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
                .AddAzureADBearer(options => Configuration.Bind("AzureAd", options));

This is the template you get when creating a new project with Azure AD configured.
In the Azure AD Portal we have configured out Application and the ID's (TentantId, ClientId/ApplicationId) are configured on the client applications and the Web API.
We have done reseach in the On-Behalf-Of flow but I'm not sure that this is the flow we need.
The application is registered as a Single tentant application and the Suggested Redirect Uriis set to msal[UNIQUE_ID_I_REMOVED_FOR_SECURITY]://auth should this be set to https://login.microsoftonline.com/common/oauth2/nativeclient
We do not have experience with the Azure AD flow and could use some help. If anybody can point me in the correct direction with links, documentation, sample code it would be greatly appreciated.
Thank you for any help.

A: This sample shows how to call a core API from a WPF application using the V1 endpoint or this one if using V2 endpoint. The API needs to know 1) who issued the token (authority) so it can get its issuer name and signing keys 2) its audience id so it can validate whether the incoming token's audience is for it (usually a guid or uri). OBO flow would become only relevant to you if your API needs to call yet another API on-behalf of the original user: the flow allows you to exchange a token you recived (API1) for a token to another API (API2) preserving information about the original user.


text:
Q: magnitude of the best approximants denominator for an irrational number If the irrationality measure of an irrational number $x\in \mathbb{R}$ is some $\mu>0$, it implies that for $\mu'<\mu$ there are infinitely many couples of integers
$(p_n,q_n),n\in \mathbb{N}$ such that $$|x-p_n/q_n|<q_n^{-\mu'}.$$
The $p_n,q_n$ can be expressed by the means of the continued fraction of $x$.
Is it possible in general to choose the $q_n$ with a not too large magnitude, such as $q_n\leq C n^a$ for some $C,a>0$?


text:
Q: How to dynamically reference to another cell in other workbooks? i'm trying to create an excel workbook that will automatically collect data from other workbooks in the directory i come up with a code but it does not work correctly
="'"&LEFT(CELL("filename",$A$1),FIND("~",SUBSTITUTE(CELL("filename",$A$1),"[","~",1))-1)&"["&RIGHT(LEFT(CELL("filename",$A$1),FIND("~",SUBSTITUTE(CELL("filename",$A$1),"[","~",1))-2),3)&RIGHT(LEFT(CELL("filename",$A$1),FIND("~",SUBSTITUTE(CELL("filename",$A$1),"[","~",1))+16),1)&".xlsx]Final Data'!"&E3

if i use this code it will call the value of the E3 in the current workbook if i use ADDRESS(3,5) it will give me the right address but the moment i put =INDIRECT() before it, the value of E3(in the current workbook) will come up (the other file is open since i'm using indirect). how can i correct this and is there a way to get ell values while the file is closed ?


text:
Q: Chrome does not resize SVG image I would like to read in a SVG file, determine its width and height in order to scale it. At the moment, my code looks as follows:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <style type="text/css" media="all">@import "style/style.css";</style>
  <meta name="svg.render.forceflash" content="false" />
  <script src="svg.js" data-path="svgweb/src/"></script>
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js">   </script>
  <script type="text/javascript">
    $(window).load(function() {
      function loadContent(){
        /*  SVG  */
        var svg = document.getElementById('myimage')

        /*  Adapt size of SVG */
        try {
      SVGDoc = svg.contentDocument;
    } catch (Err) {
      SVGDoc = svg.getSVGDocument;
        }
        var root = SVGDoc.documentElement;
        if (root.attributes['width'] != null) {
        var width = root.attributes['width'].nodeValue;
        width = width.substring(0, width.length - 2);
        width = (width * 1.25);
        var height = root.attributes['height'].nodeValue;
        height = height.substring(0, height.length - 2);
        height = (height * 1.25);
        svg.width = width;
        svg.height = height;
      }
</script>
</head>
<body>
  <div id="map">
    <!--[if IE]>
    <object id="myimage" src="images/myimage.svg" classid="image/svg+xml">
    <![endif]-->
    <!--[if !IE]>-->
    <object id="myimage" data="images/myimage.svg" type="image/svg+xml">
    <!--<![endif]-->
    </object>
  </div>
</body>
</html>

This code works fine in Firefox (although one can see for a very short time the resizing). However, the developer tool within Chrome nags: Uncaught TypeError: Cannot read property 'documentElement' of undefined for the line "var root = SVGDoc.documentElement;". In addition, Chrome does not resize the image.
I can't find a working solution for both browsers.

A: First, getSVGDocument() is a method, not a property. You have to call it:
SVGDoc = svg.getSVGDocument();

Second, SVGDoc itself should be declared somewhere:
var SVGDoc;

Third, Chrome's same origin policy does not like the file: protocol. You'll have to serve your SVG images instead of reading them from local files.


text:
Q: Can you restore deleted messages on iPhone 6 from iPad? While trying to delete a few messages, I accidentally deleted all messages from a contact on my iPhone, but they're all still there on my iPad. For some reason, iCloud backup doesn't include the messages. Can I restore the deleted messages on the iPhone using my iPad? And how do I include messages in iCloud backup for the future?

A: The only way to get your messages back on your iPhone is to restore your iPhone from a backup that predates when you deleted the messages.
Right now there is no option to include messages in iCloud backups. Starting with iOS 11, however, there will be. In iOS 11 beta 1, there's an option in Settings to enable full chat archive synchronization in iCloud.


text:
Q: Insert into view In Oracle I create a view using a 'union all' as below
create view TESTVIEW as
select column1 from TABLE1
union all
select column1 from TABLE2;

If I want to insert into this view I get
SQL Error: ORA-01732: data manipulation operation not legal on this view
Is there any way around this if I know I want to insert in TABLE1?

A: Yes, you should be able to create an INSTEAD OF INSERT trigger on the view.
You'll need to write the trigger to insert the row in the base table, and it will run "instead of" the original insert.

A: Please refer http://docs.oracle.com/cd/E17952_01/refman-5.1-en/view-updatability.html to understand which views are directly updatable. For views which are not directly updatable use "Instead of" trigger as suggested in the above post.


text:
Q: Union of locally finite family of $G_\delta$ sets Is an arbitrary union of a locally finite family of $G_\delta$ sets is again $G_\delta$?
Suppose my collection of $G_\delta$ sets are $\left\{G_\lambda=\bigcap_{i\ge 1} G_i^\lambda:\lambda\in\Lambda\right\}$, where $G_i^\lambda$ are open sets. Then, $$\bigcup_{\lambda\in\Lambda} G_\lambda=\bigcup_{\lambda\in\Lambda}\bigcap_{i\ge 1}G_i^\lambda=\bigcap_{\alpha\in\mathbb{N}^\Lambda} \bigcup_{\lambda\in\Lambda}G_{\alpha(\lambda)}^\lambda$$ Now, $A_\alpha=\bigcup_{\lambda\in\Lambda}G_{\alpha(\lambda)}^\lambda$ is clearly open for each $\alpha \in \mathbb{N}^\Lambda$. But I am unable to show that the intersection $\bigcap_{\alpha \in \mathbb{N}^\Lambda}A_\alpha$ can be made countable.
Is my approach correct? Also if the claim is false itself, can someone please provide any counter-example? Any help regarding this is appreciated!

A: Define a new topology $\tau$ on $\Bbb R$ as follows. Each $x\in\Bbb R\setminus\Bbb Q$ is isolated. For $q\in\Bbb Q$ and $\epsilon>0$ let
$$B(q,\epsilon)=\{q\}\cup\{x\in\Bbb R\setminus\Bbb Q:|x-q|<\epsilon\}\;;$$
$\{B(q,\epsilon):\epsilon>0\}$ is local base at $q$. I'll use $X$ to denote the reals with the topology $\tau$.
Clearly $\Bbb Q$ is a closed, discrete subset of $X$. Moreover, $X$ is first countable, so $\{q\}$ is a $G_\delta$ for each $q\in\Bbb Q$, and $\big\{\{q\}:q\in\Bbb Q\big\}$ is a locally finite family of $G_\delta$ sets.
Suppose that $\Bbb Q\subseteq U\in\tau$; then $U$ contains a Euclidean open nbhd of $\Bbb Q$, which is of course a dense open set in $\Bbb R$ with the usual topology. Let $\{U_n:n\in\Bbb N\}\subseteq\tau$ be a family of open nbhds of $\Bbb Q$ in $X$; without loss of generality we may assume that each $U_n$ is open in the usual topology. By the Baire category theorem $\Bbb Q$ is not a $G_\delta$ in the usual topology of $\Bbb R$, so $\bigcap_{n\in\Bbb N}U_n\ne\Bbb Q$, and $\Bbb Q$ is not a $G_\delta$ in $X$, either.


text:
Q: Show number of zeros of $z^9+z^5-8z^3+2z+1$ in between $\vert z \vert =1$ and $\vert z \vert = 2$ So using Rouche's theorem we need to find the number of zeros
$$z^9+z^5-8z^3+2z+1$$
has on $\{z \in \mathbb{C}: 1 < \vert z \vert < 2\}$
(i) For $\vert z \vert = 1$ I let the "smaller" function be
$$g(z)=z^9+z^5$$
and my "bigger" or dominating function to be the rest, so
$$f(z) = -8z^3+2z+1$$
and if $\vert z \vert = 1$ we clearly have
$$\vert g(z) \vert \leq \vert f(z) \vert.$$
Then here there's 3 zeroes.
(ii) For $\vert z \vert = 2$, I swapped the big and little thus
$$g(z)=-8z^3+2z+1$$
and
$$f(z) = z^9+z^5$$
which has 9 zeroes and thus inside the annulus we have $9-3=6$ zeros. Is this correct?

A: Your estimates are correct, but for the first part you still have to show that $f(z) = -8z^3+2z+1$ has three zeros in $|z| < 1$.
It becomes a bit simpler if you split the polynomial in
$$
g(z) = z^9+z^5+2z+1 \, , \, f(z) = -8z^3
$$
for the zeros in $|z|< 1$, and in
$$
g(z) = z^5-8z^3+2z+1\, , \, f(z) = z^9
$$
for the zeros in $|z|< 2$.


text:
Q: get an array of dates from today for datepicker with Javascript I am trying to write a function that returns an array of dates from today till the maximum date, so that I can restrict the date picker selection.  At the moment I have the following:-
   datesAfterToday: function (date) {
    var dates = []
    var currentDate = new Date()
    var endDate = new Date(8640000000000000).getFullYear()
    var addDays = function (days) {
      var date = new Date(this.valueOf())
      date.setDate(date.getDate() + days)
      return date
    }
    while (currentDate <= endDate) {
      dates.push(currentDate)
      currentDate = addDays.call(currentDate, 1)
    }
    return dates
  }

and then I am using Vue.js to mount it as follows :-
 mounted () {
   this.allowedDates = this.datesAfterToday
 },

however I am only getting an array of objects instead of the proper array.
How can I get the proper array of dates so that I can bind it to the allowdates property.
Thanks for your help and time!

A: For starters new Date(8640000000000000).getFullYear() will set endDate to the year of that date, which is 275760. currentDate will be today's date (in milliseconds), which at the time of me writing is 1511272934156. As you can see currentDate is always greater than endDate, so your while loop never goes to the statements inside.
Another issue is that the date you picked is really far in the future and you're populating an array one day at a time. Your loop will most likely make the page freeze or crash completely. Try picking a date that's more manageable.
For instance, in the snippet below I set endDate by first initializing it to today, then setting the year to exactly one year from now. This gives me an array with roughly 365 values.
You can imagine how big this array would be if I used a year that was 273,748 years in the future.

var dates = []
var currentDate = new Date()
var endDate = new Date()

endDate.setFullYear(endDate.getFullYear()+1)

var addDays = function (days) {
  var date = new Date(this.valueOf())
  date.setDate(date.getDate() + days)
  return date
}

while (currentDate <= endDate) {
  dates.push(currentDate)
  currentDate = addDays.call(currentDate, 1)
}

console.log(dates)

With all that being said, it looks like you're actually allowed to pass an object specifying the minimum and maximum values rather than an array.
https://vuetifyjs.com/components/pickers#example-6
let d = new Date()                  // today
let d2 = new Date()
d2.setFullYear(date.getFullYear()+1) // Next year

this.allowedDays = {
    min : d.toISOString().substr(0, 10), // e.g. 2017-11-21
    max : d2.toISOString().substr(0, 10)
}

A: Another option would be to use vuejs-datepicker  For example:
<script>
var state = {
    disabled: {
        to: new Date(), // Disable all dates up to specific date
        from: new Date(8640000000000000) // Disable all dates after specific date
    }
}
</script>

<datepicker :disabled="state.disabled"></datepicker>

See Disabled Dates in the documentation.


text:
Q: Angular UI Bootstrap datepicker Does anybody have an idea how to find out which timespan the datepicker popup cuurently shows and how to apply additional classes on some days?

A: Generally speaking I use moment.js for all of my date calculations / display.  That said, Angular does provide a decent enough date filter for displaying..


text:
Q: Synchronising messages from multiple ZeroMQ publishers I'm trying to create a stock monitoring application. I have two ZeroMQ publishers running that get the current stock price from two respective services. The first service is the major source of information and no message from the service can be dropped.
I want to combine the two prices into one object and push it to the front-end.
Each message has a timestamp that indicates the time of the observation of the price and is the basis of combining the messages.
However, both the messages do not arrive at the same time and the system has to wait until both the messages have arrived and then combine them and subsequently push them to the front-end.
I have been able to get it working using an in-memory map that stores the messages indexed by timestamp and checks if both the messages have arrived. If they haven't, it waits for a certain time before sending the messages. The message delivery is expected to be in order and the data from the first service cannot be dropped.
const messageQueue = new Map();

monitoringServiceOne.on('message', function (topic, message) {
   synchroniseMessages(topic, message);
});

monitoringServiceTwo.on('message', function (topic, message) {
   synchroniseMessages(topic, message);
});

function synchroniseMessages(topicName, incomingMessage) {

    if (topicName == "ServiceOne") {
        const message = messageQueue.get(message.time);

        // If message exists, it means service two message has been received
        if (message) {
            pushToFE({ ... { message }, "ServiceOne": incomingMessage })
        } else {
            setTimeout(() => {
                const message = messageQueue.get(message.time);
                if (message) {
                    pushToFE({ ... { message }, "ServiceOne": incomingMessage })
                }
            }, DELAY)
        }
        messageQueue.set(message.time, { "ServiceOne": incomingMessage });
    } else {
        const message = messageQueue.get(message.time);

        // If message exists, it means service one message has been received
        if (message) {
            pushToFE({ ... { message }, "ServiceTwo": incomingMessage })
        } else {
            messageQueue.set(message.time, { "ServiceTwo": incomingMessage });
        }
    }

}

Even though this is working, I feel like reinventing the wheel. Are there any existing ZeroMQ paradigms or patterns that I can use to improve the code? I have been looking for an event-driven pattern that allows me just define the logic for the sink.

A: The short answer is no, there's nothing in ZMQ that'll do that for you. It's an actor model system, and all it does is guarantee that whole messages will turn up in the order they were sent machine to machine. There are no timing guarantees.
For example, if there is a PUB / SUB setup and there are two or more PUBlishers (an allowed combo I think), the time order in which messages are PUBlished by different PUBlishers does not necessarily result in them arriving in that order in the SUBscriber. But it does guarantee that multiple messages sent by any one of those PUBlishers won't get swapped around in transit.
So, if your ServiceOne and ServiceTwo were PUBlishers on the same ZMQ socket, you could not be confident of getting messages in the order 1a, 2a, 1b, 2b, 1c, 2c, 1d, 2d, 1e, 2e, 1f, 2f, 1g, 2g. They could arrive as 1a, 2a, 1b, 1c, 2b, 2c, 2d, 1d, 2e, 1e, 1f, 2f, 1g, 2g. The numbers need not be in order, but the letters for any one given number will be.
I like the idea of using a map (a dictionary? My node.js knowledge is very limited...), elegant. Presumably, you'd have to have something to prune the map now and then, e.g. if ServiceOne got disconnected for a while the map could get quite large.
Er, is it supposed to be incomingMessage.time that's used in the call to messageQueue.get(), so messageQueue.get(incomingMessage.time), and similar for the messageQueue.set()?


text:
Q: Does Magento send the order increment_id to paypal? I'm interrested in matching orders paid with PayPal by their increment id.
Therefore I want to use a summary (from PayPal) of orders and compare it with a list of the increment ids provided by the magento backend.
Currently I'm doing this by opening the transactions panel in the backend and match the transaction numbers. Is there a option doing this the way described above?!

A: Yes If you are using Magento's Paypal standard module then the increment_id is sent over to Paypal and here is the proof:

A: It seems it is possible with some of the explained here.
You can use the paypal_prepare_line_items event and create an Observer to add some more info.
There are 2 other events for PayPal, im not sure if they will fit better. Check them here.

A: Yes, I think Magento pass the increment id into Paypal. If you look at transaction detail in your Paypal page, you can see that increment id.
But I do not really understand what you are trying to do. Can you be more specific? I may assist you with this.


text:
Q: Model Accepts Nesting Attributes without declaring that it accepts them everyone. So, I'm working on a basic Rails 4 application for practice, and I have a model for FriendCircle and a model for FriendCircleMembership. (the FriendCircleMembership's corresponding table is basically a join table).
In the console, I'm able to create a new FriendCircle object while passing in :friend_circle_memberships_attributes. This successfully inserts a new FriendCircle row into my table as well as inserting the proper rows into the FriendCircleMembership table.
The WEIRD thing is that, even if i comment out that the FriendCircle accepts_nested_attributes for :friend_circle_memberships, it still works. Is this because i am whitelisting it as a permission in the controller?
The other issue is that, even though i can successfully make the nested objects via the rails console, when i try making it through my html form it says my friend_circle_memberships_attributes is an unpermitted parameter. Not sure why this is happening. I check the incoming parameters and they look fine.
any help would be SWEEEEET. thanks.

A: I determined what the error was: One of my controllers for a nested attributes was validating the presence of the id of the controller it was nested under.
I'm assuming the validation occurs before an id is created, which makes sense, but im not 100%. So i just took out the validator and things worked.


text:
Q: Dynamically create and add new component on button click in Angular Dart I have a problem very similar to the one asked here How to add a component programatically in Angular.Dart?.  I am using Angular Dart and have a task bar component that I want to fill with a list of task components.  I would like a new task component to be added when a button is pressed.  Here is the code I currently have.
task_bar_component.html

        {{task}}

task_bar_component.dart
@Component(
    visibility: Directive.CHILDREN_VISIBILITY,
    selector: 'taskbar',
    templateUrl: '../lib/components/taskbar_component.html',
    publishAs: 'taskbarCmp',
    useShadowDom: false)

class TaskBarComponent {
  List tasks;

  TaskBarComponent() {
    tasks = new List();
  }

  void addTask() {
    var newTask = new TaskComponent();
    tasks.add(newTask);
  }
}

task_component.dart
@Component(
    visibility: Directive.CHILDREN_VISIBILITY,
    selector: 'task',
    templateUrl: '../lib/components/task_component.html',
    publishAs: 'taskCmp',
    useShadowDom: false)

class TaskComponent {
  bool _collapsed = true;
  int _lopCount = 0;
  int _geoCount = 0;
  int _volume = 1;
  String id;

  TaskComponent() {
    Collapse.use();
  }
}

This code currently adds an "Instance of 'TaskComponent'" to the html on the button click, but it does not contain the actual task_component.html.  I tried using the ShadowRootAware from the solution in the previous question but am not sure how onShadowRoot gets called when the button is pressed.  I also tried to use the directive solution that was suggested in that post as well and had the same issue, not being able to create the component when the button is pressed.  ANy suggestions would be greatly appreciated.

A: Actually, your code doesn't work because

{{task}}

don't call the view of your component, it try to display the object directly, and it's not what you want.
To get the behavior that you want, you need do more like that :
class Task {
   // What you want in your task
}

@Component(
   visibility: Directive.CHILDREN_VISIBILITY,
   selector: 'task',
   templateUrl: '../lib/components/task_component.html',
   publishAs: 'taskCmp',
   useShadowDom: false)

class TaskComponent {
  @NgTwoWay('task')
  Task task;
  // What you want for you task view

  TaskComponent() {
    Collapse.use();
  }
}

// task bar
class TaskBarComponent {
  List<Task> tasks;

  TaskBarComponent() {
    tasks = new List();
  }

  void addTask() {
     var newTask = new Task();
     tasks.add(newTask);
  }
}

and in your html :

      <task task="task"></task>

In this case, you have perfectly separate the logic from the view and get the modularity of Angular Component

A: I would suggest more something like

        <task id={{task.id}}>
{{task.caption}}

{{task.description}}
</task>

and your collection of tasks in your component holds instances of Task classes with the data attributes that define your task (like the id, caption and text attributes I used in the example).


text:
Q: Using the Apple Wireless Keyboard with an iPad with PC/Mac-like keyboard commands I have jailbroken iPad 2 (iOS5.1.1) and an Apple wireless Bluetooth keyboard that I use for typing on the iPad. Although the keyboard is a joy to use, I can't use it for much else other than typing documents and creating notes.
I'd like to be able to use some kind of keyboard shortcuts to move around/switch between apps, use shortcuts like Cmd + K or Ctrl + K in the browser and so on.
Is this somehow possible? And if so how?

A: BeeKeyboard is a tweak available via Cydia that adds the ability to create custom keyboard shortcuts. I'm not sure if it can do app-switching shortcuts, but you can install a plugin called BeeSafari to add some browser shortcuts.

A: When you're in a programme, press and hold the CMD button, a pop-up should appear giving you a list of commands.


text:
Q: Wavy top div css I have looked around on the web and found a few good solutions on how to make a wavy div on the bottom but I could not find anything on how to make the top wavy. This is what I was attempting to reverse to make it on top: https://css-tricks.com/creating-non-rectangular-headers/
Here is an image of what I am trying to accomplish (The wavy top with css, bottom is straight). Any help would be great


text:
Q: 'stationary' almost disjoint families Consider almost disjoint families on regular $\kappa > \omega$ consisting only of stationary sets.
My question: Is there consistently an upper bound $<2^\kappa$ on the size of such a 'stationary' almost disjoint family (under suitable large cardinal assumptions)?
E.g. a Woodin cardinal implies the consistency of '$\text{NS}_{\aleph_1}$ is $\aleph_2$-saturated', which implies that any s.a.d. family has size $\leq \aleph_1$. However, as $X_i \cap X_j$ is not only non-stationary but bounded in $\kappa$, maybe weaker assumptions also imply the consistency of 'Every s.a.d. family on $\aleph_1$ has size $\leq \aleph_1$' ? (solved)
EDIT: The following cases for $\kappa$ remain open:
Always require $2^\kappa > \kappa^+$:

*

*$\kappa=\kappa^{<\kappa}$ and $\text{sad}< 2^\kappa$ ?

*$\text{sad} < \text{sat}(\text{NS}_\kappa)$ ?

*and, of course, $\text{sad} < \text{min} \{\text{sat}(\text{NS}_\kappa), \text{mad}\}$ ?

A: First let us show that consistently there is no such bound, along with $2^\kappa$ larger than any prescribed cardinal. Assume $\diamondsuit_\kappa$.  This is consistent with any large cardinal assumption and any value of $2^\kappa$, by forcing with $Add(\kappa,\theta)$.  This principle states:

There is a sequence $\langle a_\alpha : \alpha < \kappa \rangle$ such that for every $X \subseteq \kappa$, $\{ \alpha : X \cap \alpha = a_\alpha \}$ is stationary.

It is easy to see that if $X \not= Y$, then the set points where the diamond sequence guesses $X$ is almost-disjoint from the set where it guesses $Y$.
Thus under $\diamondsuit_\kappa$, there is an almost-disjoint family of stationary subsets of $\kappa$ of maximal size.
Second, let us show that consistently there is such a bound.  This is inspired by exercise 23.11 in Jech.  Suppose GCH holds in $V$.  Force with $Add(\omega,\omega_3)$.  In the extension, $2^{\omega_1} = \omega_3$.  We will show that there is no almost-disjoint family of subsets of $\omega_1$ of size $\omega_3$.  Suppose otherwise and let $\langle \dot A_\alpha : \alpha < \omega_3 \rangle$ be a name for a counterexample.  For each pair $\alpha<\beta$, it is forced that $A_\alpha \cap A_\beta$ has size $<\omega_1$, and by the ccc, there is some ordinal $\delta_{\alpha,\beta}$ such that $1 \Vdash \dot A_\alpha \cap \dot A_\beta \subseteq \check \delta_{\alpha,\beta}$.  By the Erdos-Rado theorem (and GCH), there is some $X \subseteq \omega_3$ of size $\omega_2$ and a $\delta <\omega_1$ such that $\delta_{\alpha,\beta} = \delta$ for all $\alpha,\beta \in X$.  Thus it is forced that $\{ A_\alpha \setminus \delta : \alpha \in X \}$ is pairwise disjoint.  This is impossible.