text:
Q: how to slip this multi-dimensional array? I have a nested array and I wanted to know if there is a way to slip it, so having the nested arrays as individual arrays
Array
(
    [0] => Array
        (
            [menu] => Array
                (
                    [pizza] => Array
                        (
                            [Tomato & Cheese] => Array
                                (
                                    [small] => 5.50
                                    [large] => 9.75
                                )

                            [Olives] => Array
                                (
                                    [small] => 6.85
                                    [large] => 10.85
                                )

                        )

                    [Speciality Pizzas] => Array
                        (
                            [Our Special] => Array
                                (
                                    [ingredients] => Array
                                        (
                                            [0] => Tomatoes
                                            [1] => Olives
                                            [2] => Spinach
                                            [3] => Fresh Garlic
                                            [4] => Mozzarella & Feta Cheese
                                        )  --- theres more but you get the idea

Now I want to may a new array with all the pizzas, but without knowing the name "pizza"
at the moment I can do this:
$array = array(json_decode($json, true));
$pizzas = (array)$array[0]['menu']['pizza']

But if the menu changes content (but not structure) and if the 'pizza' changes to 'salads' the above would fail.  Is the a way to create the above pizzas array without the name
Thanks

A: $array = array(json_decode($json, true));
$menu = (array)$array[0]['menu'];
foreach($menu as $item => $item_Data){
    //$item might be pizza for example
    //$item_Data might be Olives or Our special. Now you have to consider what to do with this. Maybe next foreach loop ?
}

A: Right now your array has parallel sections for related data. How about if you did something like:
$food_choices = array(
     'pizza' => array(
         'Tomato & Cheese' => array(
               'type' => 'regular',
               'prices' => array(...),
               'ingredients' => array(...)
         ),
         'Our Special' => array(
              'type' => 'specialty',
              'prices' => array(...),
              'ingredients' => array(...)
         ),
     ),
     'salads' => array(
          'Caesar' => array(...);
          'Tossed' => array(...);
     )
)

where all the information related to any one menu item as all in the same branch of the meu tree. Then to access any one pizza's information is as simple as:
$data = $food_choices['pizza']['Tomato & Cheese'];
echo 'The large of this pizza costs $', $data['prices']['large'];
echo 'The small Caesar salad contains ', implode($food_choices['salad']['Caesar']['ingredients);

A: A series of foreach loops might do, even though I don't know what you're doing.
<?php

    $pizza = '';

    foreach ($array as $food) {

        $pizza .= $food;

        if (is_array($food)) {

            foreach ($food as $option) {

                $pizza .= " > " . $option;

                if (is_array($option)) {

                    foreach ($option as $value) {

                        //etc
                    }
                }
            }
        }
    }

?>

A: To learn about the keys in an array, use the array_keys function (Demo):
$array = array(array('menu' => array(/* ... */))); # your array

print_r(array_keys($array[0])); # Array(menu)


text:
Q: Clojure Passing Individual Variables to Function I am trying to pass some vectors containing a list of nodes in to a function in clojure the function works if i was to type the variables in but i am not sure how to pass a single variable from each vector in at a time.
(def ItemPickUp [:a1 :Mail])
(def ItemDestinations [:Storage :a1])
(def Robot {[ItemPickUp] [ItemDestinations]})

(defn shortestPath [g start dest]
(let [not-destination? (fn [[vertex _]] (not= vertex dest))]
(-> (shortest-paths g start)
    (->> (drop-while not-destination?))
    first
    (nth 2))))

(apply shortestPath G (apply first Robot)((apply second Robot)))

I need to pass a variable from the ItemPickUp and ItemDestination into shortestPath using robot but instead of passing one of the variable in it passes both :a1 and :Mail and vice versa for the other one.
How do i go about passing each variable in individually so the first two variables for the first iteration is :a1 and :Storage and so on?
Thanks.

A: In Clojure this is normally done with map - it takes a function f and any number of collections and lazily produces a sequence of (f (first coll1) (first coll2)...), (f (second coll1) (second coll2)...)...
So it should just be
(map (partial shortestPath G) ItemPickup ItemDestinations)

(Some other functional languages distinguish one-collection mapping from multi-collection zipping - I believe Haskell is influential here. It needs this because its functions have fixed arities, so you have zipWith,zipWith3 etc. Having the parenteses to indicate number of arguments means Lisps don't have to deal with that.)

A: In case of (def Robot [[ItemPickUp] [ItemDestinations]]) and you want to use it you can do:
(apply map (partial shortestPath G) Robot)
Apply in this case will reduce to:
(map (partial shortestPath G) (first Robot) (second Robot))
and of course will throw ArityException if Robot has other than two elements.
You can think about apply as moving parentheses (function call) to his first argument and taking out parentheses from last argument (if some).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Сложности с версткой линий Есть макет header

body {
  margin: 0;
}

hr {
  margin-top: 8px;
  border: 1px solid #fff;
  width: 217%;
}

.container {
  background: #070707;
  padding: 5px 0 16px 0;
  display: flex;
  justify-content: space-between;
}

.left_side_block {
  margin: 17px 205px 0 42px;
}

.left_side_block span {
  margin-right: 27px;
  font-family: 'Roboto';
  font-size: 12px;
  line-height: 14px;
  color: #FFFFFF;
}

.left_side_block span:last-child {
  margin-right: 0;
}

.right_side_block {
  margin: 12px 42px 0 205px;
}

.left_side_textblock {
  margin-bottom: 2px;
}

.right_side_block span {
  color: #FFFFFF;
  font-family: 'Roboto';
  font-weight: 700;
  font-size: 20px;
  line-height: 27px;
  margin-bottom: 2px;
}

        Портфолио
        Блог
        О нас

        +7 (495) 120-77-62

Результат:
Все так, кроме правой части. Не получается правый текст и линию поставить в нужные положения.

A: Попробуйте линии задавать не через
, а через нижнюю границу блока.

*

*Внутри основного блока флексами разнесите левый, правый блок (будут с линиями) и центральный с логотипом.

*Задайте левому и правому высоту с половину логотипа (кажется, что линии должны идти по центру общего блока).

*Внутри левого и правого тоже флексами расположите внутренние элементы.
Вот пример (в html убрал линии и лишние div, классы не менял):

body {
  margin: 0;
}

.container {
  background: #070707;
  padding: 15px 30px 15px; /* Внутренние поля контейнера */
  display: flex;
  justify-content: space-between;
}

.left_side_block {
  align-self: start;
  min-width: 33%; /* Ширина блока с горизнтальной линией */
  height: 25px; /* Половина высоты контейнера */
  border-bottom: 1px solid #fff;
  display: flex;
  align-items: start;
  gap: 20px;
}

.right_side_block {
  align-self: start;
  min-width: 33%; /* Ширина блока с горизнтальной линией */
  height: 25px; /* Половина высоты контейнера */
  border-bottom: 1px solid #fff;
  display: flex;
  justify-content: right;
  align-items: start;
}

.logo_block {
  min-height: 50px; /* Высота логотипа */
  background-color: tomato;
}

.left_side_block span {
    font-family: 'Roboto';
    font-size: 12px;
    line-height: 14px;
    color: #FFFFFF;
}

.right_side_block span {
    color: #FFFFFF;
    font-family: 'Roboto';
    font-weight: 700;
    font-size: 20px;
    line-height: 27px;
    margin-bottom: 2px;
}

      Портфолио
      Блог
      О нас

     +7 (495) 120-77-62

A: Я бы на Вашем месте использовал бы для реализации такой шапки flex:
Идея в том, чтобы убрать тэги hr а вместо них нарисовать нижнюю границу border-bottom для левого и правого div.
Ниже я привел Вам пример кода, который на мой взгляд можно использовать. Там в HTML-документе я добавил обёртку
 для всех элементов, расписал для него стили в css-файле и исправил стили для .left_side_block и .right_side_block. Только подкорректируйте ширину блоков и нижней линии под свой макет, потому что сложно это сделать, не имея логотипа)

body {
    margin: 0;
}

hr {
    margin-top: 8px;
    border: 1px solid #fff;
    width: 217%;
}

.container {
    background: #070707;
    padding: 5px 0 16px 0;
    display: flex;
    justify-content: space-between;
}

.header__flex {
    display: flex;
    width: 100%;
    padding: 0px 10px;
    justify-content: space-between;
    align-items: center;
}

.left_side_block {
    border-bottom: 1px solid #fff;
    flex: 0 1 250px;
}

.left_side_block span {
    margin-right: 27px;

    font-family: "Roboto";
    font-size: 12px;
    line-height: 14px;

    color: #ffffff;
}

.left_side_block span:last-child {
    margin-right: 0;
}

.right_side_block {
    border-bottom: 1px solid #fff;
    flex: 0 1 200px;
    text-align: right;
}

.left_side_textblock {
    margin-bottom: 2px;
}

.logo_block {
  text-align: center;
}

.right_side_block span {
    color: #ffffff;
    font-family: "Roboto";
    font-weight: 700;
    font-size: 20px;
    line-height: 27px;
    margin-bottom: 2px;
}

                        Портфолио
                        Блог
                        О нас

                        +7 (495) 120-77-62


text:
Q: Relative link and smooth scroll to it on load A have relative links /info/here#point-reach. When I click a link to it it goes to page /info/here and simultaneously takes to anchor #point-reach. Is it possible to go to this /info/here#point-reach link from other page and smoothly from the top get to this anchor?
Code I'm trying to use:
$(document).ready( function(){
    var getLink = window.location.hash
    setTimeout(function(){
        $("html, body").animate({ scrollTop: $(getLink).offset().top }, 1000);
    }, 1000);
})

                <input type="radio" id="package-5" class="accordion-section" hidden="">

Lorem ipsum dolor sit amet, in vix inermis principes, vis soluta definiebas no. Sea cu laboramus comprehensam, homero ullamcorper vis te. Eam id insolens antiopam, pri an nihil libris facilisis. Perpetua efficiantur per ne. Ne per simul tritani offendit, eu quo atqui virtute deserunt.

Швидкі результати тесту

Зручне, просте і швидке проходоження тесту

Приємна ціна!

A: This script should be added in the head of each page or put in a js file and include that file in the head/body and setTimeout() method isn't needed because that waits for one sec after dom ready but page jumps on the link and the smooth scroll effect doesn't show up:
// file.js <---include this file at a common place which is available for all pages.
$(document).ready( function(){
    var getLink = window.location.hash;
    if(getLink){
       $("html, body").animate({ scrollTop: $(getLink).offset().top }, 1000);
    }
})

This will ensure if we have a hash in the url and document.ready block ensures that we have our element to work on. So, the idea is make a common js file which can be added for each html file or say different urls and if the url contains any hash value it'll run for that.

A: If we pass Div id which is available in page then directly it will go on that div id.
To avoid this just pass some special character in hash

eg. Just add !(or any symbol) after hash so i will be work fine.
/info/here#!point-reach

$(document).ready( function(){
        var getLink = document.location.hash.substr(1);
         if(getLink.indexOf("!") != -1){
                var rel = hash.replace("!","");
            setTimeout(function(){
              $('html, body').animate({
                scrollTop: $('#'+rel).offset().top
            }, 1000);
         }, 1000);`enter code here`
        }
})

A: Instead of using document.ready, I used window.load. So the first action we get on top of the window, then with a delay we get to our anchor.
So here is the code that helped (nevermind some other code adds):
$(window).load(function() {
       $(this).scrollTop(0)
        var getLink = window.location.hash;
        if(getLink){
            $(getLink).next().prop('checked', 'checked')
            setTimeout(function(){
                $("html, body").animate({ scrollTop: $(getLink).offset().top }, 1000);
            }, 1000);
        }
    });


text:
Q: CLion, MinGW and SDL2: Process finished with exit code -1073741515 (0xC0000135) I am trying to add SDL2 to my CLion project. I found this guide and tried to follow it while including only SDL2. Everything compiles, but when I start my app I get "Process finished with exit code -1073741515 (0xC0000135)".
In my CMakeLists.txt file:
cmake_minimum_required(VERSION 3.15)
project(Test)

set(CMAKE_CXX_STANDARD 14)

set(CMAKE_CXX_FLAGS "-lmingw32 -static-libgcc -static-libstdc++")
set(SDL2_PATH "C:/CPP/libs/SDL2-2.0.10/x86_64-w64-mingw32")
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "C:/CPP/libs/CMakeModules")

find_package(SDL2 REQUIRED)
include_directories(${SDL2_INCLUDE_DIR})

if (${SDL2_FOUND})
    message(VERBOSE, "sdl found!")
else ()
    message(FATAL_ERROR, "sdl not found")
endif ()

message(VERBOSE, ${SDL2_INCLUDE_DIR})
message(VERBOSE, ${SDL2_LIBRARY})

add_executable(Test src/main.cpp)
target_link_libraries(Test ${SDL2_LIBRARY})

main.cpp:
#include <SDL.h>
#include <cstdio>

int main(int argc, char *args[]) {

    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError());
    }
    SDL_Quit();
    return 0;
}

I am using CLion 2019.3.2 with bundled CMake, latest MinGW build (x86_64-8.1.0-win32-seh-rt_v6-rev0) and latest SDL2 (2.0.10).
CMake output also looks ok:
VERBOSE,sdl found!
VERBOSE,C:/CPP/libs/SDL2-2.0.10/x86_64-w64-mingw32/include/SDL2
VERBOSE,mingw32-mwindowsC:/CPP/libs/SDL2-2.0.10/x86_64-w64-mingw32/lib/libSDL2main.aC:/CPP/libs/SDL2-2.0.10/x86_64-w64-mingw32/lib/libSDL2.dll.a-lpthread

A: My CMakeLists.txt seems different from yours.
Here are my configurations, Hope can help you.
cmake_minimum_required(VERSION 3.15)
project(cppSDL)

set(CMAKE_CXX_STANDARD 17)

set(CMAKE_CXX_FLIGS "${CMAKE_CXX_FLAGS} -std=c++17 -lmingw32")
set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -static-libstdc++")

include_directories(${PROJECT_SOURCE_DIR}/include)
link_directories(${PROJECT_SOURCE_DIR}/lib/x86)

set(SOURCE_FILES SDLtutorial.cpp)
add_executable(SDLtutorial ${SOURCE_FILES})

target_link_libraries(SDLtutorial SDL2main SDL2 SDL2_ttf SDL2_image)

A: if you are using visual studio toolchains in CLion:
You need to paste in folder cmake-build-debug or cmake-build-release the files .dll,  but no only SDL2_image.dll, all files from folder lib/x86
SDL2_image-devel-2.0.5-VC.zip


text:
Q: Swift: Full screen UIImageView not working Using Swift, I want to click a smaller image view which then expands to full screen of the device and once clicked again to go back to the default size it was before.
This is the code I have but when clicked it doesn't expand to full screen more as in, it expands to the views width.
I have a pop up UIView on top of my main view to show as a pop up and the image expands to that pop up view but not the whole screen.
Before clicking imageView

After clicking imageVjew

How would I achieve a full screen of my imageView?
@IBOutlet var backgroundView: UIView!
@IBOutlet weak var popUpView: UIView!
@IBOutlet weak var iconImage: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
    iconImage.addGestureRecognizer(tapGesture)

}

@IBAction func handleTap(_ gesutureRecognizer: UITapGestureRecognizer) {

    let screenSize = UIScreen.main.bounds
    let screenWidth = screenSize.width
    let screenHeight = screenSize.height
    iconImage.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)
}

A: You can follow the logic of this tutorial, but instead of creating a UIViewController for the "popup" you can create an UIViewController with an imageView in fullscreen mode.
https://www.youtube.com/watch?v=FgCIRMz_3dE&t=430s


text:
Q: Xcode 4 and git issue The base project is managed in git of Xcode 4. Then, I have another project that will use also the same base code but different UI only. How I can copy the base project or do I need to add another working local copy?

A: If the two programs are closely related, you could simply stay within the project, but creating a new branch for that variation (See XCode4 SCM guide):
You would stay in the same local copy, but you would update your local working tree, switching from one branch to another.

That may be simpler that trying to use submodules in this case (unless you have many projects reusing the same base code).


text:
Q: Transform array of arrays to array of hashes with new keys I have array of arrays like this:
status = [
   ["Deleted", "deleted", 0],
   ["In planning", "planning", 1],
   ["In approval", "approval", 2]
]

How do I transform it to an array of hashes like this?
[
  {:label => "Deleted", :value => "deleted"},
  {:label => "In planning", :value => "planning"},
  {:label => "In approval", :value => "approval"}
]

So far I tried:
status.each do |s| label: s[0], value: s[1] end

However, I don't get back an array of hashes. If I do:
puts s[0], value: s[1]

I see only hashes in my console:
{:label => "Deleted", :value => "deleted"}
{:label => "In planning", :value => "planning"}
{:label => "In approval", :value => "approval"}

I believe I somehow would need to add those hashes to the array.

A: Try to the following:
status.map { |label, value, _| { label: label, value: value } }

A: status.map{ |s| Hash[label: s[0], value: s[1]] }
# => [{:label=>"Deleted", :value=>"deleted"}, {:label=>"In planning", :value=>"planning"}, {:label=>"In approval", :value=>"approval"}]


text:
Q: How to catch error exception in ActionMailer The problem is how can I catch exception in delivering mail by ActionMailer. For me it sounds impossible, because in this case ActionMailer should sent mail to mailserver, and if mailserver returns error, ActionMailer should show me this error. I am interested only in counting undelivered mails.
Do you have any ideas how to implement this?
Thanks!

A: If you are sending a lot of emails, you can also keep your code more DRY and get notifications of exceptions to your email by doing something like this:
status = Utility.try_delivering_email do
  ClientMailer.signup_confirmation(@client).deliver
end

unless status
  flash.now[:error] = "Something went wrong when we tried sending you and email :("
end

Utility Class:
class Utility
  # Logs and emails exception
  # Optional args:
  # request: request Used for the ExceptionNotifier
  # info: "A descriptive messsage"
  def self.log_exception(e, args = {})
    extra_info = args[:info]

    Rails.logger.error extra_info if extra_info
    Rails.logger.error e.message
    st = e.backtrace.join("\n")
    Rails.logger.error st

    extra_info ||= "<NO DETAILS>"
    request = args[:request]
    env = request ? request.env : {}
    ExceptionNotifier::Notifier.exception_notification(env, e, :data => {:message => "Exception: #{extra_info}"}).deliver
  end

  def self.try_delivering_email(options = {}, &block)
    begin
      yield
      return true
    rescue  EOFError,
            IOError,
            TimeoutError,
            Errno::ECONNRESET,
            Errno::ECONNABORTED,
            Errno::EPIPE,
            Errno::ETIMEDOUT,
            Net::SMTPAuthenticationError,
            Net::SMTPServerBusy,
            Net::SMTPSyntaxError,
            Net::SMTPUnknownError,
            OpenSSL::SSL::SSLError => e
      log_exception(e, options)
      return false
    end
  end
end

Got my original inspiration from here: http://www.railsonmaui.com/blog/2013/05/08/strategies-for-rails-logging-and-error-handling/

A: This is inspired by the answer given by @sukeerthi-adiga
class ApplicationMailer < ActionMailer::Base
  # Add other exceptions you want rescued in the array below
  ERRORS_TO_RESCUE = [
    Net::SMTPAuthenticationError,
    Net::SMTPServerBusy,
    Net::SMTPSyntaxError,
    Net::SMTPFatalError,
    Net::SMTPUnknownError,
    Errno::ECONNREFUSED
  ]

  rescue_from *ERRORS_TO_RESCUE do |exception|
    # Handle it here
    Rails.logger.error("failed to send email")
  end

end

The * is the splat operator. It expands an Array into a list of arguments.
More explanation about (*) splat operator

A: I'm using something like this in the controller:
 if @user.save
      begin
      UserMailer.welcome_email(@user).deliver
      flash[:success] = "#{@user.name} created"
      rescue Net::SMTPAuthenticationError, Net::SMTPServerBusy, Net::SMTPSyntaxError, Net::SMTPFatalError, Net::SMTPUnknownError => e
        flash[:success] = "Utente #{@user.name} creato. Problems sending mail"
      end
      redirect_to "/"

A: This should work in any of your environment files. development.rb or production.rb
config.action_mailer.raise_delivery_errors = true

A: class ApplicationMailer < ActionMailer::Base
  rescue_from [ExceptionThatShouldBeRescued] do |exception|
    #handle it here
  end
end

Works with rails 5 onwards. And it's the best practice.


text:
Q: Calculate 30 days Ago PHP I am pulling the lastBillingDate from my DB. It is a normal timestamp. I want to have the system check to see if the timestamp is 30 days ago. Basically we bill a customer every 30 days. What I'd like is it to trigger the function when the date is exactly 30 days, or over 30 days. This doesn't seem to be working. Here is an example of one of my timestamps too:
1339477200

Here's the cron function:
    $query = "SELECT * FROM contacts";
                $result = mysql_query($query);

                while($row = mysql_fetch_row($result)){

                        $id = $row[0];
                        $ownerID = $row[1];
                        $company = $row[4];
                        $lastBillDate = $row[36];

                        echo $lastBillDate.'<br>';

                    if($lastBillDate<strtotime('-30 days')){
                        $billdate = RelativeTime($lastBillDate);

                                    mailBillNotice($id, $ownerID, $company, $billdate);
                    }

                }

A: IMHO, it would be better to put that criteria in the SQL query.
SELECT * FROM contacts WHERE last_bill_date <= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 30 DAY))

