text:
Q: Woocommerce include custom dimension into $product class Situation: A Woocommerce product object typically holds an array dimensions with raw x y z values.
$product = [
  'dimensions' => [
    'length' => 1,
    'width' => 1,
    'height' => 1
  ],
  'dimensions_html' => '1 x 1 x 1 cm',
  ...

Using "Additional custom dimensions for products in Woocommerce" answer code, I created 3 new custom dimensions (depth, diameter, seat-height)…
Problem: I want to add these properties to the product class so they are directly available everywhere like:
$product = [
  'dimensions' => [
    'length' => 1,
    'width' => 1,
    'height' => 1,
    'depth' => 1,
    'diameter' => 1,
    'seat-height' => 1
  ],
  'dimensions_html' => '1 x 1 x 1 x 1 x 1 x 1 cm',
  ...

How can this be done?

A: I worked around and manipulated the dimensions_html instead to include all necessary dimensions. This is not a elegant or universal solution, but works for me right now.
// functions.php
add_filter( 'woocommerce_format_dimensions', 'change_formated_product_dimentions', 10, 2 );
function change_formated_product_dimentions( $dimension_string, $dimensions ){
    global $product;
    $cm = get_option( 'woocommerce_dimension_unit' );

    $html = '';

    if( $dimensions['length'] ){
        $html .= 'Length '.$dimensions['length'].' '.$cm.'';
    }

    if( $dimensions['width'] ){
        $html .= 'Width '.$dimensions['width'].' '.$cm.'';
    }

    if( $dimensions['height'] ){
        $html .= 'Height '.$dimensions['height'].' '.$cm.'';
    }

    $depth = $product->get_meta( '_depth' );
    if( $depth ){
        $html .= 'Depth '.$depth.' '.$cm.'';
    }

    $diameter = $product->get_meta( '_diameter' );
    if( $diameter ){
        $html .= 'Diameter '.$diameter.' '.$cm.'';
    }

    $seat_height = $product->get_meta( '_seat_height' );
    if( $seat ){
        $html .= 'Seat height '.$seat_height.' '.$cm.'';
    }

    return $html;
}

This is now included in $product['dimensions_html'] and, when echoed results in
Length 1 cm
  Width 1 cm
  Height 1 cm
  Depth 1 cm
  Diameter 1 cm
  Seat height 1 cm
and which (almost) just what I wanted.


text:
Q: Drawing circles in custom UIView I have a custom UIView with drawRect:
-(void)drawRect:(CGRect)rect{

CGContextRef context = UIGraphicsGetCurrentContext();
[self drawControlPointsWithCoordsX:point.x andY:point.y forRect:CGRectMake(0, 0, 320, 600) andContext:context];
NSLog(@"Values: %f and %f", point.x, point.y);

static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    [self  startTimer];
});
}

[self  startTimer]; is the initiation method. In this method I start a timer which produces some pairs of ordinates. It is called only once. The coordinates come in this form:
Values: 276.711670 and 117.279999
and keep changing all the time. All the values are logged. In the method which is repeated by the timer every 0.1s I call:
[self drawRect:CGRectMake(0, 0, 320, 600)];

The log works, and the coordinates keep changing, and are correct, but only two or three dots are plotted (instead of more or less 400) and they are in the wrong place.
This is the code to draw the points:
- (void)drawControlPointsWithCoordsX:(int)x andY:(int)y forRect:(CGRect)rect andContext:(CGContextRef)contextRef
{
UIGraphicsPushContext(contextRef);
CGContextSetLineWidth(contextRef, 2.0);
CGContextSetRGBFillColor(contextRef, 0, 0, 1.0, 1.0);
CGContextSetRGBStrokeColor(contextRef, 0, 0, 1.0, 1.0);
CGRect circlePoint = (CGRectMake(x,y, 5.0, 5.0));

CGContextFillEllipseInRect(contextRef, circlePoint);
}

A: First, you should not be manually calling drawRect:, because it gets called automatically when the view is told to be redrawn. So if you choose to redraw it manually like this, the behavior is probably undefined because what the current graphics context is might be different or not valid. The following is taken from Apple's documentation on the drawRect: method:

This method is called when a view is first displayed or when an event occurs that invalidates a visible part of the view. You should never call this method directly yourself. To invalidate part of your view, and thus cause that portion to be redrawn, call the setNeedsDisplay or setNeedsDisplayInRect: method instead.

Also you should probably not be starting a timer running from within drawRect:. You should probably be starting your timer from somewhere else, like somewhere in your code where you first display this view. Also each time you redraw the view, it is clearing out what was previously there, not overlaying it. So if you expect this to build on what was previously drawn, you must keep track of every point that you draw and redraw all of them up to the current point. You could accomplish this in other ways that wouldn't involve redrawing what you've already drawn, but it would be more complicated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: On the structure of a finite group of order $144$ Let $G$ be a finite group of order $144$. Suppose there is an irreducible $\mathbb{C}$-character $\theta$ such that $\theta(1)=9$.

QUESTION: Prove $G\cong A_4\times A_4$.

By using Magma, we know there is only one group of order $144$ with an irreducible $\mathbb{C}$-character $\theta$ of degree $9$. Now I want to prove this result without using Magma.

A: Since $G$ has an irreducible character of degree $9 = |G|_{3},$ we have $O_{3}(G) = 1,$ so $G$ has more than one Sylow $3$-subgroup. If $G$ has only $4$ Sylow $3$-subgroups, then $G$ has a normal subgroup of order divisible by $6$ with a normal Sylow  $3$-subgroup ( consider the permutation action of $G$ on $N_{G}(S)$ for $S \in {\rm Syl}_{3}(G)$ in the case $[G:N_{G}(S)] = 4.$ The image in $S_{4}$ has order dividing $24,$ so the kernel of the action  has order divisible by $6$, and (being a subgroup of $N_{G}(S)$) has a normal Sylow $3$-subgroup, which remains normal in $G$, contrary to $O_{3}(G) = 1).$
Hence $G$ does indeed have $16$ Sylow $3$-subgroups, and a self-normalizing Sylow $3$-subgroup. By Burnside's normal $p$-complement theorem, $G$ has normal $3$-complement of order $16.$ In particular, $G$ is solvable (we could also see this from Burnside's $p^{a}q^{b}$-theorem, but that seems like overkill).
Let $Q = O_{2}(G),$ which is a Sylow $2$-subgroup of $G.$ Since $O_{3}(G) =1,$ we have $Q = F(G).$ Now $G/Q$ acts faithfully as a group of linear transformations on $Q/\Phi(Q),$ so that $G/Q$ is isomorphic to a subgroup of ${\rm GL}(m,2)$ for some $m \leq 4.$ Since $[G:Q]$ is divisible by $9,$ we must have $m =4,$ and $Q$ is elementary Abelian. Since $GL(4,2)$ contains no element of order $9,$ we see that $G/Q$ is elementary Abelian of order $9.$ Further, the action of a Sylow $3$-subgroup of $GL(4,2)$ on the natural module gives the desired structure for $G.$


text:
Q: Derivation of Euler-Lagrange equation Here is  a simple (probably trivial) step in the derivation of the Euler-Lagrange equation.
    If we denote $Y(x) = y(x) + \epsilon \eta(x) $, I want to know why is
$\dfrac{\partial f(Y,x)}{\partial Y} \Big\vert_{\epsilon = 0} = \dfrac{\partial f(y,x)}{\partial y} $
Could someone justify the  steps involved in justifying this ? I am sure am missing something elementary.
EDIT: Could someone comment on correctness of the 'proof ' ?
    $\dfrac{\partial f(Y,x)}{\partial Y} \Big\vert_{\epsilon = 0} = \lim_{H\rightarrow 0} \dfrac{f(y + \epsilon \eta  + H,x) -f(y + \epsilon \eta,x)}{H} \Big\vert_{\epsilon = 0} = \lim_{H\rightarrow 0} \dfrac{f(y + H,x) -f(y,x)}{H} = \dfrac{\partial f(y,x)}{\partial y} $
EDIT 2:
The answers provided still leave me confused. Here is another attempt at a "proof".
$\dfrac{\partial f(Y,x)}{\partial Y} \Big\vert_{\epsilon = 0} = \lim_{\epsilon\rightarrow 0} \dfrac{\partial f(Y,x)}{\partial Y} = \lim_{\epsilon \rightarrow 0} \left(\lim_{H\rightarrow 0} \dfrac{f(y + \epsilon \eta  + H,x) -f(y + \epsilon \eta,x)}{H} \right)$
Now if I could interchange the limits, then it would make sense that I get
  $\lim_{H\rightarrow 0}  \dfrac{f(y + H,x) -f(y,x)}{H} = \dfrac{\partial f(y,x)}{\partial y} $.
So is the interchange of limits allowed. What hypothesis must be satisfied for that to happen ?

A: This Confusion with Euler-Lagrange Derivation was basically what convinced me that it was all a muddle with symbols and notation.  Just for the benefit of future readers, I write it down in my own words.
So, the notation $ \dfrac{d f}{dx}\Big|_{x = x^*}$ basically means derivative of the function $f(\cdot)$ with respect to its argument, and then evaluation of the result when the argument is set to $x^*$.
Exactly the same reasoning is involved in the question, for we take  the partial derivative  with respect to $Y$ and the result is evaluated at $\epsilon =0$.
But evaluation of the result at $\epsilon =0$ is equivalent to
$ \dfrac{\partial f(Y, x)}{\partial Y}\Big|_{Y = y}$ which looks silly, but it is blindingly obvious to me now that
$ \dfrac{\partial f(Y, x)}{\partial Y}\Big|_{\epsilon = 0} = \dfrac{\partial f(Y, x)}{\partial Y}\Big|_{Y = y} = \dfrac{\partial f(y, x)}{\partial y}$

