Q: Create table on cluster of clickhouse error When I create table as follows:
CREATE TABLE partition_v3_cluster ON CLUSTER perftest_3shards_3replicas(
ID String,
URL String,
EventTime Date
) ENGINE = MergeTree()
PARTITION BY toYYYYMM(EventTime)
ORDER BY ID;

I get errors:
Query id: fe98c8b6-16af-44a1-b8c9-2bf10d9866ea
┌─host────────┬─port─┬─status─┬─error─────────────────────────────────────────────────────────────────────────────────────────────────────────────     ──────────────────────────────────────────────────────────────────────────┬─num_hosts_remaining─┬─num_hosts_active─┐
│ 10.18.1.131 │ 9000 │    371 │ Code: 371, e.displayText() = DB::Exception: There are two exactly the same ClickHouse instances 10.18.1.131:9000 i     n cluster perftest_3shards_3replicas (version 21.6.3.14 (official build)) │                   2 │                0 │
│ 10.18.1.133 │ 9000 │    371 │ Code: 371, e.displayText() = DB::Exception: There are two exactly the same ClickHouse instances 10.18.1.133:9000 i     n cluster perftest_3shards_3replicas (version 21.6.3.14 (official build)) │                   1 │                0 │
│ 10.18.1.132 │ 9000 │    371 │ Code: 371, e.displayText() = DB::Exception: There are two exactly the same ClickHouse instances 10.18.1.132:9000 i     n cluster perftest_3shards_3replicas (version 21.6.3.14 (official build)) │                   0 │                0 │
└─────────────┴──────┴────────┴───────────────────────────────────────────────────────────────────────────────────────────────────────────────────     ──────────────────────────────────────────────────────────────────────────┴─────────────────────┴──────────────────┘
← Progress: 0.00 rows, 0.00 B (0.00 rows/s., 0.00 B/s.)  0%
3 rows in set. Elapsed: 0.149 sec.
Received exception from server (version 21.6.3):
Code: 371. DB::Exception: Received from localhost:9000. DB::Exception: There was an error on [10.18.1.131:9000]: Code: 371, e.displayText() = DB::     Exception: There are two exactly the same ClickHouse instances 10.18.1.131:9000 in cluster perftest_3shards_3replicas (version 21.6.3.14 (official      build)).
And here is my metrika.xml:
<?xml version="1.0" encoding="utf-8"?>
<yandex>
<remote_servers>
    <perftest_3shards_3replicas>
        <shard>
            <replica>
                <host>10.18.1.131</host>
                <port>9000</port>
            </replica>
            <replica>
                <host>10.18.1.132</host>
                <port>9000</port>
            </replica>
            <replica>
                <host>10.18.1.133</host>
                <port>9000</port>
            </replica>
        </shard>
        <shard>
         <replica>
                <host>10.18.1.131</host>
                <port>9000</port>
            </replica>
            <replica>
                <host>10.18.1.132</host>
                <port>9000</port>
            </replica>
            <replica>
                <host>10.18.1.133</host>
                <port>9000</port>
            </replica>
        </shard>
        <shard>
            <replica>
                <host>10.18.1.131</host>
                <port>9000</port>
            </replica>
            <replica>
                <host>10.18.1.132</host>
                <port>9000</port>
            </replica>
            <replica>
                <host>10.18.1.133</host>
                <port>9000</port>
            </replica>
        </shard>
    </perftest_3shards_3replicas>
</remote_servers>
<zookeeper>
    <node>
        <host>10.18.1.131</host>
        <port>2181</port>
    </node>
    <node>
        <host>10.18.1.132</host>
        <port>2181</port>
    </node>
    <node>
        <host>10.18.1.133</host>
        <port>2181</port>
    </node>
</zookeeper>
<macros>
    <shard>01</shard>
    <replica>01</replica>
</macros>
</yandex>

I don't know where is wrong, can someone help me? Thank u


Q: Read Only File System view files within .zip I am working with a read only file system through Putty SSH. I have lots of zip files which contain multiple directories. I want to read a .kml file stored within one of these sub-directories. Is there a way to do this?
I have accessed the list of files with unzip -l

A: unzip -p archive.zip the-file-name-here

From the unzip man page:

-p
extract files to pipe (stdout). Nothing but the file data is sent to stdout, and the files are always extracted in binary format, just as they are stored (no conversions).


Q: Returning generated HTML from .NET Core controller I have a .NET Core 2 app that needs to be able to return generated HTML from a controller. I've been able to get it returning the HTML as plain text, but not to persuade the browser that it's HTML and render that; as soon as an HTML content type is provided, the content type negotiation appears to break it and it just renders a 406 Not Acceptable.
(Simplified) options I've tried -
    [HttpGet]
    [Produces("text/html")]
    public string Display()
    {
        return "<title>Testing</title>Hello, world!";
    }

    [HttpGet]
    [Produces("text/html")]
    public HttpResponseMessage Display()
    {
        try
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent("<title>Testing</title>Hello, world!")
            };
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");

            return response;
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
            return new HttpResponseMessage(HttpStatusCode.InternalServerError);
        }
    }

    [HttpGet]
    [Produces("text/html")]
    public IActionResult Display()
    {
        var pageHtml = "<title>Testing</title>Hello, world!";
        var result = StatusCode(200, pageHtml);
        result.ContentTypes.Add(new MediaTypeHeaderValue("text/html"));

        return StatusCode(200, pageHtml);
    }

The Startup.ConfigureServices method has been tried with all combinations I can think of of the RespectBrowserAcceptHeader and ReturnHttpNotAcceptable properties, but they didn't seem to make a difference.
Can anyone see what I've missed to persuade the server to just return the generated HTML?

