text:
Q: How to initialize a pointer to a dynamic 2D Array in C++ I was giving a adventurer class containing a bunch of functions and member variables.
One of them is:
string*** items;

so first I thought it was a 3d array that I have to make but I was told that it suppose to be a pointer to a 2d array.
What I tried to do was make a temp array
string** temp;

Init that and fill it, I then point my items to temp
items = &temp;

This works till the function exits. Then we I try and call a index value inside items
cout<<*item[0][0];

there is nothing. When temp disappears so does the array.
This line also doenst work
(*items) = new string*[2];

I couldn't find anything online  that helped me.
How can I initialize items or keep the array data that i made using temp.
For those asking for the code, this is what they gave me:
class Adventurer{
private:
    string*** items;
    string name;
    double maxCarryWeight;
    double currentCarryWeight;
    int currentNumberOfItems;
    int maxNumberOfItems;
    double health;
    static int numberOfAdventurers;

public:
    Adventurer(); //default constructor
    Adventurer(const Adventurer& a);  //copy constructor
    ~Adventurer();
    bool pickUpItem(string it, double weight);
    bool dropItem(string it);
    bool dropItem(int index);
    void setName(string n);
    string getName() const;
    void setMaxCarryWeight(double w);
    double getMaxCarryWeight() const;
    void setCurrentCarryWeight(double w);
    double getCurrentCarryWeight() const;
    void setMaxNumberOfItems(int n);
    int getMaxNumberOfItems() const;
    void setCurrentNumberOfItems(int n);
    int getCurrentNumberOfItems() const;
    int getNumberOfAdventurers() const;
    void setHealth(double h);
    double getHealth() const;
    string** getItem(int index) const;
    Adventurer& operator = (const Adventurer& a);
};

And said that
string*** items;

is a pointer to a 2d array

A: It's not entirely clear what you are trying to achieve from your question but it seems your main issue is likely to do with returning the address of a local variable when attempting to allocate your 2D C-style std::string array. Below is a very basic example of how to avoid such an issue via returning the allocated 2D array and then taking the address of this returned value and storing it in your std::string*** items variable.
// allocate memory for a 2D C-style array of std::string's
std::string** allocate_2d_array(std::size_t rows, std::size_t cols) {
    std::string** items_arr = new std::string*[rows];
    for (std::size_t i = 0; i < rows; ++i)
        items_arr[i] = new std::string[cols];
    return items_arr;
}
// print each element of the 2D C-style array via a pointer to the array
void print_items(std::ostream& os, std::string*** items, std::size_t rows, std::size_t cols) {
    for (std::size_t i = 0; i < rows; ++i) {
        for (std::size_t j = 0; j < cols; ++j)
            os << (*items)[i][j] << ' ';
        os << '\n';
    }
}
// destruct the 2D C-style array
void deallocate_2d_array(std::string** items_arr, std::size_t rows, std::size_t cols) {
    for (std::size_t i = 0; i < rows; ++i)
        delete[] items_arr[i];
    delete[] items_arr;
}
int main(void) {
    std::size_t rows = 3;  // matrix rows
    std::size_t cols = 3;  // matrix columns
    // allocate a 2D array of std::string's
    std::string** items_arr = allocate_2d_array(items, 3, 3);
    // set the pointer to a 2D std::string array to address of items_arr
    std::string*** items = &items_arr;
    int count = 0;
    // fill items_arr with data via items pointer
    for (std::size_t i = 0; i < rows; ++i) {
        for (std::size_t j = 0; j < cols; ++j)
            (*items)[i][j] = std::to_string(++count);
    }
    print_items(std::cout, items); // print matrix to terminal
    deallocate_2d_array(items_arr, rows, cols);  // deallocate items_arr
}

However, as mentioned in the comments, this is not in keeping with modern c++ and one would much rather use a std::vector<std::vector<std::string>> to store a matrix of std::string instances.
You mentioned that using std::vector is not an option but I suspect that your teacher probably didn't say anything about making your own barebones dynamic array with similar semantics to a std::vector so that is always one way around these silly restrictions. With that in mind, below is the framework for a very basic (and untested) class which mimics a std::vector (without using allocators) which would make your task much simpler.
template<typename Ty>
class dynamic_array {
public:
    typedef Ty value_type;
    typedef Ty& reference;
    typedef const Ty& const_reference;
    typedef Ty* pointer;
    typedef const Ty* const_pointer;
    typedef std::size_t size_type;
    typedef std::ptrdiff_t difference_type;
    // CONSTRUCTION/ASSIGNMENT
    dynamic_array()
        : arr_capacity(0), arr_size(0) {}
    dynamic_array(size_type count)
        : arr_capacity(count), arr_size(count) { allocate(count); }
    ~dynamic_array() { destroy(); }
    dynamic_array& operator=(dynamic_array _other) {
        swap(*this, _other);
        return *this;
    }
    // CAPACITY
    bool empty() const noexcept { return arr_size; }
    size_type size() const noexcept { return arr_size; }
    size_type capacity() const noexcept { return arr_capacity; }
    void reserve(size_type new_cap) { if (new_cap > arr_capacity) reallocate(new_cap); }
    // ELEMENT ACCESS
    reference operator[](size_type n) { return arr[n]; }
    const_reference operator[](size_type n) const { return arr[n]; }
    // MODIFIERS
    void clear() {
        for (size_type i = 0; i < arr_size; ++i)
            (&arr[i])->~value_type();
        arr_size = 0;
    }
    void push_back(const value_type& _val) {
        if (arr_size == arr_capacity) // TODO: expand arr using reallocate
        pointer val = new (arr + arr_size) value_type(_val);
        ++arr_size;
    }
    void pop_back() {
        (&arr[arr_size-1])->~value_type();
        --arr_size;
    }
    void swap(dynamic_array& _other) {
        std::swap(arr, _other.arr);
        std::swap(arr_capacity, _other.arr_capacity);
        std::swap(arr_size, _other.arr_size);
    }
    static void swap(dynamic_array& lhs, dynamic_array& rhs) { lhs.swap(rhs); }
private:
    value_type* arr;
    size_type arr_capacity;
    size_type arr_size;
    void allocate(size_type n) { arr = new value_type[n]; }
    void reallocate(size_type new_cap) {
        value_type* tmp = new value_type[new_cap];
        size_type tmp_rows = (new_cap > arr_capacity) ? arr_capacity : new_cap;
        for (size_type i = 0; i < tmp_rows; ++i)
            tmp[i] = std::move(arr[i]);
        delete[] arr;
        arr = tmp;
        arr_capacity = new_cap;
    }
    void destroy { clear(); delete[] arr; }
};

Then instead of messing around with lots of raw pointers and the headaches they bring, you can just pass around your dynamic_array<dynamic_array<std::string>> class instance without needing to worry about memory management.

