Q: How to hide hover and click event of UniformGrid? I try to create a list of buttons with two columns using a ListBox and UniformGrid. Everything seemed to be okay until I faced the following issue. The margin space of the button was shown with light blue color when I click it or hover over it. How to remove this effect?

This is my code:
<ListBox Width="1000" Grid.Row="1" VerticalAlignment="Top" VerticalContentAlignment="Top" Name="uniformGrid1" Margin="50" ItemsSource="{Binding SomeItemsList}">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Columns="2" Background="Transparent"   Name="uniformGrid1"></UniformGrid>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Button Margin="50" Height="70" Click="keyword_Click" Width="250"
         Foreground="Black" FontSize="16" FontFamily="Helvetica Neue" FontWeight="Bold"
        BorderBrush="SlateGray" Content="{Binding Name}">
                <Button.Background>
                    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                        <GradientStop Color="White" Offset="0.073" />
                        <GradientStop Color="White" Offset="1" />
                        <GradientStop Color="#FFE9E9F9" Offset="0.571" />
                        <GradientStop Color="#FFD7D7EC" Offset="0.243" />
                    </LinearGradientBrush>
                </Button.Background>
            </Button>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

A: The problem here is that the ListBox has a selection, and selected items get highlighted. You need to disable this highlighting to get the desired result, for example by setting ListBox.ItemContainerStyle as described in this answer. This will remove the (lightblue) selection color.

A: Each item in the ItemsSource is wrapped in a ListBoxItem inside the ListBox. A ListBox is a control derived from Selector, which is a base type for items controls that allow selection of items.

Represents a control that allows a user to select items from among its child elements.

What you specified as DataTemplate will be placed in a ListBoxItem at runtime, which is the container for the content. This container has a default style and control template that defines its appearance and visual states. What you see is the MouseOver state and the Selected state. You can change this by extracting the default style for ListBoxItem and adapting it or by writing your own.

*

*How to create a template for a control (WPF.NET)
However, it seems that your intention is different. What you probably wanted was to simply display buttons in a UniformGrid depending on a bound collection, without any selection. You can achieve this by using an ItemsControl instead. It does not offer any selection capabilities, but lets you bind a collection with the UniformGrid as items panel.
<ItemsControl Width="1000" Grid.Row="1" VerticalAlignment="Top" VerticalContentAlignment="Top" Margin="50" ItemsSource="{Binding SomeItemsList}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Columns="2" Background="Transparent" Name="uniformGrid1"></UniformGrid>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button Margin="50" Height="70" Click="keyword_Click" Width="250"
         Foreground="Black" FontSize="16" FontFamily="Helvetica Neue" FontWeight="Bold"
        BorderBrush="SlateGray" Content="{Binding Name}">
                <Button.Background>
                    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                        <GradientStop Color="White" Offset="0.073" />
                        <GradientStop Color="White" Offset="1" />
                        <GradientStop Color="#FFE9E9F9" Offset="0.571" />
                        <GradientStop Color="#FFD7D7EC" Offset="0.243" />
                    </LinearGradientBrush>
                </Button.Background>
            </Button>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Please note that I have removed one of two Name="uniformGrid1" as duplicate names lead to a compilation error. If your content exceeds the viewport and you need scrollbars, you have to add a ScrollViewer, since this is built into the ListBox, but not the ItemsControl.
<ScrollViewer HorizontalScrollBarVisibility="Auto"
              VerticalScrollBarVisibility="Auto">
   <ItemsControl  Width="1000" Grid.Row="1" VerticalAlignment="Top" VerticalContentAlignment="Top" Margin="50" ItemsSource="{Binding SomeItemsList}">
      <!-- ...other code. -->
   </ItemsControl>
</ScrollViewer>


Q: Error in your SQL syntax for INNER JOINS I have been trying to run this mysql query through rstudio, but I keep getting an error. Any idea why?
Here is my query:
SELECT host.key AS 'uid',
 daily_summary.date AS 'date'
 FROM host INNER JOIN daily_summary
 USING(weekly_id);

This is the error I get.
42000 1064 [MySQL][ODBC 5.1 Driver][mysqld-5.5.40-
0ubuntu0.14.04.1]You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server
version for the right syntax to use near 'FROM host INNER
JOIN daily_summary USING(weekly_id)' at line 1

A: This is the query as it would better be written:
SELECT host.key AS uid, daily_summary.date
FROM host INNER JOIN
     daily_summary
     USING(weekly_id);

In addition to removing the spurious commas, this also removes the unneeded quotes around the column aliases.  Only use single quotes for string and date constants.  Otherwise, they are likely to cause confusion in queries.  If you need to escape aliases in MySQL, then use backticks.

A: Check version simplified without typos:
SELECT host.key, daily_summary.date
FROM host INNER JOIN daily_summary
USING(weekly_id);

I also prefer to use word ON instead of USING:
SELECT host.key, daily_summary.date
FROM host INNER JOIN daily_summary
ON host.weekly_id = daily_summary.weekly_id

A: The MySQL syntax error message shows you part of your statement starting with the first character it can't understand.  In your case the first characters it can't understand are FROM.  It's looking for another column name after the comma.


Q: using handler for every single task(method) in android Hello i am new to android and android thread so want to know that
How could we use more number of thread in order to perform every single task or method so that while user click on any UI component it does effect the performance ,having little knowledge of how the handler thread and asynctask work.But how can we run every method inside the asynctask so to do the operation and mean while user can do the other operation also.
In the application

*

*i have voice recording from mic.

*next showing progress bar.

*next showing gallery with some image and with that setting effect to the picture.

A: The recommended way is to use AsyncTasks for long running tasks. So, not everything needs to be run with AsyncTasks, as you can get a performance hit due to the context switching.
As for how AsyncTasks work, read the documentation.

A: Use an AsyncTask and make sure to implement these as needed. You mention the idea of doing something in the background while a user is doing something so I'm guessing you'll want to alter the UI.
Take a look at these links for an more details from Android. They cover Runnable, AsyncTask and Handler

*

*Overview of them all http://developer.android.com/guide/components/processes-and-threads.html

*AsyncTask example http://developer.android.com/reference/android/os/AsyncTask.html

*Old but relevant, Painless Threading http://android-developers.blogspot.com/2009/05/painless-threading.html

*Another, more complex example http://developer.android.com/training/displaying-bitmaps/process-bitmap.html
I don't generally paste full examples in here but I had a lot of trouble finding an example I was happy with for a long time and to help you and others, here is my preferred method. I generally use an AsyncTask with a callback to the Activity that started the task.
In this example, I'm pretending that a user has triggered onClick(...) such as with a button, but could be anything that triggers a call into the Activity.
// Within your Activity, call a custom AsyncTask such as MyTask
public class MyActivity extends Activity implements View.OnClickListener, MyTask.OnTaskComplete {
    //...

    public void onClick(View v) {
        // For example, thet user clicked a button
        // get data via your task

        // using `this` will tell the MyTask object to use this Activty
        // for the listener
        MyTask task = new MyTask(this);
        task.execute(); // data returned in callback below
    }

    public void onTaskComplete(MyObject obj) {
        // After the AsyncTask completes, it calls this callback.
        // use your data here
        mTextBox.setText(obj.getName);
    }
}

Getting the data out of a task can be done many ways, but I prefer an interface such as OnTaskComplete that is implemented above and triggered below.
The main idea here is that I often want to keep away from inner classes as they become more complex. Mostly a personal preference, but it allows me to separate reusable tasks outside of one class.
public class MyTask extends AsyncTask<Void, Void, MyObject> {

    public static interface OnTaskComplete {
        public abstract void onTaskComplete(MyObject obj);
    }
    static final String TAG = "MyTask";

    private OnTaskComplete mListener;

    public MyTask(OnTaskComplete listener) {
        Log.d(TAG, "new MyTask");
        if (listener == null)
            throw new NullPointerException("Listener may not be null");

        this.mListener = listener;
    }

    @Override
    protected MyObject doInBackground(Void... unused) {
        Log.d(TAG, "doInBackground");
        // do background tasks

        MyObbject obj = new MyObject();
        // Do long running tasks here to not block the UI
        obj.populateData();
        return
    }

    @Override
    protected void onPostExecute(MyObject obj) {
        Log.d(TAG, "onPostExecute");
        this.mListener.onTaskComplete(obj);
    }
}


Q: Running Program from Call Doesn't Seg Fault My program writenotes keeps seg faulting when I try to write a note that is too long.
./writenotes lolololololololololololololololololololololololololololololololololololololololololololololololololololololololololololololololololo
[ * ] Writing notes
Segmentation fault

Anyways, I was trying to write a python script that calls the program and curiously enough, calling it from a python script doesn't bring a seg fault, which I thought was rather peculiar.
Heres this code:
#!/usr/bin/python

from subprocess import call

call(["./writenotes", "lolololololololololololololololololololololololololololololololololololololololololololololololololololololololololololololololololo"])

Which returns
[ * ] Writing notes

Is this because of parent processing or something like such?  How would calling a program through subprocess save a program from a segfault though?  Are there other ways to call programs from a script that suffer seg faults?
As a note, the writenotes program was written in C.  The other script is python.

A: You'll almost certainly find your C program is crashing but that Python is hiding that from you. Try instead with:
print call(["./writenotes", "lolololol..."])

and see what you get as a return value.

For example, this program tries to modify a string literal and, when run normally dumps core:
int main (void) {
    *"xyzzy" = 'X';
    return 0;
}

However, when run from the following script:
from subprocess import call
print call(["./testprog"])

I get the output -11, indicating that signal 11 (usually SIGSEGV) was raised, as per the documentation discussing Popen.returncode which subprocess.call() uses under the covers:

A negative value -N indicates that the child was terminated by signal N (Unix only).

An alternative to checking the return code is to import check_call and CalledProcessError instead of call and then use that function. It will raise an exception if the return code is non-zero.
That's probably not so important if you're only calling one executable (just get the return value in that case) but, if you're doing a lot in sequence, catching an exception from the entire group may be more readable.
Changing the C program to only crash when the first argument is 3:
#include <stdio.h>
#include <string.h>
int main (int argc, char *argv[]) {
    if (argc > 1) {
        printf ("hello there %s\n", argv[1]);
        if (strcmp (argv[1], "3") == 0)
            *"xyzzy" = 'X';
    }
    return 0;
}