A: The formula for $\frac{\partial f(Y,x)}{\partial Y}|_{\epsilon=0}$ is not correct: you should write
$$\frac{\partial f(Y,x)}{\partial Y}|_{\epsilon=0}:=
\lim_{\epsilon\rightarrow 0}\frac{
f(y+\epsilon\eta,x)-f(y,x)}{\epsilon}=
\lim_{\epsilon\rightarrow 0}\frac{
\langle \nabla f(y,x),h_\epsilon\rangle+O(\|h\|^2)}{\epsilon},
$$
where we suppose that $f$ is differentiable at $(y(x)+\epsilon\eta(x),x)$ for all $x$, denoting by $h_\epsilon$ the increment
$$h_\epsilon=( \epsilon\eta(x), 0)$$
and by $\nabla f(y,x)=\left(\frac{\partial f}{\partial y},\frac{\partial f}{\partial x}\right)$ the gradient of $f$ at $(y(x),x)$.
Then
$$\frac{\partial f(Y,x)}{\partial Y}|_{\epsilon=0}=
\lim_{\epsilon\rightarrow 0}\frac{\frac{\partial f}{\partial y}\epsilon\eta(x)
+O(\epsilon^2)}{\epsilon}=\frac{\partial f}{\partial y}(y(x),x)\eta(x),
$$
as claimed (for all small variations $\eta(x)$).
What we are missing here are the boundary conditions on the increment $\eta$ of $y$ in order to talk about a "variational problem" and the explicit form of the functional $f$.


text:
Q: Create connection in Airflow Docker using entrypoint.sh I am working on creating local dev environment for Airflow using Docker. I have setup most of the things but not able to create connection automatically in airflow.  I can bash into the docker container and run my command by following steps:

*

*docker exec -it jdf90dfusiodfsocontainerid /bin/sh

*airflow connections add 'my_con_id'  --conn-uri 'SSH://myuser@255.255.255.255:22'
I tried to automate it by adding a run command in Dockerfile as below:
RUN ["/bin/bash", "-c", "airflow connections add 'my_con_id'  --conn-uri 'SSH://myuser@255.255.255.255:22'"]
This throws error and that makes me think that this statement run before I made some necessary adjustment of variable in docker-compose and airflow.cfg files. So now my goal is to run the airflow connections command after all setup commands has run. I tried putting this command airflow connections add 'my_con_id'  --conn-uri 'SSH://myuser@255.255.255.255:22'in entrypoint.sh but it is not running. I also tried to echo some statements from entrypoint.sh but none of those statements are getting printed in my terminal. Am I doing something wrong here?
here is a entrypoint.sh that I am following: Any other way to create airflow connection in docker is also welcome.
https://github.com/aws/aws-mwaa-local-runner/blob/main/docker/script/entrypoint.sh


text:
Q: ERROR running force:package:version:create An object 'My Profine' of type Profile was named in package.xml, but was not found in zipped directory Hi all after updated sfdx to version 7.72.0 when I try to create the unlocked package - it fails with the error:
ERROR running force:package:version:create:  An error occurred while trying to install a package dependency, ID 04t3u000002znQE: Admin: An object 'Admin' of type Profile was named in package.xml, but was not found in zipped directory.
NOTE: It was working without any problems with version 7.71.0

A: I was having same problem, I ran sfdx update and it bumped to 7.73 and my error went away. Salesforce must have just fixed the bug.

A: I faced similar issue like you.
To resolve that wse the latest version: 7.73.2-feef087df8 of sfdx with the command sfdx update.
It works


text:
Q: Show  border in html only when there's a data in HTML using jQuery or Javascript? I have a table like this in HTML:

            Tag
            Time Code

            {{ choice.tag1 }}
            {{ choice.time_code1 }}

            {{ choice.tag2 }}
            {{ choice.time_code2 }}

            {{ choice.tag3 }}
            {{ choice.time_code3 }}

            {{ choice.tag4 }}
            {{ choice.time_code4 }}

            {{ choice.tag5 }}
            {{ choice.time_code5 }}

            {{ choice.tag6 }}
            {{ choice.time_code6 }}

            {{ choice.tag7 }}
            {{ choice.time_code7 }}

            {{ choice.tag8 }}
            {{ choice.time_code8 }}

            {{ choice.tag9 }}
            {{ choice.time_code9 }}

            {{ choice.tag10 }}
            {{ choice.time_code10 }}

The variable that I passed using {{}} most of the times are empty. Even if's it empty td is shown. I don't cut off the space and don't show any td's if they are empty. For example sometimes I may have data up to 3rd td only thus I want to show only up to 3rd td. Is this possible using jQuery or JavaScript?

A: Try like
{% if(!empty{choice.time_code1 }) %}

    {{ choice.tag1 }}
    {{ choice.time_code1 }}

{% end:if %}

A: you can try this may be it will you help you:
$(document).ready(function(){
  $(".table tbody td").each(function(){
    if($(this).html()=="")
      {
       $(this).hide();
      }
   });
});

A: If you want to hide td if they are empty and entire tr if both td are empty try this:
$(function(){
  $(".table tbody tr").each(function(){
     var empty = true;
     $(this).find("td").each(function(){
        if ($(this).html()=="")
           $(this).hide();
        else
           empty = false;
     });
     if (empty){
        $(this).hide();
     }
  });
});

A: Or you could run a for loop in javascript


text:
Q: Test the real function or mock the dependency for unittest? Given the function below:
def _extract_row(self, rnumber, rcontent):
    number = rnumber.find('p').text.strip()
    p = rcontent.find('p')
    dloms = p.find_all('a')

    docs = {}
    for d in dloms:
        docs[d.text.strip()] = DOMAIN + d['href']

    ems = p.find_all('em')
    for e in ems:
        name = e.text.strip()
        if not docs.get(name):
            docs[name] = None

    ldocs = []
    for name, link in docs.iteritems():
        ldocs.append({'name': name,
                      'link': link})

    return {'number': number,
            'docs': ldocs}

where rnumber and rcontent are BS4 or Beautifulsoup objects, is it better to install BS4 as a test dependency and test the function normally or is it better to mock BS4 ?
Here is what I did:
@patch("agc_law.bs4.BeautifulSoup")
def test_law_pages_private_extract_row(self, mock_bs4):

    """Test asserting correct calls are made in _extract_row"""

    agc_law.DOMAIN = "http://example.com"
    mock_rnumber = mock_bs4
    mock_rcontent = mock_bs4

    result = self.lp._extract_row(mock_rnumber, mock_rcontent)
    for item in [call.find('p'),
                 call.find().text.strip(),
                 call.find('p'),
                 call.find().find_all('a'),
                 call.find().find_all('em')]:
        self.assertIn(item, mock_rcontent.mock_calls)

    for item in [call.find('p'),
                 call.find().text.strip(),
                 call.find('p'),
                 call.find().find_all('a'),
                 call.find().find_all('em')]:
        self.assertIn(item, mock_rnumber.mock_calls)

Would value comments.

A: Your code is rather tightly coupled with BeautifulSoup and the document being parsed. If the structure of your document changes, you'll have to refactor both your code-under-test and your test.
Furthermore, if you were to find a more efficient way of using BeautifulSoup (say, by using CSS selectors for example), you could not refactor the code-under-test without again having to alter your test completely to match.
You may as well use a real document in that case, that reflects the current structure; that way you test the outcome of your code rather than how it achieves the outcome.


text:
Q: Call 'sudo make install' from gvim I am developing a program which has a fairly standard looking Makefile like the one below.
.PHONY=default install

hello: hello.o

install: hello
    cp hello /usr/local/bin

This example Makefile builds a program called hello from a file called hello.c and has an installation rule to install it to a directory which is owned by root. This means that the install must be called with the sudo command like so:
sudo make install

Now I use gvim as a text editor and use the :make command all the time to make it. I would also like to be able to install it from the vim command, but I cannot figure out how to insert the sudo command into the :make command.
There is a workaround that I can do which is to put the sudo in the Makefile rule itself, but I feel like this is bad practice.
Does anyone know how to run a single command from within vim with elevated privileges?

A: The easiest way would be just have vim run an external command with !
:!sudo make install

Take a look at :help :!


text:
Q: How to declare a table variable in SQL Server 2012 stored procedure? I'm trying to create a stored procedure but the following problem occurs:

Msg 2715, Level 16, State 3, Procedure usp_UpatePriv, Line 1
Column, parameter, or variable #1: Cannot find data type tblScreen. Parameter
or variable '@screen' has an invalid data type.
Msg 1087, Level 16, State 1, Procedure usp_UpatePriv, Line 8
Must declare the table variable "@screen".

This is the stored procedure:
create procedure usp_UpatePriv
    @screen tblScreen Readonly
as
    declare @username nvarchar(50)
    declare @prev bit
    declare @idscreen bigint

    declare privlange cursor for
        (select username, idScren, Prev from @screen)

    open privlange

    fetch next from privlange into @username, @idscreen, @prev

    while @@FETCH_STATUS = 0
    begin
        update tblScreenPriv
        set Prev = @prev
        where Username = @username and idScreen = @idscreen

        fetch next from privlange into @username, @idscreen, @prev
    end

    close privlange;
    deallocate privlange;

A: You need to declare the Table-Valued Type, and you should get rid of the cursor.  EG:
create type tblScreen as table(username nvarchar(50), idScren int, Prev bit)
go

create proc usp_UpatePriv
 @screen  tblScreen Readonly
as
begin
        with q as
        (
          select o.Prev, n.Prev NewPrev
          tblScreenPriv o
          join @screen n
            on o.UserName = n.UserName
           and o.idScreen = n.idScreen
        )
        --select * from q
        update q set Prev = NewPrev;
end