Note: The above dynamic_array class is untested and probably requires some tweaks, it is also not a great example of implementing a STL-style container (you'd need allocator and iterator support), it is just intended as a barebones std::vector mimicking container to get around the "no vector" task requirement.


text:
Q: Get wikitext from wikipedia API? I'm looking at the API documentation here,
https://www.mediawiki.org/wiki/API:Query
Getting the wikitext for a page is mentioned in the beginning of the documentation,

The action=query module allows you to get information about a wiki and the data stored in it, such as the wikitext of a particular page, the links and categories of a set of pages, or the token you need to change wiki content.

but I cant seem to figure out what parameters to pass in the API request to return the wikitext for a given page.  Anyone know how to do this?
I've tried parameters like,
{'action':'query', 'titles':'Anarchism', 'prop':'wikitext', 'format':'json'}

A: You must use this query       .
   https://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=json&titles=Anarchism&rvslots=main

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is my webcam messed up in Chrome but fine in Firefox? I use Ubuntu a freshly installed Ubuntu 19.10 with a Logitech C905 webcam "QuickCam Pro for Notebooks" (2MP, autofocus, etc.). lsusb seems to detect the webcam properly as Bus 001 Device 005: ID 046d:0991 Logitech, Inc. QuickCam Pro for Notebooks and when I test my camera with the Ubuntu built-in Cheese app then the image is exactly as it should be.
But when I try using Google Duo or Google Hangouts, then the image is cut and shifted. My counterpart receives the same shifted image, so obviously it's pretty useless.
edit: As per comments, I have discovered that it works just fine in Firefox so it appears to be a problem with the Google Chrome browser!
This is Google Duo:
This is Google Hangouts:
Oddly, the test image looks fine for the first half second or so, and then it shifts. Even stranger, the top 10 pixels or so are not shifted. Next time I tried, the top pixels were shifted as well, and my counterpart told me that I was far off-center when I was directly in front of the camera. My elbow was in center.
I've also tested the webcam in a browser using https://webcamtests.com and the first image it shows it shifted, then that disappears, then a good image appears and stays good.
I can't find any Linux drivers on the Logitech website, and given that the image is fine using Cheese, I am also very hesitant to spend money on a new webcam (this one was expensive).
What steps can I take to pinpoint the cause and fix the problem?


text:
Q: Get-ADGroup to retrieve members not returning members in other forest (but does return for different domain/same forest) I'm in a multi-domain and multi-forest environment. Forest 1 contains the vast chunk of users and domains - forest 2 contains a single legacy domain, and this setup is causing issues.
Get-ADGroup -Identity $_.groupname -Server $_.domainname -Properties members | select members

When this is run on groups from either forest, the results ONLY return members that are in the same forest as the group. This is an issue as we have users from forest 1 inside forest 2 groups, and vice-versa. Edit: The users from the other forest are NOT listed as foreign security principals in this output, but I know they are there based on Forefront Identity Manager.
The objective here is to get a full listing of users within groups, regardless of domain or forest, as we need this for an upcoming audit.


text:
Q: Bundle APK with app I am creating an app which uses ZLib (QR code reader), but it requires another app to be installed for it to work. I want to be able to package the other apps APK file within my APK. Is this possible?
Sidenote: I am trying doing this because my app will be used on an Amazon Fire kindle, but the prerequisite app is only on the Google Play store.

A: You can have a copy of the other app's APK in your app (e.g. within the assets directory).
After your app is installed, you can copy the APK to the public storage and launch the package manager to install the other app from the APK:
Intent pmIntent = new Intent(Intent.ACTION_VIEW)
        .setDataAndType(Uri.parse("file:///path/to/the.apk"),
                        "application/vnd.android.package-archive");
startActivity(pmIntent);

But note that this requires the user to have enabled side loading of apps from third-party sources.

A: Your current approach is unsuitable in many ways.
You can use alternative libraries that can be embedded in your app and don't need any other application to be installed on the user's device. There are a handful of options on the Android Arsenal.


text:
Q: NG0303: Can't bind to 'ngif' since it isn't a known property of 'div' I try to learn Angular with documentation but I have an error but this code work (I learn with this tutorial https://angular.io/tutorial/toh-pt4):

NG0303: Can't bind to 'ngif' since it isn't a known property of 'div'.

I found this I should import commonModule in app.module.ts. But it doesn't work. Why? Do, you think that learning with offical documentation is good idea?

A: Please use the format like this :
    <div *ngIf="condition; else elseBlock">
    Content to render when condition is true.
    </div>
    <ng-template #elseBlock>Content to render when condition is false.
    </ng-template>

A:
Common module is common for all modules.
if you are using lazy loaded modules then it must contains the CommonModule as well


text:
Q: How do you run an event after a advancement is completed? I'm trying to code a plugin where the border follows a player and doubles everytime they get an advancement. The problem is I don't know how to detect when someone gets an advancement and keep it in the same class. Here is the current code.
survivalBorders.class
package sc458.survivalborders;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.WorldBorder;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerAdvancementDoneEvent;
import org.bukkit.event.player.PlayerEvent;
import org.bukkit.plugin.java.JavaPlugin;

public class survivalBorders extends JavaPlugin {
    public void onEnable() {
        World world = Bukkit.getWorld("survival");
        WorldBorder border = world.getWorldBorder();
        double borderSize = border.getSize();

        while(true) {
            if(PlayerAdvancementDoneEvent) {
                border.setSize(borderSize*2);
            }
        }
    }
    public void onDisable() {

    }
}

MoveEvent.class
package sc458.survivalborders;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.WorldBorder;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;

public class MoveEvent implements Listener {
    public void onMove(PlayerMoveEvent e) {
        Player p = e.getPlayer();
        World world = Bukkit.getWorld("survival");
        WorldBorder border = world.getWorldBorder();
        int locX = p.getLocation().getBlockX();
        int locZ = p.getLocation().getBlockZ();
        border.setCenter(locX, locZ);
    }
}

A: Try to call the PlayerMoveEvent with a Listener and then you can just everytime he moves (event gets triggered) -> set the border again. So basically when his coordinates change, the border will immediantly follow you.
public class MoveEvent implements Listener {
   @EventHandler
   public void onMove(PlayerMoveEvent e) {
     Player p = e.getPlayer();
     WorldBorder border = world.getWorldBorder();
     int locX = p.getLocation().getBlockX();
     int locZ = p.getLocation().getBlockZ();
     border.setCenter(locX, locZ);
   }
}


text:
Q: What is the difference between user variables and system variables? What is the difference between user variables such as PATH, TMP, etc. and system variables?
I accidentally deleted the user variable PATH. What am I supposed to do?

A: System environment variables are globally accessed by all users.
User environment variables are specific only to the currently logged-in user.

A: Just recreate the Path variable in users.  Go to user variables, highlight path, then new, the type in value.  Look on another computer with same version windows.
Usually it is in windows 10: Path %USERPROFILE%\AppData\Local\Microsoft\WindowsApps;

A: Right-click My Computer and go to Properties->Advanced->Environmental Variables...
What's above are user variables, and below are system variables. The elements are combined when creating the environment for an application. System variables are shared for all users, but user variables are only for your account/profile.
If you deleted the system ones by accident, bring up the Registry Editor, then go to HKLM\ControlSet002\Control\Session Manager\Environment (assuming your current control set is not ControlSet002). Then find the Path value and copy the data into the Path value of HKLM\CurrentControlSet\Control\Session Manager\Environment. You might need to reboot the computer. (Hopefully, these backups weren't from too long ago, and they contain the info you need.)

A: Environment variables are 'evaluated' (ie. they are attributed) in the
following order:

*

*System variables

*Variables defined in autoexec.bat

*User variables

Every process has an environment block that contains a set of environment variables and their values. There are two types of environment variables: user environment variables (set for each user) and system environment variables (set for everyone). A child process inherits the environment variables of its parent process by default.
Programs started by the command processor inherit the command processor's environment variables.
Environment variables specify search paths for files, directories for temporary files, application-specific options, and other similar information. The system maintains an environment block for each user and one for the computer. The system environment block represents environment variables for all users of the particular computer. A user's environment block represents the environment variables the system maintains for that particular user, including the set of system environment variables.

A: An environment variable (can access anywhere/ dynamic object) is a type of variable. They are two types of system environment variables and user environment variables.
System variables have a predefined type and structure. That are used for system functions. Values which are produced by the system are stored in the system variable. They generally indicated by using capital letters
Example: HOME,PATH,USER
User environment variables are the variables that determined by the user, and are represented by using small letters.


text:
Q: Passing parameter in inner html in java script I want pass parameter in inner html.
function func() {
    var ul = document.getElementById("section");
    var newLI = document.createElement("LI");
    ul.appendChild(newLI);
    var ch = 'kuldeep';
    newLI.innerHTML = "Click Me ";
}

Please advice how to add parameter in itemcustom function right now it is not taking any parameter.

A: You need to break the string literal, to insert the variable ch as such:
function func() {
    var ul = document.getElementById("section");
    var newLI = document.createElement("LI");
    ul.appendChild(newLI);
    var ch = 'kuldeep';
    newLI.innerHTML = "Click Me ";
}

This is called string concatenation, which means adding two or more strings together as one.

A: Right now it's rendering as text. You'll have to escape the string like so:
"Click Me "

A: Why not just create a proper element ?
function func() {
    var ul     = document.getElementById("section");
    var newLI  = document.createElement("li");
    var anchor = document.createElement("a");
    var ch     = 'kuldeep';

    anchor.href = "#";
    anchor.addEventListener('click', function() {
        itemcustom(ch);
        return false;
    }, false);
    anchor.innerHTML = 'Click Me';

    newLI.appendChild(anchor);
    ul.appendChild(newLI);
}

FIDDLE


text:
Q: Baire category theorem and countable union of closed meagre sets in complete metric space In my functional analysis course Baire category theorem is the following: Complete metric spaces are of second category.
The following was stated as Baire Category theorem's consequence:
Suppose $X$ is a complete metric space. Suppose $c_1,...,c_n,...$ are closed meagre sets. Then $c = \cup_{n=1}^{\infty}c_n$ is also a meagre set.
I can prove this in the following way. Suppose $c$ is not meagre and thus contains a closed ball. Suppose that ball is $B_0 = B[x_0, r_0]$. Then there exists a ball $B_1 = B[x_1,r_1] \subset B_0, r_1 < r_0/2$ such that $B_1 \cap c_1 = \emptyset$. Then $\exists B_2 = B[x_2,r_2] \subset B_1 \subset B_0, r_2<r_1/2<r_0/2^2$ such that $B_2 \cap c_1 = \emptyset, B_2 \cap c_2 = \emptyset$. In this way we get a sequence $B_n = B[x_n,r_n]$ such that $B_{n+1} \subset B_n$ and $r_n < r_0/2^n$. $X$ is complete so $\cap_{n=0}^{\infty} B_n = {a}$ where $ a \in X, a\notin c$. But this is a contradiction which is the end of the proof.
Now, this is very similar to how Baire category theorem is proven. But it is listed as a consequence so I don't know how this result could be derived from the initial theorem statement.
Also, I've noticed that this theorem is stated in different ways which are (I assume) equivalent and the above statements are two of those. While I can see clear correlation between the other possible ways to state the theorem, I don't see direct correlation between the above two.


text:
Q: Add String value on Array I want to add a string code ("CUS") with $row['id'] number. how can I do that?
for example, if id value is 1 then it should display as CUS1.
while ($row = mysqli_fetch_assoc($empRecords)) {
$data[] = array(
        "id"=>$row['id'],
        "name"=>$row['name'],
        "id_no"=>$row['id_no'],
        "address"=>$row['address'],
        "grmadiv"=>$row['grmadiv'],
        "mobile"=>$row['mobile'],
        "branch"=>$row['branch'],
        "loanOfcr"=>$row['loanOfcr'],
        "collectOfcr"=>$row['collectOfcr']
    );

A: Just place any string Concatenation with ".", Example like
"id"=> 'CUS'. $row['id'],
$code = 'CUS'.$row['id];
Thanks


text:
Q: How to prevent a 'Array index out of range' error? Is there a way, similar to using if let and/or optionals, to test whether you are about to index an empty buffer in Swift?

A: Define your own:
extension Array {
  func ref (i:Int) -> T? {
    return 0 <= i && i < count ? self[i] : nil
  }
}

The ref() function returns an optional, so it can be nil, and you can use the if let syntax to access the returned value from ref() when it exists.  You would use this as such:
var myA = [10,20,30]
if let val = myA.ref(index) {
  // Use 'val' if index is < 3
}
else {
  // Do this if the index is too high
}


text:
Q: Do SQL Server stored procedures cache data results? I have heard this from friends, but I never investigated whether this is true.
Is it true that the data results of an executed query are stored in cache?
I mean, if I have a stored procedure like :
SELECT * FROM USERLIST

...is it true that the result (list of users, in this case) is stored in cache.
Also, if I have these :
SELECT * FROM USERLIST WHERE user="user"
SELECT * FROM USERLIST WHERE user="userzzz"

(in which user/userzzz are passed as parameters), is it correct that it stores 2 different results on the database cache.
I don't think so, but I want the confirmation from you, experts!

A: When a stored procedure is executed it is optimized and compiled and the query plan is placed in procedure cache.
Procedures remain in cache for other users, as long as there is space. Procedures are removed using the least recently used (LRU) algorithm.

While the initial execution of a stored procedure necessitates retrieval from sysprocedures on disk, it is possible, for subsequent executions, to simply retrieve the optimized plan from procedure cache. This behaviour can lead to significant performance gain.
So, what's in cache is the optimized plan from the stored procedure and not the results of the stored procedure.

A: When a query is ready to be processed by SQL Server, the SQL Manager looks it up in cache; and if it's not there, it must be compiled. The compilation process encompasses a few things.
When a stored procedure is executed it is optimized and compiled. according this a query plan is placed in procedure cache.
Check the Compilation and Execution section on  Microsoft SQL Server Query Processor Internals and Architecture   for detailed information about the query processing etc.

The end product of the compilation phase is a query plan, which is put
  into the procedure cache. SQL query result/operation could be of size
  in MB, GB so it is not put in the procedure cache or query plan.

Check the following diagram (from MSDN)  for stored procedure execution to clear about your question:

A: Query results are not cached
However, the source table and index data and metadata will be cached after the 1st use (subject to continued use, load and memory pressure though)
That is, the results of a query will be evaluated every execution but the tables(s) (and any indexes etc) used by the query will most likely be in memory already.
The compiled execution plan will be cached which is where the confusion comes from I suspect

A: SQL Server basically goes through these steps to execute any query (stored procedure call or ad-hoc SQL statement):
1) syntactically check the query
2) if it's okay - it checks the plan cache to see if it already has an execution plan for that query
3) if there is an execution plan - that plan is (re-)used and the query executed
4) if there is no plan yet, an execution plan is determined
5) that plan is stored into the plan cache for later reuse
6) the query is executed
(copy of Marc_s answer)

A: As others have stated, query results in SQL Server are not cached.
If you want to cache the results of a query (or an SP), there are workarounds. For example, see this article at the Brent Ozar website.