and the script to call it with several different arguments:
from subprocess import check_call, CalledProcessError
try:
    check_call(["./testprog", "0"])
    check_call(["./testprog", "1"])
    check_call(["./testprog", "2"])
    check_call(["./testprog", "3"])
    check_call(["./testprog", "4"])
    check_call(["./testprog", "5"])
    check_call(["./testprog", "6"])
    check_call(["./testprog", "7"])
    check_call(["./testprog", "8"])
    check_call(["./testprog", "9"])
except CalledProcessError as e:
    print e.cmd, "failed with", e.returncode
else:
    print "Everything went well"

shows that in action:
hello there 0
hello there 1
hello there 2
hello there 3
['./testprog', '3'] failed with -11


Q: Is it possible to recuperate data entered by user in a dynamic table I have created a dynamic table using html+php with input like a form (this is a matrix in reality) and
  I want to know if it is possible to recuperate data entered by user in a dynamic table? This is my code:
<?php
$rows = 3; // define number of rows
echo ' <form action="f.php" method="post">';
echo "
";
for($tr=1;$tr<=$rows;$tr++){
    echo "
";
    echo " E".$tr." 	";
        for($td=1;$td<=$rows;$td++){
               echo '<input type="number" name="etat" placeholder="nb d etat" />	';
        }
    echo "
";
}
echo "
";
echo '<input type="submit" value="Create Table">';
echo '</form>'
?>

A: Yes it is possible but you have to create form by giving row and column number because you want to create matrix:
$rows = 3; // define number of rows
echo ' <form action="f.php" method="post">';
echo "
";
for($tr=1;$tr<=$rows;$tr++){
    echo "
";
    echo " E".$tr." 	";
        for($td=1;$td<=$rows;$td++){
               echo '<input type="number" name="etat_'.$tr.'_'.$td.'" placeholder="nb d etat" />	';
        }
    echo "
";
}
echo "
";
echo '<input type="submit" name="submit" value="Create Table">';
echo '</form>';

in f.php fetch data :
if(isset($_POST['submit'])) {
    print_r($_POST);
}

It gives you output:
Array
(
    [etat_1_1] => 1 //means 1st row 1st column
    [etat_1_2] => 2 //means 1st row 2nd column
    [etat_1_3] => 3 //means 1st row 3rd column
    [etat_2_1] => 4 //means 2nd row 1st column and so on...
    [etat_2_2] => 5
    [etat_2_3] => 6
    [etat_3_1] => 7
    [etat_3_2] => 8
    [etat_3_3] => 9
    [submit] => Create Table
)


Q: Daemon java process - is there such a thing? My java program creates a process in the following manner:
ProcessBuilder builder = new ProcessBuilder("phantomjs.exe crawl.js");
Process proc = builder.start();

In case the java program terminates abruptly (could always happen), the phantomjs process (which is not a java process) could stay alive and there would be no way to terminate it.
I want the phantomjs process to be terminated when the enclosing java process terminates (whether abruptly or not).
Is there a way to define the Process instance as a "daemon" object that terminates automatically when its super process (which is the java process executing the code above) terminates?

A: The API documentation seems pretty definite, no qualifications or weasel-wording:

The subprocess is not killed when there are no more references to the Process object, but rather the subprocess continues executing asynchronously.

So the parent has to kill it, it won't go away when the parent terminates.

A: Not a great solution, but you could always check periodically the PID of the parent from the children.


Q: c++ mysql connection bad_alloc using c++ connector Trying to build a simple mysql connection, but getting a bad_alloc and I can't figure out how to solve this, even looking at similar posts
here is my code
#include <iostream>
#include <stdlib.h>
#include <sstream>
#include <memory>
#include <string>
#include <stdexcept>

#include "mysql_connection.h"
#include "cppconn\driver.h"
#include "cppconn\statement.h"
#include "cppconn\connection.h"
#include "cppconn\exception.h"
#include "cppconn\prepared_statement.h"
#include "cppconn\statement.h"

using namespace std;
using namespace sql;

int main()
{

    Driver *driver;
    Connection *conn;
    Statement *stmt;

    driver = get_driver_instance();
    conn = driver->connect("127.0.0.1:3306", "root", "root"); // breaks here
    stmt = conn->createStatement();
    stmt->execute("USE mydb");

    return 0;
}

I'm using mysql-connector-c++-1.1.7
mysqlcppconn.lib is used as a dependencies
mysqlcppconn.dll is located in the same dir as the .exe is.
Here is the error Exception thrown at 0x000007FEFD39A06D in MysqlConn.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x000000000014F5D0.
Thanks

A: I also had this error. In my case I am compiling using VS2015 in Windows.
First time I choose compile static version of the MySQL lib. Then later I decided to compile the dynamic version. This time the error bad_alloc at memory went off.
The solution is rolling back the CPPCONN_PUBLIC_FUNC= configuration.
Go to project Property Pages, under C++ > Preprocessor > Preprocessor Definitions and remove the item CPPCONN_PUBLIC_FUNC=".

A: I had the same error on linux.
The error was : I was using g++-4.8 to build the project
The issue lies on the version of the build tools (gcc,msvs,clang) used to build the project


Q: Combine table and matrix with R I am performing an analysis in R. I want to fill the first row of an matrix with the content of a table. The problem I have is that the content of the table is variable depending on the data so sometimes certain identifiers that appear in the matrix do not appear in the table.
> random.evaluate
     DNA LINE LTR/ERV1 LTR/ERVK LTR/ERVL LTR/ERVL-MaLR other SINE
[1,]  NA   NA       NA       NA       NA            NA    NA   NA

> y
  DNA          LINE      LTR/ERVK      LTR/ERVL LTR/ERVL-MaLR     SINE
    1             1             1             1             1       4

Due to this, when I try to join the data of the matrix with the data of the table, I get the following error
random.evaluate[1,] <- y
Error in random.evaluate[1, ] <- y :
  number of items to replace is not a multiple of replacement length

Could someone help me fix this bug? I have found solutions to this error but in my case they do not work for me.

A: First check if the column names of the table exist in the matrix
Check this link
If it exists, just set the value as usual.


Q: Make a iOS WebView behave like a ebook reader Normally within a webview, when your page is too long, you can scroll vertically like a browser, that is the default.
I want to make this webview behave like a ebook reader, say when you need 3 pages to display the whole content, instead of scrolling vertically, you can slide to the next page which like a ebook reader (e.g. iOS Kindle app).
Any thoughts on how to implement this? Or any existing components I can use?
Cheer.

A: Very much depends on how much control you (want to) have on the html...
For complete layout control (magazine like) there's baker framework.
Or if you need a quick and dirty script auto generate html file with pagination (instapaper like), I'd use css3 multi-column layout, with some js to calculate the column needed. And use something like SwipeView to manage the scrolling.

A: This is not trivial, and there are a couple of HTML projects having to do with pagination. The ubiquitous jQuery also includes support for paginating HTML content.
Have look at this S.O. post for more details.

A: You can use UISwipeGestureRecognizer on UIWebView and move to the Page programmatically
Good Luck

A: To do this, you could start with a UIPageViewController and populate each page with a UIWebView, each scrolled down to a certain offset and disable scrolling of the underlying scroll view.


Q: Spring Boot Security: Why Strict-Transport-Security header is not including preload; when preload set to true I have a spring boot application where i have added WebSecurityConfigurerAdapter.
I want to have the response header strict-transport-security: max-age=16000000; includeSubDomains; preload;
I have added the below code to the SecurityConfig as:
@Override
  protected void configure(HttpSecurity http) throws Exception {

    http.headers(headers ->
        headers.httpStrictTransportSecurity(hstsConfig -> {
          hstsConfig.preload(true);
          hstsConfig.includeSubDomains(true);
          hstsConfig.maxAgeInSeconds(31536000);
        })
            .contentSecurityPolicy(contentSecurityPolicy ->
                contentSecurityPolicy
                    .policyDirectives("script-src 'self'")
            )
            .addHeaderWriter(new StaticHeadersWriter("X-My-Custom-Header","myvalue"))
    );

    http.csrf().disable();
  }

The response header is not adding the "preload;" instead it looks like:
Strict-Transport-Security: max-age=31536000; includeSubDomains
Can someone please help me to understand what am I missing here?
Spring Security Config: v5.4.6
Thanks


Q: In android, what can I use for a root element (View, ViewGroup, etc.) of my custom control which only allows a single child? Trying to write better-encapsulated custom views and composite controls.
The old way I would do this was to subclass a ViewGroup such as LinearLayout, like so...
public class RadioButton extends LinearLayout
{
    private RadioButtonView radioButtonView;
    private TextView        textView;

    public RadioButton(Context context)
    {
        super(context);
        commonInit(context, null, 0);
    }

    public RadioButton(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        commonInit(context, attrs, 0);
    }

    public RadioButton(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        commonInit(context, attrs, defStyle);
    }

    private void commonInit(Context context, AttributeSet attrs, int defStyle)
    {
        View.inflate(context, R.layout.part_radio_button, this);

        radioButtonView = (RadioButtonView) findViewById(R.id.radioButtonView);
        textView        = (TextView)        findViewById(R.id.textView);

        final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RadioButton, defStyle, 0);

        String text = a.getString(R.styleable.RadioButton_text);
        setText(text != null ? text : "Unset");

        boolean isSelected = a.getBoolean(R.styleable.RadioButton_isSelected, false);
        setIsSelected(isSelected);

        a.recycle();
    }

    public String getText()
    {
        return textView.getText().toString();
    }
    public void setText(String newValue) { textView.setText(newValue); }

    public boolean getIsSelected()
    {
        return radioButtonView.getIsSelected();
    }
    public void setIsSelected(boolean newValue){ radioButtonView.setIsSelected(newValue);}
}

The layout R.layout.part_radio_button would look like this (note the Merge tag)...
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <com.citi.mobile.reusable.ui.RadioButtonView
        android:id="@+id/radioButtonView"
        style="@style/DefaultRadioButtonView" />

    <TextView
        android:id="@+id/textView"
        style="@style/DefaultRadioButtonText" />

</merge>

This worked really well ...at first!  It looked like it properly handled automatic loading the layout so the user could simply 'new-up' the control, or just reference it in a layout file themselves.
But soon it became evident that there were issues with this approach.

*

*DataBinding which requires a root <layout /> tag.

*The <merge /> tag cannot be a child of the  tag nor vice-versa.

*I couldn't define the default properties for the root control in the XML and had to do it programmatically in the constructor.

*Since I was setting them in the constructor, I also couldn't style them since the constructor was overriding their values.  I couldn't simply set the constructor-set values first, because until they were loaded from the layout, there was nothing to set.