That will return only the contacts that have a last_bill_date that is 30 or more days back from today. Then do whatever processing you need, bill the clients, and update the timestamp.

A: Seeing as it's just a number, you can use normal arithmetic on your timestamp:
$timestamp = 1339477200;
$thirtyDays = (60 * 60 * 24 * 30)
$thirtyDaysAgo = time() - (60 * 60 * 24 * 30)

if($timestamp - $thirtyDays <= $thirtyDaysAgo) {
    // Do your thang
}

Doing it in MySQL, however, is much more sensible. It removes the overhead of fetching extra rows from the database. Try this:
SELECT * FROM contacts
WHERE
    last_bill_date <= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 30 DAY))


text:
Q: Android's Material Design of Toolbar / SupportActionBar I'm experimenting with the news themes tonight and I'm wondering if anyone knows these fix to this issue.
This appears on the stock Toolbar and even, as seen below, when referring to custom layout file.
It's relatively minor but my OCD eyes go right to it so maybe someone can help. Thanks :)

A: UPDATE: Inheriting from the correct theme and declaring attributes in pairs (with and without the android: prefix) was the fix!

<!-- Base app theme. -->
<style name="AppTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="android:actionBarStyle">@style/MyActionBar</item>
    <item name="actionBarStyle">@style/MyActionBar</item>
