text:
Q: when I downloading file from google drive with java i get symbols when I downloading file from google drive with java I get response like that in pic

there is my code
public void downloadFile(String fileId, OutputStream outputStream) {
        if (fileId != null) {
            try {
                googleDriveService.getInstance().files()
                    .get(fileId).executeMediaAndDownloadTo(outputStream);
            } catch (IOException | GeneralSecurityException e) {
                e.printStackTrace();
            }
        }
    }

there is also my controller
@GetMapping("/download/{fileId}")
    public void download(@PathVariable String fileId, HttpServletResponse response) {
        try {
            documentService.downloadFile(fileId, response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Do you have any suggestions?

A: I believe that your problem is that you aren't setting the ContentType header in your HTTP response, and so your browser doesn't know what to do with the data coming back in the response body.  To get the right behavior from your browser, you should set the ContentType header appropriately for the type of data you are returning.
For a JPEG, you want to call something like:
response.setContentType("image/jpeg");

For a PDF, you want to call:
response.setContentType("application/pdf");

For "docx", it's strange, but it seems that what you want is:
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");

Doing this should cause your browser to properly display any file type that it knows how to display.
Lacking any type information, I believe that the browser is interpreting the data as plain text, which is why you're seeing the funny display that you are.
UPDATE: Per the original poster's comment, the Google Drive API allows to get the MIME type of a downloaded file via the call:
String mimeType = googleDriveService.getInstance().files().get(fileId).execute().getMimeType();

This value can then be used to set the ContentType header in the response, via:
response.setContentType(mimeType);

The addition of these two lines of code should cause the OP's code to return the correct mime type for any type of file uploaded to Google Drive, thereby causing the requesting browser to properly display any file type it knows what to do with.


text:
Q: ISAPI Block external access to folder / filetype I have a website running on IIS - Is there a way to do the following using ISAPI Rewrite:
1) prevent external access to a folder on my site (ie request not from within the website - a user is trying to get into the folder via the address bar) - say http://www.example.com/folder1 but allow the website itself to pull elements from within the folder1 (images, flash files etc) without the same restrictions
Thanks...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is the existential quantifier commutative in intuitionistic higher order logic? In higher order logic, one sometimes defines the existential quantifier by
$$(\exists x. \phi(x)) := (\forall \rho.(\forall x.\phi(x)\to\rho)\to\rho).$$
I am having trouble proving that
$$(\exists x.\exists y.\psi(x,y)) \to (\exists y.\exists x.\psi(x,y)).$$
Is this even true? If not, what would be a counter example?

A: The trick is to unfold and instantiate both instances of $\exists$ in the hypothesis with the right hand side as follows:
Let $\rho_0 := \exists y.\exists x.\psi(x,y)$, then the following is a derivation tree (read from bottom to top):
\begin{align*}
(\exists x.\exists y.\psi(x,y))&\vdash \rho_0\\
((\forall x.(\exists y.\psi(x,y)) \to \rho_0)\to \rho_0) &\vdash \rho_0\\
&\vdash(\forall x.(\exists y.\psi(x,y)) \to \rho_0)\\
&\vdash_x (\exists y.\psi(x,y))\to\rho_0\\
\exists y.\psi(x,y)&\vdash_x\rho_0\\
(\forall y.(\psi(x,y) \to\rho_0)\to\rho_0)&\vdash_x \rho_0\\
&\vdash_x \forall y.(\psi(x,y)\to\rho_0)\\
&\vdash_{x,y}\psi(x,y) \to(\exists y.\exists x.\psi(x,y))\\
\psi(x,y)&\vdash_{x,y}\psi(x,y),
\end{align*}
Where the last step follows from the general observation that (again, from bottom to top)
\begin{align*}
\phi(x)&\vdash_{x}\exists x.\phi(x)\\
\phi(x),(\forall x.\phi(x)\to\rho) &\vdash_{x,\rho} \rho\\
\phi(x),\phi(x)\to\rho &\vdash_{x,\rho}\rho\\
\rho&\vdash_\rho\rho.
\end{align*}


text:
Q: R plot not showing data points when adding colour by factor I am trying to plot an R graph with data points coloured by a factor. I am using the property col with values from a data frame column as the factor, but they seem not to be recognised correctly.
My code is as follows:
plot(marrmales$tot_nochc, xlab="", ylab="Tot hours worked",   col=marmales.df$cor_partner, pch=15)

marmales.df$cor_partner is a vector of 0 and 1.

When I plot this, only data points for which the cor_partner value is 1 are shown. If I specify colours (I thought 0 might be read as NULL and return white), all data points are shown, but in the first of the specified colours.
I have tried converting cor_partner to characters, but nothing changed.
Anyone knows what is happening?
Thanks

A: The parameter col = 0 in plot() indicates no color, you can see this via colors().
A solution to your problem can be:
plot(marrmales$tot_nochc, xlab="",
     ylab="Tot hours worked",
     col=as.factor(marmales.df$cor_partner),
     pch=15)


text:
Q: Logstash drop logs if field does not have value I have the following logstash.conf
input {
    tcp {
       port => 5000
      # codec => json { charset=>"UTF-8" }

    }

    stdin {}
}

filter {

    if "userId" not in [contextMap] {
     drop {}
    }

    json {
            source => "message"
    }

 }

 output {
    elasticsearch {
            hosts => ["localhost:9200"]
            index => "logs"
            user => "user"
            password => "password"
    }

    stdout {}
 }

And I have json request printed in logstash
{
"message" => " testing ,essage",
"instant" => {
    "nanoOfSecond" => 267000000,
    "epochSecond" => 1631632671
},
"thread" => "http-nio-8080-exec-1",
"level" => "INFO",
"loggerFqcn" => "org.apache.logging.slf4j.Log4jLogger",
"loggerName" => "",
"endOfBatch" => false,
"@version" => "1",
"@timestamp" => 2021-09-14T15: 17: 51.504Z,
"threadPriority" => 5,
"hostname" => "hostname",
"contextMap" => {
    "requestId" => "f6f65bab-bdd1-4cca-ba09-ff0d06d16e41",
    "userId" => "bc1289cd-d3ed-43ec-87ba-9c5ff9c5f205",
    "moduleName" => "LOGGER_SERVICE",
},
"host" => "hostname",
"threadId" => 139,
"port" => 55555
}

What I want to achieve is that where the field contextMap does not has field userId, logs should be droped.
Could someone tell me ware I am doing wrong?

A: if "userId" not in [contextMap] can be used for either a sub-string match if [contextMap] is a string, or an array membership test if [contextMap] is an array. It cannot be used to test if a key exists in a hash. That said, you can use
if ! [contextMap][userId] { drop {} }

A: I managed to solve the problems. The issue was I didn't want to certain logs to be loaded to to elastic search only with specific field. so I moved the filter to the output section. the complete logstash config file is as below
input {
  tcp {
   port => 5000
  # codec => json { charset=>"UTF-8" }

  }

  stdin {}
}

filter {
  json {
     source => "message"
  }
}

output {
 if [contextMap][requestId]{
   elasticsearch {
        hosts => ["localhost:9200"]
        index => "logs"
        user => "user"
        password => "password"
   }
 }
 stdout {}
}

Home help someone else


text:
Q: Tengo un error con [(ngModel)] en una aplicacion de ionic 2 Tengo un error y no se que es lo que se esta haciendo mal
mi código es el siguiente:
Html
<ion-col col-12 class="informacion flex" *ngFor=" let edad of edades; let i=index ">
    <ion-input class="" [(ngModel)]="edad" type="text" placeholder="Ej: (7-12) Infantil, Etc..." ></ion-input>
    <button class="papelera" ion-button color="rojoTomato" clear icon-only (click)="eliminarEdad(i)">
        <ion-icon name="ios-trash-outline" ></ion-icon>
    </button>
</ion-col>

ts
edades = [''];

Error

Error: Uncaught (in promise): Error: Cannot assign to a reference or
  variable! Error: Cannot assign to a reference or variable!

Otros Ejemplos que si funcionan:
Html
<ion-col col-12 class="flex" *ngFor=" let valor of valores; let i=index ">
    <ion-input class="" [(ngModel)]="valor[0]" type="text" placeholder="Ej: Infantil" ></ion-input>
    <ion-input class="" [(ngModel)]="valor[1]" type="text" placeholder=" $20.000 COP." ></ion-input>
    <button ion-button class="papelera" color="rojoTomatoColsport" clear icon-only (click)="eliminarValor(i)">
        <ion-icon name="ios-trash-outline" ></ion-icon>
    </button>
</ion-col>

ts
valores= [['','']];

A: El error esta diciendo que no puedes asignar a [(ngModel)] una variable/referencia creada localmente para el valor del input dinámicamente.
Una solución sería referir al objeto edades para evitar el fallo:
[(ngModel)]="edades[i]"

Pero pierdes el foco (focus) del input, porque estás repitiendo sobre una matriz y estás cambiando los elementos de la matriz.


text:
Q: Why are so many opensource projects moving from SVN To git?
Possible Duplicate:
Why is Git better than Subversion?

I follow a number of different open source projects, mainly around Java technology, but this question is probably universal. I have noticed over the last 6 months or so that many projects are moving Way from subversion and moving to git.
My question is why? What are the advantages of git over subversion, and do these advantages lend themselves to a commercial world (I.e should i be looking to replace my cvs and svn repositories with git)?

A: C'mon, have you checked out WHO wrote git? Linus Torvalds himself!
Now seriously, I think there are mainly 3 great reasons to use git:
1) the cloning model: Using Subversion, you perform a "checkout", which is, in fact, just a snapshot of the repository in a given moment in time. Every other action (commit, branch, check logs, compare with previous versions) required network access to the original repository. Using git you effectively "clone" the entire repository to your local machine, allowing you to perform a series of local commits, rollbacks, browse the history, etc, without pooling the server again. This is a great thing for most open-source developers.
2) the forking model: In the days of Subversion, creating a fork of a project was such a catastrophic event. It usually meant that, in a few months, one of the projects would die. With git (and Github helps a lot on that matter), forks are easy and healthy, developers can merge changes in both ways, and many forks of a given projects can coexist.
3) partial commits: not many people use this, but you can choose to commit only part of a changed file (using git add -p). It saves a lot of time on delicate situations.
Of course there are a lot of other reasons why git (or DVCS in general) are way better than Subversion, but, for me, those 3 are the killers.

A: Hi please don't miss difference between github and git.
Github is only freely available git server.
And why github ? - Because you can easily fork and merge projects, only by clicking mouse.
This gives business value for me as:
- anybody can do some work with my project and ask me to merge his changes, no special knowledge required, history of request easily visible...
- watch changes on projects by using one account for all of them
- you can also have closed repositories not publicly available (with some fees).
- and probably a lot more, just visit github
What git itself gives please see responses of others.