*I also realized by subclassing LinearLayout (or any other such control) I was also exposing that LinearLayout to whomever was using this, meaning they could change the orientation, etc.
Because of the above, especially #5, I realized I should do the following instead:

*

*Don't subclass LinearLayout directly as you're exposing it to the outside world when you do.  Instead find a different root control to subclass.

*Because of the change in #1, you can now move LinearLayout back as the root of the layout portion of the layout.xml file (either directly, or under a <layout /> tag when data-binding

*Make the control you've chosen in #1 expose only the bare essentials (i.e. width, height, and whatever attributes you specifically want to expose.)
At this point, I'm starting to think what I need to do is subclass ViewGroup, or perhaps even View (as ViewGroup itself does) and enforce the one-child policy, but I'm not 100% sure, hence this question.

Note: In C#/WPF, they have a Panel class, which is similar to a ViewGroup, but they also have a ContentPresenter class which does exactly what I want... presents a single piece of content.
It's actually pretty slick in that not only can it present a UI component directly, but if you attempt to present something that isn't a UI component, like a (view)model object, it will actually apply a data-bound data template to that object based on its data type, which converts it to something for the UI.  Even if there's no defined template for that specific data type, it will call toString() on it and spit out the equivalent of a TextView.
As cool as that automatic data-presentation capability is though, I'm really only after the first part... the ability to display a single child view(group) which is somewhat protected from the outside world.


Q: Run Multiple timer simultaneously in datagrid wpf I am new to the Window Presentation Foundation (WPF). I have a Data grid showing data very well but I now want to show time in Time column dynamic like call time which is changed every second for every row of data.
here is my class
 public class UserTab
{
    public int Id { get; set; }
    public string AgentName { get; set; }
    public string Extension { get; set; }
    public string Name { get; set; }
    public DateTime Birthday { get; set; }
    public string RowDetail { get; set; }
    public int ActiveParticipants { get; set; }
    public int HeldParticipants { get; set; }
    public int Duration { get; set; }
    public string CallStatus { get; set; }
    public string QueueName { get; set; }
    public string Time { get; set; }
    public string CallStatusColor { get; set; }
    public bool isRowDetail { get; set; }
    public List<UserTab> GetUsers()
    {
        List<UserTab> users = new List<UserTab>();
        users.Add(new UserTab() { CallStatusColor = "#1BDA6D", Time = "00:40:00", QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "John Doe", Extension = "42033", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
        users.Add(new UserTab() { CallStatusColor = "#d70d0d", Time = "00:05:00", QueueName = "AMQ", isRowDetail = false, CallStatus = "Not Ready - Lunch", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "John Doe", Extension = "42034", Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) });
        users.Add(new UserTab() { CallStatusColor = "#E6A30C", Time = "00:00:30", QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "John Doe", Extension = "42035", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
        users.Add(new UserTab() { CallStatusColor = "#E6A30C", Time = "00:06:00", QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 2, AgentName = "AJohn Doe", Extension = "42036", Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) });
        users.Add(new UserTab() { CallStatusColor = "#E6A30C", Time = "00:05:00", QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "BJohn Doe", Extension = "42037", Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) });
        users.Add(new UserTab() { CallStatusColor = "#E6A30C", Time = "00:00:55", QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "CJohn Doe", Extension = "42038", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
        users.Add(new UserTab() { CallStatusColor = "#E6A30C", Time = "00:00:40", QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 2, AgentName = "DJohn Doe", Extension = "42039", Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) });
        users.Add(new UserTab() { CallStatusColor = "#E6A30C", Time = "00:55:00", QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "EJohn Doe", Extension = "42003", Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) });
        users.Add(new UserTab() { CallStatusColor = "#1BDA6D", Time = "00:06:00", QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "EJohn Doe", Extension = "42053", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
        users.Add(new UserTab() { CallStatusColor = "#1BDA6D", Time = "00:10:00", QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 2, AgentName = "FJohn Doe", Extension = "42073", Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) });
        users.Add(new UserTab() { CallStatusColor = "#1BDA6D", Time = "00:00:20", QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "GJohn", Extension = "42078", Name = "Sammy", Birthday = new DateTime(1991, 9, 2) });
        users.Add(new UserTab() { CallStatusColor = "#1BDA6D", Time = "00:00:41", QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "HJohn Doe", Extension = "42083", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
        users.Add(new UserTab() { CallStatusColor = "#1BDA6D", Time = "00:25:00", QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 2, AgentName = "IJohn Doe", Extension = "42093", Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) });
        users.Add(new UserTab() { CallStatusColor = "#1BDA6D", Time = "00:00:00", QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "JJohn Doe", Extension = "42013", Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) });

        return users;
    }
}

  public partial class Tabs : Window
  {
        InitializeComponent();
        List<UserTab> us = new List<UserTab>();
        UserTab user = new UserTab();
        us = user.GetUsers();
        dgSimple.ItemsSource = us
}

here is DataGrid
 <DataGrid Name="dgSimple" VerticalAlignment="Center" VerticalContentAlignment="Center" CellStyle="{StaticResource Body_Content_DataGrid_Centering}" Height="350" EnableRowVirtualization="False">
                                        <DataGrid.Columns>
                                            <DataGridTextColumn Header="Agent Name" Binding="{Binding AgentName}" IsReadOnly="True" />
                                            <DataGridTemplateColumn SortMemberPath="CallStatus" CanUserSort="True" Header="Status" CellTemplate="{StaticResource StatusTemplate}"/>
                                            <DataGridTextColumn Header="Time" Binding="{Binding Time}" IsReadOnly="True"/>
                                            <DataGridTextColumn Header="Extension" Binding="{Binding Extension}" IsReadOnly="True" />
                                        </DataGrid.Columns>
  </DataGrid>

A: A simple sample based on your code, it refresh the DataGrid every 1 second.

*

*In class Tabs, start a new thread by StartMockValue to mock Time value.

*In StartRefreshDataGrid, start a new thread to determine whether to update the DataGrid

*If the Time is different from DisplayTime, then set UserTab -> DisplayTime to notify property changed.

*Finally, the DataGrid updated by new data.
Tabs.xaml
<Window x:Class="TestWpfApp.Tabs"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" Title="MainWindow" Height="450" Width="800">
    <StackPanel>
         <DataGrid Name="dgSimple" VerticalAlignment="Center" VerticalContentAlignment="Center" Height="350"
                   EnableRowVirtualization="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Agent Name" Binding="{Binding AgentName}" IsReadOnly="True" />
                <DataGridTemplateColumn SortMemberPath="CallStatus" CanUserSort="True" Header="Status"/>
                <!--NOTE: bind 'DisplayTime' instead of 'Time'-->
                <DataGridTextColumn Header="Time" Binding="{Binding DisplayTimeString}" IsReadOnly="True"/>
                <DataGridTextColumn Header="Extension" Binding="{Binding Extension}" IsReadOnly="True" />
            </DataGrid.Columns>
         </DataGrid>
    </StackPanel>
</Window>

Tabs.xaml.cs
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace TestWpfApp
{
    public partial class Tabs : Window
    {
        public Tabs()
        {
            InitializeComponent();

            this.Users = new List<UserTab>();
            UserTab user = new UserTab();
            this.Users = user.GetUsers();
            dgSimple.ItemsSource = this.Users;

            this.StartMockValue();

            this.StartRefreshDataGrid();
        }

        private List<UserTab> Users;

        private void StartMockValue()
        {
            // NOTE: this is a thread to mock the business logic, it change 'Time' value.
            Task.Run(() =>
            {
                var rando = new Random();
                while (true)
                {
                    foreach (var user in this.Users)
                    {
                        if (rando.Next(0, 3) == 1)
                        {
                            user.Time = user.Time + 1;
                        }
                    }

                    Thread.Sleep(1000);
                }
            });
        }

        public void StartRefreshDataGrid()
        {
            // NOTE: this is a thread to update data grid.
            Task.Run(() =>
            {
                while (true)
                {
                    foreach (var user in this.Users)
                    {
                        // NOTE: update if the time changed.
                        if (user.DisplayTime != user.Time)
                        {
                            user.DisplayTime = user.Time;
                        }
                    }

                    // NOTE: refresh the grid every seconds.
                    Thread.Sleep(1000);
                }
            });
        }
    }
}

UserTab.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace TestWpfApp
{
    public class UserTab : INotifyPropertyChanged
    {
        public int Id { get; set; }
        public string AgentName { get; set; }
        public string Extension { get; set; }
        public string Name { get; set; }
        public DateTime Birthday { get; set; }
        public string RowDetail { get; set; }
        public int ActiveParticipants { get; set; }
        public int HeldParticipants { get; set; }
        public int Duration { get; set; }
        public string CallStatus { get; set; }
        public string QueueName { get; set; }

        // NOTE: this is the 'real time', some business thread will update the value.
        public int Time { get; set; }

        private int displayTime;

        // NOTE: this is the 'displayed time' in the DataGrid.
        public int DisplayTime
        {
            get => displayTime;
            set
            {
                displayTime = value;
                this.OnPropertyChange(nameof(this.DisplayTimeString));
            }
        }

        public string DisplayTimeString => $"{displayTime / 60 / 60}:{displayTime / 60 % 60}:{displayTime % 60}";

        public string CallStatusColor { get; set; }
        public bool isRowDetail { get; set; }

        public event PropertyChangedEventHandler? PropertyChanged;
        private void OnPropertyChange(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        public List<UserTab> GetUsers()
        {
            var maxSeconds = 24 * 60 * 60;
            var random = new Random();

            List<UserTab> users = new List<UserTab>();
            users.Add(new UserTab() { CallStatusColor = "#1BDA6D", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "John Doe", Extension = "42033", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
            users.Add(new UserTab() { CallStatusColor = "#d70d0d", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = false, CallStatus = "Not Ready - Lunch", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "John Doe", Extension = "42034", Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) });
            users.Add(new UserTab() { CallStatusColor = "#E6A30C", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "John Doe", Extension = "42035", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
            users.Add(new UserTab() { CallStatusColor = "#E6A30C", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 2, AgentName = "AJohn Doe", Extension = "42036", Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) });
            users.Add(new UserTab() { CallStatusColor = "#E6A30C", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "BJohn Doe", Extension = "42037", Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) });
            users.Add(new UserTab() { CallStatusColor = "#E6A30C", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "CJohn Doe", Extension = "42038", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
            users.Add(new UserTab() { CallStatusColor = "#E6A30C", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 2, AgentName = "DJohn Doe", Extension = "42039", Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) });
            users.Add(new UserTab() { CallStatusColor = "#E6A30C", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "EJohn Doe", Extension = "42003", Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) });
            users.Add(new UserTab() { CallStatusColor = "#1BDA6D", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "EJohn Doe", Extension = "42053", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
            users.Add(new UserTab() { CallStatusColor = "#1BDA6D", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 2, AgentName = "FJohn Doe", Extension = "42073", Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) });
            users.Add(new UserTab() { CallStatusColor = "#1BDA6D", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "GJohn", Extension = "42078", Name = "Sammy", Birthday = new DateTime(1991, 9, 2) });
            users.Add(new UserTab() { CallStatusColor = "#1BDA6D", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "HJohn Doe", Extension = "42083", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
            users.Add(new UserTab() { CallStatusColor = "#1BDA6D", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 2, AgentName = "IJohn Doe", Extension = "42093", Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) });
            users.Add(new UserTab() { CallStatusColor = "#1BDA6D", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "JJohn Doe", Extension = "42013", Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) });
            return users;
        }
    }
}


Q: HTTPD ReverseProxy ProxyPass directive ending in wrong Location header HTTPD is configure as following:
#redirectder edit Location "(^http[s]?://)([^/]+)" "" port 80 to secure
<VirtualHost *:80>

    ServerName mitestui02.sn.test.net
    #ServerAlias server server2.domain.com server2
    ServerAdmin support.p240@test.com
    ErrorLog /var/log/test/iiq/appserver/apache-error.log
    CustomLog /var/log/test/iiq/appserver/apache-access.log common

    Redirect /identityiq/ https://mitestui02.sn.test.net/identityiq/
    Redirect / https://mitestui02.sn.test.net/identityiq/

</VirtualHost>

#redirect to port 8080 on localhost
<VirtualHost *:443>
    ServerName mitestui02.sn.test.net
    # ServerAlias mitestui02 mitestui02.sn.test.net
    ServerAdmin support.p240@test.com
    SSLProxyEngine On
    SSLEngine On
    #allow only tls
    SSLProtocol -all +TLSv1.2
    SSLHonorCipherOrder on
    SSLCipherSuite ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384...

    SSLCertificateFile /etc/opt/test/iiq/appserver/secure/ssl/web-iiq.crt
    SSLCertificateKeyFile /etc/opt/test/iiq/appserver/secure/ssl/apache-iiq.key

    Redirect /identityiq/ https://mitestui02.sn.test.net/
    Redirect / https://mitestui02.sn.test.net/identityiq/

    ProxyRequests     Off
    ProxyPreserveHost On

    ProxyPass /identityiq/ http://localhost:8080/identityiq/

    RewriteEngine On
    RewriteCond %{REQUEST_METHOD} ^OPTIONS
    RewriteRule .* - [F]

    <If "%{THE_REQUEST} =~ m#.jsf/?[?\s]#">
        Header add X-UI-Source "mitestui02"
        Header add X-UA-Compatible "IE=edge"
        Header add Referrer-Policy "strict-origin-when-cross-origin"
        Header add Feature-Policy "microphone 'none'; geolocation 'none'; usb 'none'; payment 'none'; document-domain 'none'; camera 'none'; display-capture 'none'; ambient-light-sensor 'none'"
        Header add Permissions-Policy "accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()"
        Header add Strict-Transport-Security "max-age=63072000; includeSubDomains"
        Header add Content-Security-Policy "default-src 'self' 'unsafe-inline' 'unsafe-eval'"
        Header add X-Content-Type-Options "nosniff"

        Header always edit Set-Cookie (.*) "$1; Secure; SameSite=Strict"
        Header onsuccess edit Set-Cookie (.*) "$1; Secure; SameSite=Strict"
    </If>
</VirtualHost>

When I connect to the front-end URL, https://mitest.sn.test.net/ I get redirected with a response code 302 and Location header pointing to https://mitestui02.sn.test.net/identityiq/ instead of  https://mitest.sn.test.net/identityiq/ .
This doesn't happen when connecting to https://mitest.sn.test.net/identity/ directly.
I have tried with different ProxyPass and ProxyPassReverse directives and also rewriting the Location header, nothing seems to help.
Thanks

A: So the issue seemed to be related to the Redirect directives.
We removed them and added the following for 443:
    RewriteEngine On
    RewriteCond %{HTTP:X-Forwarded-Proto} ^http$
    RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301,NE]
    # Redirect / to /identiyiq
    RedirectMatch ^/$ /identityiq

We removed them and added the following for 80:
   Redirect permanent / https://mitestui02.sn.test.net/

Now it is working as expected.


Q: using std::size in a function i have written the following code. The std::size() function ist executing properly in the main() function but not in the getMin() function. Why?
#include <iostream>

int getMin(int numbers[]) {
    int temp = numbers[0];
    int sizeA = std::size(numbers);
    for (int i = 1; i < sizeA; i++) {
        if (temp > numbers[i])
            temp = numbers[i];
    }
    return temp;
}

int main()
{
    int numbers[5] = { 5, 5, -2, 29, 6 };

    std::cout << getMin(numbers) << " with Size of "<< std::size(numbers) << std::endl;

    std::cin.get();
}


Q: Google Maps API Solid State Borders When creating a map, the state borders keep coming up as dashed lines.  Is there any way to make them solid?  I am working with the province settings in the json but I cannot seem to find a directive for solid line, perhaps in .stroke?

A: If you can't do it with Styled Maps (and I don't see how you can right now), you could use Styled Maps to hide the state boundaries:
 {
    featureType: 'administrative.province',
    elementType: 'geometry.stroke',
    stylers: [{visibility: '#off'}]
  },

Then add your own (note that you need a source of the boundaries somewhat consistent with the map tiles).
Example of using borders from a FusionTable
proof of concept fiddle
proof of concept fiddle with styled borders

code snippet:

function initMap() {
  // Styles a map in night mode.
  var map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: 40.674,
      lng: -73.945
    },
    zoom: 7,
    styles: [{
      featureType: 'administrative.province',
      elementType: 'geometry.stroke',
      stylers: [{
        visibility: '#off'
      }]
    }, ]
  });
  var layer = new google.maps.FusionTablesLayer({
    query: {
      select: 'kml_4326',
      from: '19lLpgsKdJRHL2O4fNmJ406ri9JtpIIk8a-AchA'
    },
    map: map
  });
}
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
}