</style>

<!-- ActionBar styles. -->
<style name="MyActionBar" parent="Widget.AppCompat.ActionBar">
    <item name="android:titleTextStyle">@style/MyActionBarTitleText</item>
    <item name="titleTextStyle">@style/MyActionBarTitleText</item>

    <item name="android:subtitleTextStyle">@style/MyActionBarSubTitleText</item>
    <item name="subtitleTextStyle">@style/MyActionBarSubTitleText</item>

    <item name="android:background">@color/blue</item>
    <item name="background">@color/blue</item>
</style>

<style name="MyActionBarTitleText" parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title">
    <item name="android:textColor">@color/white</item>
</style>

<style name="MyActionBarSubTitleText" parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Subtitle">
    <item name="android:textColor">@color/white</item>
    <item name="android:textSize">@dimen/subtitle</item>
</style>

A: If es0329's answer doesn't work for you, try to replace titleTextStyle by titleTextAppearance. It is working for me:
    <style name="MyActionBar" parent="Widget.AppCompat.ActionBar">
        <item name="android:titleTextAppearance">@style/MyActionBarTitleText</item>
        <item name="titleTextAppearance">@style/MyActionBarTitleText</item>

        <item name="android:subtitleTextAppearance">@style/MyActionBarSubTitleText</item>
        <item name="subtitleTextAppearance">@style/MyActionBarSubTitleText</item>

        <item name="android:background">@color/blue</item>
        <item name="background">@color/blue</item>
    </style>


text:
Q: Select column from similarly named tables I want to select a specific column form many tables that have similar names i.e.:
Tables Names
x1
x2
x3
y1
y2
z1
smth like this : select field from like x%;
all tables have the same structure and column names


text:
Q: Sign the ClickOnce manifests checkbox keeps defaulting to checked on publish I am trying to get a .NET solution to publish using ClickOnce without signing the manifests in Visual Studio 2008 SP1, but I am having no joy. Specifically the check box called "Sign the ClickOnce manifests" keeps getting re-checked every time I publish. Strangely, another developer says he can publish on the same solution and leave this unchecked.
I saw the other Stack Overflow question, How to not sign a ClickOnce manifest. But I thought you are supposed to be able to publish using ClickOnce without signing in Visual Studio 2008 SP1 per Microsoft's post, How to: Sign Application and Deployment Manifests.
But no amount of re-publishing and un-checking allows me to continue without generating some sort of certificate.

A: I had the same problem, and I never figured out how to "fix" this problem. My solution has been to sign every publish. However, the certificate that I associate with the application is a "dummy" one that I allow Visual Studio to generate, with the expiration date set to the maximum available date.
Your application will still be signed, but you should have to worry about your user's having to uninstall & re-install your application when the certificate expires.

A: I eventually found a fix.. By right clicking the certificate file from the original publish machine and installing it. I don't know why this was required. Maybe there was a mismatch in the certificate first used to publish (by a different developer) and my VS was generating another.

A: I had the same problem. It turns out my certificate had expired, which I could verify by using the "Certificates" snap-in in MMC. I created a new test certificate for another year and used that, and it's all good now.


text:
Q: Listing files with spaces in name Problem
In some directory, I have some files with spaces (or maybe some special character) in their filenames.
Trying to list one file per line, I used ls -1 but files with spaces in name are not processed as I expected.
Example
I have these three files:
$ ls -1
My file 1.zip
My file 2.zip
My file 3.zip

and I want to list and do something with them, so I use a loop like this:
for i in `ls -1 My*.zip`; do
    # statements
    echo $i;
    # Do something with each file;
done

But like split names with spaces:
My
file
1.zip
My
file
2.zip
My
file
3.zip

Question
How can I solve this?, Is there some alternative in shell?

A: Don't use output from ls, use:
for f in *.zip; do
    echo "processing $f"
done

A: By not using ls, and by quoting properly.
for i in My*.zip
do
  echo "$i"
done

A: shopt -s dotglob
for i in *;
do :; # work on "$i"
done
shopt -u dotglob

By default, files that begin with a dot are special in that * will not match them.


text:
Q: Prevent TextView overlapping another in ConstraintLayout? I'm encountering an issue where the "Den Dolder" TextView is always overlapping the date TextView. I have tried using app:layout_constraintRight_toLeftOf="@id/date_txtView" but it has no effect surprisingly!
That's okay:

That's not okay:

A: Short solution:
Try to add app:layout_constraintHorizontal_weight="1" and android:layout_width="0dp" to both of your textViews - they will both take the same width in the layout.
Another solution for more complicated layouts:
You need to tell both of your text views to be in a width of 0dp, so they will drop a line if the text is too long.
For example, set a Chain between your  2 textViews like this:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  android:layout_width="match_parent"
  android:layout_height="match_parent">

<TextView
    android:id="@+id/textView3"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
    app:layout_constraintEnd_toStartOf="@+id/textView4"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/textView4"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    android:text="TextView"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toEndOf="@+id/textView3"
    app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

And it will look like this (no textView overlaps another one, they just drop down a line):


text:
Q: Form just refreshes page on submit and does not go to routes I have been struggling with this for so long and can't figure out what the problem is. I want to just POST to /accountRoutes/editFinalMark and I have included the code for the route as well as the controller.
<form method="post" action="/accountRoutes/editFinalMark">
  <fieldset class="form-group">

        <input type="" id="moduleID" name="moduleID" style="display: none;" value="<%= module._id %>">
        <input type="" name="editFinalMarkInput" id="editFinalMarkInput" class="urlInput" placeholder="Add Final Mark" style="">

        <input type="submit" name="editFinalMarkButton" id="editFinalMarkButton" class="submit-docs" value="Add" style="background-color: #6dabe4; border-top-right-radius: 15px; border-bottom-right-radius: 15px; color: white;" />

  </fieldset>
</form>

// The Route:
router.post('/editFinalMark', accountController.editFinalMark_post);

// The Controller I want to call:
module.exports.editFinalMark_post = async (req, res) => {
    try {
        const { editFinalMarkInput, moduleID }  = req.body;

        console.log("\n\n\n\n\n");
        console.log("editFinalMarkInput: ", editFinalMarkInput);
        console.log("moduleID: ", moduleID);

        Module.findOneAndUpdate(
               { _id: moduleID },
               { $push: { final_mark: editFinalMarkInput } },
                 function (error, success) {
                        if (error) {
                            console.log(error);
                        } else {
                            console.log(success);
                        }
                }
        );

        res.status(201).json({  });

    } catch (err) {
        res.status(400).json({ err })
    }
};

All that happens when I click submit is that the page reloads and the url updates to include the data from the form, but it doesn't complete the action specified in the form. There are also no errors at all in the console.

A:
All that happens when I click submit is that the page reloads and the url updates to include the data from the form, but it doesn't complete the action specified in the form.

So it ignores both the action (because it goes to the wrong URL) and the method (because it puts the data in the URL so it is making a GET request).
From this we can infer that you have another <form> element and that is the one being submitted. You just haven't included it in the code in the question.
<form> elements aren't allowed to be nested so a validator would help you find it.


text:
Q: jQuery Random reward point system I am quite new to jQuery.
I am making a game in HTML 5, jQuery and CSS.
I want to create a random point system for an object. This is what I have now, but the random point system doesn't work 100%. When the color is: colors[1] then the variable (reward points) needs to be 5. If it is colors[2], it needs to be 10 as example. Here is the code:
// http://jsfiddle.net/39r1xfhc/1/

// Point Object
var Point;
var pointID = 0;
var speed = 3;
var rewardPoints;
var colors;
var rand;