text:
Q: Unable to import issues I am getting multiple errors when trying to run this program. Here they are below:
Unable to import 'matplotlib.pyplot'
Unable to import 'yfinance'
Unable to import 'dateutil.relativedelta'
Unable to import 'pandas'
Unable to import 'mplcursors'
Unable to import 'matplotlib'
Unable to import 'matplotlib.dates'
Unable to import 'dateutil'
Unable to import 'numpy'
I have never used python before so I am really confused as to what to do?
EDIT: SOLVED
I had to change the path and install python in addition to Visual Studio and restart the whole thing. Thanks for your answers!

A: If you have python installed, then the most immediate way to get this working is to do:
pip install -r requirements.txt

However, I strongly recommend using a virtual environment for every new project you look at. There are many different ways to make a virtual environment so I leave it to you to research that.


text:
Q: HTML5 datalist - always show unfiltered options I would like to have a textfield input with a datalist of e.g. 10 fixed options.
Instead of the usual autocomplete behavior, I would like the dropdown to always show the complete list.
Especially, if the input has a pre-filled value, and the user clicks, I would like the dropdown to open and show the unfiltered list of options, so the user can use it like a select element.
Any idea how to do that?


text:
Q: PHP cant connect to MySQL $link = mysql_connect('localhost', $username, $password);
if (!$link)
{
     die('Could not connect: ' . mysql_error());
}

I get this error:
Could not connect: Access denied for user 'www-data'@'localhost' (using password: NO)
Why?
Edit:

$username="root";
$password="root";
$database="test";

    function Save($name)
    {
        $link = mysql_connect('localhost', $username, $password);
        if (!$link) {
            die('Could not connect: ' . mysql_error());
        }
        @mysql_select_db($database) or die( "Unable to select database");
        $query = "INSERT INTO test (name)" .
                 "VALUES ('" . $name . "')";
        mysql_query($query);
        mysql_close();
    }

A: Did you give $username and $password values? Something like this?
$username="root";
$password="";

A: Your $password variable is empty ((using password: NO)) then you trying log into www-data user without password, and server result is access denied. Propably this user have setted password.

A: From your edit, the issue appears to be a scoping one.
You're attempting to make a connection inside a function where the $username, $password and $database variables are defined outside that function.
I suggest you read the Variable Scope section of the manual and turn up your error reporting as @netcoder suggests in the question comments.

A: I think the problem is that, you are trying to connect to the database twice.
Somewhere in your code, you are already trying to connect to the database with username as "www-data"...... and again you are connecting to the database with username "root".
Also the password you are providing with the username "www-data" is wrong, thats y you getting the error message.

A: $username="root";
$password="root";
$database="test";

    function Save($name)
    {
        global $username;
        global $password;
        global $database;

        $link = mysql_connect('localhost', $username, $password);
        if (!$link) {
            die('Could not connect: ' . mysql_error());
        }
        @mysql_select_db($database) or die( "Unable to select database");
        $query = "INSERT INTO test (name)" .
                 "VALUES ('" . $name . "')";
        mysql_query($query);
        mysql_close();
    }


text:
Q: Edit context menu (selectiontree) in customize dialog? How do I edit the context menu (selectiontree) in a customize dialog?
I don't want to display the option "entire feature will be installed on local hard drive".

A: You can't remove this option. It gets displayed when your feature has subfeatures and allows selecting all subfeatures for installation as well as the currently selected (parent) feature, without clicking each of child features.
See also my answer to How to hide feature options.


text:
Q: GStreamer Get Exact Time of 1st Frame I'm running GStreamer from the command line to record video to H.264 avi like this.
gst-launch tvsrc fps-n=25 ! 'video/x-raw-yuv, width=(int)720, height=(int)576, framerate=(fraction)25/1' ! vpuenc codec=6 ! avimux ! queue2 max-size-buffer=1 max-size-bytes=0 max-size-time=0 ! filesink location=output.avi

There is some init time from when I do gst-launch till when the video actually starts recording.
Is there any method to get the exact time of the very 1st frame output to text file? Or better still, the exact time of every frame?
Thank you.


text:
Q: How to set in range in hexbin plots pandas? I want to set range of y-axis in the following code.My values are [19,20,21,22,23,24.....,40].I want the labels to be starting from of difference 10,starting from 10 upto 40.How should I set that.
I was trying to use x-lim but it is not working.
plt.hexbin(p_df['Age'], p_df['Salary'], gridsize = 50,bins ='log',cmap ='BuGn',xlim =(19, 40))

A: To set the range of values to include in the binning, you must use the 'extent' keyword. So to have a hexbin plot with a range between your desired x and y values, you can use,
extent=[-x,x,10,40]

where x is your included x coordinates.
So your new code would be
plt.hexbin(p_df['Age'], p_df['Salary'], gridsize = 50,bins ='log', extent=[-x,x,10,40],cmap ='BuGn')


text:
Q: PHP Soap Client and .NET Web Service Hi everyone Im trying to consume a .NET with PHP using SoapClient but I got the following issue when my php client send the request, the .NET WS doesnt get the request xml on the right format heres my code i hope some one help me, thanks ind advice
class login {
    public $User;
    public $Password;
}

$logr = new login;

$logr->User = 'user';
$logr->Password = 'pass';

try {
    $client = new soapclient ("http://..../Service.asmx?WSDL", array('classmap' => array('LoginRequest' => 'login'),));

    print_r($logr);
    $client -> Login ($logr);

}
catch (Exception $e) {
    echo "Error!<br />";
    echo $e -> getMessage ();
}

when i test my .net webserver on a .net application i send this, and it works well
<soap:Envelope
    xmlns:soap="http://schemas.xmlsoap.org/soap/envelope"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2011/XMLScheme">
    <soap:Body>
        <Login
            xmlns="http://tempuri.org">
            <LoginRequest>
                <User>user</User>
                <Password>pass</Password>
            </LoginRequest>
        </Login
    </soap:Body>
</soap:Envelope>

but when i test it on php i get this, and this error Server was unable to process request. ---> Object reference not set to an instance of an object.
<SOAP-ENV:Envelope
        xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope"
        xmlns:ns1="http://tempuri.org"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        <SOAP-ENV:Body>
            <Login
                xmlns="http://tempuri.com"
                xso:type="ns1:LoginRequest">
                    <User>user</User>
                    <Password>pass</Password>
            </Login>
        </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>

A: class LoginRequest {
    public $User;
    public $Password;

    public function __construct($usr, $pwd) {
         $this->User = $usr;
         $this->Password = $pwd;
    }
}

$login = new LoginRequest('user', 'password');

$client = new SoapClient('http://..../services.asmx?wsdl');
$client->login($login); // try 1
$client->login(array('LoginRequest' => $login)); //try 2

A: To use a .Net web service, using the NetBeans IDE, add a 'service' and point to the .net web service (make sure to put ?WSDL at the end), and then drag and drop from the 'service's ' toolbox to a php file and it writes the code for you :)
Works great too.
[I can't say what's wrong with your code though]

A: I recently ran into this issue as well when helping a customer consume our .Net web service so I thought I would share in case anyone else came across this in the future.
Thanks to adudly for providing guidance that helped shed light on the issue. You have to provide a name for the parameter in the array, and note that the name is case sensitive.
Working Code
try {
    $wsdl_url = 'http://<mywebserver>/LeadWs.svc?wsdl';
    $client = new SOAPClient($wsdl_url);

    $params = array(
        'lead' => ""
    );
    $return = $client->Insert2($params);

    print_r($return);
} catch (Exception $e) {
    echo "Exception occurred: " . $e;
}

My failed attempts used a capital 'L' for Lead. This is apparently the only thing in the WSDLs/XSDs that is lowercase by default. If you do a careful search through the WSDLs/XSDs you will see the exact names of any parameters your method expects. Once you get those right, SoapClient handles the rest of the XML encoding.
My final Code looked like this:
try {
    $wsdl_url = 'http://<mywebserver>/LeadWs.svc?wsdl';
    $client = new SOAPClient($wsdl_url);

    $lead = new Lead(); // Could just be an array as well
                        // but I created a class to help the user
    $lead->FirstName = "Tester";
    $lead->LastName = "Test";
    $lead->ZipCode = "00000";
    $lead->NumberOfTVs = 2;

    $params = array('lead' => $lead);
    $return = $client->Insert2($params);

    print_r($return);
} catch (Exception $e) {
    echo "Exception occurred: " . $e;
}

Hope that helps someone in the future.

A: You can use SoapHeader and setSoapHeaders here


text:
Q: ElasticSearch dont return result im new with elastic and can't solve this problem
i have 2 requests:
1) curl -XGET 'host/process_test_1/1/_search?title:*New*'
it returns me
    {
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 116,
    "max_score": 1.0,
    "hits": [
      {
        "_index": "process_test_1",
        "_type": "1",
        "_id": "7118_folder_1",
        "_score": 1.0,
        "_source": {
          "obj_type": "folder",
          "obj_id": 7118,
          "title": "sadasd"
        }
      },
      {
        "_index": "process_test_1",
        "_type": "1",
        "_id": "6780_folder_1",
        "_score": 1.0,
        "_source": {
          "obj_type": "folder",
          "obj_id": 6780,
          "title": "New Object"
        }
      }
    }
  ]
}
}

why it returns me an object with title "sadasd"?
and second request
`curl -XGET 'host/process_test_1/1/_search' -d '{"query":{"match":{"text":{"query":"*New*","operator":"and"}}}}`'

it returns
{
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 0,
    "max_score": null,
    "hits": [

    ]
  }
}

why it return me nothins if i really have one element which match (actually i have more than 50 elements with such name and different ids)

A: First, your first query is missing the parameter name q=
curl -XGET 'host/process_test_1/1/_search?q=title:*New*'
                                          ^
                                          |
                                   this is missing

Second, the match query doesn't interpret the * character as a wildcard, so if you want an equivalent query using the DSL for the first query above, you need to be using the query_string query instead:
curl -XGET 'host/process_test_1/1/_search' -d '{
  "query": {
    "query_string": {
      "query": "*New*",
      "default_field": "text"
    }
  }
}'


text:
Q: Get "Unable to delete directory" error when trying to delete all the sub-directories with ant My goal is to perform a full clean-up of my workspace.
I try to delete all files and sub-directories with ant, including .svn dirs.
    <delete includeemptydirs="true">
        <fileset dir="${basedir}" defaultexcludes="false">
            <include name="**"/>
        </fileset>
    </delete>

It does remove all the sub-directories. But, unfortunately, I get the following error (on windows):

"Unable to delete directory {working dir}"

How to avoid this error?
For information, fileset documentation specifies that ** matches zero or multiple directories. Tried several things to exclude current directories but did not find the solution.

A: When adding

don't get the error anymore...
This is may be due to the fact that the delete task is trying to delete the script being executed !


