text:
Q: What is the best practice for modeling Java classes with Hibernate? I have a question about what would be the best practice for modeling my Java classes and how they should be related in the database. I'm using Spring-Boot and Spring-Data in the project
I have the situation containing professional Administrative, Professional Financial and Professional Developer. Each of them have specific characteristics.
So, I created a Professional class with the attibutos that are common to all employees:
Professional Class
@Entity
@Table(name = "Professional")
@Inheritance(strategy = InheritanceType.JOINED)
public class Professional {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private String age;

    ... getters e setters
}

The other classes, extend from the professional class:
Administrative Class
@Entity
public class Administrative extends Professional {
    private String attribute1;
    private String attribute2;

    ... getters e setters
}

Financial Class
@Entity
public class Financial extends Professional {
    private String attribute1;
    private String attribute2;

    ... getters e setters
}

Developer Class
@Entity
public class Developer extends Professional {
    private String attribute1;
    private String attribute2;

    ... getters e setters
}

Is this the most appropriate way to handle this scenario? Should I use Class Composition instead of Inheritance? Could you please share examples?
Thank you

A: Inheritance makes more sense here. As an example, composition makes sense where an entity has another entity, e.g.
class Adult extends Person {
    private List<Animal> pets; // person HAS pets (with are another class)
    private ID identityCard; // person HAS an identity card
}

It wouldn't make sense here for a Person to extend either of Animal or ID because they aren't a subset of either. However, they are a child of the Person class so it makes sense to inherit.
In your case inheritance makes sense because your child classes are a subset of the Professional. You wouldn't say that a Developer has a Professional, but they are a Professional.


text:
Q: Is there any pure html way to "combine" markup tags into custom one? I am wondering if I can make something like:
<myTag>myAwesomText</myTag>

While "myTag" is a combination of other html tags, example:

myAwesomText

A: Simply the answer is no, this is not possible in HTML.
Usually your text editor (for example Sublime Text) has an option to create snippets where you can customise a shortcut like <myTag> in which custom HTML or any code can be inserted. If you are interested in this, see Sublime Text and Their Snippet Feature
Note: you could also use a functional language like Javascript to create a feature like this
Also, a hacky way of doing something similar to this is creating a custom html element and using css to modify its properties (although I'm sure this isn't widely supported):

mytag {
  font-weight: bold;
  color:red;
}
<mytag>This is bold and red</mytag>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Webpack weirdly export two images in dist As in title, after build, I found 2 images in dist folder

*

*one with hashed name(the broken one) and

*one with original name(the good one)
but my index.html(in dist) is referenced to the broken one

After few hours of trying, I fixed this problem by commenting out this part in config
{
    test: /\.(jpeg|jpg|png|gif|webp)$/,
    use: {
      loader: 'file-loader',
      options: {
        name: '[name].[ext]',
      }
    }
  }

It's super weird for me because I thought I need file-loader to handle those pictures
Can someone give me a hint? Thank you!
package.json
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');

module.exports = {
  entry:{
    index: path.resolve(__dirname, "src", "js", "index.js"),
    // main: path.resolve(__dirname, "src", "js", "main.js"),
  },
  output: {
    filename:'[name].js',
    path: path.resolve(__dirname, "dist") //output to ./build
  },
  module: {
    rules: [
      {
        test: /\.html$/,
        use: ["html-loader"]
      },
      {
        test: /\.(sa|sc|c)ss$/,
        use: [{loader: MiniCssExtractPlugin.loader}, "css-loader",'postcss-loader',"sass-loader"]
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: ["babel-loader"]
      },
      {
        test: /\.(eot|woff|woff2|[ot]tf)$/,
        use: {
          loader: 'file-loader',
          options: {
              name: '[name].[ext]',
              outputPath: './fonts/',
              publicPath: '/fonts/'
          }
        }
      },
      {
        test: /\.html$/,
        use: {
          loader: 'file-loader',
          options: {
            name: '[name].[ext]',
          }
        },
        exclude: path.resolve(__dirname, "src", "index.html")
      },
      // {
      //   test: /\.(jpeg|jpg|png|gif|webp)$/,
      //   use: {
      //     loader: 'file-loader',
      //   }
      // }

    ]
  },

  plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, "src", "index.html")
    }),
    new CleanWebpackPlugin(),
    new MiniCssExtractPlugin({filename: './[name].css',})
  ],

  optimization: {
    minimizer: [
      new TerserPlugin({
          terserOptions: {
              output: {
                  comments: false
              }
          },
          extractComments: false
      })
    ]
  }

};


text:
Q: React/TypeScript testing failed. "Consider using the "jsdom" test environment." I have a very simple React/TypeScript application, and I'm trying to learn how to implement testing. I'm using React Testing Library and Jest. It's a very simple product page, and I just want to test that the words "Welcome to our product page" have rendered.
When I run the test, I get this error message: The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/configuration#testenvironment-string. Consider using the "jsdom" test environment. ReferenceError: document is not defined.
I went through all the solutions in similar questions on Stack Overflow, but nothing is working. I tried adding
/**
 * @jest-environment jsdom
*/

to the top of the test file, but that just produces a different error message: ReferenceError: global is not defined.
I'd appreciate any help. Below is my code:
ProductPage.test.tsx
import React from "react";
import { render, screen } from "@testing-library/react";
import ProductPage from "../ProductPage";

describe("<ProductPage />", () => {
  test("should display the product page", () => {
    render(<ProductPage />);
    expect(
        screen.getByText(/Welcome to our product page/)
    ).toBeInTheDocument();
  });
});

jest.config.js
module.exports = {
  roots: ["<rootDir>/src"],

  transform: {
    "^.+\\.tsx?$": "ts-jest",
    "^.+\\.svg$": "<rootDir>/svgTransform.js",
    "^.+\\.css$": "<rootDir>/cssTransform.js"
  },

  setupFilesAfterEnv: [
    "@testing-library/jest-dom/extend-expect"
  ],

  testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$",

  moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"]
};

tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "module": "esnext",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "noFallthroughCasesInSwitch": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": [
    "src"
  ]
}

package.json
{
  "name": "product-page",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@apollo/client": "^3.4.17",
    "@babel/core": "^7.16.0",
    "@babel/preset-env": "^7.16.4",
    "@babel/preset-typescript": "^7.16.0",
    "@emotion/react": "^11.6.0",
    "@emotion/styled": "^11.6.0",
    "@mui/material": "^5.1.1",
    "@mui/system": "^5.1.1",
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "@types/jest": "^27.0.2",
    "@types/node": "^16.11.7",
    "@types/react": "^17.0.35",
    "@types/react-dom": "^17.0.11",
    "babel-jest": "^27.3.1",
    "graphql": "^16.0.1",
    "jest": "^27.3.1",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3",
    "ts-jest": "^27.0.7",
    "typescript": "^4.4.4",
    "web-vitals": "^1.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "jest",
    "test:watch": "jest --watch",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "ts-node": "^10.4.0"
  }
}

A: In order to use jsdom you need to add
testEnvironment: 'jsdom',

to your jest.config.js
Edit: You might need to add it as a dependency also.

A: *

*Add testEnvironment: 'jsdom' to jest.config.js. This resolved the jsdom error.

*Add jest-environment-jsdom as a dev dependency (adding jsdom did not help for whatever reason). This resolved the global error.


text:
Q: How to match '/#' in href I'm using this code to match if href attribute starts with # and according to that to add class:
$('.navbar-nav a').each(function(index, element) {
    if($(element).attr("href").match("^#"))
    {
        //Add class to inernal links
        $(element).addClass("internal");
    }
    else
    {
        //Add class to external links
        $(element).addClass("external");
    }
});