Q: jquery form plugin does not work I am a newbie programmer. I have been stuck for two days with a simple coding problem.I try to use jquery form plugin for submitting a form to another page and get feedback from that page.The problem is the plugin is not working, the form is submitted normally without feedback. Here is the code:

<form  action='ajaxcall.php' id='upload_pic' enctype='multipart/form-data'  method='post'>
<input type='file' id='pic' name='picture'>
<input type='submit' id='sub'>
</form>

var options=
{
  target:'#preview',
  url:'ajaxcall.php'
};

$(document).ready(function(){
    $("#sub").click(function(){
        $('#preview').html("");
        $('#upload_pic').ajaxForm(options).submit();
    });
});

Here is my ajaxcall.php page code
if(!empty($_FILES['picture']['size']))
{
 echo "";
}

Expectation was the echoed image would feedback but the page is simply redirected to ajaxcall.php page.I understand that ajaxForm() function is not working. The same question I am asking two times in SO, but still no satisfactory solution. But why? Please help.Thanks in advance.

A: Use adeneo's answer, because I also do not see why you would use this plugin, but here could be a few reasons why what you have isn't working:
In the examples from the plugin's website, you should

*

*bind to the form, not the button

*use the beforeSubmit option

*Remove the submit() from the end of your call, not sure why it is
there

*Watch console for any errors

var options=
{
  target:'#preview',
  url:'ajaxcall.php',
  beforeSubmit:  showLoading,
  error: function(e){
      alert("Error: " + e);
  }
};

function showLoading(){
    $('#preview').html("");
}

$(document).ready(function(){
    $("#upload_pic").ajaxForm(options);
});


Q: FileDialog does not work in some excel versions VBA I have a code that works in the excel version 2010 normally, but in the 2013 version does not. Take a look.
Sub select_strategy()
'Subroutine that lets the user select a strategy table
'
    'Declare local variables
    Dim strategyFileDialog As Office.FileDialog
    'Declare local variables
    Dim intStrategySelection As Integer

    'Initialize global variables
    Call initialize_global_variables

    ' Allows the user to select the strategy table to use
    Set strategyFileDialog = Application.FileDialog(msoFileDialogFilePicker)

    With strategyFileDialog
        .Title = "Select Strategy Table"
        .InitialFileName = ActiveWorkbook.Path
        .AllowMultiSelect = False
    End With

    intStrategySelection = strategyFileDialog.Show  'updates cell only if a file is selected
     If intStrategySelection <> 0 Then
        wsMain.Cells(2, 3) = strategyFileDialog.SelectedItems(1)
     Else
        wsMain.Cells(2, 3) = ""
     End If

End Sub

The error for the 2013 version is Compile error: Cant find project or library.
Any ideas how to solve it?

A: To use late binding use the FileDialog() function from the Excel.Application Object. Excel.Application.FileDialog() Is a function that returns a FileDialog Object for an open Workbook. If you declare a variable as a specific object such as Office.FileDialog it will create the object of the version that is used in the VBA reference the code was written with and at runtime on a different pc will ignore other version references and look for the specific version that the variable was declared with.
You can use the reference to the active workbook but is not explicitly needed in Excel
Dim strategyFileDialog As Object
Set strategyFileDialog = ActiveWorkbook.Application.FileDialog(3)

'Filedialog Enumerations:
'msoFileDialogFilePicker = 3 File picker dialog box.
'msoFileDialogFolderPicker = 4 Folder picker dialog box.
'msoFileDialogOpen = 1 Open dialog box.
'msoFileDialogSaveAs = 2 Save As dialog box


Q: GoCD - Task Plugins not adding tasks I have setup a GoCD server and agent (on a Windows machine if that matters). I am using it to build a .NET application. I have installed a few Task plugins (Powershell, Xunit-converter) and when I restart the server I see those as loaded and installed without issue in the plugin admin screen.
However, when I go to create or edit a job, I do not see these new tasks in the "Add Task" dropdown.  I can get around the powershell one by using a Custom command, but I need to be able to convert my MsTest ouptut to Xunit so that it can display the results in the Test Results Tab.