text:
Q: PCB Layout - Design Critique Requested I was wondering if I could get some critique on my first PCB layout.
I've tried to isolate the 240V side from the 3.3V side as best as I can.
Only thing really concerning me is if I there is enough distance between my tracks on the 240V side and if the track widths are enough?
I am trying to keep the PCB as compact as possible. At the moment it measures about 46mmx39mm.

The PCB is to wirelessly control lights with a regular light switch as the input, 240V connected to the IRM-02-3.3 with the 3.3V then powering the ESP8266-01.
Got an optocoupler and Triac in there to switch the light load.
Schematic:

Thoughts and feedback greatly appreciated :)
UPDATED PCB:

A: Allowing the ESP8266 module to overhang the optoisolator violates the isolation boundary. Consider rotating the module so that it overhangs the (currently unused) space on the left of the board.
Using surface-mount resistors for pullups will save you a considerable amount of board space. (The thru-hole resistor on the HV side is fine.)
You only need to use thick traces for nets that will be carrying a lot of current. You can safely use thinner traces for the optocoupler and the voltage regulator, as neither of these should be carrying a lot of current.
Rotating the BT136 180° may allow you to move the optocoupler up and the resistor down, saving some trace length.
Adding a fuse on the line input might be a good idea.

A: Your questions seem to be:
Is the slit enough isolation?
Are the tracks separated enough?
Are the tracks substantial enough?
First, there is not an apparent safety ground on the board.  If you're using line voltages, neutral cannot be counted on to be ground.  You seem to have a push button on this board, but no Earth ground at all.  I'm all for experimentation, but this made me create a stackexchange account just to respond to-please fix this.
Your line and load connector selection is looking like it's going to be the limiting factor in how much separation you can get.  Also consider your thru-hole leads- I can't tell whether components are mounted on the red or blue side.  Consider also the addition of solder when checking your separations.  Check your board material and thickness for voltage rating also.
Regarding trace widths, you have to calculate that based on load current drawn and copper thickness (weight) on the PCB.
I would recommend you research how much separation is actually needed, use a PCB software package that has conductor to conductor separation design rules, and set them to that value, so you can determine if you have any violations.  Add safety ground, and please be careful.

A: Normally a board house can do slot cuts as narrow as 31 mils or 2mm. Your slot cut need not be wider than that, but it should extend to the purple line which I assume is your 50 mil perimeter clearance.
This way you isolate R2 from R1 in terms of creapage. 240 VAC is not that high, but even with 600 VAC (Canada) a slot cut kills any chance of creapage or creapage plus arcing.
Taken to extremes you could insert thin sheets of mica into the slots in case the triac or SCR blows in a violent way. Mica will stop plasma-hot debris for a second or so, time for an upstream fuse to blow.
You could stop the slot cut just past the R2 annular ring. Slot cuts can go past the edge of a board but it looks tacky unless a robust isolation barrier is needed.
Note that all slot cuts have rounded corners equal to the radius of the bit doing the cut. Since you need to give precise dimensions to the board house do not confuse them with square corners as they cannot make them. For slot cut dimensions give them the length and width minus the radius of the bit they use. For 2mm bits decrease documented dimensions by 1mm, etc.

A: If that purple line is your board edge and you're using Altium, you need to set it. Select the board edge lines and then go to (I think) Edit->Board Shape->Define from Selected Objects
(Apparently this is EasyEDA, not Altium. Wow they sure were going for 'that Altium look'!!)

I don't know what your part looks like with that ESP8266 footprint, but the holes are TINY.

Typically on a DIP part, pin 1 is square and the others are circular or stretched circular

R3 and switch pad (U2?) are too close together IMO. If you solder waved this there is a decent chance of bridging and it can be just annoying to have leads that close that aren't connected.

Typically ICs are designated "U". Switches/buttons are "SW" "S" "PB".

Note: I make no claim or comment on the safety of this design.


text:
Q: Вывод переменных окружения Windows в файл .txt с форматированием Привет всем есть задание , вывести переменные окружения Windows в файл .txt чтобы данных отображались в нём в виде таблицы, сделать это нужно с помощью bat файла. Если мы делаем вывод в файл данные выглядят таким образом изначально:

нужно привести к такому виду:

но основная загвоздка в том что картинка №2 была сделана с помощью скрипта написанного в powershell , нужно же сделать такой же вывод как на 2 ой картинке но только с помощью batch(на котором пишутся bat файлы для windows), все кто может помочь в решении помогите пожалуйста я уже тонну информации перелопатил так и не смог сделать, если можете сделать за деньги то пишите цену.Всем спасибо за внимание.

A: Следующий комментиробанный 653805.bat скрипт может помочь.
@ECHO OFF
SETLOCAL EnableExtensions DisableDelayedExpansion
:: вычислить максимальную длину
set "_varLenMax=2"
for /F "tokens=1 delims==" %%G in ('set %~1 ^|findstr /V "^_"') do (
    set "_varName=%%G"
    call :strlen _varLen _varName
    rem отладочный вывод call echo %%_varLen%% %%_varName%%
    call :compareLen
)

set "_separator=  "
for /L %%G in (1,1,%_varLenMax%) do call set "_separator= %%_separator%%"

:: (optional) header (Факультативный) заголовок
set "_varName=Name%_separator%"
call echo %%_varName:~0,%_varLenMax%%% Value
:: (optional) header separator (Факультативный) разделитель заголовки
set "_varName=----%_separator%"
call echo %%_varName:~0,%_varLenMax%%% -----

for /F "tokens=1,* delims==" %%G in ('set %~1 ^|findstr /V "^_"') do (
    set "_varName=%%G%_separator%"
    call echo %%_varName:~0,%_varLenMax%%% %%H
)

ENDLOCAL
goto :eof

:: похвала: jeb, http://stackoverflow.com/a/5841587/3439404
:strlen <resultVar> <stringVar>
(
    setlocal EnableDelayedExpansion
    set "s=!%~2!#"
    set "len=0"
    for %%P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
        if "!s:~%%P,1!" NEQ "" (
            set /a "len+=%%P"
            set "s=!s:~%%P!"
        )
    )
)
(
    endlocal
    set "%~1=%len%"
    exit /b
)

:compareLen
if %_varLen% GTR %_varLenMax% set /A "_varLenMax=_varLen"
goto :eof

Кракозя́бры в имени пользователья USERNAME и USERPROFILE происходят из разности набора символов в кодировках Windows-1251 и  CP-866
d:\bat> chcp 866
Active code page: 866

d:\bat> >D:\bat\SU_ru\file653805.txt D:\bat\SU_ru\653805.bat x

d:\bat> type D:\bat\SU_ru\file653805.txt
Name               Value
----               -----
x32                C:\Windows\SysWOW64
xProgramFiles(x86) C:\Program Files (x86)
xrussian           Александр

d:\bat> chcp 1251
Active code page: 1251

d:\bat> type D:\bat\SU_ru\file653805.txt
Name               Value
----               -----
x32                C:\Windows\SysWOW64
xProgramFiles(x86) C:\Program Files (x86)
xrussian           Ђ«ҐЄб ¤а

d:\bat> >D:\bat\SU_ru\file653805.txt D:\bat\SU_ru\653805.bat x

d:\bat> type D:\bat\SU_ru\file653805.txt
Name               Value
----               -----
x32                C:\Windows\SysWOW64
xProgramFiles(x86) C:\Program Files (x86)
xrussian           Александр

d:\bat> chcp 866
Active code page: 866

d:\bat> type D:\bat\SU_ru\file653805.txt
Name               Value
----               -----
x32                C:\Windows\SysWOW64
xProgramFiles(x86) C:\Program Files (x86)
xrussian           └ыхъёрэфЁ

d:\bat>


text:
Q: Procedure to double INSERT, SQL Server? I need to make an insert condition into 2 tables, I think the only way to do this is with a procedure, but I don't know how to do it, can you help me? Is for a system in Visual Basic, also if you know an easiest way to do this please let me know.
I have this tables:
PREGUNTAS_OPERACIONES
ID (INT)
ID_OPERACION (INT)
TIPO_PREGUNTA (INT)
PREGUNTA (VARCHAR MAX)
RESPUESTA (CHAR(1))
NIVEL  (INT)
.
OPCIONES_PREGUNTAS
ID (FOREAN KEY FROM PREGUNTAS_OPERACIONES "ID")
INCISO (CHAR(1))
DESCRIPCION_OPCION
I'm using ASPX in Visual Basic

A: In spite of not having enough details as user Bridge mentions, here is a thought :
You could run the statements separately ? Or, even better, wrap them in a Transaction and commit them together ?


text:
Q: Get a promise with angular2 in dart from an http request? It seems in the 2.0.0-beta.12 build they removed angular2.http from dart in favor of using dart's built in http classes.
However if you were to do something like the following then property is null until the request sets the property.
class Component {
  var property;

  Component() {
    HttpRequest.getString("/path/to/something")
      .then((resp) {
        property = JSON.decode(resp);
      });
  }
}

What we really want is a promise place holder for the property until the promise is resolved and the view is updated. So how do you do it in angular2 with dart?
Or is there a different dart/angular2 idiomatic way to do it?

A: HttpRequest.getString(...) returns a Future (Promise in JS/TS land) otherwise you wouldn't be able to call .then(...) on the result.

You can either use async / await
class Component {
  var property;

  Component() async {
    await HttpRequest.getString("/path/to/something")
      .then((resp) {
        property = JSON.decode(resp);
      });
    doSomethingAfterRequestReturned();
  }
}

nope - you can't use async / await in a constructor.
Alternatives are static methods or an extra call after object creation. Doing extensive work in the constructor is bad practice anyway.
class Component {
  Future<Component> createNewInstance() async {
    var c = new Component();

    await HttpRequest.getString("/path/to/something")
    .then((resp) {
      c.property = JSON.decode(resp);
    });
    return c;
  }

  var property;
}