A: How/why are you generating html yourself?  I think an eaiser solution might be to make an ASP.NET Core 2 MVC app.  That will allow you to use ViewModels.  I'd take a look into that.
Anyways, try returning Content... this returns a Http Status code of 200, and will allow you to return a string with other details of how the content is formatted.
[HttpGet]
[Produces("text/html")]
public IActionResult Display()
{
     return Content("
hello world!
", "text/html", Encoding.UTF8);
}


Q: Month number to month name in php I think the title is clear!
I want to make to take a number between 1-12 and give back the name of the month in that number (and if possible I want to have custom names for months).

A: Make an array for your month names like so
$montnames = ['', "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dez"];

Trick is to leave first one empty, because months begin with 1 and arrays count at 0.
echo $month[2]; // feb


Q: Testing Parse Server Cloud Code on Node.js fails "Parse.Cloud.beforeSave is not a function" I'm attempting to implement automated tests in my parse server repository that I run in node.js in my development environment. However, it appears that some of the functions available in the parse cloud code SDK are not available in the NPM parse library. In particular, test code imports
Parse = require('parse/node');
And then my code calls Parse.Cloud.beforeSave. This causes the error  Parse.Cloud.beforeSave is not a function. How can I get around this?

A: Edit:
I published an NPM library called parse-node-with-cloud that provides a Parse.Cloud object in node.js. I hope this will enable node.js unit tests of Parse cloud code.
===========
My solution to this is to use the parse-cloud-express library on NPM. Import it with
const Parse = require('parse-cloud-express').Parse;
Then Parse.Cloud functions will work as expected.
Unfortunately, the source code is no longer available on github and the module is likely no longer maintained.


Q: Can't get div height when including javascript in Django template I'm trying to use the flot plugin for jquery and it keeps on complaining that a div has a width/height of zero.  I'm actually including the javascript for this in a Django template.  So my template file looks like:
<style>
#graph {
     width: 100px;
     height: 100px;
}
</style>
<script>
$.plot(stuff)
console.log($(#graph).width())
</script>
<div id="#graph">
</div>

This template code is inserted into the DOM of another page with AJAX.
$.ajax({
     url: 'something',
     success: function(data){ $("#content").html(data);
              console.log($("#graph").width()) }
});

For some reason, I can't get the width to be non-zero, but if I test the width in the "success" function from the ajax call, it returns correctly.  Is something wrong with the order that commands are being run/placed into the DOM?

A: Well, in your first code block, you are checking the width of your DIV before you actually create the DIV in your markup, and sense you aren't using a DOMReady event or Window Loaded event, it will come up 0 or null at best.
So, if you just move your script block below the div in your first example that will fix that.
I imagine you will find a similar situation in your second example but I can't be sure without seeing more code.


Q: Adding to instance based on if statements? I'm a new coder trying to create a simple "Sword crafting" terminal app in ruby.
So I've got a class with a few instanced variables I want to iterate upon depending on the users input (@strength and @speed). So here, if the user inputs that the grip is "straight" i want it to increase the instance variable "strength" by 5 - but for some reason it's not editing it no matter what I do. I've already set "strength" as attr_accessor, and i've tried making the method manually as well - but I still can't iterate upon it. What am i doing wrong?
class Weapon
    attr_reader :id, :weapon_name, :guard, :blade
    attr_accessor :grip, :strength, :speed

    SWORDS = []

    def initialize(weapon_name, grip, guard, blade)
        @id = SWORDS.length + 1
        @weapon_name = weapon_name
        @grip = grip.to_str
        @guard = guard
        @blade = blade
        @strength = 0
        @speed = 0
        SWORDS << self
    end

    def strength=(strength)
        if @grip == "straight"
            @strength = strength + 5
        end
    end

    def to_s

        "Your weapon is called: #{@weapon_name}
            The grip is: #{@grip}
            The guard is: #{@guard}
            The blade is: #{@blade}
            Total stats are: Strength = #{@strength} and Speed = #{@speed}"

    end
end

A: Accessors are only called if you refer to a name on the class.
@strength = 0

This doesn't call an accessor. Ever. Even if one is defined.
self.strength = 0

This will call an accessor. Now, attr_accessor defines strength and strength=. If you're planning to write strength= yourself, then you want attr_reader, which does not define strength= for you.
class Weapon
  attr_reader :strength

  def initialize()
    ...
    self.strength = 0
  end

  ...

  def strength=(value)
    ...
  end

end

A: It might be easier to modify the getter:
class Weapon
  attr_accessor :grip, :strength

  # ...

  def strength
    if grip == 'straight'
      @strength + 5
    else
      @strength
    end
  end
end

w = Weapon.new
w.strength = 10

w.strength
#=> 10

Since the getter always re-calculates the value, you can modify both, strength and grip and it will instantly reflect the change:
w.grip = 'straight'
w.strength
#=> 15

w.strength = 12
w.strength
#=> 17

w.grip = 'curved'
w.strength
#=> 12

To avoid confusion, you could call the initial strength base_strength.


Q: How to prevent PyMongo from mutating inserted dict? If a document doesn't have an _id field, MongoDB automatically assigns a proper _id field for inserted document, I get that and that's fine for me.
But why pymongo mutates the inserted dict by adding _id field?
I want to use the inserted dict after it gets inserted and that extra _id field is a little bit problem.
I know I can use dict.pop('_id') to drop _id field, but if it is a list of documents(for insert_many) then that need an extra effort.
My question is, is there a way to prevent the inserted dict or List[dict] being mutated by _id field?

A: You could prevent this by inserting a copy of the dictionary or list of dictionary
In [1]: from copy import deepcopy

In [2]: from pymongo import MongoClient

In [3]: data = [{'a': 2}, {'a': 3}]

In [4]: with MongoClient() as client:
   ...:     client.test.collection.drop()
   ...:     result =  client.test.collection.insert_many(deepcopy(data))
   ...:

In [5]: result.inserted_ids
[ObjectId('5a819d34d99e830381e025b0'), ObjectId('5a819d34d99e830381e025b1')]

In [6]: data
Out[6]: [{'a': 2}, {'a': 3}]


Q: How can I check if the filename of a LaTeX document contains a string? I am preparing a LaTeX beamer presentation for students. I am looking for a simple way to create two versions of my presentation.
One version for the Students, which just contains the text of the tasks they get for homework and an other one for me which also contains the solution.
So I have created a macro that is intended to check if the file name contains "student".
If it does, the macro outputs nothing, and if it does not, the argument is passed:
\newcommand{\hausaufgabenLoesung}[1]{%
    \IfSubStringInString{student}{\jobname}{}{#1}%
}

But this does not work as intended.
No matter how I name the file, the conditional always goes to the false-expression.
I think the \jobname macro returns something which can not be processed by \IfSubStringInString but I have no other idea how I could approach this.
If I replace the \jobname macro in the conditional with a fixed string, it works as intended but this would render it fairly useless.
I used \jobname to avoid including the currfile-package, but with the currfile-macros I get the same behaviour. I am using texlive 2014 pdflatex on Linux and Windows.
Anyone here got a hint for that?
Here is a minimal complete example:
\documentclass[ngerman]{beamer}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[ngerman]{babel}

\usepackage{ifthen}
\usepackage{substr}

\newcommand{\hausaufgabenLoesung}[1]{%
    \IfSubStringInString{student}{\jobname}{}{#1}%
}

\begin{document}

\begin{frame}{Title}{Subtitle}
    \begin{itemize}
        \item \jobname
        \item Visible in both files
        \hausaufgabenLoesung{\item Solution not in the student file}
    \end{itemize}
\end{frame}

\end{document}

A: According to Ulrike Fischer's comment \jobname consists of 'wrong' catcode characters, a direct comparison is not possible with some hacks. One workaround is to write the jobname to a dummy file and read it immediately back to some \def\.... macro, say \RealJobName. This can be used as one string placeholder for the tests.
The \AtBeginDocument{} environment hook automatically does this and 'returns' the jobname in \RealJobName for later use.
Both approaches with substr and xstring work.
studentname.tex
\documentclass[ngerman]{beamer}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[ngerman]{babel}%

\usepackage{ifthen}
\usepackage{substr}
\usepackage{xstring}%

\newcommand{\hausaufgabenLoesung}[1]{%
    \IfSubStringInString{student}{\RealJobName}{}{#1}%
}

\newcommand{\hausaufgabenLoesungXString}[1]{%
\IfSubStr{\RealJobName}{student}{}{#1}%
}

\gdef\RealJobName{}%

\newwrite\mywrite%
\newread\myread%
\AtBeginDocument{%
\immediate\openout\mywrite\jobname.dum%
\immediate\write\mywrite{\jobname}%
\immediate\closeout\mywrite%
\immediate\openin\myread=\jobname.dum%
\read\myread to \RealJobName%
\immediate\closein\myread%
}%

\begin{document}

\begin{frame}{Title}{Subtitle}
    \begin{itemize}
        \item \jobname
        \item Visible in both files
          \hausaufgabenLoesung{\item Solution not in the student file}
          \hausaufgabenLoesungXString{\item Solution not in the student file}
    \end{itemize}
\end{frame}

\end{document}

A: The characters in \jobname have category code 12 and this defies substr, which uses an \ifx based comparison. You can simply stringify student, using the fact that substr commands fully expand their arguments:
\documentclass[ngerman]{beamer}

\usepackage[T1]{fontenc}
\usepackage[ngerman]{babel}

\usepackage{substr}

\newcommand{\hausaufgabenLoesung}[1]{%
    \IfSubStringInString{\detokenize{student}}{\jobname}{}{#1}%
}

\begin{document}

\begin{frame}{Title}{Subtitle}
    \begin{itemize}
        \item \jobname
        \item Visible in both files
        \hausaufgabenLoesung{\item Solution not in the student file}
    \end{itemize}
\end{frame}

\end{document}

This is what I get if the file name doesn't contain student:

This is what I get if the file name contains student:

A classical solution (without \detokenize):
\documentclass[ngerman]{beamer}

\usepackage[T1]{fontenc}
\usepackage[ngerman]{babel}

\usepackage{substr}

\begingroup\escapechar=-1
\xdef\studentstring{\string\student}
\endgroup

\newcommand{\hausaufgabenLoesung}[1]{%
    \IfSubStringInString{\studentstring}}{\jobname}{}{#1}%
}

\begin{document}

\begin{frame}{Title}{Subtitle}
    \begin{itemize}
        \item \jobname
        \item Visible in both files
        \hausaufgabenLoesung{\item Solution not in the student file}
    \end{itemize}
\end{frame}

\end{document}

A solution with regular expressions (vastly generalizable):
\documentclass[ngerman]{beamer}

\usepackage[T1]{fontenc}
\usepackage[ngerman]{babel}

\ExplSyntaxOn
\NewDocumentCommand{\hausaufgabenLoesung}{m}
 {
  \regex_match:nVF {student} \c_sys_jobname_str {#1}
 }
\cs_generate_variant:Nn \regex_match:nnF { nV }
\ExplSyntaxOff

\begin{document}

\begin{frame}{Title}{Subtitle}
    \begin{itemize}
        \item \jobname
        \item Visible in both files
        \hausaufgabenLoesung{\item Solution not in the student file}
    \end{itemize}
\end{frame}

\end{document}


Q: Initializing class object I am new to Java. I apologize if I ask a simple thing.
I wrote the below code but it seems that it doesn't initialize properly. because when I print the size of list1 it show the size = 0!! However, it should be 4!
public static class MyClass{
        public List <Integer> list1

        // Class Constructor
        public MyClass(int n){
            list1 = new ArrayList <Integer> (n);
            System.out.println("Size = " + list1.size() );
                    // prints Size = 0 !!!why???
        }

        public void init(int n){
            for(int cnt1 = 0; cnt1 < list1.size(); cnt1++){
            list1.set(cnt1 , cnt1);
            }
        }
        ...}

public static List<Integer> Func1(int n){
        MyClass = new myclass (n);
        myclass.init(n);
        ... }

public static void main(String args[]){
        int n = 4;
        result = Func1 (n);
        ...}

Why the size of the list1 is 0? It should be 4, because I pass 4 to Func1, and then it creates MyClass object with size n.
I would be thankful if someone can help me about this problem.

A: Array lists in Java have both a size and a capacity.

*

*Size tells you how many items are there in the list, while

*Capacity tells you how many items the list can hold before it needs to resize.

When you call ArrayList(int) constructor, you set the capacity, not the size, of the newly created array list. That is why you see zero printed out when you get the size.
Having a capacity of 4 means that you can add four integers to the list without triggering a resize, yet the list has zero elements until you start adding some data to it.

A: You have used the ArrayList constructor that determines its initial capacity, not its initial size.  The list has a capacity of 4, but nothing has been added yet, so its size is still 0.
Quoting from the linked Javadocs:

Constructs an empty list with the specified initial capacity.

Also, don't use set to add to the list.  That method replaces an element that is already there.  You must add to the list first (or use the other overloaded add method).


Q: Question regarding line element $y=bx^2$ is a parabola. Let h be the height of a variable line segment parallel to the x-axis having it's end points on the parabola.
I wish to solve:
$$\int_{\sqrt{\frac{h}{b}}}^{-\sqrt{\frac{h}{b}}}(-\textbf{i})\bullet (d \textbf{l})$$
Wouldn't $d\textbf{l}=dx(-\textbf{i})$ Since we are moving in negative x direction??

A: We have:
$$\int_{\sqrt{\frac{h}{b}}}^{-\sqrt{\frac{h}{b}}}(-\textbf{i})\bullet (d \textbf{l})=-\int_{\sqrt{-\frac{h}{b}}}^{\sqrt{\frac{h}{b}}}-(\textbf{i})\bullet (d \textbf{l})=
\int_{-\sqrt{\frac{h}{b}}}^{\sqrt{\frac{h}{b}}}(\textbf{i})\bullet (d \textbf{l})=
\int_{-\sqrt{\frac{h}{b}}}^{\sqrt{\frac{h}{b}}}dx
$$


Q: Control system with one setpoint, one process variable, and two outputs? I asked a version of this question before and got some unhelpful answers, I think because 1) the minutiae of my question distracted from the core concept, and 2) I didn't adequately describe the operation of my system. Original question can be found here.
In my system, I have a single process variable that I would like to control, concentration (C). The equipment I'm using has two ways to influence C. One way is by changing the amount of stuff (A) or by changing the speed at which stuff is introduced (S). A and S are controlled independently. C is measured by a single sensor. I originally assumed that A was a sort of "coarse" control and S was a "fine" control, but I no longer believe that to be the case.
Currently, I'm choosing A at the start of an experiment and letting a single PI controller change S as needed. This seems like a waste, since the equipment was designed for the tandem use of A and S to control its output. I only have a single sensor to monitor C.
Is there a control scheme that's fitting for this situation? The sole purpose of this system is to control and measure C. I've heard about cascading PI controllers, but I don't have a second sensor or even a second variable to measure, and ultimately I'd like to control both A and S.


Q: Is this a proper way of using AJAX with jQuery and PHP? I need some help. I'm going use AJAX (for the first time) and I'd like you to tell me whether the way I am going to show you is optimal.
Let's say that I have a select element.
<select class="update-db" data-id="25" data-original-value="2">
    <option value="1">Yellow</option>
    <option value="2" selected="selected">Red</option>
    <option value="3">Blue</option>
</select>

So here is what I do:
$(document).on('change', 'select.update-db', function() {

// Get needed data
var select = $(this);
var id = select.attr('data-id');
var originalValue = select.attr('data-original-value');
var newValue = select.val();

    // Perform the request
    $.ajax({
        method: 'POST',
        url: 'update-db.php',
        data: { id: id, 'original-value': originalValue, 'new-value': newValue }
    });

  // Then, if everything is okay, change the "original value" of the select element
  // so that we can perform the updating operation again without having to refresh the page
  .done(function() {
      select.attr('data-original-value', newValue);
  });

});

Then, on the other side, a PHP script validates everything and updates the database.
Is this the correct way of using AJAX? I feel it's not. What am I doing wrong?


Q: Convert array of objects into number for inject sum I am using Ruby 1.9.2, Rails 3.1. I have the following:
# review.rb
def calculate_rating
  all_rating = Review.select("rating").where("reviewable_id = ?", self.reviewable_id)
  all_rating.inject(:+)
end

# reviews_controller.rb
def create
  @reviewable = find_reviewable
  @review = @reviewable.reviews.where("user_id = ?", current_user).first
  if @review.save
    @review.calculate_rating
    redirect_to :id => nil
  else
    flash[:error] = 'Error saving review. Please try again.'
    redirect_to :id => nil
  end
end

The idea behind this is that when a new review with rating is submitted and saved, it will find all ratings for all @reviewable, sum all the ratings and divide by the total number of ratings.
Problem that I am facing currently is this line: all_rating = Review.select("rating").where("reviewable_id = ?", self.reviewable_id) where all_rating returns an array of objects, like below:
[#<Review rating: #<BigDecimal:1050f0a40,'0.3E1',9(18)>>, #<Review rating: #<BigDecimal:1050f0928,'0.1E1',9(18)>>]

which I can't do any arithmetic calculation to it. I need it to be an array of numbers before I could use the inject to sum it and divide by the number of ratings.
Please advise me how I can get the inject to work. Many thanks!

A: AR/SQL (faster):
Review.select("rating").where(:reviewable_id => self.reviewable_id).sum(:rating)

Ruby (slower):
Review.select("rating").where(:reviewable_id => self.reviewable_id).map(&:rating).sum

A: How about just doing this:
def calculate_rating
  all_rating = Review.select(:rating).where(:reviewable_id => reviewable_id).map(&:rating)
  all_rating.inject(:+) # or you could just do all_rating.sum
end


Q: How can I select specific parts of an image in android? If you have used photoshop, they have a tool that allows you to select parts of an image in order to edit specific locations within an image. Such as having a picture of a basketball and selecting that basketball with the use of the lasso tool in photoshop so you can make the rest of the image black and white.
I was wondering if there is any pre-defined class in the Android resource library that can make this sort of selection. Or would i have to make my own class that would look for a pattern in an image? Basically is there a tool available in android that can make these image selections that I can use inside my app?
It would also be helpful if someone can point me towards a reading on the subject of image selection programming or a third party library. I can't seem to find anything specific.


Q: Unicode-Math and \not I am using unicode-math to typeset equations. Since I am using a non-standard keyboard layout, I prefer to enter most math symbols with their unicode representation. However, the the \not operator sometimes produces a 6 as output. Consider the following MWE.
\documentclass{standalone}

\usepackage{unicode-math}

\begin{document}
  \(\not ∈ \; \not\in \quad ≠ \; \not = \; \neq \quad ≮ \; \not<\)
\end{document}

Which produces—using XeLaTeX—the following output.

Is this a bug of the unicode-math package or is it because of some encoding problems?

A: I think you have an old version of unicode-math (the “6 problem” has been solved months ago). However, even for the last version, \not ∈ will not yield the expected result; help unicode-math to:
\documentclass{article}

\usepackage{unicode-math}
\NewNegationCommand{∈}{\notin}

\begin{document}
  \(\not ∈ \; \not\in \quad ≠ \; \not = \; \neq \quad ≮ \; \not<\)
\end{document}


Q: ¿como capturar el valor de un checkbox sin usar un formulario y pasar ese valor como parámetro? hola comunidad tengo una duda como puedo capturar el valor de un checkbox sin usar un formulario, quiero capturar el valor simplemente seleccionando el checkbox una vez teniendo el valor pasarlo como parámetro aun método el cual llama a endpoint en un controlador
este es mi checkbox toggle en el cual quiero capturar su valor:
<input id="toggle-one" data-onstyle="info" type="checkbox" data-toggle="toggle" data-on="Enabled" data-off="Disabled">

este es el método al cual le quiero pasar el valor capturado en el checkbox:
   protected async Task GetXml(bool filtro)
    {
        var responseHttp = await repositorio.Get<PaginadorGenerico<Comprobante>>($"api/Xml?filtro={filtro}");
        var resultado = responseHttp.Response.Resultado;
        Comprobante = (List<Comprobante>)resultado;
    }

y esta es solo una parte del controlador el cual recibirá el parámetro enviado por el método:
 [HttpGet]
        public async Task<ActionResult<PaginadorGenerico<Comprobante>>> Get(bool filtro,string buscar, int pagina,
                                                                                string orden = "Rfc",
                                                                                string tipo_orden = "ASC",
                                                                                int registros_por_pagina = 10)
        {
            List<Comprobante> _Xml;
            PaginadorGenerico<Comprobante> _PaginadorFacturas;
            _Xml = db.XMLs.Find(_ => true).ToList();

A: Debes definir el evento onchange del checkbox.
Una de las formas más sencillas de afrontar este escenario sería mantener una propiedad en la view para luego usarla en tu método GetXml, en vez de pasarlo por parámetro.
<input id="toggle-one" type="checkbox" @onchange="e => CheckChanged(e)">

@code
{
    bool _checked = false;

    void CheckChanged(ChangeEventArgs ev)
    {
        _checked = (bool)ev.Value; // Guardamos el valor
    }

    // ...

    async Task GetXml()
    {
        // En la llamada ya no usas el parámetro filtro sinó la propiedad _checked.
        // ...
    }
}

Espero que sirva.


Q: What is good naming form for variables in loops JS? Hi so as I mentioned in the title I have a bunch of loops within loops in my code and most of them use a variable to loop through stuff. I call my variables ia, then ib then ic and so on. What is good form for the naming of these variables?
Here is some code that might help make sense of what I am saying

for (var ic = 0; ic <= currState.length; ic++) { //loop the columns and check if there is a
  if (currState[ic] == 0) {
    for (var id = 1; id <= currState.length; id++) { //loop the rows of a column

      tryPos = [id, ic + 1]; //id -> row | ic -> column

      if (checkClash(currState, tryPos) == false) {

        currState[ic] = id
        break;
      }
    }
  }
}

A: The name of your variables requires good descriptive skills and a shared cultural background.
In this case you should use row and col but don't forget the scope of your variables.
I would like recommend you read the Book: Clean Code.
Especially you can review some of the proposed rules on this post (http://www.itiseezee.com/?p=83).

A: looping over a table or grid, row and column are perfectly fine variable names.
for more generic nested loops i, j, and k (in that order) are typical counter variables even though they are less aptly named


Q: C++ code execution time depends on code structre I came across this great youtube tutorial and in one of the slides I saw something I didn't understand. Why is this happening? Is this compiler related?
Version #1 looks like this:
const int N = 5000;
float a [N*N];

for (int x=0; x<n; ++x)
     for(int y=0; y<N; ++y)
          sum+=a[x+y*N];

and takes about 239.4ms to execute.
And version #2 looks like this:
const int N = 5000;
float a [N*N];

for (int y=0; y<n; ++y)
     for(int x=0; x<N; ++x)
          sum+=a[x+y*N];

and takes about 79.5ms to execute.
Why is this happening?

A: The second example demonstrates better data locality since it accesses elements in the same row. Basically it performs sequential memory read, while first example jumps over sizeof(float) * N bytes on each iteration putting extra stress on CPU cache / memory.


Q: Using where clause for R Variable in R script to use it in SQL statement I have two tables; viz
table1 = PID (primary key) + 20 other columns & 200 records from database1 AND
table2 = [Serial no] (primary key) + 10 other columns  & 300 records from database2.
I am trying to extract values from table2 where PID = [Serial no].
Note: PID = [SCK34ICV7, NSCK876DL, ......].
I refered "Pass string Variable in R script to use it in SQL statement"
t1 <- sqlquery(db1, "select * from table1")
r1 <- t1$PID
class(r1) = 'factor'
t2 <- sqlquery(db2, "select * from table2 where [Serial no] = '(",r1,")' ",sep ="")

I also tried other functions viz paste0(), fn$ from gsubfn and sprintf() and getting error like - 'c is not a recognized built in function name' ; 'Incorrect syntax'.
Please suggest the best way to do it.
Reg,
Mrutyunjaya

A: Your query is off. See here for what the proper format should be.
r1 <- c("PID1","PID2","PID3")

wrong
paste("select * from table2 where [Serial no] = '(",r1,")' ",sep ="")

output:
[1] "select * from table2 where [Serial no] = '(PID1)' " "select * from table2 where [Serial no] = '(PID2)' " "select * from table2 where [Serial no] = '(PID3)' "

correct
paste("select * from table2 where [Serial no] IN (",paste(r1,collapse=", "),") ",sep ="")

Output:
[1] "select * from table2 where [Serial no] IN (PID1, PID2, PID3) "

So the query becomes:
t2 <- sqlquery(db2,paste0("select * from table2 where [Serial no] IN (",paste(r1,collapse=", "),") ",sep =""))

Hope this helps.


Q: PGM image not opening I have a pgm file which is well formatted like this
P2
# CREATOR: GIMP PNM Filter Version 1.1
19 19
0 71 73 74 73 73 74 73 71 70 71 74 72 69 68 71 72 66 69
70 70 74 70 69 69 69 69 71 68 70 72 66 70 71 69 65 68 69
66 72 73 74 74 73 70 73 72 66 70 68 67 68 68 68 67 66 69
66 72 78 74 74 73 71 71 70 70 68 70 66 69 66 65 66 62 62
62 72 76 72 73 75 72 71 68 74 71 68 66 70 65 67 62 56 57
66 70 72 71 72 69 72 73 74 69 65 66 60 64 68 93 99 139 225
240 68 71 70 70 69 70 71 64 64 46 60 57 86 153 206 233 240 244
245 72 69 70 68 67 68 68 68 61 58 82 178 229 236 236 229 238 244
245 74 67 67 70 68 66 69 65 64 97 218 240 242 235 234 240 243 244
244 75 74 73 72 69 68 73 74 128 223 239 242 239 242 243 242 244 241
244 72 76 74 72 69 71 68 83 155 234 242 240 237 242 237 241 240 245
243 72 75 75 71 68 69 65 68 127 237 241 240 241 243 245 244 244 245
244 72 71 69 71 66 66 63 63 107 239 240 244 245 245 246 245 246 246
246 72 70 70 67 64 63 60 74 218 242 245 245 245 245 246 246 247 246
245 73 72 71 70 70 66 61 201 241 244 245 246 245 246 247 246 247 246
247 71 69 71 68 63 61 115 236 239 244 244 245 245 246 246 246 246 246
245 78 72 73 73 68 63 167 243 244 244 245 245 245 246 246 246 246 246
245 75 72 69 71 67 61 218 245 245 246 246 246 246 246 246 246 247 246
246 76 72 72 68 65 74 238 246 246 246 247 246 246 246 246 246 246 246

But trying to open it with "visionneur d'images" on ubuntu i get an error :

Please help me.. I don't know what is the issue.

A: The number after image dimensions is supposed to be the maximum value in the image. You have it as '0'. Scanning quickly through the data, the value should be 247. Just replace the 0 with 247, using a text editor.


Q: Is there a destructor for a pointer in c++? string * str=new string;
delete str;

when I delete 'str' which points to an object, do two destructors get called - one for the pointer itself, and one for the object it points to?
What would the pointer's destructor do?

A: The concept of destructor is applicable only to objects (i.e. entities defined with class or struct), not to plain types, like a pointer is. A pointer lives just like a int variable does.

A: The pointer it self doesn't been destructed by the delete statement. but as any scope variable it's been destroyed when the scope ends.
Example:
void Function()
{
    string * str=new string;
    delete str; // <-- here the string is destructed
} // <-- here the pointer is "destructed", which is mean it's memory freed from the stuck but no actual destruction function is called..

A: delete just causes the object that the given pointer is pointing at to be destroyed (in this case, the string object. The pointer itself, denoted by str, has automatic storage duration and will be destroyed when it goes out of scope like any other local variable.
Note, however, that non-class types do not have destructors. So even when you use delete with non-class types, no destructor is called, but when the pointer goes out of scope, it gets destroyed as normally happens with any other automatic variable (means the pointer just reaches the end of its lifetime, though the memory pointed to by the pointer is not deallocated until you  use delete to explicitly deallocate it.).

A:
when I delete 'str' which points to an object, do two destructors get called - one for the pointer itself, and one for the object it points to?

No. delete takes a pointer argument. It destroys the object that's pointed to (using its destructor, if it has one, and doing nothing otherwise), and deallocates the memory that's pointed to. You must previously have used new to allocate the memory and create the object there.
The pointer itself is not affected; but it no longer points to a valid object, so you mustn't do anything with it. This is sometimes known as a "dangling pointer".

What would the pointer's destructor do?

Nothing. Only class types have destructors.

A: The destructor for a raw pointer, like your example of std::string*, is trivial (just like the destructors for other primitive types: int, double, etc.)
Smart pointer classes have non-trivial destructors that do things like free resources, adjust reference counts, etc.

A: I like the simplification you get from the notion that every type has a destructor. That way you don't have a mental glitch with a template that explicitly destroys a stored value, even if the type of that stored value is an int or a pointer:
template <class T> struct wrapper {
    unsigned char data[sizeof(T)];
    wrapper(T t) { ptr = new (data) T; }
    ~wrapper() { (T*)&data->~T(); } // ignore possible alignment problem

wrapper<int> i(3);

However, the destructors for ints and pointers are utterly trivial: they don't do anything, and there is no place you can go to see the definition of the destructor, because the definition doesn't exist. So it's also reasonable to say that they don't have destructors.
Either way, when a pointer goes out of scope it simply disappears; no special code runs.


Q: Prevent table cells from breaking across page when converting html to pdf Using Google Apps Script, I have an html template that I fill and then send out (via fax and/or email) as a pdf.  The template includes a two-column table with questions/answers.
If there are enough rows, the table breaks across pages in the pdf, and the page breaks usually happen in the middle of cells; I'd like to avoid this.
I've tried using break-inside: avoid; in both the
 and  elements, with no effect.
Here's the template:

      Question
      Response

  <? rows.forEach(function(row){ ?>

       <?= row.question ?>
       <?!= row.answer ?>

  <? }) ?>

and here's the Apps Script code that converts it to pdf:
var html = '
' + subject + '
'
var tableTemplate = HtmlService.createTemplateFromFile('response-table-template')
tableTemplate.rows = rows;
html += tableTemplate.evaluate().getContent();

var blob = Utilities.newBlob(html, MimeType.HTML, subject).getAs(MimeType.PDF);

and then the blob is attached to an email/fax.  All of that works fine except for my question: Is there a way to avoid breaking table rows over the pages?  Possibly another way to convert the html to pdf that respects the break-inside property?  Or an html/css solution that will be respected by Apps Script when converting the html blob to pdf?

A: Unfortunately, in the current stage, it seems that break-inside is not reflected to Utilities.newBlob(html, MimeType.HTML, subject).getAs(MimeType.PDF). But I'm not sure whether this is the current specification. So as a workaround, in your case, how about the following flow?

*

*Prepare HTML data.

*

*This has already been prepared in your script.

*Convert HTML data to Google Document.

*

*In this case, Drive API is used.

*Convert Google Document to PDF data.

*Create blob as a file.

When your script is modified, it becomes as follows.
Modified script:
Before you use this script, please enable Drive API at Advanced Google services.
From:
var blob = Utilities.newBlob(html, MimeType.HTML, subject).getAs(MimeType.PDF);

To:
// 1. Prepare HTML data.
var blob = Utilities.newBlob(html, MimeType.HTML, subject);

// 2. Convert HTML data to Google Doc
var id = Drive.Files.insert({title: subject, mimeType: MimeType.GOOGLE_DOCS}, blob).id;

// 3. Convert Google Document to PDF data.
var url = "https://docs.google.com/feeds/download/documents/export/Export?exportFormat=pdf&id=" + id;
var pdf = UrlFetchApp.fetch(url, {headers: {authorization: "Bearer " + ScriptApp.getOAuthToken()}}).getBlob().setName(subject);
DriveApp.getFileById(id).setTrashed(true);

// 4. Create blob as a file.
DriveApp.createFile(pdf);

Reference:

*

*Files: insert

A: By experimentation I found that Utilities.newBlob(html, MimeType.HTML, subject).getAs(MimeType.PDF) will respect page-break-inside: avoid; (rather than break-inside: avoid;) but only if it's applied to an entire table.  So I had to treat each table row as a separate table.  This version of the html template solved the problem:

      Question
      Response

<? rows.forEach(function(row){ ?>

         <?= row.question ?>
         <?!= row.answer ?>

<? }) ?>

For the record, converting to a Google Doc and then to pdf did not solve the problem; it appears that Google Doc also allows table cells to break across pages.  However, writing the data to a Google Sheet and then downloading as pdf does prevent breaking cells across pages; Sheets seems to take care of this automatically, so that's an alternate solution.


Q: Random number generator for python based discord bot What I am trying to do is when someone enters the command !random (argument) I want the bot to generate a number between 1 and what they put as the argument. But whenever I try to do this it gives me around 6 different errors that are very long and make no sense to me. My current code for this command is below.
@Bot.command(pass_context=True)
async def random1and10(ctx, number):
    arg = random.randint(1, number)
    if number:
        await Bot.say(arg)
    else:
        await Bot.say('Please select a valid number')

A: I guess number is passed as a string, so:

*

*you need to cast it to an integer before passing it to randint

*probably need to cast it to a string again before "saying" it

What's more, you're not using the correct way to check for wrong integer values; if number will never be False because your randint call will only return integers greater than 0 (or raise an error).

A fixed version would be something like:
@Bot.command(pass_context=True)
async def random1and10(ctx, number):
    try:
        arg = random.randint(1, int(number))
    except ValueError:
        await Bot.say("Invalid number")
    else:
        await Bot.say(str(arg))

Your mileage may vary, I didn't run it. I'm not sure about the decorated function signature.

whenever I try to do this it gives me around 6 different errors that are very long and make no sense to me.

Maybe they can make sense to others :) I'm relatively new to this site, but I think including them in your post would have been better. Cheers !


Q: How to determine who started a process? every few minutes I found this process running
 root      949062  100  0.0  37204  1488 ?        R<   05:14   0:51 /usr/local/cpanel/3rdparty/bin/clamdscan --quiet --no-summary /etc/passwd

It's using 100% cpu. I kill it , and after some time I see it again .
How can I determine who is running this process ?

A: One way would be to replace the process by a "wrapper" script.
 # cd /usr/local/cpanel/3rdparty/bin/
 # cp -p clamdscan clamdscan.orig
 # cat >clamdscan <<eof
 #!/bin/bash
 echo ==================== >>/tmp/clamscan.log
 date  >>/tmp/clamscan.log
 id    >>/tmp/clamscan.log
 ps -fp $PPID   >>/tmp/clamscan.log
 tty   >>/tmp/clamscan.log
 pstree -Ap >> /tmp/clamscan.log
 exec $0.orig $*
 eof

That way each each call of clamscan will log some information.
The commands are just to illustrate that you may change it at your convenience.
Of course you should not let it run too long if you don't want to have a full /tmp directory.
To abort simply do:
 # cd /usr/local/cpanel/3rdparty/bin/
 # mv clamdscan.orig clamdscan


Q: Example for customizing the ignored pattern list in Django's collectstatic Like other questions here, I want to ignore my .scss files when running collectstatic. But because I'm using Heroku, which runs a collectstatic automatically, I would rather customize collectstatic's ignore pattern list rather than change the management command.
Django 2.2 provides a way to do this, as documented below:

The default ignored pattern list, ['CVS', '.', '~'], can be
  customized in a more persistent way than providing the --ignore
  command option at each collectstatic invocation. Provide a custom
  AppConfig class, override the ignore_patterns attribute of this class
  and replace 'django.contrib.staticfiles' with that class path in your
  INSTALLED_APPS setting:

from django.contrib.staticfiles.apps import StaticFilesConfig

class MyStaticFilesConfig(StaticFilesConfig):
    ignore_patterns = [...]  # your custom ignore list

My problem is that, this being my first Django project, I don't quite know how to provide a custom AppConfig class (and diving into the AppConfig docs hasn't helped). I mean, should I add this class to a whole new app or use an existing one? Is this class going to be in a apps.py file? If so, what should be the best app to do so? So I'm asking if anyone could provide me with an example of the best practice.
For reference, right now my app structure is like this (with all templates, assets and apps grouped together in their own folders rather than within each app):
-- project_name
  -- assets
    -- app1
  -- templates
  -- project_name
    -- app1
    -- app2
    -- __init__.py
    -- settings.py
    -- urls.py
    -- wsgi.py

UPDATE:
As Nico suggested, I've created an app called static in project_name.project_name with only an init.py file and an apps.py. The apps.py is exactly like the doc example:
from django.contrib.staticfiles.apps import StaticFilesConfig

class StaticConfig(StaticFilesConfig):
    name = 'static'
    ignore_patterns = ['CVS', '.*', '*~', '*.scss']

However, I'm running into errors when replacing 'django.contrib.staticfiles' from INSTALLED_APPS.

*

*Replacing it for 'project_name.static' makes the terminal not understand the collectstatic management command.

*Adding 'project_name' after 'django.contrib.staticfiles' (i.e.
not removing the later) makes it ignore the overwrite and collect the
.scss files.

*Replacing for 'project_name.static.apps.StaticConfig' throws a
Cannot import 'static'. error

UPDATE 2:
After I rollbacked the app creation, I tried is again, but now, instead of using the startapp with the file path, I created the app on the project root, tested it, then moved it manually to my apps' folders, and tested it again. For some reason I don't quite understand, this time I replaced 'django.contrib.staticfiles' for 'project_name.static' and now it worked.

A: You can add it to some other app, or even create just a file called static in the root of project_name and refer to the class inside this file in your settings.INSTALLED_APPS directly, but the recommended way to provide AppConfigs is inside an apps.py file inside the application package.
If you have no app where this AppConfig could be placed, I think the best practice would be to create a package under project_name.project_name called static, with only an init.py file and an apps.py file.
In this file you can create your AppConfig in the way you described.
Your file structure will then look like this:
-- project_name
  -- assets
    -- app1
  -- templates
  -- project_name
    -- app1
    -- app2
    -- static
       -- __init__.py
       -- apps.py
    -- __init__.py
    -- settings.py
    -- urls.py
    -- wsgi.py


Q: Revoke drive access through Google Play Services Is there a way to revoke drive access granted through Google Play Services?
Referring to this article:
https://developer.android.com/google/auth/api-client.html
I granted access to g drive from my app like so:
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();

My question is, is there a clean way to revoke g drive access
i.e. without needing to do credential.getToken() and making http call to https://accounts.google.com/o/oauth2/revoke?token=
I'm looking for something like Drive.DriveApi.revokeAccessAndDisconnect();
I know there is one for g plus, but i cant find one for g drive.
http://developer.android.com/reference/com/google/android/gms/plus/Account.html

A: Yes, there is an method for revoking of Google Drive scope.
GoogleSignInClient googleSignInClient = buildGoogleSignInClient();
googleSignInClient.revokeAccess().addOnCompleteListener(onCompleteListener);

where
private GoogleSignInClient buildGoogleSignInClient() {
    GoogleSignInOptions signInOptions =
            new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestScopes(Drive.SCOPE_FILE)
                    .build();
    return GoogleSignIn.getClient(this, signInOptions);
}

For more information, you can check this reference


Q: Django - deleting users with on_delete=models.CASCADE causes problems with signals.post_delete We are using Django 3.1 for our websites. We have a model, User, which is related to two SiteProfile models for two websites, and is also related to other models such as Friend and UserEmailAddress. All the relations are with on_delete=models.CASCADE. We also have models.signals.post_delete signals for models such as Friend, to update the number of friends a user has, which is saved in one of the SiteProfile models. But the problem is, when deleting a user, the signal is called and then the SiteProfile object is saved, and then I get an exception for django.db.utils.IntegrityError - violations of foreign keys. We used to have the same problem with the UserEmailAddress model (a user's email address), which I fixed with the following code:
def delete(self, *args, **kwargs):
    if ((self.is_staff) or (self.is_superuser)):
        warnings.warn('Can’t delete staff user.')
        return False
    else:
        with transaction.atomic():
            for user_email_address in self.email_addresses.all():
                user_email_address.delete()
            return_value = super().delete(*args, **kwargs)
        return return_value

But I would like to know, is there a better way to delete a user with all its related objects which have on_delete=models.CASCADE, but without saving the counters in models.signals.post_delete to the database? Can I check something in models.signals.post_delete to know if the user is being deleted and then don't save the counters? Since I don't want to specifically delete any related object in the def delete method - there are at least 5 such models not including the two SiteProfile models.


Q: F# unit of measure to model area How can I use F# unit of measure to model the area of certain geometries.
The code i have so far is this but it isn't quite compiling.
[<Measure>] type radius
[<Measure>] type PI
[<Measure>] type area

let convertRadiusToArea (r:float<radius>) : float<area>  =
    // let pi = System.Math.PI
    let a:float<PI> = 3.14<PI>
    r * r * System.Math.PI

A: There are several things here:

*

*You need to define area as being a square length with type area = radius * radius. Otherwise the compiler has no way to match your input and output units.

*Pi, when used like this, is dimensionless, which is represented in F# as <1> or just no unit suffix.

[<Measure>] type radius
[<Measure>] type area = radius * radius

let convertRadiusToArea (r:float<radius>) : float<area>  =
    let pi = System.Math.PI
    r * r * pi

A: A better example of using F#'s unit of measure would be this:
[<Measure>] type cm

let convertRadiusToArea(r:float<cm>) : float<cm^2> =
    r * r * System.Math.PI

The idea being that you get benefits of the units of measurement in your calculations and derivations. You're not getting that by creating a unit of measure called 'radius'. Is it in meters? Feet? Centimetres? And that is why you would introduce them into an F# function, to be non-ambiguous about the unit of measurement for the inputs and outputs.
Units of measure in F# should IMO be modelled the way we use units of measurement in any other calculations or real world example like speed, temperature, force etc.


Q: NSG Configuration Management I am looking for a tool or some way to manage the Azure NSG configuration. NSG rules are changed manually on ad-hoc basis at the moment. I am looking to implement this NSG config change in more scripted fashion so that I can track the changes history as well.
I am looking at Git based repository of NSG where all ARM templates for NSG with different parameter files and run via those via Azure powershell or running as part of Azure Devops CI/CD pipeline.
I am not sure if Ansible can help with this management of NSGs or Terraform can help.
I love to think about Ansible for this. Anyone knows about this requirement how NSG can be managed.
Thank you

A: You can manage Azure NSG configuration via ARM template, Teffaform and Ansible.

*

*ARM template

1,You can check out below examples to create ARM Template to manage Azure NSG.
Create a Network Security Group.
How to create NSGs using a template
Please check the official document for more examples.
2, After the ARM template is created and pushed to your git repo. You can create azure pipeline to automate the deployment. See tutorial here.
3, Then you need to create an azure Resource Manager service connection to connect your Azure subscription to Azure devops. See this thread for an example.
4, In your azure devops pipeline. You can use ARM template deployment task to deploy the ARM template.
steps:
- task: AzureResourceManagerTemplateDeployment@3
  displayName: 'ARM Template deployment: Resource Group scope'
  inputs:
    azureResourceManagerConnection: 'azure Resource Manager service connection'
    subscriptionId: '...'
    resourceGroupName: '...'
    location: 'East US'
    csmFile: azuredeploy.json
    csmParametersFile: azuredeploy.parameters.json

*

*Teffaform

1, Create Teffaform configuration file. See example here.
Check out terraform-azurerm-network-security-group module for more information.
2, Upload Teffaform configuration file to git repo. Create Azure devops pipeline
3, Create azure Resource Manager service connection like above using ARM template.
4, Use Terraform task in the azure devops pipeline.
steps:
- task: ms-devlabs.custom-terraform-tasks.custom-terraform-installer-task.TerraformInstaller@0
  displayName: 'Install Terraform 0.12.3'

- task: ms-devlabs.custom-terraform-tasks.custom-terraform-release-task.TerraformTaskV1@0
  displayName: 'Terraform : azurerm'
  inputs:
    command: apply
    environmentServiceNameAzureRM: 'azure Resource Manager service connection'

*

*Ansible

1, Create Ansible playbook with plugin azure.azcollection.azure_rm_securitygroup
Please check out the example here.
2,Upload ansible playbook to git repo. Create Azure devops pipeline. Use Ansible task in your pipeline.
Please check out this detailed tutorial for more information about how to run ansible playbook in azure devops pipeline.

*

*Azure powershell/Azure CLI commands

You can using azure powershell or azure cli commands to manage azure nsg. And run the commands in Azure powershell task or azure cli task in azure devops pipeline.
Please check out this document for more information.


Q: Macosx yosemite installing mysql-python config error I am trying install mysql-python but always throw error. The command is "pip install mysql-python". I searched in google and tried everything but i am still getting error.
I am using mamp, MAMP's path is "/Applications/MAMP". I tested mysql with php and there is no error, mysql is working. I also connected to mysql by navicat. I am sure that mysql is installed and it is working.
I put the error screenshoot.

A: You need libmysqlclient.so library to be able to install MySQLdb,
Which come with MySQL Server and client and can also be downloaded with MySQL Connector/C.
Locate the library and set your DYLD_LIBRARY_PATH to have the path where libmysqlclient.so is present.


Q: How do i make a println list of random numbers with no duplicates? is there a way I can make the drawerList() method look at the output from the drawerNumber() and add them to an array. I want to store the outputs into an array list in order to find the duplicates and print out both the stored values and possibly make an if else statement that finds duplicates of the random numbers and mark those outputs as "already drawn" This is my first semester of CS and i am in the learning stages so i feel like what i'm trying to do is out of my knowledge and I'm not sure what to do.
import java.util.Scanner;

import java.util.Random;

class RandomNumbers{
    public static void main(String [] args){

 System.out.println(drawerNumbers());
}

//drawerNumbers()-draws new numbers

public static int drawerNumbers(){
    Random rand = new Random();
    int num = rand.nextInt(75)+1;
    return num;
}

//  drawerList()- List of numbers drawn
 public static int drawerList(){ //Method.
  String p = Integer.toString(drawerList()); //Convert method into string in order to be put in array
int[] numbers = new int[p.length()]; // creates the array to store the values

//

After this not sure how to make the outputs be listed to the console and how to make the program find the duplicate random numbers.

`

*

*Heading

` ##

A: It seems your intention is to randomly pick numbers between 1 and 75 without repeating a number. This is most easily done by inverting the problem to randomly ordering the numbers 1-75 then iterating through them:
List<Integer> nums = new ArrayList<Integer>(75);
for (int i = 1; i < 75; i++)
    nums.add(i);
Collections.shuffle(nums);

Now they are in random order, just use them one by one:
for (Integer i : nums) {
    // use i
}


Q: Should I use systemd or docker-compose to keep Docker containers running on my systems? We are talking about Docker containers as sysdig, consul, fluentd, mesos-slave, etc. that we are running on almost all machines.
Currently we are using Ubuntu's Upstart and CoreOS's Fleetctl. We're migrating to Ubuntu 18.04 LTS and currently considering whether to convert the configuration to:

*

*Systemd or

*Docker-compose

Systemd can do health checks and automatically bring back processes that died back online. It's also the most similar to Upstart that we use heavily. Our Upstart configuration files are generated from cloud-config like this:
- >
    /usr/local/bin/generate-docker-upstart fluentd registry/fluentd:1.0.1
    -e HOST=elasticsearch
    -e PORT=9200
    -e INDEX=fluentd
    -e NODE=`hostname -s`
    -e ROLE=app
    -e ENVIRONMENT={{Ref:Environment}}
    -e TENANT={{Ref:Tenant}}
    -p 24224:24224
    --name \$NAME \$IMAGE

We use AWS CloudFormation to bring the virtual machines online.
We cannot use a real container orchestration framework (we already use Marathon/Mesos) because these services have to be running on each host and before Marathon/Mesos run.
What solution makes most sense? Convert these files to systemd or start using docker-compose, despite already using Marathon on Mesos?


Q: How does this endian conversion work? A QNX library called gfpr.h contains the line
#define ENDIAN_LE16(__x)    (__x)

which is used as follows
var1 = ENDIAN_LE16(var1);

to convert the endianness of (unsigned short) var1.  How does this work?  __x and x__ must have some special meaning to the preprocessor?

A: __x does not have a special meaning.  ENDIAN_LE16 is a macro that makes a place to change endianness without changing your source code.  Each build target can have a different version of gfpr.h specific for that target.
You must be compiling for a little-endian machine, so ENDIAN_LE16 doesn't need to make any changes.  It just leaves its argument (__x) unchanged.  If you were compiling for a big-endian target, ENDIAN_LE16 would be defined to swap the bytes of its argument.  Something like:
#define ENDIAN_LE16(__x) ( (((x) & 0xff) << 8) | (((x) >> 8) & 0xff) )

That way, by changing which target's gfpr.h file you include, you get the right results without having to change your source code.
Edit Per the file you're probably looking at, ENDIAN_BE32 invokes ENDIAN_RET32, which twiddles bits in a way similar to what I showed above.


Q: Live Reload of SCSS in React JS using Webpack I would like to ask if there's a way that the compiling of .scss file to .css is included in webpack hot reload, I use to always run npm run build to convert my .scss to .css
Here's my webpack.config:
var autoprefixer = require('autoprefixer');
var ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
    entry: './app/main.js',
    output: {
        path: './',
        filename: 'index.js'
    },
    devServer: {
        inline: true,
        port: 3333
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                exclude: '/node_modules/',
                loader: 'babel',
                query: {
                    presets: ['es2015','react']
                }
            },
            {
                 test: /\.scss$/,
                 loader: ExtractTextPlugin.extract("style-loader", "css-loader!sass-loader")
            }
        ]
    },
    plugins: [
        new ExtractTextPlugin('[name].css',{
            allChunks: false
        })
    ],
    postcss: [
        autoprefixer({
          browsers: ['last 2 versions']
        })
    ]
}


Q: Can the argument for Switch statement have an expression to eliminate a variable used for comparison? This program simulates a simple menu driven calculator with +, -, *, and / operations
#include <stdio.h>
#include <conio.h>
int main()
{
    float a = 0, b = 0;
    printf(" Enter two numbers: ");
    scanf(" %f %f",&a ,&b);

    puts(" Enter choice number of operation: ");
    puts(" 1)Addition ");
    puts(" 2)Subtraction ");
    puts(" 3)Multiplication ");
    puts(" 4)Division ");

    flushall();    //To clear the trailing '\n'
    switch( getchar() - 48 )
    {
        case 1: printf("The Sum of %.2f and %.2f is : %.2f",a,b,(a+b));
            break;
        case 2: printf("The Difference of %.2f and %.2f is : %.2f",a,b,(a-b));
            break;
        case 3: printf("The Product of %.2f and %.2f is : %.2f",a,b,(a*b));
            break;
        case 4: if ( b != 0 ) printf("The Quotient of %.2f and %.2f is : %.2f",a,b,(a/b));
            else puts("Error, divide by zero not possible.");
            break;
        default: puts("Error, Invalid choice");
    }
    return 0;
}

Is it better this way? As I have avoided the usage of a variable, and equivalently described why the program crashes when the last input is not a valid choice, I don't think there is any need to add info about what was entered. It adds an extra variable into the picture.

A: Yes, switch statement can take an expression for the value on which you switch. Your code should work fine, except that getchar() would read the leftover '\n' character from scanf of the operands.
Add another call to getchar() before the switch to read and discard that extra character.

A: While the code is valid and correct, I'd do the following to make it more readable:
switch(getchar()) {
    case '1': // ...
    case '2': // ...
    case '3': // ...
    case '4': // ...
}

Or
switch(getchar() - '0') {
    case 1: // ...
    case 2: // ...
}

This is to avoid using the magic number 48, which may not be understood easily by readers.
Furthermore, you can discard input until the next \n using a simple while loop:
while(getchar() != '\n') ;

In addition to the \n, this will also read and discard anything before the newline.

A: switch ( expression )

So you have a valid expression and you can have a expression like you have if you really have a need for something like this.
Else
char ch = getchar(); /* or scanf(" %c",&ch); (Better)*/
int a = ch - '0';

switch(a)
{
}

A: For your answer : Yes the switch can accept an expression in its arguments but it should returns only one of these types char int short long int long long int it can be also signed or unsigned !
There is no need to make a cast for the expression getchar() - 48  because getchar() returns int and 48 is an int so th result would be an int
now after compiling you have to add 3 number one for the variable a and the second for the variable b and the third for the switch statement... for instance
$./executable_file
Enter two numbers: 1 2 3

A: Switch formatting
This is a suggested formatting of your switch statement.  I disagree with the idea of using getchar() in the switch statement (though it is technically legal, it is simply a bad idea in practice), so I've replaced that with c:
int c;

/* c is set by some input operation.
** It might be char c; if you read its value with scanf(), but it must be int if you use getchar()
*/
switch (c)
{
    case 1:
        printf("The Sum of %.2f and %.2f is : %.2f", a, b, (a+b));
        break;
    case 2:
        printf("The Difference of %.2f and %.2f is : %.2f", a, b, (a-b));
        break;
    case 3:
        printf("The Product of %.2f and %.2f is : %.2f", a, b, (a*b));
        break;
    case 4:
        if (b != 0)
            printf("The Quotient of %.2f and %.2f is : %.2f",a, b, (a/b));
        else
            fputs("Error, divide by zero not possible.\n", stderr);
        break;
    default:
        fprintf(stderr, "Error, Invalid choice %c\n", c);
        break;
}

Note the use of break; after the default: label too; it protects you against future additions to the code and is completely uniform.  (The default: label does not have to be last, though that is the conventional place for it to go.)  Commas get a space after them; so do if, for, while, switch, but function calls do not get a space between the name and the open parenthesis.  You don't normally need a space after an open parenthesis or before a close parenthesis.  Errors are reported to standard error.
Personally, I like the actions of the switch to be indented just one level, not two levels, so I'd use:
switch (c)
{
case 1:
    printf("The Sum of %.2f and %.2f is : %.2f", a, b, (a+b));
    break;
case 2:
    printf("The Difference of %.2f and %.2f is : %.2f", a, b, (a-b));
    break;
case 3:
    printf("The Product of %.2f and %.2f is : %.2f", a, b, (a*b));
    break;
case 4:
    if (b != 0)
        printf("The Quotient of %.2f and %.2f is : %.2f",a, b, (a/b));
    else
        fputs("Error, divide by zero not possible.\n", stderr);
    break;
default:
    fprintf(stderr, "Error, Invalid choice %c\n", c);
    break;
}

Many people disagree, so you're certainly not under an obligation to do that.


Q: docker push doesn't use the correct repository and fails I'm trying to push a docker image to an Azure container repository and even after successfully "logging in" the push command tries to push it to docker.io and then fails.

Note: I am using Windows 10 Pro and have set up docker to to use the minikube docker dameon

How do I tell docker push to use my Azure container repo?
See the output:

A: You must tag your image with the Docker Registry URL and then push like this:
docker tag design-service dockerregistry.azurecr.io/design-service
docker push dockerregistry.azurecr.io/design-service

Note: The correct term is registry and not repository.  A Docker registry holds repositories of tagged images.


Q: Custom DetailView like function returns the same set of data - Django I have a view with a list of items and want to create a  detail view of those items so i can update, enable or disable items, the problem I have is I always get the same set of data no matter what item I click on to get the details of.
I've posted this here multiple times now but never had an answer, maybe I am failing to explain my issue.
View that handles the details
def detalle_Items(request, pk):
    model = Transaccion
    template_name = 'inventario/carrito/test-template.html'
    try:

        items_update = Transaccion.objects.filter(activo=True, carrito_id=pk, herramienta_id=pk)
    except Transaccion.DoesNotExist:
        raise Http404()

    return render(request, template_name, {'items_update':items_update})

This is where the function gets trigerred  by the green "actualizar" button

No matter what button I press this is what I get:

This is my views.py set of functions for carrito:
# =========================================================================== #
#   LOGICA PARA CREAR CARRITOS
# =========================================================================== #
# ===================> Logica relacinado con Cortadores <=====================#

def home_carrito(request):
    template_name = 'inventario/carrito/createcarrito.html'
    model  = Carritos

    carritos = Carritos.objects.all()
    if carritos:
        return render(request, template_name, {'carritos':carritos})
    else:
        return render(request,template_name)

class CarritoCreate(CreateView):
    model = Carritos
    fields = [
        'no_carrito',
        'empleado',
        'activo',
    ]

class ItemCreate(CreateView):
    model = Transaccion
    fields = [
        'carrito',
        'herramienta',
    ]

def detalle_carrito(request, pk):
    model = Carritos, Transaccion
    template_name = 'inventario/carrito/detalles_carrito.html'

    carritos = Carritos.objects.filter(pk=pk)
    # GEST ALL TOOLS ASSIGN TO CARRITO'S PK THAT ARE ACTIVE
    # TRY TO GET ALL ACTIVE ITEMS THAT BELONG TO CARRITO = PK AND AGREGATE TOTAL ITEMS PER TYPE
    cantidades = Transaccion.objects.values('herramienta__description').annotate(Sum('cantidad')).filter(activo=True, carrito_id=pk)

    # GEST ALL TOOLS ASSIGN TO CARRITO'S PK THAT ARE NOT ACTIVE
    eliminados = Transaccion.objects.filter(activo=False,carrito_id=pk)

    return render(request,template_name, {'carrito':carritos, 'trans':cantidades, 'eliminados':eliminados})

class CarritoUpdate(UpdateView):
    model = Carritos
    fields = [
        'no_carrito',
        'empleado',
        'activo',
    ]
    template_name_suffix = '_update_form'

def detalle_Items(request, pk):
    model = Transaccion
    template_name = 'inventario/carrito/test-template.html'
    try:

        items_update = Transaccion.objects.filter(activo=True, carrito_id=pk, herramienta_id=pk)
    except Transaccion.DoesNotExist:
        raise Http404()

    return render(request, template_name, {'items_update':items_update})

class ItemUpdate(UpdateView):
    model = Transaccion
    fields = [
        'carrito',
        'herramienta',
        'cantidad',
        'tipo',
        'motivo',
        'activo',
    ]
    template_name_suffix = '_update_form'

class ItemDelete(DeleteView):
    model = Transaccion
    success_url = reverse_lazy('item-herramienta')

And these are my models.py for carritos:
# =========================================================================== #
#   MODELO PARA CREAR CARRITOS
# =========================================================================== #

class Carritos(models.Model):
    no_carrito = models.CharField(max_length=3, unique=True)
    empleado = models.OneToOneField(Empleados, on_delete=models.CASCADE)
    # empleado = models.ManyToManyField(Empleados,  through='Transaccion')
    items = models.ManyToManyField(Item, through='Transaccion', related_name='carritos')
    f_creacion = models.DateTimeField(auto_now_add=True)
    f_actualizacion = models.DateTimeField(auto_now=True)
    activo = models.BooleanField(default=True)

    def get_absolute_url(self):
        return reverse('inventario:carrito')#, kwargs={'pk': self.pk})

    class Meta:
        verbose_name_plural = "Carritos"

    def __str__(self):
        return self.no_carrito

class Transaccion(models.Model):

    carrito = models.ForeignKey(Carritos, on_delete=models.CASCADE, related_name='items_carrito')
    herramienta = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='items_carrito')
    cantidad = models.PositiveSmallIntegerField(default=1)
    activo = models.BooleanField(default=True)
    tipo = models.CharField(max_length=10, choices=CONSUMIBLE, blank=True, null=True)
    motivo = models.CharField(max_length=10, blank=True, null=True)

    def get_absolute_url(self):
        return reverse('inventario:carrito')#, kwargs={'pk': self.pk})

Template for image #1
{% extends "inventario/base.html" %}

    {% block lista %}

                {% if carrito %}
                    {% for c  in carrito %}

Carrito:

{{c.no_carrito}}

Asignado a:

{{c.empleado.nombre}} {{c.empleado.apellido}}

                                {% if eliminados %}

                                {% else %}

No hay elementos eliminados

                                {% endif %}

                            Ver reporte de daños

                                    Contenido de carrito
                                    cantidad
                                    actualizar

                                {% for i in trans %}

                                        {{i.herramienta__description}}
                                        {{i.cantidad__sum}}
                                        Actualizar

                                {% endfor %}

                            Agregar

                    {% endfor%}
                {% else %}

No hay articulos por vencer

                {%endif%}

    {% endblock lista%}

Template for image #2
{% extends "inventario/base.html" %}

    {% block lista %}

                    Contenido de carrito
                    cantidad
                    actualizar

                {% for i in items_update %}

                        {{i.herramienta}}
                        {{i.cantidad}}
                        Actualizar

                    {% endfor %}

    {% endblock lista%}


Q: multiple triggered subsystem + algebraic loop, initialisation problem I have a Simulink diagram which contains multiple triggered subsystem with different timestamp. In this model I also got a feedback loop inducing an algebraic loop. Therefore the signal must be initialised, in order to do that, I used a Memory block.
The problem is on the feedback loop, the value of the signal seems to be not initialised.
I believe the origin of this problem is that it is indeed initialised by the memory block for the first timestamp, however, the trigger on the next subsystem did not occur. By default, this subsytem puts its out signal value to be 0. The loop is therefore broken there.

Did someone already encounter this situation ? Any Tips ?
Thank you for your time.

A: You could add initialization blocks for your trigger values? I don't know about what SubSystem0 looks like inside, but its output could use an initialization block as well, this way you guarantee that you have an input to Subsystem


Q: Should Job/Step/Reader/Writer all be bean? As fars as all the examples from the Spring Batch reference doc , I see that those objects like job/step/reader/writer are all marked as @bean, like the following:
@Bean
public Job footballJob() {
    return this.jobBuilderFactory.get("footballJob")
                     .listener(sampleListener())
                     ...
                     .build();
}

@Bean
public Step sampleStep(PlatformTransactionManager transactionManager) {
    return this.stepBuilderFactory.get("sampleStep")
                .transactionManager(transactionManager)
                .<String, String>chunk(10)
                .reader(itemReader())
                .writer(itemWriter())
                .build();
}

I have a scenario that the server side will receive requests and run job concurrently(different job names or same job name with different jobparameters). The usage is to new a job object(including steps/reader/writers) in concurrent threads, so I propabaly will not state the job method as @bean and new a job each time.
And there is actually a differenence on how to transmit parameters to object like reader. If using @bean , parameters must be put in e.g. JobParameters to be late binding into object using @StepScope, like the following example:
@StepScope
@Bean
public FlatFileItemReader flatFileItemReader(@Value(
"#{jobParameters['input.file.name']}") String name) {
return new FlatFileItemReaderBuilder<Foo>()
.name("flatFileItemReader")
.resource(new FileSystemResource(name))
}

If not using @bean , I can just transmit parameter directly with no need to put data into JobParameter,like the following
public FlatFileItemReader flatFileItemReader(String name) {
return new FlatFileItemReaderBuilder<Foo>()
.name("flatFileItemReader")
.resource(new FileSystemResource(name))
}

Simple test shows that no @bean works. But I want to confirm formally:
1、 Is using @bean at job/step/reader/writer mandatory or not ?
2、 if it is not mandatory, when I new a object like reader, do I need to call afterPropertiesSet() manually?
Thanks!

A:
1、 Is using @bean at job/step/reader/writer mandatory or not ?

No, it is not mandatory to declare batch artefacts as beans. But you would want to at least declare the Job as a bean to  benefit from Spring's dependency injection (like injecting the job repository reference into the job, etc) and be able to do something like:
ApplicationContext context = new AnnotationConfigApplicationContext(MyJobConfig.class);
Job job = context.getBean(Job.class);
JobLauncher jobLauncher = context.getBean(JobLauncher.class);
jobLauncher.run(job, new JobParameters());

2、 if it is not mandatory, when I new a object like reader, do I need to call afterPropertiesSet() manually?

I guess that by "when I new a object like reader" you mean create a new instance manually. In this case yes, if the object is not managed by Spring, you need to call that method yourself. If the object is declared as a bean, Spring will call
the afterPropertiesSet() method automatically. Here is a quick sample:
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class TestAfterPropertiesSet {

    @Bean
    public MyBean myBean() {
        return new MyBean();
    }

    public static void main(String[] args) throws Exception {
        ApplicationContext context = new AnnotationConfigApplicationContext(TestAfterPropertiesSet.class);
        MyBean myBean = context.getBean(MyBean.class);
        myBean.sayHello();
    }

    static class MyBean implements InitializingBean {
        @Override
        public void afterPropertiesSet() throws Exception {
            System.out.println("MyBean.afterPropertiesSet");
        }

        public void sayHello() {
            System.out.println("Hello");
        }
    }

}

This prints:
MyBean.afterPropertiesSet
Hello


Q: Four-dimensionalism vs energy economy Four-dimensionalism claims that the universe is basically one huge space-time worm and that everything exists at once (however you want to say that since "internal time" is then just another coordinate in this worm and I'm talking about the look from the outside).
OTOH, all processes in the universe seem to follow an energy economic principle (second law of thermodynamics), that is, everything tries to reach a state of lowest energy.
Now I'm wondering if that isn't enough to refute the idea of 4D-ism: For it to be the correct theory about space-time, you'd need a lot more matter (at least) because every point in time must be materialized as a "solid" state. That means for everything can happen within what we perceive as "one second", one state must be encoded.
Quantum processes happen at attoseconds (10^-18s), so you need at least 10^18 states just to encode one second of the 4D worm.
So my argument is that, just to prove the theory, you're "wasting" insane amounts of whatever the universe is made of.
Is that correct or am I missing something?
NOTE: English is not my mother language, so I may have use the wrong terms but I hope you get the idea.

A: In both cases you need a very large infinity of states to describe the universe. Whether you treat time as a special coordinate, and thus use standard mechanics with trajectories, velocities etc., or if you treat time as just one of the four coordinates in a special four dimensional manifold, these coordinates are assumed to vary continuously.
The difference between the two representations are the following:

*

*In 3d you have the concept of a place, and of a time-evolution; in 4d you have the concept of an event, or series of events.

*In 3d time and space are absolute, in 4d are bound to an observer and freely mix, in general relativity they are curved, even absolutely (e.g. the whole universe might not be flat).

*In 3d you have one "copy" of matter that evolves through time; in 4d you have one "copy" of matter as well, which "lives" along a 4d curve, describing its position at each time (depending on the observer).

So, both theories are just as economical.
Now, you may be interested by the many-world hypothesis. That theory is much more expensive as a (at least partial) copy of the universe is created each time a measurement is made. However, though, nothing changes - energy only tends to settle to local minima and not necessarily absolute ones: each copy of the universe has then its minima to tend to, and nothing is out of place.


Q: Android ViewPager2 FragmentStateAdapter shows Menu from every Fragment i have an activity with bottom navigation view with 3 Fragments associated.
One of them is a Fragment with a ViewPager2 that uses a  FragmentStateAdapter.
Inside the createfragment(int position) method of the Adapter I return a couple Instances of another Fragment which has an Options Menu and inside it's onCreate() i call setHasOptionsMenu(true).
The Problem is that on initialization of the adapter, the menu from all fragments are visible not just the menu of the currently visible fragment.
After the first swipe it seems that the menu gets invalidated and everything is as it should be.
The problem also occurs if i notify the adapter about changes that another fragment is added, then another menu item appears for the newly added fragment.
I saw a similar question but the answer was to call setHasOptionsMenu() inside the onResume() method of the fragment but that doesn't seem to be the right behavior to handle this. In a comment another user suggested to upgrade ViewPager2 to another version but I am using the latest version.
Can anybody tell me how to handle this?

A: I joined StackOverflow just to reply to this question as I've also wasted time on this exact issue.
The fix is to update to the latest alpha01 version of ViewPager2.
implementation "androidx.viewpager2:viewpager2:1.1.0-alpha01"

See: https://developer.android.com/jetpack/androidx/releases/viewpager2#1.1.0-alpha01

Fixed FragmentStateAdapter issue with initial fragment menu visibility when adding a fragment to the FragmentManager. (I9d2ff, b/144442240)

A: I tried updating to the latest viewpager2 alpha as suggested in the currently accepted answer, but it didn't help.
I have seen answers to similar questions where they say to clear the entire menu first. That should work, too, but I have some menu items that are loaded in the Activity, which do not duplicate, and some that load in the fragment, which do duplicate. I want to keep the ones inflated in the Activity and remove only all the ones from all fragments (not just the current fragment, just in case).
My work-around, therefore, is to each time remove only the items added in all fragments, checking to make sure each is actually there (not null) before removing each one. Then, once those have been removed, I inflate the menu(s) needed for all/each fragment.
Note that the existing menu is removed item by item (R.id...) while the inflated one is added by menu (R.menu...) as usual.
In the below sample, the search menu will always be inflated, while the second menu to be inflated will depend on which fragment it currently active.
    @Override public void onCreateOptionsMenu (@NonNull Menu menu, @NonNull MenuInflater
        inflater)
{
    super.onCreateOptionsMenu (menu, inflater);

    removeMenuItemIfPresent (menu, R.id.menu_search);
    removeMenuItemIfPresent (menu, R.id.menu_sample_filter1);
    removeMenuItemIfPresent (menu, R.id.menu_sample_filter2);

    inflater.inflate (R.menu.menu_search_menu, menu);
    inflater.inflate (mCurrentSection == 0 ? R.menu.menu_frag0 : R.menu.menu_frag1, menu);
}

private void removeMenuItemIfPresent (@NonNull Menu menu, int resourceIDToRemove)
{
        MenuItem menuItemToRemove = menu.findItem (resourceIDToRemove);

        if (menuItemToRemove != null) {
            menu.removeItem (menuItemToRemove.getItemId ());
    }
}

A: I am not sure if it worked before but now im having issues with ViewPager2. When, I add fragments, each with different menuitems, the menuitem does not reflect on the first fragment added.
It works when offscreenpagelimit is not set. However, its performance is bad. Didnt have issues with ViewPager.


Q: Riverpod: How to read provider after async gap I am trying to build a simple login screen. For this I have set up a StateProvider to indicate whether to show a loading indicator:
final loginIsLoadingProvider = StateProvider<bool>((ref) => false);

When a button is pressed I call the following function:
void logInUser(WidgetRef ref) async {
    ref.read(loginIsLoadingProvider.notifier).state = true;
    await Future.delayed(1.seconds); //login logic etc.
    ref.read(loginIsLoadingProvider.notifier).state = false; //Exception
return;

But calling ref.read(...) after awaiting the future throws the following exception:

FlutterError (Looking up a deactivated widget's ancestor is unsafe. At this point the state of the widget's element tree is no longer stable. To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.)

Why cant I call ref.read() after an async gap? Is there any way to do this?

A: A solution is to read your providers before the async gap, but not use them immediately.
For example:
Future<void> logInUser(WidgetRef ref) async {
  final isLoadingNotifier = ref.read(loginIsLoadingProvider.notifier);
  isLoadingNotifier.state = true;

  await someAsyncOperation();

  isLoadingNotifier.state = false;
}


Q: How to Calculate statistics PDR, Delay ,Broadcast Success rate For Protocol works in Phy Layer ,Link Layer using OMNET 5.0,VEINS 4.4? What are The Programming instructions that can be written in omnet.ini file or .ned file for calculating the statistics Packet Delivery Ratio, Delay ,Broadcast Success rate For Protocol works in Physical Layer ,Link Layer using OMNET 5.0 ,VEINS 4.4???
Please reply ...


Q: Printing a generator in python tensor flow I am trying to follow the tensor flow tutorial as described in this link
I am trying to print the predicted result as described :
print ("Predicted %d, Label: %d" % (classifier.predict(test_data[0]), test_labels[0]))

But I am not able to print the result. I am getting the following error.
    print ("Predicted %d, Label: %d" % (classifier.predict(test_data[0]), test_labels[0]))
TypeError: %d format: a number is required, not generator

How do I print the generator in python.
I tried to write a loop and iterate over the elements it didn't work and I tried to use next to print the generator. That also didn't work. How do I print it ?

A: This is how I solved it
new_samples = np.array([test_data[8]], dtype=float)

y = list(classifier.predict(new_samples, as_iterable=True))
print('Predictions: {}'.format(str(y)))

print ("Predicted %s, Label: %d" % (str(y), test_labels[8]))

A: No tensorflow here, so let's mock up a generator and test it against your print expression
In [11]: def predict(a, b):
    ...:     for i in range(10):
    ...:         yield i, i*i
    ...:

In [12]: print('a:%d, b:%d'%(predict(0, 0)))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-29ec761936ef> in <module>()
----> 1 print('a:%d, b:%d'%(predict(0, 0)))

TypeError: %d format: a number is required, not generator

So far, so good: I have the same problem that you've experienced.
The problem is, of course, that what you get when you call a generator function are not values but a generator object...
You have to iterate on the generator objects, using whatever is returned from each iteration, e.g.,
In [13]: print('\n'.join('a:%d, b:%d'%(i,j) for i, j in predict(0,0)))
a:0, b:0
a:1, b:1
a:2, b:4
a:3, b:9
a:4, b:16
a:5, b:25
a:6, b:36
a:7, b:49
a:8, b:64
a:9, b:81

or, if you don't like one-liners,
In [14]: for i, j in predict(0, 0):
    ...:     print('a:%d, b:%d'%(i,j))
    ...:
a:0, b:0
a:1, b:1
a:2, b:4
a:3, b:9
a:4, b:16
a:5, b:25
a:6, b:36
a:7, b:49
a:8, b:64
a:9, b:81

In other words, you have to explicitly consume what the generator is producing.

A: From the documentation:

Runs inference to determine the class probability predictions.
  (deprecated arguments)
SOME ARGUMENTS ARE DEPRECATED. They will be removed after 2016-09-15.
  Instructions for updating: The default behavior of predict() is
  changing. The default value for as_iterable will change to True, and
  then the flag will be removed altogether. The behavior of this flag is
  described below.

Try:
classifier.predict(x=test_data[0])


Q: task shedule, sharing form label variable I am writting some easy program in Java FX. I am begginer in Java.
I would like make,
You fill textbox (time in minutes) and run it.
And than it run timer.schedule that it will every minute refresh label with time. Something like stopwatch.
(You set time whitch you want remember time).
I have Controller
public class Controller implements Initializable  {

    @FXML
    public Label label;

    @FXML
   private TextField timeEnd;
    .
    .

And method onClick
@FXML
private void handleButtonAction(ActionEvent event) {
    Integer timeEndVal = Integer.parseInt(timeEnd.getText());
    Date startDate = new Date();
    Date endDate = new Date();
    endDate.setTime(startDate.getTime() + (timeEndVal * 60000));

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {

        @Override
        public void run() {
            long currentMinutes = currentTime().getTime() - startDate.getTime();

            System.out.println(currentMinutes / 60000 + " / " + timeEndVal + " min");
            label.setText(String.valueOf(currentMinutes / 60000 + " / " + timeEndVal + " min"));

        }
    }, 0, 60000);

But I don't know, how I get label variable to timer.schedule.
What I do wrong. Thank for helping.

A: Here is a non Controller version that you can use to get some ideas from. I suggest you use TimeLine instead of Timer. This is not a complete program!
import java.util.concurrent.atomic.AtomicInteger;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Duration;

/**
 *
 * @author blj0011
 */
public class JavaFXApplication267 extends Application
{

    @Override
    public void start(Stage primaryStage)
    {
        AtomicInteger timeInSeconds = new AtomicInteger();
        TextField textField = new TextField();
        Label label = new Label(Integer.toString(timeInSeconds.get()));
        Button btn = new Button("Play");

        textField.setPromptText("Enter the number of minutes");
        textField.textProperty().addListener((obs, oldValue, newValue) -> {
            //This assume the input is corret!
            timeInSeconds.set(Integer.parseInt(newValue) * 60);//Number of minutes times 60 seconds
            label.setText(getMinsSeconds(timeInSeconds.get()));
        });

        Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1), (event) -> {
            if (timeInSeconds.get() > 0) {
                label.setText(getMinsSeconds(timeInSeconds.decrementAndGet()));
            }
        }));
        timeline.setCycleCount(Timeline.INDEFINITE);

        btn.setOnAction((ActionEvent event) -> {
            switch (btn.getText()) {
                case "Play":
                    timeline.play();
                    btn.setText("Pause");
                    textField.setEditable(false);
                    break;
                case "Pause":
                    timeline.pause();
                    btn.setText("Play");
                    textField.setEditable(true);
                    break;
            }
        });

        VBox root = new VBox(label, btn, textField);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        launch(args);
    }

    String getMinsSeconds(int seconds)
    {
        return String.format("%02d:%02d", (seconds / 60), (seconds % 60));
    }
}


Q: Different themes for different languages in Visual Studio Code I've tried searching for the answer to this but am coming up blank.
In sublime text, it's possible to have different themes for different file types as specified in the preferences file. For example, you can have a light coloured theme for Markdown/Plain text files and a normal Monokai type theme for all other languages. I find this very useful as I prefer to have different fonts and settings when typing compared to when coding.
As far as I can see, this functionality isn't present in VSCode. Am I wrong or is there a way to achieve the above?

A: You are right, there is no way to do that.
You can however, define different themes (color and icon) for each workspace (Preferences: Open Workspace Settings). It's not exactly what you are looking for, but it may be useful if your different languages are located/related in different workspaces.

A: It's now possible to do using an extension called "Theme by language" from Julien Saulou. It can be downloaded from Visual Studio Code Marketplace.


Q: Spring Data Rest: Null Pointer If-Modified-Since Header Present and Resource Not Auditable If a Client makes a request for a Resource and specifies the If-Modified-Since header when the mapped Entity does not have any of the Spring Data JPA auditing annotations (@CreatedBy, @LastModifiedBy, @CreatedDate, @LastModifiedDate ) then this appears to result in a null-pointer exception in the class org.springframework.data.rest.webmvc.HttpHeadersPreparer:
public boolean isObjectStillValid(Object source, HttpHeaders headers) {

    Assert.notNull(source, "Source object must not be null!");
    Assert.notNull(headers, "HttpHeaders must not be null!");

    if (headers.getIfModifiedSince() == -1) {
        return false;
    }

    //THE WRAPPER IS NULL IF NO AUDITING ANNOTATIONS PRESENT
    AuditableBeanWrapper wrapper = auditableBeanWrapperFactory.getBeanWrapperFor(source);
    long current = wrapper.getLastModifiedDate().getTimeInMillis() / 1000 * 1000;

    return current <= headers.getIfModifiedSince();
}

Is this a bug and, short of adding a field to the Entity to prevent this, is there any other workround.

A: If fetching the entity doesn't emit a Last-Modified header, then I would say this is a bug in the client, not SDR.
If none of your entities support Last-Modified, maybe create a filter that strips If-Modified-Since from the request or catches it early and responds appropriately.
All of that said, I also don't think a NPE is acceptable and a SDR bug should be filed.


Q: hide the name of app in windows task manager
Possible Duplicate:
Hide a C# program from the task manager?

Hi.
I write WinForms app and i want to hide my app name in this place windows Task Manager>>Applications .how can hide when i run my app??
thanks.

A: The application name that Task Manager shows is the Window text of the taskbar window. If you want to hide it you'll just have to set that text to an empty string.
If a blank string is no good, and you don't want your app to appear in the list at all, then don't register a taskbar button.
If you don't want your app to appear in the process list, then don't start it.


Q: VB.Net Listview Groups I am new here and come up with my first question:
I have a listview with some groups, every groups has some items.
I added a ContextMenuStrip to the Listview, and when I rightclick on the selected item, I like to get the Name of the Group which it belongs to.
Can someone help me how to do this?
If LV1.SelectedItems(0).Text = LV1.Groups(0).ToString Then
    MsgBox("Hi")
End If

A: Get LV group name for the item the mouse is down over:
Private thisGroupName As String = ""

Private Sub MouseDown(sender, e As MouseEventArgs)...
    If e.Button = MouseButtons.Right Then
        thisGroupName = GetLVGroupAt(e.X, e.Y)
    End If
End Sub

Private Function GetLVGroupAt(X As Integer, Y as Integer) As String
    Dim theGrp As String = ""

    Dim ht As ListViewHitTestInfo = myLV.HitTest(X, Y)
    ' the mouse might be down over a NON item area, like a blank "row"
    ' AND if the items does not belong to a Group, 'Group' will
    ' be Nothing:
    If (ht.Item IsNot Nothing) AndAlso (ht.Item IsNot Nothing) Then
         theGrp = ht.Item.Group.Name
    End If

    Return theGrp
End Function

Evaluating the Group name is left for the consuming code.