text:
Q: powershell - combine array properties in new one I have some array with lot of rows (thousands and more). It have columns like 'ColumnXXXXX'
Row example:
Group_name = "proxy_users"
Column1   = "domain\Igor"
Column2   = null
.......
Column989 = 'domain\Andrew'
Column999 = 'domain\Mike'

What is the right and FAST way to create new variable that will be the sum of 'ColumnXXX' ignoring 'null' values?
Like "domain\igor, domain\Andrew, domain\mike"
I can use smth like $group | select -Property "Column*"...but how to sum and how to ignore null ?

A: You can list all properties using ex. $_.psobject.properties, filter out the ones you want and use -join to combine the values. Ex
$o = [pscustomobject]@{
    Group_Name = "Test"
    Column1 = "Foo"
    Column2 = $null
    Column3 = "1"
}, [pscustomobject]@{
    Group_Name = "Test2"
    Column1 = $null
    Column2 = "Bar"
    Column3 = "2"
}

#Add property as constant
$o | ForEach-Object {
    $_ | Add-Member -NotePropertyName Summed -NotePropertyValue (($_.psobject.Properties | Where-Object { $_.Name -ne 'Group_name' -and $_.Value -ne 'null' } | Select-Object -ExpandProperty Value) -join '' )
}
$o | ft

Or you can use a ScriptProperty to calculate the value on every call
#Remember to exclude itself to avoid infinite recursion
$o | Add-Member -MemberType ScriptProperty -Name Summed -Value {($this.psobject.Properties | Where-Object { $_.Name -ne 'Group_name' -and $_.Name -ne 'Summed' -and $_.Value -ne 'null' } | Select-Object -ExpandProperty Value) -join '' }
$o | ft

Result:
Group_Name Column1 Column2 Column3 Summed
---------- ------- ------- ------- ------
Test       Foo             1       Foo1
Test2              Bar     2       Bar2

As an alternative, you can use $_.Name -like 'Column*' -and $_.Value -ne 'null' as the property-filter if they are actually called ColumnXXX.

A: To complement Frode F.'s elegant ScriptProperty-based solution with a more concise PSv4+ version that also performs better due to avoiding the use of cmdlets (a pipeline) in the property-definition script block in favor of operators (with a large number of input objects, this may matter):
$o | Add-Member -PassThru -MemberType ScriptProperty -Name Joined -Value {
 @($this.psobject.Properties.Where({$_.Name -match 'Column*'}).Value) -ne 'null' -join ', '
}

Note the use of:

*

*The .Where() collection operator (PSv4+), a faster alternative to the Where-Object cmdlet.

*Member-access enumeration (PSv3+), where accessing a property at the collection level yields an array of the elements' property values;
e.g., $this.psobject.Properties.Name yields the .Name property values of all elements of the $this.psobject.Properties collection.

*Applying comparison operator -ne to an array-valued LHS, in which case the operator acts as a filter: the operator is applied to each element, and the matching elements are returned as an array; note the @(...) around the LHS, which ensures that it is treated as an array even if it happens to return only a single value.
With the sample data in the question, the above yields (look for property Joined):
Group_name : proxy_users
Column1    : domain\Igor
Column2    : null
Column989  : domain\Andrew
Column999  : domain\Mike
Joined     : domain\Igor, domain\Andrew, domain\Mike

With the above optimizations, you could even consider a simpler Select-Object solution that constructs new custom-object instances that contain all of the input object's properties (*) plus a new calculated property that contains the combined column values of interest:
$o | Select-Object *, @{ n='Joined'; e={
  @(($_.psobject.Properties.Where({$_.Name -match 'Column*'})).Value) -ne 'null' -join ', ' }
}

This solution is slower than the one above, but not by much.
A caveat is that if you collect all output in memory, the newly constructed objects take up space in addition to the originals.

Optional reading: Performance comparison; the impact of pipeline use:
The code at the bottom times the various approaches from Frode's and my answer.
Here's a sample timing from my machine - the absolute numbers aren't important, but their ratios are (though I don't know how factors such as CPU core count and disk speed would come into play) - input set size is 1000 objects:
Approach                                 TotalSeconds
--------                                 ------------
add-member w/ scriptproperty - operators 0.35
select-object w/ noteproperty            0.40
add-member w/ scriptproperty - pipeline  0.72
add-member w/ noteproperty - pipeline    0.98

Conclusions:

*

*The solutions that use pipelines in the property definition are noticeably slower, by a factor of about 2, which doesn't seem to vary even with larger input counts.

*The optimized Select-Object-based solution that creates new objects (rather than adding properties to the input objects) is only slightly slower than the optimized Add-Member solution.
Source code for the tests:
# The number of input objects to test with.
# Adjust to experiment.
$objCount = 1000

Write-Verbose -Verbose "# of input objects: $objCount"

$ndx = 0; $approaches = 'select-object w/ noteproperty',
                        'add-member w/ scriptproperty - operators',
                        'add-member w/ scriptproperty - pipeline',
                        'add-member w/ noteproperty - pipeline'
$tempFile = New-TemporaryFile # requires PSv5+
$(foreach($approach in $approaches) {

  # Create test collection (recreate it in every iteration to support repeated Add-Member operations)
  $al = [System.Collections.ArrayList]::new()
  for ($i = 0; $i -lt $objCount; ++$i) {
    $null = $al.add([pscustomobject] @{ one = 1; Column1 = 'col1'; Column2 = 'col2'; Column3 = 'null'; Column4 = 'col4' })
  }

  Measure-Command {

    Write-Verbose -Verbose "Running: $approach..."
    switch ($ndx) {
      0 { # select-object w/ noteproperty
        $al | Select-Object *, @{ n='Joined'; e={ @(($_.psobject.Properties.Where({ $_.Name -match 'Column*'})).Value) -ne 'null' -join ', ' } } |
          Export-Csv $tempFile
        break
      }

      1 { # add-member w/ scriptproperty - operators
        $al | Add-Member -PassThru -MemberType ScriptProperty -Name Joined -Value { @($this.psobject.Properties.Where({ $_.Name -match 'Column*'}).Value) -ne 'null' -join ', ' } |
          Export-Csv $tempFile
        break
      }

      2 { # add-member w/ scriptproperty - pipeline
        $al | Add-Member -PassThru -MemberType ScriptProperty -Name Joined -Value { ($this.psobject.Properties | Where-Object { $_.Name -match 'Column*'  -and $_.Value -ne 'null' } | Select-Object -ExpandProperty Value) -join ', ' }  |
         Export-Csv $tempFile
         break
        }

        3 { # add-member w/ noteproperty - pipeline; requires an intermediate ForEach-Object call
          $al | ForEach-Object {
            $_ | Add-Member -PassThru -NotePropertyName Joined -NotePropertyValue (($_.psobject.Properties | Where-Object { $_.Name -match 'Column*' -and $_.Value -ne 'null' } | Select-Object -ExpandProperty Value) -join ', ' )
          } |
            Export-Csv $tempFile
        break
      }
      default { Throw "What are you doing here?" }
    }

    # Import-Csv $tempFile | Select-Object -First 1 Joined | Write-Verbose -Verbose

    ++$ndx

  } | Select-Object @{ n='Approach'; e={ $approach }}, @{ n='TotalSeconds'; e={ '{0:N2}' -f $_.TotalSeconds } }

}) | Sort-Object { [double] $_.TotalSeconds }

Remove-Item $tempFile


text:
Q: What is this "fixing the build scripts" for compiling x264? I am trying to compile an all static build of source-customized ffmpeg libraries with the additional codecs from VideoLAN, such as their x264 codec. I am ultimately building for use in Windows with Visual Studio 2015 C++, so I am comparing a few compiling guides for my instructions.
In the guide linked below (I located via Google searches) shows how to compile x264 with the VS2015 toolchain in MSYS2 without any special steps:
https://gist.github.com/RangelReale/3e6392289d8ba1a52b6e70cdd7e10282
While in this other guide, offered by the compiling guide pages from ffmpeg's web site, it includes steps for "fixing the build scripts" for x264:
https://www.roxlu.com/2019/062/compiling-ffmpeg-with-x264-on-windows-10-using-msvc
Problem being, when I "fix the build scripts" the configure script no longer finds a C compiler. Building with the first guide seems to work, but it was also written nearly 2 years ago, so perhaps the ffmpeg guide is doing some important fix? I don't know.
I am:

*

*Running a "VS2015 x64 Native Tools Command Prompt"

*launching a pacman loaded msys2 shell via "msys2_shell.cmd -mingw64 -use-full-path"

*git cloning http://git.videolan.org/git/x264.git
and at this point the two compiling guides vary, the first guide just cd's into x264 and runs configure while the other guide does some curl download of a config.guess file and then some sed manipulation of ./configure. Considering these instructions are "endorsed" by the ffmpeg site, I am left wondering what that is doing and how critical is it that these "special" steps cause my x264 configure to fail.

A: All this manipulations with "config.guess" and "configure" are only needed because later on they run simple "msys2_shell.cmd" i.e. in MSYS-mode. Correct/supported way in x264 is to run shell in MINGW32 or MINGW64 mode with "-mingw32" and "-mingw64" options like you do (or run mingw32.exe / mingw64.exe instead of msys2_shell.cmd). This change result in different output of "uname" command which is important for x264's configure.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Laravel 5.4: logout keep redirecting me to an unexisting URI I'm learning laravel 5.4 from laracast and in episode 19, where I should create a user session system.
So, for now, I can register a new user, log him in but I can't logout. this method keeps redirecting me to an unexisting uri "app.dev/home".
Here is the method:
public function destroy()
{
    Auth::logout();
    return redirect('/');
}

and here are all the routes
Route::get('/', 'PostsController@index')->name('home');
Route::get('/posts/{post}', 'PostsController@show');
Route::get('/post/create', 'PostsController@create');
Route::post('/posts', 'PostsController@store');
Route::post('/post/{post}/comment', 'CommentsController@store');
Route::get('/tasks', 'TasksController@index');
Route::get('/tasks/{task}', 'TasksController@show');
Route::get('about', function () {
return view('about');
});
// Auth::routes();
//Route::get('/home', 'HomeController@index');
Route::get('/register', 'RegistrationController@show');
Route::post('/register', 'RegistrationController@store');
Route::get('login', 'SessionController@create');
Route::post('login', 'SessionController@store');
Route::get('/logout', 'SessionController@destroy');


text:
Q: How do I make and access shared instances of a LocalDB instance? I installed the LocalDB component (only) from SQL Server 2019 Express on a Windows 10 machine that had NO Sql Server installation of any kind.  I installed SSMS next.
The AUTOMATIC instance MSSQLLOCALDB works as advertised.  I can use SSMS to access it, add a database, perform queries, everything is fine.
I want to make this instance shared.
So I typed (from Powershell) sqllocaldb share MSSQLLOCALDB SharedDb
The shared instance is properly created.
PS C:\WINDOWS\system32> sqllocaldb i
.\SharedDb
MSSQLLocalDB
But I cannot access the shared instance from SSMS
Things I have tried

*

*Stopped and started the automatic instance

*used the servername as (localdb)\.\SharedDb as documented.

*tried it from sqlcmd where it works for the automatic instance, but fails for the shared instance.

*rebooted the machine

Fails with:
Sqlcmd: Error: Microsoft ODBC Driver 13 for SQL Server : Named Pipes Provider: Could not open a connection to SQL Server [2]. .
Sqlcmd: Error: Microsoft ODBC Driver 13 for SQL Server : Login timeout expired.
Sqlcmd: Error: Microsoft ODBC Driver 13 for SQL Server : A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online..
Any suggestions on how to share a LocalDB instance would be appreciated.  Thanks.

A: There is a known bug in SQL Server Version 2017 and newer that breaks the use of Shared Instance. Currently the only Option is to downgrade to SQL Server Version 2016.
Please Upvote this Issues  on the SQl Feedback Forum, hopfuly they will fix it eventually.
For an detailed explanation  of the problem view the answer on this Post


text:
Q: Android - Display progress bar when certain operation is done by another thread How to block UI thread from doing anything and just displaying a progress bar until certain condition is met.
For example I have a list initialized to null, Lets call it list. I start another thread in UI to initialize its value which is going to take around 10 seconds. How can I block UI thread displaying progress dialog until the list is initialized.
// Initially
List list = null;

// Display progress bar until certain condition is met
while(list == null){
    // Display progress dialog
}

I think AsyncTask will work if we ask that AsyncTask to update the list etc, what about another thread doing it. I have tried to simplify the problem.

A: you need to create a public method in mainActivity, named for examble yourcallback()
instead of instantiating all the objects in the OnCreate mainActivity, you can instantiate all objects in addition to quell ic you need for the progressbar in the callback method
yourcallback()
your callback
now you need to create an extenction of AsyncTask where you declare a base method constructor
like this
     privte Activity mainObj;
     public TestAsyncTask(Context context, Activity mainact ) throws Exception {
       mainObj=mainact
       your code
     }

when the task naturally terminate the class AsyncTask call onPostExecute method
     protected void onPostExecute(Long result) {
        mainObj.yourcallback();
  }

hope this help!


text:
Q: Mysqli query are not fetching database values I am trying with php 7.0 as everyone recommend me here to start with it as 5.6 has been depreveted . But after writing its code i am unable to fetch the values from database. what wrong i am doing here. thank you
//This is my aboutus page//

    <?php  include('config.php');
    $query = mysqli_query('select * from about ');
    while($row = mysqli_fetch_array($query)){
    ?>

    <?php echo $row['about_desc'] ;?>

    <?php echo $row['about_desc1']; ?>

    <?php echo $row['about_desc2'] ;?>

    <?php echo $row['about_desc3'] ;?>

    <?php echo $row['about_desc4']; ?>

    <?php
    }
    ?>

    <?php  include('config.php ');
    $query = mysqli_query('select * from news LIMIT 0,2');
    while($row = mysqli_fetch_array($query)){
    ?>

<?php echo $row['news_name']; ?>

<?php echo $row['dat']; ?>

<?php echo $row['news_desc']; ?>

        se mer >>

    <?php
    }
    ?>

//This is my config.php file//
<?php
$connection = mysqli_connect('localhost','root','','dandelion') or die(mysqli_error($connection));
?>

Looking for good suggestion as a learner. thank you

A: Your About us page should be like this:

                                    <?php  include('config.php');
                    $query = mysqli_query($connection, 'select * from about ');
                    while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
                       ?>

                        <?php echo $row['about_desc'] ;?>

                                                    <?php echo $row['about_desc1']; ?>

                                                            <?php echo $row['about_desc2'] ;?>

                                                                    <?php echo $row['about_desc3'] ;?>

                                                                            <?php echo $row['about_desc4']; ?>

                                        <?php
                                        }
                                        ?>

                                     <?php  include('config.php ');
                                    $query = mysqli_query($connection, 'select * from news LIMIT 0,2');
                                    while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
                                       ?>