and use it like
Component.createNewInstance().then((c) => print(c.property));

with an extra call
class Component {
  getData() {
    return HttpRequest.getString("/path/to/something")
    .then((resp) {
      property = JSON.decode(resp);
    });
  }

  var property;
}

and use it like
var c = new Component()
c.getData().then((_) => print(c.property));


text:
Q: How to make Clickhouse Materialized View work correctly on a cluster with 6 nodes There is 6 nodes in my clickhouse cluster. I create local tables(with ReplicatedReplacingMergeTree engine) and distributed tables on the cluster. A Materialized View on node 'cdh03' is created to join data from tables and write the result to the distributed table. I then create a Materialized View on node 'cdh06', which select data from the distributed table and push them to mysql, with a mysql engine.
However, since data is correctly writen to the distributed table, and could be seen on other nodes, the Materialized View on node 'cdh06' writes nothing to mysql.
I tried to create the Materialized View with the same query on other nodes, but only on the node 'cdh03' it works correctly. What's wrong with this? And what can I do to make it work?


text:
Q: Property inheritance involving objects and prototypes I'm a newbie at JS and in one of my tests I've been trying to figure out how the following code works in terms of property inheritance.
function doSomething(){}

doSomething.prototype.foo = "bar"; //Add "foo" property to doSomething's prototype
let anInstance = new doSomething();
anInstance.prop = "value"; //Add "prop" property to object "anInstance"
doSomething.prop = "another value"; //Add "prop" property to "doSomething"
let anotherInstance = new doSomething();

console.log(doSomething.prop);
console.log(anInstance);
console.log(anotherInstance.prop);

This is the above script's output in the console:
another value

doSomething{prop: "value"}
  prop: "value"
  __proto__:
    foo: "bar"
    constructor: ƒ doSomething()
    __proto__: Object

undefined

As you can see, printing doSomething's prop property after being added to it returns expected another value, but accessing anotherInstance's prop returns undefined.
Isn't that anotherInstance supposed to "inherit" such prop property since it's defined within the function from which it was created?
Thanks in advance.

A: Adding a property to a function is not the same as adding a property to the function's prototype object. Instances of the function inherit the function's prototype properties, not the function's own properties:

function doSomething(){}

doSomething.prototype.foo = "bar"; //Add "foo" property to doSomething's prototype

doSomething.prop = "another value"; //Add "prop" property to "doSomething" but no the prototype

let anotherInstance = new doSomething();

// only has foo:
console.log(doSomething.prototype)

// this is the object it will inherit from
// only has foo
console.log(Object.getPrototypeOf(anotherInstance))

//they are the same object:
console.log(doSomething.prototype === Object.getPrototypeOf(anotherInstance))

In the code above doSomething.prop is just a property of the function, it plays no role in prototype inheritance.


text:
Q: Height the same as width I'm using a block grid in Foundation:

Something

Something

Something

I want each li to have the same height as it's width. Each li has a different width at each of Foundation's breakpoints.
I've checked the web and looked into vw, the only decent solution I can think of is setting the vw height to be the same as Foundations li width at each break point.
Is there a better solution?
I do not want to use anything other than CSS.

A: The alternative option in CSS to viewport units is to make use of padding-bottom
DEMO

div {
  width: 40%;
  padding-bottom: 40%;
  background: tomato;
}


text:
Q: Creating hover and current page states with sibling elements I have animated nav buttons and can actually set everything with css with the exception of one element. An arrow. Here's the actual live page.
http://sclarkstudio.com/testing/mm/index.htm
I'm trying to make the arrow visible and static on the current page. I have a hover script that animates the arrow when the class is set to .arrow and it's static and visible when the class is set to .currenta.

        Home

        News

and so on...

The script that I'm trying to write just needs to change the class of the arrow div to ".currenta"
var bodyID = $("body").attr("id");
var url = window.location;

$(function() {

$('nav ul li a #BtnText').each(function(){
var myHref = $(this).attr('href');
if( url == myHref) {
    $(this).closest('div','#arrow').css('currenta');
}
});
});

I have been pulling my hair out trying to figure this one out and not the best coder.

A: First :  ID's should be unique.  It will only grab the first element it finds with that ID
Second : To add a class use addClass()
Third : window.location will never == your href so the code will never run.  You want to check if it contains your href by using indexOf
Fourth: You can just grab the elements with their class name.
$('.arrow').each(function(){
     var $this = $(this);
     if(window.location.indexOf($this.siblings('a.navButton').attr('href')) > -1){  //
         $this.removeClass('arrow').addClass('currenta');
         // I think you wanted to remove the arrow class.. if not just remove it
     }
});

http://jsfiddle.net/9x9uF/

A: First of all you have duplicate ids in your page (BtnText and arrow) exists more than once, change them to class because id must be unique. So your html should be like something like following

            Home

            News

JS
var url = window.location;
$(function() {
    $('nav ul li a.BtnText').each(function(){
        var myHref = $(this).attr('href');
        if(url.match(myHref)) { // use match
            $(this).next('div.arrow')
            .removeClass('arrow').addClass('currenta'); // use removeClass and addClass
        }
    });
});

DEMO.
Update:
Remember that after removing the class arrow you'll lose all styles associated with this class so you may just use addClass without removing the class arrow using removeClass. So, in that case
$(this).next('div.arrow').removeClass('arrow').addClass('currenta');

should be
$(this).next('div.arrow').addClass('currenta');


text:
Q: When to use @@@ vs. /@ So much thanks to Szabolcs in improving sequence.. for complete explanation. I am so glad to read all explanation which fundamentally remove the problem. But in number 4 of its explanation pointed to Apply in {1} level: As we show with @@@. But I have a problem with this function. As Szabolcs pointed, this function acts as:
list = {{x1,y1}, {x2,y2}, ..., {xn,yn}},
 f@@@list= {f[x1,y1], f[x2,y2], ..., f[xn,yn]}

But for example we want to use Last for a list as:
m = {{1, 2, I}, {0, 0, 0}, {I, I, 3}, {2, 6, I}, {0, 0, 0}, {0, 0, 0}, {1, 6, 4}, {0, 0, 0}, {1, 4, 5}}

Last@m

{1, 4, 5}

Apply[Last, {m}]= Last@@{m}

{1, 4, 5}

Last /@ m
{I, 0, 3, I, 0, 0, 4, 0, 5}

But Apply[Last, {m}, {1}] or Last@@@{m} doesn't have any result. I predicted that I should have Last@@@ {m}={Last{1, 2, I},Last{0,0,0},....} which is the result of Last/@ m.
Also I can't understand what is the exact differnce between  Last@m and Last@@{m}. I have confused with these syntax.

A: I know this has been answered already on this site, but I cannot seem to find it.
Map and Apply do subtly different things. For example,
Map[f, {a,b,c}]
(* {f[a], f[b], f[c]} *)

If you have a list that is more deeply nested, without using the third argument which is for level specification, you get
Map[f, {{a,b}, {c}}]
(* {f[{a,b}], f[{c}]} *)

or, if you do use it
Map[f, {{a, b}, {c}}, 2]
(* {f[{f[a], f[b]}], f[{f[c]}]} *)
Map[f, {{a, b}, {c}}, {1,2}]
(* {f[{f[a], f[b]}], f[{f[c]}]} *)
Map[f, {{a, b}, {c}}, {2}]
(* {{f[a], f[b]}, {f[c]}} *)

But, in every case, Map applies f to each element as is.
Apply does not do that; it explicitly replaces the Head of the element with f, as follows:
Apply[f, bob[a]] (* f @@ bob[a] *)
(* f[a] *)
Apply[f, {{a, b}, {c}}, {1}] (* f @@@ {{a, b}, {c}} *)
(* {f[a, b], f[c]} *)
Apply[f, {{a, b}, {c}}, {0, 1}]
(* f[f[a, b], f[c]] *)

On the surface, these look a lot like the results from Map, but the key difference is Apply does not work on something that is AtomQ as they are effectively headless (except in special cases), e.g.
Through[{AtomQ, ValueQ}[a]]
(* {True, False} *)
f @@ a
(* a *)
f @@@ {a}
(* {a} *)

For your application, you have nested lists, and to see how those are interpreted, use FullForm, e.g.
FullForm@{{1, 2, I}, {0, 0, 0}}
(* List[List[1, 2, Complex[0, 1]], List[0, 0, 0]] *)

(As an aside, note how I is interpreted as Complex[0,1], but despite this, AtomQ@Complex[0,1] returns True.)
So, you want to use Map, e.g.
Last /@ {{1, 2, I}, {0, 0, 0}}
(* {I, 0} *)

because @@@ will replace the heads of the inner lists with Last, e.g.
f @@@ {{1, 2, I}, {0, 0, 0}} (* where f is standing in for Last *)
(* {f[1, 2, I], f[0, 0, 0]} *)


text:
Q: Vector Autoregression with constrained variables Assume we have 3 time-series variables $Y$, $W$, and $P$. They are positive and co-integrated with $0 < W + P < Y$ at any time $t$.
Now define $w = W/Y$, $p = P/Y$, and $c = 1 - w - p$.
Also define some latent variable driving $Y$, for instance we care about $Z$ with $Y = Z * X$, where $Z$ is stationary and $X$ is co-integrated with $Y$.
Now, I want to understand how $Z$ is related with $w$ and $p$.
I perform some univariate regressions:
I find that $\Delta w$ depends on $\Delta log Z$ with positive coefficient.
I find that $\Delta p$ depends on $\Delta log Z$ with negative coefficient.
I find that $\Delta c$ does not depend on $\Delta log Z$.
My question is does it makes sense to estimate a VAR for $\Delta w$, $\Delta p$, and $\Delta \log Z$?
How does the constraint $0 < W + P < Y$ affect my results? How do I account for it?
Should I impose long-run restrictions (given $W,$ $P$, and $Y$ are co-integrated)?
Thanks a lot