text:
Q: Why does my Player follow the OrthographicCamera My game renders a tiledmap. I let the OrthographicCamera change its position.x to the right and can see the background (the tiledmap) scroll. This is fine.
But other Objects (the player and some balls) do (visually) change their position corresponding to the camera. They should not move, because only the camera moves.
package com.me.drop;
import java.util.Iterator;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapRenderer;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.math.Circle;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.GdxNativesLoader;
import com.badlogic.gdx.utils.TimeUtils;

public class MyTestGame extends Game {
   Texture dropImage;
   Texture bucketImage;
   Sound dropSound;
   Music rainMusic;
   SpriteBatch batch;
   OrthographicCamera camera;
   Rectangle bucket;
   Array<Rectangle> raindrops;
   long lastDropTime;

   Animator animator = new Animator();
   Body animatorBody;
   private Physics physics;

   public Environment environment;
  // public PerspectiveCamera cam;
   public Model model;
   public ModelBatch modelBatch;
   public ModelInstance instance;

   static final int WIDTH  = 1600;
   static final int HEIGHT = 960;
   public final static float ORTHO_SCALE=1;
   public final static float WORLD_SCALE=32;

   Ball balls[] = new Ball[10];
   Spieler player;

   @Override
   public void create() {

       environment = new Environment();
       environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
       environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));

       glViewport = new Rectangle(0, 0, WIDTH, HEIGHT);

      // load the images for the droplet and the bucket, 64x64 pixels each
      dropImage = new Texture(Gdx.files.internal("droplet.png"));
      bucketImage = new Texture(Gdx.files.internal("bucket.png"));

      // load the drop sound effect and the rain background "music"
      dropSound = Gdx.audio.newSound(Gdx.files.internal("drop.wav"));
      rainMusic = Gdx.audio.newMusic(Gdx.files.internal("rain.mp3"));

      // start the playback of the background music immediately
      rainMusic.setLooping(true);
      rainMusic.play();

      // create the camera and the SpriteBatch
      camera = new OrthographicCamera();
      //camera.setToOrtho(false, 400, 240);
      camera.setToOrtho(false, 800/ORTHO_SCALE, 480/ORTHO_SCALE);
      batch = new SpriteBatch();

      ModelBuilder modelBuilder = new ModelBuilder();
      model = modelBuilder.createBox(5f, 5f, 5f,
          new Material(ColorAttribute.createDiffuse(Color.GREEN)),
          Usage.Position | Usage.Normal);
      instance = new ModelInstance(model);

      // Box2d
      physics = Physics.getInstance();

      // floor
      physics.initFloor(0f, 0f, camera.viewportWidth, 0f);
      // ceiling
     // physics.initFloor(0f, camera.viewportHeight, camera.viewportWidth, 10f);
      // left Wall
      physics.initFloor(0f, 0f, 0f, camera.viewportHeight);
      // right Wall
      physics.initFloor(camera.viewportWidth, 0f, 0f, camera.viewportHeight);

      float x = 150;
      float y = camera.viewportHeight;
      for (int i = 0; i < balls.length; i++) {
          if (i%10==0) {
              x += 10;
              y = camera.viewportHeight / 2;
          }
          y += x;
         balls[i] = new Ball(x, y , 20f , 20f, 0.4f, 0.8f);
      }
      player = new Spieler(50, camera.viewportHeight, 60f, 120f);

      loadBackground();
   }

   TiledMapRenderer tileRenderer;

   public void loadBackground() {
       TiledMap map = new TmxMapLoader().load("maps/mymap.tmx");
       System.out.println(map.getTileSets().toString());
       float unitScale = 1 / 1;
       tileRenderer = new OrthogonalTiledMapRenderer(map, unitScale);

       physics.createFixturesForMap(map);
   }

   private Rectangle           glViewport;

   //@Override
   public void render() {

      GL10 gl = Gdx.graphics.getGL10();

      // Camera --------------------- /
      gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
      gl.glViewport((int) glViewport.x, (int) glViewport.y,
              (int) glViewport.width, (int) glViewport.height);
//

      // tell the camera to update its matrices.
      camera.update();
      camera.apply(gl);

      // tell the SpriteBatch to render in the
      // coordinate system specified by the camera.
      batch.setProjectionMatrix(camera.combined);

   // background
      tileRenderer.setView(camera);
      tileRenderer.render();

      for (Ball b : balls)
          b.render();

      player.render();

      grabUserAction();

      // Box2d
      physics.step();
      updateObjects();
      physics.debugRenderer.render(physics.world, camera.combined);

   }

    private void grabUserAction() {
          // process user input
          if(Gdx.input.isTouched()) {
             Vector3 touchPos = new Vector3();
             touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
             camera.unproject(touchPos);
             bucket.x = touchPos.x - 64 / 2;
          }

        Vector2 vel = this.player.getBody().getLinearVelocity();
        Vector2 pos = this.player.getBody().getPosition();
        // apply left impulse, but only if max velocity is not reached yet
        if (Gdx.input.isKeyPressed(Keys.LEFT)) { // && vel.x > -MAX_VELOCITY) {
            // this.animatorBody.localPoint2.x -= 200 *
            // Gdx.graphics.getDeltaTime();
            pos.x -= 2 * Gdx.graphics.getDeltaTime();
            this.player.getBody().setTransform(pos, 0);
            // this.animatorBody.applyLinearImpulse(0, -0.8f, pos.x, pos.y,
            // true);
            // this.animatorBody.applyLinearImpulse(-5000, 0, pos.x, pos.y,
            // true);
        }

        // apply right impulse, but only if max velocity is not reached yet
        if (Gdx.input.isKeyPressed(Keys.RIGHT)) { // && vel.x < MAX_VELOCITY) {
            // this.animatorBody.localPoint2.x += 200 *
            // Gdx.graphics.getDeltaTime();
            pos.x += 2 * Gdx.graphics.getDeltaTime();
            this.player.getBody().setTransform(pos, 0);
            // this.animatorBody.applyLinearImpulse(5000, 0, pos.x, pos.y,
            // true);

        }

        if (Gdx.input.isKeyPressed(Keys.UP)) {
            Vector2 impuls = new Vector2(0, 500f);
            this.player.getBody().applyLinearImpulse(impuls, player.getBody().getWorldCenter(),true);
//          this.animatorBody.applyAngularImpulse(-5.0f, true);
            //(impulse, wake);(new b2Vec2(0.0, -3.0), Body.GetWorldCenter());
        }

        if (Gdx.input.isKeyPressed(Keys.D)) {
            this.camera.position.x += 2;
            this.camera.update();

        }
        else if (Gdx.input.isKeyPressed(Keys.A)) {
            this.camera.position.x -= 2;
            this.camera.update();
        }

    }

   private void updateObjects() {
       Array<Body> array = new Array<Body>();
       physics.world.getBodies(array);
       Iterator<Body> bi = array.iterator();

       while (bi.hasNext()){
           Body b = bi.next();

           // Get the body's user data - in this example, our user
           // data is an instance of the Entity class
           IObject e = (IObject) b.getUserData();

           if (e != null) {
               // Update the entities/sprites position and angle
               e.setPosition((b.getPosition().x - e.getWidth()/2/WORLD_SCALE) * WORLD_SCALE
                           , (b.getPosition().y - e.getHeight()/2/WORLD_SCALE) * WORLD_SCALE);
               // We need to convert our angle from radians to degrees
               //e.setRotation(MathUtils.radiansToDegrees * b.getAngle());
           }
       }
   }

   @Override
   public void dispose() {
      // dispose of all the native resources
      dropImage.dispose();
      bucketImage.dispose();
      dropSound.dispose();
      rainMusic.dispose();
      batch.dispose();

    //  modelBatch.dispose();
      model.dispose();
   }

   @Override
   public void resize(int width, int height) {
       super.resize(width, height);
//
//     Vector3 oldpos = new Vector3(camera.position);
//     camera.setToOrtho(false,
//                        width/WORLD_SCALE,
//                        height/WORLD_SCALE);
//     camera.translate(oldpos.x-camera.position.x,oldpos.y-camera.position.y);
   }

   @Override
   public void pause() {
       super.pause();
   }

   @Override
   public void resume() {
       super.resume();
   }
}


text:
Q: SQL Profiler (SQL Server 2000), how to filter only my activities? We have a big system with several hundred concurrent users so sql profiler gives a bit too much information without appropriate filters. I'd like to see what SQL commands are run under my account and my account only. With account I mean the username I use to log in to the system. These user names are stored in a regular database table and thus can't as such be entered to any filter in sql profiler, I guess? But every user that logs in might have some unique id anyway even thou we all use the same SQL login/user?
So, the question is mostly how to get that unique value and which filter to use? Or is there any way to see this and only this in sql profiler?

A: Each appilcation, which connects to the SQL Server, has a unique host id (the value returned by the HOST_ID() function), and you can filter on it. Of course, first you have to connect to the database from your application, in order to get your host id.
The host id can also be found in the hostprocess column of the sysprocesses system table. And in Profiler it is called ClientProcessId.

A: You should be able to get the hostname of the machine connecting to SQL server. In the Trace Properties/Event Section tab, tick the Show all Columns option then in Column Filters you can specify HostName.
If you want to know the hostname of a machine you are using then at the command prompt type hostname


text:
Q: How to start Drawer Layout below the toolbar in Android? Here is my main xml file:
  <?xml version="1.0" encoding="utf-8"?>
    <android.support.v4.widget.DrawerLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        android:id="@+id/nav_drawer">

    <android.support.design.widget.CoordinatorLayout
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:context="com.example.amit.rssreader.MainActivity">

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/AppTheme.AppBarOverlay">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:popupTheme="@style/AppTheme.PopupOverlay" />

        </android.support.design.widget.AppBarLayout>

        <include layout="@layout/content_main" />

    </android.support.design.widget.CoordinatorLayout>
        <android.support.design.widget.NavigationView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            app:menu="@menu/navigation_menu"
            android:layout_gravity="start">

        </android.support.design.widget.NavigationView>
    </android.support.v4.widget.DrawerLayout>

This is what is happening

I want to have the drawer below the Action bar .This wasnt a navigation Drawer Activity, the navigation drawer has been added later by xml.

A: I think this might help you:

*

*Modify the xml layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        </android.support.v7.widget.Toolbar>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.DrawerLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <android.support.design.widget.CoordinatorLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <include layout="@layout/content_main" />
        </android.support.design.widget.CoordinatorLayout>
    </android.support.v4.widget.DrawerLayout>
</LinearLayout>

*Create theme for activity without toolbar in values/styles.xml and apply it to your activity in AndroidManifest file:
<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