<?php echo $row['news_name']; ?>

<?php echo $row['dat']; ?>

<?php echo $row['news_desc']; ?>

                                        se mer >>

                                    <?php
                                    }
                                    ?>

A: if your database connection is sucessfully work and problem with fetching data than use number.it may be useful to fetch the data.
<?php echo $row[o]; ?>
<?php echo $row[1]; ?>

instead of
<?php echo $row['about_desc1']; ?>


text:
Q: How to disable/remove outlook on windows xp professional? I have a windows xp machine which has been installed with Microsoft Office 2007. I would like to disable the outlook access only for other admin/power users on the same.

A: Can you explain correctly? You want to remove Outlook Express/ Outlook 2010 for certain people only or everyone?
For everyone:
For Outlook Express it's listed in Control Panel/ Add or Remove Component / Add Remove Windows component and in the list uncheck Outlook express.
For Outlook, the easiest way is to rerun the Office setup, choose to customize the install and remove outlook.
For specific users it could be difficult

A: My only thought on this is to password protect your .pst file, I'm not even sure if you can do that in 2007.
This method works in 2003, hopefully 2007 is the same:
Open outlook, right click on your personal folder, select properties, select advanced, change password. Your original password is probably blank, enter a new password and verify. Now whenever you open Outlook it will prompt you for a password.


text:
Q: Передать data-title в div

$('.btn_text').click(function() {
  let formTitle = $('.btn_text').data('title');
  $('.form-title').html(formTitle);
});

Привет 1
Привет 2

При первом клике название из data-title передается как надо и попадает в div, но при клике на следующую кнопку (Привет 2), название остается прежним из (Привет 1), не меняется, в чем проблема?

A: Ваша ошибка в том, что необходимо вытаскивать атрибут.

$('.btn_text').click(() => {
  const formTitle = $('.btn_text').attr('title');
  $('.form-title').html(formTitle);
});
.btn_text {
  width: 100px;
  margin-top: 5px;
  padding 5px;
  text-align:center;
  user-select: none;
  cursor:pointer;
  background: cadetblue;
  border-radius: 5px;
  box-shadow: 0px 0px 10px grey;
}
.btn_text:active {
  box-shadow: none;
}

  default

  Header

Текст не меняется(визуально) потому, что вы присваиваете одно и то же значение. Вот пример с новыми значениями:

// Возвращает случайное число между min (включительно) и max (не включая max)
function getRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min;
}

$('.btn_text').click(() => {
  let formTitle = $('.btn_text').attr('title');
  formTitle += getRandomArbitrary(10,19);
  $('.form-title').html(formTitle);
});
.btn_text {
  width: 100px;
  margin-top: 5px;
  padding 5px;
  text-align:center;
  user-select: none;
  cursor:pointer;
  background: cadetblue;
  border-radius: 5px;
  box-shadow: 0px 0px 10px grey;
}
.btn_text:active {
  box-shadow: none;
}

  default

  Header

Пример с несколькими элементами (самое простое — добавить пользовательский атрибут):

// Возвращает случайное число между min (включительно) и max (не включая max)
function getRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min;
}

$('.btn_text').click(function() {
  let element = $(this);
  let title = $(element).attr('title');
  const id = $(element).attr('data-id');
  title += getRandomArbitrary(10,19);
  $(`.form-title-${id}`).html(title);
});
.btn_text {
  width: 100px;
  margin-top: 5px;
  padding 5px;
  text-align:center;
  user-select: none;
  cursor:pointer;
  background: cadetblue;
  border-radius: 5px;
  box-shadow: 0px 0px 10px grey;
}
.btn_text:active {
  box-shadow: none;
}

  default1

  Header1

  default2

  Header2

Ваш пример:

$('.btn_text').click(function(evet) {
  event.preventDefault();
  const formTitle = $(this).attr('title');
  $('.form-title').html(formTitle);
});

Привет 1

Привет 2

Вы не правильно брали пользовательский атрибут, который вам и не нужно инициализировать. У тега  есть свой атрибут title.

Функция getRandomArbitrary() взята с developer.mozilla.org.

A:

var ids = document.getElementById('input-city');
var lis = [...document.querySelectorAll("ul li")];
var linx = [...document.querySelectorAll("ul li a")];

for (var i = 0; i < lis.length; i++) {
  lis[i].onclick = function(e) {
    e.preventDefault();
    ids.innerHTML = this.getAttribute('data-value')
  }
}

Город 1

Город 2

Город 3


text:
Q: Keystone JS retrieve row ID in HTML table I'm having some trouble to update some info :
I have an array where each line is a form. Here what it looks like in jade :
each info in infos
    form(method="post")
        input(type='hidden', name='action', value='save')
        td
            input(value='#{info.name.full}' disabled).form-control
        td
            input(value='#{info.field}' disabled).form-control
        td
            input(value='#{info.field1}' disabled).form-control
        td
            input(value='#{info.field2}' disabled).form-control
        td
            input(value='#{info.field3}' disabled).form-control
        td
            input(value='#{info.field4}' disabled).form-control
        td
            input(value='#{info.field5}' disabled).form-control
        td
            input(value='#{info.field6}' disabled).form-control
        td
            input(value='#{info.field7}' disabled).form-control
        td
            select(name='status').form-control
                option(value="")=(require)
                option(value="bla")="Bla"
                option(value="blabla")="Bla bla"
                option(value="blablabla")="Bla bla bla"
                option(value="blablablabla")="Bla bla bla bla"
        td
                button(type='submit').btn.btn-primary Save

And I'd like to be able to save each line but I can't retrieve the ID when clicking on "save".
My JavaScript looks like this :
view.on('post', { action: 'save' }, function (next) {

    var application = new Info.model();
    var updater = application.getUpdateHandler(req);

    updater.process(req.body, {
        flashErrors: true
    }, function (err) {
        if (err) {
            locals.validationErrors = err.errors;
        } else {
            locals.updateSubmitted = true;
        }
        next();
    });

});

But I guess I don't understand how the updateHandler works.
Does anyone have an idea of how to save the row by retrieving the ID ?

A: To solve it, I added
input(type='hidden', name='id', value='#{info.id}')

Just after
input(type='hidden', name='action', value='save')

Then I had access to the data with :
console.log(req.body.id);
console.log(req.body.item1);

And I updated my table like that :
    Info.model.findByIdAndUpdate(req.body.id, { $set: {field1: req.body.item1, field2: item2}},
            function(err, info) {
            if (err) {
                next(err);
            }
    });

Hope this will help some of you.


text:
Q: " expected" in constructor method I'm just starting out with Netbeans and I ran into a problem trying to write a new class.
public class DeliveryList<T> extends ArrayList<T>
{
    public DeliveryList<T> // <identifier> expected
    {
    }
}

Netbeans throws this error at me and I'm not quite sure what to do.

A: Try this - read Java generics tutorial pages.
class DeliveryList<T> extends ArrayList<T>
{
  public <T>DeliveryList() {}
}