text:
Q: How to manage a Git merge conflict with xlsx (binary)? How to manage a Git merge conflict with xlsx (binary)?
It requested to fix the conflict:
$ git merge
warning: Cannot merge binary files: proj/data/specs.xlsx (HEAD vs.
refs/remotes/origin/master)
Auto-merging proj/data/specs.xlsx
CONFLICT (content): Merge conflict in proj/data/specs.xlsx
Automatic merge failed; fix conflicts and then commit the result.

I want get the origin/master version of the file
git add proj/data/specs.xlsx; git commit

it keep my local version of the file.
If I checkout the file I get this error:
$ git checkout labor_um/data/UM_specs.xlsx
error: path 'labor_um/data/UM_specs.xlsx' is unmerged

A: Do:
git checkout --theirs proj/data/specs.xlsx
git add proj/data/specs.xlsx
git commit

The --theirs flag for the checkout command tells Git to use the version from the branch you are merging (in this case origin/master). Similarly, the --ours flag would use the version from the branch you are on (likely master).
Note that the definition of --theirs and --ours is swapped during a rebase.

A: git checkout --theirs proj/data/specs.xlsx

should take the version of the xlsx file on the origin and ignore your modified version.
It should fix the conflict then you need to commit it.


text:
Q: $divide is mongoose is giving "Cast to Number failed for value" Here i am trying to update the 'rating' field of my document by taking average of previously existing value of the rating field and newly sent rating value.
this is my rating field specification in the model
rating: {
      type: Number,
      min: 0,
      max: 5,
      required: true,
},

this is my request body and controller function
const { newRating, bookID, userName, comment } = req.body;

const updateRating = await Book.findByIdAndUpdate(
    { _id: bookID },
    {
      rating: { $divide: [{ $inc: { rating: Number(newRating) } }, 2] },
      $inc: { numOfRatings: 1 },
    },
    { new: true }
    );

and i am using postman to send client side data
here for example the rating field has previously set value of 4.1 and i am sending 5 as new rating in req.body then i want the rating field to have an updated value of 4.55 ((4.1+5)/2)
and this is the output i am getting in postman
{
"message": "Cast to Number failed for value "{ '$divide': [ { '$inc': [Object] }, 2 ] }" (type Object) at path "rating"",
"stack": "CastError: Cast to Number failed for value "{ '$divide': [ { '$inc': [Object] }, 2 ] }" (type Object) at path "rating"\n    at model.Query.exec (D:\Programs\VS Code\Web Development\lmsbackend\node_modules\mongoose\lib\query.js:4891:21)\n    at model.Query.Query.then (D:\Programs\VS Code\Web Development\lmsbackend\node_modules\mongoose\lib\query.js:4990:15)\n    at processTicksAndRejections (node:internal/process/task_queues:96:5)"
}
i tried few things seeing mongodb solutions but it is not working out for me. Thank you in advance.

A: $divide is only available for Aggregation framework, so you need to change your update (second) input like this:
await Book.findByIdAndUpdate({
  _id: bookID
},
[
  {
    "$set": {
      "rating": { "$divide": [{ "$sum": ["$rating", Number(newRating)] }, 2] },
      "numOfRatings": { "$sum": ["$numOfRatings", 1 ] }
    }
  }
])

Working example

A: I hope this will work:
const updateRating = await Book.findByIdAndUpdate(
  { _id: bookID },
  [{
    "$set": {
      "rating": { "$divide": [{ "$sum": ["$rating", 5] }, 2] },
      "numOfRatings": { "$sum": ["$numOfRatings", 1 ] }
    }
  }],
  { new: true }
);


text:
Q: Converting CMD script to GUI I have a question.
I'm currently trying to convert a simple batch script that I have made to a GUI-version. I'm not a professional, but I love to tinker around and try stuff out.
Is there anyone who could help me to go in the right direction?
Here is my simple batch script:
@echo off
::BatchHasAdmin
:-------------------------------------
REM --> Check if this file has administrator rights.
    IF "%PROCESSOR_ARCHITECTURE%" EQU "amd64" (
>nul 2>&1 "%SYSTEMROOT%\SysWOW64\cacls.exe" "%SYSTEMROOT%\SysWOW64\config\system"
) ELSE (
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
)

REM --> If no rights, we don't have setted the flag for it.
if '%errorlevel%' NEQ '0' (
    echo Requesting administrative privileges...
    goto UACPrompt
) else ( goto gotAdmin )

:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    set params= %*
    echo UAC.ShellExecute "cmd.exe", "/c ""%~s0"" %params:"=""%", "", "runas", 1 >> "%temp%\getadmin.vbs"

    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
    exit /B

:gotAdmin
    pushd "%CD%"
    CD /D "%~dp0"
:--------------------------------------
:: MainCode
@echo off
title pcHealth - Check your PC's Health! - version 1.5.7-beta
cd /
color D
cls

:MENU
cls
color D
echo.
echo Thanks for downloading and using pcHealth!
echo Please be sure that you are running this Batch file in Administrator mode.
echo.
echo Made by REALSDEALS - Licensed under GNU-3 (You are free to use, but not to change or to remove this line.)
echo You are now using version 1.5.7 (Beta)
echo.
echo %DATE%, %TIME%
echo.
echo ...........................................................
echo Enter number 1 to open a menu regarding testing scripts.
echo Enter number 2 to open a menu regarding programs for testing /w downloadable redirects.
echo Enter number 3 to go to the repository of pcHealth.
echo Enter number 4 to close this batch script.
echo ...........................................................
echo.

SET /P A=Type one of the numbers from the menu above to open the desired menu and then press ENTER. Enter:
IF %A%==1 GOTO TOOLS
IF %A%==2 GOTO PROGRAMS
IF %A%==3 GOTO PCHEALTHGETVER
IF %A%==4 GOTO CLOSE

:TOOLS
cls
color 9
echo.
echo ...........................................................
echo Enter number 1 to gather generic information about the system.
echo Enter number 2 to see which CPU and GPU are in the system.
echo Enter number 3 to run a system scan for missing/corrupt files.
echo Enter number 4 to try and repair missing/corrupt files.
echo Enter number 5 to run a system scan and to start an attempt on repairing missing/corrupt files.
echo Enter number 6 to generate a battery report. (Laptop only)
echo Enter number 7 to open the GUI to Windows Updates.
echo Enter number 8 to start a short ping test.
echo Enter number 9 to start a continues ping test.
echo Enter number 10 to update system programs.
echo Enter number 11 to re-start the audio drivers of your system.
echo Enter number 12 to re-open the generated battery report file.
echo Enter number 13 to re-open the CBS.log (AKA DISM.log)
echo Enter number 14 to get your Ninite! Includes Edge, Chrome, VLC and 7Zip.
echo Enter number 15 to see your systems Windows License key.
echo Enter number 16 BIOS Password Recovery.
echo Enter number 17 to shutdown, reboot or log off from your PC/laptop.
echo Enter number 18 to open the programs menu.
echo Enter number 19 to return to the previous menu.
echo Enter number 20 to close this batch file.
echo ...........................................................
echo.

SET /P B=Type one of the numbers from the menu above to run the desired function, then press ENTER. Enter:
IF %B%==1 GOTO SYSINFO
IF %B%==2 GOTO CPUANDGPUINFO
IF %B%==3 GOTO SCAN
IF %B%==4 GOTO DISM
IF %B%==5 GOTO SCSM
IF %B%==6 GOTO BATTERY
IF %B%==7 GOTO UPDATE
IF %B%==8 GOTO SHORTPING
IF %B%==9 GOTO CONTINUESPING
IF %B%==10 GOTO SYSUPDATE
IF %B%==11 GOTO AUDIORE
IF %B%==12 GOTO BATOPEN
IF %B%==13 GOTO OPENCBSLOG
IF %B%==14 GOTO NINITE
IF %B%==15 GOTO LICENSE
IF %B%==16 GOTO BIOSPW
IF %B%==17 GOTO RESHUT
IF %B%==18 GOTO PROGRAMS
IF %B%==19 GOTO MENU
IF %B%==20 GOTO CLOSE

:PROGRAMS
cls
color B
echo.
echo ...........................................................
echo Enter number 1 to get hardware info.
echo Enter number 2 to get ADW Cleaner.
echo Enter number 3 to get DiskInfo64.
echo Enter number 4 to get DiskMark64.
echo Enter number 5 to get Prime95.
echo Enter number 6 to open the tools menu.
echo Enter number 7 to return to the previous menu.
echo Enter number 8 to close the script.
echo ...........................................................
echo.

SET /P AB=Type one of the numbers above to run the desired function. Enter:
IF %AB%==1 GOTO HARDINFODOWN
IF %AB%==2 GOTO ADWCLEANER
IF %AB%==3 GOTO DISKINFODOWN
IF %AB%==4 GOTO DISKMARKDOWN
IF %AB%==5 GOTO PRIMEDOWN
IF %AB%==6 GOTO TOOLS
IF %AB%==7 GOTO MENU
IF %AB%==8 GOTO CLOSE

:SYSUPDATE
cls
color A
winget upgrade --all
pause
echo.
SET /P LL=Enter number 1 to return to the sub-menu, enter number 2 to return to the main-menu or enter number 3 to exit the script. Enter:
IF %LL%==1 GOTO TOOLS
IF %LL%==2 GOTO MENU
IF %LL%==3 GOTO CLOSE

:SYSINFO
cls
color A
systeminfo
pause
echo.
SET /P C=Enter number 1 to return to the main-menu, enter number 2 to go back to the previous sub-menu or enter number 3 to close the script. Enter:
IF %C%==1 GOTO MENU
IF %C%==2 GOTO TOOLS
IF %C%==3 GOTO CLOSE