*And to make it working, make the onCreate method of your activity to look like this:
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    final DrawerLayout drawerLayout = (DrawerLayout)
        findViewById(R.id.drawerLayout);

    ActionBar supportActionBar = getSupportActionBar();
    if(supportActionBar != null) {
        supportActionBar.setDisplayHomeAsUpEnabled(true);
        supportActionBar.setHomeButtonEnabled(true);
    }

    setSupportActionBar(toolbar);

    final ListView drawerList = (ListView)
        findViewById(R.id.drawerList);
        drawerList.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,
        new String[] { "Item 1", "Item 2", "Item 3" } ));

        drawerLayout.setScrimColor(Color.TRANSPARENT);

        ActionBarDrawerToggle actionBarDrawerToggle =
        new ActionBarDrawerToggle(this, drawerLayout,
                toolbar, R.string.app_name, R.string.app_name);

        actionBarDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(drawerLayout.isDrawerOpen(drawerList)) {
                drawerLayout.closeDrawers();
            } else {
                drawerLayout.openDrawer(drawerList);
            }
        }
    });

    drawerLayout.addDrawerListener(actionBarDrawerToggle);

    actionBarDrawerToggle.syncState();
}

And this is how does it work.


text:
Q: PHP Session Array empty but have counts So I'm trying to pass my radio buttons value to another page using session arrays, unfortunately the session array comes with an empty value though it still shows the array counts it just returns a blank value.
Here is my code in html form
Top:
<?php
if (!isset($_SESSION))
{
session_start();
}
?>

Html:
<form method="post" action="page1.php">

  Info
  Yes
  No

  Name
   <input type="radio" name="Fullname" value="Full Name">	 //yes
   <input type="radio" name="Fullname" >	                 //no

  Address
   <input type="radio" name="Address" value="Address">	  //yes
   <input type="radio" name="Address">	                  //no

  Age
  <input type="radio" name="Age" value="Age">	          //yes
  <input type="radio" name="Age">	                      //no

</form>

<?php
if (isset($_POST['Fullname']) && ($_POST['Address']) && ($_POST['Age'])){
$Fullname = $_POST['Fullname'];
$Address = $_POST['Address'];
$Age = $_POST['Age'];
}
$info = array($Fullname, $Address, $Age);
$_SESSION['Info'] = $info;

?>

and here is my code for page2.php
above html of page2
if (!isset($_SESSION))
{
session_start();
}

inside html
<?php
if (isset($_SESSION['Info']) && is_array($_SESSION['Info'])) {
foreach($_SESSION['Info'] as $key=>$value)
{
echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".'
';
}
?>

So, what i'm really trying to do is when the user choose "yes" radio button the value of it will be push to an array. For instance, the user choose yes for Name and Address then no for Age, then on the page2.php Name and Address will be displayed. Anything that the user choose as yes will be displayed through array. But somehow with my code it only displays the count and not the actual value of the radio button.
or is there any alternative idea for this?
thanks in advance!

A: There are couple of ways of doing that. If you follow your approach, then start session in page1.php too on top,
 <?php
    if (!isset($_SESSION))
    {
       session_start();
    } ?>
<form method="post" action="page1.php">

  Info
  Yes
  No

  Name
   <input type="radio" name="Fullname" value="Full Name">	 //yes
   <input type="radio" name="Fullname" >	                 //no

  Address
   <input type="radio" name="Address" value="Address">	  //yes
   <input type="radio" name="Address">	                  //no

  Age
  <input type="radio" name="Age" value="Age">	          //yes
  <input type="radio" name="Age">	                      //no

</form>

<?php
if (isset($_POST['Fullname']) && ($_POST['Address']) && ($_POST['Age'])){
$Fullname = $_POST['Fullname'];
$Address = $_POST['Address'];
$Age = $_POST['Age'];
}
$info = array($Fullname, $Address, $Age);
$_SESSION['Info'] = $info;

?>

Keep everything same, once your form is submitted to page1.php itself, it will store the session data in $_SESSION['Info'] array. Go to page2.php, and reload the page. You will see your results like this:
The value of $_SESSION['0'] is 'Full Name'
The value of $_SESSION['1'] is 'Address'
The value of $_SESSION['2'] is 'Age'

Also, you can use page2.php in your form action and store the session their as well. :)

A: Try to shorten your code this way below.
Use your html form submission, then.
page1.php
<?php
session_start();
if (isset($_POST['Fullname'], $_POST['Address'], $_POST['Age'])){
    $_SESSION['Info'] = filter_input_array(INPUT_POST);
}
?>

insidehtml.php
<?php
session_start();
if (isset($_SESSION['Info']) && is_array($_SESSION['Info'])) {
    foreach($_SESSION['Info'] as $key => $value){
        echo 'The value of ['.$key.'] is ('.$value.')
';
    }
}
?>

A: My Answer: maybe that you are missing some html code in your snippet... try with my changes... radio inputs need to have different values... in your snippet assign the value Fullname but at second input radio you miss a value, the same you have done for Address and Age... other issue... you are storing into SESSION without starting session_start(); I figure out what you want obtain from your code and I reworked my answer, it's more bit complex but works fine as you expected:
<?php if (session_status() == PHP_SESSION_NONE) { session_start(); } ?>
<form method="post" action="page1.php">

  Info
  Yes
  No

  Name
   <input type="radio" name="Fullname" value="yes">Yes
   <input type="radio" name="Fullname" value="no">No

  Address
   <input type="radio" name="Address" value="yes">Yes
   <input type="radio" name="Address" value="no">No

  Age
  <input type="radio" name="Age" value="yes">Yes
  <input type="radio" name="Age" value="no">No

 <input type="submit" value="Send">
</form>
<?php
if (isset($_POST['Fullname']) && isset($_POST['Address']) && isset($_POST['Age'])) {
  if ($_POST['Fullname'] == "yes") {
    $Fullname = array("Fullname" => "Yes");
  } elseif ($_POST['Fullname'] == "no") {
    $Fullname = array("Fullname" => "No");
  }
  if ($_POST['Address'] == "yes") {
    $Address = array("Address" => "Yes");
  } elseif ($_POST['Address'] == "no") {
    $Address = array("Address" => "No");
  }
  if ($_POST['Age'] == "yes") {
    $Age = array("Age" => "Yes");
  } elseif ($_POST['Age'] == "no") {
    $Age = array("Age" => "No");
  }
} elseif (!isset($_POST['Fullname']) || !isset($_POST['Address']) || !isset($_POST['Age'])) {
  $Fullname = array("Fullname" => "Not Set");
  $Address = array("Address" => "Not Set");
  $Age = array("Age" => "Not Set");
}
$info = array($Fullname, $Address, $Age);
$_SESSION['Info'] = $info;
?>

insidehtml.php
<?php
if (session_status() == PHP_SESSION_NONE) {
  session_start();
}
if (isset($_SESSION['Info']) && is_array($_SESSION['Info'])) {
  foreach($_SESSION['Info'][0] as $key => $value) {
    echo 'The value of $_SESSION[' . "'" . $key . "'" . '] is ' . "'" . $value . "'" . '
';
  }
  foreach($_SESSION['Info'][1] as $key => $value) {
    echo 'The value of $_SESSION[' . "'" . $key . "'" . '] is ' . "'" . $value . "'" . '
';
  }
  foreach($_SESSION['Info'][2] as $key => $value) {
    echo 'The value of $_SESSION[' . "'" . $key . "'" . '] is ' . "'" . $value . "'" . '
';
  }
}
?>

Let's me know if it's what you are looking for... ;-)


text:
Q: Firebase query help for react-native I'm kinda new to firebase & react-native but I need a little help with a query I have to do for my project.
So let's say I have 2 tables
Posts:{postID(key), posterID, description}
Likes:{likeID(key), postID, likerID}

so the relationship between these two tables is on postID
Is there a way to count all likes for each Post and return top 10 with most likes? I know that this process can't be all on server side so I'm fine with any solutions really.
I think this is the query to count likes for one post:
firebase.database().ref(`/likes`)
        .orderByChild('postId').equalTo(postID)
        .once('value', snapshot => {
            const likesCount = snapshot.count;

        })

A:
Is there a way to count all likes for each Post...?

Firebase has no built-in aggregation queries. You'll typically either do this client-side, or through Cloud Functions, and write the count into each post. You'd then order on that "count property" to return the posts with the most likes.
Also see:

*

*In Firebase, is there a way to get the number of children of a node without loading all the node data? (showing how to atomically increment a counter)

*this sample of counting child nodes using Cloud Functions

*Is the way the Firebase database quickstart handles counts secure? (a discussion about securely counting likes)

*Aggregate values coming from firebase database


text:
Q: Which properties should be declared in View controller m and which in model m objective c? Sorry for noob question. I have of bunch of properties for my iPhone app and first three properties are straight forward like this
model.m file
@property (nonatomic,strong)NSMutableArray *celsiusStack;
@property (nonatomic,strong)NSMutableArray *fahrenheitStack;

viewController.m
@property (nonatomic) BOOL userFinishedTyping;

Now what should I do if property is ambiguous and is used extensively in both model and viewController. Does it matter where I declare it and what is a good practice.
@property (nonatomic) BOOL celsius;

A: It very much depends on the purpose of celcius?
One of the basic concepts of the MVC pattern is to make it easier to replace the GUI completely without the need to modify the underlying model.
My guess is that it would make good sense to have the celcius property in your model, but again. It depends on it's purpose.


text:
Q: PHP - Cookies are being removed, but are regenerated on the next page I have an option for users to select a "Remember me" option on my site that saves certain information to cookies so that they can be authenticated without needing to log in.
However, when users want to log out, it seems that these cookies are being deleted, but are for some reason being created again when they are sent to the next page.
The following is an example of my log out script. Before this exact code is called, the user is authenticated via a different file included in the log out file and cookies are set if the user has specified that they wish to be remembered.
// -- FROM THE AUTH FILE -- //

setcookie("username", "bob240", time() + (86400 * 30), "/", ".domain.com");
setcookie("password", "password123", time() + (86400 * 30), "/", ".domain.com");

// -- END FROM THE AUTH FILE -- //

// Clear cookies by setting them to a past date.
setcookie("username", "", time() - (86400 * 30), "/", ".domain.com");
setcookie("password", "", time() - (86400 * 30), "/", ".domain.com");

// Check if the session was destroyed.
if(session_destroy()) {

    // Redirect the user.
    header('Location: /next/page/'); die("Redirecting...");

}

This means that the same cookies are set twice on the same page. However, because these cookies are set in the order from which they are listed, there should not be any conflicts.
However, to test this theory, I tracked the header requests and responses from my browser and I could see that the cookies were being set when the user was authenticated and deleted when the user logged out.
To check further, I printed $_SESSION and $_COOKIE multiple times on the log out page and the page the user was redirected to. I could see that the cookies were being removed, as $_COOKIE was empty. However, $_SESSION still contained the necessary information to authenticate the user. Because of this, I thought that the sessions were somehow causing the problem. However, I threw away this thought when I tested logging out without the cookies being set from the "Remember me" option, and everything worked fine.
I also want to note that when visiting the log out page from a sub-domain, going from sub-domain.domain.com -> www.domain.com/log-out-page/, I was able to successfully log out even with cookies set.
I am also able to sometimes successfully log out after visiting the log out page multiple times.
I use the same code (AFAIK) on two others sites, which are both on the same web servers, and everything is working fine. I even tried using the files from the other two sites, but the problem still persists. All of these sites use CloudFlare and have the same settings set.
Since this is a very vague issue, you can use the demo account on my site to log in and test anything yourself.
Site that isn't working: https://theartex.net/system/login/,
site that is working: https://mathhulk.me/system/login/
Account:
username - demo,
password - demo

