text:
Q: How to populate hosts file with IPs then invoke ansible playbooks I have 2 "aws_instance" resource modules one for master, and another for multiple worker instances. Here's the Terraform code:
#Create and bootstrap EC2 Kubernetes Master in us-east-1
resource "aws_instance" "kubernetes-master" {
  provider = aws.region-master
  ami = "ami-0747bdcabd34c712a" #Ubuntu 18 x64
  instance_type = var.instance-type
  key_name = aws_key_pair.master-key.key_name
  associate_public_ip_address = "true"
  vpc_security_group_ids = [aws_security_group.kubernetes-sg.id]
  subnet_id = aws_subnet.subnet_1.id

  tags = {
    Name = "kubernetes_master_tf"
  }

  depends_on = [
    aws_main_route_table_association.set-master-default-rt-assoc
  ]

  provisioner "local-exec" {
    command = <<EOF
aws --profile ${var.profile} ec2 wait instance-status-ok --region ${var.region-master} --instance-ids ${self.id}
ansible-playbook --extra-vars 'passed_in_hosts=tag_Name_${self.tags.Name}' ansible_templates/kubernetes-master.yml
EOF
  }
}

#Create EC2 Kubernetes Workers in us-east-1
resource "aws_instance" "kubernetes-worker" {
  provider = aws.region-master
  count = var.workers-count
  ami = "ami-0747bdcabd34c712a" #Ubuntu 18 x64
  instance_type = var.instance-type
  key_name = aws_key_pair.master-key.key_name
  associate_public_ip_address = "true"
  vpc_security_group_ids = [aws_security_group.kubernetes-sg.id]
  subnet_id = aws_subnet.subnet_1.id

  tags = {
    Name = join("_", ["kubernetes_worker_tf", count.index + 1])
  }

  depends_on = [
    aws_main_route_table_association.set-master-default-rt-assoc
  ]

  provisioner "local-exec" {
    command = <<EOF
aws --profile ${var.profile} ec2 wait instance-status-ok --region ${var.region-master} --instance-ids ${self.id}
ansible-playbook --extra-vars 'passed_in_hosts=tag_Name_${self.tags.Name}' ansible_templates/kubernetes-worker.yml
EOF
  }
}

The idea is to invoke ansible-playbooks on them right after they're initiated. Though I stumbled upon an issue. To apply some configuration I need all these instances to include all private_ips of all instances including their own in the HOSTS file. So based on this answer I ended up with this code that is supposed to populate all hosts files with all IPs:
resource "null_resource" "write_resource_cluster_member_ip_addresses" {
  depends_on = ["aws_instance.kubernetes-master", "aws_instance.kubernetes-worker"]

  provisioner "local-exec" {
    command = <<EOF
echo ${ aws_instance.kubernetes-worker.*.private_ip } kubernetes-master # ${ aws_instance.kubernetes-master.id } >> /etc/hosts
echo '${join("\n", formatlist("%v kubernetes-worker # %v", aws_instance.kubernetes-worker.*.private_ip, aws_instance.kubernetes-worker.*.id))}' >> /etc/hosts
EOF
  }
}

But I now have no idea how to invoke ansible playbooks AFTER editing hosts files. The issue is also that the playbooks I am using are Master/Worker specific: "kubernetes-master.yml", "kubernetes-worker.yml", which makes it only more difficult to come up with a solution.

A: Ok, looks like it's quite simple. There's a resource "local_file" which does the trick:
resource "local_file" "instance_ip_file" {
  depends_on = [aws_instance.kubernetes-master, aws_instance.kubernetes-worker]

  content  = join("\n", concat([aws_instance.kubernetes-master.public_ip], aws_instance.kubernetes-worker.*.public_ip))
  filename = "${path.module}/instance_ip_file.txt"
}


text:
Q: RxJava - RepeatWhen not cancelling after disposal? I have a repeating observable, but when it comes time to dispose of it, such as when I move to another screen, it continues to repeat in the background?
I'm positive it's being disposed of as I've stopped the code and confirmed it's happening.  I'm also positive that it's not being restarted as the function never gets called again once I move to the new screen.
At first I thought it was just going to stop, but after some reading, it sounds like the repeat might be outside of the disposable I'm clearing, so I tried adding that if/else in the repeat when statement.
 observable.observeOn(AndroidSchedulers.mainThread())
                .repeatWhen { result ->
                    if(!disposable.isDisposed) {
                        result.delay((20000 + delay), TimeUnit.MILLISECONDS)
                    }else {
                        Observable.empty<Int>()
                    }
                }
                .subscribeOn(Schedulers.io())
                .subscribe({ result ->
                    //Do something
                }, { error ->
                    error.printStackTrace()
                }).addTo(tickerDisposables)

How do I make this stop when I call call disposables.dispose and switch screens?
Note - The observable is generic type so I need to add a type when doing the Observable.empty()
Update: looks like the problem is somewhere else in my code. The size of my tickerDisposable is empty by the time I try to dispose it, so it's not stopping the calls.  If I find where that is it should fix the issue.

A: So I'm not sure I understand why this resolves the issue yet, but the following resolved it.
Originally my dispose call was happening in onStop(). I noticed that my dispose call worked when I closed the app, but it wasn't working when I launched a new activity.
I tried moving the dispose to my onPause instead, figuring that maybe by the time onStop has called the references in the disposable were lost, and it now works properly.
This might be a side effect of how my repos are set up?  I'd have to investigate further, but that's what was wrong.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Phonegap on Android: Layout scrollable when using keyboard I just started creating a mobile application with Maqetta for phonegap on Android and WindowsPhone. The application includes some webpages with text-input so I need the soft-keyboard to work.
My problem is that the keyboard reacts totally different on the two operating systems. On windows phone, when I click a  text box, the Keyboard shows up and covers all the things that are located underneath it. To reach the other text boxes, I can still scroll in the field that shows my website and select it. In addition, which is quite important for me, the website is not compressed. That is exactly what I want.
On Android, things are a little more complicated. After doing a lot of research I stumbled upon these guys:
android:windowSoftInputMode="adjustResize" and
android:windowSoftInputMode="adjustPan"
I have tried both, but both do not fit my needs.
adjustRezise compresses my website (because the website is height:100%) and adjustPan covers everything underneath it without any possibility to reach it (except for closing the keyboard and reopening it for every textbox // and having to type without seeing what you type).
I have also heard about ScrollViews and stuff like that, but as I am new to this topic i have no clue what the heck that is and how to use it, because i am focusing on the html and css part of the app, so if you have any tips there please keep in mind that it might take some information for me to understand. ;)
I would be very happy if one of you could help me with this problem. I hope there is a solution.

A: Setting height: 150% did not work for me. It made page scrollable even if there is not enough content to scroll. Following solution (mixed of CSS & Javascript) worked for:

*

*In CSS: I kept height of app/HTML: 100%; and overflow-y: auto;
#container {
   height: 100%;
   overflow-y: auto;
}

*Detect focused textarea or input, then wait a while until keyboard is shown and finally scroll the page to reach focused input.
$("#textarea").focus(function(e) {
    var container = $('#container'),
    scrollTo = $('#textarea');

    setTimeout((function() {
       container.animate({
       scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop()
       });
    }), 500);

});

When keyboard is hidden the text-area keeps focused, so if it's clicked again the keyboard will show and the container needs to scroll again to show the input
$("#textarea").click(function(e) {
    e.stopPropagation();
    var container = $('#container'), //container element to be scrolled, contains input
    scrollTo = $('#textarea');

    setTimeout((function() {
        container.animate({
        scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop()
      });
    }), 500);
});


text:
Q: What is the equivalent increment! on mongoid I am new to mongoid, I am trying to use increment! method and getting an error.
myinstance.increment!(:number_of_calls)

