Q: undefined reference yaml-cpp I'm on Manjaro Linux using gcc and codelite to compile my code.
It's a project with sfml and yaml-cpp in C++.
My GCC version is 4.9.2 (20150304)
GCC compiler flags are -pg;-g;-O0;-O2;-Wall;-std=c++14
My yaml-cpp version is 0.5.1-1
When I compile I have the followings errors:
/bin/sh -c '/usr/bin/make -j4 -e -f  "MyProject.mk"  all'
----------Building project:[ MyProject - Debug ]----------
/usr/bin/g++   -c  "/home/myuser/.codelite/MyProject/MyProject/sprite.cpp" -pg -g -O0 -O2 -Wall -std=c++14  -o ./Debug/sprite.cpp.o -I. -I/usr/include/
/usr/bin/g++   -c  "/home/myuser/.codelite/MyProject/MyProject/tile.cpp" -pg -g -O0 -O2 -Wall -std=c++14  -o ./Debug/tile.cpp.o -I. -I/usr/include/
/usr/bin/g++   -c  "/home/myuser/.codelite/MyProject/MyProject/main.cpp" -pg -g -O0 -O2 -Wall -std=c++14  -o ./Debug/main.cpp.o -I. -I/usr/include/
/usr/bin/g++   -c  "/home/myuser/.codelite/MyProject/MyProject/grid.cpp" -pg -g -O0 -O2 -Wall -std=c++14  -o ./Debug/grid.cpp.o -I. -I/usr/include/
/usr/bin/g++   -c  "/home/myuser/.codelite/MyProject/MyProject/loader.cpp" -pg -g -O0 -O2 -Wall -std=c++14  -o ./Debug/loader.cpp.o -I. -I/usr/include/
/usr/bin/g++  -o ./Debug/MyProject @"MyProject.txt" -L. -L/lib/  -lsfml-graphics -lsfml-window -lsfml-system -lsfml-network -lsfml-audio
./Debug/loader.cpp.o: in function « Mercenaries::Loader::Loader(std::string, std::vector<std::string, std::allocator<std::string> >) »:
/home/myuser/.codelite/MyProject/MyProject/loader.cpp:10: undefined reference to « YAML::LoadFile(std::string const&) »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::set_null() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:34: undefined reference to « YAML::detail::node_data::set_null() »
./Debug/loader.cpp.o: in function « YAML::Node::AssignNode(YAML::Node const&) »:
/usr/include/yaml-cpp/node/impl.h:270: undefined reference to « YAML::detail::memory_holder::merge(YAML::detail::memory_holder&) »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::mark_defined() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o: in function « YAML::detail::memory_holder::create_node() »:
/usr/include/yaml-cpp/node/detail/memory.h:30: undefined reference to « YAML::detail::memory::create_node() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::mark_defined() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o:/usr/include/yaml-cpp/node/detail/node_ref.h:29: more undefined reference follow to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::set_null() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:34: undefined reference to « YAML::detail::node_data::set_null() »
./Debug/loader.cpp.o: in function « YAML::Node::AssignNode(YAML::Node const&) »:
/usr/include/yaml-cpp/node/impl.h:270: undefined reference to « YAML::detail::memory_holder::merge(YAML::detail::memory_holder&) »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::mark_defined() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o: in function « YAML::detail::memory_holder::create_node() »:
/usr/include/yaml-cpp/node/detail/memory.h:30: undefined reference to « YAML::detail::memory::create_node() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::mark_defined() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o: in function « YAML::detail::memory_holder::create_node() »:
/usr/include/yaml-cpp/node/detail/memory.h:30: undefined reference to « YAML::detail::memory::create_node() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::mark_defined() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::set_null() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:34: undefined reference to « YAML::detail::node_data::set_null() »
/usr/include/yaml-cpp/node/detail/node_ref.h:34: undefined reference to « YAML::detail::node_data::set_null() »
./Debug/loader.cpp.o: in function « YAML::detail::memory_holder::create_node() »:
/usr/include/yaml-cpp/node/detail/memory.h:30: undefined reference to « YAML::detail::memory::create_node() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::mark_defined() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o:/usr/include/yaml-cpp/node/detail/node_ref.h:29: more undefined reference follow to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o: in function « YAML::detail::node& YAML::detail::node_data::get<std::string>(std::string const&, boost::shared_ptr<YAML::detail::memory_holder>) »:
/usr/include/yaml-cpp/node/detail/impl.h:89: undefined reference to « YAML::detail::node_data::convert_to_map(boost::shared_ptr<YAML::detail::memory_holder>) »
./Debug/loader.cpp.o: in function « YAML::detail::memory_holder::create_node() »:
/usr/include/yaml-cpp/node/detail/memory.h:30: undefined reference to « YAML::detail::memory::create_node() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::mark_defined() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::set_scalar(std::string const&) »:
/usr/include/yaml-cpp/node/detail/node_ref.h:35: undefined reference to « YAML::detail::node_data::set_scalar(std::string const&) »
./Debug/loader.cpp.o: in function « convert_to_node<std::basic_string<char> > »:
/usr/include/yaml-cpp/node/detail/impl.h:162: undefined reference to « YAML::detail::memory_holder::merge(YAML::detail::memory_holder&) »
./Debug/loader.cpp.o: in function « YAML::detail::memory_holder::create_node() »:
/usr/include/yaml-cpp/node/detail/memory.h:30: undefined reference to « YAML::detail::memory::create_node() »
./Debug/loader.cpp.o: in function « YAML::detail::node& YAML::detail::node_data::get<std::string>(std::string const&, boost::shared_ptr<YAML::detail::memory_holder>) »:
/usr/include/yaml-cpp/node/detail/impl.h:102: undefined reference to « YAML::detail::node_data::insert_map_pair(YAML::detail::node&, YAML::detail::node&) »
./Debug/loader.cpp.o: in function « YAML::detail::memory_holder::create_node() »:
/usr/include/yaml-cpp/node/detail/memory.h:30: undefined reference to « YAML::detail::memory::create_node() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::mark_defined() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::set_null() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:34: undefined reference to « YAML::detail::node_data::set_null() »
./Debug/loader.cpp.o: in function « YAML::detail::memory_holder::create_node() »:
/usr/include/yaml-cpp/node/detail/memory.h:30: undefined reference to « YAML::detail::memory::create_node() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::mark_defined() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::set_null() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:34: undefined reference to « YAML::detail::node_data::set_null() »

Loader.cpp
#include <yaml-cpp/yaml.h>
#include <fstream>
#include <iostream>
#include "loader.hpp"

namespace Mercenaries
{
    Loader::Loader(std::string config_path, std::vector<std::string> fields_list) : m_config_path(config_path), m_fields_list(fields_list)
    {
        m_config_file = YAML::LoadFile(m_config_path);
    }

    void Loader::parse_file()
    {
        // if the file exist
        if(!m_config_file.IsNull())
        {
            //the first node is the file
            YAML::Node current_node = m_config_file;

            // we get the next node
            YAML::Node node = move_into_node(current_node, "Grid");

            // get the data inside the node
            auto data = node;
        }
        else
        {
            // the file doesn't exist
            std::cout << "Failed to load " << m_config_path << " settings file.";
        }
    }

    YAML::Node Loader::move_into_node(YAML::Node current_node, std::string next_node)
    {
        YAML::Node node;

        // we verify that the node exist
        if(current_node[next_node])
        {
            node = current_node[next_node]; // get the value
        }
        else
        {
            // the node doesn't exist in the yaml file
            std::cout << next_node << " node is not found in " << m_config_path << " goal file";
        }

        return(node);
    }
}

Loader.hpp
#ifndef DEF_LOADER
#define DEF_LOADER

#include <yaml-cpp/yaml.h>

namespace Mercenaries
{
    class Loader
    {
        public:
            Loader(std::string config_path, std::vector<std::string> fields_list);
            void parse_file();
            YAML::Node move_into_node(YAML::Node current_node, std::string next_node);

        private:
            std::string m_config_path;
            YAML::Node m_config_file;
            std::vector<std::string> m_fields_list;
    };
}

#endif

Do you think that it's an yaml-cpp issue ?
Is there an error in my code that make it bug ?
Should I report it if it's a yaml issue ?

A: It looks like you're not linking to yaml-cpp; you need to add the argument -lyaml-cpp (to the command that begins /usr/bin/g++  -o ./Debug/MyProject).

A: If you are considering a CMakeLists.txt project ...
cmake_minimum_required(VERSION 3.10)
project(Test_yaml_cpp)

set(CMAKE_CXX_STANDARD 14)
# In case of third party library
#find_package(yaml-cpp PATHS ./thirparty/yaml-cpp/build)

# In case of installed library
find_package(yaml-cpp)
add_executable(yaml_exec main.cpp)
target_link_libraries(yaml_exec yaml-cpp)

In case of the third-party approach, the yaml-cpp library should be already built inside build folder and recommended by their documentation.

A: Try add following to your cmakelist:
find_package(PkgConfig REQUIRED)


Q: C# MySQL Connection problems I'm trying to connect a C# application (using Visual C# 2008 Express Edition) to a remote MySQL server. I have the drivers for this, but when I followed the tutorials (including adding the pooling and connection reset properties), I get an error that: Object reference not set to an instance of an object. I've included the two lines of code that should be making a connection. The error is thrown on the second line.
        MySqlConnection connect = new MySqlConnection("database=d*******;Data Source=mysql.netfirms.com;user id=*******;pwd=*****;pooling=false;connection reset=false");
        connect.Open();

A: I'd try setting the connection string outside of the constructor to help narrow down the issue:
MySqlConnection connect = new MySqlConnection();
//Do you get the null exception in this next line?
connect.ConnectionString = "your conn string here";
connect.Open(); //-> If you get the exception here then the problem is with the connection string and not the MySqlConnection constructor.

If you do get the exception in the connect.ConnectionString = ... line, then the problem is with the driver and sounds like you need to reinstall it.
I would also try a simpler connection string, without the pooling and reset keys.

A: Can you post more code? The exception line is probably a bit off due to compiler optimization or related. Constructors must return an object or throw an exception. It is impossible to say
MyType item = new MyType();
Debug.Fail(item == null); // will never fail.

The null reference is probably on the line just above your instantiation.


Q: g:submitButton- onclick doesn't work I have the following g:submitButton:
 <g:submitButton name="next" class="signup-button skyblue-btn pull-right pl-pr-36" value="${message(code:"buttons.ok")}" onclick="return showSpinnerSignUp()"/>