Q: Unable to get the value in the shell variable     #!/bin/ksh
    for i in 1 2 3 4 5
    do
        echo "hello world"> $i
    done
    v = echo $?
    if [ $v -eq 0 ]; then
     echo " Completed"
    else
     echo "Not completed"
    fi

Unable to get the value in v = echo s?, due to this if condition always fails

A: Wrong logic use just this (direct assignation):
v=$?

A: Instead of v = echo $?
Either write
v=`echo $?`

OR
v=$?


Q: Xcode 9.2 - Can't see "iOS Simulator" within run destination I'm trying to run my application with a Xcode simulator but I can't select any simulator since my only options are the one showed in this screenshot
As per apple guide, I should see the section "iOS Simulator" below "Build Only Device", but within my Xcode that section is missing.
What I've already tried to solve the issue:

*

*Set iOS Deployment Target under Project > Info > Deployment Target and restart Xcode.

*Check if there are simulators installed within Xcode>Preferences>Components. There are Simulator 11.0 and 11.1

*Check if there are simulator within Window > Device and Simulator > Simulators. There are around 30 simulators.

*Restart Xcode

*Reinstall Xcode

I am using Xcode 9.2 and macOS version 10.12.6.
Does anyone knows what could be the problem?


Q: Start and Stop indicatorView and put it in centre tableView in swift I am using a spinner in bottom of tableView to show the spinner when data is reloading.
var sneakers: [sneakerModel] = []

I stored all my data in sneakers and returning the count on numberOfRowsInSection method.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.sneakers.count
}

And now I am using willDisplay method to show the spinner in bottom.
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

let lastSectionIndex = tableView.numberOfSections - 1
let lastRowIndex = tableView.numberOfRows(inSection: lastSectionIndex) - 1

if indexPath.row == self.sneakers.count - 1 && !didPageEnd {
    pageNo += 1
    getSneakerSearch()
 }

    if (indexPath.row == self.sneakers.count) {
       self.tableView.tableFooterView?.isHidden = true
    } else {

    if indexPath.section ==  lastSectionIndex && indexPath.row == lastRowIndex {
     let spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)
     spinner.activityIndicatorViewStyle = .whiteLarge
     spinner.color = .red
     spinner.startAnimating()
     spinner.frame = CGRect(x: CGFloat(0), y: CGFloat(5), width: tableView.bounds.width, height: CGFloat(44))

     self.tableView.tableFooterView = spinner
     self.tableView.tableFooterView?.isHidden = false
        }

    }

}

But it is not working. How can I stop spinner when no more data is loading. Please help?
Getting the data from api.
func getSneakerSearch() {

   let param: [String:Any] = [ "search_term" :  searchText ?? "","page": pageNo, "token": commonClass.sharedInstance.userToken ?? ""]

    if self.pageNo == 0{
        commonClass.sharedInstance.startLoading()
    }
    Alamofire.request(Constants.API.url("search"), method: .post, parameters: param, encoding: URLEncoding.httpBody, headers: nil).responseJSON {
        (response:DataResponse<Any>) in

        commonClass.sharedInstance.stopLoading()

        guard let json = response.result.value as? [String:Any] else {return}
        printD(json)

        guard let status = json["status"] as? Int else {return}
        printD(status)

        if status == 1 {

            guard let data = json["data"] as? [[String:Any]] else { return}
            printD(data)
            if self.pageNo == 0 {
                self.sneakers.removeAll()
            }
            for item in data {
                guard let description =  item["description"] as? String else { return}
                printD(description)
                self.sneakers.append(sneakerModel(response: item))
            }
            self.didPageEnd = data.count < limitPerPage

        }
        DispatchQueue.main.async {
            self.reloadData()
        }
    }
}

A: Create loadingview in viewdidload
override func viewDidLoad() {
    super.viewDidLoad()
    let spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)
    spinner.activityIndicatorViewStyle = .whiteLarge
    spinner.color = .red
    spinner.startAnimating()
    spinner.frame = CGRect(x: CGFloat(0), y: CGFloat(5), width: tableView.bounds.width, height: CGFloat(44))

    self.tableView.tableFooterView = spinner
    self.tableView.tableFooterView?.isHidden = true
}

and update willDisplay cell
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

    let lastSectionIndex = tableView.numberOfSections - 1
    let lastRowIndex = tableView.numberOfRows(inSection: lastSectionIndex) - 1

    if indexPath.row == self.sneakers.count - 1 && !didPageEnd {
        pageNo += 1
        getSneakerSearch()
    }
}

Update getSnackerSearch func:
...
    if self.pageNo == 0{
        commonClass.sharedInstance.startLoading()
    }else{
        self.tableView.tableFooterView?.isHidden = false
    }
    Alamofire.request(Constants.API.url("search"), method: .post, parameters: param, encoding: URLEncoding.httpBody, headers: nil).responseJSON {
        (response:DataResponse<Any>) in

        if self.pageNo == 0{
            commonClass.sharedInstance.stopLoading()
        }else{
            self.tableView.tableFooterView?.isHidden = true
        }

    }
   ...

A: For center of you spinner to tableview you can follow these steps to do it. You don't need to provide height and width for spinner.
    let spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)
    spinner.activityIndicatorViewStyle = .whiteLarge
    spinner.color = .red
    spinner.startAnimating()

    let topBarHeight = UIApplication.shared.statusBarFrame.size.height +
        (self.navigationController?.navigationBar.frame.height ?? 0.0)

    spinner.center=CGPointMake(self.tableView.center.x, self.tableView.center.y- topBarHeight);


Q: Incoming IP addresses for webhooks? What IP Address range do your webhooks come from? We need to white list them to receive your Copyleaks results to our web server.
Thank You,

A: As of now, Copyleaks API not arriving from fixed list of IP addresses. But, you have other alternatives to securing your endpoints. The options described here:
https://api.copyleaks.com/documentation/v3/webhooks/security
Another option you have to secure your endpoints is to add "Authentication" header to the webhook request with a private secret in its value. With Copyleaks API you have the ability to specify the headers that will arrive to your endpoints.


Q: PHP - Refactoring / improving Ifs I have the following data structure;
Array ( [0] => Array ([suit] => c [rank] => A )
        [1] => Array ( [suit] => d [rank] => A ) )

I want to test if these cards are certain values and display an appropriate message;
if (
    (($hand[0]['rank'] == "A") && ($hand[1]['rank'] == "A"))
 || (($hand[0]['rank'] == "K") && ($hand[1]['rank'] == "K"))
 || (($hand[0]['rank'] == "Q") && ($hand[1]['rank'] == "Q"))
 || (($hand[0]['rank'] == "A") && ($hand[1]['rank'] == "K"))
 || (($hand[0]['rank'] == "K") && ($hand[1]['rank'] == "A"))
   ) {
    echo "Action: Raise pre-flop. Re-raise if already raised.
\n";
}

 if (
       (($hand[0]['rank'] == "7") && ($hand[1]['rank'] == "7"))
    || (($hand[0]['rank'] == "A") && ($hand[1]['rank'] == "J") && ($hand[0]['suit'] == $hand[1]['suit']))
    || (($hand[0]['rank'] == "J") && ($hand[1]['rank'] == "Q") && ($hand[0]['suit'] == $hand[1]['suit']))
    || (($hand[0]['rank'] == "10") && ($hand[1]['rank'] == "J") && ($hand[0]['suit'] == $hand[1]['suit']))
       ) {
        echo "Action: Worth a call pre-flop (provided no-one has raised).
\n";
    }

I have simplified the IFs by removing some of the conditions.
Can anyone suggest a better way of doing this?

A: Maybe try to use in_array() method
php.net in_array()

A: Try to use references like this:
$rank0 =& $hand[0]['rank'];
$rank1 =& $hand[1]['rank'];