:SCAN
cls
color A
sfc /scannow
pause
echo.
SET /P D=If the scan found any corrupt files, enter number 1 to check the .log, enter number 2 to return to the previous sub-menu, enter number 3 when you want to return to the menu or enter number 4 to close the script. Enter:
IF %D%==1 GOTO OPENCBSLOG
IF %D%==2 GOTO TOOLS
IF %D%==3 GOTO MENU
IF %D%==4 GOTO CLOSE

:CPUANDGPUINFO
cls
color A
echo.
echo Your CPU information:
echo.
wmic cpu get caption, deviceid, name, numberofcores, maxclockspeed, status
echo.
echo Your GPU information:
echo.
wmic path win32_VideoController get name
pause
echo.
SET /P E=Enter number 1 to return to the main-menu, enter number 2 to go back to the previous sub-menu or enter number 3 to close the script. Enter:
IF %E%==1 GOTO MENU
IF %E%==2 GOTO TOOLS
IF %E%==3 GOTO CLOSE

:DISM
cls
color A
DISM /online /cleanup-image /checkhealth
DISM /online /cleanup-image /scanhealth
pause
echo.
SET /P F=Enter number 1 to start an attempt on repairing, enter number 2 to return to the previous sub-menu, number 3 for the main-menu or number 4 to exit the script. Enter:
IF %F%==1 GOTO DISMRESTORE
IF %F%==2 GOTO TOOLS
IF %F%==3 GOTO MENU
IF %F%==4 GOTO CLOSE

:DISMRESTORE
cls
color A
DISM /online /cleanup-image /restorehealth
pause
echo.
SET /P G=Enter number 1 to return to the main-menu, enter number 2 to go back to the previous sub-menu or enter number 3 to close the script. Enter:
IF %G%==1 GOTO MENU
IF %G%==2 GOTO TOOLS
IF %G%==3 GOTO CLOSE

:SCSM
cls
color A
sfc /scannow
pause
echo.
SET /P H=If the scan found any corrupt files, enter number 1 to check the .log, enter number 2 to start an attempt to repair the corrupt/missing files,enter number 3 to return to the previous sub-menu, enter number 4 to return to the main-menu or enter number 5 to exit the script. Enter:
IF %H%==1 GOTO SCSMOPENLOG
IF %H%==2 GOTO CONTINUE
IF %H%==3 GOTO TOOLS
IF %H%==4 GOTO MENU
IF %H%==5 GOTO CLOSE

:SCSMOPENLOG
cls
color A
start %windir%\explorer.exe "C:\Windows\Logs\CBS\CBS.log"
pause
echo.
SET /P I=Enter number 1 to start an attempt to repair the corrupt/missing files, if any are found... Enter number 2 to return to the previous sub-menu, enter number 3 to return to the main-menu or enter number 4 to exit the script. Enter:
IF %I%==1 GOTO CONTINUE
IF %I%==2 GOTO TOOLS
IF %I%==3 GOTO MENU
IF %I%==4 GOTO CLOSE

:CONTINUE
cls
color A
DISM /online /cleanup-image /checkhealth
DISM /online /cleanup-image /scanhealth
pause
DISM /online /cleanup-image /restorehealth
pause
echo.
SET /P J=Enter number 1 to return to the previous sub-menu, enter number 2 to return to the main-menu or enter number 3 to exit. Enter:
IF %J%==1 GOTO TOOLS
IF %J%==2 GOTO MENU
IF %J%==3 GOTO CLOSE

:BATTERY
cls
color A
powercfg /batteryreport
pause
echo.
SET /P K=Enter number 1 to open the generated file, enter number 2 to return to the previous sub-menu, number 3 to return to the main-menu or enter number 4 to exit the script. Enter:
IF %K%==1 GOTO BATOPEN
IF %K%==2 GOTO TOOLS
IF %K%==3 GOTO MENU
IF %K%==4 GOTO CLOSE

:UPDATE
cls
color A
control update
pause
echo.
SET /P L=Enter number 1 to return to the previous sub-menu, enter number 2 to return to the main-menu or enter number 3 to exit the script. Enter:
IF %L%==1 GOTO TOOLS
IF %L%==2 GOTO MENU
IF %L%==3 GOTO CLOSE

:SHORTPING
cls
color A
ping 8.8.8.8
pause
echo.
SET /P M=Enter number 1 to return to the previous sub-menu, enter number 2 to return to the main-menu, enter number 3 to start a continues ping test or enter number 4 to exit the script. Enter:
IF %M%==1 GOTO TOOLS
IF %M%==2 GOTO MENU
IF %M%==3 GOTO CONTINUESPING
IF %M%==4 GOTO CLOSE

:CONTINUESPING
cls
color A
ping 8.8.8.8 -t -l 256
pause
echo.
SET /P N=Enter number 1 to return to the previous sub-menu menu, enter number 2 to return to the main-menu or enter number 3 to exit the script. Enter:
IF %N%==1 GOTO TOOLS
IF %N%==2 GOTO MENU
IF %N%==2 GOTO CLOSE

:AUDIORE
cls
color A
if "%1"=="am_admin" (powershell start -verb runas '%0' am_admin)
net stop audiosrv
net stop AudioEndPointBuilder
net start AudioEndPointBuilder
net start audiosrv
echo.
echo Your audio drivers have been reset, hope it solved your audio problem!
echo.
pause
GOTO TOOLS

:BATOPEN
cls
color A
start %windir%\explorer.exe "C:\battery-report.html"
pause
echo.
SET /P O=Enter number 1 to return to the previous sub-menu, enter number 2 to return to the main-menu or enter number 3 to exit the script. Enter:
IF %O%==1 GOTO TOOLS
IF %O%==2 GOTO MENU
IF %O%==3 GOTO CLOSE

:OPENCBSLOG
cls
color A
start %windir%\explorer.exe "C:\Windows\Logs\CBS\CBS.log"
pause
echo.
SET /P P=Enter number 1 to return to the previous sub-menu, enter number 2 to return to the main-menu or enter number 3 to exit the script. Enter:
IF %P%==1 GOTO TOOLS
IF %P%==2 GOTO MENU
IF %P%==3 GOTO CLOSE

:NINITE
cls
color A
start "" https://ninite.com/7zip-chrome-edge-vlc/ninite.exe
pause
echo.
SET /P Q=Enter number 1 to return to the previous sub-menu, enter number 2 to return to the main-menu or enter number 3 to exit the script. Enter:
IF %Q%==1 GOTO TOOLS
IF %Q%==2 GOTO MENU
IF %Q%==3 GOTO CLOSE

:LICENSE
cls
color A
echo.
echo "Your systems license key:"
wmic path SoftwareLicensingService get OA3xOriginalProductKey
pause
color E
echo.
echo If it didn't showed a key, it is possible that this PC is using a 'illegal' key, or a key that was used for a previous installation of Windows 7/8 - then upgraded to 10/11.
echo.
echo You can also try to use a different script for the license key, you can find it in the 'Scripts' folder in this pcHealth folder!
echo.
SET /p R=If you want to return to the previous sub-menu, enter number 1. To return to the main-menu, enter number 2. To exit the script, enter the number 3. Enter:
IF %R%==1 GOTO TOOLS
IF %R%==2 GOTO MENU
IF %R%==2 GOTO CLOSE

:BIOSPW
cls
color E
echo.
echo The BIOS Password Recovery tool is a website that can be used to gather/generate a recovery code for the BIOS.
echo.
echo If you don't know how to use this function/website, then
echo I would suggest that you enter '2' on the next line to learn more.
echo.
echo The credits for this function and repository goes to the owner: @bacher09
echo.
SET /P SK=Enter number 1 to visit the website, enter number 2 to go to the repository of BIOS-PW and learn more! Enter number 3 to return to the sub-menu, enter number 4 to return to the main-menu or enter number 5 to close the script. Enter:
IF %SK%==1 start "" https://bios-pw.org && GOTO BIOSPW
IF %SK%==2 start "" https://github.com/bacher09/pwgen-for-bios && GOTO BIOSPW
IF %SK%==3 GOTO TOOLS
IF %SK%==4 GOTO MENU
IF %SK%==5 GOTO CLOSE

:RESHUT
cls
color A
echo.
SET /P S=If you want to log off from your PC/Laptop enter number 1, to restart enter number 2, to shutdown enter number 3 and to return to the previous sub-menu enter number 4 or to exit the script... enter number 5. Enter:
IF %S%==1 GOTO LOGOFF1
IF %S%==2 GOTO RESTART2
IF %S%==3 GOTO SHUTDOWN3
IF %S%==4 GOTO TOOLS
IF %S%==5 GOTO CLOSE

:LOGOFF1
cls
color A
echo.
SET /P T=Are you sure that you want to log off your PC? Enter number 1, enter number 2 to return to the previous sub-menu, enter number 3 to return to the main-menu or enter number 4 to exit the script. Enter:
IF %T%==1 GOTO LOGOFFCONFIRM1
IF %T%==2 GOTO TOOLS
IF %T%==3 GOTO MENU
IF %T%==4 GOTO CLOSE

:LOGOFFCONFIRM1
cls
color A
shutdown /l
EXIT /B

:RESTART2
cls
color A
echo.
SET /P U=Are you sure that you want to restart your PC? Enter number 1, to do so. Enter number 2 to return to the previous sub-menu, enter number 3 to return to the main-menu or enter number 4 to exit the script. Enter:
IF %U%==1 GOTO RESTARTCONFIRM2
IF %U%==2 GOTO TOOLS
IF %U%==3 GOTO MENU
IF %U%==4 GOTO CLOSE

:RESTARTCONFIRM2
cls
color A
shutdown /r
EXIT /B