text:
Q: Spring framework IDE - where to learn efficently? im looking at spring right now and im not sure how to use it in most efficent way as im not sure if it does not have some features or do i need some special way to enable them.
Question: What resources would you recommend to pick up quickly the tools necessary for quick and easy java jsf/spring development?
Some of the problems i saw so far:

*

*Spring IDE does not help me in beans.xml. In netbeans once i add schemas to my netbeans.xml i have very pretty auto completion so that beans xml becomes really quick and easy, does spring ide have this kind of feature? how do i enable it?

*validation - seems like i can easily make mistakes in the app configuration and things like misspelled beans, calss names in xml etc go unnoticed untill the runtime. Is there any way to enable better validation for this kind of problem? I can see netbeans is bad at it asa well. EL is not validated, benas in jsf projects are not validated. Many things that could be checked fail in runtime.

*in netbeans EL auto completion does not work for some of my beans
etc

A: Mannings Spring in Action book (http://www.manning.com/walls3/) is an excellent resource for getting into the Spring framework.


text:
Q: Elements fail to form a basis Consider the vector space $P^2$ and the set
$$5−1t+4t^2,−4+3t+1t^2,8+5t+kt^2$$
For which $k \in \mathbb{R}$, do these three elements fail to be a basis of $P^2$?
I thought in order to make the three elements fail to be a basis, one of the elements must be redundant. But I have no idea how to make one of the elements a linear combination of the other two.
I tried
$$-2(5−1t+4t^2)+−4+3t+1t^2=-14+5t-7t^2=8+5t+kt^2$$
which makes $-22=(k+7)t^2$
But I do not what the value of $t$ is. So I was stuck. Am I even on the right track?

A: Hint
Consider a linear combination of these three vectors which equals the zero vector (polynomial)
\begin{align*}
x(5−1t+4t^2)+y(−4+3t+1t^2)+z(8+5t+kt^2) & =\mathbf{0}\\
t^2(4x+y+kz)+t(-x+3y+5z)+(5x-4y+8z) & = \mathbf{0}\\
\end{align*}
By linear independence of $1,t,t^2$ we get the following system:
$$
\begin{bmatrix}
4&1&k\\
-1&3&5\\
5&-4&8
\end{bmatrix}
\begin{bmatrix}
x\\y\\z
\end{bmatrix}
=\mathbf{0}.
$$
Now you want a non-trivial (non-zero) solution to this system. So find a $k$ which makes this matrix non-invertible etc...


text:
Q: Invoke a unix shell from java program?read and write a steady stream of data to and from a unix pipe from java program I have 2 questions
1) how do I i invoke a unix shell from a java.runtime library to run a command like this
Process p = Runtime.getRuntime().exec(commands);
cat alias > bias
2) How can I read and write to a unix pipe a steady stream of data from java.
Do i have to make all the system calls like open read write to a pipe
I basically want to replicate this command
cat alias > bias
where the steady stream of data will be come from  java program to bias and not cat alias.

A: Since JDK7, there is a convinience way to do this:
ProcessBuilder pb = new ProcessBuilder("cat", "alias");
File bias = new File("bias");
pb.redirectOutput(Redirect.appendTo(bias));
pb.start();

Reference: ProcessBuilder#redirectOutput

A: You can invoke a Unix shell like you would invoke any other program. Use the -c option to pass the command to run as a parameter. Also make sure to use the exec(String[]) method, and not exec(String), to avoid the command being tokenized the wrong way:
String[] cmd = {"/bin/sh", "-c", "/bin/cat alias > bias"};
Process p = Runtime.getRuntime().exec(cmd);

To read and write from/to the process, get the input, output, and error streams from the Process instance you just created:
InputStream in = p.getInputStream();
InputStream err = p.getErrorStream();
OutputStream out = p.getOutputStream();

Then read from/write to these streams as usual.
Note that streams are named relative to the Java application. Anything written to the OutputStream is piped to the standard input of the process you created. Anything written by the process to stdout/stderr is piped to the InputStreams obtained from p.getInputStream() and p.getErrorStream() respectively.
Reference: http://download.oracle.com/javase/6/docs/api/java/lang/Process.html

A: You can't use ">" directly in a Runtime.exec() command. It won't have the expected effect, and will not redirect the output to the file.
You have to get the input stream of your process and redirect it to the file to write:
Process p = Runtime.getRuntime().exec(new String[] {"cat", "alias"});
InputStream in = p.getInputStream();
FileOutputStream fos = new FileOutputStream("yourFile");
// Write in into fos...
// handle the process streams

I don't detail the writing method but:

*

*you have to handle the exceptions (IO)

*you have to consume (at least to close) all the process streams (error, input, output).


text:
Q: How transpose array of mixed data in efficient way in HANA XS / Javascript I have to transpose data of a HANA table into an array on which to create a json model, so I've got an array like:
[COLOR, TYPE, INFO, DAY, VALUE]
COLOR, TYPE and DAY is the Primary Key and period is the same for all keys:
[BLACK,JEANS,Info01,2020-12-01,25], //start period
[BLACK,JEANS,Info01,2020-12-02,22],
[BLACK,JEANS,Info01,2020-12-03,18],
[BLACK,JEANS,Info01,2020-12-04,33], //end period
[WHITE,SHIRT,Info02,2020-12-01,15], //start period
[WHITE,SHIRT,Info02,2020-12-02,12],
[WHITE,SHIRT,Info02,2020-12-03,58],
[WHITE,SHIRT,Info02,2020-12-04,63], //end period

I would like to transpose it to get the following array:
[BLACK,JEANS,Info01,25,22,18,33],
[WHITE,SHIRT,Info02,15,12,58,63],

Is there an efficient way to do it?

A: Assuming same dates in order.
You could use a joined key for the first three items and collect the values.