function Points() {
this.drawY = Math.floor(Math.random() * 260);

pointID++;

// Colors for Points
colors = ["#0F0","#F00C00","#00E1FF"];
rand = Math.floor(Math.random() * colors.length);

if(colors[rand] === colors[1]) {
    rewardPoints = 5;

    Point = $('

');
    $(Point).css({'right': '0', 'top': this.drawY, 'background-color': colors[1]});

    canvasPoints.append(Point); // Spawn Point
} else if(colors[rand] === colors[2]) {
    rewardPoints = 10;

    Point = $('

');
    $(Point).css({'right': '0', 'top': this.drawY, 'background-color': colors[2]});

    canvasPoints.append(Point); // Spawn Point
} else if(colors[rand] === colors[3]) {
    rewardPoints = 20;

    Point = $('

');
    $(Point).css({'right': '0', 'top': this.drawY, 'background-color': colors[3]});

    canvasPoints.append(Point); // Spawn Point
}
}


text:
Q: Why I can't use the word "fions" to create google my business profile? I have a problem with creating a google my business profile for my client , his company name is "Fions Interior Solutions" the problem is when I tried to create a google my business account with this name it shows a error like The term fions is not allowed, do you have any idea why is that?
really appreciate your help.
Thanks.


text:
Q: How can I get unkown input in c++ and recognize the type of that value? Is there any way to get Unknown input in c++?
I mean if we want to get an " int number " we should use this code:
int main()
{
    int x; //now we can get int number
    cout <<"Enter your number: ";
    cin >> x;
    cout << "The number is: " << x;
    return 0;
}

but if I dont know the type of value which user enter as an input how can I get that? should I use something like this :
unknown x; //to get unknown value?

And after I get that value how can I recognize what type is it?
for exp:
unknown x;
if ( x = int x )
{
cout << "The value is an int number";
}

I am amatuar in c++ so simple explanations would be better.thanks

A: What you need to do, is to follow the general rules for all IO operations: Check the functions result.
If a IO function does not succeed, then 1 or more failure indication bits will be set.
You will find a very nice description in the CPP reference here.
What you will notice additionally, is that the ! and bool operator is overloaded. Please see here and here. With that, it is very simple to check the result of an IO-operation.
Example. Let us assume that you want to open a stream to a file.
// Open text file
std::istream fileStream{"test.txt"};

To check, if that worked, you can write
// Check, if open worked
if (fileStream)  // bool operator will be invoked
    std::cout << "Success\n";

Negative test can be done with:
// Check, if open proble
if (!fileStream)  // ! operator will be invoked
    std::cout << "Problem\n";

OK, next, the IO operation:
int x; std::cin >> x;

You may have read that the extractor >> and the inserter << operator, return a reference to the stream for which they were invoked. With that a chain of operations can be done:
int x,y,z; std::cin >> x >> y >> z;

How does this work? So, first the operation std::cin >> x is done. which return std::cin. Then the line reads like std::cin >> y >> z. Y is extracted and again std::cin is returned. Now we have std::cin >> z. Z is extracted and return std::cin. And std::cin has the bool operator overloaded. This can be checked with a simple if:
int x;
if (std::cin >> x) {
    std::cout << "Integer value " << x << " read\n";
}
else {
    std::cerr << "\nError while reading an integer value\n";
}

So, you cannot enter nonesense like "abc". If an integer can be converted from the input, it will do that. Caveat with things like "1,23".
We can also combine this with additional criterea. And this with the help of boolean shortcut evaluation:
int x;
if (std::cin >> x and x >= 0 and x<= 100) {
    // Do something
}
else
{
    std::cerr << "\nWrong input\n";
}

The above will get a number betwenn 0..100.
So, for the future, check the result of IO operations . . .

If you really want to read unknown data types, then please read a string and parse it. Either by handcrafted analysis or by parsing techniques.

A: I don't think it would be possible to declare a variable's type at runtime, because types must be known at compile time. You could try to use the boost libraries:
boost::variant<std::string, int, float, char> x;

but then it would be cumbersome to identify the intended type of whatever the user inputs.
For your second question, you could use typeid(x).name(), where x is the name of the variable you want to find the type of; however, this returns a mangled result, which is fine if you're using MSVC since it automatically handles the demangling for you, but not so great if you're using another compiler. If you're using another compiler, you have to demangle the result of calling typeid(x).name(), and for that, I would recommend looking at https://gcc.gnu.org/onlinedocs/libstdc++/manual/ext_demangling.html
Edit: You need to #include <typeinfo> to use typeid(x)

A: i write a program like this to judge :
read it as a string and we write judge-fuctions
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
struct unknown
{
    private: char ch[1024];
    public: void Input()
    {
        scanf("%s",ch);
        return ;
    }
    public: bool IsInt()
    {
        bool flg=true;
        for(int i=0;i<(int)strlen(ch);i++)
        if(ch[i]<'0'||ch[i]>'9')
        {
            flg=false;
            break;
        }
        return flg;
    }
};
int main()
{
    unknown x;
    x.Input();
    if(x.IsInt())
    printf("Int");
    return 0;
}


text:
Q: Mapbasic code runs but no output is generated My code (from previous questions here) to generate a list runs but there is no output...
Include "MapBasic.def"

Declare Sub Main

Sub Main
Dim path_to_temp_tables As String
path_to_temp_tables = ""

'Run the Dos Command
Run program "Cmd.exe /c dir """+path_to_temp_tables+"*.tab"" /b /w  > """+path_to_temp_tables+"List.txt"""

End Sub

Also even if I run the cmd manually and get the List.txt file I get a file not found error on running the code
    Include "MapBasic.def"

Declare Sub Main
Declare Sub ReadTextFileToArray(ByVal txtFilePath as String, myArray() as String)

Sub Main()
Dim myArray() as String    '// create an array to store the table paths
Dim tabName, tabPath, txtFile as String
Dim i as Integer

'// test file
txtFile = "List.txt"

'// create your list of paths text file... then:

Call ReadTextFileToArray(txtFile, myArray) '// populate your array with the table paths from the text file

For i = 1 to UBound(myArray)
    If right$(myArray(i), 3) = "tab" then   '// check that this is a tab file path
        tabPath = myArray(i)    '// get path from array
        Open table tabPath      '// open table
        tabName = TableInfo(0, TAB_INFO_NAME)   '// get table name
        Alter table tabName(drop igds_class,igds_color,igds_graph,igds_style,igds_weigh add elevation_text Char(10) order elevation_text,elevation,contour_le,tile_name,contour_type)   '// alter table
        Update tabName Set elevation_text = elevation+"m"
        Pack table tabName  Graphic Data    '// pack table
    End if
Next    '// go to next element in array

End Sub

Sub ReadTextFileToArray(ByVal txtFilePath as String, myArray() as String)

Dim i as Integer

    i = 1

    Open file txtFilePath for input as #1   '// open text file for input (to read) as #1
    Do Until EOF(1)             '// do until the end of file #1 is reached
        Redim myArray(i)        '// resize array to i
        Input #1, myArray(i)    '// read value from text file
        i = i + 1               '// increment i
    Loop                        '// return to Do Until...

End Sub


text:
Q: I get the Jtable but no data
Possible Duplicate:
I can't get my JTable to show anything

I can show my Table but I can't get any data in the table, just the column name. My code looks like this.
public static DefaultTableModel buildTableModel(ResultSet rs)
            throws SQLException {

        java.sql.ResultSetMetaData metaData = rs.getMetaData();

        // names of columns
        Vector<String> columnNames = new Vector<String>();
        int columnCount = metaData.getColumnCount();
        for (int column = 1; column <= columnCount; column++) {
            columnNames.add(metaData.getColumnName(column));
        }

        // data of the table
        Vector<Vector<Object>> data = new Vector<Vector<Object>>();
        while (rs.next()) {
            Vector<Object> vector = new Vector<Object>();
            for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {

                vector.add(rs.getObject(columnIndex));

            }
            data.add(vector);
        }

        return new DefaultTableModel(data, columnNames);

    }

and my kaldSql looks like this.
public ResultSet Hentalleordreliste(Connection con){

    ResultSet Hentalleordreliste = null;

    try {
        PreparedStatement statement = con.prepareStatement("select varebestillinger.BestillingsID, " +
                "varebestillinger.LeverandoerID, "+
                "varebestillinger.BestillingsDato, varebestillinger.LeveringsDato, "+
                "varebestillinger.BestillingsStatus, varebestillinger.ModtagetAf, "+
                "varebestillinger.ModtagelsesDato, varebestillingsliste.Vare, " +
                "varebestillingsliste.Antal from varebestillinger left outer join " +
                "varebestillingsliste on  ListeID = BestillingsID");
                ResultSet rs = statement.executeQuery();

        while(rs.next()) {
            Hentalleordreliste = rs;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return Hentalleordreliste;

}

and the GUI looks like this.
public GUIHentOrdre() {

    try {
        con = ks.connectNow();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    ResultSet rs = ks.Hentalleordreliste(con);
    GUIOrdreHandler gh = new GUIOrdreHandler();
    JTable table = null;
    try {
        table = new JTable(gh.buildTableModel(rs));
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Handler handler = new Handler();

    JPanel info = new JPanel();
    info.setLayout(new BorderLayout());
    LavBestilling = new JButton("Lav ny bestilling");
    TableModel ClassOrVoidOrModelNameReturnsTableModel = null;
    JScrollPane scroll = new JScrollPane(table);
    info.setSize(1024, 768);
    add(scroll, BorderLayout.CENTER);
    add(LavBestilling, BorderLayout.NORTH);

    LavBestilling.addActionListener(handler);

}

As told before, I can get the column name, I can create my table but cant get any data stored inside.

A: Unless you're using a database that supports cursors, I would take a look hard look at
while(rs.next()) {
    Hentalleordreliste = rs;
}

Which would suggest that you're exhausted the result BEFORE you've tried to populate the table model...


text:
Q: In javascript find () method of an array how to get any element using only array argument of the callback function? See the code below var check = [1,2,3,4,5,6];
var check1 =check.find((elements,index,array)=>{ return array ;}); console.log(check1);

Output is 1. Why? And if i want 3 as output from above array by giving checks or condition to the array argument then how to get it?

A:
The find method executes the callbackFn function once for each index of the array until the callbackFn returns a truthy value. If so, find immediately returns the value of that element. Otherwise, find returns undefined.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
And since you aren't really doing any checks and just returning c (a truthy value), which is the array itself, that's why it returns 1.
If you want to find 3 or any other value, you do the following (also name your function params better so it's easier to understand what is going on):
var check = [1, 2, 3, 4, 5, 6];
var check3 = check.find((element, index, array) => {
  return element === 3
});
console.log(check3); // output : 3

A: In response to OP request in comments. The third parameter of the callback function passed into array.find can be used to modify the original array based on a condition. This example switches even values to the odd value 1.
const check = [1,2,3,4,5,6]
check.find((el, index, arr) => {
    if (el % 2 === 0){
        arr[index] = 1
    }
})
console.log(check) // [2,2,3,4,5,6]

However, this is not the proper use of .find, and .find should not be used in this way. .find should be used to simply return the first value of an array that satisfies a condition, as decho explained in his answer. If you are wanting to update the values in an array consider using a for loop or .forEach.

A: Based on your comment here's how to check if a number exists at a particular index, and returning the number based on that check.

var check = [1, 2, 3, 4, 5, 6];

var check1 = check.find((el, i, arr) => {
  return arr.indexOf(3) > 1 && el === 3;
});

var check2 = check.find((el, i, arr) => {
  return arr.indexOf(3) > 3 && el === 3;
});

console.log(check1);
console.log(check2);


text:
Q: Как удалить из папки все файлы которые меньше 100 байт? Хочу реализовать удаление из папки C:\Users\userprofile\Downloads\ppp всех файлов меньше 100 байт?
Вот такой код использую , но где то ошибка:

const fs = require('fs');
const path = 'c:\\Users\\userprofile\\Downloads\\ppp';
const max = 100

fs.readdir(path, (err, items) => {
    for (let i=0; i<items.length; i++) {
        const file = path + '\\' + items[i];
        (file => fs.stat(file, (err, stats) => {
      if (!stats.isFile()) return
      if (stats.size < max) {
        console.log('Удаление файла', file);
        console.log(stats.size);
        fs.unlinkSync(file, err => console.log(err))
      }
        }))(file);
    }
});


text:
Q: Diamond Problem C++: Derived class of diamond calls default constructor So as part of the public API of my program I expose class D, such that the user inherits from class D to create their own classes.
However class D is the tip of the deadly diamond and I have run into an issue where the user's classes are calling the default constructor of class A, instead of the parametrized constructor as desired.
  A
 / \
B   C
 \ /
  D
  |
E or F

In the following code, class E is a clean API however calls the wrong A constructor. Class F works as intended, however the user has to add A's parameterised constructor, which is ugly because that class is an internal class.
Is there a way to have class E work as intended? Why is this happening?
#include<iostream>
using namespace std;
class A {
public:
    A(int x)  { cout << "A::A(int ) called" << endl;   }
    A()     { cout << "A::A() called" << endl;   }
};

class B : virtual public A {
public:
    B(int x): A(x)   {
       cout<<"B::B(int ) called"<< endl;
    }
};

class C : virtual public A {
public:
    C(int x): A(x) {
        cout<<"C::C(int ) called"<< endl;
    }
};

class D : public B, public C  {
public:
    D(int x): A(x), B(x), C(x)   {
        cout<<"D::D(int ) called"<< endl;
    }
};

class E : public D {
public:
    E(int x): D(x) {
        cout<<"E::E(int ) called"<<endl;
    }
};

class F : public D {
public:
    F(int x): D(x), A(x) {
        cout<<"F::F(int ) called"<<endl;
    }
};

int main()  {
    D d(0);
    cout<<endl;
    E e(1);
    cout<<endl;
    F f(2);
}

Output:
A::A(int ) called
B::B(int ) called
C::C(int ) called
D::D(int ) called

A::A() called
B::B(int ) called
C::C(int ) called
D::D(int ) called
E::E(int ) called

A::A(int ) called
B::B(int ) called
C::C(int ) called
D::D(int ) called
F::F(int ) called

A: When constructing a class that has any virtual bases, initializers that name a virtual base class are only called for the most derived class. If your class has any virtual base classes, and you want to use the non-default constructor of that virtual base, then you must specify that constructor in the derived class.
1 "All virtual base subobjects are initialized before any non-virtual base subobject, so only the most derived class calls the constructors of the virtual bases in its member initializer list: ..."
2 "The initializers where class-or-identifier names a virtual base class are ignored during construction of any class that is not the most derived class of the object that's being constructed."
This topic is relatively new to me, so I hope anybody with more experience will point out any nuance I missed.


text:
Q: Identifying groups in Group By NEW select v.vehicleID, y.year, ma.make, mo.model, s.style, p.partID, p.dateModified
from Part as p
join VehiclePart as vp on p.partID = vp.partID
join Vehicle as v on vp.vehicleID =  v.vehicleID
join Year as y on v.yearID = y.yearID
join Make as ma on v.makeID = ma.makeID
join Model as mo on v.modelID = mo.modelID
join Style as s on v.styleID = s.styleID
where p.status != 999
group by p.partID, ma.make, mo.model, s.style, y.year, vp.drilling

And I get results like this:

I want all the Volkswagen Golf, "2 or 4 door H", 11000, 2013-10-09 to have a generated column(alias) to have a groupID (such as 1)
then I want all the volkswagen gti, "2 or 4 door H" 11000, 2013-10-09 to have a generated column(alias) to have a groupID of 2 and so on.
So basically each of the "groups" would have their own ID.

A: That is possible, but it is better to have sort of a group identifier or a hash consisting of soms selections. For example
SELECT MD5(CONCAT(mo.model, p.dateModified)) AS group_identifier, * FROM ...

Then you have a unique identifier of each group, which is always the same, but not a number. When you want a number, you come up with some problems such as mapping a number to a certain group of sub identifiers. So a hash is probably a better solution for you problem.


text:
Q: how to find difference in days between day and month irrespective of years I want to know the difference between to two dates irrespective of year..
For Example : format date/month/year
For example difference of today date to some date lets take 01/06
The expected answer for this will be around 185 days..
I tried below example..Let me know whats wrong with this
   var a = moment('06/01','M/D');
   console.log(a);
   var b = moment();
   console.log(b);

   var diffDays = b.diff(a, 'days');
   alert(diffDays);

I dont want to use momet.js atmost. If it can be done with javascript its so good for me.

A: A nice trick could be to set the year to always the same.
   var a = moment('2015/06/01','Y/M/D');
   console.log(a);
   var b = moment().set('year', 2015);
   console.log(b);

   var diffDays = b.diff(a, 'days');
   alert(diffDays);

The problem about your question in general is how to deal with leap years; how the script should know the difference between 2/20 and 3/1 ? You have to consider how to solve this.

A: Barth Zaleweski is 100% on track with that.  If you want to use straight javascript:
    var today = new Date();
    var otherDate = new Date(today);

    otherDate.setMonth(5); // Set the month (on scale from 0 to 11)
    otherDate.setDate(1); // set day

    var seconds = (otherDate.getTime() - today.getTime()) / 1000;
    var minutes = seconds / 60;
    var hours = minutes / 60;
    var days = hours / 24;
    console.log(days);

There are methods for setting hour/minute/second as well, but if you don't do anything they'll be the same as the start, and you can obviously call those same methods on your start time if you don't want to use today.

A: Can try using this:
var str1 = '06/01', str2 = '02/28', d1, d2, diff;

function setDate(str, date) {
    var date = new Date(),
        dateParts = str.split('/'),
        monthIndex = parseInt(dateParts[0], 10) - 1,
        day = parseInt(dateParts[1], 10);

    date.setMonth(monthIndex);
    date.setDate(day);
    return date
}

d1 = setDate(str1);
d2 = setDate(str2);
diff = Math.round(Math.abs((d1 - d2) / (24 * 60 * 60 * 1000)))
console.log(diff) // returns 93

The rounding is due to differences in daylight savings (or other locale time shifts within the year) that can cause decimal values returned.
It is probably better to use UTC for this
If current year is leap year and dates span end of February then Feb 29 would also be counted
DEMO

A: If it is this year then I am getting a difference of 147 using a library that I have been working on (AstroDate) which doesn't rely on javascript's Date object, it's all done with pure math.

require.config({
    paths: {
        'astrodate': '//rawgit.com/Xotic750/astrodate/master/lib/astrodate'
    }
});

require(['astrodate'], function (AstroDate) {
    "use strict";

    var diff = new AstroDate("2015","6","1").jd() - new AstroDate("2015","1","5").jd();

    document.body.appendChild(document.createTextNode(diff));
});
<script src="http://requirejs.org/docs/release/2.1.8/minified/require.js"></script>

If it was next year, which is a leap year then I am getting 148

require.config({
    paths: {
        'astrodate': '//rawgit.com/Xotic750/astrodate/master/lib/astrodate'
    }
});

require(['astrodate'], function (AstroDate) {
    "use strict";

    var diff = new AstroDate("2016", "6", "1").jd() - new AstroDate("2016", "1", "5").jd();

    document.body.appendChild(document.createTextNode(diff));
});
<script src="http://requirejs.org/docs/release/2.1.8/minified/require.js"></script>


text:
Q: WPF Layout - Fill Height, Auto Scrollbar The Grid at the bottom contains a ListBox.  It stretches vertically, but the scrollbar does not appear when it reaches the bottom.

Layout --
<RibbonWindow ResizeMode="CanResize">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <StackPanel>
            <Ribbon ... />

            <ListBox
                VerticalAlignment="Stretch"
                ScrollViewer.VerticalScrollBarVisibility="Auto"
            />
        </StackPanel>
    </Grid>
</RibbonWindow>

I have heard that StackPanels can cause this behavior, but replacing it with a Grid causes its own set of issues.
EDIT --
This Layout works -
<RibbonWindow ResizeMode="CanResize">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <Ribbon Grid.Row="0" />

        <ListBox Grid.Row="1"
            VerticalAlignment="Stretch"
            ScrollViewer.VerticalScrollBarVisibility="Auto"
        />
    </Grid>
</RibbonWindow>

A: Turns out I needed the Grid.Row="x" tags, and then I could remove the StackPanel, and everything worked.


text:
Q: Getting a value from Dexie promise Trying to get data returned by the below function using Dexie.JS:
function findEvent(key) {
  let snippet = '';
  if (!db.isOpen()) {
    lastEvent = lastEvent.then(() => db.open());
  }
  lastEvent = lastEvent.then(() => db.transaction('r', db.events, () => {
    db.events.each((element) => {
      let d = element.cause.data;
      if (d.hasOwnProperty('deleted') && (false == d.deleted) && d.hasOwnProperty('abbreviation') &&
        d.hasOwnProperty('contents') && (d.abbreviation == key)) {
          console.log(`found matching snippet for key: ${key}, contents: ${d.contents}`);
          snippet = d.contents;
      }
    }).then(() => {
      console.log('search callback returning:', snippet);
      return snippet;
    });
  }));

  return lastEvent;
}

I call it as:
  return findEvent(request.key).then((result) => {
    console.log(`findEvent return: ${result}`);
  });

Apparently, I am doing something wrong. My promises are executed in the correct order. I get snippet printed correctly in the log from inside findEvent. When result is logged in the calling code, it is undefined.
What should be done differently?

A: You're not returning the promise from db.events.each, so undefined gets piped into your top level promise.


text:
Q: command not found Mais uma dúvida de novato
echo "Enter an integer number"
read int
checkNum=$(( int % 2 ))

if [$checkNum -eq '0' ]; then

 echo "the number is even"
else
  echo "the number is odd"
fi

Erro quando digito qualquer número:

./test4.sh: line 9: [0: command not found
  the number is odd


text:
Q: Disabling Random-MAC permanetly on Samsung Hello Stackoverflow Communitie,
does anyone know how to disable the random-mac permanetly. I know where to set the tablet mac and I only can find instructions how to do that, but after a reboot of the tablet I have to change the mac-adress again.
Thank you for your time and help. If there is a better place to ask this questions please tell me.

A: It is not possible to change the random MAC to the tablet MAC permanently. After a reboot of your tablet you have to repeat the process of changing the random MAC to the tablet MAC.
The following Websites are my sources:
https://wifi-helpcenter.nokia.com/hc/en-us/articles/360056890733-Issues-with-random-MAC-addresses-Android-10-iOS-14-
https://source.android.com/devices/tech/connect/wifi-mac-randomization
How to change random MAC to Tablet MAC:
https://www.easytechguides.com/disable-device-security-on-a-samsung-galaxy/
After a reboot you have to repeat the process.


text:
Q: how to refresh data from a json url in android? I have created an application to listen to webradio from an URL and display the artist's name/song's from a JSON URL. It's working but I would like to change these names when a new song begins. For that I suppose I need to refresh the data from the JSON URL but I don't know how.
I have tried many tutorials but I can't find the solution. Thank you.
Mainactivity :
 public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        btn_play = (Button) findViewById(R.id.buttonplay);
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        progressDialog = new ProgressDialog(this);

        if (initialStage) {
            new Player().execute("http://www.radioking.com/play/tft-radio");
            btn_play.setBackgroundResource(R.drawable.pause);
        } else {
            if (!mediaPlayer.isPlaying())
                mediaPlayer.start();
        }

        btn_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!playPause) {
                    btn_play.setBackgroundResource(R.drawable.pause);
                            mediaPlayer.start();
                    playPause = true;

                } else {
                    btn_play.setBackgroundResource(R.drawable.playbutton);

                    if (mediaPlayer.isPlaying()) {
                        mediaPlayer.pause();
                    }

                    playPause = false;
                }
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (mediaPlayer != null) {
            mediaPlayer.reset();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    class Player extends AsyncTask<String, Void, Boolean> {
        @Override
        protected Boolean doInBackground(String... strings) {
            Boolean prepared = false;

            try {
                mediaPlayer.setDataSource(strings[0]);
                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mediaPlayer) {
                        initialStage = true;
                        playPause = false;
                        btn_play.setText("Lecture");
                        mediaPlayer.stop();
                        mediaPlayer.reset();
RestOperation test = new RestOperation();
            String test2 = null;
            try {

                test2 = test.execute(restURL).get().toString();
                Log.i("result", test2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }

            splitArray = test2.split(",");
            artiste = (splitArray[0]).replace("{\"artist\":\"","");
            finalArtiste = artiste.replace("\"","");
            titre = (splitArray[1]).replace("\"title\":\"","");
            finalTitre = titre.replace("\"","");
            image = (splitArray[3]).replace("\"cover\":\"","");
            finalImage = image.replace("\"","");
            finalImage2 = finalImage.replace("\\","");

            Log.i("splitage",finalImage2);

            tvTitre = (TextView) findViewById(R.id.tv_titre);
            tvArtiste = (TextView) findViewById(R.id.tv_artiste);

            tvTitre.setText("Titre : " + finalTitre);
            tvArtiste.setText("Artiste : " + finalArtiste);

            welcome = (ImageView) findViewById(R.id.imgArtiste);

    if(finalImage2.contains("http") ){
        Picasso.with(this).load(finalImage2).into(welcome);
    }else {
        welcome.setBackgroundResource(R.drawable.logokol);
    }
                        }
                    });

                mediaPlayer.prepare();
                prepared = true;

            } catch (Exception e) {
                Log.e("MyAudioStreamingApp", e.getMessage());
                prepared = false;
            }

            return prepared;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);

            if (progressDialog.isShowing()) {
                progressDialog.cancel();
            }

            mediaPlayer.start();
            initialStage = false;
        }

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

            progressDialog.setMessage("Chargement...");
            progressDialog.show();
        }
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    private class RestOperation extends AsyncTask<String, Void, String> {

        String content;
        String error;
        ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
        String data = "";

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

            progressDialog.setTitle("Please wait ...");
//            progressDialog.show();

        }

        @Override
        protected String doInBackground(String... params) {
            BufferedReader br = null;

            URL url;
            try {
                url = new URL(params[0]);

                URLConnection connection = url.openConnection();
                connection.setDoOutput(true);

                OutputStreamWriter outputStreamWr = new OutputStreamWriter(connection.getOutputStream());
                outputStreamWr.write(data);
                outputStreamWr.flush();

                br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line = null;

                while((line = br.readLine())!=null) {
                    sb.append(line);
                    sb.append(System.getProperty("line.separator"));
                }

                content = sb.toString();

            } catch (MalformedURLException e) {
                error = e.getMessage();
                e.printStackTrace();
            } catch (IOException e) {
                error = e.getMessage();
                e.printStackTrace();
            } finally {
                try {
                    br.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            return content;
        }

        }

    }

A: You have to add the web service call into your CompletionListener
 mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
     @Override
     public void onCompletion(MediaPlayer mp) {
         test2 = test.execute(restURL).get().toString();
     }
});

A: test2 = test.execute(restURL).get().toString();

is not the way you should execute async task (AsyncTask is by definition asynchrone).
You should use your result in onPostExecute(..) method.
Take a look at https://developer.android.com/reference/android/os/AsyncTask.html


text:
Q: ExtJS could not load data to grid from JSON file I'm a newbee in ExtJS and I have a problem with loading data to grid from JSON file.
Here's my code:
Model:
Ext.define('EXP.model.EXT.EXTModel', {
extend: 'Ext.data.Model',
fields: [
    {name: 'id'},
    {name: 'name'},
    {name: 'email'}
]
});

Store:
Ext.define('EXP.store.EXT.EXTStore', {
extend: 'Ext.data.Store',
storeId:'EXTStore',
model: 'EXP.model.EXT.EXTModel',
autoLoad: true,

proxy: {
type: 'ajax',
url: 'data/users.json',
reader: {
type: 'json',
root: 'users',
successProperty: 'success'
}
}
});

View:
Ext.define('EXP.view.EXT.ComponentsField' ,{
extend: 'Ext.grid.Panel',
alias: 'widget.componentsfield',
title: 'All Users',
store: 'EXT.EXTStore',
initComponent: function() {
this.columns = [
{header: 'Id', dataIndex: 'id', flex: 1},
{header: 'Name', dataIndex: 'name', flex: 1},
{header: 'Email', dataIndex: 'email', flex: 1}
];
this.callParent(arguments);
}
});

JSON File:
{
  "users": [
  {"id": 1, "name": "Ed", "email": "ed@sencha.com"},
  {"id": 2, "name": "Tommy", "email": "tommy@sencha.com"}
  ]
}

Do I need something more to display this data? I've red a couple of topics about my issue, but none of them was helpful. :(
I haven't any errors in the console. Grid is displaying, but it have no data in it.


text:
Q: The set of elements of order $7$ of $A_7$ is not a conjugacy class. I think the problem is simple but I just want to make sure I am doing it right.
Elements of order $7$ are of the form $(abcdefg)$. There are $6!$ such elements. But $6! \nmid 7!/2$ and thus if it was a conjugacy class, it would contradict orbit stabilizer theorem.

A: Yes, your solution is good.

In fact, it is not too hard to determine a "splitting" criterion (if you already understand wreath products, anyway).
Permutations of a given cycle type are a conjugacy class in $S_n$. As an $S_n$-set, by Orbit-Stabilizer the conjugacy class of $\sigma$ is equivalent to the coset space $S_n/C(\sigma)$. Under conjugation, the $A_n$-orbit of $\sigma$ corresponds to the subset $A_nC(\sigma)/C(\sigma)$ of $S_n/C(\sigma)$. The conjugacy class "inerts" (doesn't split) when
$$ \left|\frac{S_n}{C(\sigma)}\right|=\left|\frac{A_nC(\sigma)}{C(\sigma)}\right|=\left|\frac{A_n}{A_n\cap C(\sigma)}\right| $$
which may be rearranged to
$$ 2=\left|\frac{S_n}{A_n}\right|=\left|\frac{C(\sigma)}{A_n\cap C(\sigma)}\right|. $$
The sign homomorphism $C(\sigma)\to\mathbb{Z}_2$ shows $C(\sigma)$ is either half even / half odd elements (if the homomorphism is onto) or all even elements (if the homomorphism is trivial). Thus, the only time the equality above fails (i.e. the conjugacy class of $\sigma$ splits in $A_n$) is if $C(\sigma)\subseteq A_n$ is all even elements.
Let $c_k(\sigma)$ denote the number of $k$-cycles of $\sigma$. Then
$$ C(\sigma)=\prod_{k=1}^n \mathbb{Z}_k\wr S_{c_k(\sigma)} $$
is a direct product of wreath products of cyclic groups. The $c_k(\sigma)$-many copies of $\mathbb{Z}_k$
$$\mathbb{Z}_k\wr S_{c_k(\sigma)}=(\underbrace{\mathbb{Z}_k\times\cdots\times\mathbb{Z}_k}_{c_k(\sigma)})\rtimes S_k$$
are generated by the $k$-cycles of $\sigma$, and the elements of $S_{c_k(\sigma)}$ "block"-permute the cycles themselves.
A low-tech way to understand this is to write cycles of common length (in cycle notation) in rows to form rectangles. For instance, if $\sigma=(123)(456)$ then we may write the rectangle
$$ \begin{array}{ccc} 1 & 2 & 3 \\ 4 & 5 & 6 \end{array} $$
The elements of $C(\sigma)\subset S_6$ are generated by those that cycle the labels of individual rows and permutations of the rows themselves (preserving the order of labels within the rows). That is, $C(\sigma)$ is generated by $\mathbb{Z}_3\times\mathbb{Z}_3=\langle(123),(456)\rangle$ and $S_2=\{e,(14)(25)(36)\}$.
Exercise. $C(\sigma)\subseteq A_n$ if and only if $\sigma$ is a product of distinct odd-length cycles.


text:
Q: How to fill missing values when you have it in both columns? dictionary - map( ) method I have this scenario. I'm in the process of learning. I'm cleaning a dataset. Now I have a problem
There are a lot of rows that have this issue
I have the key but not the name product. I have the name product but not the key.
prod_key    product
0   21.0    NaN
1   21.0    NaN
2   0.0 metal
3   35.0    NaN
4   22.0    NaN
5   0.0 wood

I know that the key of metal is 24 and the key of wood is 25
The product name that belongs to key 21 is plastic and the product name that belongs to key 22 is paper
There are hundreds of rows with the same situation. So, rename each and everyone of them will take me a lot of time.
I created a dictionary and then I used the .map() method but I'm still unable to 'merge' or you can say 'mix' the missing values in both columns without removing the other column value.
Thank you

A: You can create an extra dataframe and do merge two times
lst = [
    ['metal',   24],
    ['wood',    25],
    ['plastic', 21],
    ['paper',   22]
]

df2 = pd.DataFrame(lst, columns=['name', 'key'])

df1['product'].update(df1.merge(df2, left_on='prod_key', right_on='key', how='left')['name'])

df1['prod_key'].update(df1.merge(df2, left_on='product', right_on='name', how='left')['key'])

print(df2)

      name  key
0    metal   24
1     wood   25
2  plastic   21
3    paper   22

print(df1)

   prod_key  product
0      21.0  plastic
1      21.0  plastic
2      24.0    metal
3      35.0      NaN
4      22.0    paper
5      25.0     wood


text:
Q: Nodejs GraphQL cannot connect to interface on localhost I am setting up a GraphQL API for accessing postgreSQL database on localhost but currently I can not connect to the GraphQL browser interface. I have checked that node is up to date and graphql dependecies are installed, the client configurations are correct as I can access the database through psql.
After I run node server.js in the root directory and access the api through its url in a browser it loads forever and nothing happens. The code is working on my partner's machine so I am not sure what is going on.
How can I log any errors after app.listen?
const express = require('express')
const { graphqlHTTP } = require('express-graphql')
const graphql = require('graphql')
const { Client } = require('pg')
const joinMonster = require('join-monster')

const client = new Client({
    host: "localhost",
    user: "postgres",
    password: "postgres",
    database: "postgres"
})
client.connect()

......

const app = express()
app.use('/api', graphqlHTTP({
    schema: schema,
    graphiql: true,
}))

app.listen(4000, () => {
 console.log('Server running on port %d', 4000);
});

A: //server.js

import path from 'path';
import express from 'express';
import graphQLHTTP from 'express-graphql';
import cors from 'cors';
import config from './server/config/environment';
import schema from './server/data/schema';

if (config.env === 'production') {
  // Launch GraphQL
  const graphql = express();

  graphql.use(cors({credentials: true, origin: true}));

  graphql.use('/graphql', graphQLHTTP((req, res) => ({
      schema,
      graphiql: true
  }))
  );

  graphql.listen(config.port, () => {
    console.log(chalk.green(`GraphQL is listening on port ${config.port}`))
  });
}

//db.js

 import Sequelize from 'sequelize';
    import {Op} from 'sequelize';

    const sequelize = new Sequelize('', '', '', {
      host: 'localhost',
      port:5432,
      dialect: 'postgres',
      operatorsAliases: Op,
    })

    // model list
    const models = {
        Admin: sequelize.import('./admin'),
      };

    models.sequelize = sequelize;
    module.exports = {
        models
    }

// schema.js

var {
    GraphQLSchema,
    GraphQLObjectType,
    GraphQLID,
    GraphQLString,
    GraphQLInt,
    GraphQLBoolean,
    GraphQLList,
    GraphQLNonNull
} = require('graphql');

var Db = require('./db');

var Sectors = new GraphQLObjectType({
  name: 'sectors',
  description: 'list of all the sectors',
  fields: () => {
    return {
      id: {
        type: GraphQLInt,
        resolve (sectors) {
          return sectors.id;
        }
      },
      name: {
        type: GraphQLString,
        resolve (sectors) {
          return sectors.name;
        }
      }
    };
  }
});

var Query = new GraphQLObjectType({
  name: 'Query',
  description: 'Root query object',
  fields: () => {
    return {
      sectors: {
        type: new GraphQLList(Sectors),
        args: {
          id: {
            type: GraphQLInt
          },
          name: {
            type: GraphQLString
          }
        },
        resolve (root, args) {
          return Db.models.sectors.findAll({ where: args });
        }
      }
    };
  }
});

var Schema = new GraphQLSchema({query: Query});
exports.default = Schema;


text:
Q: Colocar nombre a imagen Buenas tardes en mi app tomo una foto con la cámara y seguidamente la guardo en el álbum de fotos de la cámara, pero me la guarda con un nombre por default me gustaría saber como colocarle el nombre que yo quiera a la foto, el código que tengo a la hora de guardar la imagen es el siguiente:
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

        self.guardaImagen = info[UIImagePickerControllerOriginalImage] as? UIImage

        UIImageWriteToSavedPhotosAlbum(self.guardaImagen!, nil, nil, nil);

        self.imagePick.dismissViewControllerAnimated(true, completion: {
            self.performSegueWithIdentifier("envioFotoLink", sender: self)
        })

    }

A: No es posible utilizando el método UIImageWriteToSavedPhotosAlbum ya que la imagen se guarda en el carrete. Es la forma que tiene el sistema de evitar duplicados en el nombre del fichero, mantener una sincronización correcta, etc.
Para más info UIImageWriteToSavedPhotosAlbum Reference
ACTUALIZACIÓN 1
Añado código para guardar imagen en la carpeta Documents
// Carpeta Documents
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]

// Nombre imagen
let imageName = "imagen.png"

// Imagen y imagen en formato NSData
if let image = UIImage(named: "image"), let imageData = UIImageJPEGRepresentation(image, 1.0) {

    // Creamos la URL final
    let filePath = NSURL(fileURLWithPath: documentsPath).URLByAppendingPathComponent(imageName)

    do {

        // Guardamos imagen
        try imageData.writeToURL(filePath, options: [])

    } catch {

        print(error)

    }

}


text:
Q: No converter found capable of converting from type java.lang.Double to type java.lang.Long when fetching a Mongo collection using GORM My model is:
package com.apposit.terra.connect.model

import java.util.Date;

import com.apposit.connect.security.User;
import com.apposit.terra.connect.FertilizerTypeEnum
import com.apposit.terra.connect.InputTypeEnum
import com.apposit.terra.connect.model.AbstractDomain

class UnionAllocation extends AbstractDomain {

    static mapWith = "mongo"

    Organization union
    InputTypeEnum inputType
    FertilizerTypeEnum fertilizerType
    CommodityType seedType
    InputCommodityType seedVariety
    Double requestedAmount = 0.0
    Double allocatedAmount = 0.0
    Double deliveredAmount = 0.0
    Double remaining  = 0.0
    Organization supplier
    Date expectedCompletionDate

    Date dateCreated
    Date lastUpdated
    User createdByUser
    User updatedByUser

    static constraints = {
        union(nullable: false )
        inputType(nullable: false)
        fertilizerType( nullable: true, unique: 'union')
        seedType( nullable: true)
        seedVariety( nullable: true, unique: 'union' )
        allocatedAmount( nullable: false)
        supplier( nullable: true)
        requestedAmount( nullable: true)
        createdByUser( nullable: true )
        updatedByUser( nullable: true )
    }

    static mapping = {
        id generator: 'identity'
        sort id: "desc"
    }
}

And my collection looks like:
/* 0 */
{
    "_id" : NumberLong(14),
    "allocatedAmount" : 450,
    "dateCreated" : ISODate("2014-03-07T05:22:16.832Z"),
    "deliveredAmount" : 0,
    "expectedCompletionDate" : ISODate("2014-03-17T21:00:00.000Z"),
    "inputType" : "SEED",
    "lastUpdated" : ISODate("2014-03-07T05:25:17.996Z"),
    "remaining" : 400,
    "requestedAmount" : 400,
    "seedType" : NumberLong(4),
    "seedVariety" : NumberLong(122),
    "supplier" : NumberLong(1406),
    "union" : NumberLong(1702),
    "version" : NumberLong(1)
}

/* 1 */
{
    "_id" : NumberLong(15),
    "allocatedAmount" : 800,
    "dateCreated" : ISODate("2014-03-07T14:17:02.006Z"),
    "deliveredAmount" : 0,
    "expectedCompletionDate" : ISODate("2014-03-19T21:00:00.000Z"),
    "inputType" : "SEED",
    "lastUpdated" : ISODate("2014-03-07T14:17:02.006Z"),
    "remaining" : 800,
    "requestedAmount" : 800,
    "seedType" : NumberLong(4),
    "seedVariety" : NumberLong(109),
    "supplier" : NumberLong(1406),
    "union" : NumberLong(1757),
    "version" : NumberLong(0)
}

/* 2 */
{
    "_id" : NumberLong(17),
    "allocatedAmount" : 12645.5,
    "dateCreated" : ISODate("2014-03-08T17:22:00.053Z"),
    "deliveredAmount" : 0,
    "expectedCompletionDate" : ISODate("2014-05-08T21:00:00.000Z"),
    "fertilizerType" : "DAP",
    "inputType" : "FERTILIZER",
    "lastUpdated" : ISODate("2014-03-08T17:24:08.372Z"),
    "remaining" : 126455,
    "requestedAmount" : 12434,
    "supplier" : NumberLong(1405),
    "union" : NumberLong(1702),
    "version" : NumberLong(1)
}

/* 3 */
{
    "_id" : NumberLong(19),
    "allocatedAmount" : 2210,
    "dateCreated" : ISODate("2014-03-08T17:27:21.759Z"),
    "deliveredAmount" : 0,
    "expectedCompletionDate" : ISODate("2014-05-08T21:00:00.000Z"),
    "fertilizerType" : "DAP",
    "inputType" : "FERTILIZER",
    "lastUpdated" : ISODate("2014-03-08T17:27:21.759Z"),
    "remaining" : 2210,
    "requestedAmount" : 0,
    "supplier" : NumberLong(1405),
    "union" : NumberLong(1617),
    "version" : NumberLong(0)
}

/* 4 */
{
    "_id" : NumberLong(20),
    "allocatedAmount" : 21068,
    "dateCreated" : ISODate("2014-03-08T17:29:25.274Z"),
    "deliveredAmount" : 0,
    "expectedCompletionDate" : ISODate("2014-05-08T21:00:00.000Z"),
    "fertilizerType" : "DAP",
    "inputType" : "FERTILIZER",
    "lastUpdated" : ISODate("2014-03-08T17:29:25.274Z"),
    "remaining" : 21068,
    "requestedAmount" : 16227,
    "supplier" : NumberLong(1405),
    "union" : NumberLong(1664),
    "version" : NumberLong(0)
}

/* 5 */
{
    "_id" : NumberLong(21),
    "allocatedAmount" : 3000,
    "dateCreated" : ISODate("2014-03-10T04:54:30.172Z"),
    "deliveredAmount" : 0,
    "expectedCompletionDate" : ISODate("2014-03-30T21:00:00.000Z"),
    "inputType" : "SEED",
    "lastUpdated" : ISODate("2014-03-10T04:54:30.172Z"),
    "remaining" : 3000,
    "requestedAmount" : 3000,
    "seedType" : NumberLong(6),
    "seedVariety" : NumberLong(93),
    "supplier" : NumberLong(1406),
    "union" : NumberLong(1430),
    "version" : NumberLong(0)
}

/* 6 */
{
    "_id" : NumberLong(22),
    "allocatedAmount" : 5000,
    "dateCreated" : ISODate("2014-03-11T13:25:09.123Z"),
    "deliveredAmount" : 0,
    "expectedCompletionDate" : ISODate("2014-03-21T21:00:00.000Z"),
    "inputType" : "SEED",
    "lastUpdated" : ISODate("2014-03-11T13:25:09.123Z"),
    "remaining" : 5000,
    "requestedAmount" : 5000,
    "seedType" : NumberLong(13),
    "seedVariety" : NumberLong(54),
    "supplier" : NumberLong(1406),
    "union" : NumberLong(2076),
    "version" : NumberLong(0)
}

/* 7 */
{
    "_id" : NumberLong(23),
    "allocatedAmount" : 5000,
    "createdByUser" : NumberLong(97),
    "dateCreated" : ISODate("2014-03-13T05:34:59.047Z"),
    "deliveredAmount" : 0,
    "expectedCompletionDate" : ISODate("2014-03-28T21:00:00.000Z"),
    "inputType" : "SEED",
    "lastUpdated" : ISODate("2014-03-13T05:34:59.047Z"),
    "remaining" : 5000,
    "requestedAmount" : 5000,
    "seedType" : NumberLong(4),
    "seedVariety" : NumberLong(110),
    "supplier" : NumberLong(1406),
    "union" : NumberLong(2079),
    "version" : NumberLong(0)
}

/* 8 */
{
    "_id" : NumberLong(24),
    "allocatedAmount" : 1000,
    "createdByUser" : NumberLong(97),
    "dateCreated" : ISODate("2014-03-13T06:10:40.031Z"),
    "deliveredAmount" : 300,
    "expectedCompletionDate" : ISODate("2014-05-31T21:00:00.000Z"),
    "inputType" : "SEED",
    "lastUpdated" : ISODate("2014-03-25T11:36:51.085Z"),
    "remaining" : 1000,
    "requestedAmount" : 1000,
    "seedType" : NumberLong(6),
    "seedVariety" : NumberLong(94),
    "supplier" : NumberLong(1407),
    "union" : NumberLong(1523),
    "version" : NumberLong(1)
}

/* 9 */
{
    "_id" : NumberLong(25),
    "allocatedAmount" : 6000,
    "createdByUser" : NumberLong(97),
    "dateCreated" : ISODate("2014-03-13T08:37:27.129Z"),
    "deliveredAmount" : 0,
    "expectedCompletionDate" : ISODate("2014-03-30T21:00:00.000Z"),
    "inputType" : "SEED",
    "lastUpdated" : ISODate("2014-03-13T08:37:27.129Z"),
    "remaining" : 6000,
    "requestedAmount" : 12000,
    "seedType" : NumberLong(6),
    "seedVariety" : NumberLong(94),
    "supplier" : NumberLong(1407),
    "union" : NumberLong(1496),
    "version" : NumberLong(0)
}

/* 10 */
{
    "_id" : NumberLong(26),
    "allocatedAmount" : 500,
    "createdByUser" : NumberLong(97),
    "dateCreated" : ISODate("2014-03-13T12:43:47.693Z"),
    "deliveredAmount" : 0,
    "expectedCompletionDate" : ISODate("2014-03-30T21:00:00.000Z"),
    "inputType" : "SEED",
    "lastUpdated" : ISODate("2014-03-13T12:43:47.693Z"),
    "remaining" : 500,
    "requestedAmount" : 500,
    "seedType" : NumberLong(6),
    "seedVariety" : NumberLong(92),
    "supplier" : NumberLong(1407),
    "union" : NumberLong(1496),
    "version" : NumberLong(0)
}

/* 11 */
{
    "_id" : NumberLong(27),
    "allocatedAmount" : 0,
    "createdByUser" : NumberLong(90),
    "dateCreated" : ISODate("2014-03-13T23:26:00.044Z"),
    "deliveredAmount" : 0,
    "expectedCompletionDate" : ISODate("2014-05-08T21:00:00.000Z"),
    "fertilizerType" : "DAP",
    "inputType" : "FERTILIZER",
    "lastUpdated" : ISODate("2014-03-13T23:26:00.044Z"),
    "remaining" : 0,
    "requestedAmount" : 34506,
    "supplier" : NumberLong(1405),
    "union" : NumberLong(2079),
    "version" : NumberLong(0)
}

/* 12 */
{
    "_id" : NumberLong(28),
    "allocatedAmount" : 0,
    "createdByUser" : NumberLong(90),
    "dateCreated" : ISODate("2014-03-13T23:31:04.347Z"),
    "deliveredAmount" : 0,
    "expectedCompletionDate" : ISODate("2014-05-08T21:00:00.000Z"),
    "fertilizerType" : "UREA",
    "inputType" : "FERTILIZER",
    "lastUpdated" : ISODate("2014-03-13T23:31:04.347Z"),
    "remaining" : 0,
    "requestedAmount" : 26952,
    "supplier" : NumberLong(1405),
    "union" : NumberLong(2079),
    "version" : NumberLong(0)
}

/* 13 */
{
    "_id" : NumberLong(29),
    "allocatedAmount" : 25000,
    "createdByUser" : 97,
    "dateCreated" : ISODate("2014-03-14T05:21:25.536Z"),
    "deliveredAmount" : 0,
    "expectedCompletionDate" : ISODate("2014-03-31T21:00:00.000Z"),
    "inputType" : "SEED",
    "lastUpdated" : ISODate("2014-03-14T05:21:25.536Z"),
    "remaining" : 25000,
    "requestedAmount" : 25000,
    "seedType" : NumberLong(13),
    "seedVariety" : NumberLong(83),
    "supplier" : NumberLong(2156),
    "union" : NumberLong(2079),
    "version" : NumberLong(0)
}

/* 14 */
{
    "_id" : NumberLong(30),
    "allocatedAmount" : 25000,
    "createdByUser" : 97,
    "dateCreated" : ISODate("2014-03-14T05:21:48.485Z"),
    "deliveredAmount" : 0,
    "expectedCompletionDate" : ISODate("2014-03-31T21:00:00.000Z"),
    "inputType" : "SEED",
    "lastUpdated" : ISODate("2014-03-14T05:21:48.485Z"),
    "remaining" : 25000,
    "requestedAmount" : 25000,
    "seedType" : NumberLong(13),
    "seedVariety" : NumberLong(84),
    "supplier" : NumberLong(2156),
    "union" : NumberLong(2079),
    "version" : NumberLong(0)
}

/* 15 */
{
    "_id" : NumberLong(31),
    "allocatedAmount" : 3000,
    "createdByUser" : 97,
    "dateCreated" : ISODate("2014-03-17T13:02:05.912Z"),
    "deliveredAmount" : 0,
    "expectedCompletionDate" : ISODate("2014-04-29T21:00:00.000Z"),
    "inputType" : "SEED",
    "lastUpdated" : ISODate("2014-03-17T13:02:05.912Z"),
    "remaining" : 3000,
    "requestedAmount" : 5000,
    "seedType" : NumberLong(4),
    "seedVariety" : NumberLong(126),
    "supplier" : NumberLong(1407),
    "union" : NumberLong(1686),
    "version" : NumberLong(0)
}

/* 16 */
{
    "_id" : NumberLong(32),
    "allocatedAmount" : 2000,
    "createdByUser" : 97,
    "dateCreated" : ISODate("2014-03-17T13:14:25.379Z"),
    "deliveredAmount" : 0,
    "expectedCompletionDate" : ISODate("2014-05-30T21:00:00.000Z"),
    "fertilizerType" : "DAP",
    "inputType" : "FERTILIZER",
    "lastUpdated" : ISODate("2014-03-17T13:14:25.379Z"),
    "remaining" : 2000,
    "requestedAmount" : 2000,
    "supplier" : NumberLong(1405),
    "union" : NumberLong(1686),
    "version" : NumberLong(0)
}

/* 17 */
{
    "_id" : NumberLong(33),
    "allocatedAmount" : 8000,
    "createdByUser" : NumberLong(97),
    "dateCreated" : ISODate("2014-03-19T10:28:02.631Z"),
    "deliveredAmount" : 0,
    "expectedCompletionDate" : ISODate("2014-06-29T21:00:00.000Z"),
    "fertilizerType" : "UREA",
    "inputType" : "FERTILIZER",
    "lastUpdated" : ISODate("2014-03-19T10:28:02.631Z"),
    "remaining" : 8000,
    "requestedAmount" : 10000,
    "supplier" : NumberLong(1405),
    "union" : NumberLong(1702),
    "version" : NumberLong(0)
}

/* 18 */
{
    "_id" : NumberLong(34),
    "allocatedAmount" : 5000,
    "createdByUser" : NumberLong(97),
    "dateCreated" : ISODate("2014-03-25T14:39:07.030Z"),
    "deliveredAmount" : 1000,
    "expectedCompletionDate" : ISODate("2014-06-29T21:00:00.000Z"),
    "fertilizerType" : "DAP",
    "inputType" : "FERTILIZER",
    "lastUpdated" : ISODate("2014-03-25T14:39:07.030Z"),
    "remaining" : 5000,
    "requestedAmount" : 10000,
    "supplier" : NumberLong(1405),
    "union" : NumberLong(1757),
    "version" : NumberLong(0)
}

/* 19 */
{
    "_id" : NumberLong(35),
    "allocatedAmount" : 6000,
    "createdByUser" : NumberLong(97),
    "dateCreated" : ISODate("2014-03-25T14:39:32.458Z"),
    "deliveredAmount" : 2000,
    "expectedCompletionDate" : ISODate("2014-06-29T21:00:00.000Z"),
    "fertilizerType" : "DAP",
    "inputType" : "FERTILIZER",
    "lastUpdated" : ISODate("2014-03-25T14:39:32.458Z"),
    "remaining" : 6000,
    "requestedAmount" : 10000,
    "supplier" : NumberLong(1405),
    "union" : NumberLong(1523),
    "version" : NumberLong(0)
}

When I do UnionAllocation.list() I get:
org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type java.lang.Double to type java.lang.Long
    at org.grails.datastore.mapping.model.types.conversion.DefaultConversionService.convert(DefaultConversionService.java:21)
    at org.grails.datastore.mapping.engine.NativeEntryEntityPersister.refreshObjectStateFromNativeEntry(NativeEntryEntityPersister.java:478)
    at org.grails.datastore.mapping.mongo.engine.MongoEntityPersister.refreshObjectStateFromNativeEntry(MongoEntityPersister.java:110)
    at org.grails.datastore.mapping.mongo.engine.MongoEntityPersister.refreshObjectStateFromNativeEntry(MongoEntityPersister.java:78)
    at org.grails.datastore.mapping.engine.NativeEntryEntityPersister.createObjectFromNativeEntry(NativeEntryEntityPersister.java:379)
    at org.grails.datastore.mapping.mongo.query.MongoQuery$MongoResultList.convertDBObject(MongoQuery.java:993)
    at org.grails.datastore.mapping.mongo.query.MongoQuery$MongoResultList$1.next(MongoQuery.java:967)

A: I know is a old question, but it could eventually help someone.
Anyway, I had a similar issue and I solve it creating my own converter.
public class LongToDateConverter implements Converter<Long, Date> {
    @Override
    public Date convert(Long lng) {
        if(lng!=null)
            return new Date(lng);
        else
            return null;
    }
}

then I registered as a bean.
@Bean
@Override
public CustomConversions customConversions() throws Exception {
    List<Converter<?, ?>> converterList = new ArrayList<Converter<?, ?>>();
    converterList.add(new LongToDateConverter());

    return new CustomConversions(converterList);
  }

for more details, you can check here:
https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mapping-configuration

A: Have you updated any data manually, i.e. directly using mongodb shell? Data row with id 17 seems to be polluted.


text:
Q: Сохранение активной ссылки Есть меню категорий. При нажатии на определённую категорию нужно, чтобы ссылка стала активной и исчез атрибут href. А так же при переходе на другую страницу (например, страница 2, то есть есть постраничная навигация для текущей категории), эта же ссылка также сохраняла свою актвиность, пока не переключусь на другую категорию.
Как это можно реализовать?

A: Я там понимаю, что при клике на номер страницы происходит переход на эту страницу. То есть надо где-то сохранить данные о том, что пользователь выбрал какую-то категорию и получить эту информацию на новой странице.
Предлагаю сохранять данные о выбранных категориях в $_SESSION при помощи ajax запроса при клике на категорию, а на новой странице из $_SESSION получать эту информацию и отображать ее.