:SHUTDOWN3
cls
color A
echo.
SET /P V=Are you sure that you want to shutdown your PC? Enter number 1, to continue. Enter number 2 to return to the previous sub-menu, enter number 3 to return to the main-menu or enter number 4 to exit the script. Enter:
IF %V%==1 GOTO SHUTDOWNCONFIRM3
IF %V%==2 GOTO TOOLS
IF %V%==3 GOTO MENU
IF %V%==4 GOTO CLOSE

:SHUTDOWNCONFIRM3
cls
color A
shutdown /s
EXIT /B

:PCHEALTHGETVER
cls
color A
echo.
echo Are you sure that you want to download the newest version of pcHealth?
echo.
SET /P AC=If yes, enter the number 1, if not enter number 2 to return to the previous sub-menu. Enter:
IF %AC%==1 GOTO PCHEALTHGETVERDOWNLOADLINK
IF %AC%==2 GOTO MENU

:PCHEALTHGETVERDOWNLOADLINK
cls
color A
echo.
echo Your download will start now!
echo.
start "" https://github.com/REALSDEALS/pcHealth/archive/refs/heads/main.zip
echo.
SET /P AD=To return to the main menu enter 1, to close the script enter 2. Enter:
IF %AD%==1 GOTO MENU
IF %AD%==2 GOTO CLOSE

:HARDINFODOWN
cls
color A
echo.
echo Are you sure that you want to download the newest version of Hardware Info?
echo.
SET /P AE=If yes, enter the number 1, if not enter number 2 to return to the sub-menu. Enter:
IF %AE%==1 GOTO HARDINFODOWNLOADLINK
IF %AE%==2 GOTO PROGRAMS

:HARDINFODOWNLOADLINK
cls
color A
echo.
echo Your download will start now; if not click on 'installer' on the download page!
echo.
start "" https://www.fosshub.com/HWiNFO.html?dwl=hwi_726.exe
echo.
SET /P AF=To return to the previous sub-menu enter 1, enter number 2 to return to the main-menu or enter number 3 to exit the script. Enter:
IF %AF%==1 GOTO PROGRAMS
IF %AF%==2 GOTO MENU
IF %AF%==3 GOTO CLOSE

:ADWCLEANER
cls
color A
echo.
echo Are you sure that you want to download the latest version of ADW Cleaner?
echo.
SET /P AG=If yes enter the number 1 to start the download, enter number 2 to return to the previous sub-menu. Enter:
IF %AG%==1 GOTO ADWCLEANERDOWNLOADLINK
IF %AG%==2 GOTO PROGRAMS

:ADWCLEANERDOWNLOADLINK
cls
color A
echo.
echo Your download will start now!
echo.
start "" https://downloads.malwarebytes.com/file/adwcleaner
echo.
SET /P AH=To return to the previous sub-menu enter 1, enter number 2 to return to the main-menu or enter number 3 to exit the script. Enter:
IF %AH%==1 GOTO TOOLS
IF %AH%==2 GOTO MENU
IF %AH%==3 GOTO CLOSE

:DISKINFODOWN
cls
color A
echo.
echo Are you sure that you want to download the latest version of Disk Info?
echo.
SET /P AI=If yes enter the number 1 to start the download, enter the number 2 to return to the previous sub-menu. Enter:
IF %AI%==1 GOTO DISKINFODOWNLOADLINK
IF %AI%==2 GOTO PROGRAMS

:DISKINFODOWNLOADLINK
cls
color A
echo.
echo Your download will start now!
start "" https://osdn.net/projects/crystaldiskinfo/downloads/77538/CrystalDiskInfo8_17_4.zip/
echo.
SET /P AJ=To return to the previous sub-menu enter 1, enter number 2 to return to the main-menu or enter number 3 to exit the script. Enter:
IF %AJ%==1 GOTO TOOLS
IF %AJ%==2 GOTO MENU
IF %AJ%==3 GOTO CLOSE

:DISKMARKDOWN
cls
color A
echo.
echo Are you sure that you want to download the latest version of Disk Mark?
echo.
SET /P AK=If yes enter the number 1 to start the download, enter the number 2 to return to the previous sub-menu. Enter:
IF %AK%==1 GOTO DISKMARKDOWNLOADLINK
IF %AK%==2 GOTO PROGRAMS

:DISKMARKDOWNLOADLINK
cls
color A
echo.
echo Your download will start now!
start "" https://osdn.net/projects/crystaldiskmark/downloads/77539/CrystalDiskMark8_0_4b.zip/
echo.
SET /P AL=To return to the previous sub-menu enter 1, enter number 2 to return to the main-menu or enter number 3 to exit the script. Enter:
IF %AL%==1 GOTO TOOLS
IF %AL%==2 GOTO MENU
IF %AL%==3 GOTO CLOSE

:PRIMEDOWN
cls
color A
echo.
echo Are you sure that you want to download the latest version of Prime95? Enter:
echo.
SET /P AM=If yes enter the number 1 to start the download, enter the number 2 to return to the previous sub-menu.
IF %AM%==1 GOTO PRIMEDOWNLOADLINK
IF %AM%==2 GOTO PROGRAMS

:PRIMEDOWNLOADLINK
cls
color A
echo.
echo Your download will start now!
start "" https://www.guru3d.com/files-get/prime95-download,3.html
echo.
SET /P AN=To return to the previous sub-menu enter 1, enter number 2 to return to the main-menu or enter number 3 to exit the script. Enter:
IF %AN%==1 GOTO TOOLS
IF %AN%==2 GOTO MENU
IF %AN%==3 GOTO CLOSE

:CLOSE
EXIT /B

Main goal:

*

*I want to make a GUI version of this script.

Problems or things that I'm struggling with:

*

*How can I make commands like batch/ps and vbs run with each other, like for example from a click in the GUI. Because it are all languages on their own, I have now made 3 seperate folders. (The .vbs script is not my own, I got it and changed it a bit)

*A local database for users to run certain test, like the battery-report and save it to a local file/database that users could later acces.

*A kind of version control that when the script (GUI) is launched it would fetch from GitHub to check if there is a new version available.

I'm sorry if I'm asking some dumb questions, I'm trying to teach and help myself by doing some projects for myself. So all help is welcome! The pcHealth repo may be dumb, but a few people do use it :)
Please keep in mind that I'm not a pro, I would consider myself as a complete noob on this subject.
I'm looking forward to your responses though!
~ REALSDEALS

A: It is possible using python, but with a batch it is not possible.


text:
Q: NSManagedObjectContext working in background I have problem with merging changes between two context. One of them is working in background(additional context) as WebServices reading and writing data to database. While I was trying save any changes in main context, application gone stuck and nothing happend. Context from web services(singleton) I create as I showed below. When I try save main context I send notification to merge changes with WebServices context but it does not work correctly. Whats wrong? It happend when background is reading data and main context try to save something i database.
managedObjectContext = [NSManagedObjectContext new];
NSPersistentStoreCoordinator *store = [ [theDelegate managedObjectContext] persistentStoreCoordinator];
[managedObjectContext setPersistentStoreCoordinator:store];
[managedObjectContext setStalenessInterval:0.0];

Before save of Main Context I Use:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mergeChanges:) name:NSManagedObjectContextDidSaveNotification object:self.managedObjectContext];

where I merge changes
 [[[WebServie instance] managedObjectContext] mergeChangesFromContextDidSaveNotification:notification]

It should working but I have no idea whats going wrong, WebServices are working on background, and DataBaseManager is in main thread

Thats code of my merge context is it wrong?
NSNotificationCenter *dnc = [NSNotificationCenter defaultCenter];
[dnc addObserverForName:NSManagedObjectContextDidSaveNotification
                 object: self.managedObjectContext queue:nil
             usingBlock:^(NSNotification *notification)
 {
     NSLog(@"merge");
     [[[WebServiceManager instance] managedObjectContext] mergeChangesFromContextDidSaveNotification:notification];

 }];

NSError *error;
NSLog(@"error");
if (![self.managedObjectContext save:&error])
{
    NSLog(@"error :%@", error);// Update to handle any error appropriately.
}
NSLog(@"after error");

[dnc removeObserver:self
               name:NSManagedObjectContextDidSaveNotification
             object:self.managedObjectContext];

A: You need to do the merging on the queue of the context that's supposed to do the merge. Not on the queue (or thread) that it's being sent on.

A: If you are trying to keep two context synchronized, you need to listen to the NSManagedObjectContextDidSaveNotification for both context, and merge the notification of the first context to the second and viceversa. So, let's say you have your context on your applicationDelegate, and you have a context on your web singleton. You would create a method on your applicationDelegate to be fired when the singleton context saves. On that method, you would take the notification from the singleton object and merge it with the main thread context. On your singleton, you would listen to the NSManagedObjectContextDidSaveNotification from the main thread and merge it with the singleton's context.


text:
Q: Create vs Login when using Google oauth for access I am currently trying to setup my server to allow users to login with google oauth 2.0.
I am using passport and passport-google-oauth.
Normal set up is something like:
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
passport.use(new GoogleStrategy({
    clientID: GOOGLE_CLIENT_ID,
    clientSecret: GOOGLE_CLIENT_SECRET,
    callbackURL: "http://127.0.0.1:3000/auth/google/callback"
  },
  function(accessToken, refreshToken, profile, done) {
    User.findOrCreate({ googleId: profile.id }, function (err, user) {
      return done(err, user);
    });
  }
));

However what I really want is to still control access to my server after accounts are approved.
Meaning a user would first 'create' and account using google, then be able to signin once there account is approved.
I would really like there to be a signup route and login route:
app.get('/auth/google/signup',
  passport.authenticate('google', { scope: ['profile', 'email'] }));

app.get('/auth/google',
  passport.authenticate('google', { scope: 'https://www.googleapis.com/auth/plus.login' }));

app.get('/auth/google/callback',
  passport.authenticate('google', { failureRedirect: '/login' }),
  function(req, res) {
    // Successful authentication, redirect home.
    res.redirect('/');
  });