A: Because many programmers think that a distributed source control management system (such as GIT) is superior to one that required a centralized server.

A: There are several reasons

*

*Git, as a distributed system, is perceived as better.

*You don't need read/write permissions and the administration hassle in a git-world.

*It is easier to contribute to the project.

*Git ultimately gives you more control of what is in the main repository and what is not.
Most of the cool advantages carries over to a commercial world I think. But start slow if you want to make the shift.

A: Frankly, I have no clue.  I find git to have an obscure command syntax, and be generally really annoying and difficult to use.  git is fast, but there are other DVCSes out there that are just as fast.  I think overall there are better DVCSs than git that I think make a lot more sense to be using.
Now, why people are moving from Subversion to a DVCS is an obvious and easy question.  Distributed version control systems are simply better in every respect.
In Subversion, I cannot check things out, make my own local changes and check them in.  I have to have go through contortions like copying things into a vendor branch periodically and merging or some other ridiculous thing.
This has a whole host of positive benefits.  The barrier to becoming a contributor becomes much lower.  The project becomes easier to usefully fork.  Tracking changes that the maintainer of a project doesn't want, but you do becomes much easier.
Additionally, when you check the project out on your laptop, your USB stick and your system at work there is now a clear and logical way to allow checking in all of those places regardless of internet connectivity and being able to join everything back up again later.
It also makes for an excellent distributed backup of the entire source repository and all of its history.  It's nearly impossible for a DVCS repository to lose significant history since there are so many copies of it in existence.
Some people think the 'central control' of Subversion is a good thing.  But really, you don't have any kind of control at all.  All you're doing is making things really inconvenient for anybody who's not in the hallowed group of people you decide are committers.  All those people can make their own copies of the source code and even the entire history.  I routinely pull the whole Subversion history of a project into a DVCS in order to work on it.
A project using a DVCS has an authoritative repository that is every bit as authoritative as a 'centrally controlled' Subversion repository.  The distributed model is a strict superset of the centralized model.

A: It is because GIT makes branching and merging seamless. I have not heard any praise for SVN regarding branching and merging. GIT gives you total freedom over your own commits, and what you want to push to a common repository.


text:
Q: Using ReactGridLayout with AngularJS I am new to React.
I would like to try and incorporate the 'ReactGridLayout' module found here: https://github.com/STRML/react-grid-layout
in a Mean.JS v0.4 project I am working on.
I started off by adding ngReact to my project and adding the assets:
    // application/config/assets/default.js
    module.exports = {
      client: {
        lib: {
          css: [
            // ...
            'public/lib/react-grid-layout/css/styles.css',
            'public/lib/react-resizable/css/styles.css'
          ],
          js: [
            // ...
            'public/lib/react/react.js',
            'public/lib/react/react-dom.js',
            'public/lib/ngReact/ngReact.min.js',
            'public/lib/react-grid-layout/react-grid-layout.min.js',
          ]
        }
      }
    };

And then in my model's module.config file:
    angular
    .module('model', ['react'])

In my Client Controller I've added the following:
    // model.client.controller.js

    var MyFirstGrid = React.createClass({
      displayName: 'MyFirstGrid',

      render: function render() {
        // layout is an array of objects, see the demo for more complete usage
        var layout = [{ i: 'a', x: 0, y: 0, w: 1, h: 2, static: true }, { i: 'b', x: 1, y: 0, w: 3, h: 2, minW: 2, maxW: 4 }, { i: 'c', x: 4, y: 0, w: 1, h: 2 }];
        return React.createElement(
          ReactGridLayout,
          { className: 'layout', layout: layout, cols: 12, rowHeight: 30, width: 1200 },
          React.createElement(
            'div',
            { key: 'a' },
            'a'
          ),
          React.createElement(
            'div',
            { key: 'b' },
            'b'
          ),
          React.createElement(
            'div',
            { key: 'c' },
            'c'
          )
        );
      }
    });

    app.value('MyFirstGrid', MyFirstGrid);

and then in my view I have added:
    // view-model.client.view.html

    <react-component name="MyFirstGrid" props="layout" watch-depth="reference"/>

However, on page load I get:
    **ReferenceError: ReactGridLayout is not defined**

This isn't entirely unexpected, the documentation for STRML's ReactGridLayout includes a:
    var ReactGridLayout = require('react-grid-layout');

However, because I am trying to include this in my clientside controller I can't use "requires", which is why I've tried to add it as an 'asset'.
How can I get around this?
Thanks!


text:
Q: Logstash grok pattern to extract a part of String starts with and ends with I am trying to extract the application Id.
As an example i need to extract

application_1621858977521_0074

from the following log line
 /yarn/container-logs/application_1621858977521_0074/container_1621858977521_0074_01_000004 [2021-06-08 05:40:06,231] INFO Changing view acls groups to:  (org.apache.spark.SecurityManager)

I have tried the following custom grok pattern but doesn't work.
%{(^application_:/$):appID}%

I Appreciate your suggestions and help

A: You can use
/(?<applicationId>application(?:_[0-9]+)+)/

Quick alternatives are:
/(?<applicationId>application(?:_\w+)+)/
/(?<applicationId>application_[^/]*)

See the regex demo.
The pattern (with / added as path separators):

*

*/ - a / char

*(?<applicationId>application(?:_[0-9]+)+) - Group "applicationId": application and then one or more repetitions of _ and one or more digits

*/ - a / char

*[^/]* - zero or more chars other than /.

The Grok debugger shows the following output with your given string:
{
  "applicationId": [
    [
      "application_1621858977521_0074"
    ]
  ]
}


text:
Q: What kind of document is suitable for a book if customer wants changes I have a situation that I have to write a book from the material that my customer gave and she has not yet decided the layout of the book. What kind of document should I wrote that I can easily change for example
Paper size (A4 vs A5)
Font size and style
Margin sizes
Vertical space between lines
How many letters should the line on maximal length contain, such that the space between letters should be configurable?

A: It actually does not matter very much which document class you use. Most document classes can be adjust to have a different paper size either out of the box or with the help of a package. But even the decision of the document class is at this point not crucial, because you can change it later with little or no effort. Generally, I would use either memoir or scrbook. Both offer many possibilities to adjust the layout to your needs.
You can simply start to write the text, since the content does not/should not depend much on the book design. If you have long equations or tables you may have to rearrange them if your customer decides to use a different page size. What I would not do is to start creating figures. Figures depend strongly on the page size and the overall layout. Which font you use, which (text) colors you use etc.
For your last point: you can take a look into the documentation of memoir and scrbook both have some considerations about the margin sizes, font size and the text width. Also a good resource of information is the memdesign document.


text:
Q: Get users AD details when logged into Outlook Web Addin Im still battleing with trying to pull down the details of the logged in (Outlook) user within the add in im developing.
I have exploered the EWS service but, as far as I cant tell, the functions I need are not available so I have started looking at the Outlook REST API.
I can get very basic user details with the following call:
    function sendFindPersonRequest() {

    //get auth token for Graph
        Office.context.mailbox.getCallbackTokenAsync({ isRest: true }, function (result) {
        if (result.status === "succeeded") {
            var accessToken = result.value;
            console.log('REST Access Token : ' + accessToken);
            // Use the access token.
            getCurrentItem(accessToken);
        } else {
            // Handle the error.
        }
    });}

    function getCurrentItem(accessToken) {

    // Construct the REST URL to the current item.
    // Details for formatting the URL can be found at
    // https://learn.microsoft.com/previous-versions/office/office-365-api/api/version-2.0/mail-rest-operations#get-messages.
    var getMessageUrl = Office.context.mailbox.restUrl +
        '/v2.0/me/';

    $.ajax({
        url: getMessageUrl,
        dataType: 'json',
        headers: { 'Authorization': 'Bearer ' + accessToken }
    }).done(function (item) {
        // Message is passed in `item`.
        var subject = item.displayName;
        console.log('item subject: ' + subject);

  }).fail(function (error) {
    // Handle error.
});
}

But this doesnt pass any more than Alias, DisplayName and Emailaddress.
@odata.context: "https://outlook.office365.com/api/v2.0/$metadata#Me"
@odata.id: "https://outlook.office365.com/api/v2.0/Users('')"
Alias: "Joe.Bloggs"
DisplayName: ""
EmailAddress: "Joe.Bloggs@emailhere.co.uk"
Id: "baf52ae4-............"
MailboxGuid: "257f3fe1-6.............."

Im looking to get extendeddetails such as Jobtitle, OfficeAddress etc (which are standard AD fields).
I have looked at the GetUser method as well but that returns the same. I really dont want to go down Graph route and it feels that I am missing something as really expect those other fields to be there.
Has any one else used this to better affect?
Thanks

A: I didn't see where we can create extensions for a user based on Office 365 Data Extensions and Outlook Extended Properties.
And Microsoft.OutlookServices.User also doesn't have such properties as Jobtitle, OfficeAddress etc.
When I tried to use the OData $select query parameter like:
https://outlook.office365.com/api/v2.0/me?$select=DisplayName,Jobtitle,OfficeAddress

It will give an error: "Could not find a property named 'Jobtitle' on type 'Microsoft.OutlookServices.User'."
I'm afraid that what you want is not available in Outlook REST API. You should use Microsoft Graph API or AAD Graph API instead.

Update:
We can use GET https://outlook.office365.com/api/v2.0/me/people?$search="" to find the person's information.


text:
Q: Android - can not get JSON from PHP   private void getJSON(String url) {
        class GetJSON extends AsyncTask<String, Void, String>{
            ProgressDialog loading;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                Log.d(TAG, "onpre");
                loading = ProgressDialog.show(MainActivity.this, "Please Wait...", null, true, true);
            }

            @Override
            protected String doInBackground(String... params) {
                Log.d(TAG,"doin");
                String uri = params[0];

                BufferedReader bufferedReader = null;
                try {
                    URL url = new URL(uri);  Log.d(TAG, "url "+url);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    StringBuilder sb = new StringBuilder();

                    bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));

                    String json;
                    while((json = bufferedReader.readLine())!= null){
                        sb.append(json+"\n");Log.d(TAG, "sb "+sb.toString());
                    }

                    return sb.toString().trim();

                 }catch(Exception e){
                e.printStackTrace();
                Log.d(TAG, " error");
                return null;
            }

            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
             Log.d(TAG,"json= "+s);
            }
        }
        GetJSON gj = new GetJSON();
        gj.execute(url);
    }