=> undefined method `increment!' for #Myinstance:0x00007faac25f8448

A: Probably Model#inc in https://docs.mongodb.com/mongoid/master/tutorials/mongoid-persistence/#atomic though you have not said what you expect increment! to do.


text:
Q: Linear operators with zero eigenvalues increase the kernel Let $V$ be a $n$-dimensional vector space. In a proof that any linear operator $f$ on $V$ with only zero eigenvalues is nilpotent, the following reasoning is made:
For any linear operator $f$, $\ker f\subseteq \ker f^2$. However, since $f$ only has zero eigenvalues, $\ker{f}\neq \ker{f^2}$ unless $\ker{f}=V$. Therefore the following chain
$$
\ker f\subset \ker f^2 \subset \ker f^3 \subset \ldots
$$
implies $\ker f^k=V$ for some $k\leq n$, so that $f$ is nilpotent.
I do not see why for any $f$ with only zero eigenvalues $\ker{f}\neq \ker{f^2}$ unless $\ker{f}=V$. Is it so clear?

A: One way: Suppose $\ker f=\ker f^2$.  Apply rank-nullity to get $f(V)=f^2(V)$, and so if $f(V)\neq 0$ we would get a nonzero eigenvalue for $f\vert_{f(V)}$.  But each eigenvalue of $f\vert_{f(V)}$ must be an eigenvalue of $f$, so $f(V)$ must be $0$.


text:
Q: How can I color the background of multiple selected items in Vue? I have code below for category selection. When a category is selected, it sets its background to green, otherwise the background is gray; this works fine.
What I want to achieve is when I select multiple items, I want it to keep the background green for all selected categories. Is there a way to do this?

  {{ category.category_name }}

A: The only major change that needs to be made to accommodate this is to make selectedIndex an array rather than a single value, so that we can hold more than one selection.
Eg.:

*

*Set selectedIndex to an array [] in data()

*When clicked, we should push the value onto the array instead of setting it equal

*To check if a given index is selected, we use selectedIndex.includes(index) instead of selectedIndex == index
There's one other side effect to allowing multiple selection though, which is adding support for on-click deselection. But this is also fairly simple, we just need to check whether selectedIndex already contains the value in Add(), and if it does, remove it. We can use Array.prototype.splice() to do this.
Here's an interactive version:

new Vue({
  el: '#app',
  data() {
    return {
      selectedIndex: [],
      categories: [{ _id: 0, category_name: 'noodles' }, { _id: 1, category_name: 'pizza' }, { _id: 2, category_name: 'hamburgers' } ],
    }
  },
  methods: {
    Add(AddCategory, index) {
      //Check if item is selected...
      if (this.selectedIndex.includes(index))
        this.Remove(index); //If so, remove from selectedIndex
      else
        this.selectedIndex.push(index); //If not, add to selectedIndex
    },
    Remove(index) { //Find index in selectedIndex, and splice out
      this.selectedIndex.splice(this.selectedIndex.indexOf(index),1);
    },
    RemoveAll() { //To deselect all, we empty the selectedIndex array
      this.selectedIndex = [];
    },
  }
});
.green {
  background-color: #41B883;
}

.gray {
  background-color: #e5e0ed;
}

    {{ category.category_name }}

  <button @click="RemoveAll">Unselect All</button>

A: That's because you are doing it based on the index, so the index is unique and also changing on each click. Try a property for each category such as selected and make it false as default. Then in your click function just do this.categories[index].selected = !this.categories[index].selected. After that bind the class to the category.selected value.


text:
Q: Why must all list literals being concatenated be parenthesized in kdb to prevent type error, but the last one can be left unparenthesized? What's this about?
q)(42+2*til 10),(til 10),til 3
42 44 46 48 50 52 54 56 58 60 0 1 2 3 4 5 6 7 8 9 0 1 2
q)(42+2*til 10),til 10
42 44 46 48 50 52 54 56 58 60 0 1 2 3 4 5 6 7 8 9

q)(42+2*til 10),til 10,til 3 / til 10 is not a list?
'type
  [0]  (42+2*til 10),til 10,til 3 / til 10 is not a list?
                     ^
q)type til 10
7h
q)type (til 10)
7h

Just wondering what the interpreter considers til 10 to be there? Apparently only the last list can skip the parentheses. Why is that? What evaluation order occurs and what type does it produce?

A: The interpreter reads from right to left. Therefore the 10 is joined onto the resultant list from til 3 before being passed to the til on the lefthand side. Putting in brackets will avoid this
q)10,til 3
10 0 1 2j
q)til 10 0 1 2j
'type
q)til[10],til 3
0 1 2 3 4 5 6 7 8 9 0 1 2j


text:
Q: Sentence pattern in interrogative sentence am class 8.
My teacher was revising sentence pattern today, I got a thought of asking my friend a question that is:
Frame a sentence with pattern of  V + S + V + O
He couldn't find an answer and asked to the teacher, the teacher wondered a pattern starting with Verb. Then I said the answer, "Were they playing  cricket". The teacher told me that interrogative sentences do not have sentence pattern.
Then I thought for a while. Then I realized that the words like what and why cannot come as S, V, O, C or A. But can't a yes or no question have the sentence pattern? Can't a who question have a separate sentence pattern?

A: The seven English clause patterns are expressed as declarative sentences. They were playing cricket is on the pattern S-V-O, and the pattern remains the same even when the word order changes in the interrogative.


text:
Q: Can AWS MFA work as follows? In order to log into AWS MFA is required. But if I had a program running on an EC2 instance that invoked AWS services via API calls, would such a program also need to authenticate using MFA or would this not be required because we are already "in?"

A: MFA is only required when logging into the AWS web console with a username/password. When you make API calls you would use an IAM access key, or even better (since your program is running on EC2) an IAM instance profile, which doesn't require MFA.

A: API calls can be made to require MFA as well using an IAM policy. However, if you were to deploy such policy, you could also exclude VPC-internal subnets from the MFA requirement so that MFA would only be required when accessing the AWS API endpoints from the outside.
Here's a link to my repository which contains an example enforcement policy (see example-mfa-policies/EnforceMFA.txt): https://github.com/vwal/awscli-mfa


text:
Q: SSL certificate warning We have an installed SSL certificate on our website. First time user needs to install this certificate (accept it) on their browsers. Is there way to disable it?
I think it might be possible with apache conf or .htaccess file setting SSL path in it.
Can anyone did this and can paste me the settings here.
Thanks.

A: It sounds as if your certificate is signed incorrectly or for the wrong domain. Most browsers today don't ask about security certificates if they're completely valid.


text:
Q: python failed to import cv2 (OpenCV) when I try to import cv on python3.6.8,it tracebacked:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/dist-packages/cv2/__init__.py", line 3, in <module>
from .cv2 import *
ImportError: libSM.so.6: cannot open shared object file: No such file or directory

my opencv-python version is 4.1.0.25

A: You will have to install libsm6 package.
Below is the command to do so.
apt-get update
apt-get install -y libsm6 libxext6 libxrender-dev
pip install opencv-python

A: It is a simple question, but I am not familiar with Ubuntu,the solution is install libSM.so.6.


text:
Q: how to echo php from html i have a php code that that have a function that print html via echo like so:
<?php
function show_html($num_found)
{
$html="

ERROR REPORT

Number of error found
  ***$num_found***

";

return $html;

}
echo show_html($num_found);
?>

how can i print the $num_found variable inside the table ?

A: This is basic PHP. Since you are using double quotes for your string you can just place the variable into the string and it will be interpolated:
<?php
function show_html($num_found)
{
$html="

ERROR REPORT

Number of error found
$num_found

";

return $html;

}
echo show_html($num_found);
?>

or you can use concatentation:
" . $num_found . "

A: If what you have isn't working, try concatenating the value:
<?php
function show_html($num_found)
{
   // if you aren't sure if "num_found" is going to be set, add this:
   if (!isset($num_found)) $num_found = 0;

   // now set the html
   $html = "

ERROR REPORT

            Number of error found
            ".$num_found."

   ";

   return $html;
}

// the num found variable needs to be defined somewhere...
$num_found = 10;

// after that the echo will work
echo show_html($num_found);
?>

A: What you have now should print the value of the variable $num_found inside the table as-is.  If it does not, the variable may not be defined.
Try this:  in your function, put this line before your $html="...":

   $num_found=5; //test

if the value shows up now, somehow the variable is not being set in your code.  I think the issue is elsewhere, i.e. how are you calling your AJAX function.   The value passing may be dropped somewhere on the way.


text:
Q: How to assign variables to data passed through a WEB API in Angular? I am consuming a WEB API endpoint that returns product data. However, upon subscribing, I want to assign variables to this data to be used as part of a bar chart generated using Chart.js (Not relevant).
The data that is returned can be seen as follows:

What I have tried is the following:
generateReport() {
    if(this.service.reportForm.valid) {
      this.service.getData().subscribe
      (res => {
        console.log(res)
        let productNames = res['reportData'].map(res => res.ProductName);
        let avgQuantityOrdereed = res['reportData'].map(res => res.AverageQuantityOrdered);
        let orderQuantity = res['reportData'].map(res => res.ProductOrders.orderQuantity)
      })
    }
  }

However, I get the error: "Element implicitly has an 'any' type because expression of type '"reportData"' can't be used to index type 'Object'" under the "res['reportData'].
Is there any alternative way to doing what i tried above? And also, what is wrong with the way i did it?

A: Using rxjs functional operators, you can achieve the same thing with:
export class ReportComponent {
 clickObservable$: Observable<Event> = fromEvent(document,'click');
 generateReport$: Observable<string[]> = this.clickObservable$.pipe(
        filter(t => this.service.reportForm.valid),
        switchMap(t => this.service.getData()),
        map(t => t.reportData),
        map(t => t.productNames)
  )
}

HTML Template
 <ul>
    <li *ngFor="let productName of generateReport$ | async">
       {{ productName }}
    </li>
 </ul>

A: I realized that i simply needed to pass 'res' as a type of any:
generateReport() {
    if(this.service.reportForm.valid) {
      this.service.getData().subscribe
      ((res:any) => {
        console.log(res)
        let productNames = res['reportData'].map((res: any) => res.ProductName);
        let avgQuantityOrdereed = res['reportData'].map((res: any) => res.AverageQuantityOrdered);
        let orderQuantity = res['reportData'].map((res: any) => res.ProductOrders.orderQuantity)
        console.log(productNames)
      })
    }
  }


text:
Q: Why would I use a session over a private member in a Response Servlet? I am building a small Poker app to work on my java skills.  I am creating it in Texas Hold'em format.
Basically I want to maintain the hand state in a servlet that handles my AJAX responses.  I am guessing the member variable in a servlet is not safe, whereas the session should be.  Could you please explain the correct implementation of this solution?
public class PokerClientResponse extends HttpServlet {
private static Logger LOG = Logger.getLogger(PokerClientResponse.class);

private static final long serialVersionUID = 1L;
private HandState handState = null;

public PokerClientResponse() {
    super();
}

protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
            //Which is the best way to maintain hand state?

    //Get the State from the session, then increment it
    HttpSession session = request.getSession();
    Object obj = session.getAttribute("handState");

            //Advance the Hand State
    getHandState().goToNextState();

A: A servlet instance variable (unless it's a ThreadLocal is indeed not safe, because there is only a single servlet instance serving all request made to its mapping.
All you need to do is save/load the hand state from the session, which is unique per user conversation1. Remove the hand state instance variable.
Remove the hand state getter. Only deal with hand state inside the request processing call, and pass that hand state to other methods that need it (if any).
Your code would be closer to this:
protected void doGet(etc) {
    HandState state = (HandState) request.getSession().getAttribute("handState");
    state.nextState();
}

Although I recommend using a constant for the session attribute key.

1 Which is different from unique per browser window or tab; if you have multiple windows or tabs open, they may be sharing the same session.

A: For starters, HTTP was originally meant as a stateless protocol. That's for the origins...
Then, if you look at your code, ask yourself this: would it be OK for a VisitorB to have access to the session of VisitorA?
Hint: Probably not.
So, you guess is right. You need to manage the unicity of the session for one user. The in-built session management gives you this.


text:
Q: Render child items with their own layout in a carousel control Here is what I am trying to do:
I have a content item "Carousel Presenter". Essentially this will present its child items within the carousel. I want the flexibility to have any number of child items. I also want the flexibility to be able to specify the presentation of each child item - they may be the same or different. I am using Sitecore 6.5.
The carousel is jcarousel. I need to generate markup generally like this (from item "Carousel Presenter"):

 ... MARKUP FROM ITEM 1 ...

 ... MARKUP FROM ITEM 2 ...

        ... and so on

Here is what I have tried:

*

*Created sublayout "carousel presenter.ascx", markup:

*

Codebehind:
  protected void Page_Load(object sender, EventArgs e)
    {
        // Get all children and render them inside the

        var kids = Sitecore.Context.Item.GetChildren();
        foreach (Item snippet in kids)
        {
            // RENDER THE ITEMS HERE INTO THE PLACEHOLDER...
            // Get the first rendering from item's presentation definition
            RenderingReference rendering = snippet.Visualization.GetRenderings(Sitecore.Context.Device, false).FirstOrDefault();
            // We assume that its a Sublayout, but you can also check for xslt and create an XslFile() object
            Sublayout sublayout = new Sublayout();
            sublayout.DataSource = snippet.Paths.FullPath; // creates a reference to the snippet item, so you can pull data from that later on
            sublayout.Path = rendering.RenderingItem.InnerItem["Path"];
            sublayout.Cacheable = rendering.RenderingItem.Caching.Cacheable;
            // Copy cache settings
            if (rendering.RenderingItem.Caching.Cacheable)
            {
                sublayout.VaryByData = rendering.RenderingItem.Caching.VaryByData;
                sublayout.VaryByDevice = rendering.RenderingItem.Caching.VaryByDevice;
                sublayout.VaryByLogin = rendering.RenderingItem.Caching.VaryByLogin;
                sublayout.VaryByParm = rendering.RenderingItem.Caching.VaryByParm;
                sublayout.VaryByQueryString = rendering.RenderingItem.Caching.VaryByQueryString;
                sublayout.VaryByUser = rendering.RenderingItem.Caching.VaryByUser;
            }
            // Now render the sublayout to the placeholder
            carouselItemsPh.Controls.Add(sublayout);
        }
    }

Note that I stole most of this code from here: Temporarily change a Sitecore item's layout

*

*Created child items in content tree, beneath content item "Carousel Presenter" which are "Carousel Items", with a sublayout control assigned to each (via standard values in configuration/layout).

Everything is published.
When I hit my test page markup is generated for each of the child items ("Carousel Items"), and the carousel works, but it looks like the Datasource is not being assigned properly - the datasource/context of all child items is the parent item, despite setting the Datasource explicitly when I create the child controls. How do I fix this?
Is there a better approach to what I am trying to achieve in Sitecore 6.5?
Thanks

A: The user controls/sublayouts for your child items need to programmatically read the datasource. For this job I always have my own 'base' Sublayout class which handles the datasource issue for user controls.  In my base class I default to using Sitecore.Context.Item if the datasource has not been set.  The code is as follows:
public class SublayoutBase : UserControl
{
    private Item _dataSource;

    public Item DataSource
    {
        get
        {
            if (_dataSource == null)
            {
                if (Parent is Sublayout)
                {
                    _dataSource =
                        Sitecore.Context.Database.GetItem(((Sublayout)Parent).DataSource);
                }
                if (_dataSource == null)
                {
                    _dataSource = Sitecore.Context.Item;
                }
            }
            return _dataSource;
        }
    }

    protected override void OnLoad(EventArgs e)
    {
        foreach (Control c in Controls)
        {
            SetFieldRenderers(DataSource, c);
        }
        base.OnLoad(e);
    }

    private void SetFieldRenderers(Item item, Control control)
    {
        if (item != null)
        {
            var ctrl = control as Sitecore.Web.UI.WebControl;
            if (ctrl != null && !string.IsNullOrEmpty(ctrl.DataSource))
            {
                //don't set the source item if the DataSource has already been set.
                return;
            }
            if (control is FieldRenderer)
            {
                var fr = (FieldRenderer)control;
                fr.Item = item;
            }
            else if (control is Image)
            {
                var img = (Image)control;
                img.Item = item;
            }
            else if (control is Link)
            {
                var link = (Link)control;
                link.Item = item;
            }
            else if (control is Text)
            {
                var text = (Text)control;
                text.Item = item;
            }
            else
            {
                foreach (Control childControl in control.Controls)
                {
                    SetFieldRenderers(item, childControl);
                }
            }
        }
    }
}

A: I tend to create a Repeater for things like this.
You can do something like:

    <asp:Repeater id="repeater" runat="server">
        <HeaderTemplate>

        </HeaderTemplate>
        <ItemTemplate>

                ..markup from item such as:
                <sc:FieldRenderer FieldName="Title" runat="server" id="titlefield" Item="<%# Container.DataItem %>" />

        </ItemTemplate>
        <FooterTemplate>

        </FooterTemplate>
    </asp:Repeater>

Then in CodeBehind all you need to do is something like:
protected void Page_Load(object sender, EventArgs e)
{
    repeater.DataSource = Sitecore.Context.Item.GetChildren(); // Could also make a LINQ statement where you make sure Children are of specific template if required
    repeater.DataBind();
}

Of course, it depends what's on your child item SubLayouts whether you can use something like this


text:
Q: Unable to run curlpp library on c++ I am compiling a C++11 program with:
g++ -std=c++11 main.cpp -o main -I/opt/homebrew/Cellar/curlpp/0.8.1_1/include/ -Iinclude  -lcurl

Yet I am getting the following error:
Undefined symbols for architecture arm64:
  "curlpp::Cleanup::Cleanup()", referenced from:
      _main in main-18dda9.o
  "curlpp::Cleanup::~Cleanup()", referenced from:
      _main in main-18dda9.o
ld: symbol(s) not found for architecture arm64


text:
Q: Get Caller derived-class when calling a base-class static method I was wondering if it's possible (even via reflection et similia) to get the caller derived-class inside of a called base-class static method.
For example, I've a base-class with a static method defined:
public MyBaseClass {
    public static void MyBaseClassStaticMethod() { /** ... **/ }
}

and a derived-from-it class:
public MyDerivedClass : MyBaseClass { }

then I call:
MyDerivedClass.MyBaseClassStaticMethod()

Is it possibile, inside of method MyBaseClassStaticMethod, to know which is the caller derived type?
(i.e. MyDerivedClass)
I just need a string...

A: Generics in following way can be used to solve your scenario
public class BaseClass<TDerived> where TDerived : BaseClass<TDerived>
{
    public static void LogCallerType()
    {
        Console.WriteLine(typeof(TDerived).Name);
    }
}

public class FooClass : BaseClass<FooClass> { }

public class BooClass : BaseClass<BooClass> { }

class Program
{
    static void Main(string[] args)
    {
        FooClass.LogCallerType();
        BooClass.LogCallerType();
    }
}

This will in turn output the following
1. FooClass
2. BooClass

A: No, this is not possible - by no means. static methods are not polymorphal and as such this information simply doesn't exist.
Consider redesigning your code.
Update:
Upon compilation, the compiler replaces MyDerivedClass with the class the static method is actually declared on, in your case MyBaseClass.
So even in the IL you don't see MyDerivedClass. The information exists only in your source code. It doesn't exist in your compiled assembly.

A: A static method is statically bound to a certain class and does not really participate in the inheritance-chain. Thus it does not exist in the derived class. The static method therefor does not know that it was actually used in the derived class.
You can however - through a compiler-trick - access the static member from your derived class. As of this post on MSDN-forum a static member-access from a derived class is translated to a call from the base-class containing the static member. So MyDerivedClass.MyBaseClassStaticMethod is translated to MyBaseClass.MyBaseClassStaticMethod. Thus MethodBase.GetCurrentMethod().DeclaringType will allways return MyBaseClass.
So in short: no, it´s not possible to get the derived type from a static member.

A: First of all, the static method will not have access to the instance that is calling it.  A static method is different from a normal class method in that it does not have access the 'this' reference to a class instance.
If you passed 'this' as a parameter to the static method, then you can try casting it as follows.  Assume you have a number of derived class which you want to test for.
public static void MyBaseClassStaticMethod(MyBaseClass callingInstance)
{
    MyDerivedClass myDerivedClass = callingInstance as MyDerivedClass;
    MyDerivedClass2 myDerivedClass2 = callingInstance as MyDerivedClass2;
    MyDerivedClass3 myDerivedClass3 = callingInstance as MyDefivedClass3;
    ...

    // test for which derived class is calling
    if (myDerivedClass != null)
        ...
    else if (myDerivedClass2 != null)
        ...

    ...
}


text:
Q: Android app doen't save data in WAMP database The user must add a marker by tapping the map. My goal is to send the Name, Category, Latitude and Longitude to a SQL database. I followed this tutorial: https://www.youtube.com/watch?v=cOsZHuu8Qog. The app works, it even gets a toast that the "Registration Succeeded!" but the database is still empty.
Also, maybe there is something wrong with the communication between my app and the WampServer. I wonder if the connection URL is correct. I found on the Internet that the default WAMP localhost IP is 10.0.2.2 or it can work with my PC's local IP. Both of them didn't work.
See the code:
AddShopActivity.java
public class AddShopActivity extends MainScreen implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {

Spinner spinner;
ArrayAdapter<CharSequence> adapter;

GoogleMap mGoogleMap;
GoogleApiClient mGoogleApiClient;

String Name, Category, Latitude, Longitude;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_shop);
    initMap();
    spinner = (Spinner) findViewById(R.id.spinner);
    adapter = ArrayAdapter.createFromResource(this, R.array.eidoskatastimatos, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
}

private void initMap() {
    MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.mapFragment);
    mapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mGoogleMap = googleMap;
    mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
    mGoogleApiClient.connect();
}

LocationRequest mLocationsRequest;

@Override
public void onConnected(Bundle bundle) {
    mLocationsRequest = LocationRequest.create();
    mLocationsRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationsRequest.setInterval(5000);
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }

     LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationsRequest, this);

    mGoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
        @Override
        public void onMapClick(LatLng latLng) {

            EditText shop_name = (EditText)findViewById(R.id.editName);
            Spinner shop_category = (Spinner)findViewById(R.id.spinner);

            MarkerOptions marker = new MarkerOptions()
                                       .position(new LatLng(latLng.latitude, latLng.longitude))
                                       .draggable(true)
                                       .title(shop_name.getText().toString())
                                       .snippet(shop_category.getSelectedItem().toString());

            CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLng, 16);
            mGoogleMap.animateCamera(update);

            mGoogleMap.clear();
            mGoogleMap.addMarker(marker);

            Name = shop_name.getText().toString();
            Category = shop_category.getSelectedItem().toString();
            Latitude = String.valueOf(latLng.latitude);
            Longitude = String.valueOf(latLng.longitude);
        }
    });

}

public void shopReg(View view)
{
    String method = "save";
    BackgroundTask backgroundTask = new BackgroundTask(this);
    backgroundTask.execute(method, Name, Category, Latitude, Longitude);
    finish();
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

@Override
public void onLocationChanged(Location location) {
    if (location == null){
        Toast.makeText(this, "Can't get current location", Toast.LENGTH_LONG).show();
    } else {
        LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
        CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, 16);
        mGoogleMap.animateCamera(update);
    }

}
}

BackgroundTask.java
public class BackgroundTask extends AsyncTask<String,Void,String> {

Context ctx;

BackgroundTask(Context ctx)
{
    this.ctx = ctx;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
}

@Override
protected String doInBackground(String... params) {
    String reg_url = "http://10.0.2.2/shop/register.php";
    String method = params[0];
    if(method.equals("save"))
    {
        String Name = params[1];
        String Category = params[2];
        String Latitude = params[3];
        String Longitude = params[4];
        try {
            URL url = new URL(reg_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream OS = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
    String data = URLEncoder.encode("Name", "UTF-8") +"="+URLEncoder.encode(Name,"UTF-8")+"&"+
            URLEncoder.encode("Category", "UTF-8") +"="+URLEncoder.encode(Category,"UTF-8")+"&"+
            URLEncoder.encode("Latitude", "UTF-8") +"="+URLEncoder.encode(Latitude,"UTF-8")+"&"+
            URLEncoder.encode("Longitude", "UTF-8") +"="+URLEncoder.encode(Longitude,"UTF-8");
            bufferedWriter.write(data);
            bufferedWriter.flush();
            bufferedWriter.close();
            OS.close();
            InputStream IS = httpURLConnection.getInputStream();
            IS.close();
            return "Το κατάστημα προστέθηκε!";
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    return null;
}

@Override
protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
}

@Override
protected void onPostExecute(String result) {
    Toast.makeText(ctx,result,Toast.LENGTH_LONG).show();
}
}

init.php
<?php
$db_name="shops";
$mysql_user="root";
$mysql_pass="";
$server_name="localhost";

$con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$db_name);

?>

register.php
<?php
require"init.php";

$shop_name=$_POST["Name"];
$shop_category=$_POST["Category"];
$shop_latitude=$_POST["Latitude"];
$shop_longitude=$_POST["Longitude"];

$sql_query="insert into shop_info values('$shop_name','$shop_category','$shop_latitude','$shop_longidude');";

?>

A: Assuming the backend (php) code is just what you provide in this example, you never actually execute any code that saves anything, so no wonder your db is empty.
What your code does now:

*

*Prepares a connection in init.php

*Prepares a string representation of an SQL query by inserting user supplied data in the string in register.php (ouch, read below)

What is missing:

*

*Executing the query to actually do something with the data, i.e. mysqli_query($conn, $sql_query);

*Learning about SQL injection

*Implementing one of the proper ways to avoid SQL injection in a PHP script (i.e. prepared statements)

*(Optional but recommended) Use the modern PDO interface to access the database.

As a general suggestion, you should aim to break down complex code to small testable parts that you can verify they work.
For example had you tried to call register.php with actual values instead of those coming from POST data you would quickly see that it doesn't save anything, instead of looking at IPs, connections or your android code. The comment you got was in that direction - forget about your android app and try to verify the backend saves a request once it comes in.


text:
Q: React-native-vector-icons ios error I get the following error:

RNVectorIconsManager not available, did you add library to your
  project and link with libRnVectorIcons.a

after npm installing the React-native-vector-icons and running react-native link. I am using react-native v0.42, react-native-vector-icons v4.0.0 and Xcode v8.2.1.
I have checked plist and it has all the fonts in array. and libRNVectorIcons.a is showing under build phases but it is red. see image:

A: Try running react-native link react-native-vector-icons in the terminal.

A: The broken file:
https://github.com/facebook/react-native/blob/master/local-cli/core/fixtures/files/package.json
Try running react-native link
or simply remove the above broken file and restart your xcode.


text:
Q: Graph API returning blank 1x1 pixel image When I use the Graph API to get a list of posts from a page, the picture field, which contains the URL for the image returns a blank 1x1 pixel image.
For example, this is one of the URLs that it returns:
http://www.facebook.com/l.php?u=http%3A%2F%2Fexternal.ak.fbcdn.net%2Fsafe_image.php%3Fd%3DAQBj9y7r5zdKLsTF%26w%3D90%26h%3D90%26url%3Dhttp%5Cu00253A%5Cu00252F%5Cu00252Fwww.thisislondon.co.uk%5Cu00252Fincoming%5Cu00252Farticle7630373.ece%5Cu00252FBINARY%5Cu00252Foriginal%5Cu00252FTerry-Deary.jpg&h=GAQEzRMSC
I've also seen this using the RSS feed from the page: https://www.facebook.com/feeds/page.php?id=128931583879163&format=rss20 except that the URLs are encoded slightly differently.
I've had a good look on stackoverflow, but haven't seen anyone else with the same problem.  Could you tell me what I need to do to decode it to get the appropriate URL please?
Thanks,
Gregor

A: This is a bug, as reported on the Facebook Developer site, for both pictures and video. The issue is still pending a fix from Facebook.

A: (MacBook)-I was receiving this as well, but only when I was on  my dashboard page. After several seconds, the dashboard page would slide to the blank Facebook pixel page.This was driving me crazy.  I finally deleted my dashboard page, which i really didn't use anyway, by using a code and running it on terminal. (from "how to hide or disable the dashboard page). The docking page disappeared and so did the 1x1 pixel page. I can restore the docking page whenever i want by using a second code.


text:
Q: How can I insert Foreign Key(FK) in starUML ER diagram? I'm working on a ER diagram in starUML but can't find a Foriegn Key option in it. I've looked through various setting in the application but couldn't find it. Is they a way to insert? Also, I've seen images using FK in starUML but couldn't find out how. Can someone help me out?

A: Select a column in the table and look at the properties on the right side of the editor.


text:
Q: Delete duplicate store in mail chimp I contacted mailchimp support because I have an issue with 'best sellers' pulling through sold out items - they told me its due to a duplicate store but theyre unable to delete it and have offered the advice below.

Issue of duplicate stores in your account. The work around for the
  issue would be to use the API playground or a REST client to delete
  the duplicate store in the account. Before doing this, we want to
  stress that this deletion can not be undone and could potentially
  affect the sending of ecommerce automations/emails that you have in
  the account. That being said, I am aware that your account was running
  into issues with accessing the playground earlier. If you would like
  to delete the duplicate store from the account, we'd recommend using
  the DELETE call for the duplicate store through a REST client and
  would recommend doing this with the assistance of a developer if
  needed. The endpoint that you'll want to use to delete that store from
  the account is as follows:
  http://developer.mailchimp.com/documentation/mailchimp/reference/ecommerce/stores/#delete-delete_ecommerce_stores_store_id
If you would like to use the work around of deleting the store from
  the account using the API, we'd recommend recreating the ecommerce
  automations in your account to make sure that they are using the most
  current and only instance of the store connected to MailChimp. While
  the issue of having duplicate stores is unfortunate enough, I do see
  how not being able to access the playground and having to use a REST
  client/outside application only complicates the resolution to this
  issue.

From the answers they provided me with I can't figure out how to do it, I appreciate your help.

A: get the list of your stores then confirm which store to delete then delete it.

A: I was able to delete that extra store using Postman api client
Example displayed in mail chimp doc
curl --request DELETE \
--url 'https://usX.api.mailchimp.com/3.0/ecommerce/stores/MC002' \
--user 'anystring:apikey' \
--include

You can use this medium tutorial if you are new to postman and mail chimp api.


text:
Q: How to go about isolating dollar amounts using Regex? I used the PDFPlumber library to extract all the lines in my PDF, a sample line extract looks like this:

Total Return Transportation   $16.01

The goal is to put all of these into a data frame. How do I use regex to group this line so that I may isolate the charge type and dollar amount?
Currently, I have:
totals=re.compile(r"(\ATotal) ([\w]+) ([\w]*)")
for line in text.split("\n"):
    line2=totals.search(line)
    if line2:
        print(line)
        print(line2.group(1))
    else:
        pass

Group 1 returns "Total", Group 2 returns "Return" and Group 3 "Transportation" but I'm unable to make a group that retrieves the dollar amount. Any suggestions?
Note: Dollar amounts over $1000 contain a "," that might need to be included in the regex syntax

A: Just change your regex like so:
totals=re.compile(r"(\ATotal) ([\w]+) ([\w]*) ([\$ ]+?(\d+([,\.\d]+)?))")
>>> totals.search("Total Return Transportation $16.01").group(4)
'$16.01'
>>> totals.search("Total Return Transportation $1,006.01").group(4)
'$1,006.01'

A: You could use a pattern with 4 capture groups.
Note that you can write [\w] as just \w.
Using \w* matches optional word characters, and could possibly also match an empty string.
You can match the word characters 1+ times, and use a pattern for the dollar amount matching 1-3 digits at the left and optional parts of a comma and 3 digits in between.
\A(Total) (\w+) (\w+) (\$\d{1,3}(?:,\d{3})*(?:\.\d+)?)(?!\S)

*

*\A Start of string

*(Total)  Capture Total in group 1 and match a space

*(\w+)  Capture 1+ word chars in group 2 and match a space

*(\w+)  Capture 1+ word chars in group 3 and match a space

*( Capture group 4

*

*\$\d{1,3} Match $ and 1-3 digits

*(?:,\d{3})*(?:\.\d+)? Optionally repeat 3 digits and optionally match . and 1+ digits

*) Close group 4

*(?!\S) Assert a whitespace boundary to the right to prevent a partial match

See a regex demo and a Python demo.
import re

strings = [
    "Total Return Transportation $16.01",
    "Total Return Transportation $123,899,116.01",
    "Total Return Transportation $1612.01"
]

pattern = r"\A(Total) (\w+) (\w+) (\$\d{1,3}(?:,\d{3})*(?:\.\d+)?)(?!\S)"

for s in strings:
    match = re.match(pattern, s)
    if match:
        print(match.group(4))

Output
$16.01
$123,899,116.01


text:
Q: Calling a controller action with link_to After playing around with links in Rails for a view hours i've managed to actually get a link to invoke a method in my controller. But i still don't understand why all my other attempts failed. Im hoping you could help me out with that.
I have the scaffold "Cars". When in the show view for a car, id like to click a link that invokes the method "drive" in my Car controller.
This WORKS: <%= link_to "Drive", drive_car_path(@car) %>
It seems this only works if i have this is my routes.rb:
resources :cars do
  member do
    get 'drive'
  end
end

Why does <%= link_to "Drive", car_path, :method => :drive %> not work?
Do I need to put a GET in the routes.rb file for every method I create in my controller?
I can't seem to find any sites explain how to use links together with routes. They only seem to come separate. Do you guys have any easily understandable tutorials on this?

A: Try link_to "Drive", :controller => "car", :action => "drive"
Also, method is for choosing the HTTP method (GET, POST, ...). It's not method as in routine.
Be sure to check out Rails Routing from the Outside In and The Lowdown on Routes in Rails 3, they're both awesome resources.


text:
Q: Java trying change the variable value within a method and constructor The code that i've written works like this:
There is a Superhero class, with instance variables, two constructors, (a possibly faulty method called powerUp) and a method to initiate a fight between two object instances.
When i run my code i am getting the following output from command line:

Cyclops 10
  Colossus 40
  The winner is: Colossus
  After receiving a power-up: Cyclops has a Strength of: 50
  Testing the Cyclops strength: 50
  The winner is: Colossus

After the first "The winner is Colossus" it should be Cyclops as the winner as this object instance receives a powerUp of 100 which is a boost of 40 strength, however for some reason this rule does not get applied and the code says Colossus is still the winner.. the program calculates the winner based on the strength, the highest is the winner, or if they are both equal the opponent is the winner.
The code is displayed below.
Super hero class:
public class Superhero{

//private instance variables declared below
//name of the super hero
private String name;
//name of the strength variable
private int strength;
//The variable for the powerUp method
private int powerUp;
//variable to store the power of the power up
private int storePower;

//Getter methods
public int getStrength(){
    return strength;
}

public String getName(){
    return name;
}

//constructor for if the player wanted to specify the name and the strength
public Superhero(String name, int strength){
    this.name = name;
    this.strength = strength;

    System.out.println(name + " " + strength);
}

//if the user doesn't enter the strength as it is optional
//this constructor below will run and set the default
public Superhero(String name){
    this.name = name;
    this.strength = 10;
    System.out.println(name + " " + strength );

}

/*
This method takes in an integer paremeter and based on that it does
some calculations.

There are four possible integer values you can pass in: 100, 75, 50 and 25.

If 100 has been passed in the storePower variable is set to 40 which would be
a power-up of 40, if 75 then power-up of 30, if 50 then a power-up of 20,
if 25 then a power-up of 10 and if the right ammount is not specified a power-up
of 0 will be assigned.

*/
public void powerUp(int powerUp){
    this.powerUp = powerUp;
    if(powerUp == 100){
        strength = strength + 40;
    }else if(powerUp == 75){
        strength = strength + 30;
    }else if(powerUp == 50){
        strength = strength + 20;
    }else if(powerUp == 25){
        strength = strength + 10;
    }else{
        strength = strength + 0;
    }
    this.strength = strength + storePower;
    System.out.println("After receiving a power-up: " + name +  " has a Strength of: " + strength);

}

//the method for fight
public Superhero fight(Superhero opponent) {
  if (this.getStrength() > opponent.getStrength()){
    return this;
  }else if(this.getStrength() == opponent.getStrength()){
    return opponent;
  }else{
    return opponent;
  }
}

}
Fight class:
public class Fight{
public static void main(String[] args){

    // a. Create a Superhero named Cyclops
    Superhero Cyclops = new Superhero("Cyclops");

    //b. Create a Superhero named Colossus. Colossus has a strength of 40
    Superhero Colossus = new Superhero("Colossus", 40);

    //c. Make Cyclops fight Colossus. Print the winner to the terminal.
    Superhero winner = Cyclops.fight(Colossus);
    System.out.println("The winner is: " + winner.getName());

    //d. Give Cyclops a powerUp of 100
    Cyclops.powerUp(100);

    //e. Make Cyclops fight Colossus. Print the winner to the terminal.
    Superhero winner2 = Cyclops.fight(Colossus);
    System.out.println("Testing the Cyclops strength: " + Cyclops.getStrength());
    System.out.println("The winner is: " + winner.getName());

}

}
During debugging i have tried everything i can possibly think of i have changed up this code below:
public void powerUp(int powerUp){
    this.powerUp = powerUp;
    if(powerUp == 100){
        strength = strength + 40;
    }else if(powerUp == 75){
        strength = strength + 30;
    }else if(powerUp == 50){
        strength = strength + 20;
    }else if(powerUp == 25){
        strength = strength + 10;
    }else{
        strength = strength + 0;
    }
    this.strength = strength;
    System.out.println("After receiving a power-up: " + name +  " has a Strength of: " + strength);

}

with
    public void powerUp(int powerUp){
    this.powerUp = powerUp;
    if(powerUp == 100){
        storePower = 40;
    }else if(powerUp == 75){
        storePower = 30;
    }else if(powerUp == 50){
        storePower = 20;
    }else if(powerUp == 25){
        storePower = 10;
    }else{
        storePower = 0;
    }
    this.strength = strength + storePower;
    System.out.println("After receiving a power-up: " + name +  " has a Strength of: " + strength);

}

and nothing seems to change, for some reason Cyclops will not be set to that value of 50.

A: You are calling getName() on winner, shouldn't it be winner2.
Superhero winner2 = Cyclops.fight(Colossus);
    System.out.println("Testing the Cyclops strength: " + Cyclops.getStrength());
    System.out.println("The winner is: " + winner.getName());


text:
Q: Dynamically loaded control - how can I access a value in Page_Init I am loading a LinkButton dynamically when a user clicks on another LinkButton.  I am attaching an event handler to it.  When the user clicks on the dynamically loaded LinkButton, the event does not fire.
From what I've been reading, I understand this is because when the page posts back the dynamically loaded control no longer exists.  It looks like I'm supposed to make sure this control is recreated in Page_Init.
The dynamically created LinkButton is dependedent on a value (Product ID).  I need someway to access this value so I can properly create the control.  ViewState is not accessible and I'm concerned if I use Session it could time out and then that wouldn't help.  Any ideas?
Also, I hardcoded a Product ID value just for testing, and that still did not cause the event to fire.  Is there something else I need to do?
protected void Page_Init(object sender, EventArgs e)
{
   SetTabText(1, 1);
}

SetTabText calls SetActionLinks which creates the LinkButton:
protected Panel SetActionLinks(int prodID, int tabID) {
...
LinkButton lnkBtn = new LinkButton();
lnkBtn.ID = "lnkBtn" + rand.Next().ToString();
lnkBtn.CommandName = "action";
lnkBtn.Command += new CommandEventHandler(this.lnkAction_Command);
panel.Controls.Add(lnkBtn);
...
}
void lnkAction_Command(object sender, CommandEventArgs e)
{
   LinkButton btn = (LinkButton)sender;
   switch (btn.CommandArgument)
   {
      AddCart();
   }
}

A: You can put your Product ID in a hidden field and get its value in Page_Init using
Page.Request(Page.FindControl("hdnPageIdField"))

This way you don't need to rely on ViewState or SessionState
Also for dynamic controls I highly suggest you read this greate arcticle series

A: In your scenario I tried your code, the line below causes your event firing fault :
lnkBtn.ID = "lnkBtn" + rand.Next().ToString();

try to set an id that not changes between postbacks.
For ViewState, You can move your code to Page_Load. Your code works same, but you can access ViewState and your Control's posted values

A: I spent a sleepless night figuring out something like this a few months ago.  That was when I fully grokked the fact that ASP.NET is built on a stateless foundation and it maintains state by ping-ponging viewstate back and forth between the client and the server.
If you are dynamically adding and deleting controls or modifying existing controls in response to a dynamically created control's event firing, then the parent element's PageInit needs to recreate the child controls in the state that they existed at the time the event fired (before the event's actions are applied). It may seem redundant, but it's necessary in order to ensure that the receiver exists and it's handler can be invoked when server wants to fire the event.  Then the control's event handler will be able apply the changes (and add or remove controls, assign different ID's etc.)
I found this page on the ASP.NET event lifecycle (http://msdn.microsoft.com/en-us/library/ms178472.aspx) helpful.

A: This works in Page_Init
HiddenField ctrl = (HiddenField)Page.FindControl("hfTest");
string strValue = Page.Request.Form.Get(ctrl.ClientID);

The HiddenField will store the controls to be loaded (Pipe Delimited) and the we can load the controls dynamically.

A: Look at anonymous delegates
LinkButton lb = new LinkButton();
lb.Command += delegate { // do something here. also you can access any variable from current stack };

A: Have you AutoEventWireup="true" in your .aspx file?


text:
Q: Is there any way in C# to automatically set the DefaultValueAttribute for properties that have default values set? Is there anyway to implicitly carry out the following pattern?
    [DefaultValue(true)]
    public bool SomeBooleanProperty { get; set; } = true;

Repeating the default value in two locations just seems to be begging for mistakes somewhere and in any case seems very redundant. I can imagine some cases where having the DefaultValueAttribute automatically set to the default value (or any value) would be undesirable, but I think those would be the exception rather than the rule. And in those cases the solution would simply be to set the default value in the constructor rather than at declaration which I think is less burdensome than redundant code.

A: MSDN says this about the DefaultValueAttribute

A DefaultValueAttribute will not cause a member to be automatically
  initialized with the attribute's value. You must set the initial value
  in your code.

This article suggests doing something like this to avoid repeated code
static public void ApplyDefaultValues(object self)
{
    foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(self)) {
        DefaultValueAttribute attr = prop.Attributes[typeof(DefaultValueAttribute)] as DefaultValueAttribute;
        if (attr == null) continue;
        prop.SetValue(self, attr.Value);
    }
}


text:
Q: send keys in WndProc method in C# I override WndProc method in windows form and use SendKeys.
I wanna send "CTRL + N" when the bool value if true and wanna send just "n" when bool value is false.
My problem is here when i send "n" send unlimited "n".
Is the any way to fix this ?
   public ShiledMaker()
   {
        InitializeComponent();
        this.KeyPreview = true;
        RegisterHotKey(Handle, (int)Keys.N, 0, (int)Keys.N);
   }

  protected override void WndProc(ref Message xMessage)
  {
        base.WndProc(ref xMessage);

        if (bool value)
             SendKeys.Send("n");
        else
             SendKeys.SendWait("^n");
  }

A: Boolean value is added in your class. If the key is sent I am changing it to true. So that the keypress event is called only once.
class MyClass {

   private bool keySent = false;

   protected override void WndProc(ref Message xMessage)
   {
        if (keySent)
            return;

        base.WndProc(ref xMessage);

        if (bool value)
             SendKeys.Send("n");
        else
             SendKeys.SendWait("^n");

        keySent = true;

   }
}


text:
Q: Sed: Finding and replacing a pattern that wraps around into next line I want to find and replace a pattern but it also wraps around to the next line as well, I need to find some way to handle this
Something that looks like:
....tr("Changes to output mappings will be deleted. "
"There is no undo available. Do you want to continue?"));

to turn into something like
...."Changes to output mappings will be deleted. "
"There is no undo available. Do you want to continue?");

(the ... is previous code)
So far, I have code such as (works for a single line but not wrapped text/code):
sed -i 's/tr(\([^)]*\))/\1/I' $file_t

How would I go about this?

A: For the case where the tr( commands are always spread over two lines, try:
$ sed  '/tr(/N; s/tr(\([^)]*\))/\1/I' "$file_t"
...."Changes to output mappings will be deleted. "
"There is no undo available. Do you want to continue?");

The only change here is the addition of /tr(/N.  For any line that matches tr(, this reads in the next line and adds it to the pattern space (N).
To change the file in place, use -i:
sed  -i.bak '/tr(/N; s/tr(\([^)]*\))/\1/I' "$file_t"

More robust version
If it is possible that tr(...) commands may appear on one line, on two lines, or more than two lines, we need to change the logic a bit:
sed  '/tr(/{ :a; s/tr(\([^)]*\))/\1/I; t; N; ba}' filename

This looks for lines that contain tr(.  For any such lines, the commands in curly braces, {...}, are performed.  For those lines, the substitution is first attempted on that line only.  If the substitution happens, then the t command tells sed that we have completed this line.  If it didn't happen, meaning that there was no closing ), then the next line is read in (N) and sed branches back to label a (ba) and the substitution is tried again.  This repeats until enough lines are read in to find the ).
As an example, here is a file with tr(...) spread over one, two, and three lines:
$ cat filename
tr("abc");
....tr("Changes to output mappings will be deleted. "
"There is no undo available. Do you want to continue?"));
tr("one
two
three");

Here is the output:
$ sed  '/tr(/{ :a; s/tr(\([^)]*\))/\1/I; t; N; ba}' filename
"abc";
...."Changes to output mappings will be deleted. "
"There is no undo available. Do you want to continue?");
"one
two
three";

Distinguishing between tr(...) and Ptr(...)
To make sure that we substitute only for tr and not for Ptr or Str, we need to make sure that tr starts at a word boundary.  With GNU sed (Linux), a word boundary is denoted \b:
sed  '/\btr(/{ :a; s/\btr(\([^)]*\))/\1/I; t; N; ba}' filename

Using BSD (OSX) sed, the following might work:
sed  '/[[:<:]]tr(/{ :a; s/[[:<:]]tr(\([^)]*\))/\1/I; t; N; ba}' filename


text:
Q: Маршрут в сеть за wireguard Есть vpn на wireguard (далее сервер). Вот конфиг сервера:
wg0.conf
[Interface]
Address = 172.20.100.1/24
ListenPort = 9002
PrivateKey = uio77898hFT89UY=
SaveConfig = false

PostUp = iptables -A FORWARD -i %i -j ACCEPT; iptables -t nat -A POSTROUTING -s 172.20.100.0/24 -o ens18 -j MASQUERADE

PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -t nat -D POSTROUTING -s 172.20.100.0/24 -o ens18 -j MASQUERADE

[Peer]

PublicKey = 4m7879878798098098
AllowedIPs = 172.20.100.50/32,172.16.100.0/24

Есть машинка со следующим конфигом подключенная к wireguard (далее клиент).
[Interface]
Address = 172.20.100.50/32
PrivateKey = CC/Ti8RUTv8gCTrwixgCsRW9QK/A89Hb6cY0D6Xy3nI=
DNS = 208.67.222.222 208.67.220.220
PostUp = iptables -A FORWARD -i %i -j ACCEPT;iptables -t nat -A POSTROUTING -s 172.16.100.0/24 -o enp0s5 -j MASQUERADE

PostDown = iptables -A FORWARD -i %i -j ACCEPT;iptables -t nat -D POSTROUTING -s 172.16.100.0/24 -o enp0s5 -j MASQUERADE

[Peer]

AllowedIPs = 172.20.100.0/24

PublicKey = B24s34juy0HNp6jvztoLmoTudpmKhLag7Qh+f64EUUA=

Endpoint = wireguard-ip:9002

PersistentKeepalive = 25

Нужно все машины подключенные к wiregard пустить в сеть 172.16.100.0/24 которая находится за клиентом.

С такой конфигурацией я захожу на клиента по его локальному адресу без проблем. А на другие адреса его локалки не получатся. ipv4.forward везде 1

A: PostUp = iptables -A FORWARD -i %i -j ACCEPT;iptables -t nat -A POSTROUTING -s 172.!!!>>>20<<<!!!.100.0/24 -o enp0s5 -j MASQUERADE

PostDown = iptables -A FORWARD -i %i -j ACCEPT;iptables -t nat -D POSTROUTING -s 172.!!!>>>20<<<!!!.100.0/24 -o enp0s5 -j MASQUERADE

В клиентском конфиге ошибка в адресе сети. 20 должно быть вместо 16-ти все работает.


text:
Q: Is it possible to dynamically generate Android UI using a complex XML template file? I am trying to dynamically generate a user interface by creating an XML template that will eventually be appended to a LinearLayout parent that is statically defined in the Activity XML. The LinearLayout parent that is statically defined is wrapped within a ScrollView.
In my sample code, it seems I am only able to transverse the parent LinearLayout of the template and not its children. I am also not getting any of its attributes, buttons, or images. I am using LayoutInflater to get the XMl and return it as a LinearLayout since that is the parent of my template file. Any ideas or suggestions would be appreciated.
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feed);
        Context context = getApplicationContext();

        final LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        LinearLayout b = (LinearLayout)inflater.inflate(R.layout.event, null);

        LinearLayout lLayout = (LinearLayout)findViewById(R.id.main_feed_parent);
        lLayout.addView(b);
    }

Here is my complex xml file I am trying to dynamically add to my parent LinearLayout.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="325dp"
android:orientation="vertical"
android:weightSum="100">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="17"
    android:orientation="horizontal"
    android:weightSum="100">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="15"
        android:orientation="horizontal"
        android:weightSum="100">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="20"
            android:orientation="vertical"
            android:weightSum="100">

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="80"
            android:orientation="horizontal"
            android:weightSum="100">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_alignParentTop="true"
                android:layout_weight="50"
                android:paddingBottom="20dp"
                android:src="@drawable/thumbs1" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_alignParentTop="true"
                android:layout_weight="50"
                android:paddingTop="5dp"
                android:text="343"
                android:textSize="18dp" />
        </LinearLayout>
    </LinearLayout>

</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="12"
    android:gravity="center"
    android:orientation="horizontal"
    android:weightSum="100">
    <Button
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="1dp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:layout_weight="33"
        android:orientation="horizontal"
        android:text="Join"
        android:textSize="11dp" />

   </LinearLayout>
</LinearLayout>

A: Ok, so I was able to load the template XML by using fragments. The following was added during onCreate() which fixed it...
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    EventActivity fragment = new EventActivity();
    fragmentTransaction.add(R.id.main_feed_parent, fragment);
    fragmentTransaction.commit();

A: It displays on my emulator. That being said, it doesn't display in the way you wanted.
Here are a couple of changes that you may try:

*

*The SearchView and the ImageView next to it - they have weight property for width, but also have the width set to match the parent. Change it to android:layout_width="0dp"

*The way you inflate the template causes some xml elements to be lost. When you inflate a view with the intention of adding it later to another view, you probably want to inflate in its parent "context":

LinearLayout lLayout = (LinearLayout)findViewById(R.id.main_feed_parent);
 LinearLayout b = (LinearLayout)inflater.inflate(R.layout.event, lLayout, false);
or
//this will return lLayout/parent, not the inflated view; template is automatically added to parent
(LinearLayout)inflater.inflate(R.layout.event, lLayout, true);


text:
Q: NodeJS и MySQL, pool connetctions Есть express, установлен модуль mysql, цель: соединиться с базой где-то в каком-то месте один раз, и не делать в разных скриптах, в т.ч. и скриптах других моих модулей подобное:
var mysql = require('mysql');

var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'user',
  password : '1111',
  database : 'test'
});

connection.connect(function(err){
  if(!err) {
    console.log("Database is connected ");
  } else {
    console.log("Error connecting database ");
  }
});

При этом, нужно ли мне использовать pool запросов? Если да, то как правильно к этому подойти? Весь смысл в том, чтобы понять как данное соединение сделать глобальным чтобы его повсеместно использовать, и так чтобы это не вызвало нагрузки на систему и со временем не повесило мускул.
p.s. мои знания того как это работает в  node.js - сыры пока что, очень надеюсь на детальное изъяснение решения по данной задаче.

A: Давайте по порядку.
Для начала, о необходимости использования пула. Драйвер mysql обрабатывает запросы в каждом подключении последовательно (хотя и асинхронно). Поэтому если у вашего приложения больше одного клиента, то для каждого из них необходимо создавать свое собственное подключение к БД. Или же использовать пул соединений, значительно облегчающий жизнь во многих аспектах (контроль максимального количества подключений, переоткрытие подключений, ...).
А теперь несколько слов о глобальных переменных в node.js.
Node.js кэширует вызовы require, поэтому логику подключения к БД (и хранения внутреннего состояния) можно реализовать в одном из модулей. Предположим, есть модуль lib/mysql_pool.js с таким вот кодом:
var mysql = require('mysql'),
    pool = null;

exports.connect = function(options) {
    pool = mysql.createPool(options);
};

exports.getInstance = function() {
    if (!pool) {
        throw new Error('Connect the pool first');
    }

    return pool;
};

Далее, в процессе инициализации приложения вы инициализируете и пул соединений:
var pool = require('./lib/mysql_pool');

pool.connect({
    host: 'localhost',
    user: 'user',
    password: '1111',
    database: 'test'
});

И там, где собственно необходимо соединение с базой можно выполнить:
var pool = require('./lib/mysql_pool');

pool.getInstance().getConnection(function(err, connection) {
    // ... do something cool
    connection.release();
});

P.S.: На мой взгляд, правильнее было бы создавать пул соединений на этапе инициализации приложения и прередавать его в явном виде между модулями. Это несколько увеличит объем необходимого кода, зато позволит полностью отказаться от магии require (и глобального состояния) и упростит модульное тесторование.


text:
Q: Getting GET http://localhost:4200/null 404 (Not Found) in angular I am working on an angular app using ng9.
I have a div in which I want to set an avatar using using an image from the api.
In the component.ts
....

export class HomeComponent implements OnInit {

  nextLaunch$: Observable<SpacexNext>;

  panelOpenState: true;

  search = '';

  constructor(
    private spacexService: SpacexService,
    private sanitizer: DomSanitizer
    ) { }

  ngOnInit(): void {
    this.nextLaunch$ = this.spacexService.getNextLaunch();
    }

...

in the .html
<div mat-card-avatar *ngIf="(nextLaunch$ | async)?.links?.patch?.small !== null" [style.backgroundImage]="'url('+(nextLaunch$ | async)?.links?.patch?.small+')'" class="example-header-image">
</div>

This works perfectly and the avatar is set as expected, however I have I get an error in the browser console:
GET http://localhost:4200/null 404 (Not Found)

Any ideas to get rid of the error?
More Info..
The api works well and my service returns data as expected.
The avater image is displayed without any problem.
My only issue is the error that appears on the browser console.
I had done some research and saw that using async pipe could be the cause of the issue but I prefer this rather than subscribe method.
TIA.

A: The async pipe is not well suited to be used in this way.
I'd suggest to use an intermediate variable in your component code, to hold the result of your asynchronous operation
public smallPatchUrl: string;

(I assume this url is of type string, adapt if necessary).
In your ngOnInit use:
this.spacexService.getNextLaunch().subscribe(x => {
  if (x && x.links && x.links.patch) {
    this.smallPatchUrl = x.links.patch.small;
  }
});

in your template code, you can use for your component:
*ngIf="this.smallPatchUrl" [style.backgroundImage]="'url(' + this.smallPatchUrl + ')'"

This way, your component will never use this.smallPatchUrl when it is null or undefined.


text:
Q: Maven 2.2 seems to fail during compilation on OSX 10.10 We have a big maven project which compiles just fine on linux(ubuntu) machines.
We are using JDK 1.7.0_71
However, trying to build it(mvn clean install) on osx 10.10.1 on some modules in the project, maven fails with the following exception message:
any ideas??
[ERROR] FATAL ERROR
[INFO] ------------------------------------------------------------------------
[INFO] 9728
[INFO] ------------------------------------------------------------------------
[INFO] Trace
java.lang.ArrayIndexOutOfBoundsException: 9728
    at hidden.org.codehaus.plexus.util.xml.pull.MXParser.parsePI(MXParser.java:2470)
    at hidden.org.codehaus.plexus.util.xml.pull.MXParser.parseEpilog(MXParser.java:1575)
    at hidden.org.codehaus.plexus.util.xml.pull.MXParser.nextImpl(MXParser.java:1405)
    at hidden.org.codehaus.plexus.util.xml.pull.MXParser.next(MXParser.java:1105)
    at org.apache.maven.model.io.xpp3.MavenXpp3Reader.parseModel(MavenXpp3Reader.java:2133)
    at org.apache.maven.model.io.xpp3.MavenXpp3Reader.read(MavenXpp3Reader.java:3912)
    at org.apache.maven.project.DefaultMavenProjectBuilder.readModel(DefaultMavenProjectBuilder.java:1606)
    at org.apache.maven.project.DefaultMavenProjectBuilder.readModel(DefaultMavenProjectBuilder.java:1571)
    at org.apache.maven.project.DefaultMavenProjectBuilder.findModelFromRepository(DefaultMavenProjectBuilder.java:562)
    at org.apache.maven.project.DefaultMavenProjectBuilder.buildFromRepository(DefaultMavenProjectBuilder.java:251)
    at org.apache.maven.project.artifact.MavenMetadataSource.retrieveRelocatedProject(MavenMetadataSource.java:163)
    at org.apache.maven.project.artifact.MavenMetadataSource.retrieveRelocatedArtifact(MavenMetadataSource.java:94)
    at org.apache.maven.artifact.resolver.DefaultArtifactCollector.recurse(DefaultArtifactCollector.java:387)
    at org.apache.maven.artifact.resolver.DefaultArtifactCollector.recurse(DefaultArtifactCollector.java:435)
    at org.apache.maven.artifact.resolver.DefaultArtifactCollector.collect(DefaultArtifactCollector.java:74)
    at org.apache.maven.artifact.resolver.DefaultArtifactResolver.resolveTransitively(DefaultArtifactResolver.java:316)
    at org.apache.maven.artifact.resolver.DefaultArtifactResolver.resolveTransitively(DefaultArtifactResolver.java:304)
    at org.apache.maven.plugin.DefaultPluginManager.resolveTransitiveDependencies(DefaultPluginManager.java:1499)
    at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:442)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:694)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalWithLifecycle(DefaultLifecycleExecutor.java:556)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:535)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:387)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:348)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:180)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:328)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:138)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:362)
    at org.apache.maven.cli.compat.CompatibleMain.main(CompatibleMain.java:60)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
    at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
    at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)
    at org.codehaus.classworlds.Launcher.main(Launcher.java:375)


text:
Q: how to clear grow heap size in titanium app in android? I have download 100 images store in application data directory its working fine
but i have download more images then grow heap size problem is coming and application is closed.I have remove all objects,value of objects define null and window is also closed but result is same.
ERROR:grow heap (frag case) to 14.687MB for 517197-byte allocation
Like in Core android System.gc();
So what is the option of titanium

A: why not use
android:largeHeap="true"
  <android xmlns:android="http://schemas.android.com/apk/res/android">
<manifest>
    <application android:largeHeap="true"/>
</manifest>

read titanium official doc here

A: As far as I know, you have no control over the garbage collection. The JavaScript interpreter does this for you.
I did something similar in a project (downloading lots of images) and also ran into memory issues. The most optimal solution I have found is to make sure that garbage collection is possible. The reason for this is that the JavaScript interpreter executes your code and if you loop through all the images and download them, it might not get to do garbage collection before you're done downloading. This means that all the temporary images will still be in memory.
To deal with this issue, you either need to use the defer-method of underscore.js or the setTimeout-function. In sense what they both do is that they tell the interpreter that it's okay to run other stuff before this e.g. garbage collection.
This code sample (using underscore.js) should give you the general idea:
var images = [...many entries here...];

function downloadImage(index) {
  //Make sure the index is valid
  if(index < images.length) {
    var httpClient = Ti.Network.createHttpClient({
       onload: function() {
         //Save the image to the filesystem.
         _defer.(downloadImage, ++index); //Download the next image.
       }
    });

    //Run the HttpClient here.
  }
}

_.defer(downloadImage, 0); //Start the download sequence.

There are also some tags that you can set in the tiapp.xml file, but in my experience they don't help much.

These three articles on "Keeping your app response" explain the point I'm trying to make quite well:

*

*Part 1: The problem

*Part 2: The reason

*Part 3: The solution


text:
Q: R clusplot point shape I'm using kMeans and then clusplot function to plot the data, however i want to use custom point shapes or no point-shapes at all. Using pch argument in clusplot yields an errors (formal argument "pch" matched by multiple actual arguments).
Eg. in following plot change all point shapes by a custom vector:
library(cluster)
d <- dist(scale(mtcars), method="euclidean")
k <- kmeans(d, 2)
clusplot(d, diss=T, k$cluster, labels=2, col.txt=c("blue", "red")[k$cluster])

A: You can get the locations of the points with cmdscale, and then either plot them first and do the cluster plot with invisible points via cex=0 and add=TRUE or do the clusplot first and use points to add the dots in whatever style you want. Points first:
> plot(cmdscale(d),pch=19)
> clusplot(d, diss=TRUE, k$cluster, labels=2, col.txt=c("blue", "red")[k$cluster],cex=0,add=TRUE)

Cluster first, then points with alternating symbols just for illustration:
> clusplot(d, diss=TRUE, k$cluster, labels=2, col.txt=c("blue", "red")[k$cluster],cex=0)
> points(cmdscale(d),pch=1:2)

You might also want to use xlim=c(-5,5) to get the labels completely in.


text:
Q: JQuery - Typeahead with unique listing on suggestion This is the first time I am using typeahead for my search. I have successfully listed the search result in the suggester. I am listing my item title as suggestion in my suggester.

As you see from the screenshot, item have same name is repeating. I only need to show the full title once the prefix are completed or entered. Let me share my base code for your reference.
/* typeahead script */
            $('input.typeahead').typeahead({
            source:  function (query, process) {
            return $.get('ajaxpro.php', { query: query }, function (data) {
                    console.log(data);
                    data = $.parseJSON(data);
                    return process(data);
                });
            }
        });
  /*Backend Processing*/
        $sql = "SELECT menu_name FROM myqstar_menus
            WHERE menu_name LIKE '%" . $_GET['query'] . "%'
    LIMIT 10";
    $result = $mysqli->query($sql);

    $json = [];
    while ($row = $result->fetch_assoc()) {
        $json[] = $row['menu_name'];
}

I tried to group the result, but failed. what I am looking for a result as search-as-you-type.


text:
Q: select statement blocking another select statement I'm not quite sure what is happening here.  I have an alert that goes out if @StoreOrderID >1.
It goes like this:
declare @message varchar(1000)
@StoreID --(retrieves info from StoreOrders tables)

BEGIN
    select @message =  'store' + storename
                                from StoreOrders as so
                                join Distributors as ds
                                on ds.DistributorID = so.StoreOrderID
                                where ds.SDistributorID = @StoreID

    select @message =   brandID
                                from StoreOrders a
                                join Brandtitles as b
                                on b.branddistributorID = a.StoreOrderID
                                where b.brandNum = @DistributorNum and b.branddistributorID = @StoreID

select @message = 'date' + ISNULL(convert(varchar, @Date),'')
select @message = 'cost' + ISNULL(Convert(varchar,@Cost),'')

Also for some reason if i try to concatenate a string unto the 'brand' select it throws an error.  I can do it for the 'storename'. I think this may have something to do with it.
If I comment out the storename select it will send the alert for brandID, if I comment out the other one it does the other one. However, if I leave both of them, it will only show one of them.  What am I doing wrong here?

A: As a user mentioned in the comments, you are overwriting the  @message variable everytime you assign it a new value, you are not concatenating any of the values. A much simpler and cleaner way would be something like....
declare @message varchar(1000)
        @StoreID [DataType]--(retrieves info from StoreOrders tables)

BEGIN

Declare  @storename  VARCHAR(100)
       , @brandID    VARCHAR(100)
       , @Date       VARCHAR(100)
       , @Cost       VARCHAR(100);

    select @storename =  'store' + ISNULL(storename , 'Unknown')
    from StoreOrders as so
    join Distributors as ds
    on ds.DistributorID = so.StoreOrderID
    where ds.SDistributorID = @StoreID;

    select @brandID =   ISNULL(CAST( brandID AS VARCHAR(100) , 'Unknown')
    from StoreOrders a
    join Brandtitles as b
    on b.branddistributorID = a.StoreOrderID
    where b.brandNum = @DistributorNum
      and b.branddistributorID = @StoreID;

select @Date = 'date' + ISNULL(convert(varchar, @Date),'');
select @Cost = 'cost' + ISNULL(Convert(varchar,@Cost),'');

SET @message = @storename + @brandID + @Date + @Cost;

A: I Assume the code "alerting" the message is after the snipped you showed.
Then, as you use the same variable @message as target for both assignments, you overwrite the contents you assigned the first time when doing the second assignment. Only the values from the second assignment make it to the "alerting" command.
Use two different variables or "alert" your message after each assignment.


text:
Q: C standard prohibition on warnings by default Seeing yet another question the answer to which would have been obvious had the questioner compiled with -Wall got me thinking.
Is there a 'C standard' based reason why -Wall cannot be enabled by default by the compiler?
As far as I know none of the major compilers do this (and certainly historically none of them did it), and I'd like to know whether this is adherence to the standard, or some other reason (inertia, back compatibility or whatever). Speculating as to the other reason is probably off-topic (opinion based), but I think asking whether a standard requires this behaviour is on-topic (factual).

A: Quoted from N1570 Annex I:

1 An implementation may generate warnings in many situations, none of
  which are specified as part of this International Standard.

This implies that warnings are non-compulsory to compilers, so I don't think there would be any "C standard" based reasons.

A:
Is there a 'C standard' based reason why -Wall cannot be enabled by default by the compiler?

I think that the answer to that is that no standard-based reason.  The behavior of compiler switches is outside the scope of a language standard.
Beyond that, a compiler is (generally speaking) not required to produce diagnostics for things that are not specified to be compilation errors, so requiring such diagnostics be output "by default" is nonsensical.

And to be clear, these general statements apply in the case of the C language.

A: Besides the reason mentioned above, that the standard does not have specifications on warnings, make Wall default would be more a obstacle for many people because there are warnings that you actually don't want to turn on from time to time, such as warnings on unused variables/functions etc.
If you want to make it "by default", you can alias the compiler of your choice, take gcc as example, add following in your bashrc:
alias gcc="gcc -Wall"


text:
Q: font-face for local fonts I have a framework of html/css pages using a font-face declaration with a otf. Now I want to switch it to a common font like Verdana. How can I assign Verdana to the font-face declaration avoiding a numerous replacement of font-family declaration? In other words: How can I use the font name declarated by font-face as a font variable?
@font-face {
    font-family: 'bauer-bodoni.otf';
    src: url(../fonts);

Should be something like this (which is not working in this form):
@font-face {
    font-family: 'Verdana', 'Arial', sans-serif;

Thank you very much in advance.
-R.
EDIT/ANSWER: I've found out on my own. The trick is not to list the fonts the way you do in a normal font declaration, separated by comma, but with a "local()" for each:
@font-face {
    font-family: 'myOwnFontSet';
    src: local('Verdana');
    src: local('Arial');
    src: local(sans-serif);

A: Your update is still wrong. You need the following:
@font-face {
font-family: 'myOwnFontSet';
src: local('Verdana'), local('Arial'), local(sans-serif); }


text:
Q: how to set default value for text type in mysql CREATE TABLE IF NOT EXISTS `te` (
  `id` int(30) NOT NULL,
  `name` text NOT NULL,
  `address` text NOT NULL,
  `Aboutus` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Here Table 'te' consist 4 fields id, name, address, Aboutus, Aboutus is optional means how can i update default text to the Profile in db , by phpmyadmin sql

A: I have changed not null to null for about us field
CREATE TABLE IF NOT EXISTS `te` (
  `id` int(30) NOT NULL,
  `name` text NOT NULL,
  `address` text NOT NULL,
  `Aboutus` text NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Here is your trigger BEFORE INSERT
CREATE TRIGGER new_insert
BEFORE INSERT ON `te`
FOR EACH ROW
SET NEW.`Aboutus` = CASE WHEN NEW.Aboutus IS NULL THEN 'Not Updated' ELSE NEW.Aboutus END
;

Insert without Aboutus
INSERT INTO `te` (`id`, `name`, `address`)
VALUES (1, 'name', 'address') ;

Insert with Aboutus
INSERT INTO `te` (`id`, `name`, `address`, `Aboutus`)
VALUES (2, 'name', 'address', 'Aboutus') ;

Insert by passing null Aboutus
INSERT INTO `te` (`id`, `name`, `address`, `Aboutus`)
VALUES (3, 'name', 'address', null) ;

Demo
Edit As @garethD pointed a case for update scenario,you also need another trigger on BEFORE UPDATE so if null appears in update then aboutus should be updated as Not Updated
CREATE TRIGGER update_trigger
BEFORE UPDATE ON `te`
FOR EACH ROW
SET NEW.`Aboutus` = CASE WHEN NEW.Aboutus IS NULL THEN 'Not Updated' ELSE NEW.Aboutus END
;

UPDATE te
SET AboutUs = NULL;

Demo 2

A: For Ubuntu 16.04:
How to disable strict mode in MySQL 5.7:
Edit file /etc/mysql/mysql.conf.d/mysqld.cnf
If below line exists in mysql.cnf
sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

Then Replace it with
sql_mode='MYSQL40'

Otherwise
Just add below line in mysqld.cnf
sql_mode='MYSQL40'

This resolved problem.


text:
Q: Combining resources in AngularJS I have a RESTful API that provides me with employees and departments. In my AngularJS app, I need to know the employee and the departments the employee belongs to. I have defined two factory services for that:
angular.module('myApp.services', [])
    .factory('Employee', function ($resource) {
        return $resource ('/api/employees/:id', { id: '@id' });
    })
    .factory('Department', function ($resource) {
        return $resource ('/api/departments/:id', { id: '@id' });
    })
;

In the controller, I call:
$scope.employee = Employee.get({id: 'me'});

Next, I want to call:
$scope.departments = [];
angular.forEach($scope.employee.departmentIds, function (departmentId) {
    $scope.departments.push(Department.get({ id: departmentId }));
});

But $scope.employee is a promise object, so $scope.employee.departmentIds will only be known when the first request is completed.
I could solve it like this:
Employee.get({id: 'me'}).$promise.then(function (employee) {
    $scope.employee = employee;
    $scope.departments = [];
    angular.forEach(employee.departmentIds, function (departmentId) {
        $scope.departments.push(Department.get({ id: departmentId }));
    });
});

The problem is that I need this information in multiple controllers, and don't want to repeat this code in every controller. So my question is: is there a way to combine these two resources as a service which provides both the employee data and the data of the departments to which that employee belongs?

A: You can do something like that:
angular.module('myApp.services', [])
    .factory('SimpleEmployee', function ($resource) {
        return $resource ('/api/employees/:id', { id: '@id' });
    })
    .factory('Department', function ($resource) {
        return $resource ('/api/departments/:id', { id: '@id' });
    })
    .factory('Employee', ['SimpleEmployee', 'Department', function(SimpleEmployee, Department) {
        return {
            get: function(params) {
                var data = SimpleEmployee.get({id: params.id}, function (employee) {
                    var obj = {
                        employee: employee,
                        departments: []
                    };
                    angular.forEach(employee.departmentIds, function (departmentId) {
                        obj.departments.push(Department.get({ id: departmentId }));
                    });
                    return obj;
                });
                return data;
            }
        }
    }]);

And you dont need to change anything in your controller.

A: This answer is based on the answer of @Beterraba (but the code example in that answer is incorrect):
Service:
angular.module('myApp.services', [])
    .factory('SimpleEmployee', function ($resource) {
        return $resource ('/api/employees/:id', { id: '@id' });
    })
    .factory('Department', function ($resource) {
        return $resource ('/api/departments/:id', { id: '@id' });
    })
    .factory('Employee', ['SimpleEmployee', 'Department', function(SimpleEmployee, Department) {
        return {
            get: function(params) {
                return SimpleEmployee.get({id: params.id}).$promise.then(function (employee) {
                    employee.departments = [];
                    angular.forEach(employee.departmentIds, function (departmentId) {
                        employee.departments.push(Department.get({ id: departmentId }));
                    });
                    delete employee.departmentIds;
                    return employee;
                });
            }
        }
    }]);

Controller:
Employee.get({ id: 'me' }).then(function (employee) {
    $scope.employee = employee;
});

From AngularJS 1.2 RC3 on you need to unwrap any promise objects on the controller. I found this information here.

*

*commit

*issue


text:
Q: getting a list of divs within a parent (querySelectorAll) I have a simple bar chart, as shown below, - each bar is a simple div contained within a parent div. I'd like to iterate through the parent div and pull the value and data-cat attribute for further processing.

4

4

4

4

So far I've tried variations of querySelectorAll without success - I'm messing up the syntax somehow.
 //finds chart within a parent div not shown above
 var chart = $('#comment-' + index).find('.chart');

//var everyChild = document.querySelectorAll('.graph');
var everyChild = chart.querySelectorAll('.graph');
for (var i = 0; i<everyChild.length; i++) {
    console.log(everyChild[i]);
}

document.querySelectorAll('.graph'); returns a result, but as there's more than one graph on the page, it returns multiple results. How can I use chart as a point of reference o I can get the data on an individual graph? At the moment it's returning the error chart.querySelectorAll('.graph') is not a function
Thanks in advance...

A: jQuery is great, should be use if possible, here is how you can traverse in given DOM.

var charts = $('.chart > .graph');
charts.each(function(i,graph){
  console.log("Graph: "+ i)
    $(graph).find('.bar').each(function(j,bar){
      console.log("data-cat: "+ bar.getAttribute('data-cat'))
    });
});

2

2

2

2

4

4

4

4

A: You can change the querySelector itself to something like:
document.querySelectorAll('.chart .graph');

Furthermore you should take a look at the documentation of querySelectorAll() it returns a NodeList and you can perform a loop through a NodeList by calling .forEach() on the NodeList everyChild
Even though this should be a solution I would recommend using something like jQuery.
Best regards.

A: Try putting IDs to your parent divs:

4

4

4

4

And then do
$("#graph1").children().each(function () {
    var cat = $(this).data("cat");
    var text = $(this).text();
});