A: The constant pinging of /cloud/api/ to get the alerts for the user sets the cookies at the same time as /system/logout removes them. If you keep /cloud/api from setting the two cookies then it should all work again.


text:
Q: dagger2 non-@Nullable @Provides method I'm at the beginning of use Dagger to my projects.
I've made this modules:
@Module
public class FirebaseModule {

@Provides @Singleton
public FirebaseUser provideCurrentUser(){
    return FirebaseAuth.getInstance().getCurrentUser();
}

@Provides @Singleton
public DatabaseReference provideDatabaseReference(){
    return FirebaseDatabase.getInstance().getReference();
}

@Provides @Singleton
public FirebaseAuth provideFirebaseAuth(){
    return FirebaseAuth.getInstance();
}
}

and this:
@Module
public class AppModule
{
private HappyParkApp app;

public AppModule(HappyParkApp app) {
    this.app = app;
}

@Provides
public HappyParkApp providesApp()
{
return this.app;
}

@Provides
public Context getAppContext(){
    return this.app;
}
}

I've also made the component:
@Singleton
@Component(modules = {AppModule.class,
                      FirebaseModule.class})
public interface AppComponent {

    void inject(MainActivity activity);
}

and this is the appComponent implemented in the application:
public class HappyParkApp extends Application {

private AppComponent appComponent;
private static HappyParkApp instance = new HappyParkApp();
@Override
public void onCreate() {
    super.onCreate();
    createAppComponent();
}

public static HappyParkApp getInstance() {
    return instance;
}

public AppComponent createAppComponent() {
 if(appComponent == null){
     appComponent = DaggerAppComponent.builder()
             .appModule(new AppModule(this))
             .firebaseModule(new FirebaseModule()).build();
 }

 return appComponent;
}

}
so I've tried to to this in onCreate() method of MainActivity:
HappyParkApp.getInstance().createAppComponent().inject(this);

and this before:
 @Inject
FirebaseUser user;

@Inject
DatabaseReference reference;

@Inject
FirebaseAuth mAuth;

but I'm getting this error:
 Caused by: java.lang.NullPointerException: Cannot return null from a non-@Nullable @Provides method

at this line:
 HappyParkApp.getInstance().createAppComponent().inject(this);

and I don't know how to fix it: what is the error? Is this a wrong injection?
Thank you

A: if you annotate your provider method with @Nullable and forget to use @Nullable whenever you want to use that object dagger will throw an error (is not nullable but is being provided by @Provides @android.support.annotation.Nullable)
so simply use if you provide a nullable object make sure to add @Nullable to every method that uses that object as a parameter
ex:
@Nullable
@Provides
static Object provideHomePost(MainActivity activity){
    return activity.getObject();
}
@Provides
static Presenter providePresenterFactory(@Nullable HomePost post) {
    return new CommentPresenterImpl(post);
}

A:
Cannot return null from a non-@Nullable @Provides method

You try to provide null from a provider method that is not marked as @Nullable.
Have a look at getCurrentUser()

Returns the currently signed-in FirebaseUser or null if there is none.

So in case there is no signed in user, this will be null, making the following invalid...
@Provides @Singleton
public FirebaseUser provideCurrentUser(){
  return FirebaseAuth.getInstance().getCurrentUser(); // could be null!
}

So to fix it you have 2 options:

*

*provide FirebaseAuth and grab the user in your application code, or

*mark the provider as @Nullable
Which approach is better depends on your setup, but since you put the user in a @Singleton scoped component I recommend not providing the user, as it is likely to change within the lifetime of "Singleton".
Either move it into a different Scope (e.g. @UserScope or @PerUser) or just grab the user where you need it using FirebaseAuth.getCurrentUser(). You can ofc still provide FirebaseAuth.
Also read about nullability here.


text:
Q: How to write integration tests to check if the cron job runs at the right time and does the right job? I am building cron-jobs using Quartz Framework in my application. I am looking for any automation framework for the integration tests to test cron jobs.
What I want to achieve is to write a test, giving cron expression as an input and expect my test to trigger the job and assert the action.
I have looked for multiple options but couldn't find any solution.
What exactly I want to verify through integration test is:

*

*if the cronjob is configured correctly

*Test for the execution of the cronjob by calling the execute method directly from the test.

*Test to verify the cron format

*Break the flow of cron job

*Run multiple cron job in parallel in a test


text:
Q: Plot mathematica get 'Invalid integration variable' New to mathematica and trying to plot this function:
Integrate[1/Sqrt[0.24/x + 0.76/x^(-2)], x]
Plot[Integrate[1/Sqrt[0.24/x + 0.76/x^(-2)], x], {x, 0, 1}]