I define the showSpinnerSignUp() in the JS file:
$(function() {
    function showSpinnerSignUp(){
        $('.spinner-ctn').show();
        return true;
    }
});

The spinner is not displayed (the onclick doesn't work).

A: This is the default behaviour of a form submission in the browser. You have registered a showSpinnerSignUp() method on the click of a button while the click on that same button is responsible for submitting the enclosing form.
Since the browser's built-in behavior for submitting forms works by making a full roundtrip to the server, that immediately interrupts your code execution of onclick event because your browser is navigating away from your current page.
This can be simulated as if you had clicked your button and refreshed the page immediately. Your current setup might work when you deploy this to the production server, but the possibility of working this setup locally is low because a local development server used to run on a faster machine  so the page refresh time of form submission is quite faster.
To verify this happening, open your browser's console and call the method showSpinnerSignUp() directly (remember to remove it from $(function() {}) temporarily) and see if the spinner is showing up.
Also, there is an option to Preserve Logs which keeps the Javascript console logs even after page refresh. So, put a simple console.log() inside your method call and then try hitting that button. You'll see your method is called but no spinner is displayed due to form submission.


Q: iPhone/iPod Touch: application executable contains unsupported architeture(s): armv7s i'im seeing a problem releasing on AppStore my App!
The validation process say: "iPhone/iPod Touch: application executable contains unsupported architeture(s): armv7s"
this is my library linked:
CoreLocation (required)
Twitter (optional)
QuartzCore (required)
MapKit (required)
UIKit (required)
Foundation (required)
CoreGraphics (required)
libGoogleAnalytics.a (required)
libsqlite3.dylib (required)
CFNetwork (required)
I've also tryed to remove GoogleAnalytics Library but the problem is the same! Do you have any idea?
Thanks

A: Based on discussions at the Apple dev forums (https://devforums.apple.com/message/749949) it looks like this is a bug affecting a lot of people.  Probably due to a change in Apple's validations servers.
I was able to work around it by changing the build architecture in Build Settings from Standard(armv7,armv7s) to armv7 and rebuilding.  This should only have the effect that the compiled code is not optimized for iPhone 5.  It will still run, but may not be quite as fast as if it were compiled for armv7s.  I suspect the performance difference would be negligible in most cases.

A: This helped me:

Project -> Build Settings -> remove the architecture from "valid
  architectures" as well as setting the "Build Active Architecture Only"
  to Yes in the Project

A: I had the same problem today. My app has no third-party libraries.
12 days ago I submitted a build from Xcode 4.5.1 that was subsequently reviewed and released to the App Store. Today I tried to submit a new build and suddenly received this error.
I then tried to validate the same executable (not a rebuild) from within Xcode that I had submitted 12 days ago and that had passed validation and is now available for download in the App Store, but this time it failed validation with the above error.
Performing step 4 above allowed me to submit the new build. But the executable is smaller even though I have added a small amount of code and three small png/jpegs. This makes me think that armv7s code is missing from the archive.
What is happening? Why should step 4 above 'work'? Why does an executable that previously submitted OK and was released suddenly no longer pass validation?
Note: this is not a duplicate of any previous post that I was able to find 15 hours ago. This is the first time I have seen any mention made of seeing this error when submitting to iTunes Connect rather than receiving a compiler warning. So please do not mark this as a duplicate. It is not.

A: Most of the answers here are ones that I did not find ideal, mainly because they essentially suggest that you remove armv7s support from your app. While that will make you app pass validation, that could potentially make your app run slower on the iPhone 5.
Here is the workaround I'm using (though, I must say that I wouldn't call this a solution).
Instead of using XCode Organizer, I'm uploading the binary using Application Loader.
To upload the binary using Application Loader
Open Organizer > Right Click on Archive > Reveal in Finder.
Right Click the Archive file > Show Archive Content
Go to Products > Application > YourAPP.app
Compress YourAPP.app and upload using Application Loader.

A: My problem was the fact I was using an old version of Application Loader.
The solution for me was to download the latest version of Application Loader iTunes Connect > Manage Your Applications > Download Application Loader and try again.

A: Try this:
1.Select your project in Xcode (with the blue icon)
2.Select Build Settings
3.Set the view to All/Combined
4.Set "Build Active Architecture Only" to Yes


Q: Values from checkbox group are correct in querystring, but are not arrays in the $_GET variable I have a form, with a checkbox group which looks like this:
<input type="checkbox" name="countries" value="US" class="chkcountries" checked="checked" /> United States

<input type="checkbox" name="countries" value="FR" class="chkcountries" checked="checked" /> France

<input type="checkbox" name="countries" value="CA" class="chkcountries" checked="checked" /> Canada

<input type="checkbox" name="countries" value="AU" class="chkcountries" checked="checked" /> Australia

<input type="checkbox" name="countries" value="UK" class="chkcountries" checked="checked" /> United Kingdom

<input type="checkbox" name="countries" value="DE" class="chkcountries" checked="checked" /> Germany

<input type="checkbox" name="countries" value="Ja" class="chkcountries" checked="checked" /> Japan

<input type="checkbox" name="countries" value="IT" class="chkcountries" checked="checked" /> Italy

<input type="checkbox" name="countries" value="IN" class="chkcountries" checked="checked" /> India

<input type="checkbox" name="countries" value="ES" class="chkcountries" checked="checked" /> Spain

<input type="checkbox" name="countries" value="BR" class="chkcountries" checked="checked" /> Brazil

<input type="checkbox" name="countries" value="NL" class="chkcountries" checked="checked" /> Netherlands

<input type="checkbox" name="countries" value="MX" class="chkcountries" checked="checked" /> Mexico

When I select more than one country and run the form and print_r both the query string and the $_GET array, the querystring looks like this:

report=rawdata&sales=sales&kenp=kenp&startdate=&enddate=&format=table&track=unit&countries=US&countries=CA&countries=AU&countries=UK&allchannels=All&channels=2&channels=1&books=5&submit=Get+Report

and the $_GET array looks like this:

Array ( [report] => rawdata [sales] => sales [kenp] => kenp [startdate] => [enddate] => [format] => table [track] => unit [countries] => UK [allchannels] => All [channels] => 1 [books] => 5 [submit] => Get Report [SQLiteManager_currentLangue] => 2 )

As you can see, it's only selecting the last item in the countries array. (The same thing happens in checkbox groups on this form, e.g. channels).
I'm working in a test environment running MAMP on my Mac, FWIW.
What's weird is that it was working properly. (I've tried rebooting MAMP and then rebooting my entire system to see if that makes a difference, and it doesn't seem to.)
It's possible I've missed something dumb somewhere, but I've now been looking at it so long, I'm going cross-eyed. Any assistance would be greatly appreciated.

A: I think that you need to do an array for your select :
<select name="countries[]" multiple>

And then deal with the array in your php code.

A: PHP determines if form data should be presented as a string or an array based on the name of the field, not the number of times it appears.
Append [] to the name attribute in the HTML.


Q: Import SQL File into existing DB-Table (phpmyadmin) I have an SQL-File defining a table with 2 columns - product-id and product-reference. I need to import that file into an existing table that has the same structure (plus some extra columns), where product-id corresponds to the product-id from the backup file. Is there a simple way to do that via phpmyadmin?

A: One approach is to use load data infile (see here) with the set option to assign column values.  Columns that are not being set will be given their default values, which is typically NULL.
Personally, I would load the data into a staging table with two columns and then insert the data from the staging table into the final table.  This makes it easier to validate the data before putting it into the "real" table.


Q: C++ gdb breakpooint in second thread causing core dump I have a C++ program I'm trying to debug in a new docker instance that is causing the program to crash when I try to hit a breakpoint in a created thread (but not the launch thread). Another version of the program run on a separate computer (different g++, gdb versions) works. I've created a test app to replicate the problem.
I'm using a ubuntu docker image (which is new to me). I've started a docker container with:
docker run -it -v "/home/test/":"/home/test" -w "/home/test" ubuntu

I've attached to this container in VS Code, in the /home/test/ folder. I've then installed g++ and gdb with: apt-get update then apt-get install g++ gdb.
This installs versions g++: 4:11.2.0-1ubuntu1 gdb: 12.0.90-0ubuntu1
I then create a main.cpp with the following code:
#include <iostream>
#include <chrono>
#include <thread>

void thread_runner()
{
    while (1) {
        std::cout << "Background Thread" << std::endl;                //Second Breakpoint
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }
}

int main()
{
    std::cout << "Test App" << std::endl;                              // First Breakpoint
    std::thread ioc_thread = std::thread(thread_runner);                    // Create a separate (background) thread to run the io_context on
    ioc_thread.join();
}

And I set breakpoints on the 2 std::cout ... lines.
I create a tasks.json file to compile this, which looks like:
{
    "tasks": [
        {
            "type": "cppbuild",
            "label": "C/C++: g++ build active file",
            "command": "/usr/bin/g++",
            "args": [
                "-fdiagnostics-color=always",
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": "build",
            "detail": "Task generated by Debugger."
        },
    ],
    "version": "2.0.0"
}

Then I run the command "Run and Debug" and use that task to compile. I hit the first breakpoint at "Test App" okay but it crashes before hitting "Background Thread", the terminal output is:
Test App
Aborted (core dumped)
[1] + Aborted (core dumped)      "/usr/bin/gdb" --interpreter=mi --tty=${DbgTerm} 0<"/tmp/Microsoft-MIEngine-In-mv2ltsxy.3ok" 1>"/tmp/Microsoft-MIEngine-Out-0zvvty3q.t43"

If I remove the second breakpoint the app runs printing "Background Thread" every second.
Apologies for the long winded description. I'm not sure where I'm going wrong so I looked to include everything. The other computer that appears to work (using my full original program) using g++ 9.3 and gdb 8.1.

A: I had a similar issue where my program would coredump when there was a breakpoint present in a thread. I found out that my instance of gdb (12.0.9) was not working, and installing 12.1 from launchpad fixed my issue.
Found solution here


Q: Azure giving subscription level resource group access to application I created a application in active directory and gave access to it at the resource group level and I am able to access the resources inside the resource group. But I don't see any option in preview portal to give access to the application at the subscription level.
When I am running the following code
ResourceManagementClient client =
testMain.createResourceManagementClient();
ResourceGroupOperations gpoperations = client.getResourceGroupsOperations();
ResourceGroup gp1 = new ResourceGroup("West US");
ResourceGroupCreateOrUpdateResult res = gpoperations.createOrUpdate("test123", gp1);
System.out.println("Resource group creation result" + res.getRequestId()+res.toString());

I am getting the following exception

Exception in thread "main"
  com.microsoft.windowsazure.exception.ServiceException:
  AuthorizationFailed: The client '2e027029-1019-46dc-b540-cbfe4a761647'
  with object id '2e027029-1019-46dc-b540-cbfe4a761647' does not have
  authorization to perform action
  'Microsoft.Resources/subscriptions/resourcegroups/write' over scope
  '/subscriptions/88335ad5-6fe2-4532-b3d5-1af946310f85/resourcegroups/test123'.
      at com.microsoft.windowsazure.exception.ServiceException.createFromJson(ServiceException.java:292)
      at com.microsoft.azure.management.resources.ResourceGroupOperationsImpl.createOrUpdate(ResourceGroupOperationsImpl.java:495)
      at com.mycompany.resourcegroup.testMain.main(testMain.java:70)

How can i give access to the application, so that it can create and manage any resource group in my subscription ?

A: *

*GO to your Azure Active Directory

*Click on Groups

*Click “+ New Group”

*Select the group type “Security”

*Enter group name (any name you want)

*Select Membership type “Assigned”

*In the owner select the owner of the application

*In the members select the application that you created/registered in the active directory.

*Now you are able to create your resources directly from your java client.


Q: CentOS 6 not displaying I installed CentOS on Oracle VirtualBox and it run perfectly fine on command line but then I installed desktop environment by typing the following command:
yum groupinstall "X windows system" "KDE Desktop", edit the initdefault id from 3 (command line) to 5 (GUI), save the file and reboot the system but it doesn't display the login screen, in fact it hangs on loading. . Please help me out in this.
I can't attach the image as the message pops up stating that i need at least 10 reputation to post images...
I will write down the last two lines when it hangs..
Starting postfix :      [OK]
Starting httpd:         [OK]
Starting crond:         [OK]

Thanks.

A: It seems that some yum commands are case sensitive (atleast install and groupinstall), so the correct command is
$ yum groupinstall "X Window System" "KDE Desktop"


Q: Select sub element based on classes it has Below is the HTML that I have

    See Stats

    See Stats

    See Stats

I want to find this unordered list, then tell which item has the starting qb class and then return the class that has their name (brady rodger manning) etc.
What's throwing me in a loop is the fact that the link is wrapped in the list element.
Here is what I am trying:
element = $("#qbs"); // pretty sure I want this vs getElementbyDocumentID
children = element.children();` // gets me all the list elements

for (i=0;i<children.length;i++) {
  grandchild = children[i].children();
  ???? How would I get the 3rd class on this element?
}

Sorry about the formatting.

A: How about this?
var allClasses = $("#QBS").find('li a[class^="qb_"]')
     .map(function () {
          return this.className.split(" ").pop();
}).get();
console.log(allClasses);

Fiddle
Provided the class started with qb_* is at the beginning and you want to take only the last class of the match.
if all your class names are qb_mode then:
var allClasses = $("#QBS").find('.qb_mode').map(function () {
    return this.className.split(" ").pop();
}).get();

if you want all of them then:
var allClasses = $("#QBS").find('.qb_mode').map(function () {
    var cls = this.className.replace(/qb_mode/,'');
    return cls.trim().split(/\W+/);
}).get();
console.log(allClasses);

Fiddle

A: If I understood you correctly, how about:
var name = $('#QBS a.qb_mode.starting').prop('class').replace(/\s*(qb_mode|starting)\s*/g,'');
console.log(name); // Rogers

See demo here.

A: a=document.getElementById('QBS');
var b=a.getElementsByClassName("qb_mode");
var i, j=b.length, result=[];
for(i=0;i<j;i++) {
  c=b[i].className.split(" ");
  result.push(c.pop());
}
return result;

A: fiddle http://jsfiddle.net/3Amt3/
var names=[];

$("#QBS > li a").each(function(i){
    var a=$(this).attr("class").split(" ");
    names[i]=a[(a.length-1)];
    console.log("Name  is " + names[i]);
 });

or a more precise selector
 $("#QBS > li a.qb_mode").each( ....


Q: How to fetch with method GET And Type script I'm true beginner with type script
can you help me with this simple fetch
this is function
export async function askForList(){
   return await fetch('http://127.0.0.1:3333/applist').then((res) => res.json())
}

this is expected data
interface RnMcharacter{
    id: number,
    img: string,
    name: string,
    number: number
};

I'v tried many combination but moast common error is
ERROR in src/transmission/apiserv.ts:27:4
@typescript-eslint/no-unsafe-return: Unsafe return of an any typed value.
Can you show me example of proper function so I can understad what mi doing wrong.
Thx

A: You can type the data prop as RnMcharacter.
You can also remove the then call as you're using async|await
export async function askForList(){
  const res = await fetch('http://127.0.0.1:3333/applist');
  const { data }: { data: RnMcharacter } = await res.json();
  return data;
}


Q: Akka cluster error Is it mandatory to use sbt for cluster usage in akka. I have tried to add a few jars to the classpath. While the compiling goes well, running the relevant class generates an error.

scala -cp
  ../akka-2.2.1/lib/akka/akka-cluster_2.10-2.2.1.jar:../akka-2.2.1/lib/akka/netty-3.6.6.Final.jar:../akka-2.2.1/lib/akka/akka-remote_2.10-2.2.1.jar:../akka-2.2.1/lib/akka/protobuf-java-2.4.1.jar:./
  TransformationFrontend 2551

here's the issue encountered:

java.lang.NoSuchMethodException:
  akka.cluster.ClusterActorRefProvider.(java.lang.String,
  akka.actor.ActorSystem$Settings, akka.event.EventStream,
  akka.actor.Scheduler, akka.actor.DynamicAccess)   at
  java.lang.Class.getConstructor0(Class.java:2800)  at
  java.lang.Class.getDeclaredConstructor(Class.java:2043)

This is the official Akka cluster example. Can someone throw some light on my query?

A: The issue here is probably that you have an akka-actor.jar in your scala distributuion that is Akka 2.1.x and you're trying to use Akka 2.2.x.
You'll have to run your code by running the java command and add the scala-library.jar and the correct akka-actor.jar and typesafe-config.jar to the classpath.

A: Are you using Scala 2.10? This is the Scala version you need for Akka 2.2.
What does the following yield?

scala -version

It should show something like

$ scala -version
Scala code runner version 2.10.3 -- Copyright 2002-2013, LAMP/EPFL


Q: actionscript facebook get url of uploaded image using the latest facebook actionscript library, I upload an image using:
Facebook.api('me/photos', etc...)
it returns an ID, which method would I call to get the url of the uploaded image?
Thanks.

A: Looks like it's a simple REST service call:  https://graph.facebook.com/10150146071831729
Take a look at the "Example" at the bottom of this page:  https://developers.facebook.com/docs/reference/api/photo/


Q: My worker threads are not being picked up I'm implementing worker threads in my Node/Typescript application. Now I've come quite far except for the fact that it seems my worker threads are not being picked up/executed. I've added some loggers inside function which should be executed by the worker thread, but for some reason it doesn't show.
I'm calling a function to create a worker. Like this:
create_worker("./src/core/utils/worker.js", {
        term: "amsterdam",
        search_grid: chunked_maps_service![i],
        path: "../../adapters/worker.ts",
})

And this is the function to create a worker:
import { Worker } from "worker_threads";

const create_worker = (file: string, workerData: {}) =>
  new Promise<void>((resolve, reject) => {
    const worker = new Worker(file, {
      workerData: workerData,
    });

    worker.on("message", resolve);
    worker.on("error", reject);
    worker.on("exit", (code) => {
      if (code !== 0)
        reject(new Error(`Worker stopped with exit code ${code}`));
    });
  });

export default create_worker;

Because I'm using typescript I need to compile the typescript code to javascript code to make the worker understand it: Like this:
const path = require("path");
const { workerData } = require("worker_threads");

require("ts-node").register();
require(path.resolve(__dirname, workerData.path));

And then this is the function which should be executed in the worker thread:
import { parentPort } from "worker_threads";

async function worker() {
  console.log("started");
  parentPort.postMessage("fixed!");
}

Is there anything I'm forgetting?

A: You aren't ever calling the function in your worker.
This code in the worker:
import { parentPort } from "worker_threads";

async function worker() {
  console.log("started");
  parentPort.postMessage("fixed!");
}

Just defines a function named worker.  It never calls that function.
If you want it called immediately, then you must call it like this:
import { parentPort } from "worker_threads";

async function worker() {
  console.log("started");
  parentPort.postMessage("fixed!");
}

worker();

FYI, in the worker implementations I've built, I usually either execute something based on data passed into the worker or the worker executes something based on a message it receives from the parent.


Q: Issues with validation in rails I have a working validation on my user model. But since we're discovered that users tend to give up during their long registration form, we've split up registration form into steps so that user can give up any time and still use the site.
I'm having issues with the first step of user registration with validations. Here is the relevant bit of my User model :
with_options :if => lambda { |u| u.current_step == "get_started" } do |user|
    user.validates :firstname, presence: true, length: { maximum: 50 }
    user.validates :surname, presence: true, length: { maximum: 50 }
    user.validates :email, presence:   true,
              format:     { with: VALID_EMAIL_REGEX }

    user.validates :password_digest, presence: true
    user.validates :password, length: { minimum: 6 }
end

This validation works perfectly. However we now added facebook so its possible to login with facebook and we have hidden fields in our form facebook_uid. So I want to validate password only if these fields are nil.
Here is how I tried to modify my current validation :
with_options :if => lambda { |u| u.current_step == "get_started" } do |user|
   user.validates :firstname, presence: true, length: { maximum: 50 }
   user.validates :surname, presence: true, length: { maximum: 50 }
   user.validates :email, presence:   true,
        format:     { with: VALID_EMAIL_REGEX }

   with_options :if => lambda { |u| u.facebook_uid.nil? } do |user|
     user.validates :password_digest, presence: true
   end

   with_options :if => lambda { |u| u.user.password_digest_changed? && !u.password.nil? } do |user|
    user.validates :password, length: { minimum: 6 }
   end
end

Or inline (the relevant password part only) :
user.validates :password_digest, presence: true, if: lambda { |u| u.facebook_uid.nil? }
user.validates :password, length: { minimum: 6 }, if: lambda { |u| u.user.password_digest_changed? && !u.password.nil? }

None of these worked for me, whatever I tried I get this error :
undefined method `user' for #<User:0x00000008e924a8>

Again if I remove ifs and lambdas works as charm. Is there another way of accomplishing this or something I'm currently doing wrong with my code?

A: In your password validation lambda, you're calling
u.user.password_digest_changed? && !u.password.nil?

ie, you're sending a user method to the u object, which is your User instance. That object doesn't respond to user. You probably just want
u.password_digest_changed? && !u.password.nil?


Q: Navigation Drawer does not cover an activity I am writing an organiser app and I am stuck at this problem. Navigation drawer stacks itself with the listview in activity 1 . There is no exception and the app is working, but the listview elements and navigation drawer elements are clicked at the same time.
Here is the activity layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".EventActivity">

<androidx.drawerlayout.widget.DrawerLayout
    android:id="@+id/my_drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:ignore="HardcodedText">

  <com.google.android.material.navigation.NavigationView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:menu="@menu/navigation_menu" />

</androidx.drawerlayout.widget.DrawerLayout>

<ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/list"/>

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="20dp"
    android:layout_alignParentEnd="true"
    android:layout_alignParentBottom="true"
    />

</RelativeLayout>

A: DrawerLayout should be the parent of your layout. Here`s my example:
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mDrawer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="false"
    tools:openDrawer="end">

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   >
    //my code

</androidx.constraintlayout.widget.ConstraintLayout>

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/navrapoarte"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"

      >
    //my code
        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:minHeight="200dp"
            android:orientation="vertical">

        </androidx.constraintlayout.widget.ConstraintLayout>

    </com.google.android.material.navigation.NavigationView>
</androidx.drawerlayout.widget.DrawerLayout>


Q: Click “Accept Cookies” popup with Selenium in Python I've been trying to scrape some information of this E-commerce website with selenium. However when I access the website I need to accept cookies to continue. This only happens when the bot accesses the website, not when I do it manually. When I try to find the corresponding element either by xpath, as I find it when I inspect the page manually I always get this error message:

selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document

My code is mentined below.
import time
import pandas
pip install selenium
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
from bs4 import BeautifulSoup #pip install beautifulsoup4

PATH = "/Users/Ziye/Desktop/Python/chromedriver"
delay = 15

driver = webdriver.Chrome(PATH)
driver.implicitly_wait(10)

driver.get("https://en.zalando.de/women/?q=michael+michael+kors+taschen")
driver.find_element_by_xpath('//*[@id="uc-btn-accept-banner"]').click()

This is the HTML corresponding to the button "That's ok". The XPATH is as above.
<button aria-label="" id="uc-btn-accept-banner" class="uc-btn uc-btn-primary">
                          That’s OK
                      </button>

Does anyone know where my mistake lies?

A: You should add explicit wait for this button:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

driver = webdriver.Chrome(executable_path='/snap/bin/chromium.chromedriver')
driver.implicitly_wait(10)

driver.get("https://en.zalando.de/women/?q=michael+michael+kors+taschen")
wait = WebDriverWait(driver, 15)
wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="uc-btn-accept-banner"]')))
driver.find_element_by_xpath('//*[@id="uc-btn-accept-banner"]').click()

Your locator is correct.
As css selector, you can use .uc-btn-footer-container .uc-btn.uc-btn-primary


Q: Inverse process of :keys destructuring: construct map from sequence The more I write in Clojure, the more I come across the following sort of pattern:
(defn mapkeys [foo bar baz]
   {:foo foo, :bar bar, :baz baz})

In a certain sense, this looks like the inverse process that a destructuring like
(let [{:keys [foo bar baz]}] ... )

would achieve.
Is there a "built-in" way in Clojure to achieve something similar to the above mapkeys (mapping name to keyword=>value) - perhaps for an arbitrary length list of names?

A: No such thing is built in, because it doesn't need to be. Unlike destructuring, which is fairly involved, constructing maps is very simple in Clojure, and so fancy ways of doing it are left for ordinary libraries. For example, I long ago wrote flatland.useful.map/keyed, which mirrors the three modes of map destructuring:
(let [transforms {:keys keyword
                  :strs str
                  :syms identity}]
  (defmacro keyed
      "Create a map in which, for each symbol S in vars, (keyword S) is a
  key mapping to the value of S in the current scope. If passed an optional
  :strs or :syms first argument, use strings or symbols as the keys instead."
    ([vars] `(keyed :keys ~vars))
    ([key-type vars]
       (let [transform (comp (partial list `quote)
                             (transforms key-type))]
         (into {} (map (juxt transform identity) vars))))))

But if you only care about keywords, and don't demand a docstring, it could be much shorter:
(defmacro keyed [names]
  (into {}
        (for [n names]
          [(keyword n) n])))

A: I find that I quite frequently want to either construct a map from individual values or destructure a map to retrieve individual values.  In the Tupelo Library I have a handy pair of functions for this purpose that I use all the time:
(ns tst.demo.core
  (:use demo.core tupelo.core tupelo.test))

(dotest
  (let [m {:a 1 :b 2 :c 3}]
    (with-map-vals m [a b c]
      (spyx a)
      (spyx b)
      (spyx c)
      (spyx (vals->map a b c)))))

with result
; destructure a map into values
a => 1
b => 2
c => 3

; construct a map
(vals->map a b c) => {:a 1, :b 2, :c 3}

P.S.  Of course I know you can destructure with the :keys syntax, but it always seemed a bit non-intuitive to me.


Q: Inconsistent date between SSAS Cube and Tabular Model I have a very weird problem. I have built a tabular model which takes data from a SSAS cube. In the data source cube, there is a column called "Process Date" and it is in UK date format (dd/mm/yyyy). When I bring this column into my model, the dates are messed up, where the date and month values are swapped for some dates!
Below are the images to illustrate this and I have highlighted one particular date in red. In the data source SSAS cube, the date is 12/02/2019, and when it goes to the tabular model, this date beomces 02/12/2019. I have added a check_month column in the tabular model and found that the tabular model thinks its December i.e. the day/month has been swapped!
data source date
model date
Thank you
JC
Edit: This has been solved by changing the Locale Identifier in the connection. See the comment in the answer below by userfl89. This is due to the data source cube is using a different locale (US English) then what I am using in the model, changing the locale identifier will override this and hence solve the problem

A: The date format can be defined from SSDT.  Highlight the date column and go to the properties window (press F4).  For the Data Format property select the desired date format.  If you need a date format that's not listed a calculated column using the FORMAT function can be created based off the original column, with the data type of this column then set to Date.  An example of this is below.  Additionally, confirm the Locale Identifier (LCID) in SSDT.  This can by viewed by selecting Model > Existing Connections > Edit > Build > All > then the Locale Identifier property.  The Microsoft documentation provides details in regards to identifying the correct LCID.
=FORMAT('Process'[Process Date], "dd-MM-yyyy")


Q: How to properly consume a WCF Web Service in a Classic Xamarin Solution? I'm following the documentation on Consuming a WCF Web Service and need clarification on how best to do this in a Classic Xamarin (not Xamarin Forms) solution that uses a .NET Standard library.
Specifically, I need to understand whether separate API calls must be wrapped in the interface class e.g. ISoapService so that they can be made asynchronously?  The project already as an auto-generated Reference.cs class that documents all the available web service endpoints.  Does the interface class need to include all potential API calls?
How do ensure that my interface class is properly referenced from the Xamarin.Android and Xamarin.IOS projects?  Is there something specifically required aside from referencing the .NET Standard Project from the mobile projects?
I've looked high and low for WCF web service integration with Classic Xamarin but have not found any helpful samples Any links would be helpful.


Q: Thread scheduling in .NET regarding blocking calls Suppose I spawn 3 threads in a C# application: T1, T2 and T3 and issue Run calls for each.
Usually, the processor will schedule the threads in a round-robin fashion (single processor and all threads have same priority).
However, suppose Thread T1 issues a Blocking web service call.
Will it be preempted immediately or after completion of its time slice?
Basically does issuing the web service network call (or any other call) cause the thread to be in a blocked state?

A: Once a thread issues a blocking system call (any request to IO) it is suspended, and only marked as "Ready" (not yet running) when that system call completes.
So yes it will be preempted immediately.


Q: android : LayoutInflater in static method i want to call LayoutInflater from static method as below :
    private static void inflateLayout_keluarga_pp(int counter2, String name) {
            LayoutInflater inflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.layoutkeluarga, null);
..................
..................
}

this is how i call method inflateLayout_keluarga_pp :
    public static void onRetrieve(int position){
    List<ModelKeluargaPP> mk = helper.getSelectTable_Marital();
        for (int i=0; i<mk.size();i++){
        inflateLayout_keluarga_pp(i,mk.get(position).getAnggota_pp());

  }
}

but i got error in getActivity(), they said : Cannot make a static reference to the non-static method getActivity() from the type Fragment i need to make this method into static. how to fix it? i hope someone can help to solve my problem, thank you.

A: getActivity() belongs to the instance of the current Fragment; it cannot be part of a static context.
When you declare a method static, you are stating that this method will not belong to each particular instance of the Class; it belongs to the Class itself. Since the static method will be available regardless if you instantiate an object of the Class, you cannot guarantee that object members and methods (that are not static) will be available. Hence you cannot reference "things" that will be available only when the object is instantiated inside a static method that will always be available.
Like Jems said, if you need to access the Fragment you need to always make it available within the method's scope. This can be accomplished by either passing a Fragment to the static method or by instantiating it inside the static method.

A: If it must be static, pass a reference to the Fragment you want to call getActivity on into the method.
private static void inflateLayout_keluarga_pp(int counter2, String name, Fragment myFragment) {
            LayoutInflater inflater = (LayoutInflater)myFragment.getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);


Q: Create a Mobile Responsive Version of a PowerBI report that is Published to the Web I've recently published a specific PowerBI report and despite creating a 'Phone' View on PowerBI Desktop this didn't show up in the final embed code.
I've looked into PowerBI Embedded Playground and managed to generate the relevant access tokens and even try it out, but still couldn't figure out how to modify the code in such a way to generate a mobile view.
The questions and answers below somehow didn't give me the insight I needed, still somehow need some additional work:
Mobile view is not being shown for embedded powerbi report
Create Report in Embed View via PowerBI API
Power BI RS web embedding in mobile web browser
What do I need to do to get started? Which documentation do I need to look into exactly? I need to embed this report in a Sharepoint 2010 Page and I need it to be mobile responsive on page load and not via a seperate link.

A: This isn't related to the access token in any way. It is generated before configuring the embedding process. To embed the report in phone view, you must specify MobilePortrait layout type in the embed configuration, i.e. something like this:
var config = {
    .....
    settings: {
        filterPaneEnabled: true,
        navContentPaneEnabled: true,
        layoutType: models.LayoutType.MobilePortrait <-- THIS ONE
    }
};

If you omit layoutType, it will be shown in the landscape view (i.e. like in the desktop). For more information about the configuration see Embed Configuration Details, and for embedding in general you should start from Embedding Basics.


Q: Replace NULL with SUBTOTAL and TOTAL in a ROLLUP I have tried to use IFNULL to replace the NULL fields returned by ROLLUP for subtotals and totals but it doesn't appear to be working.
Query:
select IFNULL(usergroups.name, 'GROUP') AS DEALER,
IFNULL(users.name, 'TOTAL') AS SERVICE_ADVISOR,
COUNT(DISTINCT vcrs.uid) AS COMPLETED,
..........
..........
and vcrs.vcrSubStatus = 4
group by DEALER, SERVICE_ADVISOR with ROLLUP;

Output:
DEALER          SERVICE_ADVISOR COMPLETED   IDENTIFIED  AUTHORISED
Aston Martin    Chris           3           664.56      0
Aston Martin    Graham          6           0           0
Aston Martin    (NULL)          15          664.56      0
Bentley         Sukraj          1           0           0
Bentley         Terry           4           0           0
Bentley         (NULL)          5           0           0
Jaguar          Emma            10          2448        1224
Jaguar          Paul            1           0           0
Jaguar          Simon           7           2754        918
Jaguar          (NULL)          18          5202        2142
(NULL)          (NULL)          2611        96591.62    42130.14

Desired Output:
DEALER          SERVICE_ADVISOR COMPLETED   IDENTIFIED  AUTHORISED
Aston Martin    Chris           3           664.56      0
Aston Martin    Graham          6           0           0
Aston Martin    TOTAL           15          664.56      0
Bentley         Sukraj          1           0           0
Bentley         Terry           4           0           0
Bentley         TOTAL           5           0           0
Jaguar          Emma            10          2448        1224
Jaguar          Paul            1           0           0
Jaguar          Simon           7           2754        918
Jaguar          TOTAL           18          5202        2142
GROUP           TOTAL           2611        96591.62    42130.14

A: To resolve the issue with COALESCE/IFNULL still returning NULL for the WITH ROLLUP placeholders, you need to GROUP BY the table column names, rather than the aliased column expressions.
The issue is caused by the GROUP BY clause being specified on the aliased column expressions, because the aliases are assigned after the column expression is processed.
Resulting in the WITH ROLLUP NULL placeholders not being in the recordset to be evaluated by COALESCE.
Meaning the aliases DEALER, SERVICE_ADVISOR in the GROUP BY do not exist until after IFNULL/COALESCE have already been executed.
See MySQL Handling of GROUP BY for more details.
Example DB-Fiddle
CREATE TABLE foo (
  `amount` INTEGER,
  `created` INTEGER
);

INSERT INTO foo
  (`amount`, `created`)
VALUES
  ('1', '2019'),
  ('2', '2019');

Query #1 (Reproduce Issue)
SELECT
    SUM(amount) AS amounts,
    COALESCE(created, 'Total') AS created_coalesce
FROM foo
GROUP BY created_coalesce WITH ROLLUP;

| amounts | created_coalesce |
| ------- | ---------------- |
| 3       | 2019             |
| 3       |                  |

Query #2 (Corrected)
SELECT
    SUM(amount) AS amounts,
    COALESCE(created, 'Total') AS created_coalesce
FROM foo
GROUP BY foo.created WITH ROLLUP;

| amounts | created_coalesce |
| ------- | ---------------- |
| 3       | 2019             |
| 3       | Total            |

Use-Case Specific
Example DB-Fiddle
SELECT
    COALESCE(usergroups.name, 'GROUP') AS DEALER,
    COALESCE(users.name, 'TOTAL') AS SERVICE_ADVISOR,
    COUNT(DISTINCT vcrs.uid) AS COMPLETED,
/* ... */
GROUP BY usergroups.name, users.name WITH ROLLUP;

Query #1 (Original)
SELECT
    COALESCE(usergroups.name, 'GROUP') AS DEALER,
    COALESCE(users.name, 'TOTAL') AS SERVICE_ADVISOR,
    COUNT(DISTINCT vcrs.uid) AS COMPLETED
/* ... */
GROUP BY DEALER, SERVICE_ADVISOR WITH ROLLUP;

| DEALER | SERVICE_ADVISOR | COMPLETED |
| ------ | --------------- | --------- |
| Foo    | Jane Doe        | 1         |
| Foo    | John Doe        | 1         |
| Foo    |                 | 2         |
|        |                 | 2         |

Query #2 (Corrected)
SELECT
    COALESCE(usergroups.name, 'GROUP') AS DEALER,
    COALESCE(users.name, 'TOTAL') AS SERVICE_ADVISOR,
    COUNT(DISTINCT vcrs.uid) AS COMPLETED
/* ... */
GROUP BY usergroups.name, users.name WITH ROLLUP;

| DEALER | SERVICE_ADVISOR | COMPLETED |
| ------ | --------------- | --------- |
| Foo    | Jane Doe        | 1         |
| Foo    | John Doe        | 1         |
| Foo    | TOTAL           | 2         |
| GROUP  | TOTAL           | 2         |

Considerations

*

*

With MySQL 5.7+ and ONLY_FULL_GROUP_BY enabled, selected
non-aggregate columns that are not specified in the GROUP BY clause
will fail.  Meaning the following query will not work as expected: DB-Fiddle
SELECT COALESCE(YEAR(foo), 'foo') /* ... */ GROUP BY YEAR(foo) WITH ROLLUP
-> ER_WRONG_FIELD_WITH_GROUP: Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'test.foo_bar.foo' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

*

COALESCE,
IFNULL,
IF(... IS NULL)
and CASE WHEN ... IS NULL
will all function
similarly. Where IFNULL is the proprietary to MySQL and is a less
functional replacement of COALESCE. As COALESCE can accept more
than two parameters to check against NULL, returning the first non-NULL value.
mysql> SELECT COALESCE(NULL, NULL, 1, NULL);
       -> 1

mysql> SELECT IFNULL(NULL, 1);
       -> 1

mysql> SELECT IF(NULL IS NULL, 1, '');
       -> 1

mysql> SELECT CASE WHEN NULL IS NULL THEN 1 END;
       -> 1

*

nullable columns in the GROUP BY as either aliases or column names, will result in the NULL values being
displayed as the WITH ROLLUP placeholder. This applies to using WITH ROLLUP in general. For example if
users.name can return NULL. DB-Fiddle
| DEALER | SERVICE_ADVISOR | COMPLETED |
| ------ | --------------- | --------- |
| Foo    | TOTAL           | 1         |
| Foo    | Jane Doe        | 1         |
| Foo    | John Doe        | 1         |
| Foo    | TOTAL           | 3         |
| GROUP  | TOTAL           | 3         |

Prevent NULL column values from being displayed
To ensure that nullable columns are not accidentally included, you would need to specify in the criteria to exclude them.
Example DB-Fiddle
SELECT
    COALESCE(usergroups.name, 'GROUP') AS DEALER,
    COALESCE(users.name, 'TOTAL') AS SERVICE_ADVISOR,
    COUNT(DISTINCT vcrs.uid) AS COMPLETED
FROM vcrs
LEFT JOIN users
ON users.id = vcrs.uid
LEFT JOIN usergroups
ON usergroups.id = users.group_id
WHERE vcrs.vcrSubStatus = 4
AND users.name IS NOT NULL
GROUP BY usergroups.name, users.name
WITH ROLLUP;

Result
| DEALER | SERVICE_ADVISOR | COMPLETED |
| ------ | --------------- | --------- |
| Foo    | Jane Doe        | 1         |
| Foo    | John Doe        | 1         |
| Foo    | TOTAL           | 2         |
| GROUP  | TOTAL           | 2         |

Since LEFT JOIN is used on the vcrs table, IS NOT NULL must be
applied to the WHERE clause, instead of the ON clause. As LEFT JOIN returns NULL for non-matching criteria. To circumvent the
issue, use an INNER JOIN to limit the resultset to only those with
matching ON criteria.

/* ... */
INNER JOIN users
ON users.id = vcrs.uid
AND users.name IS NOT NULL
/* ... */
WHERE vcrs.vcrSubStatus = 4
GROUP BY usergroups.name, users.name
WITH ROLLUP;

Include NULL columns values
To explicitly include nullable column values, without duplicating the WITH ROLLUP placeholder name, you would need to utilize a derived table subquery to substitute the NULL value as a textual value.
Example DB-Fiddle
SELECT
    COALESCE(v.usergroup_name, 'GROUP') AS DEALER,
    COALESCE(v.user_name, 'TOTAL') AS SERVICE_ADVISOR,
    COUNT(DISTINCT v.uid) AS COMPLETED
FROM (
  SELECT
      usergroups.name AS usergroup_name,
      COALESCE(users.name, 'NULL') AS user_name,
      vcrs.uid
  FROM vcrs
  LEFT JOIN users
  ON users.id = vcrs.uid
  LEFT JOIN usergroups
  ON usergroups.id = users.group_id
  WHERE vcrs.vcrSubStatus = 4
) AS v
GROUP BY v.usergroup_name, v.user_name
WITH ROLLUP;

Result
| DEALER | SERVICE_ADVISOR | COMPLETED |
| ------ | --------------- | --------- |
| Foo    | Jane Doe        | 1         |
| Foo    | John Doe        | 1         |
| Foo    | NULL            | 1         |
| Foo    | TOTAL           | 3         |
| GROUP  | TOTAL           | 3         |

You can also optionally replace the 'NULL' textual placeholder as desired and even display it as NULL.
SELECT
    COALESCE(v.usergroup_name, 'GROUP') AS DEALER,
    CASE v.user_name WHEN 'NULL' THEN NULL ELSE COALESCE(v.user_name, 'TOTAL') END AS SERVICE_ADVISOR,
    COUNT(DISTINCT v.uid) AS COMPLETED
FROM (
    /* ... */
) AS v
GROUP BY v.usergroup_name, v.user_name
WITH ROLLUP;

A: I'm only 2 years too late, but since I came across the same issue as @the_gimlet I thought I'd post the answer.
So don't know if this is a mySQL versioning or something, but using mysql 5.6 I get the same problem... ifnull will not replace the rollup 'nulls'.
Simply get around this by making your rollup a subquery, and doing the ifnulls in the main select... annoying to repeat the select, but it works!
e.g. for example above
SELECT
  IFNULL(`DEALER`, 'GROUP') AS DEALER,
  IFNULL(`SERVICE_ADVISOR`, 'TOTAL') AS SERVICE_ADVISOR,
  `COMPLETED`,
  /* .......... */
FROM (SELECT
        usergroups.name AS DEALER,
        users.name AS SERVICE_ADVISOR,
        COUNT(DISTINCT vcrs.uid) AS COMPLETED,
      /* .......... */
      AND       vcrs.vcrSubStatus = 4
      GROUP BY  DEALER, SERVICE_ADVISOR with ROLLUP);

A: Do you want something like this?
SELECT COALESCE(usergroups.name, 'GROUP') AS DEALER,
COALESCE(users.name, IF(usergroups.name IS NULL, 'TOTAL', 'SUBTOTAL')) AS SERVICE_ADVISOR,
COUNT(DISTINCT vcrs.uid) AS COMPLETED,
..........
..........
AND vcrs.vcrSubStatus = 4
GROUP BY DEALER, SERVICE_ADVISOR with ROLLUP;

Test:
mysql;root@localhost(playground)> select * from t;
+------+----------+-------+--------+
| id   | car      | state | tstamp |
+------+----------+-------+--------+
|    1 | toyota   | new   |   1900 |
|    2 | toyota   | old   |   1950 |
|    3 | toyota   | scrap |   1980 |
|    4 | mercedes | new   |   1990 |
|    5 | mercedes | old   |   2010 |
|    6 | tesla    | new   |   2013 |
+------+----------+-------+--------+
6 rows in set (0.04 sec)

mysql;root@localhost(playground)> select car, sum(tstamp) from t group by car with rollup;
+----------+-------------+
| car      | sum(tstamp) |
+----------+-------------+
| mercedes |        4000 |
| tesla    |        2013 |
| toyota   |        5830 |
| NULL     |       11843 |
+----------+-------------+
4 rows in set (0.03 sec)

mysql;root@localhost(playground)> select coalesce(car, 'huhu'), sum(tstamp) from t group by car with rollup;
+-----------------------+-------------+
| coalesce(car, 'huhu') | sum(tstamp) |
+-----------------------+-------------+
| mercedes              |        4000 |
| tesla                 |        2013 |
| toyota                |        5830 |
| huhu                  |       11843 |
+-----------------------+-------------+
4 rows in set (0.00 sec)

A: What you're looking for is a case statement.
What you're saying is that under a certain condition replace the found value with the one specified. You can use multiple when/then statements depending on how customised you'd like the replacements to be.
select IFNULL(usergroups.name, 'GROUP') AS DEALER,
case when(users.name is null) then 'TOTAL' else users.name end AS SERVICE_ADVISOR,
COUNT(DISTINCT vcrs.uid) AS COMPLETED,
..........
..........
and vcrs.vcrSubStatus = 4
group by DEALER, SERVICE_ADVISOR with ROLLUP;


Q: Laravel: One relation, multiple models I have a model "User", and each user has "Posts". Now there are different types of posts, like "TextPost", "VideoPost", etc.
I want to get all posts of a user like this:
$user->posts()->get()
This should return an array of objects with the correct class, so e.g. an array like this:
[App\VideoPost{}, App\TextPost{}]
I tried to use polymorphic relationships as described in the docs, but it doesn't work. Any ideas?

A: There isn't really a relationship type in Laravel for your specific use case. The easiest thing you can do in this case is create a separate hasMany relationship for each of your post types, and then write a function that returns a combination of all the results.
So you'd end up with something like this in your User class:
public function videoPosts()
{
  return $this->hasMany(App\VideoPost::class);
}

public function textPosts()
{
  return $this->hasMany(App\TextPost::class);
}

public function getPosts()
{
  return $this->textPosts->concat($this->videoPosts);
}

You can then just keep chaining concat calls for every other post type you may want to add.


Q: OpenXML excel sheet creation. Formula does not work automatically when I use Indirect to reference a list I am creating an excel template using OpenXML through c# for users to populate and import into our system.
Part of the process is for the user to select options from dropdowns and hidden columns are populated with the Id's of those selections using VLOOKUP formula. All of the ones with direct list references work fine.
I have one instance where the selection from a list called "Application Group" drives what list is used in the next column called "Application". This is done using the INDIRECT function in excel and works fine. The problem comes when trying to get the id for the dynamic list. I will post the code below but put simply opening the excel and selecting an option from application group correctly puts the correct list in Application. Selecting application does not populate the applicationid column automatically. If I select the applicationid column to see the formula is is fine. If I click into the edit box at the top of excel and then tab out of it the formula then triggers and will work from then on. Once again this is a VLOOKUP using the INDIRECT to creat the reference to the list.
I've done a few tests and it seems the INDIRECT is the issue as if I hard code the list name the vlookup triggers as it should.
I also removed the substitute functions but this did not make any difference.
I've checked the calculation mode on the column and it is set to automatic.
I've already searched online but found nothing relevant
                // Application Group
                cell = new Cell() { CellReference = "AI" + rownumber };
                cell.CellValue = new CellValue();
                cellFormula = new CellFormula()
                {
                    Text = "VLOOKUP(AH" + rownumber.ToString() + " ,ApplicationGroupList,2,FALSE)"
                };
                cell.CellFormula = cellFormula;
                row.Append(cell);

                // Application
                cell = new Cell() { CellReference = "AK" + rownumber };
                cell.CellValue = new CellValue();
                cellFormula = new CellFormula()
                {
                    Text = "VLOOKUP(AJ" + rownumber.ToString() + ",INDIRECT(SUBSTITUTE(SUBSTITUTE(AH" + rownumber.ToString() + ",\" \",\"\"),\"/\",\"\") & \"Id\") ,2,FALSE)"
                };
                cell.CellFormula = cellFormula;
                row.Append(cell);

There are no error messages and the formula is correct as simply clicking in the edit box triggers the formula and it works from then on. It seems like excel is not recognising it as a formula even though it was set up in the same way as others that work fine. See the code above. Application group works fine. Application doesn't but the formula created is fine syntactically and functionally.
Does anyone have any experience of something similar and how to get the formula to work as all the others do.

A: Ok well as seems often to be the case I've spent ages looking at this myself. Exhausted all the options, or so I thought. Just after I post this I think I'll just try this thing I've not had to do for any of the other formula just in case. Bingo!
So I had to add
cellFormula.CalculateCell = true;
And this seemed to solve the problem. Why I needed it I don't know as everything else seems to work without explicitly setting this flag but problem seems to be solved.


Q: Looking for distance history using google API (or other) I've been searching and i thought i could ask you directly in here.
I'm looking for an API (maybe Google) that does the same work as Google fit history API as of recording every distance you made and the transportation mode. It is not necessary for me to get the exact latitude or longitude by at least the number of kilometer/meter(or miles) made by day in cars/foot/run/bike by a user(using an Android App). Google fit History API is great but, if i'm correct, it only records physical activities such as foot/run/bike.
I've look for Google ActivityRecognitionClient API that gives me a way to know the transportation mode and confidence % for a certain time but still, i need to have the distance made with this transportation mode.
What i need is something like :
Date : 2019-04-24
Activity : 1
TransportationMode : Foot
distance : 10km

Date : 2019-04-24
Activity : 2
TransportationMode : car
distance : 100km
etc.

Any of you know a way to do this?

A: I don't know about an API that you can use. However I found a research paper on ML model that predicts travel mode on the basis of GPS information. If you have sufficient time to develop your own AI model you may try this:
AI model Predicting travel mode


Q: F# Type providers and Sky Biometry Has anyone used the F# type providers with Sky Biometry?
A majority of the calls work great with the type providers.  However, when I call the faces/recognize method, I am getting fails using both the Json and the Xml type provider.
Using the Json one, I declare the type like this:
type skybiometryJsonFaceRecognition = JsonProvider<"http://api.skybiometry.com/fc/faces/recognize.json?uids=default@ImageComparer&urls=https://lg2014dev.blob.core.windows.net/d69bdda9-d934-448c-acae-99019f3a564f/01ee184f-ff0b-426f-872a-cbc81ef58d90.jpg&api_key=XXXXX&api_secret=yyyyy">

When I try and use the type in my code, it is failing on the last part of the graph:
let recognition = skybiometryJsonFaceRecognition.Load(stringBuilder.ToString())

It should be:
recognition.Photos.[0].Tags.[0].Uids.[0].confidence

But instead I get:
recognition.Photos.[0].Tags.[0].Uids.[0].JsonValue

I then swapped over to the Xml type provider for just this one call and I am getting intellisense working:
let recognition = skybiometryXmlFaceRecognition.Load(stringBuilder.ToString())
recognition.Photos.Photo.Tags.Tag.Uids.Uid.Confidence

But when I run it, I get
System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.
Looking at the XML in a call from my browser, it sure looks fine to me:

Does anyone have any suggestions?  Thanks

A: Thanks to ntr's suggestion, I changed the type def to use local storage.  The Json TP then found all of the props and the actual call worked as expected.  Thanks everyone.


Q: How to do WHERE IN with sqlalchemy? Here is what I'm trying to do. The database is Postgres.
numbers is a Python set() or some other iterable.
session.execute(table.update().\
                        where(func.substring(table.c.number,1 ,5) in numbers).\
                        values(provider="testprovider")

The problem with this is that in numbers doesn't seem to work. It will work for a single number if I do something like where(func.substring(table.c.number,1, 5)== '12345')
I've googled a lot on how to do WHERE IN with sqlalchemy, but all of them are with a SELECT query or do use the .in_() function on the column itself. For example this answer: link
The documentation also says the .in_() only works on the columns.
So, I don't really know how to proceed here. How can I write this expression?

A: Ah nevermind, although the documentation doesn't say it, I can use the .in_() function on the result of func.substring.
So
where(func.substring(table.c.number, 1, 5).in_(numbers))

worked.


Q: JPA 2: mapping a map where the key is an entity, value is Boolean We are trying to map a relation where an entity has a map where the key is another entity and the value is a Boolean:
    @Id Long id;
    @ElementCollection
    @CollectionTable(name = "APPROVALS_PRODUCT_APPROVALS", joinColumns = @JoinColumn(name = "PRODUCT_APPROVAL_ID", referencedColumnName = "ID"))
    @Column(name = "EXCLUDED")
    private Map<Approval, Boolean> approvals = new HashMap<Approval, Boolean>();

For some reason, Eclipselink gives a BigDecimal for each value in the map, instead of Boolean.
approvals.get(testApproval); // returns a BigDecimal :-(

Is there anything that doesn't look right? Is this us, or is this a bug in Eclipselink?
EDIT:
Tried this (Approval has 2 @Id fields):
    @ElementCollection
    @CollectionTable(name = "APPROVALS_PRODUCT_APPROVALS", joinColumns = @JoinColumn(name = "PRODUCT_APPROVAL_ID", referencedColumnName = "ID"))
    @Column(name = "EXCLUDED")
    @MapKeyJoinColumns({ @MapKeyJoinColumn(name = "CREDENTIAL_VALUE", referencedColumnName = "CREDENTIAL_VALUE"), @MapKeyJoinColumn(name = "CREDENTIAL_TYPE", referencedColumnName = "CREDENTIAL_TYPE") })
    private Map<Approval, Boolean> approvals = new HashMap<Approval, Boolean>();

and got the same result (BigDecimal instead of Boolean)
EDIT2:
We are using Eclipselink 2.3.0, also tried with 2.3.2 with same result.

A: Your code is wrong,
targetClass on ElementCollection is for specifying an Embeddable class (if generics are not used), so should be not used.
You also need a @MapKeyJoinColumn if you want the Map key to be another object (or @MapKeyClass if it is an Embeddable.
Most databases do not have a Boolean type, so booleans are normally stored as numbers, 0/1.  So you may be missing a conversion somehow.  You can define an @Convert with a @TypeConverter for this, although it should be getting defaulted, so you may log a bug for that.


Q: I'm getting java.lang.IllegalStateException: sequencer not open. What's the solution? This is the code I'm trying to run but I keep getting IllegalStateException. I'm relatively new to java and I need some help figuring this out. Thanks:)
This is the code:
import javax.sound.midi.*;

public class MiniMusicApp {
    public static void main(String[] args){
        MiniMusicApp mini = new MiniMusicApp();
        mini.play();
    }//Close main

    public void play(){
        try{
            Sequencer player = MidiSystem.getSequencer();
            Sequence seq = new Sequence(Sequence.PPQ, 4);
            Track track = seq.createTrack();

            ShortMessage b = new ShortMessage();
            b.setMessage(128, 1, 44, 100);
            MidiEvent noteOff = new MidiEvent(b, 16);
            track.add(noteOff);

            player.setSequence(seq);
            player.start();
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }//close play
}//close class

And I'm getting this:
java.lang.IllegalStateException: sequencer not open
    at java.desktop/com.sun.media.sound.RealTimeSequencer.start(RealTimeSequencer.java:232)
    at MiniMusicApp.play(MiniMusicApp.java:21)
    at MiniMusicApp.main(MiniMusicApp.java:6)
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
    at java.base/java.lang.reflect.Method.invoke(Method.java:577)
    at jdk.compiler/com.sun.tools.javac.launcher.Main.execute(Main.java:421)
    at jdk.compiler/com.sun.tools.javac.launcher.Main.run(Main.java:192)
    at jdk.compiler/com.sun.tools.javac.launcher.Main.main(Main.java:132)

A: For demonstration only, don't do this
As @Abra said, you need to call the open method:
import javax.sound.midi.*;

public class MiniMusicApp {
    public static void main(String[] args){
        MiniMusicApp mini = new MiniMusicApp();
        mini.play();
    }//Close main

    public void play(){
        try{
            Sequencer player = MidiSystem.getSequencer();
            player.open();
            Sequence seq = new Sequence(Sequence.PPQ, 4);
            Track track = seq.createTrack();

            ShortMessage b = new ShortMessage();
            b.setMessage(128, 1, 44, 100);
            MidiEvent noteOff = new MidiEvent(b, 16);
            track.add(noteOff);

            player.setSequence(seq);
            player.start();
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }//close play
}//close class

However you should also close it at the end:
import javax.sound.midi.*;

public class MiniMusicApp {
    public static void main(String[] args){
        MiniMusicApp mini = new MiniMusicApp();
        mini.play();
    }//Close main

    public void play(){
        Sequencer player = null;
        try{
            player = MidiSystem.getSequencer();
            player.open();
            Sequence seq = new Sequence(Sequence.PPQ, 4);
            Track track = seq.createTrack();

            ShortMessage b = new ShortMessage();
            b.setMessage(128, 1, 44, 100);
            MidiEvent noteOff = new MidiEvent(b, 16);
            track.add(noteOff);

            player.setSequence(seq);
            player.start();
        }catch(Exception ex){
            ex.printStackTrace();
        }
        finally {if(player!=null) player.close();}
    }//close play
}//close class

The correct way
But this way is error prone, so in modern Java you should use try-with-resource to close it automatically:
import javax.sound.midi.*;

public class MiniMusicApp {
    public static void main(String[] args){
        MiniMusicApp mini = new MiniMusicApp();
        mini.play();
    }//Close main

    public void play(){
        Sequencer debug = null; // just for demonstrating that it is really closed at the end
        try(Sequencer player = MidiSystem.getSequencer())
        {
            debug = player;
            player.open();
            Sequence seq = new Sequence(Sequence.PPQ, 4);
            Track track = seq.createTrack();

            ShortMessage b = new ShortMessage();
            b.setMessage(128, 1, 44, 100);
            MidiEvent noteOff = new MidiEvent(b, 16);
            track.add(noteOff);

            player.setSequence(seq);
            player.start();
        }catch(Exception ex){
            ex.printStackTrace();
        }
        System.out.println(debug.isOpen());
    }//close play
}//close class

A: You forgot to open the Sequencer, which is why you got an exception. To open the player
Sequencer player = MidiSystem.getSequencer();
player.open();


Q: Diff: ignoring lines with just tabs I'm trying to diff files, and determine if they are the same, but ignoring ALL whitespace.
When using diff, the -b tells diff to ignore whitespace on a given line.  The -B option tells it to ignore all blank lines.  But, if you have a line which contains only spaces, the -B and -b don't seem to work together.
I've resorted to using the -I option, where I want diff to ignore all lines which only contain whitespaces, which works fine when the line contains only spaces, but the \t doesn't seem to match tab characters.
I found one reference online that mentioned that you need to use POSIX regexp, but POSIX states that :blank: will match any whitespace (including tab).  That does not work either.
Here's a sample of what I'm trying to do.  Ideally, my diff line would state that t1.txt, t2.txt and t3.txt were all the same.
bash#> echo hi > t1.txt
bash#> echo hi > t2.txt
bash#> echo hi > t3.txt
bash#> echo " " >> t2.txt
bash#> echo -e "\t" >> t3.txt
bash#> diff -BbaNq -I "^[ \t]*$" t1.txt t2.txt
bash#> diff -BbaNq -I "^[ \t]*$" t1.txt t3.txt
Files t1.txt and t3.txt differ
bash#> diff -BbaNq -I "^[:blank:]*$" t1.txt t3.txt
Files t1.txt and t3.txt differ
bash#>

Any help in what the syntax for diff would be would be very helpful.

A: try this:
diff -wBt -u t1.txt t2.txt


Q: Google Maps Marker Clusterer: markers never cluster I don't know why the marker clusterer don't show my markers grouped, like here: http://media.svennerberg.com/2009/01/screenshot_clusterereffect.jpg
I am facing a problem in Google map marker clustering. I am using api v3, but due to some reasons, which I am not able to figure out, I cannot apply marker clustering. I'd be thankful for any help and suggestions.
My Code is like this:

<!DOCTYPE HTML>

  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta charset="utf-8"/>
  <meta http-equiv="X-UA-Compatible" content="IE=edge"/>

Map:

A: Looking at the example in the documentation and your code, probably the simplest "fix" is to instantiate the marker clusterer inside your display markers routine, then add each marker to the clusterer as it is created:
Comments:

*

*you have have a callback specified in you script include (&callback=myMap), but no function of that name (just remove that from your script include).  Causes this error in the console:

"myMap is not a function"

*There is a javascript error Uncaught ReferenceError: marker is not defined on this line: var markerCluster = new MarkerClusterer(map, marker, because there is no variable marker available in that scope (and as @MrUpsidown observed in his comment, that should be the array of markers).  To address that I suggest using the MarkerClusterer.addMarker method to add markers to it in displayMarkers, and changing your createMarker function to return the marker it creates.

  function displayMarkers() {
    // marker clusterer to manage the markers.
    var markerCluster = new MarkerClusterer(map, [], {
      imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
    });
    var bounds = new google.maps.LatLngBounds();
    for (var i = 0; i < markersData.length; i++) {
      var latlng = new google.maps.LatLng(markersData[i].lat, markersData[i].lng);
      var name = markersData[i].name;
      var address1 = markersData[i].address1;
      var address2 = markersData[i].address2;
      var address3 = markersData[i].address3;
      var address4 = markersData[i].address4;
      var image = markersData[i].ikona;
      var wwwsite = markersData[i].wwwsite;

      markerCluster.addMarker(createMarker(latlng, name, address1, address2, address3, address4, image, wwwsite));
      bounds.extend(latlng);
    }
    map.fitBounds(bounds);
  }

  function createMarker(latlng, name, address1, address2, address3, address4, image, wwwsite) {
    var marker = new google.maps.Marker({
      map: map,
      position: latlng,
      title: name,
      icon: image
    });
    google.maps.event.addListener(marker, 'click', function() {
      var iwContent = '
' +
        '
' + name + '
' +
        '
' + address1 + '
' +
        address2 + '
' + address3 + '
' + address4 + '
' +
        wwwsite + '

';
      infoWindow.setContent(iwContent);
      infoWindow.open(map, marker);
    });
    return marker;
  }

proof of concept fiddle

code snippet:

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

Map:


Q: How to call methods from other class?
I am trying to write a Java program to book hotel rooms. I have written methods in one class and am trying to call it from my main class, but I don't know how to do it.
The program asks the user to input necessary info for the methods, but I just don't know how to execute it.
I also want to know how to change the status of a room to "B" - for booked, when the user enters the RoomId and confirms their booking and then to print the information using the print() method in Room.java. Any help would be great. Thanks
Room.java
package utilities;

public class Room
{

 private String roomId;
 private String description;
 private String status;
 private double dailyRate;
 private DateTime bookingStartDate;
 private DateTime bookingEndDate;

 public Room(String roomId, String description, double dailyRate)
 {
  this.setRoomId(roomId);
  this.setDescription(description);
  this.setDailyRate(dailyRate);
  this.status = "A";
 }

 public boolean bookRoom (String customerID, int nightsRequired)
 {
     if (status.equals('A'))
     {
         System.out.println("You have booked the room");
         status = "B";
         return true;
     }
     else
     {
         System.out.println("This room cannot be booked");
         return false;
     }
 }

 public void print()
 {
     System.out.println("Room ID: " + getRoomId());
     System.out.println("Description: "+ getDescription());
     System.out.println("Status: " + status);
     System.out.println("Daily Rate: " + getDailyRate());
     if (status.equals('B'))
     {
         System.out.println(bookingStartDate);
         System.out.println(bookingEndDate);
     }
     else{
     }

 }

/**
 * @return the dailyRate
 */
public double getDailyRate() {
    return dailyRate;
}

/**
 * @param dailyRate the dailyRate to set
 */
public void setDailyRate(double dailyRate) {
    this.dailyRate = dailyRate;
}

/**
 * @return the description
 */
public String getDescription() {
    return description;
}

/**
 * @param description the description to set
 */
public void setDescription(String description) {
    this.description = description;
}

/**
 * @return the roomId
 */
public String getRoomId() {
    return roomId;
}

/**
 * @param roomId the roomId to set
 */
}

TestRoom.java
package stuff;

import java.util.Scanner;

import utilities.Room;

public class TestRoom {

 public static void main(String[] args)
 {
     Room [] rooms =
          {
            new Room("GARDEN0001", "NorthWest Garden View", 45.00),
            new Room("GARDEN0002", "SouthEast Garden View", 65.0),
            new Room("GARDEN0003", "North Garden View", 35.00),
            new Room("GARDEN0004", "South Garden View", 52.0),
            new Room("GARDEN0005", "West Garden View", 35.00),
            new Room("GARDEN0006", "East Garden View", 35.00)

          };
  Scanner userInput = new Scanner(System.in);

  System.out.println("Input a lower price range. ");
  int lower = userInput.nextInt();

  System.out.println("Input an upper price range. ");
  int upper = userInput.nextInt();

  if (lower < 65)
  {
      for ( int i = 0; i < rooms.length; i++ )
      {
          if (rooms[i].getDailyRate() > lower && rooms[i].getDailyRate() < upper )
          {
              System.out.println("ID: \t" + rooms[i].getRoomId() );
              System.out.println("DESC: \t" + rooms[i].getDescription() );
              System.out.println("RATE: \t" + rooms[i].getDailyRate() + "\n");
          }
      }
  }
  else
  {
      System.out.println("There are no rooms that fit your criteria.");
  }

  System.out.println("Input the ID of the room you wish to book.");
  String roomId = userInput.next();

  System.out.println("Please enter your customer ID");
  String customerID = userInput.next();

  System.out.println("Please enter the amount of nights you wish to stay.");
  int nightsRequired = userInput.nextInt();

  // Code to actually make the booking. I don't know what goes here.

A: Just get the instance of the Room and call the method.
The hard-coding method will be like this:
Room toBook = null;
for (Room r : rooms) {
    if (r.getRoomId().equals(roomId))
        toBook = r;
}

if (toBook != null) {
    if (toBook.bookRoom(customerID, nightsRequired)) {
         // room booked succesfully
    } else {
         // can't book the room
    }
} else {
    // room does not exists
}

But, as long as this will be a bigger app I recommend you to code your own equals method then Arrays.contains() will find the Room.
Room toBook = new Room(roomid);
if (rooms.contains(toBook) && toBook.bookRoom(customerID, nightsRequired)){
    // room booked succesfully
} else if (rooms.contains(toBook)) {
    // can't book the room
} else {
    // room does not exists
}

A: Add the code at the end of the main() method in Test class
    Room r=null;
    boolean val=false;
    for(int i=0;i<rooms.length;i++){
        if(rooms[i].getRoomId().equals(roomId)){
            r=new Room(rooms[i].getRoomId(), rooms[i].getDescription(), rooms[i].getDailyRate());
            r.bookRoom(customerID, nightsRequired);
            val=true;
            break;
        }
    }
    if(val){
         r.print();
    }


Q: How do I create a proxy object that forwards method calls in c#? I'm trying to use selenium to run tests; seems like there isn't a good way to run the same set of unit tests on multiple browsers.
I read this post about running tests in parallel:
http://slmoloch.blogspot.com/2009/12/design-of-selenium-tests-for-aspnet_19.html
However, I'm using the visual studio unit testing framework.
I can create a proxy class like this:
public class SeleniumProxy {
    private List<DefaultSelenium> targets;
    public SeleniumProxy() {
        targets = new List<DefaultSelenium>();
        targets.Add(new DefaultSelenium(... "firefox"...));
        targets.Add(new DefaultSelenium(... "iexplore"...));
    }
    public void Open(String url) {
        foreach (var i in targets) {
            i.Open(url);
        }
    }
    ...
}

My question is this? How can I do it without having to rewrite the entire class as a proxy?
I thought maybe passing a lamda in to map arguments, or passing by a function that takes the name of the method to invoke, but these all seem like pretty lame ideas.
What I really want is to add a member like:
public class SeleniumProxy {
    public dynamic proxy;
    ....
}

And invoke this like:
var selenium = getProxy();
selenium.proxy.Open("...");

Does c# allow this kind of syntax for dynamic objects?
Or some kind of meta-handler for classes that lets them catch no-such-method exceptions and handle them manually?
Basically:
How can I create a proxy object that dynamically invokes methods on an internal member of the class?
(Edit: perhaps... using reflection on the DefaultSelenium object and creating function stubs on the dynamic proxy object for each entry..?)

A: If I understand what you're attempting, I think you can extend DynamicObject to achieve this.
class Proxy : System.Dynamic.DynamicObject
{
    public Proxy(object someWrappedObject) { ... }

    public override bool TryInvokeMember(System.Dynamic.InvokeMemberBinder binder, object[] args, out object result)
    {
      // Do whatever, binder.Name will be the called method name
    }
}

//Do whatever... would become some code that pokes at some other object's internal members (via reflection, presumably) using binder.Name as part of the lookup process.
There are TryGetMember and TryGetIndex methods to override if you need to wrap up anything fancier that simple method invokes.
You will have to cast instances of Proxy to dynamic after construction to make arbitrary calls, just like when dealing with ExpandoObject.

A: You could leverage inheritance and have your tests defined in an abstract base class with a factory method to create your selenium instance, then inherit this for each type of browser you want to model. The tests will then be run for each inherited class with the appropriate browser. Using NUnit as an example:
public abstract class AbstractTests
{
    protected abstract DefaultSelenium CreateSelenium();

    [Test]
    public void TestSomethingA()
    {
        DefaulSelenium selenium = CreateSelenium();

        //Do some testing with selenium.
    }
}

[TestFixture]
public class IETests : AbstractTests
{
    protected override DefaultSelenium CreateSelenium()
    {
        return new DefaultSelenium("iexplore");
    }
}

[TestFixture]
public class FirefoxTests : AbstractTests
{
    protected override DefaultSelenium CreateSelenium()
    {
        return new DefaultSelenium("firefox");
    }
}


Q: Rails weird result with find and where Can someone point me the reason for following:
JobType.find 17
#=>
#<JobType id: 17, title: "some_title", description: "one description", reward: #    <BigDecimal:1009bbb48,'0.1E1',9(18)>, min_payout: 0.019999999552965164, min_skill_score: 0.6000000238418579, max_payout: 1.0, max_skill_score: 0.9300000071525574, difficulty_level: 2.0, variable_reward: true>
JobType.where(id: 17).first
#=>
#<JobType id: 17, title: "some_title", description: "one description", reward: #<BigDecimal:1009bbb48,'0.1E1',9(18)>, min_payout: 0.02, min_skill_score: 0.6, max_payout: 1.0, max_skill_score: 0.93 difficulty_level: 2.0, variable_reward: true>

In database, The values for min_payout is 0.6, max_skill_score is 0.93, but the find returns that weird long float.
SQL queries logged:
# find
JobType Load (0.5ms)  SELECT `job_types`.* FROM `job_types` WHERE `job_types`.`id` = ? LIMIT [["id", 17]]

# where
JobType Load (0.6ms)  SELECT `job_types`.* FROM `job_types` WHERE `job_types`.`id` = 17

Why is find behaving like that.
I am using rails 3.2.13 and mysql gem.

A: This is due to the use floating point numbers. Floating point numbers involve a binary representation, in which some numbers that can be exactly represented in decimal notation easily are not stored exactly.
For example, 0.6 in decimal is (approximately) 0.111111000110011001100110011010 in binary. When converted back to decimal this number is (approximately) 0.6000000238418579.
Due to this, when you store 0.6 in a float column, the value returned to you will be (slightly) different. The exact value you receive depends on the specific handling that the value has gone through, which may differ depending on a variety of factors.
In order to avoid this, you would be better off using a BigDecimal, and setting the storage type on that column to :decimal.


Q: my cloud front URL redirect to S3 URL my cloud front distribution's origin is my S3 bucket . to access a S3 bucket object we put a url in such as like "cloudfront_domainname/object_name" it should be show the object if the object is public . but in my case the cloud front URL in the URL bar redirects a S3 URL, the data retrieved from S3 not from cloud front distribution. why it cause ?

A: You can optionally secure the content in your Amazon S3 bucket so users can access it through CloudFront but cannot access it directly by using Amazon S3 URLs. This prevents anyone from bypassing CloudFront and using the Amazon S3 URL to get content that you want to restrict access to. This step isn't required to use signed URLs, but we recommend it.
To require that users access your content through CloudFront URLs, you perform the following tasks:

*

*Create a special CloudFront user called an origin access identity.

*Give the origin access identity permission to read the objects in your bucket.

*Remove permission for anyone else to use Amazon S3 URLs to read the objects.

Please see documentation here