if (
($rank0 == "A" && $rank1 == "A")
|| (...)

Just, as the first step to code minimization


Q: UserDefine Runtime Attributes doesn't work in Xcode8.0 It seems like xcode8.0 does not set the value of user runtime attributes when set from storyboard.What am trying to do is simple,set the label inside a cell as corneRadius of 10 which has width/height of 20. When i try to debug the views i got the following output which has weird width height(1000/1000..?)

_UILabelLayer:0x600000283750; position = CGPoint (500 500); bounds = CGRect (0 0; 1000 1000); delegate = >; opaque = YES; allowsGroupOpacity = YES; cornerRadius = 10; contentsMultiplyColor = (null); rasterizationScale = 2; contentsScale = 2>

A: i think it's helpful for you.

and also check the clipToBounds

Checking "Clip Subviews" is equal to the code addMessageLabel.clipsToBounds = YES;

A: You can use this code and method on your controller
 override func viewDidLayoutSubviews() {
            super.viewDidLayoutSubviews()
            yourLabel.clipsToBounds = true
            yourLabel.layoutIfNeeded()
            print("Frame ------> ",yourLabel.frame)
     }


Q: rails "where" statement: How do i ignore blank params I am pretty new to Rails and I have a feeling I'm approaching this from the wrong angle but here it goes... I have a list page that displays vehicles and i am trying to add filter functionality where the user can filter the results by vehicle_size, manufacturer and/or payment_options.
Using three select form fields the user can set the values of :vehicle_size, :manufacturer and/or :payment_options parameters and submit these values to the controller where i'm using a
@vehicles = Vehicle.order("vehicles.id ASC").where(:visible => true, :vehicle_size => params[:vehicle_size] )

kind of query. this works fine for individual params (the above returns results for the correct vehicle size) but I want to be able to pass in all 3 params without getting no results if one of the parameters is left blank..
Is there a way of doing this without going through the process of writing if statements that define different where statements depending on what params are set? This could become very tedious if I add more filter options.. perhaps some sort of inline if has_key solution to the effect of:
@vehicles = Vehicle.order("vehicles.id ASC").where(:visible => true, if(params.has_key?(:vehicle_size):vehicle_size => params[:vehicle_size], end if(params.has_key?(:manufacturer):manufacturer => params[:manufacturer] end )

A: You can do:
@vehicles = Vehicle.order('vehicles.id ASC')
if params[:vehicle_size].present?
  @vehicles = @vehicles.where(vehicle_size: params[:vehicle_size])
end

Or, you can create scope in your model:
scope :vehicle_size, ->(vehicle_size) { where(vehicle_size: vehicle_size) if vehicle_size.present? }

Or, according to this answer, you can create class method:
def self.vehicle_size(vehicle_size)
  if vehicle_size.present?
    where(vehicle_size: vehicle_size)
  else
    scoped # `all` if you use Rails 4
  end
end

You call both scope and class method in your controller with, for example:
@vehicles = Vehicle.order('vehicles.id ASC').vehicle_size(params[:vehicle_size])

You can do same thing with remaining parameters respectively.

A: The has_scope gem applies scope methods to your search queries, and by default it ignores when parameters are empty, it might be worth checking


Q: XText - get content (compiled value) of XExpression I have a certain part of my XText grammer that defines a block for classes that shall print all its expressions. The XText grammar part for this looks as follows:
Print:
    {Print}
    'print' '{'
        print += PrintLine*
    '}';
PrintLine:
    obj += XExpression;

Now I use the following inferrer code to create a print() method:
Print: {
    members += feature.toMethod('print', typeRef(void)) [
    body = '''
        «FOR printline : feature.print»
            System.out.println(«printline.obj»);
        «ENDFOR»
        '''
    ]
}

Ok, I go ahead and test it with the following code in a class:
print {
    "hallo"
    4
    6 + 7
}

And the result is the following:
public void print() {
   System.out.println([org.eclipse.xtext.xbase.impl.XStringLiteralImpl@20196ba8 (value: hallo)]);
   System.out.println([org.eclipse.xtext.xbase.impl.XNumberLiteralImpl@7d0b0f7d (value: 4)]);
   System.out.println([<XNumberLiteralImpl> + <XNumberLiteralImpl>]);}

Of course, I was hoping for:
public void print() {
   System.out.println("hallo");
   System.out.println(4);
   System.out.println(6+7);
}

I understand that I might have to call the compiler somehow in the inferrer for «printline.obj», but I am really not sure how.

A: i think you are doing this on a wrong basis. this sounds to me like an extension of xbase, not only a simple use.
import "http://www.eclipse.org/xtext/xbase/Xbase" as xbase

Print:
    {Print}
    'print'
        print=XPrintBlock
    ;

XPrintBlock returns xbase::XBlockExpression:
    {xbase::XBlockExpression}'{'
        expressions+=XPrintLine*
    '}'
;

XPrintLine returns xbase::XExpression:
    {PrintLine} obj=XExpression

;

Type Computer
class MyDslTypeComputer extends XbaseTypeComputer {

     def dispatch computeTypes(XPrintLine literal, ITypeComputationState state) {
        state.withNonVoidExpectation.computeTypes(literal.obj)
        state.acceptActualType(getPrimitiveVoid(state))
    }

}

Compiler
class MyDslXbaseCompiler extends XbaseCompiler {

    override protected doInternalToJavaStatement(XExpression obj, ITreeAppendable appendable, boolean isReferenced) {
        if (obj instanceof XPrintLine) {
            appendable.trace(obj)
            appendable.append("System.out.println(")
            internalToJavaExpression(obj.obj,appendable);
            appendable.append(");")
            appendable.newLine
            return
        }

        super.doInternalToJavaStatement(obj, appendable, isReferenced)
    }

}

XExpressionHelper
class MyDslXExpressionHelper extends XExpressionHelper {

    override hasSideEffects(XExpression expr) {
        if (expr instanceof XPrintLine || expr.eContainer instanceof XPrintLine) {
            return true
        }
        super.hasSideEffects(expr)
    }

}

JvmModelInferrer
def dispatch void infer(Print print, IJvmDeclaredTypeAcceptor acceptor, boolean isPreIndexingPhase) {
    acceptor.accept(
        print.toClass("a.b.C") [
            members+=print.toMethod("demo", Void.TYPE.typeRef) [
                body = print.print
            ]
        ]

    )
}

Bindings
class MyDslRuntimeModule extends AbstractMyDslRuntimeModule {

    def Class<? extends ITypeComputer> bindITypeComputer() {
        MyDslTypeComputer
    }

    def Class<? extends XbaseCompiler> bindXbaseCompiler() {
        MyDslXbaseCompiler
    }

    def Class<? extends XExpressionHelper> bindXExpressionHelper() {
        MyDslXExpressionHelper
    }
}


Q: No cached version of androidx.databinding:databinding-compiler:3.4.2 available for offline mode Could not determine the dependencies of task :app:compileDebugJavaWithJavac.
> Could not resolve all task dependencies for configuration ':app:debugAnnotationProcessorClasspath'.
   > Could not resolve androidx.databinding:databinding-compiler:3.4.2.
     Required by:
         project :app
      > No cached version of androidx.databinding:databinding-compiler:3.4.2 available for offline mode.
      > No cached version of androidx.databinding:databinding-compiler:3.4.2 available for offline mode.
      > No cached version of androidx.databinding:databinding-compiler:3.4.2 available for offline mode.

A: Uncheck "Offline work" in Android Studio:

File -> Settings -> Gradle -> Global Gradle Settings

or in OSX:

Preferences -> Gradle -> Global Gradle Setting


Q: UNMET PEER DEPENDENCY ISSUE I have been trying to install the ngx bootstrap from [https://ng-bootstrap.github.io/#/getting-started]
by entering the command: npm install ngx-bootstrap --save
but the result is this:
+-- UNMET PEER DEPENDENCY @angular/common@2.4.10
+-- UNMET PEER DEPENDENCY @angular/compiler@2.4.10
+-- UNMET PEER DEPENDENCY @angular/core@2.4.10
+-- UNMET PEER DEPENDENCY @angular/forms@2.4.10
+-- UNMET PEER DEPENDENCY jquery@1.9.1 - 3
+-- ngx-bootstrap@2.0.0-beta.9
+-- UNMET PEER DEPENDENCY popper.js@^1.12.3
`-- UNMET PEER DEPENDENCY typescript@2.0.10

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\chokidar\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN @ng-bootstrap/ng-bootstrap@1.0.0-beta.5 requires a peer of @angular/core@^4.0.3 but none was installed.
npm WARN @ng-bootstrap/ng-bootstrap@1.0.0-beta.5 requires a peer of @angular/common@^4.0.3 but none was installed.
npm WARN @ng-bootstrap/ng-bootstrap@1.0.0-beta.5 requires a peer of @angular/forms@^4.0.3 but none was installed.
npm WARN bootstrap@4.0.0-beta.2 requires a peer of jquery@1.9.1 - 3 but none was installed.
npm WARN bootstrap@4.0.0-beta.2 requires a peer of popper.js@^1.12.3 but none was installed.
npm WARN ngx-bootstrap@2.0.0-beta.9 requires a peer of @angular/common@>=4.3.0 || >5.0.0 but none was installed.
npm WARN ngx-bootstrap@2.0.0-beta.9 requires a peer of @angular/compiler@>=4.3.0 || >5.0.0 but none was installed.
npm WARN ngx-bootstrap@2.0.0-beta.9 requires a peer of @angular/core@>=4.3.0 || >5.0.0 but none was installed.
npm WARN ngx-bootstrap@2.0.0-beta.9 requires a peer of @angular/forms@>=4.3.0 || >5.0.0 but none was installed.
npm WARN ngx-bootstrap@2.0.0-beta.9 requires a peer of typescript@>=2.3.0 but none was installed.

I do not understand what's happening.
I am fairly new to Angular 2 and the relevant technologies. Would appreciate your help ! Thank you.

A: hello you need to install your perDependencies, if you install a package that depends on specific versions of other packages, If it didn't find the correct  version of package then "Peer dependency" is unmet, try this:
npm install -g npm-install-peers

npm-install-peers

this will install peerDependencies


Q: Wraping text within a table's td I am working on trying to clean up a customers evaluation software. In this example, the text doesn't wrap within the box. Adding a fixed size to the table doesn't help, as the information called from the SQL database just places it on top with no warping.

                ![enter image description here][1]

' . base64_decode($eval['note']) . '

What steps should I look at doing or code should I add to fix this formatting error? Attached is a screen shot of the UI.
Thank you,
Paul

A: You are inserting your data inside a
 block, effectively telling the browser not to wrap the text. I assume you do this so that literal newlines in the 'note' data are indeed printed.
To alter wrapping space-characters and newline functionality of an element, you can use the CSS white-space property. So, to get what you want (both wrapping AND literal newlines), you can set white-space to either pre-line or pre-wrap, depending on your need. Eg. change the
 to
...
' . base64_decode($eval['note']) . '
...

See the reference for more details
Good luck,
bob


Q: Android JSON Get via HttpURLConnection error 405 so I'm trying to do a GET Request to my web service, and since I saw that the HttpGet class is being deprecated, I try to use the HttpURLConnection class instead, and I used it successfully with a 'POST' method... however when I try to do a simple 'GET' request - I get a 405 error (bad method).
I tested the link in DHC, and the link is fine.
Here's my method:
    public JSONObject getClientByDeviceId (String link) {
    try {
        URL url = new URL(link);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    //            conn.setRequestMethod("GET");
    //            conn.setDoOutput(true);
    //            conn.setDoInput(true);
    //            conn.setUseCaches(false);
    //            conn.setAllowUserInteraction(false);
    //            conn.setRequestProperty("Content-Type", "application/json");

        OutputStream outputStream = conn.getOutputStream();
        outputStream.close();

        if (conn.getResponseCode() != 200) {
            Log.e("conn", "Error code: " + conn.getResponseCode());
            BufferedReader br = new BufferedReader(new  InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;

            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            br.close();
            conn.disconnect();

            JSONObject returnedObject = new JSONObject(sb.toString());

            if (returnedObject != null) {
                Log.e("conn", "If 400, this is the object gained: " +     returnedObject.getString("Message"));
            } else {
                Log.e("conn", "didn't get any JSON object");
            }

            conn.disconnect();
            return returnedObject;

        }
        else {
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            Log.e("conn", "GREAT SUCCESS !!: " + conn.getResponseCode());
            StringBuilder sb = new StringBuilder();

            String line;

            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            br.close();
            conn.disconnect();

            JSONObject returnedObject = new JSONObject(sb.toString());

            return returnedObject;
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

Normally I would say that this problem is caused by trying to do a 'GET' request in a 'POST' URL. But without the two HttpGet and HttpPost classes I don't really know where to turn, all the properties that are commented out are like that because I tried them in the POST request and now I deleted one by one to try to get the method to work.
Any ideas ? or reference to an updated guide on how to properly use that HttpURLConnection class, since I couldn't find one.
Thanks in advance !

A: Solved it, apparently this code needed to be removed:
OutputStream outputStream = conn.getOutputStream();
    outputStream.close();

I guess it was because I gave a GET URL and put that outputStream in my code and that caused the issues.
I still however don't understand why I got the "405: method GET not allowed" whereas I think I should have gotten the opposite: "POST" not allowed...
Anyway that is my solution, thanks a lot for your help guys !

A: HTTP 405 is caused by bad method call (Method not Allowed). That means you called GET method on POST request or vice-versa. You should add handling for you GET method on your Web-Service to get it working.

A: For anyone still reaching here from a search engine, my solution was similar -
I removed the line "conn.setDoOutput(true);" (or set it to false)


Q: Angular 2 : How to keep two methods from repeating How can I implement my if/else statement only once so that I don't repeat this fragment of code in my header component as shown below:
export class HeaderMainComponent {
logoAlt = 'We Craft beautiful websites'; // Logo alt and title texts

@ViewChild('navTrigger') navTrigger: ElementRef;

isMenuShown: false;

constructor(private layoutService: LayoutService, private renderer: Renderer) { }

menuToggle(event: any) {
    if (this.navTrigger.nativeElement.classList.contains('opened')) {
        this.navTrigger.nativeElement.classList.remove('opened');
    } else {
        this.navTrigger.nativeElement.classList.add('opened');
    }
}

onMenuSelect(event: any) {
    this.isMenuShown = false;

    if (this.navTrigger.nativeElement.classList.contains('opened')) {
        this.navTrigger.nativeElement.classList.remove('opened');
    } else {
        this.navTrigger.nativeElement.classList.add('opened');
    }
}

}

A: souldn't you just do this?
export class HeaderMainComponent {
logoAlt = 'We Craft beautiful websites'; // Logo alt and title texts

@ViewChild('navTrigger') navTrigger: ElementRef;

isMenuShown: false;

constructor(private layoutService: LayoutService, private renderer: Renderer) { }

menuToggle(event: any) {
    if (this.navTrigger.nativeElement.classList.contains('opened')) {
        this.navTrigger.nativeElement.classList.remove('opened');
    } else {
        this.navTrigger.nativeElement.classList.add('opened');
    }
}

onMenuSelect(event: any) {
    this.isMenuShown = false;

    this.menuToggle(event); // Must apply the event binding as well
}

}


Q: Viewing Equirectangular Map I'm writing an equirectangular map viewer, all the stuff I have found so far are about the projection, conversions and inverse ones, which is the easiest part.
I don't want to use OpenGL or DirectX sphere texture solutions, I want to draw the image pixel by pixel. The only problem I have is in transformation of the viewer's camera rectangle.
I mean, I have a rectangle through which the viewer shows the equivalent pixels on the map. When viewer looks up or down, or left or right, this view changes, but the changes are not linear, even in a spherical coordination system. As the rectangle's dimensions should kept constant in a Cartesian sense, otherwise we will have a deformation.
Can anyone tell me how to solve this problem? A link to a good document, or a hint to where I start is all that I need. Thanks in advance.

A: Ok, nobody answered it, and I figured it out. There are two "practical" solutions, first one is using the Quaternions. You can define a 3d rectangle as a view and then rotate it using quaternions. After that you can sweep on the resulting rectangle, and use the reverse transforms to get the map coordinates. The other solution, which seems faster to me, is using Euler's rotation matrices. Just pay attention to use ArcTan2 instead of ArcTan function, because you need 2*PI coverage. That's all I wanted!


Q: jQueryUI add click function for multiple buttons I have a page with some number of info dialog boxes (5 in this example).  The objective is to have a variable number of info boxes on a page each called by a unique button.  When the button is clicked, any other box is closed and the current box appears. Instead of trying to keep track of which box was opened or about to open, I thought I'd simply close all the boxes and open the current info box.
The code below works: the first for loop initializes all of the dialog boxes and the closeBoxes() function closes any dialog that's open before opening the assigned dialog box.  However it seems like I should be able to loop through the .click(function()..) and add any number of info boxes.  I've tried $("#btn"+i)...("#info"+i) in a loop, but that simply doesn't work.
var TotalInfoBoxes=5;
for ( var i=1; i<=TotalInfoBoxes; i++) {
    $("#info"+i).dialog({ autoOpen: false });
}

$("#btn1").click(function() { closeBoxes(); $("#info1").dialog( "open" ); });
$("#btn2").click(function() { closeBoxes(); $("#info2").dialog( "open" ); });
$("#btn3").click(function() { closeBoxes(); $("#info3").dialog( "open" ); });
$("#btn4").click(function() { closeBoxes(); $("#info4").dialog( "open" ); });
$("#btn5").click(function() { closeBoxes(); $("#info5").dialog( "open" ); });

function closeBoxes() {
    for (var i=1; i<=TotalInfoBoxes; i++){
        $("#info"+i).dialog("close");
    }
}

The dialog box is an elegant solution, but I need some more generic code as I may have 20 or 30 info boxes on a given page.  Greatly appreciate your input.

A: for close dialog box simple use by this all dialog box close
they all inherit the same class, this is the best way to select all and close by:
$(".ui-dialog-content").dialog("close");

A: make sure that the buttons and dialogs have a common class say btn for buttons &  info for your dialogs
$(".btn").on('click',function(e){
     closeBoxes();
     var index=$(this).index();
     $(".info:eq("+index+")").dialog("open");
});


Q: How to cleanly stub out REST client when in test environment I have a basic model like the following
class MyModel
    def initialize(attrs)
        @attrs = attrs
        @rest_client = Some::REST::Client.new
    end

    def do_a_rest_call(some_str)
      @rest_client.create_thing(some_str)
    end
end

For testing purposes, I don't want @rest_client to make remote calls. Instead, in a test environment, I just want to make sure that @rest_client gets called with a specific some_str when it goes through certain branches of code.
In an ideal world, I'd have an assertion similar to:
expect(my_model_instance).to.receive(do_a_rest_call).with(some_str) where in the test I will pass some_str to make sure it's the right one.
What's the best way to do this using RSpec 3.8 and Rails 5.2.2?

A: A solution that should work without any additional gems:
let(:rest_client_double) { instance_double(Some::REST::Client, create_thing: response) }

it 'sends get request to the RestClient' do
  allow(Some::REST::Client).to receive(:new).and_return(rest_client_double)

  MyModel.new(attrs).do_a_rest_call(some_str)

  expect(rest_client_duble).to have_received(:create_thing).with(some_str).once
end

Basically, you are creating a double for REST client.
Then, you make sure that when calling Some::REST::Client.new the double will be used (instead of real REST client instance).
Finally, you call a method on your model and check if double received given message.


Q: Update databindings when a TextBox changes rather than loses focus I'm learning to develop for compact framework and I've come across an issue that's bugging me.
I've bound a couple of textboxes to some properties (firstname & lastname of a person class) and have a menuitem which just does a showmessage of the full name, and it works fairly well except that the properties only get updated once the textbox losses focus.  This means that if I change the firstname and press the show name menuitem, I get the old value of firstname.
Is there a way I can force an update of the databindings, or make it so that every time a character is changed in one of the textboxes the corresponding property is updated?

A: If you do this, you risk putting bad data into your data object, but here is how to do this:
In your MyTextBox.DataBinding.Add() method, use the this overload with OnPropertyChanged for the DataSourceUpdateMode param instead of the default OnValidate
I again say that this is one of those things that sounds really easy, but will likely cause issues in the long run as you are 'binding' to data that has never been validated.

A: Just call form's ValidateChildren() in the code on the button doing the save


Q: Fullscreen Frame Borders in Java LWJGL I want to make a game with Java and LWJGL. In many videogames you can see the black fields at the top and the bottom of the display, which is used to size the display in the resolution the game can work with.
I searched for this two days, but maybe I used wrong keywords.
So is there any possibility I can make this with LWJGL. Maybe a method I can use?


Q: Second date Picker should show dates after the date selected in first date picker I have two date pickers. In first I'm selecting a date, and I want second date picker to show the dates after that particular date. Previous dates should be disabled.

A: Use minimum date property of the date picker to disable the all date before the minimum date. The date picker would also allow you to define range as minimum and maximum date so that it can show the date from minimum to maximum date range and remaining all other date will be disabled in picker view.

A: swift 3
    datePickerEndDate.minimumDate = datePickerStartDate.date


Q: How can I apply MVVM and Commands in this specific WPF situation? I am having trouble with the MVVM pattern and Commands in my WPF app. The problem is not so much the MVVM pattern, but more the stuff that is going on on my GUI. I'll explain the situation:
My app can DoStuff to some files. I have a class with a function DoStuff(int limit). My user user interface has the following items:

*

*A Button DoStuffBtn to start parsing.

*A TextBox LimitTxt to fill in a limit.

*A CheckBox LimitChk to enabled or disable the limit.

When you would "uncheck" LimitChk, then LimitTxt.Text = "" and LimitTxt.IsEnabled = false. When you would "check" LimitChk, then LimitTxt.IsEnabled = false again, but the text remains empty until you fill something in.
I have read many tutorials on Commands in WPF and MVVM but I just can't seem to pour my case into that mold. The example I gave is actually just a small part of my UI, but I can't seem to do this nicely either.
I keep running into questions like:

*

*Do I need two Commands for LimitChk (enable and disable) or just one (toggle)?

*If I bind an int to LimitTxt, what happens if I make it empty and disable it?

*Is it a clean way to just use DoStuff(Int32.Parse(LimitTxt.Text)) when DoStuffBtn is pressed?

*If I use two commands on LimitChk, what happens with the CanExecute() function of ICommand that determines whether LimitChk is enabled?

So the main question is: How would the situation I described fit into a nice pattern using Commands in WPF?
Some links on WPF, Commands and MVVM i've looked at:

*

*http://www.devx.com/DevX/Article/37893/0/page/1

*http://msdn.microsoft.com/en-us/magazine/cc785480.aspx?pr=blog

*http://jmorrill.hjtcentral.com/Home/tabid/428/EntryId/432/MVVM-for-Tarded-Folks-Like-Me-or-MVVM-and-What-it-Means-to-Me.aspx

*http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

What I understand so far is that I have to keep as much as possible out of the UI. Even stuff like UI influencing the UI. I.e. unchecking LimitChk disables LimitText. Still, I think I should keep a difference between UI related information and actions and stuff that actually has to do with the actual work that has to be done.

A: I think you're getting confused... you don't need any commands here, you can just use bindings.

*

*Do I need two Commands for LimitChk (enable and disable) or just one (toggle)?

You need none. Just create a LimitEnabled property in your ViewModel, and bind the CheckBox to it (IsChecked="{Binding LimitEnabled}")

*

*If I bind an int to LimitTxt, what happens if I make it empty and disable it?

Disabling it has no effect. If you make the TextBox empty, the binding will fail because an empty string can't be converted to an int (at least not with the default converter)

*

*Is it a clean way to just use Parse(Int32.Parse(LimitTxt.Text)) when ParseBtn is pressed?

You don't need to. Just create a Limit property in your ViewModel, and bind the TextBox to it. You might want to add an ExceptionValidationRule to the Binding so that it highlights invalid input.
The button is not necessary, the parsing will be done automatically when the TextBox loses focus (if you use the default UpdateSourceTrigger). If you want to customize the way it's parsed, you can create a custom converter to use in the binding.

A: Just some high level thoughts, leaving out superfluous stuff like Color and alignment attributes, WrapPanels, etc.
Your ViewModel has a a couple properties:
public bool? LimitIsChecked { get; set; }
public bool LimitTextIsEnabled { get; set; }  //to be expanded, below
public ICommand ParseCommand { get; private set; } // to be expanded, below
public string LimitValue { get; set; } // further explanation, below

Your XAML has CheckBox and TextBox definitions something like:
<CheckBox Content="Limit Enabled" IsChecked="{Binding LimitIsChecked}" />
<TextBox Text="{Binding LimitValue}" IsEnabled="{Binding LimitIsEnabled}" />
<Button Content="Parse" Command="{Binding ParseCommand}" />

You'll want to initialize ParseCommand something like this:
this.ParseCommand = new DelegateCommand<object>(parseFile);

Now, let's fill in that LimitTextIsEnabled property too:
public bool LimitTextIsEnabled {
    // Explicit comparison because CheckBox.IsChecked is nullable.
    get { return this.LimitIsChecked == true; }
    private set { }
}

Your parseFile method would then pass the value of the LimitValue property to the logic doing the actual parsing.
I declared the LimitValue property as string here to avoid cluttering up the code with an explicit converter, or other validation code.  You could choose to handle that "LimitValue is a valid int" verification/conversion in several different ways.
Of course, I haven't implemented this in its entirety, but I wanted to outline a pattern where you are not using Commands to update the state of the other widgets.  Instead, bind those attributes to properties that are managed in your ViewModel.


Q: Angular component as the Mapbox control Does anybody know: can I use an angular component as the Mapbox custom control? I need to add a few buttons on the map, but I see I have to pass an HTML element.

A: I did this using https://stackoverflow.com/a/54561421/12302484. I've made the class that implements the IControl interface. Then returned the component from the onAdd method resolved by dynamic component service.
map.component.ts:
private configureControls(): void {
    this.map.dragRotate.disable();
    this.map.touchZoomRotate.disableRotation();
    this.map.addControl(new mapboxgl.NavigationControl({ showCompass: false }));
    this.map.addControl(new CustomMapControls(this.dynamicComponentService));
}

custom-map-controls.ts:
export class CustomMapControls {
    private _container: HTMLElement;
    private _switchColorButton: HTMLElement;

    private map: mapboxgl.Map;
    private dynamicComponentService: DynamicComponentService;

    constructor(dynamicComponentService: DynamicComponentService) {
        this.dynamicComponentService = dynamicComponentService;
        this._container = document.createElement('div');
        this._container.classList.add('mapboxgl-ctrl', 'mapboxgl-ctrl-group');
    }

    getDefaultPosition(): any {
        return undefined;
    }

    onAdd(map: mapboxgl.Map): HTMLElement {
        this.map = map;
        this._container.appendChild(this.dynamicComponentService.injectComponent(MapColorSwitcherComponent));
        return this._container;
    }

    onRemove(map: mapboxgl.Map): any {
    }
}

result:


Q: How to fix segfault caused by a realloc going out of bounds? Hello and TIA for your help. As I am new to to posting questions, I welcome any feedback on how this quesiton has been asked. I have researched much in SO without finding what I thought I was looking for.
I'm still working on it, and I'm not really good at C.
My purpose is extracting data from certain specific tags from a given XML and writing it to file. My issue arises because as I try to fill up the data struct I created for this purpose, at a certain point the realloc() function gives me a pointer to an address that's out of bounds.
If you look at this example
#include <stdio.h>

int main() {
    char **arrayString = NULL;
    char *testString;
    testString = malloc(sizeof("1234567890123456789012345678901234567890123456789"));
    strcpy(testString, "1234567890123456789012345678901234567890123456789");
    int numElem = 0;
    while (numElem < 50) {
        numElem++;
        arrayString = realloc(arrayString, numElem * sizeof(char**));
        arrayString[numElem-1] = malloc(strlen(testString)+1);
        strcpy(arrayString[numElem-1], testString);
    }
    printf("done\n");
    return 0;
}

it does a similar, but simplified thing to my code. Basically tries to fill up the char** with c strings but it goes to segfault. (Yes I understand I am using strcpy and not its safer alternatives, but as far as I understand it copies until the '\0', which is automatically included when you write a string between "", and that's all I need)
I'll explain more in dephth below.
In this code i make use of the libxml2, but you don't need to know it to help me.
I have a custom struct declared this way:
 struct List {
    char key[24][15];
    char **value[15];
    int size[15];
 };

struct List *list; //i've tried to make this static after reading that it could make a difference but to no avail

Which is filled up with the necessary key values. list->size[] is initialized with zeros, to keep track of how many values i've inserted in value.
value is delcared this way because for each key, i need an array of char* to store each and every value associated with it. (I thought this through, but it could be a wrong approach and am welcome to suggestions - but that's not the purpose of the question)
I loop through the xml file, and for each node I do a strcmp between the name of the node and each of my keys. When there is a match, the index of that key is used as an index in the value matrix. I then try to extend the allocated memory for the c string matrix and then afterwards for the single char*.
The "broken" code, follows, where

*

*read is the index of the key abovementioned.

*reader is the xmlNode

*string contained the name of the xmlNode but is then freed so consider it as if its a new char*

*list is the above declared struct

if (xmlTextReaderNodeType(reader) == 3 && read >= 0)
    {
        /* pull out the node value */
        xmlChar *value;
        value = xmlTextReaderValue(reader);
        if (value != NULL) {
            free(string);
            string=strdup(value);
            /*increment array size */
            list->size[read]++;
            /* allocate char** */ list->value[read]=realloc(list->value[read],list->size[read] * sizeof(char**));
            if (list->value[read] == NULL)
                return 16;
            /*allocate string (char*) memory */
            list->value[read][list->size[read]-1] = realloc(list->value[read][list->size[read]-1], sizeof(char*)*sizeof(string));
            if (list->value[read][list->size[read]-1] == NULL)
                return 16;
            /*write string in list */
            strcpy(list->value[read][list->size[read]-1], string);
        }
        /*free memory*/
        xmlFree(value);
    }
    xmlFree(name);
    free(string);

I'd expect this to allocate the char**, and then the char*, but after a few iteration of this code (which is a function wrapped in a while loop) i get a segfault.
Analyzing this with gdb (not an expert with it, just learned it on the fly)  I noticed that indeed the code seems to work as expected for 15 iteration. At the 16th iteration, the list->value[read][list->size[read]-1] after the size is incremented, list->value[read][list->size[read]-1] points to a 0x51, marked as address out of bounds. The realloc only brings it to a 0x3730006c6d782e31, still marked as out of bounds. I would expect it to point at the last allocated value.
Here is an image of that: https://imgur.com/a/FAHoidp
How can I properly allocate the needed memory without going out of bounds?

A: Your code has quite a few problems:

*

*You are not including all the appropriate headers. How did you get this to compile? If you are using malloc and realloc, you need to #include <stdlib.h>. If you are using strlen and strcpy, you need to #include <string.h>.

*Not really a mistake, but unless you are applying sizeof to a type itself you don't have to use enclosing brackets.

*Stop using sizeof str to get the length of a string. The correct and safe approach is strlen(str)+1. If you apply sizeof to a pointer someday you will run into trouble.

*Don't use sizeof(type) as argument to malloc, calloc or realloc. Instead, use sizeof *ptr. This will avoid your incorrect numElem * sizeof(char**) and instead replace it with numElem * sizeof *arrayString, which correctly translates to numElem * sizeof(char*). This time, though, you were saved by the pure coincidence that sizeof(char**) == sizeof(char*), at least on GCC.

*If you are dynamically allocating memory, you must also deallocate it manually when you no longer need it. Use free for this purpose: free(testString);, free(arrayString);.

*Not really a mistake, but if you want to cycle through elements, use a for loop, not a while loop. This way your intention is known by every reader.

This code compiles fine on GCC:
#include <stdio.h> //NULL, printf
#include <stdlib.h> //malloc, realloc, free
#include <string.h> //strlen, strcpy

int main()
{
    char** arrayString = NULL;
    char* testString;
    testString = malloc(strlen("1234567890123456789012345678901234567890123456789") + 1);
    strcpy(testString, "1234567890123456789012345678901234567890123456789");
    for (int numElem = 1; numElem < 50; numElem++)
    {
        arrayString = realloc(arrayString, numElem * sizeof *arrayString);
        arrayString[numElem - 1] = malloc(strlen(testString) + 1);
        strcpy(arrayString[numElem - 1], testString);
    }
    free(arrayString);
    free(testString);
    printf("done\n");
    return 0;
}


Q: Displaying images and their accompanying information from a database with codeigniter Ok so im uploading images to a folder on my server, and then trying to re-display them with their information.
This is the function in my model that i am using to pull the info:
    public function pull_all(){

    $this->db->select('file_name, file_type, full_path, image_type');
    $query = $this->db->get('img');
    $dbInfo = $query->result_array();
    return $dbInfo;

}

The controller implements the function like so:
function show_all(){

    $this->load->model('image_work');
    $data = array('dbInfo' => $this->image_work->pull_all());

    $data['title'] = "Uploads";
    $this->load->view('templates/header', $data);
    $this->load->view('show_all',$data);
    $this->load->view('templates/footer', $data);
}

The problem iv been having is in the view. I want each image to be shown with its info in  this format:

$image_name

$image_type

$image_size

$image_dimensions

Iv tried many different ways to do it for example nested foreach statements, but I just cant seem to get it right. Any help would be appreciated.
thanks

A: You can do like this:
<?php foreach($dbInfo as $image): ?>

        <img src="<?php echo $image['full_path']; ?>"/>

<?php echo $image['image_name']; ?>

<?php echo $image['image_type']; ?>

<?php echo $image['image_size']; ?>

<?php echo $image['image_dimensions']; ?>

<?php endforeach; ?>