But get error output:
Integrate::ilim: Invalid integration variable or limit(s) in 0.000020428571428571424`.
Integrate::ilim: Invalid integration variable or limit(s) in 0.02042859183673469`.
Integrate::ilim: Invalid integration variable or limit(s) in 0.04083675510204081`.
General::stop: Further output of Integrate::ilim will be suppressed during this calculation.

I'm not sure what the problem is in this case.

A: Try
Plot[Evaluate@Integrate[1/Sqrt[0.24/x + 0.76/x^(-2)], x], {x, 0, 1}]


text:
Q: spring JPA query with spel expression for random I am trying to generate a random number so I can do sampling in a data set in a JPA query. I have read this is totally possible everywhere but I keep getting errors:
code:
@Query("select t from Telemetry t where t.id = :id and t.updateTimestamp between :startTime and :endTime and #{ #T(java.lang.Math).random() } < :samplingRate ")
Iterable<Telemetry> findFor(@Param("id") String org, @Param("startTime") Instant startTime, @Param("endTime") Instant endTime, @Param("samplingRate") Float samplingRate);

error:

org.hibernate.QueryException: unexpected char: '#' [select t from
  com.mz.rad.dao.Telemetry t where t.id = :id and t.updateTimestamp
  between :startTime and :endTime and #{ #T(java.lang.Math).random() } <
  :samplingRate ]

Digging deeper into this I discover this exception:
throw new IllegalArgumentException("Parameter with that position [" + parameterPosition + "] did not exist");

parameter position is 1 or 2 Depending on which syntax I use.
I have tried with with/without hashes. No luck. I am using postgres which has a random() function but it doesn't like me invoking that either (which is my ultimate goal).
This question is about using SPeL, but I just need a random number

A: You can try like this :#
select t from Telemetry t where t.id = :id and t.updateTimestamp between :startTime and :endTime and :#{T(java.lang.Math).random()} < :samplingRate

If not then use ?#
select t from Telemetry t where t.id = :id and t.updateTimestamp between :startTime and :endTime and ?#{T(java.lang.Math).random()} < :samplingRate

A: Answer:
@Query("select t from Telemetry t where t.id = :id and t.updateTimestamp between :startTime and :endTime and :#{T(java.lang.Math).random()} < :samplingRate ")

Helps to bump your POM
   <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
        <version>1.10.5.RELEASE</version>
    </dependency>


text:
Q: The sum of the series $\sum_{n=0}^\infty\left(\frac{4n+3}{5^n}\right)$ What is the sum of the series $\sum_{n=0}^\infty\left(\frac{4n+3}{5^n}\right)$ ?
I got that the series converges and the sum seems to be $5$.
When trying to explicitly get the sum, I tried to find the appropriate function whose Maclaurin series would be this sum.

A: $$\sum_{n=0}^{\infty }\frac{4n+3}{5^n}=\sum_{n=0}^{\infty }\frac{4n}{5^n}+\sum_{n=0}^{\infty }\frac{3}{5^n}$$
$$\sum_{n=0}^{\infty }x^n=\frac{1}{1-x}$$
derive it
$$\sum_{n=1}^{\infty }nx^{n-1}=\frac{1}{(1-x)^2}$$
multiply by $x$
$$\sum_{n=1}^{\infty }nx^{n}=\frac{x}{(1-x)^2}$$
at $x=1/5$
$$\sum_{n=1}^{\infty }\frac{4n}{5^{n}}=4\frac{1/5}{(1-1/5)^2}$$
the second series is geometric series
$$3\sum_{n=0}^{\infty }x^n=3\left(\frac{1}{1-x}\right)$$
find the value at $x=1/5$

A: Hint:
$$\sum_{n=0}^\infty \frac{n}{5^n}=\sum_{n=1}^\infty\sum_{m=n}^\infty \frac{1}{5^m}$$

A: a telescoping way,
$\sum_{n=0}^\infty\left(\frac{n+1}{5^{n-1}}\right)$$-$ $\sum_{n=0}^\infty\left(\frac{n+2}{5^n}\right)$

A: $$
\begin{align}
\sum_{n=0}^{\infty}(4n+3)x^n&=4\sum_{n=0}^{\infty}(n+1)x^n\sum_{n=0}^{\infty}x^n\\
&=4(\sum_{n=0}^{\infty}x^{n+1})'-\sum_{n=0}^{\infty}x^n\\
&=4(\frac{x}{1-x})'-\frac{1}{1-x}\\
&=\frac{x+3}{(1-x)^2}
\end{align}
$$
Set $x=\frac{1}{5}$, we have $\sum_{n=0}^{\infty}\frac{4n+3}{5^n}=5$.


text:
Q: How do I fix this Python error? Jupyter Notebooks Converting R to Python I keep getting an error in Jupyter Notebooks and trying to convert R code to Python. I am VERY new to python and my code keeps throwing an error saying that hosp_names is undefined.
Here is my code below. Anything helps. I am also posting the original R code I am attempting to convert as well.
R Code:
# Get the unique hospital names
hosp_names = hosp_info %>%
  filter(`Hospital Type` == "Acute Care Hospitals") %>%
  filter(State == "CA") %>%
  pull(`Hospital Name`)

# Filter based on those hospital names
hosp_info_CA =
hosp_info %>%
  rename(Hospital = `Hospital Name`,
         Provider_ID = `Provider ID`,
         Safety = `Safety of care national comparison`,
         Effectiveness = `Effectiveness of care national comparison`
         ) %>%
  filter(Hospital %in% hosp_names, State == "CA") %>%
  mutate(Overall_Rating = as.numeric(`Hospital overall rating`)) %>%
  drop_na(Overall_Rating)

hosp_info_CA %>%
  arrange(desc(Overall_Rating), Hospital) %>%
  head(7)

hosp_info_CA %>%
  group_by(Overall_Rating, Safety) %>%
  count()

write_csv(hosp_info_CA, 'hosp_info_CA.csv')

Python code:
import pandas as pd #import panda
hosp_names = hosp_info
hosp_info = [(hosp_info[" Hospital Type "] == " Acute Care Hospitals ") & (hosp_info[" State "] == " CA ")].loc[:," Hospital Name "].unique()
hosp_info_CA = hosp_info.rename(columns={" Hospital Name ": " Hospital ", " Provider ID ": " Provider_ID ", " Safety of care national comparison ": " Safety ", " Effectiveness of care national comparison ": " Effectiveness "}).loc[hosp_info[" Hospital "].isin(hosp_names) & (hosp_info[" State "] == " CA ")].dropna(subset=[" Hospital overall rating "]).assign(Overall_Rating = lambda x: pd.to_numeric(x[" Hospital overall rating "]))
hosp_info_CA.sort_values(by=" Overall_Rating ", ascending=False).head(7)
hosp_info_CA.groupby([" Overall_Rating ", " Safety "]).count()
hosp_info_CA.to_csv(" hosp_info_CA.csv ")
Error I keep getting:
Error:
NameError                                 Traceback (most recent call last)
 in
3
4 # Get the unique hospital names
----> 5 hosp_names = hosp_info
6 hosp_info = [(hosp_info[" Hospital Type "] == " Acute Care Hospitals ") & (hosp_info[" State "] == " CA ")].loc[:," Hospital Name "].unique()
7
NameError: name 'hosp_info' is not defined

A: Have you imported the data file that contains the hospital info into Python?
If you have not, assuming it´s a csv file, you can do it by:
import pandas as pd

host_info = pd.read_csv(r'Path where the CSV file is stored\File name.csv')
print(host_info )

A: Look at the error:
Error:

NameError Traceback (most recent call last) in 3 4
# Get the unique hospital names -
---> 5 hosp_names = hosp_info 6 hosp_info = [(hosp_info[" Hospital Type "] == " Acute Care Hospitals ") & (hosp_info[" State "] == " CA ")].loc[:," Hospital Name "].unique() 7

NameError: name 'hosp_info' is not defined

It says:

NameError: name 'hosp_info' is not defined

because in line 5 of your code you assign hosp_names to hosp_info, which is not defined. So when you try to call hosp_info in line 6 it is not defined. i assume you want to do it the other way around :
change line 5 to :
hosp_info = hosp_names


text:
Q: How do you manually create Controllers in Symfony2 without the use of the command line? I am unable to create Controllers through the Command line. Does anyone know how can I manually create controllers for my Symfony2 project?
What files I need to update?

A: You should create file YourControllerNameController.php at src/YourBundle/Controller folder. And put class with name YourControllerNameController into this file. Also be assured that you wrote right namespace according to PSR-0.
If you create controller as a service you can define it as a service and have no problem.
If you want create standard controller that are not registered at service container you could extend your class from Symfony\Bundle\FrameworkBundle\Controller\Controller
In both cases you need also define route for your actions. The easiest way would be to define one route with annotation type. It will generate routes automatically based on your annotations related to actions:
your_route_name:
    resource: "@YourBundle/Controller"
    type:     annotation

It will scan your src/YourBundle/Controller folder and will generate new route for any method in any class in any file that will have annotation @Route:
/**
 * @Route("/your/path", name="you_can_specify_name_here_but_it_is_optional")
 */
public function yourAction()
{
    // Your code here
}


text:
Q: Filter: [?] can not be applied to primitives processing Spring Cloud Contract DSL I have a Spring Cloud Contract DSL that looks like this:
    package contracts.someconsumer.messaging

    import org.springframework.cloud.contract.spec.Contract

    Contract.make {
        label 'my_label'
        // input to the contract
        input {
            // the contract will be triggered by a method
            triggeredBy('someMethodThatSendsMessage()')
        }

        // output message of the contract
        outputMessage {
            // destination to which the output message will be sent
            sentTo 'Consumer.contractTest.VirtualTopic.some_destination'

            // the body of the output message
            body([
                id: value(consumer('11111111-2222-3333-4444-555555555555'),producer(regex(uuid()))),
                correlationId: value(producer(regex(uuid()))),
                service: 'MY_SERVICE',
                payload:
                [
                    email: 'test@example.com'
                ]
            ])
        }
    }

Without the "payload" part everything works great.  With the payload, I encounter this exception:
com.jayway.jsonpath.InvalidPathException: Filter: [?] can not be applied to primitives. Current context is: {"email":"test@example.com","legalName":"ACME Inc"}
        at com.jayway.jsonpath.internal.path.PredicatePathToken.evaluate(PredicatePathToken.java:66) ~[json-path-2.2.0.jar:2.2.0]
        at com.jayway.jsonpath.internal.path.PathToken.handleObjectProperty(PathToken.java:81) ~[json-path-2.2.0.jar:2.2.0]
        at com.jayway.jsonpath.internal.path.PropertyPathToken.evaluate(PropertyPathToken.java:79) ~[json-path-2.2.0.jar:2.2.0]
        at com.jayway.jsonpath.internal.path.RootPathToken.evaluate(RootPathToken.java:62) ~[json-path-2.2.0.jar:2.2.0]

The relevant line from the generated test:
        assertThatJson(parsedJson).field("['payload']").field("['email']").isEqualTo("test@example.com");

Just a little more info, this is what the serialized message looks like:
2017-09-21 08:32:03.721  INFO 10716 --- [           main] c.v.sccdemo.producer.InviteServiceImpl   : Event: {"id":"e63de44e-6e1a-4c4e-b98b-3c49a49efc9c","destination":"VirtualTopic.some_destination","correlationId":"8efb9740-5651-4068-8a6e-574ae7759552","service":"MY_SERVICE","payload":"{\"email\":\"test@example.com\",\"legalName\":\"ACME Inc\"}","timestamp":1505997123576,"version":"v1"}

Am I doing something wrong in the DSL?  Is the 'payload' part of the body expressed correctly?

A: The payload looks wrong... Notice that it's considering payload as a String value instead of a Map. I guess it's enough to change the payload to the proper one and things should work again!


text:
Q: how to zoom imageData How to zoom imageData? I have 160x200 imageData object, now I want to display it 640x400. This must be quick, because done each rendering step.
 var imgData = ctx.createImageData(160,200)
 .....

A: Did you try putImageData and scale with redrawing?
ctx.putImageData(imgData, 0, 0);
ctx.scale(4, 2);
canvas.width = 640;
canvas.height = 200;
ctx.drawImage(canvas, 0, 0);

A: First solution is to use an intermediate canvas.
However, you can avoid using another canvas by just drawing on the main canvas and by using drawImage in its 9 arguments flavor :

var ctx=cv.getContext('2d');

// clear canvas
ctx.fillStyle = '#FFF';
ctx.fillRect(0,0,640, 400);

// draw a circle in the 160X200 part
ctx.fillStyle = '#000';
ctx.beginPath();
ctx.arc (80,100, 80, 0, 6.28)
ctx.fill();

// retrieve image data
var imD = ctx.getImageData(0,0,160,200);

// clear canvas
ctx.fillStyle = '#FFF';
ctx.fillRect(0,0,640, 400);

// --------------------

ctx.putImageData(imD, 0, 0);
ctx.drawImage(cv, 0,0, 160, 200, 0, 0, 640, 400)
  <canvas id='cv' width=640 height=400></canvas>


text:
Q: a while loop for input validation c++ I'm writing a program with a set number of choices to select from (a, b, and c), but for some reason my while loop is not working the way I want it to. I want to only accept lowercase 'a' 'b' or 'c', and uppercase 'A' 'B' or 'C'. I'm pretty sure the way I'm doing it is incorrect. I'm in "Intro to Comp Sci", if that helps understand where I'm at.
Here's my code for what I have right now:
while (choice == 'a' && choice == 'A' || choice == 'b' && choice =='B' || choice == 'c' && choice == 'C'){
    cout << "We dont offer that package. Please try again:\n ";
    cin >> choice;
    //cin.clear();
    //cin.ignore(100, '\n');
    return choice;
}

A: Welcome to stackoverflow
You want that any one of a, A, b, B, c, C as valid. So you need to modify your code as follows:
while (choice == 'a' || choice == 'A' || choice == 'b' || choice =='B' || choice == 'c' || choice == 'C')
Also, you have written:
return choice;
This will immediately terminate the loop and return from current function which contains this while loop.

A: I think the issue here is logic. If I'm not incorrect you want to ask for input until their input is one of A a B b C c?
Putting your while loop into words your saying:
while choice is A and a
or choice is B and b
or choice is C and c
Putting it that way it obviously can't work because how can choice be A and a?
What you want is to loop until choice is one of A a B b C c
Your return also shouldn't be in the while loop, I am assuming you want to return the choice they made after it is valid?
I also added the ! (this is "not", this inverts the result of a condtion - turns true into false, and false into true) operator before all of your conditions as without this you would be looping while choice is correct which means that it would continue only after an incorrect choice is entered.
In short, this code loops through asking for an input until the user's input is one of A a B b C c, after which it returns the input they gave.
while (!(choice == 'a' || choice == 'A' || choice == 'b' || choice == 'B' || choice == 'c' || choice == 'C')) {
    std::cout << "We dont offer that package. Please try again:\n ";
    std::cin >> choice;
}
return choice;

In english this is while choice isn't A or a or B or b or C or c then ask for input

A: Welcome, glad you joined the coding train, so you want to only accept characters, but not any, just (a,b,c,A,B,C), that's cool so you made the first steps that were creating a never ending loop but our condition should be something false when the variable choice is not in the upper list. So we want something like
if((choice != 'a') && (choice != 'b') && (choice != 'c') && (choice != 'A') && (choice != 'B') && (choice != 'C'))
{
    //Stay in the loop
}

so we can write this in the while loop as follows:
while((choice != 'a') && (choice != 'b') && (choice != 'c') && (choice != 'A') && (choice != 'B') && (choice != 'C'))

Thus the full code would look something like this:
#include <iostream>

using namespace std;

int main()
{
    char choice;
    cin >> choice;
    while((choice != 'a') && (choice != 'b') && (choice != 'c') && (choice != 'A') && (choice != 'B') && (choice != 'C'))
    {
        cout << "Sorry this package isn\'t offered by us, try something else: " << endl;
        cin >> choice;
    }
    cout << "Your choice was " << choice << endl << "So you chose one of the following (a,b,c,A,B,C)";

    return 0;
}


text:
Q: Cannot parse array into defined type I am using following puppet class
class myclass{

      $foo = [{"id" => "bar", "ip" => "1.1.1.1"}, {"id" => "baz", "ip" => "2.2.2.2"}]

      map {$foo:}

     define map () { notify {$name['id']: } }

}

But this gives me
err: Could not retrieve catalog from remote server: Could not intern from pson: Could not convert from pson: Could not find relationship target "Change_config::Map[ip1.1.1.1idbar]"
warning: Not using cache on failed catalog
err: Could not retrieve catalog; skipping run

What is the reason for this ?
Regards,
Malintha Adikari

A: Your array contains hashes. The resource declaration syntax works only for arrays of strings.
 $foo = ["bar", "baz"]

 map {$foo:}

 define map () { notify {$name: } }

If you want to pass data with each resource title, you need to

*

*build a hash of your data, not an array of hashes

*use the create_resources function

Untested example code:
$foo = {
  "bar" => { "ip" => "1.1.1.1" },
  "baz" => { "ip" => "2.2.2.2" },
}

create_resources('map', $foo)

define map ($ip="") { notify { "$name has ip $ip": } }


text:
Q: Selenium cannot scrape all elements with same xpath, don't know if the page is not fully loaded? I am trying to scrape this page the title and the price,
https://magnumbikes.com/collections/e-bikes?sort_by=best-selling,
but only half of the products can be collected (it stops at product Metro X),
not sure if it is the page is not fully loaded,
Please let me know or correct me thank you!
Here is my code:
URL='https://magnumbikes.com/collections/e-bikes?sort_by=best-selling'
#driver.maxmize_window()
driver.get(URL)
#There is a subscription window popping up for first time, refresh the page again!
driver.refresh()
time.sleep(2)
driver.execute_script("window.scrollTo(0,document.body.scrollHeight);")
titless=WebDriverWait(driver, 20).until(EC.presence_of_all_elements_located((By.XPATH, '//div/div/h3[@class="collection-card__title h3"]')))

prices=WebDriverWait(driver,20).until(EC.presence_of_all_elements_located((By.XPATH,'//div[@class="collection-card__prices-inner"]/span')))

for i in range(0,len(titless)):
  print(titless[i].text)
  print(prices[i].text)

A: Here is a way to get that information using Requests:
import requests
from bs4 import BeautifulSoup as bs
import pandas as pd

pd.set_option('display.max_columns', None)
pd.set_option('display.max_colwidth', None)

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36'
}

s = requests.Session()
s.headers.update(headers)

big_list = []

for x in range(1, 3):
    r = s.get(f'https://magnumbikes.com/collections/e-bikes?page={x}&sort_by=best-selling')
    soup = bs(r.text, 'html.parser')
    items = soup.select('div[class="collection-filter__item"]')
    for i in items:
        title = i.select_one('h3 a').get_text()
        url = 'https://magnumbikes.com' + i.select_one('h3 a').get('href')
        big_list.append((title, url))
df = pd.DataFrame(big_list, columns=['Bike', 'Url'])
print(df.to_markdown())

Result in terminal:

Bike
Url

0
Nomad
https://magnumbikes.com//collections/e-bikes/products/magnum-nomad

1
Pathfinder 350
https://magnumbikes.com//collections/e-bikes/products/magnum-pathfinder-350

2
Metro S
https://magnumbikes.com//collections/e-bikes/products/magnum-metro-s

3
Scout
https://magnumbikes.com//collections/e-bikes/products/magnum-scout

4
Payload
https://magnumbikes.com//collections/e-bikes/products/magnum-payload

5
Peak T7
https://magnumbikes.com//collections/e-bikes/products/magnum-peak-t7

6
Metro 750
https://magnumbikes.com//collections/e-bikes/products/magnum-metro-750

7
Pathfinder T
https://magnumbikes.com//collections/e-bikes/products/magnum-pathfinder-t

8
Ranger 1.0
https://magnumbikes.com//collections/e-bikes/products/magnum-ranger

9
Low rider 1.0
https://magnumbikes.com//collections/e-bikes/products/magnum-low-rider-2019

10
Pathfinder 500
https://magnumbikes.com//collections/e-bikes/products/magnum-pathfinder-500

11
Cruiser 1.0
https://magnumbikes.com//collections/e-bikes/products/magnum-cruiser-1-0

12
Summit 27.5"
https://magnumbikes.com//collections/e-bikes/products/magnum-summit-27-5

13
Metro X
https://magnumbikes.com//collections/e-bikes/products/magnum-metro-x

14
Peak T5
https://magnumbikes.com//collections/e-bikes/products/magnum-peak-t5

15
Premium 3 Low Step
https://magnumbikes.com//collections/e-bikes/products/magnum-premium-3-low-step

16
Navigator X
https://magnumbikes.com//collections/e-bikes/products/magnum-navigator-x

17
Cosmo X
https://magnumbikes.com//collections/e-bikes/products/magnum-cosmo-x

18
Cosmo+
https://magnumbikes.com//collections/e-bikes/products/magnum-cosmo-1

19
Cosmo S
https://magnumbikes.com//collections/e-bikes/products/magnum-cosmo-s

20
Low rider 2.0
https://magnumbikes.com//collections/e-bikes/products/magnum-low-rider

21
Navigator S
https://magnumbikes.com//collections/e-bikes/products/magnum-navigator-s

22
Ranger 2.0
https://magnumbikes.com//collections/e-bikes/products/ranger-2-0

23
Premium 3 High Step
https://magnumbikes.com//collections/e-bikes/products/magnum-premium-3-high-step

24
Voyager
https://magnumbikes.com//collections/e-bikes/products/magnum-voyager

25
Cruiser 2.0
https://magnumbikes.com//collections/e-bikes/products/magnum-cruiser

26
Cosmo
https://magnumbikes.com//collections/e-bikes/products/magnum-cosmo

You can use Selenium if you wish - just observe the urls accessed (taken from Dev tools - Network tab) and the locators.


text:
Q: Quick GUI development for a simple app / trivia game What would be a good tool/IDE/app to build a GUI? Platform: preferably Windows, but can get away with Linux
Details:

*

*I am an embedded C programmer tasked with writing a simple game for New Year's Party...(some party)

*Game logic is very simple, grab args, alter string, display string on screen (command line version done..).

*However, the interface should look "cool" with preferably some transitional effects when changing values, and some neat visual ways of changing said values.

*I have a designer(not a programmer) friend who'll help with layout.
Having said all that, what would be your advice on how to build the GUI? Hand coding would seem counterproductive here.
EDIT: In a nutshell, I am looking for some WYSIWYGish tool to drag around entry boxes/buttons/whatnot and add a nice background picture, then glue it with my logic code.

A: When I need a quick (and even pretty) GUI for a project, I often consider HTML/CSS with Javascript.  If youre familiar with these tools it can be extremely easy to put together an interactive layout. Another plus is that it the development cycle is ridiculously fast --- just refresh your web browser. Its also cross platform.
When you're playing the game, you can always fullscreen the browser so its not as obvious. Add some animations (jQuery is my suggestion) or images, and some people won't know the difference.

A: Visual Basic is a simple GUI creator.  If you don't mind working with BASIC, then it is a quick tool.  You can download the free Express edition, which is pretty full featured, here.
On Windows and C, you are pretty much stuck with the WinAPI.  I believe there are C++ GUI generators, but I do not know of any C.

A: If you want a WYSIWYG form designer for Windows you'd do well with one of these free downloads from Microsoft:

*

*Visual C# Express

*Visual Basic Express
Visual C# Express and Visual Basic Express allow to use the Windows Presentation Foundation which I haven't used, but will probably allow you to create the cool effects you're looking for.

A: QT comes with the QtDesigner which is as easy to use as the builtin VisualStudio Designer.
Another possibility would be Microsoft Expression Blend. It uses WPF (your code needs to be .NET for that, perhaps that would be no problem), which allows you to do the most fancy GUIs you've ever seen ;)
Sadly this one isn't a thing you could learn in a few days, but its worth the experience.

A: You could always us Python to slap together a quick little application that will run on either windows or Linux. You can even find a some suggestions for a WYSIWYG designer here.
Good luck, and hope this helps some.


text:
Q: Symfony 2, validate standard authentication I've built authentication, based on tutorial.
How can I validate that form? I have no controller action for that. Only route login_check. All the operations performed by Symfony.
Here is  tutorial
Authentication, using traditional login form only requires from developer to create entity (User) and one action of controller that displays login form.
There is no need to create action for route, that handles form data. Symfony does it automatically using events listners. So I don't know, where do I need to write something like that:
$errors = $this->container->get('validator')->validate($user);

where user is object created from entity User.  Or validate POST data.
p.s.
sorry for my english.


text:
Q: How to let QRadioButton show focus border correctly I'm trying to fix focus issue on my qt project.
What I have:

What I need:

I do not need border around circle and I need to fix right margin.
Please do not worry about concrete text inside of radio buttons.

A: You can remove / change the selection border using QSS:
QRadioButton:focus {
    border: none; /* or your modified border here */
}


text:
Q: Applying a filter to subsequences of a sequence using Linq If I have a List<MyType> as so, with each line representing an item in the collection:
{{ Id = 1, Year = 2010 },
{ Id = 1, Year = 2009 },
{ Id = 1, Year = 2008 },
{ Id = 2, Year = 2010 },
{ Id = 2, Year = 2009 },
{ Id = 2, Year = 2008 }}

I wish to retrieve a collection from this collection of the most recent item for each Id. What will the Linq for this look like?
Desired output:
{{ Id = 1, Year = 2010 },
{ Id = 2, Year = 2010 }}

I have a naiive implementation using a second list variable and a foreach loop, but it's inefficient.
//naiive implementation "p-code"
//...
var mostRecentItems = new List<MyType>();
var ids = collection.Select(i => i.Id).Distinct();
foreach(var id in ids)
{
  mostRecentItems.Add(collection.Where(i => i.Id == id).OrderByDescending().First);
}

return mostRecentItems;

A: Most simply:
var mostRecentById = from item in list
                     group item by item.Id into g
                     select g.OrderByDescending(x => x.Year).First();

A: Group by id, then select the first item in each group ordered in a descending fashion.
 var mostRecentItems = collection.GroupBy( c => c.Id )
                                 .Select( g => g.OrderByDescending( i => i.Year ).First() );

A: or more simply still:
var result = list
                .GroupBy(i => i.Id)
                .Select(g => new {Id = g.Key, Year = g.Max(y => y.Year)});


text:
Q: Проблема с созданием экземпляра класса Только начинаю изучать PHP и ООП в целом. Проблема следующая: при попытке создать экземпляры player 1 и player 2 немного разными способами player 2 не создаётся. Подскажите, пожалуйста, в чём ошибка. Код прикладываю. Заранее спасибо.
<?php

class Player {

    private $name;
    private $city;

    public function __construct($name) {
        $this->name = $name;
    }

    public function setCity($city) {
        $this->city = $city;
    }

}

$player1 = new Player('Max');
$player1->setCity("Minsk");
var_dump ($player1);
echo'<br>';
$player2 = (new Player("Dmitry"))->setCity("Brest");
var_dump($player2);

что вижу при выводе:
object(Player)[1]
  private 'name' => string 'Max' (length=3)
  private 'city' => string 'Minsk' (length=5)

F:\WAMP\www\frintoProject\player.php:24:null

A: Если для второго случая нужен в качестве результата этот самый объект (например для "Fluid Interface"), то необходимо вернуть $this в методе setCity