const
    data = [['BLACK', 'JEANS', 'Info01', '2020-12-01', 25], ['BLACK', 'JEANS', 'Info01', '2020-12-02', 22], ['BLACK', 'JEANS', 'Info01', '2020-12-03', 18], ['BLACK', 'JEANS', 'Info01', '2020-12-04', 33], ['WHITE', 'SHIRT', 'Info02', '2020-12-01', 15], ['WHITE', 'SHIRT', 'Info02', '2020-12-02', 12], ['WHITE', 'SHIRT', 'Info02', '2020-12-03', 58], ['WHITE', 'SHIRT', 'Info02', '2020-12-04', 63]],
    result = Object.values(data.reduce((r, a) => {
        const
            keys = a.slice(0, 3),
            key = keys.join('|');
        r[key] = r[key] || keys;
        r[key].push(a[4]);
        return r;
    }, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


text:
Q: Add more items to same Row and same column in listview I know how to add/delete items but I don't know how to add more items to the same field (same row and same column). I want whenever I click a button, an item is added to same selected row but not to new row in the listView.
I uploaded a photo you can check to see what I exactly mean.

A: Consider looking at ObjectListView or DataGridView instead of what you are currently. It may be more flexible to your needs.
Your question is somewhat unclear. Clearly you are using listView and you have columns and rows resulting in a cell / box / grid location. I gather that, after its initial creation, you wish to append or alter the data at that location.
To get to the point: Multi-line text within a given 'cell' is not supported (as best I can tell). The picture you have shown is likely a custom object or something similar to a listView, but different (such as a ObjectListView). Or perhaps a picture.
listView2.Items[0].SubItems[4].Text = "123\nabc"; //Doesn't add a proper newline like a normal string

listView2.Items[0].SubItems[4].Text = "123\rabc"; //Doesn't add a proper return carriage like a normal string

listView2.Items[0].SubItems[4].Text = "123\r\nabc"; //Doesn't add a proper newline like a normal string

I am assuming you are using the details view
listView1.View = View.Details;

First adding your headers, listView1.Columns.Add(text, width);
listView1.Columns.Add(First Name", 50);
listView1.Columns.Add("Middle Name", 100);
listView1.Columns.Add("Last Name", 100);

You then add data to the listView. However, this is not done directly. You build a listViewITEM then add that item to the list view.
string[] row = new string[3];
row[0] = "john";
row[1] = "someone";
row[2] = "doe";

ListViewItem lvi = new ListViewItem(row);

listView1.Items.Add(item);

listView1.SelectedItems[#].SubItems[#].Text = "string" + "\n" + "string2";
CrazyPaste suggested adding a row, which could be practical and is something you often see with listViews.
However, If you choose to add or "redo" the rows, be sure to remove any old information before inputting new information to avoid duplicates.
Taken from the popup within visual studio 2013 pro
listView1.Items.RemoveAt(int index)
listView1.Items.Insert(int index, string key, string text, int imageIndex)

OR
listView1.Items.Clear(); //Clears all items

then
//Add populate logic here

Two arrays or a multidimensional array in a loop would be effective if you wish to populate the listview in that manner.
To achieve this programmatically, you could...
        listView2 = new ListView();
        listView2.View = View.Details;
        listView2.Location = new Point(50, 50);
        listView2.Size = new Size(400, 100);

        this.Controls.Add(listView2);

        listView2.Columns.Add("AAA");
        listView2.Columns.Add("BBB");
        listView2.Columns.Add("CCC");
        listView2.Columns.Add("DDD");
        listView2.Columns.Add("EEE");

        ListViewItem item1 = new ListViewItem();
        item1.Text = "0"; //The way to properly set the first piece of a data in a row is with .Text
        item1.SubItems.Add("1"); //all other row items are then done with .SubItems
        item1.SubItems.Add("2");
        item1.SubItems.Add("3");
        item1.SubItems.Add("");
        item1.SubItems.Add("");

        ListViewItem item2 = new ListViewItem();
        item2.Text = "00";
        item2.SubItems.Add("11");
        item2.SubItems.Add("22");
        item2.SubItems.Add("33");
        item2.SubItems.Add("");
        item2.SubItems.Add("");

        ListViewItem item3 = new ListViewItem();
        item3.Text = "000";
        item3.SubItems.Add("111");
        item3.SubItems.Add("222");
        item3.SubItems.Add("333");
        item3.SubItems.Add("");
        item3.SubItems.Add("");

        //item1.SubItems.Clear();
        //item1.SubItems.RemoveAt(1);
        listView2.Items.Add(item1);
        listView2.Items.Add(item2);
        listView2.Items.Add(item3);
        //listView2.Items.Insert(2, item1); //0 here is the row. Increasing the number, changes which row you are writing data across

        listView2.Items[0].SubItems[4].Text = "123\rabc";

To 'update' the information:
listView1.Items.Clear();
listView1.Items.Add(item1);
listView1.Items.Add(item2);

...etc
NOTES:

*

*I was not able to get .Insert to work with subitems.

*If you already inserted a listViewItem, You cannot insert an item
without first removing it

*SubItems are not automatically created to fill empty space. Commands like 'listView2.Items[0].SubItems[4].Text' will not work with null/non-existent SubItems

A: I don't have much to go on.  But this adds a new row:
string[] row = { "1", "snack", "2.50" };
var listViewItem = new ListViewItem(row);
listView1.Items.Add(listViewItem);

Here's a post discussing how to update an existing listitem:
C#: How do you edit items and subitems in a listview?

A: Ok. after I searched the internet for ages, it turned out that listView does not support text wrap. so instead I used DataGridView. thank you for your help


text:
Q: How to programmatically scroll TreeView control? Please advice how can I scroll a .NET TreeView Control programmatically.
It doesn't implemented any public methods to scrolling.

A: If you need to scroll to the node:
TreeNode.EnsureVisible();

A: Try this:
treeView1.TopNode = treeView1.Nodes[500];

EDIT
Maybe more suggestive :-)
    private void Form1_Load(object sender, EventArgs e)
    {
        for (int i = 0; i < 100; i++) {
            TreeNode node = treeView1.Nodes.Add(i.ToString());
            for (int j = 0; j < 10; j++) {
                node.Nodes.Add(j.ToString());
            }
        }
    }

    private void ScrollNode(TreeNode node) {
        treeView1.TopNode = node;
        treeView1.Refresh();
        System.Threading.Thread.Sleep(50);
        if (node.IsExpanded) {
            foreach (TreeNode subNode in node.Nodes)
                ScrollNode(subNode);
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        treeView1.Focus();
        foreach (TreeNode node in treeView1.Nodes) {
            ScrollNode(node);
        }
    }

A: Just select and unselect the lowest item. That should do the trick.


text:
Q: How to change default browser for wine steam game? I want to play windows steam game (duel link) on linux.
Game is working fine, but when I login with my game account.
Its open linux browser (firefox).
I login in in firefox then it say "login process, this window will automatically close when its done"
Im waiting more than 10m, but firefox still not closing.
And game waiting login success from browser.
I rasisme its because linux browser cant work well with wine.
Im install firefox in my wine too. But the game still opening linux browser.
What i ask.
How to set wine browser (firefox) as my default browser game wine?

A: Have you tried just downloading steam through synaptic/ whatever default software installer is on your computer? Steam is supported in linux, so you can log in through the client without the need for WINE and a browser.
If you do need wine to run the game, I suggest downloading winetricks though the terminal with these commands:
wget  https://raw.githubusercontent.com/Winetricks/winetricks/master/src/winetricks
chmod +x winetricks

then run it. click ok. select install a windows dll. choose a web browser to download.

A: If you use Q4wine, there is a Wine Browsers setting tab for default browser in Q4Wine Setup > System > Update Fake Drive setting dialog. I think it does sth. similar as below, but a lot better.
This may or may not work for steam game, but worked for my work application:

*

*Follow this to set the class handlers right.
http://www.webupd8.org/2010/03/how-to-make-wine-open-links-in-your.html
in short :

*

*In regedit find HKCU> Software> Wine> WineBrowser set Browsers to xdg-open,firefox,konqueror,mozilla,netscape,galeon,opera,dillo

*Find HKCR> https/http/htmlfile> shell> open,  set command to: C:\windows\system32\winebrowser.exe -nohome "%1"

*Now it should work, but not in my case...

*My app is a 64-bit exe, this simply doesn't work after the setup, need some fiddling, try:

WINEDEBUG=warn+all wine myworkapp

After trigged the launch action in the work app, in the console you should see debug info about what is missing. In my case:

01a4:warn:ntdll:NtQueryAttributesFile L"\??\C:\windows\system32\winebrowser.exe" not found (c0000034)

which is weird, since there exists ~/.wine/drive_c/windows/system32/winebrowser.exe

wine cmd
echo 1 > c:\windows\system32\mark1

mark1 is in ~/.wine/drive_c/windows/syswow64, so just a symbolink will fix it.

cd ~/.wine/drive_c/windows/syswow64
  ln -sf ../system32/winebrowser.exe winebrowser.exe

Now it works, though the workapp still complain default browser not found, the long link opens fine in linux browser.


text:
Q: Deno unit testing error No such file or directory (os error 2) Hey dont know if im being silly im trying to learn unit testing with deno and keep getting this error im using puppeteer if thats relevant cant figure out whats wrong it seems to be pointing to the await in this line
const browser = await puppeteer.launch({ headless: true })
Deno.test('log in with invalid username/password', async test => {
    // GIVEN I am on the "Log In" page
            const browser = await puppeteer.launch({ headless: true })
            const page = await browser.newPage()
            await page.goto(url, { waitUntil: 'networkidle0' })
            await page.click('a[href="/login"]', { waitUntil: 'networkidle0' })
    // WHEN I enter "fakeuser" in the username field
            await page.type('input[name="username"]', 'fakeuser')
    // AND I enter "fakepassword" in the password field
            await page.type('input[name="password"]', 'fakepassword')
    // AND I click on the login button
            await page.click('input[type="submit"]', { waitUntil: 'networkidle0' })
    // THEN I should be returned to the "Log In" page
            const heading = await page.$eval('h1', node => node.innerText)
            await assertEquals(heading, 'Log In', 'invalid credentials dont send user back to login page')
            await browser.close()
})

error code image

A: So it seems to me that puppeteer throws an error when trying to load your html-file of the login page or the page you're refering to when submitting your login form.
But there is to little information given in order to make a qualified response.
Could you please provide more background information as well as tell the specific line with the line number 72. In line 72 the error is being brought up in your test file. (Note that the line number could have been changed since your post if you added or deleted some lines in your test file, so check the line number in a fresh error output.)


text:
Q: Как обойти ошибку "WinSock.h has already been included" при сборке OSRM в Visual Studio? Я только начал делать форк этой библиотеки и уже столкнулся с ошибкой конфликта файлов WinSock.h и включенной в boost WinSock2.h. Определение константы WIN32_LEAN_AND_MEAN перед include <windows.h> не решило проблему. Возможно, мне ее следует определить в другом месте.
A: Если такие сложности возникают при сборке MSVS, то попробуйте Mingw - авось, будет проще.


text:
Q: How to convert a string to a URI without throwing exceptions I had to convert a Uri to a string so that I could serialize that Uri.
Intent openFileIntent = new Intent(Intent.ACTION_GET_CONTENT);
openFileIntent.addCategory(Intent.CATEGORY_OPENABLE);
openFileIntent.setType("audio/mpeg");
startActivityForResult(openFileIntent, PICK_MP3_FILE);

...then on activity result...
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_MP3_FILE)
        {
            if (resultCode == RESULT_OK)
            {
                try
                {
                    if (data != null)
                    {
                        Uri mp3AudioFile;
                        if ((mp3AudioFile = data.getData()) != null)
                        {
                            myObject.setMp3Path(mp3AudioFile.getPath());
                            myObject.Save();

                        }
                    }
                } catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

I closed the app and opened again. When I try to open that Uri with:
Uri uri = Uri.parse(myObject.getMp3Path();

I get an error:
java.lang.SecurityException: Permission Denial: reading com.android.providers.downloads.DownloadStorageProvider uri content://com.android.providers.downloads.documents/document/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2Faudio.mp3 from pid=601, uid=10107 requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs

My Manifest has the following permissions:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.STORAGE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

A: We need to provide persistent Uri permission.

JAVA
 Intent openFileIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
 openFileIntent.addCategory(Intent.CATEGORY_OPENABLE);
 openFileIntent.setType("audio/mpeg");
 startActivityForResult(openFileIntent, PICK_MP3_FILE);

Also, a note worth mentioning is persistent permission is available only to Intent.ACTION_OPEN_DOCUMENT and NOT Intent.ACTION_GET_CONTENT whereas the latter one is like a one-time thing.

A:

To do that I used getPath().

You should use toString() instead.
 String scheme = uri.toString();

 Uri uri = Uri.parse(scheme);

A: The permission denial issue needs to be dealt with the first time you receive a URI.
    private val pickImage = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result: ActivityResult ->
        if (result.resultCode == Activity.RESULT_OK) {
            //  you will get result here in result.data
            val uri = result.data?.data!!
            requireActivity().contentResolver.takePersistableUriPermission(
                uri,
                Intent.FLAG_GRANT_READ_URI_PERMISSION
            )
            // Do something else with the URI. E.g, save the URI as a string in the database
        }
    }


text:
Q: Show that $\int_{0}^{n} \left (1-\frac{x}{n} \right ) ^n \ln(x) dx = \frac{n}{n+1} \left (\ln(n) - 1 - 1/2 -...- 1/{(n+1)} \right )$ The problem is stated as:

Show that $\int_{0}^{n} \left (1-\frac{x}{n} \right ) ^n \ln(x) dx = \frac{n}{n+1} \left (\ln(n) - 1 - 1/2  -...- 1/{(n+1)} \right )$

My attempt
First of all, we make the substitution $1-\frac{x}{n} = t$, we then have that the integral can be rewritten as:
$\int_{1}^{0} -n t^n \ln(n(1-t)) dt = \int_{0}^{1} n t^n \ln(n(1-t)) dt$
Using logarithmic laws, we can split the integral into two seperate ones as follows:
$\int_{0}^{1} n t^n \ln(n(1-t)) dt = \int_{0}^{1} n t^n \ln(n) dt + \int_{0}^{1} n t^n \ln(1-t) dt$
We calculate each integral from the sum above:
$ I_1 := \int_{0}^{1} n t^n \ln(n) dt = \frac{n}{n+1}\ln(n)$
$ I_2 := \int_{0}^{1} n t^n \ln(1-t) dt = -n\int_{0}^{1} t^n \sum_{k=1}^{\infty}\frac{t^k}{k} dt$
Since the radius of convergence of $\sum_{k=1}^{\infty}\frac{t^k}{k}$ is 1, and we are integrating from $0$ to $1$, we can interchange the order of limit operations. Meaning, we can calculate the integral first.
$ I_2 = -n\sum_{k=1}^{\infty}\int_{0}^{1}\frac{t^{(n+k)}}{k} dt = -\sum_{k=1}^{\infty} \frac{n}{k(n+k+1)} = \frac{-n}{n+1} \sum_{k=1}^{\infty} \frac{n+1}{k(n+k+1)}$
Using partial fraction decomposition, we have that $I_2$ can be written as:
$\frac{-n}{n+1}\sum_{k=1}^{\infty} \frac{n+1}{k(n+k+1)} = \frac{-n}{n+1} \sum_{k=1}^{\infty} \frac{1}{k} + \frac{n}{n+1}\sum_{k=1}^{\infty} \frac{1}{n+k+1}$
Putting it all together we get:
$I_1 + I_2 = \frac{n}{n+1} \left ( \ln(n) -  \sum_{k=1}^{\infty} \frac{1}{k} + \sum_{k=1}^{\infty} \frac{1}{n+k+1} \right )$
Which is indeed close the the result sought, however, I don't really know what to do with the last sums, and why I did wrong in choosing $\infty$ as an upper limit in the summation. I see that the sum of $1/k's$ diverge, but how can I avoid this?
Thank you for any help that could help me complete the last step of this problem.

A: Hint: $\sum_{k=1}^{\infty} \frac{1}{k}$ and $ \sum_{k=1}^{\infty} \frac{1}{n+k+1} $ are both infinity so you cannot write these sums separately. Instead, you should write $\lim_{N \to \infty}  [-\sum_{k=1}^{N} \frac{1}{k} +\sum_{k=1}^{N} \frac{1}{n+k+1}]$.
Now $[-\sum_{k=1}^{N} \frac{1}{k} +\sum_{k=1}^{N} \frac{1}{n+k+1}]$ simplifies to $\frac 1 {N+1}+\frac 1 {N+2}+..+\frac 1 {n+N+1}-(1+\frac 1  2+\frac 1  3+...+\frac 1 {n+1})$ (for $N>n+1$). Note that $\frac 1 {N+1}+\frac 1 {N+2}+..+\frac 1 {n+N+1} \to 0$ as $N \to \infty$.

A: Just for your curiosity
Assuming that you enjoy the gaussian hypergeometric function, there is an antiderivative
$$I_n(x)=\int \left (1-\frac{x}{n} \right ) ^n \log(x)\, dx=\frac 1{n^n}\int(n-x)^n \log(x)\,dx $$
$$I_n(x)=-\frac{(n-x)^{n+1}}{n^{n+1} (n+1) (n+2)}\Big[(n-x) \, _2F_1\left(1,n+2;n+3;\frac{n-x}{n}\right)+n (n+2) \log (x) \Big]$$
$I_n(n)=0$ and then
$$\int_0^n \left (1-\frac{x}{n} \right ) ^n \log(x)\, dx=\frac{n (\log (n)-\psi (n+2)-\gamma )}{n+1}=\frac{n }{n+1}\left(\log (n)-H_{n+1}\right)$$


text:
Q: Amplifyjs posting formData I am newbie to web development and I have a have a problem when saving a file to database. I am using MVC 4, knockoutjs 2.3.0,  jquery 2.03 and amplifyjs 1.1.0.
Here is how I want it to be done.
In my upload page I have a form:
<form id="uploadForm" name="uploadForm" action="~/Administration/UploadReports"       method="post" enctype="multipart/form-data">
    <input required type="file" name="fileToUpload" id="fileToUpload" accept="html, image/jpeg">
        <input type="submit" data-bind="click:submit" value="Ladda upp fil" />
        <input type="reset" value="Avbryt" />
    </form>

Then in my knockoutViewModel I have the code below:
 this.submit = function (model, element) {
                var test = $('#uploadForm')[0];
                var formData = new FormData(test);

                amplify.request({
                    resourceId: "uploadReport",
                    success: () => {
                        console.log("success");
                    },
                    error: () => {
                        console.log("error");
                    },
                    data: formData
                });
            };

So far every thing works fine. I end up here when I press the button in my form. But I think amplifyjs is doing something with my dataForm... Amplify.request is define as below:
amplify.request.define('uploadReport', 'AJAX', {
    url: '/Administration/UploadReports',
    type: 'POST',
    contentType: false,
    processData: false,
    cache: false
});

And in my controller it looks like this:
    [HttpPost]
    public ActionResult UploadReports(HttpPostedFileBase fileToUpload)
    {

        //Update the list of files
        var model = new AdministrationViewModel();

        byte[] result;

        using (var streamReader = new MemoryStream())
        {
            fileToUpload.InputStream.CopyTo(streamReader);
            result = streamReader.ToArray();
        }

        model.BetFiles = FileInserter.InsertFile(fileToUpload.FileName, fileToUpload.ContentType, fileToUpload.ContentLength, result).Value;

        return View("Reports", model);
    }

Can anyone help me to see what is the problem?
Regards, David

Here is what I get:

And this is what I expected to get:

A: Currently amplify.js does not support FormData in version 1.1.2.
Check this issue
https://github.com/appendto/amplify/issues/107
The possible solution is modify the library in this event subscription
amplify.subscribe( "request.ajax.preprocess", function(defnSettings, settings, ajaxSettings) {
        var mappedKeys = [],
            data = ajaxSettings.data;

        if (typeof data === "string" || Object.prototype.toString.call(data) === "[object FormData]") {
            return;
        }
......(omited)
)}

That way amplify will ignore the object passed if is a native FormData object. The settings in the request definition must include to avoid jQuery messing with your FormData object again
contentType: false
cache: false
processData: false

A: If I change the this.submit function in my knockout viewmodel to the code below it works as it should but i want to use amplify to get this.
 this.submit = function (model, element) {
                var test = $('#uploadForm')[0];

                var formURL = formObj.attr("action");
                var formData = new FormData(test);

                $.ajax({
                    url: formURL,
                    type: 'POST',
                    data: formData,
                    mimeType: "multipart/form-data",
                    contentType: false,
                    cache: false,
                    processData: false,
                    success: function (data, textStatus, jqXHR) {

                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                    }
                });

            };

and of course in my controller method I should return:
return Json(model.BetFiles);

Instead of a View.


text:
Q: Jboss getting sutck while running I am using jboss-4.2.3.GA.
I face this strange issue only when I start the server from cmd prompt. The execution is getting stuck. Like from the time I execute run.bat, if I have the cmd window open and right click on the window then server continues to work. When I move to other window then it stops. Again I want to open the cmd prompt and click some where on the screen and it resumes.
This happen while running the application also. I need to click on the cmd prompt after making some action in my application.
I am not sure if there is some issue with jboss or some issue with my windows command prompt. Any idea about his will much help.

A: Right click on the title bar of the cmd windows and choose Properties, select Options tab and select "Quick Edit Mode" and click ok. I don't know what exactly happens when I do that, but it fixed the above issue.


text:
Q: "property 'storeImage' not found on object type 'UICollectionViewCell' i'm trying to subclass cell in order to show images and when i try something like cell.storeImage.image = ...
it says "property 'storeImage' not found on object type 'UICollectionViewCell'
i have created a file of UICollectionViewCell and did a IBOutlet for UIImageView and then set the custom class in story board
then i #import the .h file and still get the error.
i don't know what i'm doing wrong.
is there a way i can show images without doing this?
my main file where the view controller is run is a UICollectionViewController

A: You need to instantiate your custom collectionViewCell
MyCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];

1) Give cell identifier in Storyboard editor menu.
2) Change cell class to your class in the same menu.


text:
Q: How to install and import Scipy, Numpy, NumExpr and others on M1 (Apple Silicon / Darwin-arm64)? I have an M1 processor from Apple, which is a new ARM64 architecture, and the binaries provided for many data science Python packages will not run on it, and compiling them fails in most cases.
Questions such as How to install SciPy on Apple Silicon (ARM / M1) or numpy build fail in M1 Big sur 11.1 offer many different answers, some of which work and most don't. However, even for those that manage to make the modules compile, I don't understand how I can make pip install my locally compiled packages instead of fetching them (and failing) from pypy.
How can I install numpy, scipy, numexpr and others as a dependency on a computer with an M1 processor?

A: *

*Install Miniforge with Homebrew to compile these modules locally: brew install miniforge.

*Install the modules you need with conda instead of pip: conda install numpy (and scipy, numexpr…).

*In the environment in which you install your dependencies (global, user or virtual environment with venv, pew or similar), install as you would usually, but let your package manager know to load these native modules you installed earlier by defining PYTHONPATH: prefix the install command with PYTHONPATH=/opt/homebrew/Caskroom/miniforge/base/pkgs/:$PYTHONPATH. For example: PYTHONPATH=/opt/homebrew/Caskroom/miniforge/base/pkgs/:$PYTHONPATH pip3 install.


text:
Q: multi-select drop-down results shows Array im using multi select drop down list im able to select the list i want to update in my database but when i see the results it shows "Array" Instead Of the Selection.
 <select class="selectpicker" multiple data-live-search="true" name="Attendedby" ng-model="Attendedby">
  <option>Mustard</option>
  <option>Ketchup</option>
  <option>Relish</option>
</select>

$('select').selectpicker();

i dont know why my results display Array, please help
Here is my php
        if($form_data->action == 'Edit')
        {
            $data = array(
                ':Attendedby' =>    $Attendedby,
                ':EndDate'    =>    $EndDate,
                ':Status'     =>    $Status,
                ':Remarks'    =>    $Remarks,
                ':id'         =>    $form_data->id
            );
            $query = "
            UPDATE cov9
            SET Attendedby = :Attendedby, EndDate = :EndDate, Status = :Status, Remarks = :Remarks
            WHERE id = :id
            ";

            $statement = $connect->prepare($query);
            if($statement->execute($data))
            {
                $message = 'Data Edited';
            }
        }
    }

A: First of all you need to edit the name of the select to Attendedby[] as it expects multiple values and then use something like this to get multiple data into one column:
$Attendedby = implode(', ', $_POST['Attendedby']);

source


text:
Q: Rails can't connect to external mysql server despite Privileges I run rails on my local dev environment but the mysql instance is on a separate server.
When trying to open a page in the app I get this error:
Access denied for user 'username'@'myhostname.lan' (using password: YES)
When I ssh into the server running mysql and run this command SELECT Host from mysql.user WHERE User='username'; I get the following:
+---------------------+
| Host                |
+---------------------+
| %                   |
| myhostname.lan      |
| localhost           |
+---------------------+

All of these entries were created with GRANT ALL PRIVIELEGES ON dbname.* TO ...
So why can I not connect given that both the any-host wildcard % is in the list as well as the hostname I try to connect from specifically?

A: Despite having same usernames these users are different for mysql.
Check that the password is set on all user entries and is what you expect it to be.
You can compare authentication_strings in mysql.user.


text:
Q: Getting R Error: Error in FUN(X[[i]], ...) : invalid 'type' (character) of argument > I am new to R. When I wrote this code:
aggregate(x= IP.Causes$TOTAL.by.Type,
          by= list(IP.Causes$Payment.Type),
          FUN=sum)

I got an error:
Error in FUN(X[[i]], ...) : invalid 'type' (character) of argument
How should I change that to the correct version? Thank you.


text:
Q: Unit test assignment of property inside ngOnInit after service gets data When unit-testing in angular, how can I test that property in map.component.ts userRole = 'Admin'? Right now it fails on Expected undefined to equal 'Admin'. I try to mock service that gets the real data with testData. I am complete beginner in unit testing, please help. Thanks!
map.component.ts
export class MapComponent implements OnInit, OnDestroy {
userRole:string
...
constructor(
    private zone: NgZone,
    public deskDialog: MatDialog,
    private userFloorService: UserFloorService,
    private _snackBar: MatSnackBar,
    private route: ActivatedRoute,
    private router: Router
  ) {}

async ngOnInit(): Promise<void> {
    const userData = await this.userFloorService.getUser().toPromise();
    this.userRole = userData.records[0].user_role;
    ...
}

user-floor.service.ts
export class UserFloorService {
public getUser(): Observable<any> {
    return this.http.get(
      `https://XXX`);
  }
}

map.component.spec.ts
class UserService {
  testData = {
    message: 'Succes',
    records: [
      {
        floor_id: 3,
        reservations: [
          {
            desk_id: 11,
            reservation_date: '2021-02-22',
            reservation_id: 585,
            user_id: 7,
          },
        ],
        user_gid: 'xxx',
        user_id: 7,
        user_role: 'Admin',
      },
    ],
  };
  public getUser(): Observable<any> {
    return of(this.testData);
  }
}

describe('MapComponent', () => {
  let component: MapComponent;
  let fixture: ComponentFixture<MapComponent>;
  let userService: UserFloorService;

  beforeEach(() => {
    userService = jasmine.createSpyObj(['getUser']);

    TestBed.configureTestingModule({
      declarations: [MapComponent],
      imports: [
        MatSnackBarModule,
        AppRoutingModule,
        HttpClientModule,
        BrowserModule,
        MatDialogModule,
        HttpClientTestingModule,
      ],
      providers: [{ provide: UserFloorService, useClass: UserService }],
    }).compileComponents();
    fixture = TestBed.createComponent(MapComponent);
    component = fixture.componentInstance;
    userService = TestBed.inject(UserFloorService);
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  describe('Given the component is loaded', () => {
    describe('When getUser returns mock data', () => {
      it('Then the userRole should be Admin', (done) => {
        userService.getUser().subscribe(() => {
          expect(component.userRole).toEqual('Admin');
          done();
        });
      });
    });
  });
});

A: First, I want to address two issues I see:

*

*Remove the HttpClientModule from your Test setup. Everything you need is provided by the HttpClientTestingModule. Same is for the spy on your UserService.
Check this post for how to correctly mock the httpClient in an Unit Test:
https://medium.com/netscape/testing-with-the-angular-httpclient-api-648203820712

*The async on your ngOnInit does not concern Angular whatsoever, it still treats it as synchronous. I personally consider using async on angular lifecycle hook a serious antipattern because you invite tons of race conditions and have to null-check etc. everything anyhow. For some reason, it keeps popping up ;) There is no gain and much pain to be had from using async there. See async/await in Angular `ngOnInit`
That being said, you should be able to achieve what you want with this using changeDetectorRef (https://angular.io/api/core/ChangeDetectorRef):
constructor(private readonly cdr: ChangeDetectorRef)

ngOnInit(): void {
 this.userFloorService.getUser().subscribe(users => {
     this.userRole = userData.records[0].user_role;
   this.cdr.detectChanges; // might require markForCheck here, try it out
  });
}

And afaik you have to manually call ngOnInit() in your test, it is not called by createComponent(...)

A: So I was able to get it working without making changes to ngOnInit by using beforeEach with async and done() callback in it() :
describe('MapComponent', () => {
  let component: MapComponent;
  let fixture: ComponentFixture<MapComponent>;
  let userService: UserFloorService;

  beforeEach(async() => {
    await TestBed.configureTestingModule({
      declarations: [MapComponent],
      imports: [
        MatSnackBarModule,
        AppRoutingModule,
        BrowserModule,
        MatDialogModule,
        HttpClientTestingModule,
      ],
      providers: [{ provide: UserFloorService, useClass: MockService }],
    }).compileComponents();
    fixture = TestBed.createComponent(MapComponent);
    component = fixture.componentInstance;
    userService = TestBed.inject(UserFloorService);
    fixture.detectChanges();
  });

  it('should be created', () => {
    expect(component).toBeTruthy();
  });

  it('userRole should be Admin', (done) => {
    console.log(done);
    expect(component.userRole).toEqual('Admin');
    done();
  });

});

But thanks for help, you've ponited me in the right direction.


text:
Q: Reversing a singly linked, sentinel based, list recursively (works, but not in the way I'd like it to) I'm preparing for interviews and wrote up this simple function for recursively reversing a singly linked list.  The first node is a sentinel node, head. The following code works fine for: list.reverse(list.head.next), but I can't seem to get it to work if I just pass it head.
public Node<T> reverse(Node<T> current)
{
    if (current == null)
        return head;

    if (current.next == null)
    {
        head.next = current;
        return current;
    }

    reverse(current.next).next = current;
    current.next = null;
    return current;
}

I assume it doesn't work when I pass it head instead of head.next because I say current.next = null, but even if I check if current == head or if current.data == null and only use current.next = null when those aren't true, it still doesn't work.  I'm sure there's a really simple fix, but I'm just not seeing it right now.
The above if passed head returns an empty list, and if the suggested changes are made, simply doesn't finish running, but I don't get any sort of error.

A: (EDITED)
I kind of get your problem now:
Simply speaking, the sentinel head acts simply as a pointer to the first node, instead of being part of the linked list.  Therefore it will not be involved in the reverse process, and need to handle separately.
which means, the original list looks like:
HEAD -> a -> b -> c -> null

after reverse, it should look like
HEAD -> c -> b -> a -> null

In brief, it should look like (assume your code already works when passing in head.next)
public Node<T> reverse(Node<T> current)
{
    if (current == head) {
        return reverse(current.next);
    }

    // rest of your original code.
}

Just a further suggestion:
Your reverse() method, as an public instance method of your list class, shouldn't accept the current node, as it is conceptually meaningless for caller.
I believe you should make this method protected, which means something like:
public void reverse() {
    this.head = reverseInternal(head);
}

private Node<T> reverseInternal(Node<T> node) {
    // your original reverse logic
}

With such encapsulation, you don't even need to struggle before how to make your reverse works when you pass in the sentinel head: you can simply call reverseInternal(head.next) in your public reverse() method.

A: First: if it returns an empty list it doesn't "work".
There is no need for head to be an empty node. You should normally just keep the first node (in your case list.head.next) as your list.head. head should be a reference to where the list starts, not a separate node.
The reason your code empties the list when you pass it list.head is it sets list.head.next to null. This is because you assume the node you pass to the list is a regular one, while your head node is special.
Here's a solution for your assumptions (I'll assume someone insisted on this bizarre detached head thing. Just don't do it if you're designing the list yourself. Please...)
public Node<T> reverse(Node<T> current)
{
    if (current == null)
        return head;

    if (current.next == null)
    {
        head.next = current;
        return current;
    }
    Node<T> temp = current.next;
    current.next = null;
    head.next = temp;
    reverse(temp).next = current;
    return current;
}

Explanation: This still sets the last node's next to null, but it pushes the list's head one spot down as it runs through the list, eventually pointing it to the last (now first) member.

A: This reeks of homework.
But still.
In general:
f(Node<T> current, ...) {

     f(current.next, ...);

}

For a list a > b > c > d > e sitting in the midle at d, one
probably has built c > b > a already, so guess what is needed as additional parameter to f?
Good luck.

After comments:
public Node<T> reverse(Node<T> current)
{
    return reverseRec(current, null);
}

/**
 * @param current to-do (sub-)list.
 * @param resultDone done reversed list sofar.
 * @return reversed result.
 */
public Node<T> reverseRecursively(Node<T> current, Node<T> resultDone)
{
    if (current == null) {
        return resultDone;
    }
    Node<T> next = current.next;
    current.next = resultDone;
    return reverseRecursively(next, current);
}


text:
Q: LDAP with Guard Authentication System in Symfony 3 What I'm pretending to do is to include the LDAP for internal users in a Guard Authentication System configured by ddbb.
I already have build my Guard Authentication System and works really nice thanks to https://knpuniversity.com/screencast/symfony-security.
But I need also to try to log in previously via LDAP mode. More precisely, the functionality must be like this:
The user try to log in on the Guard System Authentication configured with a database from MySQL and:
1- Check if exist the user in the table User from MySQL. If exist, we go to step 2. If not exist return false to the authentication with the error message.
2-Check if the user exist in the LDAP mode. If exist go to the step 3. If not exist go to the step 4.
3-Try to log in via LDAP with the username and password. If the authentication is ok, it's logged in. If can't match the password via LDAP, return false to the authentication with the error message.
4-After checking the LDAP option, we will just try to log in via Guard Authentication System. If the authentication it's ok, the user is logged in. If can't match the password via Guard with the MySQL users table, return false to the authentication with the error message.

A: In the LoginFormAuthenticator file I finally could manage this behavior I want as shows the next code.
<?php

namespace AppBundle\Security;

use ...
use Zend\Ldap\Ldap;
use Zend\Ldap\Exception\LdapException;

class LoginFormAuthenticator extends AbstractFormLoginAuthenticator
{
    use TargetPathTrait;

    private $em;
    private $router;
    private $passwordEncoder;
    private $csrfTokenManager;

    public function __construct(...
    }

    public function getCredentials(Request $request)
    {
    ...
    }

    public function getUser($credentials, UserProviderInterface $userProvider)
    {
        $username = $credentials['username'];
        $ldapPassword = $credentials['password'];
        $ldaphost = 'ldap.example.com';    // your ldap servers
        $baseDn = 'dc=example,dc=es';

        $options = [
            'host'              => $ldaphost,
            'username'          => $username,
            'password'          => $ldapPassword,
            'bindRequiresDn'    => false,
            'accountDomainName' => 'example.es',
            'baseDn'            => $baseDn,
        ];

        $userInterface = $this->em->getRepository('AppBundle:User')
            ->findOneBy(['email' => $username]);
        $ldap = new Ldap($options);

        try {
            $ldap->bind();
            $userInterface->setIsAuthenticationLDAP(true);
        } catch (LdapException $zle){
            $userInterface->setIsAuthenticationLDAP(false);
        }

        return $userInterface;
    }

    public function checkCredentials($credentials, UserInterface $user)
    {
        $password = $credentials['password'];

        if($user->isAuthenticationLDAP()){
            $user->setLoginAttempts(0);
            $this->em->persist($user);
            $this->em->flush();
            return true;
        } else {
           if($this->passwordEncoder->isPasswordValid($user, $password)) {
               $user->setLoginAttempts(0);
               $this->em->persist($user);
               $this->em->flush();
               return true;
           } else {
               if($user->getLoginAttempts() == '0') $user->setFirstLoginAttempt(new \DateTime('now'));
               $user->setLoginAttempts($user->getLoginAttempts() + 1);
               if($user->getLoginAttempts() >= 5) {
                   $user->setLockedDateTime(new \DateTime('now'));
                   $user->setLoginAttempts(0);
               }
               $this->em->persist($user);
               $this->em->flush();
           }
       }

       return false;
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {
       ....
    }

    protected function getLoginUrl()
    {
        return $this->router->generate('fos_user_security_login');
    }
}

I hope anyone can enjoy this answer.


text:
Q: First Python Code I installed the PyCharm and python on my computer and trying to write this simple piece of code but I get error.
for i in range(10):
  x = 0.1*i
  print( x )
  print( x / ( 1 - x * x ) )

The error is:
File "C:/WinPython-2.7.6.2-64/python-2.7.6.amd64/Lib/site-
packages/ib/opt/wrapper_v5.py", line 50
    print errormsg
             ^
SyntaxError: Missing parentheses in call to 'print'

Process finished with exit code 1

Do I need any header statements like in C++. I am coming from C++ and Matlab background.

A: You use this:
for i in range(10):
   x = 0.1*i
   print( x )
   print( x / ( 1 - x * x ) )

but in Python 2 it's:
for i in range(10):
    x = 0.1*i
    print x
    print x / ( 1 - x * x )

Your piece of code is written in Pyhton3 so maybe install that or learn python2 in a different tutorial or something.


text:
Q: Difference log4j, slf4j and logback What is the difference between log4j, logback and slf4j. When I need to use every of them? Can you give some examples?

A: Log4j and logback are logging APIs and SLF4J is a logging facade. i.e. SLF4J is an abstraction for various and logging frameworks such as log4j, log4j2, logback, jcl and jul.
So you can't use SLF4J alone in your application. It needs one of the above listed logging API as its logging provider. SLF4J also provides various bridging APIs to route logging from other logging APIs to SLF4J.
Although logback is a logging api, you can't use it without using slf4j.
So if you want to use every one of them then you can use SLF4J and logback as your logging implementation and use log4j-over-slf4j.jar to redirect your log4j logging to SLF4J.
See following example created by Baeldung on how to use log4j bridge with slf4j.
https://www.baeldung.com/slf4j-with-log4j2-logback#Setup


text:
Q: render_template in Python-Flask is not working I am actually creating an app with Flask and I am encountering issues regarding my routing.
My situation is simple: The user enters a token to authenticate himself. Once he clicks on authenticate, an angular HTTP request uses POST to send his token to a Python server. There, if he is granted access, the home page is displayed using render_template; otherwise the login keeps still.
However, when the user authenticates himself, I see on my command line that the POST was successful, the authentication was a success but the page just stuck on login and does not redirect to home page as if the second render_template does not work. Please Help!
@app.route('/')
def index():
    if not session.get('logged_in'):
        return render_template('auth.html')  # this is ok.
    else:
        return render_template('index.html')  # this does not work

@app.route('/login', methods=['POST','GET'])
def login():
    tok = request.form['token']

    if (check_token(tok) == "pass"):  # check_token is a function I've implemented
                                      # to check if token is ok=pass, ko=fail
        session['logged_in'] = True
    else:
        flash("wrong token")

    return index()

A: Your login handler shouldn't call index directly. It should return a redirect to the index.
return redirect('/')

or better:
return redirect(url_for('index'))

A: I was thinking of the following.
@app.route('/')
def index():
    if not session.get('logged_in'):
        return return redirect(url_for('login'))
    else:
        return render_template('index.html')

@app.route('/login', methods=['POST','GET'])
def login():
    if request.method = "POST":
        tok = request.form['token']

        if (check_token(tok) == "pass"):
            session['logged_in'] = True
        return redirect(url_for('index'))

        else:
            flash("wrong token")

    return render_template("login.html")

A: I have used Angular JS in my app to send requests to my flask server and i realised that my client side angular JS had difficulties in rendering page as it was just expecting a response.
I first tried to do.. document.write('response.data') and it did display my home page but my scripts attached on my html page stopped working.
Second try, I tried to reload the page after receiving the response in my client and it works well. I don't know if it's the best way to do but it does work.


text:
Q: Why do theories of nature prefer to be renormalizable and not super-renormalizable? It seems to me (correct me if I am wrong) that all theories in the Standard Model are exactly renormalizable, as opposed to non-renormalizable or super-renormalizable. In a sense, we could say that these theories live at a critical point, that is on the boundary between non-renormalizable and super-renormalizable theories. It is kind of clear why a theory of nature would prefer to be renormalizable than non-renormalizable, but is there a known reason (or conjecture) for why nature would prefer to be renormalizable than super-renormalizable? Could that not be a hint of where to search for theories?
(of course an important caveat would be that renormalization may arise as a flaw of our current theoretical framework)

A: It is important to understand that the modern answer to "why renormalizable" has nothing to do with consistency requirements.
The confusion comes from history: in the early days of QFT, people thought that the perturbative expansion can be used as the definition of the full theory, provided that it is renormalizable. Here, renormalizability is desired, because it means the description of the theory is complete. I.e. if you want to unify General Relativity and the Standard Model into a single Theory of Everything, that ToE better be a complete description of all physical phenomena if it is to live up to its name.
It has become apparent later that even renormalizable (in fact, even superrenormalizable) perturbative expansions do not define the full theory. They are not approximation schemes in the usual meaning of that word. That is, they can not approximate a $n$-point function to an arbitrary accuracy.
For a convergent series, e.g. the Taylor series of an analytic function, the more terms you sum – the better your approximation to the right answer. This can be mathematically written down as an infinite sum:
$$
f(x) = \sum_{n=0}^{\infty} \frac{1}{n!} f^{(n)} x^n.
$$
The sum in the r.h.s. doesn't always converge on the entire real axis, however. Take, for example,
$$
\frac{1}{1-x} = \sum_{n=0}^{\infty} x^n.
$$
Interestingly, the l.h.s. is defined for $x \neq 1$, but the r.h.s. only converges for $-1 < x < 1$ – a completely different domain! The number $1$ is called the radius of convergence (akin to the fact that on the complex plane, the series is convergent when $|x| < 1$).
In QFT, the perturbative expansions are in the powers of the coupling constant, $g$:
$$
A(g) = \sum_{n=0}^{\infty} A_n g^n.
$$
Here $A$ is some quantity that should exist in the theory, and $A_n$ are the coefficients in this approximation. $A_n$ are usually represented by sums of Feynman diagrams with $n$ interaction vertices (each vertex contributes a single power of $g$).
So the natural question to ask is: what is the radius of convergence of $A(g)$?
The answer can feel very strange unless you already know it: we believe that almost uniformly, for all interacting QFTs in 2 or more space-time dimensions, the radius of convergence is zero!
Among other things, that means that the perturbative expansion can never define the full theory, and it can never be complete. Even if we have a renormalizable or a superrenormalizable perturbative expansion, summing it doesn't give you the answer, in fact, it gives you infinity.
Such expansions are known as asymptotic expansions. Their defining property is that for any chosen order of approximation $N$, and for any chosen accuracy $a$, there exists a value $g_{\text{max}}$ such that
$$ | A(g) - \sum_{n=0}^N A_n g^n | < a $$
for all $g < g_{\text{max}}$.
In this sense, asymptotic expansions can approximate exact quantities. In fact, in practice, rather paradoxically, asymptotic expansions are much better at approximating functions than convergent expansions are! (which is the reason why perturbative QFT is so successful)
But this notion is very different from the usual normal of convergence. In normal convergence, for any accuracy and any value of $g$ (within the radius of convergence) there exists an order of approximation that is good enough to yield that accuracy. Here, for any accuracy and any order, there exists a value of $g$.
In QFT, this means that even renormalizable, even superrenormalizable perturbative theories can't be used to produce arbitrarily precise predictions. What happens is that you can only achieve accuracy $a$ if your coupling constant is small enough. But the coupling constant is varied only on paper – in nature, it must have a fixed value that is a parameter of the theory. So either you're in luck and the value of the coupling allows to approximate the answer with accuracy $a$, or you're not! And once you start making $a$ smaller and smaller, eventually the physical value of the coupling will become too large for the asymptotic expansion to be a good approximation – the perturbative series will blow up. This establishes that there is a fundamental accuracy limit for all perturbative QFTs beyond which they are unable to make any predictions.
The symptoms (loss of predictive power) are very similar to what happens with nonrenormalizable theories, except that the loss of predictive power due to the diverging asymptotic series is common to all perturbative QFT, renormalizable or not.
Therefore, perturbative QFT can't be the final formulation of physics, even if it is renormalizable. One can get around this by studying non-perturbative QFT (which are notoriously difficult to even define mathematically, let alone solve / extract predictions). Another possible way is to give up on QFT alltogether and treat perturbative QFT as a convenient approximation to something very different, like strings, discrete space time of Loop Quantum Gravity, etc. In fact, because the kinematics of General Relativity lives on a differential manifold rather than on the Minkowski space-time (a property which is known as background independence); it does look very unlikely that the ToE is a Minkowski space QFT, perturbative or nonperturbative.
Regardless of which path one chooses for the formulation of the fundamental theory, perturbative QFT, being an extremely good approximation, addresses many important issues. One of these issues is the question of why in nature we only observe renormalizable interactions. The answer to that question has nothing to do with the original, naive notion of "renormalizable = consistent", which turned out to be a poor guide into the structure of the QFT.
Instead, it turns out that whatever interactions the fundamental theory has at high energies, only those that give rise to renormalizable QFT operators are physically measurable at low energies.
This conceptual picture is captured mathematically by the Renormalization Group. Having given up on formulating the perturbative QFT as a fundamental theory, one adopts a pragmatic attitude: the perturbative QFT is defined with a cutoff $\Lambda$ that makes all its integrals finite, and hence removes the need for getting rid of infinities. However, it doesn't remove the need to renormalize. Renormalization isn't about stuffing infinities under the carpet, like Dirac once said – it turns out to be a very down to Earth procedure that arises naturally. What happens is – once you have a theory with a cutoff that is finite, you want to make predictions with it. For example, you're trying to measure the mass of one of your theory's particle species. But it turns out that this mass is far from the value that you've put by hand into the Lagrangian. It acquires additional contributions, which frequently outweigh the original value by many orders of magnitude, raising concerns from the point of view of naturalness. So the predicted value of the mass and the value you put in the theory by hand are very different. This of course means that the value you put by hand has to be changed, so that the predicted value matches the experimentally measured.
Once you fix the predicted value, you have to make the bare value (the one you put in by hand) depend in a non-trivial way on the cutoff $\Lambda$ in order to retain the correct prediction for all values of $\Lambda$. This is the first example of the renormalization group flow.
It may appear at the first sight that this flow is unphysical and unmeasurable (we're only tweaking a parameter to match observations which are fixed and aren't flowing). There's some truth to it (and in fact there are different definitions of the RG flow which correspond to different renormalization schemes, which signals that some aspects of that flow are not observable), however, there is an important physical aspect of the renormalization group flow which is – anomalous scaling behavior.
Since the theory contains a dimensionful parameter $\Lambda$, it can be non-invariant under scaling transformations, even in the limit where $\Lambda \rightarrow \infty$! In fact, that's exactly what happens in many real theories, including Yang-Mills. We say that the scaling symmetry acquires a quantum anomaly. This means a non-trivial behavior of coupling constants under scaling, known as the anomalous dimension or the beta function.
The dominant term in the scaling law of couplings is usually the classical term,
$$ g \rightarrow b^d g, $$
with $b$ the scaling parameter, and $d$ the classical dimension of the coupling.
Couplings with $d > 0$ are called relevant. In the infrared region (which we can pass to by applying a scaling transformation with a very large $b$) they acquire large values, and are physically observable.
By a divergence index counting argument, these couplings correspond to superrenormalizable interactions. Note that this is a pure coincidence – our analysis doesn't use the renormalizability!
Couplings with $d < 0$ are called irrelevant, because in the infrared region they acquire very small values and are unobservable.
By a divergence index counting argument, these correspond to nonrenormalizable interactions.
In order for the analysis above to hold, a very important assumption has to be valid: the classical behavior of the scaling law has to be the leading contribution in the renormalization group. That translates into inequalities on coupling parameter values. This assumption does not always hold!
Probably the most important example of a situation where the classical term is not a leading term are marginal couplings – those with $d = 0$. For them, the classical term vanishes, and the scaling behavior of such couplings is completely determined by the quantum effects of the renormalization group. Depending on many intricate properties like the particle content of the theory, these effects can either render a marginal coupling observable in the infrared region, or unobservable.
This is the real reason we only see superrenormalizable and renormalizable interactions in nature, according to the modern understanding. Not a consistency argument, but merely the fact that if there was a nonrenormalizable interaction (in fact, there probably is!) – we would completely miss it due to its value becoming very small at low energies.
In QCD, as long as we don't couple too much matter to it, the property called asymptotic freedom holds: QCD's marginal coupling behaves a lot like a relevant coupling (large in the IR, small in the UV), though the scaling law is logarithmic rather than polynomial (since there is no classical contribution).
Interestingly, when the scale of the experiment reaches $\Lambda_{QCD}$ (about 200 MeV), the coupling constant becomes comparable to $1$ and the asymptotic perturbative expansion stops giving good approximations. QCD undergoes a phase transition at that point: quarks confine into color-neutral hadrons. Perturbative QFT completely breaks down below $\Lambda_{QCD}$, not only in theory, but also in practice.


text:
Q: View components can't link to POST action methods? I have a view component which contains some action links that points to different action methods in the home controller, like this:
Update quantity
@item.ProductTitle

The action method Details, which is a GET-method, is being executed as expected.
But when I click on the Update-link, I'm directed to a blank page with the url of /Home/Update/5, for instance, and nothing more happens. This is also the case even if I run in debug mode and set a breakpoint on the first line of the Update-method. Update is a POST-method. Does this matter?
In either case, Update is not executed.
What is going on?

A: You can't call POST request by clicking a link.
You either need to use ajax or form for this.
It depends on your needs.
Use form:
<form asp-action="Update" asp-route-id="@item.ProductId" method="post">
    <button type="submit">Update quantity</button>
</form>

Use ajax: (assume you have jQuery)
$('<update-link-selector>').on('click', function (e) {
    e.preventDefault();
    var href = $(this).attr('href');

    $.post(href).done(function(response, status, xhr) {
        //success
    }).fail(function(err) {
        //error
    });
});


text:
Q: Service Fabric Microservice AMQP equivalent TLDR;
Is there a AMQP equivalent inside Service Fabric for Stateless services for communication between microservices?
I am building an application which contains multiple microservices.
For starters this application will have microservices locked behind API gateway. This API Gateway is publicly accessible from either my web application or through an URL provided by the Gateway.
Reason why I am explaining this? Microservices will be able to communicate with each other, and can be used by developers to hook up whatever they want. From this post, I understood a REST interface is useful for exposing your service to the public, while using AMQP (Advanced Messaging Query Protocol) to request things from your database or other services. From this post I understood that AMQP is the preferred method of communication between services due to it being fully async.
So, based on this I am looking for an implementation where my microservices have A REST interface and will use AMQP to query the data that is being requested through the REST interface.
Since I am using Service Fabric and reinventing the wheel is a waste of time, I got curious whether Service Fabric comes with an "out-of-the-box" solution for
AMQP or not. I have seen the IReliableCollection come by, but the documentation gave me the impression it was restricted to stateful services (I forgot to mention my services are stateless)
Many thanks.

A: No, Service Fabric doesn't provide any messaging mechanism to communicate with reliable services. In practice, reliable services (stateful and stateless) are basically processes running doing nothing until you tell them to do something. You are responsible to create the mechanism to allow a service from receiving requests to do work (with remoting, REST, messaging...). Service Fabric only provides you the basis of how to implement this mechanism which is the ICommunicationListener.
If you want asynchronous communication between services, you could use, for example, Azure Service Bus and use a ready made communication listener.
Now, using messaging doesn't fully solve your problem of having long running processes, as starting a long running process can be done synchronously as well (you could call your service with REST for example, and the service could return immediately with an OK and start the long running process so that the client is not synchronously waiting). The main problem with long running processes is normally how to communicate back to the client that the process has completed. Note that being stateless services, you cannot poll the service to get the status of the process as the request could go to a different instance of the service (and it would go against the design rules of stateless services anyway).
If your scenario is two microservices talking to each other, you have several options to communicate back the results. If you are ok introducing a circular dependency, then you could simply do a REST call from A to B to start the process and a REST call from B to A to communicate the completion.
If you use messaging, you could create a mechanism to allow Replies, without introducing a circular dependency, for example, by sending the Reply Queue as part of the original message (or message properties in ASB). This way your service B doesn't have to know anything about the caller.
I hope it makes sense.


text:
Q: How to cancel redirection of page with click? I have a redirection code (working fine) in several pages as follow :
<meta http-equiv="refresh" content ="42; url=http://my url.html#">

But i want the automatic redirection to be cancelled or delayed if the user clicks in any point of the page.
What code should i use ?
Thanks

A: Here is the code for click on page anywhere:

A: *

*Remove you <meta http-equiv="refresh"> from Documents

*Insert a simple JS-Timer and use window.location to refer the User after the Page loaded.

var timeVar = setInterval(function () {myTimer()}, 1000);
var t = 9;
function myTimer() {
    if (t>0) {
        document.getElementById("timer").innerHTML = t;
        t--;
     }
     else { window.location = 'what/ever/you/are/workingon.html'; }
}

function StopFunction() { clearInterval(timeVar); }

Redirecting in 10Seconds.

Cancel!

The User will load your page and when not canceling the Timer be redirected to the Page you defined. If stopping the Timer the user wont be redirected and stay on the Page. br

A: Try just to empty cache, it should work.


text:
Q: Pygame game loop syntax I'm trying to create a doodle jump-style game. This code only includes the platforms, and the start screen. I need the game loop to finish my button function, at the start screen.
How do I make a game loop/define a game loop, in my code? I keep getting syntax error saying my game loop is not defined.
My code:
import pygame as pg
import sys,time,random
pg.init()
res_x,res_y=800,600
screen = pg.display.set_mode((res_x,res_y))
screen.fill((0,0,0))
pg.display.update()
clock=pg.time.Clock()

#COLOURS
light_green=(124,252,0)
green=(50,205,50)
light_red=(255,99,71)
red=(128,0,0)
yellow=(255,215,0)
black=(0,0,0)
white=(255,255,255)
light_grey=(119,136,153)
dark_pink=(220,20,60)
light_pink=(255,108,180)
sky_blue=(0,255,255)

#start screen
def text_object(text, font,):
        textsurface=font.render(text,True,(255,255,255))
        return textsurface, textsurface.get_rect()

def button(msg1,x1,y1,l1,h1,ic1,ac1,action=None):
        mouse=pg.mouse.get_pos()
        click=pg.mouse.get_pressed()

        if x1+l1>mouse[0]>x1 and y1+h1>mouse[1]>y1:
            button_start=pg.draw.rect(screen,ac1,(x1,y1,l1,h1),)
            if click[0]==1 and action!= None:
                if action=='play':
                    game_loop()

        else:
            button_start=pg.draw.rect(screen,ic1,(x1,y1,l1,h1),)

        smalltext=pg.font.Font('freesansbold.ttf',30,)
        textsurf, textrect= text_object(msg1,smalltext)
        textrect.center=((x1+(l1/2)),(y1+(h1/2)))
        screen.blit(textsurf, textrect)

def start():
    while True:
        for event in pg.event.get():
             if event.type == pg.QUIT:
                pg.quit()
                sys.exit()
        screen.fill((119,136,153))
        bigtext=pg.font.SysFont('arial.ttf',100)
        textsurf,textrect= text_object('Maze Runner',bigtext)
        textrect.center=((res_x/2),(res_y/2))
        screen.blit(textsurf,textrect)

        button('GO!',110,400,200,50,green,light_green,'play')
        button('QUIT',450,400,200,50,red,light_red,'quit')

        pg.display.update()
        clock.tick(15)
start()

#platform
rect_x=random.randrange(0,200)
rect_y=random.randrange(50,120)
rect_l=300
rect_h=50

rect1_x=random.randrange(230,430)
rect1_y=random.randrange(150,300)
rect1_l=random.randrange(50,200)
rect1_h=50

rect2_x=random.randrange(430,550)
rect2_y=random.randrange(300,450)
rect2_l=100
rect2_h=50

rect3_x=random.randrange(630,750)
rect3_y=random.randrange(450,500)
rect3_l=50
rect3_h=50

def game_loop():
    while True:
        for event in pg.event.get():
                if event.type == pg.QUIT:
                    pg.quit()
                    sys.exit()

        screen.fill(black)
        base=pg.draw.rect(screen,sky_blue,(0,540,800,60), )
        platform=pg.draw.rect(screen, yellow, [rect_x,rect_y,rect_l,rect_h],5)
        platform1=pg.draw.rect(screen,white,[rect1_x,rect1_y,rect1_l,rect1_h],5)
        platform2=pg.draw.rect(screen,dark_pink,[rect2_x,rect2_y,rect2_l,rect2_h],5)
        platform2=pg.draw.rect(screen,light_pink,[rect3_x,rect3_y,rect3_l,rect3_h],5)

        pg.display.update()

A: The NameError: name 'game_loop' is not defined gets raised because you call game_loop() in the button function before you define it with def game_loop(). Just define the game_loop function before you call start() and subsequently button().
def game_loop():
    # Code omitted.

start()  # Call start() afterwards.


text:
Q: How to get first and last document in collection? I have google-cloud-firestore collection with many documents.
I want to get first and last document in collection (sorted by timestamp).
How can I query for this?

A:
I'm not sure by which Timestamp you want to sort, so I'm gonna assume your doc looks something like this
/id/: {
 timestamp: FirebaseFirestore.Timestamp
 // ... whatever other properties
}

You can get a Query by querying on a CollectionReference<T> via the .orderBy method.
const collectionQuery = firestore
  .collection('collectionName')
  .orderBy('timestamp', 'asc')

Now we want to get a QuerySnapshot (which will allow us to access the documents), by using the .get() method.
const collectionSnapshot = await collectionQuery.get()

Now we just access the first and the last document.
const firstDocument = collectionSnapshot.isEmpty
 ? null
 : collectionSnapshot.docs[0]
const lastDocument = collectionSnapshot.isEmpty
 ? null
 : collectionSnapshot.docs[collectionSnapshot.docs.length - 1]

And voila, you have your first and last document! :-)