My problem is that when I get to the GoogleStrategy setup I don't really know which route they initially hit.  IE if they hit the login route but had not created an account I do not want to create an account I want to warn them that they did not yet create an account.  Had they hit the signup route and already had an account I would not want to create another account I would just tell them they already have an account.
Is there anyway in the GoogleStrategy that I can tell which route the user initially hit on my server?

A: In your user model create the "approved" field, with default False (Boolean)
And you can check this field on the GoogleStrategy to restrict the access.
If you want to apply this on all Strategies you can filter on the serialization method in passport.
Hope it helps.

A: You can pass a 'state' query parameter in your initial request that will be round-tripped back to your callback.
Documented here:
https://developers.google.com/identity/protocols/OAuth2WebServer

state
  Any string    Provides any state that might be useful to your
  application upon receipt of the response. The Google Authorization
  Server roundtrips this parameter, so your application receives the
  same value it sent. To mitigate against cross-site request forgery
  (CSRF), it is strongly recommended to include an anti-forgery token in
  the state, and confirm it in the response. See OpenID Connect for an
  example of how to do this.


text:
Q: How to prevent Gson from converting a long number (a json string ) to scientific notation format? I need to convert json string to java object and display it as a long. The json string is a fixed array of long numbers:
{numbers
[ 268627104, 485677888, 506884800 ] }

The code to convert works fine in all cases except for numbers ending in 0. It converts those to a scientific notation number format:
   public static Object fromJson(HttpResponse response, Class<?> classOf)
    throws IOException {
    InputStream instream = response.getResponseInputStream();

    Object obj = null;
    try {
        Reader reader = new InputStreamReader(instream, HTTP.UTF_8);

        Gson gson = new Gson();

        obj = gson.fromJson(reader, classOf);

        Logger.d(TAG, "json --> "+gson.toJson(obj));
    } catch (UnsupportedEncodingException e) {
        Logger.e(TAG, "unsupported encoding", e);
    } catch (Exception e) {
        Logger.e(TAG, "json parsing error", e);
    }

    return obj;
}

The actual result:
Java object :  268627104, 485677888, 5.068848E+8
Notice the last number is converted to a scientific notation format. Can anyone suggest what could be done to work around it or prevent it or undo it? I'm using Gson v1.7.1

A: I had a similar problem, and it not only converts integers to double, but it actually loses precision for certain long numbers, as described in this related question.
I tracked down this conversion to ObjectTypeAdapter's read method, specifically:
case NUMBER:
  return in.nextDouble();

It may be possible to plug in a modified TypeAdapter for Object, but I couldn't get that to work, so instead I just copied the read method (Object read(JsonReader in)) to my own code and modified the above lines to this:
case NUMBER:
    final String s = in.nextString();
    try {
        return Integer.parseInt(s);
    } catch (NumberFormatException e) {
        // ignore
    }
    try {
        return Long.parseLong(s);
    } catch (NumberFormatException e) {
        // ignore
    }
    return Double.parseDouble(s);

I wish Gson did this by default..
Then I put the other connecting pieces in a helper method that looks something like this:
public static Object parse(final Reader r) {
    try (final JsonReader jr = new JsonReader(r)) {
        jr.setLenient(true);
        boolean empty = true;
        Object o = null;
        try {
            jr.peek();
            empty = false;
            o = read(jr);
        } catch (EOFException e) {
            if (!empty) {
                throw new JsonSyntaxException(e);
            }
        }
        if (o != null && jr.peek() != JsonToken.END_DOCUMENT) {
            throw new JsonIOException("JSON document was not fully consumed.");
        }
        return o;
    } catch (IOException e) {
        throw new JsonIOException(e);
    }
}

So now instead of new Gson().fromJson(r, Object.class), I call parse(r).
This works well for me because I want to be able to parse json data with any structure, but if you have a particular class you're targeting, you probably just need to eliminate occurrences of Object within that class's members.

A: Got the same issue, after some investigation here is what I found.
The behavior:

*

*Gson
For a number without fractional part, Gson would convert it as Double,

*Jackson
For a number without fractional part, Jackson would convert it as Integer or Long, depends on how large the number is.

Possible solutions:

*

*Convert Gson's return value from Double to Long, explicitly.

*Use Jackson instead.
I prefer this.

Code - test for Jackson
ParseNumberTest.java:
import java.util.List;

import org.testng.Assert;
import org.testng.annotations.Test;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * test - jackson parse numbers,
 *
 * @author eric
 * @date Jan 13, 2018 12:28:36 AM
 */
public class ParseNumberTest {
    @Test
    public void test() throws Exception {
    String jsonFn = "numbers.json";

    ObjectMapper mapper = new ObjectMapper();

    DummyData dd = mapper.readValue(this.getClass().getResourceAsStream(jsonFn), DummyData.class);
    for (Object data : dd.dataList) {
        System.out.printf("data type: %s, value: %s\n", data.getClass().getName(), data.toString());
        Assert.assertTrue(data.getClass() == Double.class || data.getClass() == Long.class || data.getClass() == Integer.class);

        System.out.printf("%s\n\n", "------------");
    }
    }

    static class DummyData {
    List<Object> dataList;

    public List<Object> getDataList() {
        return dataList;
    }

    public void setDataList(List<Object> dataList) {
        this.dataList = dataList;
    }
    }
}

numbers.json:
{
    "dataList": [
        150000000000,
        150778742934,
        150000,
        150000.0
    ]
}

How to run:

*

*The test case is based on Jackson & TestNG.

*Put numbers.json at the same package as ParseNumberTest.java.

*Run as testng test, then it would print type & value of the parse result.

Output:
data type: java.lang.Long, value: 150000000000
------------

data type: java.lang.Long, value: 150778742934
------------

data type: java.lang.Integer, value: 150000
------------

data type: java.lang.Double, value: 150000.0
------------

PASSED: test

A: If serializing to a String is an option for you, you can configure GSON to do so with:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setLongSerializationPolicy( LongSerializationPolicy.STRING );
Gson gson = gsonBuilder.create();

This will produce something like:
{numbers : [ "268627104", "485677888", "506884800" ] }

A: Another work around is to use the JsonParser class instead. This will return the Gson object representations (JsonElement) rather than a user defined class, but avoids the problem of conversion to scientific notation.
import java.lang.reflect.Type;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

public class GsonTest
{
    public static void main(String[] args)
    {
        String json = "{numbers:[268627104,485677888,506884800]}";

        Gson gson = new Gson();
        Type type = new TypeToken<Map<String, Object>>(){}.getType();
        Map<String, Object> jsonMap = gson.fromJson(json, type);
        System.out.println("Gson output:");
        System.out.println(jsonMap);

        JsonParser jsonParser = new JsonParser();
        JsonElement jsonElement = jsonParser.parse(json);
        System.out.println("JsonParser output:");
        System.out.println(jsonElement);
    }
}

Code Output:
Gson output:
{numbers=[2.68627104E8, 4.85677888E8, 5.068848E8]}
JsonParser output:
{"numbers":[268627104,485677888,506884800]}

A: Not smart, but still working method is to add " at the start and at the end of the number. Then after processing is finished, delete it.

A: We can use the below code solution for number Long:
Document doc = documentCursor.next();

JsonWriterSettings relaxed = JsonWriterSettings.builder().outputMode(JsonMode.RELAXED).build();

CustomeObject obj = gson.fromJson(doc.toJson(relaxed), CustomeObject.class);

A: The best solution in case you need them as String was to force attributes to be quoted with a single quote before doing the conversion.
Do changes like this:
String readerAsString = convertReaderToString(reader);
readerAsString = readerAsString.toString().replace("=", "='");
readerAsString = readerAsString.toString().replace(",", "',");
readerAsString = readerAsString.toString().replace("}]", "'}]");

A: data class Answer(
    val question: String,
    val value: Any
)

Given the value:Any property above, I find it dubious that Gson encounters a JSON value of 1 (not "1") and cannot INFER the blatantly obvious truth: 1 is an Int.  Instead, Gson converts the integer value to the double 1.0.
Gson should only convert a JSON value from 1 to 1.0 if the value property above was of type Float or Double. When Gson encounters a property whose type is Any, it should (quite simply) infer the type from the JSON value it receives. Unfortunately, it doesn't, preferring to actually corrupt incoming integer values by casting them to Double, which unsurprisingly immediately causes exceptions.
I can find no reasonable solution to this peculiarity of the Gson parser. As such, I'm forced to either manually convert all those double values back into int values after using Gson or implement my own generic custom type adapter for Gson. Neither of these options is at all appealing.

A: I did not find a solution to my problem of gson formatting numbers ending in 0 to scientific notation. I instead used a work-around to convert this scientific notation into a double that I formatted with commas. "value" is the json string.
  private String formatNumber(String value) {
    double dValue = Double.parseDouble(value);
    String pattern = "#,###";
    DecimalFormat formatter = new DecimalFormat(pattern);
    String newNumber = formatter.format(dValue);

            return newNumber;
}

This doesn't answer the question asked but is an added step to work-around the problem to display the numbers as required by the system.


text:
Q: How to test server-sent-events with REST-Assured? How can I test a sever sent events endpoint with REST-Assured?
I have tried the following, but the test doesn't terminate:
        val stream = RestAssured.given()
                .contentType(MediaType.SERVER_SENT_EVENTS)
                .get("/status/stream").asInputStream()

        myService.publish(SomeEvent())
        val line = stream.reader().readText()

        stream.close()
        assertEquals("my-event", line)

myService.publish() pushes an object as the data payload to the SSE stream, which is validated by another test.
The assertion here is only exemplary. The problem is how to receive data from the stream.

A: You can read SSE urls with javax.ws.rs.sse.SseEventSource.