As you can see here
http://oep.esy.es/android_get_all.php
{"teachers":[{"tid":"1","name":"g\u00f6ksel","surname":"biricik",,"tc":"12345678912","email":"goksel@ce.yildiz.edu.tr","avatar":"goksel.jpg"},{"tid":"2","name":"haydar","surname":"ayg\u00f6rmez",,"tc":"12345678913","email":"aygormez@gmail.com","avatar":"haydar.jpg"},{"tid":"48","name":"Caner","surname":"Ayd\u0131n",,"tc":"12345678914","email":"caneraydinbey@gmail.com","avatar":"caner.jpg"},{"tid":"92","name":"deneme","surname":"denemesoy",","tc":"12345678914","email":"deneme@gmail.com","avatar":"5292-1017.png"},{"tid":"93","name":"deneme2","surname":"denemesoy2",,"tc":"12345678915","email":"deneme2@gmail.com","avatar":"8446-1012.png"}],"success":1}

I need to get data from here. But when i do this, i get null:
04-04 15:41:24.022 2131-2131/com.example.caneraydin.myapplication D/Chic: oncreate start
04-04 15:41:24.372 2131-2131/com.example.caneraydin.myapplication D/Chic: oncreate end
04-04 15:41:27.115 2131-2131/com.example.caneraydin.myapplication D/Chic: onpre
04-04 15:41:27.255 2131-2302/com.example.caneraydin.myapplication D/Chic: doin
04-04 15:41:27.485 2131-2131/com.example.caneraydin.myapplication D/Chic: json= null
04-04 15:44:19.623 5732-5732/com.example.caneraydin.myapplication D/Chic: oncreate start
04-04 15:44:19.753 5732-5732/com.example.caneraydin.myapplication D/Chic: oncreate end
04-04 15:46:26.537 5732-5732/com.example.caneraydin.myapplication D/Chic: onpre
04-04 15:46:26.697 5732-8187/com.example.caneraydin.myapplication D/Chic: doin
04-04 15:46:26.697 5732-8187/com.example.caneraydin.myapplication D/Chic: url http://oep.esy.es/android_get_all.php
04-04 15:46:26.867 5732-5732/com.example.caneraydin.myapplication D/Chic: json= null

Why do i get null? There is no warning or errors. omly this:
04-04 15:54:00.990 5732-5732/com.example.caneraydin.myapplication E/ViewRootImpl: sendUserActionEvent() mView == null

I did same implements as here
https://www.simplifiedcoding.net/android-json-tutorial-to-get-data-from-mysql-database/

A: I tried this and it works

   return String.valueOf(sb);


text:
Q: scss bootstrap 4 overwrite map I'm trying my hand at scss using Bootstrap 4 and I don't know how to overwrite variable (using map) correclty
custom.scss
// Your variable overrides
$primary: rgb(40, 167, 36);

$spacer: 1;
$spacers: (
  0: 0,
  1: ($spacer * .2),
  2: ($spacer * 3),
  3: $spacer,
  4: ($spacer * 8),
  5: ($spacer * 12),
  6: ($spacer * 50)
);

// Bootstrap and its default variables
@import "../node_modules/bootstrap/scss/bootstrap";

Primary color overwrite works fine but the spacers don't.
As is it now it seems like all the value are equal to 0, whenever I add a class like "mt-5" it doesn't change anything.
I don't know what I'm doing wrong.

A: Here's how to add spacers to the map. The issue is that the spacer has no units. Use px or rem to define the spacer unit...
$spacer: 1rem;
$spacers: (
  0: 0,
  1: ($spacer * .2),
  2: ($spacer * 3),
  3: $spacer,
  4: ($spacer * 8),
  5: ($spacer * 12),
  6: ($spacer * 50)
);

https://www.codeply.com/go/TY8XqnvzO9


text:
Q: Change BenchmarkDotnet exporter path The documentation says that "by default" the exporters will create a report in the .\BenchmarkDotNet.Artifacts\results path.
Is there a way to override this path?

A: This can be done via the ArtifactsPath property in IConfig as explained here


text:
Q: Why my testing view response is none? I have a post detail view as below.
class PostDetailView(AjaxResponseMixin, UpdateView):
model = UserPost
context_object_name = 'post'
template_name = 'feed/post_detail.html'
form_class = CommentForm

def get_initial(self):
    initial_data = super(PostDetailView, self).get_initial()
    obj = self.get_object()
    initial_data.update({
        "content_type": obj.get_content_type,
        "object_id": obj.id
    })
    return initial_data

def get_context_data(self, **kwargs):
    # comment_form = CommentForm
    context = super(PostDetailView, self).get_context_data(**kwargs)
    kwargs['form_comment'] = context['form']  # comment_form
    try:
        total_views = r.incr('userpost:{}:views'.format(self.object.pk))
        kwargs['total_views'] = total_views
    except (redis.exceptions.ConnectionError,
            redis.exceptions.BusyLoadingError):
        pass

    return super(PostDetailView, self).get_context_data(**kwargs)

def get_success_url(self):
    try:
        total_views = r.incr('userpost:{}:views'.format(self.object.pk))
    except (redis.exceptions.ConnectionError,
            redis.exceptions.BusyLoadingError):
        pass
    return reverse_lazy('feed:post_detail', kwargs={'pk': self.object.pk})

def form_valid(self, form):
    c_type = form.cleaned_data.get("content_type")
    obj_id = form.cleaned_data.get('object_id')
    content_data = form.cleaned_data.get("content")
    parent_obj = None
    try:
        parent_id = int(self.request.POST.get("parent_id"))
    except:
        parent_id = None

    if parent_id:
        parent_qs = Comment.objects.filter(pk=parent_id)
        if parent_qs.exists() and parent_qs.count() == 1:
            parent_obj = parent_qs.first()

    new_comment, created = Comment.objects.get_or_create(
        user=self.request.user,
        content_type=c_type,
        object_id=obj_id,
        content=content_data,
        parent=parent_obj,
    )
    if created:
        ct = ContentType.objects.get_for_id(c_type.id)
        obj = ct.get_object_for_this_type(pk=obj_id)
        create_action(self.request.user, 'commented on', obj)
    return super(PostDetailView, self).form_valid(form)

def form_invalid(self, form):
    print("invalid form")

I am writing test case as below.
class PostDetailViewTests(TestCase):
@classmethod
def setUpTestData(cls):
    user = User.objects.create_user(username='chitra', password='password123')
    cls.post = UserPost(author=user, post_body="Test post", )
    cls.post.save()

def setUp(self):
    login = self.client.login(username='chitra', password='password123')
    user = auth.get_user(self.client)
    assert user.is_authenticated

def test_postdetail_view_page_status_code(self):
    """
    Test that a PostDetailView page is rendering correctly
    """
    response = self.client.get(reverse_lazy('feed:post_detail', kwargs={'pk': self.post.pk}))
    self.assertEquals(response.status_code, 200, 'post doesnt exist with pk={}'.format(self.post.pk))
    self.assertTemplateUsed(response, 'feed/post_detail.html', 'Template used is wrong')

def test_postdetail_view_post_comment(self):
    """
    Test that a comment is posted ot post correctly
    """
    user = User.objects.get(pk=1)
    resp = self.client.post(reverse_lazy('feed:post_detail', kwargs={'pk': self.post.pk}), {'content': 'just a comment'})
    self.assertEqual(resp.status_code, 200)
    # co.refresh_from_db()
    self.assertTrue(Comment.objects.filter().exists())

Comment/forms.py
class CommentForm(ModelForm):

class Meta:
    model = Comment
    fields = ['content_type', 'object_id', 'content']  # list of fields you want from model
    widgets = {'content_type':  HiddenInput(), 'object_id': HiddenInput(),
        'content': Textarea(attrs={'rows': 4, 'cols': 65}),
   }

comment/models.py
class Comment(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
parent = models.ForeignKey("self", null=True, blank=True, on_delete=models.CASCADE)
content = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
objects = CommentManager()

Ok, Here, 'test_postdetail_view_page_status_code' test is passing but posting is getting failed i.e 'test_postdetail_view_post_comment', The resp is None here!
Basically, the view is just a display of a post, and a comment form along with comment list(If there are any), The comment body(i.e field content) is the only input parameter, and content types are used to save the comment object as shown. I am using method 'get_initial', to initialise the content type object with post id(please see), I think the resp is None because I need to first call the display as self.client.get and then use self.client.post here?, I think the get_initial is not getting called, so it's not having content type data right? I am not sure how to debug this to check where the test case is failing!
Any light on this is highly appreciated, Thank you!


text:
Q: Ubuntu 22.04 stopped detecting monitor I am running Ubuntu 22.04 on Lenovo Think Pad. It was detecting till yesterday but after I connected a Windows laptop (another laptop) to the monitor, my laptop stopped detecting the monitor. I tried various threads but it doesn't work. I am using HDMI to mini display port connection.
Output for lspci | grep VGA

00:02.0 VGA compatible controller: Intel Corporation 3rd Gen Core processor Graphics Controller (rev 09)


text: Q: Window Click to Focus Without Passing Event To App I like the click-to-focus behavior, but is there some way to prevent the window from receiving the click event until after it has been focused?  Example, I click a window in the background to bring it to front, but in doing so I accidentally click some button or link in the window.  Can I have the WM just bring the window to the front, but not send that click event into the window?


text:
Q: How DML queries execute in MySQL InnoDB I want to know if I fire query like insert into emp ...
What are the steps involved in query ?
It will go through InnoDB buffer pool?
Thanks for your help.

A: Here's a broad answer to your broad question.
All DMLs and SELECTs always goes through the buffer_pool in InnoDB.  It is a cache of the blocks that compose the BTrees that compose the data (organized by the necessary PRIMARY KEY) and each secondary INDEX.
For DML (broadly):

*

*Fetch a block, if not already in the buffer pool.

*Modify whatever.

*Mark the block "dirty".

*Rinse and repeat.

*Eventually (as a background task), the block will be written back to disk.  Meanwhile, it is in the cache so that other operations can avoid having to fetch it from disk.

Modifying a non-unique index involves the "Change buffer".  That is sort of a "delayed write" for such changes.
SELECTs:

*

*Fetch a block (if not already in buffer pool).

*Fetch row(s) out of that block.

*Rinse and repeat.

Note: in both DML and SELECT, the discovery of where a row usually involves drilling down a BTree, which involves fetching nodes (blocks) of the BTree.  They, too, are cached (and tend to live a long time in the buffer pool).
If you want more details, start another Question with more specifics.


text:
Q: Regex select all text between tags What is the best way to select all the text between 2 tags - ex: the text between all the  '
' tags on the page.

A: You shouldn't be trying to parse html with regexes see this question and how it turned out.
In the simplest terms, html is not a regular language so you can't fully parse is with regular expressions.
Having said that you can parse subsets of html when there are no similar tags nested. So as long as anything between  and  is not that tag itself, this will work:
preg_match("/<([\w]+)[^>]*>(.*?)<\/\1>/", $subject, $matches);
$matches = array ( [0] => full matched string [1] => tag name [2] => tag content )

A better idea is to use a parser, like the native DOMDocument, to load your html, then select your tag and get the inner html which might look something like this:
$obj = new DOMDocument();
$obj -> load($html);
$obj -> getElementByTagName('el');
$value = $obj -> nodeValue();

And since this is a proper parser it will be able to handle nesting tags etc.

A: Try this....
(?<=\<any_tag\>)(\s*.*\s*)(?=\<\/any_tag\>)

A: To exclude the delimiting tags:
(?<=
)(.*?)(?=
)

(?<=
) looks for text after

(?=
) looks for text before

Results will text inside pre tag

A: This is what I would use.
(?<=(
))(\w|\d|\n|[().,\-:;@#$%^&*\[\]"'+–/\/®°⁰!?{}|`~]| )+?(?=(
))

Basically what it does is:
(?<=(
)) Selection have to be prepend with
 tag
(\w|\d|\n|[().,\-:;@#$%^&*\[\]"'+–/\/®°⁰!?{}|~]| ) This is just a regular expression I want to apply. In this case, it selects letter or digit or newline character or some special characters listed in the example in the square brackets. The pipe character | simply means "OR".
+? Plus character states to select one or more of the above - order does not matter. Question mark changes the default behavior from 'greedy' to 'ungreedy'.
(?=(
)) Selection have to be appended by the
 tag

Depending on your use case you might need to add some modifiers like (i or m)

*

*i - case-insensitive

*m - multi-line search

Here I performed this search in Sublime Text so I did not have to use modifiers in my regex.
Javascript does not support lookbehind
The above example should work fine with languages such as PHP, Perl, Java ...
Javascript however does not support lookbehind so we have to forget about using `(?))` and look for some kind of workaround. Perhaps simple strip the first four chars from our result for each selection like in here
https://stackoverflow.com/questions/11592033/regex-match-text-between-tags
Also look at the JAVASCRIPT REGEX DOCUMENTATION for non-capturing parentheses

A: use the below pattern to get content between element. Replace [tag] with the actual element you wish to extract the content from.
<[tag]>(.+?)</[tag]>

Sometime tags will have attributes, like anchor tag having href, then use the below pattern.
 <[tag][^>]*>(.+?)</[tag]>

A: This answer supposes support for look around! This allowed me to identify all the text between pairs of opening and closing tags. That is all the text between the '>' and the '<'. It works because look around doesn't consume the characters it matches.
(?<=>)([\w\s]+)(?=<\/)

I tested it in https://regex101.com/ using this HTML fragment.

Cell 1	Cell 2	Cell 3

Cell 4	Cell 5	Cell 6

It's a game of three parts: the look behind, the content, and the look ahead.
(?<=>)    # look behind (but don't consume/capture) for a '>'
([\w\s]+) # capture/consume any combination of alpha/numeric/whitespace
(?=<\/)   # look ahead  (but don't consume/capture) for a '</'

I hope that serves as a started for 10. Luck.

A: You can use "
(.*?)
", (replacing pre with whatever text you want) and extract the first group (for more specific instructions specify a language) but this assumes the simplistic notion that you have very simple and valid HTML.
As other commenters have suggested, if you're doing something complex, use a HTML parser.

A:

var str = "Lorem ipsum
text 1
 Lorem ipsum
text 2
";
    str.replace(/
(.*?)<\/pre>/g, function(match, g1) { console.log(g1); });

Since accepted answer is without javascript code, so adding that:

A: preg_match_all(/
([^>]*?)<\/pre>/,$content,$matches) this regex will select everyting between  tag. no matter is it in new line(work with multiline.

A: In Python, setting the DOTALL flag will capture everything, including newlines.

If the DOTALL flag has been specified, this matches any character including a newline. docs.python.org

#example.py using Python 3.7.4
import re

str="""Everything is awesome!
Hello,
World!

"""

# Normally (.*) will not capture newlines, but here re.DOTATLL is set
pattern = re.compile(r"
(.*)
",re.DOTALL)
matches = pattern.search(str)

print(matches.group(1))

python example.py
Hello,
World!

Capturing text between all opening and closing tags in a document
To capture text between all opening and closing tags in a document, finditer is useful. In the example below, three opening and closing
 tags are present in the string.
#example2.py using Python 3.7.4
import re

# str contains three
...
 tags
str = """In two different ex-
periments, the authors had subjects chat and solve the
Desert Survival Problem
 with a
humorous or non-humorous computer. In both experiments the computer made pre-
programmed comments, but in study 1 subjects were led to believe they were interact-
ing with another person. In the
humor conditions
 subjects received a number of funny
comments, for instance: "The mirror is probably too small to be used as a signaling
device to alert rescue teams to your location. Rank it lower. (On the other hand, it
offers
endless opportunity for self-reflection
)"."""

# Normally (.*) will not capture newlines, but here re.DOTATLL is set
# The question mark in (.*?) indicates non greedy matching.
pattern = re.compile(r"
(.*?)
",re.DOTALL)

matches = pattern.finditer(str)

for i,match in enumerate(matches):
    print(f"tag {i}: ",match.group(1))

python example2.py
tag 0:  Desert Survival Problem
tag 1:  humor conditions
tag 2:  endless opportunity for self-reflection

A: (?<=>)[^<]+

for Notepad++
>([^<]+)

for AutoIt (option Return array of global matches).
or
 (?=>([^<]+))

https://regex101.com/r/VtmEmY/1

A: Tag can be completed in another line. This is why \n needs to be added.

(.|\n)*?<\/PRE>

A: This seems to be the simplest regular expression of all that I found
(?:<TAG>)([\s\S]*)(?:<\/TAG>)

*

*Exclude opening tag (?:<TAG>) from the matches

*Include any whitespace or non-whitespace characters ([\s\S]*) in the matches

*Exclude closing tag (?:<\/TAG>) from the matches

A: To select all text between pre tag I prefer
preg_match('#
([\w\W\s]*)
#',$str,$matches);

$matches[0] will have results including
 tag

$matches[1] will have all the content inside
.

DomDocument cannot work in situations where the requirement is to get text with tag details within the searched tag as it strips all tags, nodeValue & textContent will only return text without tags & attributes.

A:  test.match(/
(.*?)<\/pre>/g)?.map((a) => a.replace(/
|<\/pre>/g, ""))

this should be a preferred solution.especially if you have multiple pre tags in the context

A: You can use Pattern pattern = Pattern.compile( "[^<'tagname'/>]" );

A: const content = '
ABC
';
const blog = {content};
const re = /<([^> ]+)([^>]*)>([^<]+)(<\/\1>)/;
const matches = content.match(re);
console.log(matches[3]);

matches[3] is the content text and this is adapted to any tag name with classes. (not support nested structures)

A: How about:

(\X*?)<\/PRE>

A: More complex than PyKing's answer but matches any type of tag (except self-closing) and considers cases where the tag has HTML-like string attributes.
/<TAG_NAME(?:STRING|NOT_CLOSING_TAG_NOT_QUOTE)+>INNER_HTML<\/\1 *>/g
Raw: /<([^\s</>]+)(?:("(?:[^"\\]|\\.)*")|[^>"])+>(.*?)<\/\1 *>/g
Regex Railroad diagram:
group #1 = tag name
group #2 = string attr
group #3 = inner html

JavaScript code testing it:
let TAG_NAME = '([^\s</>]+)';
let NOT_CLOSING_TAG_NOT_QUOTE = '[^>"]';
let STRING = '("(?:[^"\\\\]|\\\\.)*")';

let NON_SELF_CLOSING_HTML_TAG =
                                                              // \1 is a back reference to TAG_NAME
    `<${TAG_NAME}(?:${STRING}|${NOT_CLOSING_TAG_NOT_QUOTE})+>(.*?)</\\1 *>`;

let tagRegex = new RegExp(NON_SELF_CLOSING_HTML_TAG, 'g');

let myStr = `Aenean <abc href="/life<><>\\"<?/abc></abc>">life</abc> sed consectetur.
Work Inner HTML quis risus eget about inner html leo.
interacted with any of the <<<ve text="<></ve>>">abc</ve>`;

let matches = myStr.match(tagRegex);

// Removing 'g' flag to match each tag part in the for loop
tagRegex = new RegExp(NON_SELF_CLOSING_HTML_TAG);

for (let i = 0; i < matches.length; i++) {
  let tagParts = matches[i].match(tagRegex);
  console.log(`Tag #${i} = [${tagParts[0]}]`);
  console.log(`Tag #${i} name: [${tagParts[1]}]`);
  console.log(`Tag #${i} string attr: [${tagParts[2]}]`);
  console.log(`Tag #${i} inner html: [${tagParts[3]}]`);
  console.log('');
}

Output:
Tag #0 = [<abc href="/life<><>\"<?/abc></abc>">life</abc>]
Tag #0 name: [abc]
Tag #0 string attr: ["/life<><>\"<?/abc></abc>"]
Tag #0 inner html: [life]

Tag #1 = [Work Inner HTML]
Tag #1 name: [a]
Tag #1 string attr: ["/work"]
Tag #1 inner html: [Work Inner HTML]

Tag #2 = [about inner html]
Tag #2 name: [a]
Tag #2 string attr: ["/about"]
Tag #2 inner html: [about inner html]

Tag #3 = [<ve text="<></ve>>">abc</ve>]
Tag #3 name: [ve]
Tag #3 string attr: ["<></ve>>"]
Tag #3 inner html: [abc]

This doesn't work if:

*

*The tag has any descendant tag of the same type

*The tag start in one line and ends in another. (In my case I
remove line breaks from HTML)

If you change (.*?)<\/\1 *> to ([\s\S]*?)<\/\1 *> it should match the tag's inner html even if everything is not in the same line. For some reason it didn't work for me on Chrome and Node but worked here with the JavaScript's Regex Engine:
https://www.regextester.com
Regex: <([^\s</>]+)(?:("(?:[^"\\]|\\.)*")|[^>"])+>([\s\S]*?)<\/\1 *>
Test String:
Aenean lacinia <abc href="/life<><><?/a>">
life</abc> sed consectetur.
Work quis risus eget urna mollis ornare about leo.
interacted with any of the <<<ve text="<></ve>>">abc</ve>

A:
([\r\n\s]*(?!<\w+.*[\/]*>).*[\r\n\s]*|\s*[\r\n\s]*)(((?!<\/code>)[\s\S])*)<\/code>[\r\n\s]*((?!<\w+.*[\/]*>).*|\s*)[\r\n\s]*<\/pre>

A: For multiple lines:
<htmltag>(.+)((\s)+(.+))+</htmltag>

A: I use this solution:
preg_match_all( '/<((?!<)(.|\n))*?\>/si',  $content, $new);
var_dump($new);

A: In Javascript (among others), this is simple.  It covers attributes and multiple lines:
/
]*>([\s\S]*?)<\/pre>/


text:
Q: Heavy use of PHP's "Some PHP code I look at is littered with "<?php" and "?>" tags depending on whether it's outputting HTML or not. Is there any performance benefit to this rather than using echo to write the HTML? It makes the code extremely hard to read when the code's constantly switching between code and HTML via the "<?php" tag.
Note that I'm not just talking about the occasional switchover. The code I'm currently looking at (the mantis-bt source code) is giving me a headache with the number of times it's switching. Very very hard to read.
I wonder if there's a reason for them doing it like this?

A: No reason whatsoever apart from its beginners scripting, there just trying to get the results to the page without any architectural thinking or planning into the system into the long run.
What you should be doing is splitting your design up away from your logical php code, and the design compilation should be done at the end of the scripts runtime.
if you redesign the application I would certainly advise you to start with a framework because the framework will force bad habits away by its design.
Start with codeigniter and create a simple blog, understand how to connect/insert/select/update with the database, learn how to handle sessions, learn the Controllers and the principles of creating one.
After you have had a decent play about with it start looking at the poorly coded applicatioon from a distance not looking at the code or the design but yet what exactly is it doing, is it fetching results from the database, does it have a user system etc etc.
then start implementing the base layer of the application such as the above, once you have the database designed you can then start building the models to fetch from the database at the point within your application, start creating the basic view files taking samples from the pooorly coded application and recoding them within the new application, keeping in mind the structure and cleanliness of the coding.
Hope this helps you start migrating because I certainly do not advise you continue to work with an application such as that.

@mitch
Event thought you second piece of code is cleaner its still combining your view with the rest of your application where it should be like so:

    <?php $this->load("segments/head"); ?>

         <?php echo $this->wrap("span",$this->link("Some Linke",$this->var("homepage"))) ?>

a dedicated set of methods for the view to prevent it interacting with the main logic, this would be wrapped within an object to prevent the scope and only the object should be able to access the main logic.

A: Reason it might be like that is for situations like this:
<?php if($logged_in) { ?>
    Welcome, <?= $_SESSION['user'] ?>
    Logout
<?php } ?>

Instead of:
<?php
   if($logged_in) {
      echo "Welcome, " . $_SESSION['user'] . "";
      echo "Lougout";
   }
?>

There are less escape characters to worry about.

A: As far as readability goes, I would rather see:

      <?php foreach ($items as $item): ?>

              <a href="<?php esc($item->url)?>">
              <img src="<?php esc($item->icon)?>"/>
              <?php esc($item->text)?>

      <?php endforeach; ?>

Than:
   echo "
";
   foreach ($items as $item)
   {
     echo "
";
     echo 'url).'">';
     echo 'icon).'"/>';
     echo esc($item->text);
     echo '
';
   }
   echo "
";

Not only that, but the latter lets your IDE of choice handle the HTML syntax and formatting (telling you, for instance, that the  is missing). So, unless there's a lot more going on in-between the short bits of HTML, <?php might be preferable.
EDIT: as for performance, anyone serious about code speed will activate a caching pre-compiler which will boil down both versions to the exact same thing.

A: While this would not produce any noticeable effects as far as code run time, the idea that this is the only place that "Performance" should be calculated, is ridiculous. Developers cost money. So cleaning this all up IS a performance boost! Your own performance!
So do it.

A: PHP offers some features that are not offered by HTML , such as loops. Thus, if you have to use loops several times in your code, you have to keep switching between php tags and HTML.
Moreover, PHP helps you implement session control that is not allowed by HTML. Thus, it is important to embed PHP in HTML
In a nutshell, to use additional features we have to use PHP or some other language

A: I don't have statistical data to back this up, but it's my understanding that it's more efficient to "turn off" php to output HTML rather than to use echo""; The reason being that when you run your html through echo tags, you're having PHP parse it out to display, while just putting it in the doc itself will let the browser display it WITHOUT having to have PHP parse it.
When I did ColdFusion development, I remember hearing the same case made for  tags.

A: I prefer to use the <?php and ?> because it is easier to read HTML, but
if any loss of performance will be very little. I've written HTML
with echo but it's very bad to read and find problems in the HTML.


text:
Q: synchronized thread execution my task is to create thread in this order: if A start->start B and C, if  B start->start D.
And destroy them in reverse order If D then B. If B and C then A. I hope you get it. I manage to do it but I guess there is better way to do it. Do you have any suggestions?
After your comments i have changed my code and it is much more simply. But now it looks "stupid". I would like to change hardcore of if statements and implementation, any advice? tnx for advice I'm learning with you.
This is my new code:
     import java.util.*;
class RobotController implements Runnable{
String name;

public void run() {
    Thread t = Thread.currentThread();
    System.out.println(t.getName() + " status = " + t.isAlive());
    System.out.println(t.getName() + " status = " + t.getState());

  }

public static void main(String args[]) throws InterruptedException{
    Thread thread_A = new Thread(new RobotController(), "Thread A");
    Thread thread_B = new Thread(new RobotController(), "Thread B");
    Thread thread_C = new Thread(new RobotController(), "Thread C");
    Thread thread_D = new Thread(new RobotController(), "Thread D");

    thread_A.start();
    thread_A.join();
    System.out.println(thread_A.getState());
    thread_B.start();
    thread_B.join();
    System.out.println(thread_B.getState());
    thread_C.start();
    thread_C.join();
    System.out.println(thread_C.getState());
    thread_D.start();
    System.out.println(thread_D.getState());

}

}

A: There are some flaws in your code which will make it not to work accordingly sometimes:

*

*You called thread_A.start() and then checked thread_A.isAlive(). Now what if , thread_A is already completed before thread_A.isAlive() condition is checked?.thread_B and thread_C is never started. Your application fails.

*Assume that thread_A is not completed and thread_A.isAlive() condition is passed, then starting of thread_B before thread_C is not always guaranteed by Java thread scheduler. Again your application fails.

*Assume that thread_B starts before thread_C and if thread_B completes before thread_B.isAlive() is checked then the if condition fails and thread_D is never started. Again your application fails.

Now a point to ponder:
There is no need to check if the thread is alive after its join() method is called. It is an unnecessary runtime overhead.
EDIT
OK, Here is the modified version of code..I hope it would let you understand the dynamics of thread:
class RobotController implements Runnable
{
    private final Object lock = new Object();
    private void notifyThread()
    {
        synchronized(lock)
        {
            lock.notify();
        }
    }
    public void run()
    {
        synchronized(lock)
        {
            try
            {
                System.out.println(Thread.currentThread().getName() + " started");
                lock.wait();
                System.out.println(Thread.currentThread().getName()+ " stopped");
            }
            catch (InterruptedException ex)
            {
                ex.printStackTrace();
            }
        }
    }

    public static void main(String args[]) throws InterruptedException
    {
        RobotController rca = new RobotController();
        RobotController rcb = new RobotController();
        RobotController rcc = new RobotController();
        RobotController rcd = new RobotController();

        Thread thread_A = new Thread(rca,"Thread A");
        Thread thread_B = new Thread(rcb,"Thread B");
        Thread thread_C = new Thread(rcc,"Thread C");
        Thread thread_D = new Thread(rcd,"Thread D");

        thread_A.start();
        while (thread_A.getState() != Thread.State.WAITING)
        {
            Thread.sleep(100);
        }
        thread_B.start();
        thread_C.start();
        while (thread_B.getState() != Thread.State.WAITING && thread_C.getState() != Thread.State.WAITING)
        {
            Thread.sleep(100);
        }
        thread_D.start();
        while (thread_D.getState() != Thread.State.WAITING)
        {
            Thread.sleep(100);
        }
        rcd.notifyThread();
        thread_D.join();
        rcc.notifyThread();
        thread_C.join();
        rcb.notifyThread();
        thread_B.join();
        rca.notifyThread();
    }

}

And here is the output:
Thread A started
Thread B started
Thread C started
Thread D started
Thread D stopped
Thread C stopped
Thread B stopped
Thread A stopped

A: In multi threading, there is no need of synchronization unless the common data is shared by multiple threads.
In your case, you want to start and stop the threads in a particular order. For this, there is join method in Thread class. This link shows good example of join method.

A: In my opinion, it is quite strange to use synchronized (lock) in your run method to lock your object. The reason is that in each Thread object has the different lock attribute, which is belong to each object. It means you are trying to lock the different objects. Actually, it doesn't make sense.
Basically, the object that you should apply the synchronized are any shared objects. For example, you need to count something and then you create a class object to share it in your class. In this case, it should be locked while being read or written.

A: I would like to highlight two points here:

*

*Have a look at thread execution life cycle here. It says that, when start() method is called, thread enters in runnable state and not in running state. When thread enters in running state, that means run() method is getting exexuted. CPU/OS decides the priority of which thread should be transferred from runnable to running thread. E.g. if you call start() method for 4 threads, it is not necessary that they will execute in that particular order. (Running the same program in my pc multiple times gives me different outputs.

In your case, when the condition if(thread_A.isAlive()) is executed, it is possible that the thread A may not be in running state. Hence, the control will not go into if which is not correct.
To correct this behavior, in main, a while loop should implemented which waits until the thread becomes alive and so on.
2 . In your program, you have not assigned names to the threads and you are printing the name in the run() method. In this case, JVM assigns the names to threads in order of their execution e.g. first thread to execute will have name as 'Thread-0' and so on. Hence, we will not be able to identify which thread executed first. Assign the names using setName() method.


text:
Q: Keras – Artificial Neural Networks - Error when using a custom activation function I'm creating an Artificial Neural Network (ANN) using Kera's Functional API. Link to the data csv file: https://github.com/dpintof/SPX_Options_ANN/blob/master/MLP3/call_df.csv. Relevant part of the code that reproduces problem:
import pandas as pd
from sklearn.model_selection import train_test_split
from tensorflow import keras
import tensorflow as tf
from tensorflow.keras import layers

# Data
call_df = pd.read_csv("call_df.csv")

call_X_train, call_X_test, call_y_train, call_y_test = train_test_split(call_df.drop(["Option_Average_Price"],
                    axis = 1), call_df.Option_Average_Price, test_size = 0.01)

# Hyperparameters
n_hidden_layers = 2 # Number of hidden layers.
n_units = 128 # Number of neurons of the hidden layers.

# Create input layer
inputs = keras.Input(shape = (call_X_train.shape[1],))
x = layers.LeakyReLU(alpha = 1)(inputs)

"""
Function that creates a hidden layer by taking a tensor as input and applying a
modified ELU (MELU) activation function.
"""
def hl(tensor):
    # Create custom MELU activation function
    def melu(z):
        return tf.cond(z > 0, lambda: ((z**2)/2 + 0.02*z) / (z - 2 + 1/0.49),
                        lambda: 0.49*(keras.activations.exponential(z)-1))

    y = layers.Dense(n_units, activation = melu)(tensor)
    return y

# Create hidden layers
for _ in range(n_hidden_layers):
    x = hl(x)

# Create output layer
outputs = layers.Dense(1, activation = keras.activations.softplus)(x)

# Actually create the model
model = keras.Model(inputs=inputs, outputs=outputs)

# QUICK TEST
model.compile(loss = "mse", optimizer = keras.optimizers.Adam())
history = model.fit(call_X_train, call_y_train,
                    batch_size = 4096, epochs = 1,
                    validation_split = 0.01, verbose = 1)

This is the error I get when I do model.fit(…) (notice that 4096 is my batch size and 128 is the number of neurons of the hidden layers):
InvalidArgumentError:  The second input must be a scalar, but it has shape [4096,128]
     [[{{node dense/cond/dense/BiasAdd/_5}}]] [Op:__inference_keras_scratch_graph_1074]

Function call stack:
keras_scratch_graph

I know the problem has to do with the custom activation function because the program runs fine if I use the following hl function instead:
def hl(tensor):
    lr = layers.Dense(n_units, activation = layers.LeakyReLU())(tensor)
    return lr

I got the same error when trying to define melu(z) like this:
@tf.function
def melu(z):
    if z > 0:
        return ((z**2)/2 + 0.02*z) / (z - 2 + 1/0.49)
    else:
        return 0.49*(keras.activations.exponential(z)-1)

From How do you create a custom activation function with Keras? I also tried the following, but without success:
def hl(tensor):
    # Create custom MELU activation function
    def melu(z):
        return tf.cond(z > 0, lambda: ((z**2)/2 + 0.02*z) / (z - 2 + 1/0.49),
                        lambda: 0.49*(keras.activations.exponential(z)-1))

    from keras.utils.generic_utils import get_custom_objects
    get_custom_objects().update({'melu': layers.Activation(melu)})

    x = layers.Dense(n_units)(tensor)
    y = layers.Activation(melu)(x)
    return y

A: This issue happens because tf.cond expects a scalar for the condition argument (instead of a multi-dimensional tensor). Instead, you can use tf.where to apply the conditional element-wise.
For example, you can define melu as follows:
def melu(z):
    return tf.where(z > 0, ((z**2)/2 + 0.02*z) / (z - 2 + 1/0.49),
                           0.49*(keras.activations.exponential(z)-1))

NOTE: Not tested.


text:
Q: Applying a function to multiple arrays/matrices in R Given two arrays:
a = array(1:3)
b = array(3:1)

I want to apply a function that sequentially compares the value of each element of A to each element of B, and return the result.
Something like:
compare = function(xa, xb) { if (xa < xb) { 1 } else { 0 } }

...where xa would be the an element from the a array, and xb would be an element from the b array.
Is there a derivative of apply I can use to accomplish this?

A: Rather than mapply I would use R internal recycling rules for vectorised functions. If a and b are the same length you need only do this:
as.integer( a < b )
#[1] 1 0 0

as.integer is just there to coerce to 1 or 0, in reality TRUE and FALSE will behave as 1 and 0 in any subsequent multiplicative operations.
example
set.seed(1); a <- sample(10)
#[1]  3  4  5  7  2  8  9  6 10  1

set.seed(2); b <- sample(10)
#[1]  2  7  5 10  6  8  1  3  4  9

a < b
#[1] FALSE  TRUE FALSE  TRUE  TRUE FALSE FALSE FALSE FALSE  TRUE

a * ( a < b )
#[1] 0 4 0 7 2 0 0 0 0 1

a[ a < b ]
#[1] 4 7 2 1

Some people may be surprised, but < is a function. It calls an underlying C function called do_relop in the files /src/main/relop.c (all the logical comparators do - they just use a different switch for the type of comparison) which handles vector recycling. You can write < like this:
`<`( a , b )
#[1] FALSE  TRUE FALSE  TRUE  TRUE FALSE FALSE FALSE FALSE  TRUE

Benchmarking
Using the primitive < operator is over 100 times quicker (on a pair of 1e6 length vectors) than using ifelse which is also a vectorized function:
set.seed(1); a <- sample(10,1e6,repl=T)
set.seed(2); b <- sample(10,1e6,repl=T)
require( microbenchmark)
bm <- microbenchmark( comparealt(a,b) , `<`(a,b) , times = 25L )
print( bm , digits = 3 , unit = "relative" , order = "median" )
#Unit: relative
#             expr min  lq median  uq  max neval
#            a < b   1   1      1   1  1.0    25
# comparealt(a, b) 131 126    122 105 48.3    25

A: I originally read "the value of each element of A to each element of B" meaning an outer join and suggested:
compare <- function(x, y){ outer(x, y, FUN="<")+0 }

which for example gives
> compare(array(1:6), array(5:3))
     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    1    1    1
[3,]    1    1    0
[4,]    1    0    0
[5,]    0    0    0
[6,]    0    0    0

For comparing matrices of the same dimension elementwise you could use something like
comparemat <- function(mat1, mat2){ (mat1 < mat2)+0 }

or
comparealt <- function(mat1, mat2){ ifelse(mat1 < mat2, 1, 0) }

where either of
comparemat(matrix(1:12,nrow=4), matrix(12:1,nrow=4))
comparealt(matrix(1:12,nrow=4), matrix(12:1,nrow=4))

give
     [,1] [,2] [,3]
[1,]    1    1    0
[2,]    1    1    0
[3,]    1    0    0
[4,]    1    0    0

A: I stumbled upon 'mapply', which seems to do the trick:
> gg = function(x,y){ if(x < y) { 1 } else { 0 }}
> gg(1,2)
[1] 1
> gg(2,1)
[1] 0
> mapply(gg, 1:4, 4:1)
[1] 1 1 0 0


text:
Q: Cannot construct instance of `com.google.com.DataAdditionalDetailsDto` (although at least one Creator exists) I am not getting what's the issue here ? It's giving the below message in error log, can anyone please explain me a bit ?
2023-02-10 05:20:21.863 ERROR 9 --- [tainer#10-8-C-1] c.g.m.d.d.r.SchemeInfoReceiver    : Exception caught in function for 123

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.google.commons.sdk.dto.DataAdditionalDetailsDto` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('bnVsbA==')
 at [Source: (byte[])""bnVsbA==""; line: 1, column: 1]
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1343)
    at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1032)
    at com.fasterxml.jackson.databind.deser.ValueInstantiator._createFromStringFallbacks(ValueInstantiator.java:371)
    at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createFromString(StdValueInstantiator.java:323)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromString(BeanDeserializerBase.java:1373)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:171)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:161)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4014)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3092)
    at com.google.service.impl.SchemeWriteServiceImpl.setAdditionalDtoInScheme(SchemeWriteServiceImpl.java:283)
    at com.google.service.impl.SchemeWriteServiceImpl.insertScheme(SchemeWriteServiceImpl.java:190)
    at com.google.service.impl.SchemeWriteServiceImpl$$FastClassBySpringCGLIB$$38b8d1da.invoke(<generated>)

This is how I am setting additionDetails in dto and it's throwing exception given above:
    private void setAdditionalDtoInScheme(Scheme Scheme, SchemeDto dto) throws IOException {
        byte[] byteDto = scheme.getAdditionalDetails();
        DataAdditionalDetailsDto additionalDetailsDto;
        if (byteDto != null && byteDto.length > 0) {
            additionalDetailsDto = objectMapper.readValue(byteDto, DataAdditionalDetailsDto.class);
            log.info("lockInYears from db : {}", additionalDetailsDto.getLockInYrs());
            if (dto.getAdditionalDetails() == null) {
                additionalDetailsDto.setLockInYrs(null);
                additionalDetailsDto.setDays(null);
            } else {
                additionalDetailsDto.setDays(dto.getAdditionalDetails().getDays());
            }
            scheme.setAdditionalDetails(objectMapper.writeValueAsBytes(additionalDetailsDto));
        } else if (dto.getAdditionalDetails() != null) {
            additionalDetailsDto = new DataAdditionalDetailsDto();
            additionalDetailsDto.setDays(dto.getAdditionalDetails().getDays());
            scheme.setAdditionalDetails(objectMapper.writeValueAsBytes(additionalDetailsDto));
        }
    }```


text:
Q: TDD : Any pattern for constant testing? Constants are beautiful people - they can hold in a unique place a value that is used everywhere in your code. Changing that value requires only one simple modification.
Life is cool.
Well, this is the promise. Reality is sometime different :

*

*You change the LogCompleteFileName constant value from L:\LOGS\MyApp.log to \\Traces\App208.txt and you get two files : \\traces\App208.txt for the traces and \\traces\App208.txt.log for the logs...

*You change TransactionTimeout from 2 to 4 minutes and you still get a timeout after 2 minutes (after spending the day, you find out that you also have to change the timeout of the DBMS and the timeout of the transaction manager...).

*You replace SleepTimeInMinutes from 1 to 10 and you see no change (after an hour or so, you find out that the constant's name was misleading : the granularity is not the minute but the millisecond...).

*Even more subtle: you change CompanyName from, say Yahoo to Microsoft but automated mail alerts are still sent to alert@yahoo.com...

Creating a constant is a contract. You are telling your readers that whenever they change the value, it will still works the way they think it should be.
Nothing less.
Of course, you need to test that you are not misleading your readers. You have to make sure that the implied contract is right.
How do you achieve that with TDD? I'm just stuck with that. The only way I can test a change for a constant (!) value is to make that constant an application setting... Should I have to conclude that the const keyword should be avoided when I think that the value can and will change?
How are you testing your (so called) constants using TDD?
Many thanks in advance :)

A: There are two kinds of constants:
1) Constants for Convenience/Readability
When writing code using TDD, each line of production code should exists because first there was a failing test that required that code to be written. And as you refactor the code, some magic values will get promoted into constants. Some of these might also be good as application settings, but for convenience (less code) they have been configured in code instead of an external configuration file.
In that case, the way that I write tests, both production and test code will use the same constants. The tests will specify that the constants are used as expected. But the tests won't repeat the value of a constant, such as in "assert MAX_ITEMS == 4", because that would be duplicated code. Instead, the tests will check that some behaviour uses the constants correctly.
For example, here is an example application (written by me) which will print a Longcat of specified length. As you can see, the Longcat is defined as a series of constants:
public class Longcat {

    // Source: http://encyclopediadramatica.com/Longcat

    public static final String HEAD_LINES = "" +
            "    /\\___/\\         \n" +
            "   /       \\         \n" +
            "  |  #    # |         \n" +
            "  \\     @   |        \n" +
            "   \\   _|_ /         \n" +
            "   /       \\______   \n" +
            "  / _______ ___   \\  \n" +
            "  |_____   \\   \\__/ \n" +
            "   |    \\__/         \n";
    public static final String BODY_LINE = "" +
            "   |       |          \n";
    public static final String FEET_LINES = "" +
            "   /        \\        \n" +
            "  /   ____   \\       \n" +
            "  |  /    \\  |       \n" +
            "  | |      | |        \n" +
            " /  |      |  \\      \n" +
            " \\__/      \\__/     \n";
...

The tests verify that the constants are used correctly, but they do not duplicate the value of the constant. If I change the value of a constant, all the tests will automatically use the new value. (And whether the Longcat ASCII art looks right, it needs to be verified manually. Although you could even automate that with an acceptance test, which would be recommendable for a larger project.)
    public void test__Longcat_with_body_size_2() {
        Longcat longcat = factory.createLongcat(2);
        assertEquals(Longcat.BODY_LINE + Longcat.BODY_LINE, longcat.getBody());
    }

    public void test__Fully_assembled_longcat() {
        Longcat longcat = factory.createLongcat(2);
        assertEquals(Longcat.HEAD_LINES + longcat.getBody() + Longcat.FEET_LINES, longcat.toString());
    }

2) Universal Constants
The same application has also some constants which are never expected to be changed, such as the ratio between meters and feet. Those values can/should be hard coded into the test:
    public void test__Identity_conversion() {
        int feet1 = 10000;
        int feet2 = FEET.from(feet1, FEET);
        assertEquals(feet1, feet2);
    }

    public void test__Convert_feet_to_meters() {
        int feet = 10000;
        int meters = METERS.from(feet, FEET);
        assertEquals(3048, meters);
    }

    public void test__Convert_meters_to_feet() {
        int meters = 3048;
        int feet = FEET.from(meters, METERS);
        assertEquals(10000, feet);
    }

And the production code looks like:
public enum LengthUnit {

    METERS("m", 1.0), FEET("ft", 0.3048), PETRONAS("petronas", 451.9), LINES("lines", 0.009);

    private final String name;
    private final double lengthInMeters;
...

    public int from(int length, LengthUnit unit) {
        return (int) (length * unit.lengthInMeters / this.lengthInMeters);
    }
}

Notice that I did not write any tests for the height of the Petronas Twin Towers, because that information is declarative (and declarative data rarely gets broken) and I had already written tests for the conversion logic (see above). If more similar constants are added (Eiffel Tower, Empire State Building etc.), they will be automatically located by the application and will work as expected.

A: From what I read of your question this has nothing to do with TDD. The usage you describe is not of a true constant but rather of a configuration value, so in these cases you shouldn't be using the const modifier.

A: That's because all those things aren't constants... Things that actually are:

*

*G (6.67300 × 10-11 m3 kg-1 s-2)

*c (299 792 458 m / s)

*pi (3.1415926535897931)

*L (6.0221415 × 1023 mol-1)

*...

If any of those things ever changes, don't worry, your application crashing will be the last that matters xD

A:
The only way I can test a change for a constant (!) value is to make that constant an application setting

All of the uses you listed in the question sound like application settings, not constants, to me. A constant is a value that is, well, constant, such as:
const decimal LITERS_PER_HOGSHEAD = 238.480942392;

Edited to add: Hopefully this is more helpful than my flippant answer. I usually create an AppSettings class. Some of the properties in this class are pulled from the config file, some are settings that I don't expect to change, and some could be constants.
public class AppSettings
{
    public const decimal GILLS_PER_HOMER = 1859.771248601;

    public string HelpdeskPhone
    {
        get { // pulled from config and cached at startup }
    }

    public int MaxNumberOfItemsInAComboBox
    {
        get { return 3; }
    }
}

A: A couple of things.
Firstly TDD and the emergent design that TDD promotes is the one of separating your responsibilities, applying DRY and dependency injection.
To unit test a const is easy and perhaps a little pointless.
But to test another unit's evalutation of that const is in my opinion not a unit test. It is an integration test. Testing the const value in other units would be coverd by a mock or stub.
Secondly your examples are varied:
You log example is only using 1 file. It is just that 2 exist. if the requirement was for only one file to exist then you could manufacture a test for that.
Transaction timeout testing should be picked up by an integration test. It should show your original test is not where the problem is.
Change of CompanyName is fine because it relates to the company name. Domain name should and could be a different const.
As others have mentioned passing a configuration class around my be helpful to mock/stub when testing other classes.

A: It sounds to me like you're using constants mostly to illustrate configuration settings.  This is ideal for the ConfigurationManager, but this can be difficult to use for testing as well.
I would recommend the following usage:
const String SomeValue = "TESTCONSTANT";

static class ConfigurationSettings
{
    static String SomeProperty
    {
        get
        {
           var result = SomeValue;
           if (ConfigurationManager.AppSettings["SOMEKEY"] != null)
               result = ConfigurationManager.AppSettings["SOMEKEY"];
           return result;
        }
    }
}

A: If you are making a Unit Test, I don't believe there is anything wrong with something like this:
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod]
public void DefaultValue_Equals_8()
{
     Assert.AreEqual<int>(8, MyNamespace.MyClass.DefaultValue);
}

that tests against:
namespace MyNamespace
{
    public class MyClass
    {
        public const int DefaultValue = 8;
    }
}

This will detect if the constant was changed.
The other part of your problem is actually using the constant consistently. If you do not use it everywhere necessary in an expected manner, then you are not relying on constants rather you are relying on calculations (or magic numbers).

A: Some of the examples are configuration items rather than constants. In this case - even if you use constants in the short term they should be injected into where they are used and that code tested as normal. If the value can't be changed at runtime then you could also use an example test around the value as described below.
If you are testing something that is truly a constant (e.g const FEET_PER_METRE = 3.28084) then just have an example test that wraps both the calculation and the value (the data from this test should come from an independent source rather than just calculating it yourself from your declared constant).
Assert.AreEqual<decimal>(29.5276, converter.metresToFeet(9))

This way the test serves two purposes:
1) If it turns out your example and your constant were wrong then you can update your test with a correct example, get a failing test and then fix the constant to go green.
2) It provides regression safety. If someone was to accidentally change the constant (e.g. changed the wrong value or fat-fingered the value whilst editing something else in the file) then they would get a failing test to warn them.


text:
Q: Overlapping address error in Packet Tracer-Possible subnet error I am working on my hands on final exam for Networking Fundamentals. I have accomplished everything except for putting the 4 devices on two separate subnets.
These are my subnet calculations: Given address:192.168.10.0/24
192.168.10.0[1-126 hosts] [127 broadcast]
192.168.10.128[129-254] [255]
I know the calculations themselves are correct because I checked my work with a subnet calculator. All devices accepted their addresses with their assigned subnet mask of either 255.255.255.0 or 255.255.255.128. However after assigning the appropriate addressing on my router g0/0 port (subnet A) I get an overlapping address error when trying to assign g0/1 (subnet B) the appropriate address. Is something not configured correctly with the router, or did I subnet wrong? Any help would be greatly appreciated as I have become very desperate. Thank you. P.S. I also encounter the same problem when trying to assign ipv6 addresses to the router ( 2001:DB8:ACAD::/64 and I try the addresses  2001:DB8:ACAD::1 and  2001:DB8:ACAD::2 respectively)

A: A /24 is equivalent to a netmask of 255.255.255.0, so you can't stuff two networks inside the 192.168.10.0/24. You should tell the router that it has 192.168.10.0/25 (a netmask of 255.255.255.128) for the first network, and 192.168.10.128/25 for the second network.


text:
Q: What's wrong with my assembly code I'm trying to write a factorial code in assembly using jmp and jz and i'm new to assembly
input should be eax and the output is ebx
    mov eax,3h ;factorial of 3
    ;initialize registers
    mov ebx,0h
    mov ecx,eax
    dec ecx
    mov edx,0h

loopstart:
    mul ecx ;edx:eax = eax * ecx
    add ebx,eax ;ebx = ebx + eax
    dec ecx ;ecx = ecx - 1
    jz exitloop ;jump to exitloop if the last math is zero ( in this ex:dec)
    jmp loopstart ;jump to loopstart
exitloop:
    ;mov eax,ebx
    call ebxprint; should be 6

Find factorial of eax
input: 2
output: 2
input: 3
output: 12
input: 4
output: 60
So, What's the problem here?

A: Thanks to @PaulHankin
I must remove add ebx, eax and uncomment mov eax,ebx
Here is the code after editing:
    mov eax,3h ;factorial of 3
    ;initialize registers
    mov ebx,0h
    mov ecx,eax
    dec ecx
    mov edx,0h

loopstart:
    mul ecx ;edx:eax = eax * ecx
    dec ecx ;ecx = ecx - 1
    jz exitloop ;jump to exitloop if the last math is zero ( in this ex:dec)
    jmp loopstart ;jump to loopstart
exitloop:
    mov eax,ebx
    call ebxprint; should be 6


text:
Q: How to set an ordered relationship with NSPersistentCloudKitContainer? When I checked Used with CloudKit, the error Folder.children must not be ordered appeared. Any idea about an ordered relationship?
IDE: Xcode11 beta3

Here's the Folder Entity.

A: (applies: as of iOS 13, and early betas of 14)
Cloud kit can't use ordered relationships (which just blows, as ordered data is a fundamental Thing That Exists). The reason is that everything is backed with CKRecord (cloud kit records) not actual core data stuff -- it's a completely different type of data storage, and the PersistentCloudKitContainer is doing on-the-fly rewrites of your data to CKRecords and back. CKRecords don't have mechanisms that work for maintaining journals of ordered items the way we need in Core Data ordered relationships.
Which means it's not likely to be "fixed" anytime soon, as it would require changes to CloudKit and apple's iCloud generally (vs. just changes to CoreData).
So...
You have a few not-good choices:

*

*Don't have formal Relationships -- instead have a field where you store, e.g.,   a list of references. Maintain this yourself as you add/remove child objects. Essentially have an "admin" field in parent record that you use to maintain your own Relationship mechanism. (e.g.: generate a UUID for each child, parent stores a concatenated list of UUID's for all children)

*Use CoreData Relationships, and store ordering data in the child objects, e.g. orderIndex int field that you maintain manually.

*Mixed: use unordered Relationship from parent to children, and also store a field of "order of children" in parent. CoreData manages the relationship, and you can manually maintain and apply ordering of those children as needed.

No matter what you do, it's bad:

*

*No relationships: no "fetch parent" and get references to children via relationship; you have to fetch both separately. Also no "delete" rules done for you, e.g. " on delete parent, cascade delete children." This works when you need children in more than one collection (as each collection record keeps it's own list of children)

*Ordering in child objects (this is what I use): you have to insert yourself in every add and delete operation on children, running code to adjust orderIndex values of all children. I manage this by having a CoreDataManager.createChild(atIndex:), CoreDataManager.deleteChild() and CoreDataManager.moveChild(toIndex:) functions that apply side effect of updating orderIndex values. But at least you get "fetch parent; for c in parent.children do..." and cascade delete's back. However: now child can only be in one parent's list, as child only has one orderIndex value.

*Relationship + manually maintained ordering field in parent: let core data manage the association, and when you need ordered children you can use a parent.orderedChildren() function that reads your .childOrder field of parent, applies it to .children list. But... You still have to manage the parent's .childOrder field manually, and change it every time you add/remove/reorder children. HOWEVER, with Cloud Sync, there are many potential bugs wit your .child list and .childOrder field value getting out of sync as children are added/removed in different app instances. Keeping the child list and the ordering separate means they can be updated by cloud sync separately.


text:
Q: Update single service I'm new in service fabric and cannot catch an idea how to update single micro-service in an application.
I have a number of repositories (one per micro-service) and need to update/deploy each micro-service separatly.
How can I make it? Where should I keep Application project? Can you please suggest solution structure.
P.S. I use standalone (on-premises) service fabric installation.

A: Short answer is you cannot update a single microservice, SF has a different architecture. It's composed of Applications which themselves consist of Services. You an only update Application as a whole by raising version number in application manifest and services. Application version always goes up whereas service versions can either change or not (that affects upgrade process).
In your case you have two options:
Wrap each microservice in a separate SF application and deploy them separately. This will sort of simulate completely independent services and that's how most microservices are developed. It's a pain to version them independently and manage dependencies. Official documentation explains more on how to write manifests https://learn.microsoft.com/en-us/azure/service-fabric/service-fabric-application-model
Another option is go in line with SF design - create a single application manifest and manifest per service, each versioned properly. Deploy that as a single application and rip the benefits of transactional SF upgrades and all the niceties. I strongly suspect your microservices are plain windows executables? In that case you can describe them as guest executables https://learn.microsoft.com/en-us/azure/service-fabric/service-fabric-deploy-existing-app


text:
Q: Can I stop hyperref from showing bookmarks in a side bar? I have a file I have been working on for two weeks now, and just added hyperref.  It is a small document and I really do not need the table of contents displayed as a sidebar next to the pdf when I PDFLaTexify it.  I see how to set hyperref to show that sidebar with option bookmarksopen=true or false.
But is there a way to get it to leave the sidebar out altogether?

A: As naphaneal says in a comment, you can use \usepackage[bookmarks=false]{hyperref} to disable booksmarks.

A: Depending on your document class, passing bookmarks=false to hyperref might not be sufficient. For instance, KOMA document classes (e.g. scrartcl) manage their own bookmarks via the bookmarks package. This will lead to the following output in the log file:

Using `bookmark' together with `hyperref' is recommended,
because of handling of possible bookmark level gaps.
You can avoid loading `bookmark' with KOMA-Script option
`bookmarkpackage=false' before \begin{document} and
you can avoid this message adding:
  \usepackage{bookmark}
before \begin{document} on input line 24.

So, to prevent KOMA-Script from creating bookmarks, pass the bookmarkpackage=false option when loading the document class.


text:
Q: log4rs error Log4rs(Os { code: 2, kind: NotFound, message: "No such file or directory" }) I'm trying to implement log4rs by following the docs. My goal is to put the result of info!("INFO") into the file requests.log, but I get an error:

thread 'main' panicked at 'called Result::unwrap() on an Err
  value: Log4rs(Os { code: 2, kind: NotFound, message: "No such file or
  directory" })', libcore/result.rs:945:5

I have the following files in the src folder:
- main.rs
- log4rs.yml
- requests.log

main.rs:
#[macro_use]
extern crate log;
extern crate log4rs;

fn main() {
    println!("Hello, world!");
    log4rs::init_file("log4rs.yml", Default::default()).unwrap();
    info!("INFO");
}

the config file log4rs.yml:
# Scan this file for changes every 30 seconds
refresh_rate: 30 seconds

appenders:
  # An appender named "stdout" that writes to stdout
  stdout:
    kind: console

  # An appender named "requests" that writes to a file with a custom pattern encoder
  requests:
    kind: file
    path: "requests.log"
    encoder:
      pattern: "{d} - {m}{n}"

# Set the default logging level to "warn" and attach the "stdout" appender to the root
root:
  level: warn
  appenders:
    - stdout

loggers:
  # Raise the maximum log level for events sent to the "app::backend::db" logger to "info"
  app::backend::db:
    level: info

  # Route log events sent to the "app::requests" logger to the "requests" appender,
  # and *not* the normal appenders installed at the root
  app::requests:
    level: info
    appenders:
      - requests
    additive: false

A: When you type cargo run, your working directory is the current directory. This means that all your relative paths will depend on this working directory.
For example, if you are in your home directory (~) and you have your  project folder named foo. When you go in it, that gives you ~/foo. If you now type cargo run, that means that when log4rs tries to open your file it will try to open the file ~/foo/log4rs.yml. The file is not here but in ~/foo/src/log4rs.yml
You have many solutions:

*

*log4rs::init_file("src/log4rs.yml", Default::default()).unwrap();

*move log4rs.yml to foo

*use an absolute path (not a good solution for your current case)


text:
Q: Infinte Series with Conditions I was wondering if someone could give me a hint about how to get started on this problem, and/or hide the solution to it. I really want to try it on my own first.
Suppose $a_k \geq 0$ for all $k \in \mathbb{N}$ and $\sum a_k < \infty$. Either prove that the given series converges, or give an example for which it diverges:
$\sum_{k=1}^{\infty} \sqrt{\frac{a_k}k}$.

A: HINT $1$: Look for a counterexample.
If $b_k=\sqrt{a_k/k}$, you want $\sum_kb_k$ to diverge while $\sum_ka_k=\sum_kkb_k^2$ converges, so $\langle kb_k:k\ge 1\rangle$ has to converge to $0$ faster than $\langle b_k:k\ge 1\rangle$. It's a good bet that $\sum_ka_k$ will be just barely convergent, while $\sum_kb_k$ will just barely diverge. The most obvious 'barely divergent' series is the harmonic series, but it's not good enough: you'll need $\sum_kb_k$ to diverge even slower than the harmonic series.
HINT $2$:

 Try $b_k=\dfrac1{kf(k)}$ for some slowly growing function $f$, so that $a_k=\dfrac1{k(f(k))^2}$.

HINT $3$:

 What is $\displaystyle\int_2^\infty\frac{dx}{x(\ln x)^2}$? Does this give you any ideas for $a_k$?

There may well be other nice solutions; this was the first that occurred to me.


text:
Q: Jest: Fail upon parsing a file I'm using react with typecript and after adding swiper dependecy my tests start to fail.

These are my configuration:
jest.config.ts:
import type { Config } from '@jest/types';

const config: Config.InitialOptions = {
  verbose: true,
  transform: {
    '^.+\\.ts?$': 'ts-jest',
  },
  transformIgnorePatterns: ['node_modules/(?!swiper|ssr-window|dom7/)'],
};
export default config;

babel.config.js
module.exports = {
  presets: ['@babel/preset-env', '@babel/preset-react', '@babel/preset-flow'],
  plugins: [
    'babel-plugin-styled-components',
    '@babel/plugin-proposal-class-properties',
  ],
  moduleNameMapper: {
    '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
      '<rootDir>/__mocks__/fileMock.js',
    '\\.(css|less)$': '<rootDir>/__mocks__/styleMock.js',
    moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  },
  transform: {
    '^.+\\.ts?$': 'ts-jest',
    '^.+\\.(js|jsx)$': 'babel-jest',
  },
};

package.json
...
 "jest": {
    "moduleNameMapper": {
      "swiper/react": "swiper/react/swiper-react.js",
      "swiper/css": "swiper/swiper.min.css"
    },
    "transform": {
      "^.+\\.css$": "jest-transform-css"
    }
  },
  "transformIgnorePatterns": "node_modules/(?!(swiper|ssr-window|dom7)/)",
...


text:
Q: Create a trial version of a Java application, with limited functionality I am searching for ideas on how I can implement a trial version of my java application. Most posts are about creating a trial software with time limitation on when it stops working. In my case I am want to create an application that has limited functionality and one can unlock all the features of the app by purchasing the product. I would appreciate the communities thoughts on the points below. A twist to this issue is to make this solution as generic as possible so that it works on Mac and Windows.
My approach to this solution involves checking for the existence of a 'registration' file, when the app starts up. If a valid registration file exists, then the application will be fully functional. This file will be placed in the User's Application Data directory. That way uninstalling the application in Windows will not touch this file. Also, on a mac, in typical cases removing the app folder there should be no problem, unless the user has installed some software like AppCleaner, which will prompt to delete the application directory under the ~/Library/Application Support folder.
So, here is my first question. What is the community's thought on how should I handle a situation where the registration file is deleted for a user that has already bought the application?
I think this is also related to how the registration/purchase is done in the first place. This is my second question. I will not handle any credit card transactions in the software, I'd much rather paypal do all that. So, say after someone purchases software, I gave them a registration key that will unlock the software. My first concern here would be that anybody that has this registration key can unlock the software. How can I restrict this? Ideas?
This topic might require a little discussion, I hope that is ok. Looking forward to hearing your inputs.
edit: I just wanted to get back to this post and update it to mention that I finally after assessing TrueLicense and License3j, i have chosen to work with TrueLicense. I am still in the process of figuring out how to use it, as the documentation is not all that easy. I am trying to study the sample and hopefully I'll have that up and running soon for my app.

A: Recently I have been doing some research on the same subject. I found that it is necessary to implement a licence manager. I found TrueLicence open source library for that and a tutorial with code samples.

...when using True License, or any other Java license manager library,
  you're going to need to create two components:

*

*A software license server, which generates a new software license    whenever a customer purchases a copy of your software, and

*A software license client, which is code you embed into your Java/Swing    client application to install and verify the license.

A: You can use a license.properties file who's key/token will be picked up everytime the software launches.
The software would have some interceptor code which will read the key/token from the license.properties file and decrypt it and generate a value.
So, when a user buys purchases your software, you issue him a  new token. Now this token when decrypted will generate some different value than the usual one and accordingly you'll unlock the rest of the features.
There are 100s of encryption alogorithms that you can search over web and use them into your software but the basic idea is this.


text:
Q: TensorFlow exited abnormally with code 137 I'm trying convolutional neural net using TensorFlow.
Though I could success some training, the script failed with
Process Python exited abnormally with code 137

when I just changed the training data.
The data sizes of the first and second data are the same, and
I could train CNN using the very second data on another platform (lasagne).
(The first data is slice of photo images, and the second is artificially generated geological patterns).
Can someone tell me the meaning of the error or the way to avoid this problem?
My platform is Mac OS X 10.10.5, Python 2.7.10 |Anaconda 2.2.0 (x86_64),
and tensorflow-0.5.0.
Thank you in advance.

A: Exit code 137 means that your Python process was killed by the SIGKILL signal. It's hard to say for certain, but one possibility is that your process was killed by the OOM (out-of-memory) killer. Check /var/log/messages to see if there is any information about why your process was killed.
This post has advice on how to disable the OOM killer for an individual process. However, this ignores the root cause, which is that your process (or TensorFlow itself) is using too much memory.