Now I have problem to match if href starts with /#. I tried with '^/#' but it doesn't work.
I'll appreciate any help.
Update
Here is the whole code I'm using:
jQuery.noConflict();
(function( $ ) {
  $(function() {
/*********************************************************************************************************/
/* -------------------------------------- Navigation ------------------------------------------ */
/*********************************************************************************************************/
//Add class to inernal and external links
$('.navbar-nav a').each(function(index, element) {
    if($(element).attr("href").match(/^\/?#/))
    {
        //Add class to inernal links
        $(element).addClass("internal");
    }
    else
    {
        //Add class to external links
        $(element).addClass("external");
    }
});

var lastId,
    topMenu = $(".navbar-nav"),
    topMenuHeight = topMenu.outerHeight(),
    // All list items without external links
    menuItems = topMenu.find("a").not(".external"),
    // Anchors corresponding to menu items
    scrollItems = menuItems.map(function() {
        var item = $($(this).attr("href"));
        if (item.length) {
            return item;
        }
    });

// Bind click handler to menu items
// so we can get a fancy scroll animation
menuItems.click(function(e) {
    if (!$(this).hasClass("dropdown-toggle")) {
        var href = $(this).attr("href"),
            offsetTop = href === "#" ? 0 : $(href).offset().top - topMenuHeight + 1;
        $('html, body').stop().animate({
            scrollTop: offsetTop
        }, 1450,  'easeInOutQuart');
        e.preventDefault();
    }
});

// Bind to scroll
$(window).scroll(function() {
    // Get container scroll position
    var fromTop = $(this).scrollTop() + topMenuHeight;

    // Get id of current scroll item
    var cur = scrollItems.map(function() {
        if ($(this).offset().top < fromTop)
            return this;
    });
    // Get the id of the current element
    cur = cur[cur.length - 1];
    var id = cur && cur.length ? cur[0].id : "";

    if (lastId !== id) {
        lastId = id;
        // Set/remove active class
        menuItems
            .parent().removeClass("active")
            .end().filter("[href=#" + id + "]").parent().addClass("active");
    }
});

/*********************************************************************************************************/
/* -------------------------------------- Home part - 100% hight ------------------------------------------ */
/*********************************************************************************************************/
jQuery.fn.refresh = function() {
    var s = skrollr.get();

    if (s) {
        s.refresh(this);
    }
    return this;
};

function fullHeight() {
    windowHeight = $(window).height();
    $('#home, .tp-banner-container').css('height', windowHeight).refresh();
};
fullHeight();
$(window).resize(function() {
    fullHeight();
});

/*********************************************************************************************************/
/* -------------------------------------- H2 big shadow ------------------------------------------ */
/*********************************************************************************************************/
$("h2").each(function () {
    var h2 = $(this);
    var span = h2.parent().find("span.title-shadow");
    span.append(h2.html());
});

/*********************************************************************************************************/
/* -------------------------------------- Back to top ------------------------------------------ */
/*********************************************************************************************************/
$(".logo").click(function() {
  $("html, body").animate({ scrollTop: 0 }, "easeInOutQuart");
  return false;
});

/*********************************************************************************************************/
/* -------------------------------------- Contact form ------------------------------------------ */
/*********************************************************************************************************/
(function(e) {
    function n(e, n) {
        this.$form = e;
        this.indexes = {};
        this.options = t;
        for (var r in n) {
            if (this.$form.find("#" + r).length && typeof n[r] == "function") {
                this.indexes[r] = n[r]
            } else {
                this.options[r] = n[r]
            }
        }
        this.init()
    }
    var t = {
        _error_class: "error",
        _onValidateFail: function() {}
    };
    n.prototype = {
        init: function() {
            var e = this;
            e.$form.on("submit", function(t) {
                e.process();
                if (e.hasErrors()) {
                    e.options._onValidateFail();
                    t.stopImmediatePropagation();
                    return false
                }
                return true
            })
        },
        notEmpty: function(e) {
            return e != "" ? true : false
        },
        isEmail: function(e) {
            return /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(e)
        },
        isUrl: function(e) {
            var t = new RegExp("(^(http[s]?:\\/\\/(www\\.)?|ftp:\\/\\/(www\\.)?|(www\\.)?))[\\w-]+(\\.[\\w-]+)+([\\w-.,@?^=%&:/~+#-]*[\\w@?^=%&;/~+#-])?", "gim");

            return t.test(e)
        },
        elClass: "",
        setClass: function(e) {
            this.elClass = e
        },
        process: function() {
            this._errors = {};
            for (var t in this.indexes) {
                this.$el = this.$form.find("#" + t);
                if (this.$el.length) {
                    var n = e.proxy(this.indexes[t], this, e.trim(this.$el.val()))();
                    if (this.elClass) {
                        this.elClass.toggleClass(this.options._error_class, !n);
                        this.elClass = ""
                    } else {
                        this.$el.toggleClass(this.options._error_class, !n)
                    }
                    if (!n) {
                        this._errors[t] = n
                    }
                }
                this.$el = null
            }
        },
        _errors: {},
        hasErrors: function() {
            return !e.isEmptyObject(this._errors)
        }
    };
    e.fn.isValid = function(t) {
        return this.each(function() {
            var r = e(this);
            if (!e.data(r, "is_valid")) {
                e.data(r, "is_valid", new n(r, t))
            }
        })
    }
})(jQuery)

/*********************************************************************************************************/
/* -------------------------------------- Ajax contact form ------------------------------------------ */
/*********************************************************************************************************/
$('#forms').isValid({
    'name': function(data) {
        this.setClass(this.$el.parent());
        return this.notEmpty(data);
    },
    'email': function(data) {
        this.setClass(this.$el.parent());
        return this.isEmail(data);
    },
    'subject': function(data) {
        this.setClass(this.$el.parent());
        return this.notEmpty(data);
    },
    'message': function(data) {
        this.setClass(this.$el.parent());
        return this.notEmpty(data);
    }
}).submit(function(e) {
    e.preventDefault();

    var $this = $(this);
    $.ajax({
        'url': $(this).attr('action'),
        'type': 'POST',
        'dataType': 'html',
        'data': $(this).serialize()
    }).done(function(response) {
        $this.find('.notification').show();
        $this.find('input[type="text"], input[type="email"], textarea').val('');
    });
    return false;
});

$('.notification').on('click', function() {
    var $this = $(this);
    $this.hide();
});

/*********************************************************************************************************/
/* -------------------------------------- Sticky navigation ------------------------------------------ */
/*********************************************************************************************************/
$("#navigation").sticky({
    topSpacing: 0,
    className: 'sticky',
    wrapperClassName: 'main-menu-wrapper'
});

/*********************************************************************************************************/
/* -------------------------------------- Wow Scroll Animate ------------------------------------------ */
/*********************************************************************************************************/
wow = new WOW({
    boxClass: 'wow',
    animateClass: 'animated',
    offset: 100,
    movile: true

});

/*********************************************************************************************************/
/* -------------------------------------- Skrollr and Wow init ------------------------------------------ */
/*********************************************************************************************************/
if (!/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {

    //Skrollr
    var s = skrollr.init({
        edgeStrategy: 'set',
        forceHeight: true,
        smoothScrolling: true,
        easing: {
            wtf: Math.random,
            inverted: function(p) {
                return 1 - p;
            }
        }
    });
    //Wow init
    wow.init();
}

/*********************************************************************************************************/
/* -------------------------------------- Charts, Skils ------------------------------------------ */
/*********************************************************************************************************/
$('.chart').waypoint(function() {
    $(this).easyPieChart({
        animate: 1000,
        size: 200,
        lineWidth: 5,
        trackColor: "#fff",
        barColor:"#de3926",
        scaleColor: false,
        size: 200,
        onStep: function(from, to, percent) {
            jQuery(this.el).find('.percent').text(Math.round(percent));
        }
    });
}, {
    triggerOnce: true,
    offset: 'bottom-in-view'
});

$(document).ready(function() {
        /*********************************************************************************************************/
    /* -------------------------------------- Ajax our team ------------------------------------------ */
    /*********************************************************************************************************/
    $('.ajax-popup-team').magnificPopup({
        type: 'ajax',
        showCloseBtn: true,
        modal: true,
        closeOnContentClick: false,
        overflowY: 'scroll'
    });

    /*********************************************************************************************************/
    /* -------------------------------------- Ajax portfolio page ------------------------------------------ */
    /*********************************************************************************************************/
    $('.ajax-popup-portfolio').magnificPopup({
        type: 'ajax',
        showCloseBtn: true,
        modal: true,
        closeOnContentClick: false,
        overflowY: 'scroll',
        gallery: {
           enabled: true,
           arrowMarkup: '<button title="%title%" type="button" class="portfolio mfp-arrow mfp-arrow-%dir%"></button>'
        }
    });

    /*********************************************************************************************************/
    /* -------------------------------------- Portfolio gallery ------------------------------------------ */
    /*********************************************************************************************************/
    $('.gallery-item-content').each(function() { // the containers for all your galleries
        $(this).magnificPopup({
            delegate: '.gallery-item', // the selector for gallery item
            type: 'image',
            gallery: {
                enabled: true
            }
        });
    });

    /*********************************************************************************************************/
    /* -------------------------------------- Video ------------------------------------------ */
    /*********************************************************************************************************/
    $('.popup-youtube, .popup-vimeo, .popup-gmaps').magnificPopup({
        disableOn: 700,
        type: 'iframe',
        mainClass: 'mfp-fade',
        removalDelay: 160,
        preloader: true,
        fixedContentPos: true
    });

    /*********************************************************************************************************/
    /* -------------------------------------- Owl carousel ------------------------------------------ */
    /*********************************************************************************************************/
    $("#carousel-our-testimonials").owlCarousel({
        autoPlay: 3000,
        stopOnHover: true,
        navigation: false,
        paginationSpeed: 1000,
        goToFirstSpeed: 2000,
        singleItem: true,
        autoHeight: true,
        transitionStyle: "fade"
    });
    $("#carousel-our-clients").owlCarousel({
        autoPlay: 10000,
        stopOnHover: true,
        navigation: true,
        paginationSpeed: 1000,
        goToFirstSpeed: 3500,
        singleItem: false,
        autoHeight: true,
        transitionStyle: "fade",
        navigationText: [
        "",
        ""
        ]
    });
    $("#blog-single").owlCarousel({
        navigation: true, // Show next and prev buttons
        pagination: false,
        slideSpeed: 300,
        paginationSpeed: 400,
        navigationText: [
            "",
            ""
        ],
        singleItem: true
    });

    /*********************************************************************************************************/
    /* -------------------------------------- Dropdown Menu Fade  ------------------------------------------ */
    /*********************************************************************************************************/
    $(".dropdown").hover(
        function() {
            $('.dropdown-menu', this).fadeIn(275);
            $(this).addClass("open");
        },
        function() {
            $('.dropdown-menu', this).fadeOut(275);
            $(this).removeClass("open");
    });

    /*********************************************************************************************************/
    /* -------------------------------------- Placeholder fix for IE  ------------------------------------------ */
    /*********************************************************************************************************/
    (function($) {
        if (!Modernizr.csstransforms3d) {
            $('[placeholder]').focus(function() {
                var input = $(this);
                if (input.val() == input.attr('placeholder')) {
                    input.val('');
                    input.removeClass('placeholder');
                }
            }).blur(function() {
                var input = $(this);
                if (input.val() == '' || input.val() == input.attr('placeholder')) {
                    input.addClass('placeholder');
                    input.val(input.attr('placeholder'));
                }
            }).blur().parents('form').submit(function() {
                $(this).find('[placeholder]').each(function() {
                    var input = $(this);
                    if (input.val() == input.attr('placeholder')) {
                        input.val('');
                    }
                })
            });
        }
    })

});

/*********************************************************************************************************/
/* -------------------------------------- Count  ------------------------------------------ */
/*********************************************************************************************************/
$('#statistic').waypoint(function() {
    $('.timer').countTo();
}, {
    triggerOnce: true,
    offset: 'bottom-in-view'
});

/*********************************************************************************************************/
/* -------------------------------------- Show and hide color-switcher  ------------------------------------------ */
/*********************************************************************************************************/
$(".color-switcher .switcher-button").click(function(){
    $( ".color-switcher" ).toggleClass("show-color-switcher", "hide-color-switcher", 800);
});

/*********************************************************************************************************/
/* -------------------------------------- Color Skins  ------------------------------------------ */
/*********************************************************************************************************/
$('a.color').click(function(){
    var title = $(this).attr('title');
    $('#style-colors').attr('href', 'css/color-schemes/' + title + '.css');
    return false;
});

/*********************************************************************************************************/
/* -------------------------------------- Loader  ------------------------------------------ */
/*********************************************************************************************************/
$(window).load(function() {
    $("#loader").delay(450).fadeOut(800);
    $(".preload-gif").addClass('fadeOut');

});

});
})(jQuery);

A: If you want to match both, you could change the Regular expression to:
/^\/?#/

The question mark is a 0 or 1 quantifier, that will match whether there is 1 or no / at the beginning.
Check it out here: http://www.regexr.com/3ajoo
Also i used your code and tried to find the error you have: I think there is no error from the answer of this question. Your error must be something else. Try and wrap the function in $(document).ready() to make sure the DOM is loaded before searching the elements.

$(document).ready(function() {

  $('.navbar-nav a').each(function(index, element) {
    if ($(element).attr("href").match(/^\/?#/)) {
      //Add class to inernal links
      $(element).addClass("internal");
    } else {
      //Add class to external links
      $(element).addClass("external");
    }
  });

});
.external {
   color: red;
}

    Link

    Link

    Link

    Link

    Link

A: Use / as delimiter.
if($(element).attr("href").match(/^\/#/))


text:
Q: Cordova 5.3.3 cordovalib.jar not exist I have installed  Cordova 5.3.3 and created android project when i run the project with eclipse it show me these errors as in the image.
http://s3.postimg.org/ebf0f0gg3/image.png
i searched in the project/libs to find the cordovalib.jar and found it empty

A: @user2239044, without announcement Cordova moved the repository server. Reset your environment, download the latest version. That likely won't be enough. When you rebuild your app, you'll need to

*

*set the version for your compiler

*set the version for your plugins

*set the source for your plugins to NPM

That still won't be enought, because there are no enough details about your app in the post. But start right there, and report the errors you get.
And for God's sake learn to use cut and paste, and don't be lazy with a screen shot.


text:
Q: how do i read a specific line in a text file in java? I have a code that needs to read lines from a 95 line text file and put each one in a string variable quickly. However, it won't be in a linear order and it will have to read each one individually. How would i do this in as efficient and compact manner possible?

A: Quite easy:
final Path path = Paths.get("path/to/your/file");

final List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);

Then you can filter from the lines.
Starting with Java 8 you can:
final Path path = Paths.get("path/to/your/file");

final List<String> lines = Files.lines(path, StandardCharsets.UTF_8)
    .filter(someLambdaImplementingPredicate).collect(Collectors.toList());

A: String ar = new String[95];
try(BufferedReader br = new BufferedReader(new FileReader(filePath))) {
    for (int i = 0; i < 95; i++) {
        ar[i] = br.readLine();
    }
}

Keep in mind that the code above does not have error handling and assumes that the file HAS 95 lines.

A: So you are "very fluent in java", huh?
List<String> lines = Files.readAllLines(path, charset);

Then do lines.get(x). 95 lines is small enough to just keep all of them in memory.


text:
Q: Error with the pytube module while attempting to do yt = YouTube(url) I have a function called downloadSong which is used to download a song from youtube when given a url, but it's drawing an error
I've tried searching through a docs and the read me, but I haven't seen any mention of this error
def downloadSong(url):
    yt = YouTube(str(url))
    video = yt.streams.first()
    downloadedVideo = video.download('/MusicCache')
    return downloadedVideo,yt.title

The expected result is for it to download the song, but instead it's drawing the error shown below:
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\bot.py", line 859, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\core.py", line 725, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\core.py", line 88, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 's'```

A: Your use of pytube is fine, but there is a bug where if you do not specify a name for the file you want to save your youtube video to it crashes because pytube cannot create a default name. I had a similar problem.
Try this:
from pytube import Youtube

def downloadSong(url):
  yt = YouTube(str(url))
  video = yt.streams.first()
  downloadedVideo = video.download(output_path='/MusicCache', filename='MySong')
  return downloadedVideo, yt.title

If that doesn't work possibly try the absolute path to your folder you want to save your songs for the value of the output_path parameter in the download() function.


text:
Q: UIButton - How to set Minimum Font Size? My question is simple. Is there any way to set a minimum font size for UIButton like this can be easily set up with UILabel?

A: button.titleLabel.numberOfLines = 1;
button.titleLabel.adjustsFontSizeToFitWidth = YES;
button.titleLabel.lineBreakMode = NSLineBreakByClipping;

copied from Set minimum font size UIButton with margin

A: Set Minimumfontsize is not available in iOS8 use minimumscalefactor instead.

A: in Swift 4/5
Please make sure that yourBtn is available in @IBoutLet, not in action
    in viewdidLoad or viewWillAppear
override func viewDidLoad() {
    super.viewDidLoad()
    yourBtn.titleLabel?.numberOfLines = 1
    yourBtn.titleLabel?.adjustsFontSizeToFitWidth = true
    yourBtn.titleLabel?.lineBreakMode = NSLineBreakMode.byClipping
}

A: Anoop's answer works like a charm. You can also do this in IB using User Defined Runtime Attributes:
- choose Button in IB
- Add Attribute
- KeyPath: titleLabel.adjustsFontSizeToFitWidth
- Type: Boolean
- Value: true
Screenshot from IB

A: For Swift 5.0
override func viewDidLoad() {

        super.viewDidLoad()
        // Do any additional setup after loading the view.
        YourButton.titleLabel?.numberOfLines = 1
        YourButton.titleLabel?.adjustsFontSizeToFitWidth = true

    }

A: Teetz's answer works like a charm. In case if you want to add margin between titleLabel of UIButton edges after it adjustsFontSizeToFitWidth, you can add few spaces before first character & after last character. So, that it looks neat.


text:
Q: Dead Poets Society I wonder why there is no apostrophe in the film title "Dead Poets Society". Shouldn't it have been written as "Dead Poets' Society"?

A: Dead Poets Society would be a society that concerns itself with dead poets - reading their works and discussing their lives.
Dead Poets' Society would be a society for dead poets - that is the members would be dead poets.
I haven't seen the movie, so I don't know for sure which is correct.

A: "Dead Poets Society" may mean that the society named "Dead poets" or they want to call that society using the name "Dead poets" Which must be reflecting the theme of the movie.


text:
Q: Message "error: use of undeclared identifier 'assert'" I had a piece of code that was including some Boost headers. Upon compilation I received errors like
/usr/local/include/boost/smart_ptr/shared_ptr.hpp:1041:9: error: use of undeclared identifier 'assert'

        BOOST_ASSERT( deleter_.use_count() <= 1 );

        ^

/usr/local/include/boost/assert.hpp:60:29: note: expanded from macro 'BOOST_ASSERT'

# define BOOST_ASSERT(expr) assert(expr)
                                ^

These errors however only occurred on Windows and macOS.
Explicitly including either <cassert> or <assert.h> before the Boost headers had no effect.

A: You need to #include <cassert> to bring in the assert implementation.
It's your job to define or not define NDEBUG accordingly.
I'm surprised Boost doesn't do that for you - are you using the Boost files correctly (i.e. including the files that you're supposed to)?

A: As it turned out I had a file called Assert.h in my include-path (a custom file of mine). On case-insensitive file systems as used by Windows and macOS, this would shadow the original assert.h header that actually defines the assert macro.
The solution therefore was simply to rename my assert-header file.
(I found the solution thanks to [Compilation Error] error: use of undeclared identifier 'assert' #15.)


text:
Q: MySQL does it matter which column I COUNT() by I've been wondering about this for quite some time. Is it better to do this where the primary key ticket_id is counted:
SELECT COUNT(ticket_id)
FROM tickets
WHERE ticket_country_id = 238

Or to do this:
SELECT COUNT(ticket_country_id)
FROM tickets
WHERE ticket_country_id = 238

In this case ticket_country_id is an indexed foreign key, but we could also assume it's just a non-indexed column (perhaps the answer would be different for non-indexed columns)
In other words, does it matter that I am calling on another column for the COUNT()?
Obviously the performance saving would probably be small, but I like to do things the best way.

A: Yes,it can matter. Select count(*) allows the DB to use whatever resources make sense and are most efficient. It can do as table scan, use a primary key or other index to answer your question.
Count(something-else) means count the non null values. Again, the DB can use several methods such as indexes if such thing are available but you are then asking a different question.
As is often the case with SQL it's better to ask the question you want answers to than play silly games trying to game the system for a few milliseconds here and there.
That helps your future colleagues too by clearly stating the thing you are trying to do.


text:
Q: C# Method to sum hh:mm data ??? I want a method that will sum data that is string in the format hh:mm (time hours and minutes)
0:15 + 0:15 = 0:30

A: Convert the strings to TimeSpans and then call the .Add method.
TimeSpan s1 = TimeSpan.Parse("0:15");
TimeSpan s2 = TimeSpan.Parse("0:45");

TimeSpan s3 = s1 + s2;

// not tested; should work.

Ref: http://msdn.microsoft.com/en-us/library/system.timespan.aspx


text:
Q: jquery print plugin load everytime when I made click I am using jquery Print Plugin
    $(document).ready(function() {

            $(".printButton").printPage({
                url: "pages/report.html",
                attr: "href",
                message:"Your document is being generated"
            });

        });

Jsp Page with the above script
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>

Press Yes to Print

Yes

When first time open the page, and press yes , it print in one time and when I open the page second time , on pressing yes, it print 2 pages on a single click, and third time it print three pages on a single click.
Its means on every click ,jquery print plugin library load again and again.
How can we control this?

A: There is no problem , with your side. Edit the jquery plugin library in the following way.
Add the following
this.die();

after the following statement
$.extend(pluginOptions, options);

This will work fine!

A: The plugin has no problem, since it use live you need to add it to your page code, not in the ajax call.
Granted maybe I (I am the author) should not have been using event delegation for that, it was a requirement of the project at the time, I will probably change it so it bind itself to the dom with on().
As for the other comments, you guys are missing the point. This plugin is use in webapps on print buttons so you can for example, print a special datagrid directly. it loads the url in a iframe and print it, so you need your print css obviously.

A: not really sure what you want to print, exception.jsp or pages/report.html.  What could be happening is that you're defining too many parameters.
From checking the plugin it seems to me you just need to set the href in the  to the url of the page you want to print and that's it, the other parameters just let you specify something other than the href (which it uses by default). So try removing url and attr from the jquery call, and change the href in the  to 'pages/report.html' (if that's the page you want to print).  Not sure what exception.jsp is supposed to do.


text:
Q: Detecting known words using the Web Speech API I'm in the planning stages of a web app that is intended to help children learn vocabulary. We would like to make the app as interactive as possible. For example, we would show a picture of an apple and ask the child to identify the object. The child would then say "apple" and we would determine whether they are correct, etc.
The new Web Speech API seems like a promising tool for this project. However, looking through the documentation, I believe it will only produce transcripts from speech (i.e. it cannot match a spoken word to a known word and produce a confidence value – at least not out of the box).
Does anyone have experience with leveraging the Web Speech API in this way (or any other API for that matter)? I'm trying to stick to technologies that can run in the browser, if possible.

A: Try ispikit.com, it's way more suitable for your needs, it's specifically designed for education tasks and works in a browser on a client side. Web Speech API is not designed for detection, so you will not be able to use it.


text:
Q: Handle multiple users in Node js Express application I am new to NodeJs, and as a practice I am trying to build a blogging API using node and express. I am looking for a way to implement the following tasks :

*

*Any user should be able to look at other user's profile, but not edit it.

*Any user should be able to view any blog but edit only their own blogs

The way I was thinking of doing this is :

*

*When a user logs in, store the user's id in a cookie (either a JWT token or something else), and whenever a profile / blog is to be displayed, check if the author of the blog / profile has the same Id as the one stored in cookie, if it is then allow the option to edit, else don't.

Would like to know if this is correct way to do it, also are there any better ways to achieve this ?

A: A better approach is to use an authentication middleware:
This blog post briefed it: https://medium.com/quick-code/handling-authentication-and-authorization-with-node-7f9548fedde8
The explanation of the concept is that you do not need to add the auth middleware to the user's profile GET endpoint (i.e the endpoints that gets user profile).
To edit a blog you need to do some checks if the id of the one who created the blog post matches.
I have a project you can check: https://github.com/razaqfatiu/Teamwork/blob/develop/api/controllers/article.js
The editArticle function on line 41 should be of help


text:
Q: Fernet raising InvalidToken error even tough it seems I'm storing it? I ma writing a simple "write_csv-row' and "read_csv_row" functions that encrypts part of the row and then uses the un-encrypted part (email) to identify the row, decrypt it and check in password is correct.
The "write" function works, but it appears I cannot decode it. I thought it is because my "read" function regenerate the key, but it seems that it uses the same one that is stored?
still getting a  "cryptography.fernet.InvalidToken" error.
Here's the code:
import csv
import os
import base64
from cryptography.fernet import Fernet

# Generate a random secret key
secret_key = Fernet.generate_key()

# Write a function to encrypt data using the secret key
def encrypt_data(data):
  fernet = Fernet(secret_key)
  encrypted_data = fernet.encrypt(bytes(data, 'utf-8'))
  return encrypted_data

def write_csv_row(data):
  # Open the CSV file in append mode
  with open('user_data.csv', 'a', newline='') as csv_file:
    writer = csv.writer(csv_file)
    # Write the first two rows (Name and Email Address) unencrypted
    unencrypted_data = [data[0], data[1]]
    # Encrypt the remaining rows and write them to the file
    encrypted_data = [encrypt_data(str(item)) for item in data[2:]]
   # Combine the unencrypted and encrypted data into a single row
    combined_data = unencrypted_data + encrypted_data
    # Write the combined data to the file
    writer.writerow(combined_data)

# Write a function to read a row of data from the CSV file based on email and password
def read_csv_row(email, password):
  # Open the CSV file in read mode
  with open('user_data.csv', 'r') as csv_file:
    reader = csv.reader(csv_file)
    # Read each row from the file
    for row in reader:
      # Check if the email address in the second column matches the specified email
      if row[1] == email:
        # Decrypt the password using the secret key
        fernet = Fernet(secret_key)
        decrypted_password = fernet.decrypt(row[2]).decode('utf-8')
        # Check if the decrypted password matches the specified password
        if decrypted_password == password:
          # Decrypt the rest of the row using the secret key
          decrypted_row = [row[0], row[1]] + [fernet.decrypt(item).decode('utf-8') for item in row[3:]]
          return decrypted_row

# Write some example data to the CSV file
write_csv_row(['Alice', 'alice@example.com', 'password123', 'Pro', '1234 5678 9012 3456', '01/23', '123', '123 Main St', '', 'New York', 'NY', '12345', 'USA', 'high', 'active', 'diversified', 'Exchange A', 'public_key_123', 'private_key_456'])

# Read the first row of data from the CSV file
row = read_csv_row('alice@example.com', 'password123')
print(row)

Looked on here for answers but it didn't help.


text:
Q: Shuffling elements of an RDD[List[Double]] in Spark In a program I am developing using Spark 2.3 in Scala, I have an RDD[List[Double]]. Every List[Double] have the same size. I can't figure out how to perform a transformation that given the RDD
[1.0, 1.5, 4.0, 3.0],
[2.3, 5.6, 3.4, 9.0],
[4.5, 2.0, 1.0, 5.7]

transform it in the RDD
[2.3, 2.0, 1.0, 3.0],
[1.0, 5.6, 4.0, 5.7],
[4.5, 1.5, 3.4, 9.0]

where every single element of the lists is swapped among them, maintaining the same position.
For example, the first element of the first list is moved to the first position of the second list, the second element of the first list is moved to the second position of the third list, and so on.
Thanks a lot.

A: One approach to shuffling column-wise would be to break down the dataset into individual single-column DataFrames each of which gets shuffled using orderBy(rand), and then piece them back together.
To join the shuffled DataFrames, RDD zipWithIndex is applied to each of them to create row-identifying ids.  Note that monotonically_increasing_id won't cut it as it doesn't guarantee generating same list of ids necessary for the final join.  Hence, this is rather expensive due to the required transformation between RDD and DataFrame.
import org.apache.spark.sql.functions._
import org.apache.spark.sql.types._
import org.apache.spark.sql.Row

val rdd0 = sc.parallelize(Seq(
    List(1.0, 1.5, 4.0, 3.0),
    List(2.3, 5.6, 3.4, 9.0),
    List(4.5, 2.0, 1.0, 5.7)
  ))
//rdd0: org.apache.spark.rdd.RDD[List[Double]] = ...

val rdd = rdd0.map{ case x: Seq[Double] => (x(0), x(1), x(2), x(3)) }
val df = rdd.toDF("c1", "c2", "c3", "c4")

val shuffledDFs = df.columns.filter(_.startsWith("c")).map{ c =>
  val subDF = df.select(c)
  val subRDD = subDF.orderBy(rand).rdd.zipWithIndex.map{
    case (row: Row, id: Long) => Row.fromSeq(row.toSeq :+ id)
  }
  spark.createDataFrame( subRDD,
    StructType(subDF.schema.fields :+ StructField("idx", LongType, false))
  )
}

shuffledDFs.reduce( _.join(_, Seq("idx")) ).
  show
// +---+---+---+---+---+
// |idx| c1| c2| c3| c4|
// +---+---+---+---+---+
// |  0|2.3|2.0|4.0|9.0|
// |  1|1.0|5.6|3.4|3.0|
// |  2|4.5|1.5|1.0|5.7|
// +---+---+---+---+---+


text:
Q: BlueJ Unit Test fails despite equality holding Unit test fails yet biComplexNumber1.equals(biComplexNumber2) holds true.
Unit test:
 public void simpleTest(){
    BicomplexNumber b1 = new BicomplexNumber(1,2,3,4);
    BicomplexNumber b2 = new BicomplexNumber(1,2,3,4);
    assertEquals("Simple Test", b1, b2);
}

Equality check
public boolean equals(BicomplexNumber bicomplexObj)
{
    if(bicomplexObj == this) return true;
    if(bicomplexObj.getA() != this.getA()) return false;
    if(bicomplexObj.getB() != this.getB()) return false;
    if(bicomplexObj.getC() != this.getC()) return false;
    if(bicomplexObj.getD() != this.getD()) return false;
    return true;
}

The equality check seems to be correct when I would like it too. But I have included it anyway.


text:
Q: When running a google app script on a google sheets, does it run one app script file, or can it run more than one file? My plan is to link a google app script to my google sheets. I have 16 tabs on my google sheets. I want to make 16 app script files inside the same app script project. I also want to set time trigger on each app script to run at a certain time. My question is will every file inside the app script file will run, or only one app script will run?
The output I am looking for is that I do not have to press any button on the sheets or the app script. I want it to run each app script file at a certain time, and for the google sheets to update at that time. Each google sheet tab should update at the time they are assigned in the app script. How can I make this happen?
Thanks in advance.

A: Every scripts are runnable, unless the function names do not duplicate.
A project is similar to a html file, while each script file is included by <script src="name.js">

However, I doubt whether you really need one script file, or even a function for each sheet.
Of course, it depends on what you want to do. But I guess the works are similar and they could be combined into one or a few functions.


text:
Q: Simple MySQL join using no indexes The query below takes about 0.3 seconds. Why? And how can I solve it. The shouldnt take so long...
SELECT tshops.OfficialName
 , tresults.StartTime
 , tresults.Price
 , tresults.shopID
FROM
 tresults
INNER JOIN tshops
ON tshops.shopID = tresults.shopID
WHERE
  tresults.pID = 15
  AND tresults.websiteID = 1
  AND tresults.StartTime = (SELECT max(tresults.StartTime) AS maxstarttime
                        FROM
                          tresults
                        WHERE
                          tshops.shopID = tresults.shopID
                          AND tresults.pID = 15
                          AND tresults.websiteID = 1)
ORDER BY
  tresults.Price DESC

Explain result:
1, PRIMARY, tshops, ALL, PRIMARY, , , , 203, Using temporary; Using filesort
1, PRIMARY, tresults, eq_ref, PRIMARY,idxPID,idxWebsite,idxStartTimeASC,idxStartTimeDESC,fk_shopID, PRIMARY, 20, func,const,pricegrabber.tshops.shopID,const, 1, Using where
2, DEPENDENT SUBQUERY, tresults, ref, idxPID,idxWebsite,fk_shopID, fk_shopID, 4, pricegrabber.tshops.shopID, 891, Using where; Using index

So a full table scan on tshops is done. But why? There's an index on shopID in both tables...

A: I would suspect the subselect which refers to the outer select is confusing matters.
Try doing a join against the subselect, using a GROUP BY on the shopID. Normally I would expect MySQL to optimise things to do this anyway, but worth a try.
Something like this (please excuse any typos)
SELECT tshops.OfficialName
 , tresults.StartTime
 , tresults.Price
 , tresults.shopID
FROM  tresults
INNER JOIN tshops
ON tshops.shopID = tresults.shopID
INNER JOIN (SELECT shopID, MAX(tresults.StartTime) AS MaxStartTime
            FROM tresults
            WHERE tresults.pID = 15
            AND tresults.websiteID = 1
            GROUP BY shopID) Sub1
ON tresults.StartTime = Sub1.MaxStartTime
WHERE
  tresults.pID = 15
  AND tresults.websiteID = 1
ORDER BY
  tresults.Price DESC


text:
Q: Warnings with a new Xcode project using FMDB, SqliteCipher and CocoaPods I have installed CocoaPods.. and loaded the workspace as instructed.
I am getting these warnings which I do not understand, here is an example:
Pods-CipherDatabaseSync-SQLCipher
sqlite.c
/Users/admin/Code/CipherDatabaseSync/Pods/SQLCipher/sqlite3.c:24035:13: Ambiguous expansion of macro 'MAX'
I have looked around for a couple of hours and I am stumped at what I need to do, can someone please point me in the direction of somewhere that will provide some insight?
Thanks.

A: In the sqlite.c file it looks as if MIN and MAX are trying to be defined in two different areas of the file. The first time on line 214
/* Macros for min/max. */
#ifndef MIN
#define MIN(a,b) (((a)<(b))?(a):(b))
#endif /* MIN */
#ifndef MAX
#define MAX(a,b) (((a)>(b))?(a):(b))
#endif  /* MAX */

Then secondly at line 8519
/*
** Macros to compute minimum and maximum of two numbers.
*/
#define MIN(A,B) ((A)<(B)?(A):(B))
#define MAX(A,B) ((A)>(B)?(A):(B))

I commented out where they define it the second time and all of the warnings went away after cleaning and building the project again.

A: Remove the MAX and MIN macro definitions from the sqlite3.c file, since they are already defined in system headers.

A: Issue Solution:
Open Xcode project Build settings
add "-Wno-ambiguous-macro" into  "Other C flags"


text:
Q: Office 365 Calendar Event NoticificationURL to localhost So Im using the Notification REST API from office 365 to get changes of a calendar. My subscription request looks like so (its an array in PHP which i transform into json later on):
        "@odata.type" => "#Microsoft.OutlookServices.PushSubscription",
        "Resource" => "me/calendars/<calendar-id>/events",
        "NotificationURL" => "https://mywebhook.azurewebsites.net/api/send/reservation",
        "ChangeType" => "Created, Deleted",
        "ClientState" => "c75831bd-fad3-4191-9a66-280a48528679"

I pass it on to the office API with my access token and email and it works fine. And I can see the results on the website ("https://mywebhook.azurewebsites.net/view/reservation") when changes happen in the calendar.
Where's the problem? How can my web app see the data that's been posted to the last website? Because I want my web app to refresh/update/react when there's a change in a calendar of office 365. Is this even possible?
My web app runs on a localhost wampserver. I tried to put a localhost url as notificationURL but that gave a Bad Request Error. My web app is also programmed using PHP.
If something's unclear do tell. My english ain't top notch. Thanks in advance for your time.

A: localhost url can't be used as notificationURL, notificationURL should be directly accessible via the internet, because other server will POST the data to it. You could make your localhost wampserver poll the notification server and sync data . You could use ajax polling ,please click here for demo .Also you could use Websocket,you can see good example of Websockets at work  here. Keep in mind this should work with most modern post  IE9+ and other browsers.


text:
Q: Find Region On Image - Automatic Rotate Image OpenCv I have an image and I want to rotate this image, to be like this :
Rotation must be automatic. in other hand angle of rotation must be calculated.
[1 - Image ]

Is there any idea for this rotation on openCV?
And how can I extract a small rectangle on this image? like this :
(I have marked some region with red color)
[2 - Image]

Is there any idea for extracting this region from this image on OpenCV?

A: I don't know openCV, but you added the C# and C++ tags, which make me suppose that you would accept an algorithm that can be implemented in these languages.
To answer your first question:
If your images are all similar to the ones you provided, you could do something like this (these are not necessarily sequential steps, they are numbered just for ease of reference):

*

*convert to black & white (you could do this only conceptually, if you prefer, by comparing pixel values to a threshold, in what follows)

*travel along the black outline in vertical, horizontal and diagonal single-pixel steps

*remember N pairs of coordinates while you travel, so that N is below the expected minimum length, in pixels, of a straight line of your images (you will have to tune N: too long gives you too little data, too short gives you too much noise)

*from the coordinates of the current point and the point N steps back, calculate m and q ofy = m x + q if abs(Δx) ≤ abs(Δy) or m' and q' of x = m' y + q' otherwise, and make 4 histograms thereof, with the resolution you need

*smooth a bit your histograms (e.g., by adding to each channel a bit of the value of its neighbor channels)

*find the maxima of m, m', q and q', and, after removing a surrounding of the maxima of q and q', the other 2 (local) maxima of q and q'; these will be your estimate of the parameters of the equations of the 4 bounding lines of your rectangle, with m ≅ -m' (depending on your desired final result you can use m, m', or, e.g. (m-m')/2)

*find the rotation or the affine transformation that puts your rectangle into the desired position (e.g., the intersection of two of the above lines may have to be transformed to a certain position), and apply it
Point 2 is done by finding, at each step, the first black pixel among the 8 possible in a circular exploration around the current pixel that ends with the pixel of the previous step. E.g., if your last step was in NE (north-east) direction, and you are travelling clockwise around the contour, you explore the surroundings in this order: NW, N, NE, E, SE, S, SW (W is missing because it would have been selected by the previous step, if it had been black). You can find the starting pixel by a line scan (which will make you arrive in E direction, or W direction in case of a reverse line scan).
You should also calculate the length (in steps) of the contour. If it is much shorter than what you expect, you should discard it and make another attempt, until you find the "real" contour.


text:
Q: Qt Installer кириллица в пути Сделал инсталятор с Qt Installer, вроде бы всё нормально, но в пути для каталога установки, если попадается кириллица - выводится ошибка. Для меня понятна, а пользователей ввергает в иррациональный ужас и панику, так как пишет, что мол найден символ не относящийся к ANCII, выберите другую папку. Нельзя ли убрать это ограничение или хотя бы изменить текст этой ошибки.

A: Простите дурака, не заметил сразу в документации. В одном из примеров сейчас наткнулся на такую строчку в конфиге.
<AllowNonAsciiCharacters>true</AllowNonAsciiCharacters>


text:
Q: Generating a cosine wave with multisim I'm attempting to complete a project using multisim. I have to determine resistor and source values for a differential opamp.
One of the specifications is to supply a -10 amplitude cosine wave when t=5s.
I figured out how to generate a sine wave using the function generator, but I cant find a way to switch it to cosine.
Anyone know how to either make the function generator cosine, or produce a cosine source?

A: Cosine signal = sinusoidal signal, but +90 degrees phase shifted. The phase angle is one of the parameters of the sine voltage source Zero degrees=sine, +90 degrees=cosine.


text:
Q: Why did logistic regression fail to model non-linear predictors, but cubic splines didnt? I am reading ESL and was looking at Chapters 4 and 5.
In chapter 4 logistic regression is performed on some 'South African Heart Disease Data'. The final model did not accurately model 2 parameters: systolic blood pressure, and obesity - the Z scores were found to be statistically insiginficant (1.023 and -1.187). It was mentioned:
"Systolic blood pressure (sbp) is not significant! Nor
is obesity, and its sign is negative. This confusion is a result of the correlation between the set of predictors. On their own, both sbp and obesity
are significant, and with positive sign. However, in the presence of many other correlated variables, they are no longer needed (and can even get a
negative sign)."
Model reduction was then performed to find a subset of variables but both of these predictors were still excluded.
In chapter 5 natural cubic splines are then used to fit the data. Plots of the splines for systolic blood pressure and obesity reveal they are inherently non-linear. Here are the plots:
The book then states:
" Both sbp and obesity are included in this model, while they were not in the linear model. The figure explains why, since their
contributions are inherently nonlinear."
To me this is suggesting that logistic regression could not accurately model these non-linear predictors. However, just because they are non-linear in the predictors, surely provided their parameters are linear, logistic regression should still be able to model this?
So my question is : Is logistic regression not always able to accurately model non-linear predictors?
Any further clarification of what was going on in this example would also be appreciated.


text:
Q: Android FragmentLayout isn't loaded I'm a beginning android develope and could need your help.
I'm doing a navigation by using a FrameLayout with Fragments. XML-Files are correct (or better to say, they are displayed correct in the IDE).
But loading the Fragments doesn't work. And there is no error which helps me.
The only error is everytime a Fragment is loaded, the debugger says:

W/PathParser: Points are too far apart 4.000000596046461

The XML is the very basic XML given bei Android Studio to start (the template with the HelloWorld-Textbox). I'm loading the Fragment with following code:
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, new Dashboard());
fragmentTransaction.commit();

R.id.fragment_container is the correct one (firstly I don't have that much that I could be confused and secondly I checked it twice).
Many thanks for your time and I hope there is help for me. If you need any further information, please request them.
Adds:
Fragment (will be changed as soon as it works):
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.david_haintz.virtualdatingcoach.Community">

<!-- TODO: Update blank fragment layout -->
<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="@string/hello_blank_fragment" />

</FrameLayout>

Main:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.david_haintz.virtualdatingcoach.MainActivity">

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

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

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

<FrameLayout
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"></FrameLayout>

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    android:src="@android:drawable/ic_dialog_email" />

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

content_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.david_haintz.virtualdatingcoach.MainActivity"
tools:showIn="@layout/app_bar_main">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!" />
</RelativeLayout>

A: It's really common issue with image in Android.
Sometimes, when we write a layout file, we want to preview the result and if the layout has an ImageView then we also want to see the image by just giving the image resources in xml. Beware of that, by the time you set image resource in image view for only preview purpose, don't forget to remove it. If we forget to remove it, then in the runtime the image will be loaded and suck the app memory.
It would seem fine if the image is only loaded once but what if the sample image is on item layout, and we use the layout in recycler view (listview)? the sample image will be loaded in every single item you have in the list. Just multiply it with the size of the image, that is how the app becomes a memory sucker.
I made this mistake, and fortunately I used a really big image, so the exception was always raised.
Here is the example of pre set image resources
 <ImageView
  android:id="@+id/iv_preview"
  android:layout_width="match_parent"
  android:layout_height="200dp"
  android:layout_below="@+id/tv_title"
  android:adjustViewBounds="true"
  android:scaleType="centerCrop"
  android:src="@drawable/budget_preview"
/>

budget_preview.png is a really big image. With default activity, my app only uses around 20mb of memory,

but after open the activity with only 3 items with that layout, it jumped into 90mb, scroll a little bit, OOM was raised.

So don't forget to remove android:src after you finish preview, and you'll probably save a good memory.
Hope it's useful.
Use tools:src instead of android:src to get the preview image in Android Studio with zero impact on runtime http://tools.android.com/tips/layout-designtime-attributes
Resource Link:
Beware of Setting Image Resource for Preview in XML for Android

A: If your using first time in your activity use this
fragmentTransaction.add(R.id.fragment_container, new Dashboard());

in the place of
fragmentTransaction.replace(R.id.fragment_container, new Dashboard());

suppose if you have more then one fragment then you will use inside if (or) switch,case that replace fragment.
I think you solve the problem when changing the replace  with  add
FragmentTransaction fragmentTransaction =getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.fragment_container, new Dashboard());
fragmentTransaction.commit();

use this code


text:
Q: Find Specific Values using SQL Like Statement I'm trying to read a file from among file in my table according to today's date. For example, if today is November 21st, I want to show LIST_21-11-2018. Here is my query :
CREATE TABLE "FILE_LIST" (
"FILENAME" VARCHAR2(40),
"STATUS" CHAR(1 Byte)
);

INSERT INTO "FILE_LIST" ("FILENAME","STATUS") VALUES('LIST_20-11-2018','N');
INSERT INTO "FILE_LIST" ("FILENAME","STATUS") VALUES('LIST_21-11-2018','N');
INSERT INTO "FILE_LIST" ("FILENAME","STATUS") VALUES('LIST_22-11-2018','N');
INSERT INTO "FILE_LIST" ("FILENAME","STATUS") VALUES('LIST_23-11-2018','N');

SELECT FILENAME FROM FILE_LIST WHERE FILENAME LIKE %'TO_CHAR(SYSDATE,'DD-MM-YYYY')'% AND STATUS = 'N'

The LIKE statement doesn't seem to be working. Hoping to know what is my mistake is ....

A: Try this :
SELECT FILENAME FROM FILE_LIST WHERE FILENAME LIKE '%' || TO_CHAR(SYSDATE,'DD-MM-YYYY') || '%' AND STATUS = 'N';

A: The % chars have to be inside the string you are looking for :
CREATE TABLE "FILE_LIST" (
"FILENAME" VARCHAR2(40),
"STATUS" CHAR(1 Byte)
);

INSERT INTO "FILE_LIST" ("FILENAME","STATUS") VALUES('LIST_20-11-2018','N');
INSERT INTO "FILE_LIST" ("FILENAME","STATUS") VALUES('LIST_21-11-2018','N');
INSERT INTO "FILE_LIST" ("FILENAME","STATUS") VALUES('LIST_22-11-2018','N');
INSERT INTO "FILE_LIST" ("FILENAME","STATUS") VALUES('LIST_23-11-2018','N');

SELECT FILENAME FROM FILE_LIST WHERE FILENAME LIKE '%' + TO_CHAR(SYSDATE,'DD-MM-YYYY') + '%' AND STATUS = 'N'


text:
Q: nvd3 multiBarChart not showing x axis Hi i tried to create a nvd3 multibarchart but i can't get x-axis display.
I searched online but cannot find a solution to my issue.
here is complete code please help. i also attached a pix for output. Thanks!
 <script>
 function data0() {
     var a0 = [],
     a1 = [];

a0.push({ x: 1, y: 5065});
a0.push({ x: 2, y: 11464});
a0.push({ x: 3, y: 200});
a0.push({ x: 4, y: 100});
a0.push({ x: 5, y: 0});
a0.push({ x: 6, y: 0});
a0.push({ x: 7, y: 100});
a0.push({ x: 8, y: 2200});
a0.push({ x: 9, y: 2200});
a0.push({ x: 10, y: 0});
a0.push({ x: 11, y: 0});
a0.push({ x: 12, y: 0});
a0.push({ x: 13, y: 0});
a0.push({ x: 14, y: 0});

a1.push({ x: 1, y: 148});
a1.push({ x: 2, y: 2966});
a1.push({ x: 3, y: 1200});
a1.push({ x: 4, y: 79});
a1.push({ x: 5, y: 0});
a1.push({ x: 6, y: 0});
a1.push({ x: 7, y: 0});
a1.push({ x: 8, y: 2185});
a1.push({ x: 9, y: 2185});
a1.push({ x: 10, y: 0});
a1.push({ x: 11, y: 0});
a1.push({ x: 12, y: 0});
a1.push({ x: 13, y: 0});
a1.push({ x: 14, y: 0});

            return [
                    {
                        values: a1,
                        key: 'Queue',
                        color: '#04B45F'
                    },
                    {
                        values: a0,
                        key: 'In Progress',
                        color: '#DBA901',
                        area: true
                    }
            ];
        }
        nv.addGraph(function () {

            var chart = nv.models.multiBarChart()
                    .margin({ left: 65, right: 40, bottom: 45 })
                    .stacked(true)
                    .showControls(false)
            ;

            chart.xAxis
                .axisLabel("Daily")
                .rotateLabels(0)
                .tickValues([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
                .tickSize(12)
                .showMaxMin(false)
                .tickFormat(function (d) {
                    var _tools = ["", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N"]
                    return _tools[d]
            });

            chart.yAxis
                .axisLabel("Number of[enter image description here][1]")
                .tickFormat(d3.format(',.0f'));

            d3.select('#BarChart-Cell svg')
            .datum(data0)
            .transition()
            .duration(500)
            .call(chart)
            ;

            nv.utils.windowResize(chart.update);

            return chart;
        });
    </script>

[ http://i.stack.imgur.com/HNNJf.png ]


text:
Q: How to change ruby version on linux I installed rvm on my Linux machine and download simple project from github. I tried to run rails s, but got a error with ruby version:
I executed next commands:

*

*rvm install ruby-2.3.0

*rvm use ruby-2.3.0

*rvm use ruby-2.3.0 --default

When I opened the project and ran rails s, I got this error
https://i.imgur.com/Dwvp8WF.png
Update
My Gemfile has ruby 2.3.0
Can't run bundle install because of this error https://imgur.com/a/UMcirdt
w
which rails, which ruby: https://imgur.com/a/vycG8wG

A: I haven't used rvm, but I'm using rbenv for version management.
From what I've read, it works similarly, although the commands are a little bit different.
Did command rvm use ruby-2.3.0 inside the project folder generate a file called .ruby_version?
It should list the current version of ruby used in this project

A: After checked the errors on your updated screenshot, I think it's better just do this:
rm -r ~/.bundle
bundle
bundle install

Maybe just
rvm reinstall all

then try again.
If permission error happens, run
rvm fix-permissions

And then do it again.


text:
Q: Determining which static libraries are linked unnecessarily I want to cut down library dependencies on some C++ executables I'm compiling for Linux with GCC. There is a list of probably 40 static libraries that being linked. I want to determine which ones are unnecessary, and I would rather not try removing them one at a time to find out.
Is there an option in GCC to make it warn about libraries that are linked but don't resolve any symbols?
Are there any Linux tools available that will help me out?
To be clearn, I'm not concerned with unused code being linked into the executable. Rather, I'm concerned with the unnecessary build dependencies. I'd like to cut down my build times.

A: Building on top of the information provided by @ThomasMatthews in a comment to the question:
Run the linker with the -M option and pipe its output to the following script:
get_used_libs
#!/bin/bash

sed -e '/^Discarded input sections$/,$ d'                                   \
-e '/^Archive member included to satisfy reference by file (symbol)$/ d'    \
-e '/^As-needed library included to satisfy reference by file (symbol)$/ d' \
-e '/^Discarded input sections$/ d'                                         \
-e '/^$/ d; /^\s/ d; s/\s\+.\+//; s/(.\+//'                                 \
| sort -u

It will return the list of the libraries that were necessary for your program to link.
Disclaimer: The script was only tested on output from GNU ld (GNU Binutils for Ubuntu) 2.25.1 on a toy program.

A: While not as convenient as the other answer, you can use nm to list the required (U) and exported (anything else, but beware of [VvWw]) symbols for any object or archive.
A little preprocessing with grep and/or sed might make this more helpful for some use cases.


text:
Q: The Cat API - Refreshing image I am using The Cat API and I would like to change to a new image every 5 seconds without refreshing the page. I tried using setInterval to swap out the source, but it gets the same URL every time until you refresh. Any ideas?

setInterval(function(){
    $("#cats img").attr("src", "http://thecatapi.com/api/images/get?format=src&type=jpg&size=med");
},5000);

JSFiddle

A: It's just being cached. Bust the cache like this :
setInterval(function(){
    $("#cats img").attr("src", "http://thecatapi.com/api/images/get?format=src&type=jpg&size=med&" + new Date().getTime());
},5000);

http://jsfiddle.net/eqsan8z5/1/


text:
Q: HTTPWebResponse is returning an error number: 500 I am trying to call my API reference but when it gets to the HttpWebResponse response = (HttpWebResponse)request.GetResponse()) section my code just returns the error 500. I'm unsure on what my code is actually missing as im pretty new to APIs
any help is appreciated.
var request = (HttpWebRequest)WebRequest.Create($"####");
                request.Method = "GET";
                request.ContentType = "application/json";
                request.Headers.Add($"USERNAME: {Username}, PASSWORD: {Password}");
                request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36";
                request.ServicePoint.Expect100Continue = false;
                request.ProtocolVersion = HttpVersion.Version11;

                string responseFromServer = "";

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    //Console.WriteLine(((HttpWebResponse)response).StatusDescription);

                    using (var dataStream = response.GetResponseStream())
                    {
                        StreamReader reader = new StreamReader(dataStream);
                        responseFromServer = reader.ReadToEnd();
                        //Console.WriteLine(responseFromServer);
                    }

A: A 500 HTTP response code is a server based error, your code is not the issue. However, some "poorly made" APIs do not handle insufficient keys with the proper HTTP codes, resulting in a server error due to the front end not sending the required keys/values in the request.
Good luck!


text:
Q: Floating point exponentiation without power-function Currently I have to work in an environment where the power-operator is bugged. Can anyone think of a method temporarily work around this bug and compute a^b (both floating point) without a power function or operator?

A: given that you can use sqrt, this simple recursive algorithm works:
Suppose that we're calculating aˆb. The way the algorithm works is by doing Fast Exponentiation on the exponent until we hit the fractional part, once in the fractional part, do a modified binary search, until we're close enough to the fractional part.
double EPS = 0.0001;

double exponentiation(double base, double exp){
  if(exp >= 1){
    double temp = exponentiation(base, exp / 2);
    return temp * temp;
  } else{
    double low = 0;
    double high = 1.0;

    double sqr = sqrt(base);
    double acc = sqr;
    double mid = high / 2;

    while(abs(mid - exp) > EPS){
      sqr = sqrt(sqr);

      if (mid <= exp) {
          low = mid;
          acc *= sqr;
      } else{
          high = mid;
          acc *= (1/sqr);
      }

      mid = (low + high) / 2;
    }

    return acc;
  }
}

A: if you have sqrt() available:
double sqr( double x ) { return x * x; }
// meaning of 'precision': the returned answer should be base^x, where
//                         x is in [power-precision/2,power+precision/2]
double mypow( double base, double power, double precision )
{
   if ( power < 0 ) return 1 / mypow( base, -power, precision );
   if ( power >= 10 ) return sqr( mypow( base, power/2, precision/2 ) );
   if ( power >= 1 ) return base * mypow( base, power-1, precision );
   if ( precision >= 1 ) return sqrt( base );
   return sqrt( mypow( base, power*2, precision*2 ) );
}
double mypow( double base, double power ) { return mypow( base, power, .000001 ); }

test code:
void main()
{
   cout.precision( 12 );
   cout << mypow( 2.7, 1.23456 ) << endl;
   cout << pow  ( 2.7, 1.23456 ) << endl;
   cout << mypow( 1.001, 1000.7 ) << endl;
   cout << pow  ( 1.001, 1000.7 ) << endl;
   cout << mypow( .3, -10.7 ) << endl;
   cout << pow  ( .3, -10.7 ) << endl;
   cout << mypow( 100000, .00001 ) << endl;
   cout << pow  ( 100000, .00001 ) << endl;
   cout << mypow( 100000, .0000001 ) << endl;
   cout << pow  ( 100000, .0000001 ) << endl;
}

outputs:
3.40835049344
3.40835206431
2.71882549461
2.71882549383
393371.348073
393371.212573
1.00011529225
1.00011513588
1.00000548981
1.00000115129

A: You can use the identity ab = e(b log a), then all the calculations are relative to the same base e = 2.71828...
Now you have to implement f(x) = ln(x), and g(x) = e^x.  The fast, low precision method would be to use lookup tables for f(x) and g(x).  Maybe that's good enough for your purposes.  If not, you can use the Taylor series expansions to express ln(x) and e^x in terms
of multiplication and addition.


text:
Q: How would you delete a specific row without using panda in Python 3.4.4? I've tried to find ways to delete a selected row but the only way I could do so is with panda.
What I want to do is to delete an entire row that matches with the csv library (errors are fine since I'll make code if the row doesn't exist) as I had developed the code around said library, I've been told that 'wb' works around deleting rows, but I'm only able to delete 2 cells instead (which doesn't even work)
with open('StudentDetails.csv', 'wb',) as csvfile:
      csvFileWriter = csv.writer(csvfile)
      a = delete_student_entry.get()
      b = delete_password_entry.get()
      csvFileWriter.writerow([a,b])

A: You could do this the old fashioned way (if you want to avoid using pandas) -
with open("StudentDetails.csv", "r") as f:
    lines = f.readlines()
with open("StudentDetails.csv", "w") as f:
    for line in lines:
        if line.strip("\n") != "YOUR ROW HERE":
            f.write(line)

This will overwrite the file while deleting the row you want to avoid.
If you really want to use the csv library you can do the following -
import csv

with open('StudentDetails.csv', newline='') as csvfile:
     csvreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
     output = [x for x in csvreader if x != [YOUR LINE HERE AS A STRING]]

with open('StudentDetails.csv', 'w', newline='') as csvfile:
    csvreader = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    for x in output:
        csvreader.writerow(x)


text:
Q: HLSL uniform variables vs constant buffers What is the difference between uniforms and constant buffers?
Are they completely separate or can the uniforms be seen as in a constant buffer?  In other words, if you want to set a uniform, do you need a constant buffer or is there another way?
I ask because I have four variables (float2 pan, float scale and float rotation) that will in all likelihood not be changing at the same time.  Do I need a constant buffer to set them all at once or is it better to set them individually, if possible?

A: Uniforms are used when you have a variable that will be assigned from a external source from outside the function. In your case of the uniforms declaration will be better because you said that you will not be changing at the same time. The const declaration makes the variable unchangeable. Check out this page for resources..http://www.opengl.org/sdk/docs/tutorials/ClockworkCoders/uniform.php


text:
Q: Angularjs passing checkbox value from one controller to other controller I am trying to make one application where i want to pass checkbox value from one controller to other. I have two panels (left and right) as shown below , and separate controllers for them, lets say leftC and rightC.

Things are working fine for left and right panels and i am able to generate graphs as well. Now i want the graphs to be appear only if the corresponding checkbox is checked and hide if it is unchecked. How can i achieve this functionality in angularjs. Any suggestion would be appreciated.
Thanks

A: i think you can use the $rootScope in this case.Take a boolean value in root scope and change the flag on checking of box. And use that flag in ng-if.


text:
Q: Nested formGroup bind Object to radio button I've got nested formGroup:
  this.form = fb.group({
  productName: ['ASD'],
  productWeightCategory: fb.group({
    id: [],
    categoryWeightName: []
  })

and template:
<form class="container col-md-2" [formGroup]="form"
    (ngSubmit)="onSubmit(form.value)">

        productName <input
            class="form-control" id="productName" type="text" placeholder=""
            formControlName="productName">
        weigh category
        <fieldset formGroupName="productWeightCategory">

                 <input [value]="element" type="radio" name="id"
                    [checked]="ind===0"> {{element.categoryWeightName}} index
                    = {{ind}}

        </fieldset>

    <input class="btn btn-primary" type="submit" [disabled]="!form.valid"
        value="submit">
</form>

and I'm unable to get value from radios.
Probably I missed something but I can't figure out what.
Working demo

A: Remove formGroupName="productWeightCategory" and instead, on your input do this:
<input formControlName="productWeightCategory" [ngValue]="element" >

To set the checked property, you need to do it programatically because you're making use of the ReactiveFormsModule. That means the value of the FormControl must be the same as the one of the [ngValue]. You can do that in your component by setting the value of that FormControl. I'm not sure how you're getting your data but it would be something similar to this:
for(let i = 0; i < this.productWeightCategory.length; i++){
     if(condition)
         this.form.get('productWeightCategory').setValue(this.productWeightCategory[i]);
}

A: Just as Christian suggested, remove the nested group, what you want is a form control. If you want the first item in array chosen, just set that when you are building form:
productWeightCategories = [
 new ProductWeightCategory(1, 'value 1'),
 new ProductWeightCategory(2, 'value 2'),
 new ProductWeightCategory(3, 'value 3')
];

constructor(fb: FormBuilder) {
  this.form = fb.group({
    productName: ['ASD'],
    productWeightCategory: [this.productWeightCategories[0]]
  });
}

If you want to set it at later point, use setValue like suggested by Christian.
For your template use [value] like you did, and with the formControlName="productWeightCategory". You also need to change the name attribute to the same, otherwise Angular will start complaining :)
<fieldset>

      <input [value]="element" type="radio"
             name="productWeightCategory"
             formControlName="productWeightCategory">
        {{element.categoryWeightName}} index = {{i}}

</fieldset>

Your StackBlitz

A: You can use id: [ this.productWeightCategory[0].id ], set the radio checked, and use formControlName="id" in radio input:
<fieldset formGroupName="productWeightCategory">

         <input [value]="element.id" type="radio" name="id" formControlName="id"> {{element.categoryWeightName}} index = {{i}}

</fieldset>

And set categoryWeightName of submit before, use the id find it.
this.form = fb.group({
  productName: ['ASD'],
  productWeightCategory: fb.group({
    id: [ this.productWeightCategory[0].id ],
    categoryWeightName: []
  })
});

This can not be used the nested FormGroup
example


text:
Q: Generating a list of reference in Doxygen I'm really not sure how to explain thats why im having hard time googling a solution.

So I added this in my doxyfile
ALIASES += "sprint=\xrefitem sprint \"Sprint\" \"Sprint\" "
I was able to see this

This is fine but I want something different, kind of reverse of this. I want to be able to see one Sprint which is 19 and it should be a link so when I want to see all codes that are related to sprint 19 I will be able to just click on 19 and see the list of objects related to it. If I do it this way it will be really hard to find the codes on a specific sprint when we reach sprint 100++ or something.
So instead of seeing this
-Department
--19
-Employee
--19
-Position
--19

I should see
-19
--Department
--Employee
--Position

Hope I made sense.. :)


text:
Q: ASP.NET Webforms project is reading from a web.config in a completely different solution on my PC when debugging My web app is reading from a web.config from a completely different project with the same name in another solution. How can I check/change what web..config my project is referencing. I want to ensure it is the web.config in the current project.

A: If it's got the same name (Copy of a project?), maybe your debugging settings are the same, e.g. do they use the same IIS Express port number?
Once you start a project IIS Express will remember where the code is. If you stop that project, open another and run it using the same port number it will get confused and view the code from the first project.


text:
Q: Google Datastore: ndb.put_multi not returning I am currently reinserting some entities from XML files into Google Datastore using the NDB library. The issue I am observing is that sometimes ndb.put_multi() does not seem to return and the script hangs waiting for it.
The code is basically doing the following:
@ndb.toplevel
def insertAll(entities):
    ndb.put_multi(entities)

entities = []
for event, case in tree:
    removeNamespace(case)
    if (case.tag == "MARKGR" and event == "end"):
        # get ndb.Model entities
        tm, app, rep = decodeTrademark(case)

        entities.append(tm)
        for app_et in app:
            entities.append(app_et)
        for rep_et in rep:
            entities.append(rep_et)
        if (len(entities) > 200):
            n_entitites += len(entities)
            insertAll(entities)
            entities = []

if(len(entities) > 0):
    insertAll(entities)

I had noticed this behaviour before but it seems to be pretty nondeterministic, I was wondering if there would be a way to debug this properly and/or set a timeout on the ndb.put_multi so I can at least retry it if it does not return after a given time.
Thanks in advance,

A: ORIGINAL ANSWER (before OP edit)
Your logic is flawed.  insertAll() may never be getting called.  Where are app and rep defined?  And if they are defined outside this function, why are they in nested loops?  Any entities in rep are getting written len(app) * len(tree) times!
Also, what about the case where len(entities) < 200?  That is inside 3 nested loops.  Surely there will be cases where iterations have len(entities) < 200.  Think of the orphaned entities if the total, after all the loops, is 750.  You would orphan 150 entities.
At least append this after the loops run, to write the orphaned entities (< 200):
if len(entities) > 0:
    insertAll(entities)

Also try reducing 200 to a smaller value, like 100.  Depending on the sizes of the entities, 200 might be too many to finish before timing out.
Have you checked to see if ANY entities are written?
Also, are you sure you understand what an entity is, as used by the datastore?  If you are simply pulling strings out of an XML file, those are not entities.  rep and app must be lists of datastore entities, and tm must be an actual datastore entity.
UPDATE:
OK, that makes more sense, but you are still orphaning some entities, and have no control over the size of the put_multi().  Instead of if (len(entities) > 200):, you should batch them:
# primitive way to batch in groups of 100
batch_size = 100
num_full_batches = len(entities) // batch_size
remaining_count = len(entities) % batch_size

for i in range(num_full_batches):
    ndb.put_multi(entities[i * batch_size : (i+1) * batch_size])

if remaining_count > 0:
    ndb.put_multi(entities[(i+1) * batch_size:])

If too many entities, you should send this off to a taskqueue

A: Based on "App Engine datastore tip: monotonically increasing values are bad" by Ikai Lan.
Monotonically increasing values are those that are stored/read/written/strictly sequentially, like timestamps in logs. In the current Datastore implementation they will be stored/read/written sequentially in the same location/spot and Datastore will not be able to properly split the workload. So when the OPS is high enough and Datastore is not able to grow horizontally you will notice a slowdown. This is called hotspoiting.
On top of that that Datastore creates an index for each indexable property, except for example Text property, which means that you can have various hotspots at some point.
Workaround
One of the workarounds mentioned in the official documentation is to prepend a hash to indexed values:

If you do have a key or indexed property that will be monotonically increasing then you can prepend a random hash to ensure that the keys are sharded onto multiple tablets.

Read more on "High read/write rates to a narrow key range
".

A: From the previous comments you have left it looks like this application is hitting entity read/write limits, which is 1 op/s. You can read more about Datastore limits here.
As an alternative you can try using Cloud Firestore because it doesn't have some of these limits when used in Datastore mode.


text:
Q: Flutter setup, android licenses unknown, Windows, VS Code I'm having a (seemingly common) unknown license status issue. However, common fixes have not worked, such as flutter doctor --android-licenses, which can be seen in the console output below. I have gone to the link also - not helpful.
C:\Users\anonymous\OneDrive\Documents\Frameworks\flutter>flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[!] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    X Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/docs/get-started/install/windows#android-setup for more details.

! Doctor found issues in 1 category.

C:\Users\anonymous\OneDrive\Documents\Frameworks\flutter>flutter doctor --android-licenses
Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema
        at com.android.repository.api.SchemaModule$SchemaModuleVersion.<init>(SchemaModule.java:156)
        at com.android.repository.api.SchemaModule.<init>(SchemaModule.java:75)
        at com.android.sdklib.repository.AndroidSdkHandler.<clinit>(AndroidSdkHandler.java:81)
        at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:73)
        at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:48)
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.annotation.XmlSchema
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
        ... 5 more

Any and all help will be greatly appreciated. Many thanks in advance :)

A: Installing the Android SDK Command-line Tools should fix the issue. Navigatie to settings,Appearance & Behavior -> System Settings -> Android SDK

Then run:
flutter doctor --android-licenses

Which should give you something like this:
coolcoders@myhost ~ % flutter doctor --android-licenses
5 of 7 SDK package licenses not accepted. 100% Computing updates...
Review licenses that have not been accepted (y/N)? y


text:
Q: Activator command not working I wanted to install the play framework today.
So I went to the download page https://www.playframework.com/download here and downloaded the Play with Activator zip file Activator 1.3.12 including Play 2.5.13 (671M).
After that, I extracted it, and added the extracted activator-dist-1.3.12 directory to the path in the enviroment variables.
So according to the download page, I should now be able to use commands like
activator new

or
activator ui

But none of them are working. It seems like my command window can't find the activator command. What did I do wrong, or what did I forget ?
**Edit: **
This is the error message I get from the command line: The command "activator" is either spelled wrong or could not be found.
I am using Windows 10 if that helps. The java version I am using is 1.8.0_111.
This is my path:
C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\Program Files (x86)\AMD APP\bin\x86_64;C:\Program Files (x86)\AMD APP\bin\x86;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Common Files\Microsoft Shared\Windows Live;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Windows Live\Shared;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Livestreamer;C:\Users\Stefan\JEE\apache-maven-3.3.3-bin;C:\Program Files (x86)\Skype\Phone\;C:\Program Files\Java\jdk1.8.0_111\bin;C:\Program Files (x86)\GNU\GnuPG\pub;C:\Program Files\MiKTeX 2.9\miktex\bin\x64\;C:\Users\Stefan\Desktop\Studium\6.Sem\bin;%USERPROFILE%\.dnx\bin;C:\Program Files\Microsoft DNX\Dnvm\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Users\Stefan\Desktop\Play\activator-dist-1.3.12

One thing I noticed is that, normally the PATH System variable is written completely in capital letters. Mine isn't it's just written normally.

A: The commands are in the subfolder bin. Update your path to point to activator-dist-1.3.12\bin and it will work.

A: You need to reload (close and open) your terminal (command window), so it will catch up the changes you did to the environment variables.


text:
Q: Determining p,q from acf and pacf python I'm having difficulties understanding how to determine p and q in ARIMA. What i understand is PACF cut off determines p and ACF hit very low determines q but at the same time the cut off in PACF which is determines p is equal to AR(q)? I'm still very confused. Then i tried it myself building ARIMA model and i get this ACF and PACF. And i assume that the p is 16 because it's cut off (hit zero abruptly) at lag 16. The q is 1 because it hits very low at lag 1. So my ARIMA order would be (16,0,1). Am i wrong? i learn it from kaggle and here. I don't know if i understand it right

A: Correlations which are within the blue bands are not statistically significant and so it doesn't look as though you have a model. There is a great tutorial here https://www.statsmodels.org/stable/examples/notebooks/generated/tsa_arma_0.html on using Python for ARMA models.